hash
stringlengths
64
64
content
stringlengths
0
1.51M
7748ecbb8ef0402c68b025368390b27b29c74723e30776e47057b5e96f16c8d1
""" This module can be used to solve 2D beam bending problems with singularity functions in mechanics. """ from sympy.core import S, Symbol, diff, symbols from sympy.core.add import Add from sympy.core.expr import Expr from sympy.core.function import (Derivative, Function) from sympy.core.mul import Mul from sympy.core.relational import Eq from sympy.core.sympify import sympify from sympy.solvers import linsolve from sympy.solvers.ode.ode import dsolve from sympy.solvers.solvers import solve from sympy.printing import sstr from sympy.functions import SingularityFunction, Piecewise, factorial from sympy.integrals import integrate from sympy.series import limit from sympy.plotting import plot, PlotGrid from sympy.geometry.entity import GeometryEntity from sympy.external import import_module from sympy.sets.sets import Interval from sympy.utilities.lambdify import lambdify from sympy.utilities.decorator import doctest_depends_on from sympy.utilities.iterables import iterable numpy = import_module('numpy', import_kwargs={'fromlist':['arange']}) class Beam: """ A Beam is a structural element that is capable of withstanding load primarily by resisting against bending. Beams are characterized by their cross sectional profile(Second moment of area), their length and their material. .. note:: A consistent sign convention must be used while solving a beam bending problem; the results will automatically follow the chosen sign convention. However, the chosen sign convention must respect the rule that, on the positive side of beam's axis (in respect to current section), a loading force giving positive shear yields a negative moment, as below (the curved arrow shows the positive moment and rotation): .. image:: allowed-sign-conventions.png Examples ======== There is a beam of length 4 meters. A constant distributed load of 6 N/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. The deflection of the beam at the end is restricted. Using the sign convention of downwards forces being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols, Piecewise >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(4, E, I) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(6, 2, 0) >>> b.apply_load(R2, 4, -1) >>> b.bc_deflection = [(0, 0), (4, 0)] >>> b.boundary_conditions {'deflection': [(0, 0), (4, 0)], 'slope': []} >>> b.load R1*SingularityFunction(x, 0, -1) + R2*SingularityFunction(x, 4, -1) + 6*SingularityFunction(x, 2, 0) >>> b.solve_for_reaction_loads(R1, R2) >>> b.load -3*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 2, 0) - 9*SingularityFunction(x, 4, -1) >>> b.shear_force() 3*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 2, 1) + 9*SingularityFunction(x, 4, 0) >>> b.bending_moment() 3*SingularityFunction(x, 0, 1) - 3*SingularityFunction(x, 2, 2) + 9*SingularityFunction(x, 4, 1) >>> b.slope() (-3*SingularityFunction(x, 0, 2)/2 + SingularityFunction(x, 2, 3) - 9*SingularityFunction(x, 4, 2)/2 + 7)/(E*I) >>> b.deflection() (7*x - SingularityFunction(x, 0, 3)/2 + SingularityFunction(x, 2, 4)/4 - 3*SingularityFunction(x, 4, 3)/2)/(E*I) >>> b.deflection().rewrite(Piecewise) (7*x - Piecewise((x**3, x > 0), (0, True))/2 - 3*Piecewise(((x - 4)**3, x > 4), (0, True))/2 + Piecewise(((x - 2)**4, x > 2), (0, True))/4)/(E*I) Calculate the support reactions for a fully symbolic beam of length L. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. The deflection of the beam at the end is restricted. The beam is loaded with: * a downward point load P1 applied at L/4 * an upward point load P2 applied at L/8 * a counterclockwise moment M1 applied at L/2 * a clockwise moment M2 applied at 3*L/4 * a distributed constant load q1, applied downward, starting from L/2 up to 3*L/4 * a distributed constant load q2, applied upward, starting from 3*L/4 up to L No assumptions are needed for symbolic loads. However, defining a positive length will help the algorithm to compute the solution. >>> E, I = symbols('E, I') >>> L = symbols("L", positive=True) >>> P1, P2, M1, M2, q1, q2 = symbols("P1, P2, M1, M2, q1, q2") >>> R1, R2 = symbols('R1, R2') >>> b = Beam(L, E, I) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, L, -1) >>> b.apply_load(P1, L/4, -1) >>> b.apply_load(-P2, L/8, -1) >>> b.apply_load(M1, L/2, -2) >>> b.apply_load(-M2, 3*L/4, -2) >>> b.apply_load(q1, L/2, 0, 3*L/4) >>> b.apply_load(-q2, 3*L/4, 0, L) >>> b.bc_deflection = [(0, 0), (L, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> print(b.reaction_loads[R1]) (-3*L**2*q1 + L**2*q2 - 24*L*P1 + 28*L*P2 - 32*M1 + 32*M2)/(32*L) >>> print(b.reaction_loads[R2]) (-5*L**2*q1 + 7*L**2*q2 - 8*L*P1 + 4*L*P2 + 32*M1 - 32*M2)/(32*L) """ def __init__(self, length, elastic_modulus, second_moment, area=Symbol('A'), variable=Symbol('x'), base_char='C'): """Initializes the class. Parameters ========== length : Sympifyable A Symbol or value representing the Beam's length. elastic_modulus : Sympifyable A SymPy expression representing the Beam's Modulus of Elasticity. It is a measure of the stiffness of the Beam material. It can also be a continuous function of position along the beam. second_moment : Sympifyable or Geometry object Describes the cross-section of the beam via a SymPy expression representing the Beam's second moment of area. It is a geometrical property of an area which reflects how its points are distributed with respect to its neutral axis. It can also be a continuous function of position along the beam. Alternatively ``second_moment`` can be a shape object such as a ``Polygon`` from the geometry module representing the shape of the cross-section of the beam. In such cases, it is assumed that the x-axis of the shape object is aligned with the bending axis of the beam. The second moment of area will be computed from the shape object internally. area : Symbol/float Represents the cross-section area of beam variable : Symbol, optional A Symbol object that will be used as the variable along the beam while representing the load, shear, moment, slope and deflection curve. By default, it is set to ``Symbol('x')``. base_char : String, optional A String that will be used as base character to generate sequential symbols for integration constants in cases where boundary conditions are not sufficient to solve them. """ self.length = length self.elastic_modulus = elastic_modulus if isinstance(second_moment, GeometryEntity): self.cross_section = second_moment else: self.cross_section = None self.second_moment = second_moment self.variable = variable self._base_char = base_char self._boundary_conditions = {'deflection': [], 'slope': []} self._load = 0 self.area = area self._applied_supports = [] self._support_as_loads = [] self._applied_loads = [] self._reaction_loads = {} self._ild_reactions = {} self._ild_shear = 0 self._ild_moment = 0 # _original_load is a copy of _load equations with unsubstituted reaction # forces. It is used for calculating reaction forces in case of I.L.D. self._original_load = 0 self._composite_type = None self._hinge_position = None def __str__(self): shape_description = self._cross_section if self._cross_section else self._second_moment str_sol = 'Beam({}, {}, {})'.format(sstr(self._length), sstr(self._elastic_modulus), sstr(shape_description)) return str_sol @property def reaction_loads(self): """ Returns the reaction forces in a dictionary.""" return self._reaction_loads @property def ild_shear(self): """ Returns the I.L.D. shear equation.""" return self._ild_shear @property def ild_reactions(self): """ Returns the I.L.D. reaction forces in a dictionary.""" return self._ild_reactions @property def ild_moment(self): """ Returns the I.L.D. moment equation.""" return self._ild_moment @property def length(self): """Length of the Beam.""" return self._length @length.setter def length(self, l): self._length = sympify(l) @property def area(self): """Cross-sectional area of the Beam. """ return self._area @area.setter def area(self, a): self._area = sympify(a) @property def variable(self): """ A symbol that can be used as a variable along the length of the beam while representing load distribution, shear force curve, bending moment, slope curve and the deflection curve. By default, it is set to ``Symbol('x')``, but this property is mutable. Examples ======== >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I, A = symbols('E, I, A') >>> x, y, z = symbols('x, y, z') >>> b = Beam(4, E, I) >>> b.variable x >>> b.variable = y >>> b.variable y >>> b = Beam(4, E, I, A, z) >>> b.variable z """ return self._variable @variable.setter def variable(self, v): if isinstance(v, Symbol): self._variable = v else: raise TypeError("""The variable should be a Symbol object.""") @property def elastic_modulus(self): """Young's Modulus of the Beam. """ return self._elastic_modulus @elastic_modulus.setter def elastic_modulus(self, e): self._elastic_modulus = sympify(e) @property def second_moment(self): """Second moment of area of the Beam. """ return self._second_moment @second_moment.setter def second_moment(self, i): self._cross_section = None if isinstance(i, GeometryEntity): raise ValueError("To update cross-section geometry use `cross_section` attribute") else: self._second_moment = sympify(i) @property def cross_section(self): """Cross-section of the beam""" return self._cross_section @cross_section.setter def cross_section(self, s): if s: self._second_moment = s.second_moment_of_area()[0] self._cross_section = s @property def boundary_conditions(self): """ Returns a dictionary of boundary conditions applied on the beam. The dictionary has three keywords namely moment, slope and deflection. The value of each keyword is a list of tuple, where each tuple contains location and value of a boundary condition in the format (location, value). Examples ======== There is a beam of length 4 meters. The bending moment at 0 should be 4 and at 4 it should be 0. The slope of the beam should be 1 at 0. The deflection should be 2 at 0. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.bc_deflection = [(0, 2)] >>> b.bc_slope = [(0, 1)] >>> b.boundary_conditions {'deflection': [(0, 2)], 'slope': [(0, 1)]} Here the deflection of the beam should be ``2`` at ``0``. Similarly, the slope of the beam should be ``1`` at ``0``. """ return self._boundary_conditions @property def bc_slope(self): return self._boundary_conditions['slope'] @bc_slope.setter def bc_slope(self, s_bcs): self._boundary_conditions['slope'] = s_bcs @property def bc_deflection(self): return self._boundary_conditions['deflection'] @bc_deflection.setter def bc_deflection(self, d_bcs): self._boundary_conditions['deflection'] = d_bcs def join(self, beam, via="fixed"): """ This method joins two beams to make a new composite beam system. Passed Beam class instance is attached to the right end of calling object. This method can be used to form beams having Discontinuous values of Elastic modulus or Second moment. Parameters ========== beam : Beam class object The Beam object which would be connected to the right of calling object. via : String States the way two Beam object would get connected - For axially fixed Beams, via="fixed" - For Beams connected via hinge, via="hinge" Examples ======== There is a cantilever beam of length 4 meters. For first 2 meters its moment of inertia is `1.5*I` and `I` for the other end. A pointload of magnitude 4 N is applied from the top at its free end. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b1 = Beam(2, E, 1.5*I) >>> b2 = Beam(2, E, I) >>> b = b1.join(b2, "fixed") >>> b.apply_load(20, 4, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 0, -2) >>> b.bc_slope = [(0, 0)] >>> b.bc_deflection = [(0, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.load 80*SingularityFunction(x, 0, -2) - 20*SingularityFunction(x, 0, -1) + 20*SingularityFunction(x, 4, -1) >>> b.slope() (-((-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))/I + 120/I)/E + 80.0/(E*I))*SingularityFunction(x, 2, 0) - 0.666666666666667*(-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))*SingularityFunction(x, 0, 0)/(E*I) + 0.666666666666667*(-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))*SingularityFunction(x, 2, 0)/(E*I) """ x = self.variable E = self.elastic_modulus new_length = self.length + beam.length if self.second_moment != beam.second_moment: new_second_moment = Piecewise((self.second_moment, x<=self.length), (beam.second_moment, x<=new_length)) else: new_second_moment = self.second_moment if via == "fixed": new_beam = Beam(new_length, E, new_second_moment, x) new_beam._composite_type = "fixed" return new_beam if via == "hinge": new_beam = Beam(new_length, E, new_second_moment, x) new_beam._composite_type = "hinge" new_beam._hinge_position = self.length return new_beam def apply_support(self, loc, type="fixed"): """ This method applies support to a particular beam object. Parameters ========== loc : Sympifyable Location of point at which support is applied. type : String Determines type of Beam support applied. To apply support structure with - zero degree of freedom, type = "fixed" - one degree of freedom, type = "pin" - two degrees of freedom, type = "roller" Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(30, E, I) >>> b.apply_support(10, 'roller') >>> b.apply_support(30, 'roller') >>> b.apply_load(-8, 0, -1) >>> b.apply_load(120, 30, -2) >>> R_10, R_30 = symbols('R_10, R_30') >>> b.solve_for_reaction_loads(R_10, R_30) >>> b.load -8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1) + 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1) >>> b.slope() (-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2) + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + 4000/3)/(E*I) """ loc = sympify(loc) self._applied_supports.append((loc, type)) if type in ("pin", "roller"): reaction_load = Symbol('R_'+str(loc)) self.apply_load(reaction_load, loc, -1) self.bc_deflection.append((loc, 0)) else: reaction_load = Symbol('R_'+str(loc)) reaction_moment = Symbol('M_'+str(loc)) self.apply_load(reaction_load, loc, -1) self.apply_load(reaction_moment, loc, -2) self.bc_deflection.append((loc, 0)) self.bc_slope.append((loc, 0)) self._support_as_loads.append((reaction_moment, loc, -2, None)) self._support_as_loads.append((reaction_load, loc, -1, None)) def apply_load(self, value, start, order, end=None): """ This method adds up the loads given to a particular beam object. Parameters ========== value : Sympifyable The value inserted should have the units [Force/(Distance**(n+1)] where n is the order of applied load. Units for applied loads: - For moments, unit = kN*m - For point loads, unit = kN - For constant distributed load, unit = kN/m - For ramp loads, unit = kN/m/m - For parabolic ramp loads, unit = kN/m/m/m - ... so on. start : Sympifyable The starting point of the applied load. For point moments and point forces this is the location of application. order : Integer The order of the applied load. - For moments, order = -2 - For point loads, order =-1 - For constant distributed load, order = 0 - For ramp loads, order = 1 - For parabolic ramp loads, order = 2 - ... so on. end : Sympifyable, optional An optional argument that can be used if the load has an end point within the length of the beam. Examples ======== There is a beam of length 4 meters. A moment of magnitude 3 Nm is applied in the clockwise direction at the starting point of the beam. A point load of magnitude 4 N is applied from the top of the beam at 2 meters from the starting point and a parabolic ramp load of magnitude 2 N/m is applied below the beam starting from 2 meters to 3 meters away from the starting point of the beam. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.apply_load(-3, 0, -2) >>> b.apply_load(4, 2, -1) >>> b.apply_load(-2, 2, 2, end=3) >>> b.load -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2) """ x = self.variable value = sympify(value) start = sympify(start) order = sympify(order) self._applied_loads.append((value, start, order, end)) self._load += value*SingularityFunction(x, start, order) self._original_load += value*SingularityFunction(x, start, order) if end: # load has an end point within the length of the beam. self._handle_end(x, value, start, order, end, type="apply") def remove_load(self, value, start, order, end=None): """ This method removes a particular load present on the beam object. Returns a ValueError if the load passed as an argument is not present on the beam. Parameters ========== value : Sympifyable The magnitude of an applied load. start : Sympifyable The starting point of the applied load. For point moments and point forces this is the location of application. order : Integer The order of the applied load. - For moments, order= -2 - For point loads, order=-1 - For constant distributed load, order=0 - For ramp loads, order=1 - For parabolic ramp loads, order=2 - ... so on. end : Sympifyable, optional An optional argument that can be used if the load has an end point within the length of the beam. Examples ======== There is a beam of length 4 meters. A moment of magnitude 3 Nm is applied in the clockwise direction at the starting point of the beam. A pointload of magnitude 4 N is applied from the top of the beam at 2 meters from the starting point and a parabolic ramp load of magnitude 2 N/m is applied below the beam starting from 2 meters to 3 meters away from the starting point of the beam. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.apply_load(-3, 0, -2) >>> b.apply_load(4, 2, -1) >>> b.apply_load(-2, 2, 2, end=3) >>> b.load -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2) >>> b.remove_load(-2, 2, 2, end = 3) >>> b.load -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) """ x = self.variable value = sympify(value) start = sympify(start) order = sympify(order) if (value, start, order, end) in self._applied_loads: self._load -= value*SingularityFunction(x, start, order) self._original_load -= value*SingularityFunction(x, start, order) self._applied_loads.remove((value, start, order, end)) else: msg = "No such load distribution exists on the beam object." raise ValueError(msg) if end: # load has an end point within the length of the beam. self._handle_end(x, value, start, order, end, type="remove") def _handle_end(self, x, value, start, order, end, type): """ This functions handles the optional `end` value in the `apply_load` and `remove_load` functions. When the value of end is not NULL, this function will be executed. """ if order.is_negative: msg = ("If 'end' is provided the 'order' of the load cannot " "be negative, i.e. 'end' is only valid for distributed " "loads.") raise ValueError(msg) # NOTE : A Taylor series can be used to define the summation of # singularity functions that subtract from the load past the end # point such that it evaluates to zero past 'end'. f = value*x**order if type == "apply": # iterating for "apply_load" method for i in range(0, order + 1): self._load -= (f.diff(x, i).subs(x, end - start) * SingularityFunction(x, end, i)/factorial(i)) self._original_load -= (f.diff(x, i).subs(x, end - start) * SingularityFunction(x, end, i)/factorial(i)) elif type == "remove": # iterating for "remove_load" method for i in range(0, order + 1): self._load += (f.diff(x, i).subs(x, end - start) * SingularityFunction(x, end, i)/factorial(i)) self._original_load += (f.diff(x, i).subs(x, end - start) * SingularityFunction(x, end, i)/factorial(i)) @property def load(self): """ Returns a Singularity Function expression which represents the load distribution curve of the Beam object. Examples ======== There is a beam of length 4 meters. A moment of magnitude 3 Nm is applied in the clockwise direction at the starting point of the beam. A point load of magnitude 4 N is applied from the top of the beam at 2 meters from the starting point and a parabolic ramp load of magnitude 2 N/m is applied below the beam starting from 3 meters away from the starting point of the beam. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.apply_load(-3, 0, -2) >>> b.apply_load(4, 2, -1) >>> b.apply_load(-2, 3, 2) >>> b.load -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 3, 2) """ return self._load @property def applied_loads(self): """ Returns a list of all loads applied on the beam object. Each load in the list is a tuple of form (value, start, order, end). Examples ======== There is a beam of length 4 meters. A moment of magnitude 3 Nm is applied in the clockwise direction at the starting point of the beam. A pointload of magnitude 4 N is applied from the top of the beam at 2 meters from the starting point. Another pointload of magnitude 5 N is applied at same position. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.apply_load(-3, 0, -2) >>> b.apply_load(4, 2, -1) >>> b.apply_load(5, 2, -1) >>> b.load -3*SingularityFunction(x, 0, -2) + 9*SingularityFunction(x, 2, -1) >>> b.applied_loads [(-3, 0, -2, None), (4, 2, -1, None), (5, 2, -1, None)] """ return self._applied_loads def _solve_hinge_beams(self, *reactions): """Method to find integration constants and reactional variables in a composite beam connected via hinge. This method resolves the composite Beam into its sub-beams and then equations of shear force, bending moment, slope and deflection are evaluated for both of them separately. These equations are then solved for unknown reactions and integration constants using the boundary conditions applied on the Beam. Equal deflection of both sub-beams at the hinge joint gives us another equation to solve the system. Examples ======== A combined beam, with constant fkexural rigidity E*I, is formed by joining a Beam of length 2*l to the right of another Beam of length l. The whole beam is fixed at both of its both end. A point load of magnitude P is also applied from the top at a distance of 2*l from starting point. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> l=symbols('l', positive=True) >>> b1=Beam(l, E, I) >>> b2=Beam(2*l, E, I) >>> b=b1.join(b2,"hinge") >>> M1, A1, M2, A2, P = symbols('M1 A1 M2 A2 P') >>> b.apply_load(A1,0,-1) >>> b.apply_load(M1,0,-2) >>> b.apply_load(P,2*l,-1) >>> b.apply_load(A2,3*l,-1) >>> b.apply_load(M2,3*l,-2) >>> b.bc_slope=[(0,0), (3*l, 0)] >>> b.bc_deflection=[(0,0), (3*l, 0)] >>> b.solve_for_reaction_loads(M1, A1, M2, A2) >>> b.reaction_loads {A1: -5*P/18, A2: -13*P/18, M1: 5*P*l/18, M2: -4*P*l/9} >>> b.slope() (5*P*l*SingularityFunction(x, 0, 1)/18 - 5*P*SingularityFunction(x, 0, 2)/36 + 5*P*SingularityFunction(x, l, 2)/36)*SingularityFunction(x, 0, 0)/(E*I) - (5*P*l*SingularityFunction(x, 0, 1)/18 - 5*P*SingularityFunction(x, 0, 2)/36 + 5*P*SingularityFunction(x, l, 2)/36)*SingularityFunction(x, l, 0)/(E*I) + (P*l**2/18 - 4*P*l*SingularityFunction(-l + x, 2*l, 1)/9 - 5*P*SingularityFunction(-l + x, 0, 2)/36 + P*SingularityFunction(-l + x, l, 2)/2 - 13*P*SingularityFunction(-l + x, 2*l, 2)/36)*SingularityFunction(x, l, 0)/(E*I) >>> b.deflection() (5*P*l*SingularityFunction(x, 0, 2)/36 - 5*P*SingularityFunction(x, 0, 3)/108 + 5*P*SingularityFunction(x, l, 3)/108)*SingularityFunction(x, 0, 0)/(E*I) - (5*P*l*SingularityFunction(x, 0, 2)/36 - 5*P*SingularityFunction(x, 0, 3)/108 + 5*P*SingularityFunction(x, l, 3)/108)*SingularityFunction(x, l, 0)/(E*I) + (5*P*l**3/54 + P*l**2*(-l + x)/18 - 2*P*l*SingularityFunction(-l + x, 2*l, 2)/9 - 5*P*SingularityFunction(-l + x, 0, 3)/108 + P*SingularityFunction(-l + x, l, 3)/6 - 13*P*SingularityFunction(-l + x, 2*l, 3)/108)*SingularityFunction(x, l, 0)/(E*I) """ x = self.variable l = self._hinge_position E = self._elastic_modulus I = self._second_moment if isinstance(I, Piecewise): I1 = I.args[0][0] I2 = I.args[1][0] else: I1 = I2 = I load_1 = 0 # Load equation on first segment of composite beam load_2 = 0 # Load equation on second segment of composite beam # Distributing load on both segments for load in self.applied_loads: if load[1] < l: load_1 += load[0]*SingularityFunction(x, load[1], load[2]) if load[2] == 0: load_1 -= load[0]*SingularityFunction(x, load[3], load[2]) elif load[2] > 0: load_1 -= load[0]*SingularityFunction(x, load[3], load[2]) + load[0]*SingularityFunction(x, load[3], 0) elif load[1] == l: load_1 += load[0]*SingularityFunction(x, load[1], load[2]) load_2 += load[0]*SingularityFunction(x, load[1] - l, load[2]) elif load[1] > l: load_2 += load[0]*SingularityFunction(x, load[1] - l, load[2]) if load[2] == 0: load_2 -= load[0]*SingularityFunction(x, load[3] - l, load[2]) elif load[2] > 0: load_2 -= load[0]*SingularityFunction(x, load[3] - l, load[2]) + load[0]*SingularityFunction(x, load[3] - l, 0) h = Symbol('h') # Force due to hinge load_1 += h*SingularityFunction(x, l, -1) load_2 -= h*SingularityFunction(x, 0, -1) eq = [] shear_1 = integrate(load_1, x) shear_curve_1 = limit(shear_1, x, l) eq.append(shear_curve_1) bending_1 = integrate(shear_1, x) moment_curve_1 = limit(bending_1, x, l) eq.append(moment_curve_1) shear_2 = integrate(load_2, x) shear_curve_2 = limit(shear_2, x, self.length - l) eq.append(shear_curve_2) bending_2 = integrate(shear_2, x) moment_curve_2 = limit(bending_2, x, self.length - l) eq.append(moment_curve_2) C1 = Symbol('C1') C2 = Symbol('C2') C3 = Symbol('C3') C4 = Symbol('C4') slope_1 = S.One/(E*I1)*(integrate(bending_1, x) + C1) def_1 = S.One/(E*I1)*(integrate((E*I)*slope_1, x) + C1*x + C2) slope_2 = S.One/(E*I2)*(integrate(integrate(integrate(load_2, x), x), x) + C3) def_2 = S.One/(E*I2)*(integrate((E*I)*slope_2, x) + C4) for position, value in self.bc_slope: if position<l: eq.append(slope_1.subs(x, position) - value) else: eq.append(slope_2.subs(x, position - l) - value) for position, value in self.bc_deflection: if position<l: eq.append(def_1.subs(x, position) - value) else: eq.append(def_2.subs(x, position - l) - value) eq.append(def_1.subs(x, l) - def_2.subs(x, 0)) # Deflection of both the segments at hinge would be equal constants = list(linsolve(eq, C1, C2, C3, C4, h, *reactions)) reaction_values = list(constants[0])[5:] self._reaction_loads = dict(zip(reactions, reaction_values)) self._load = self._load.subs(self._reaction_loads) # Substituting constants and reactional load and moments with their corresponding values slope_1 = slope_1.subs({C1: constants[0][0], h:constants[0][4]}).subs(self._reaction_loads) def_1 = def_1.subs({C1: constants[0][0], C2: constants[0][1], h:constants[0][4]}).subs(self._reaction_loads) slope_2 = slope_2.subs({x: x-l, C3: constants[0][2], h:constants[0][4]}).subs(self._reaction_loads) def_2 = def_2.subs({x: x-l,C3: constants[0][2], C4: constants[0][3], h:constants[0][4]}).subs(self._reaction_loads) self._hinge_beam_slope = slope_1*SingularityFunction(x, 0, 0) - slope_1*SingularityFunction(x, l, 0) + slope_2*SingularityFunction(x, l, 0) self._hinge_beam_deflection = def_1*SingularityFunction(x, 0, 0) - def_1*SingularityFunction(x, l, 0) + def_2*SingularityFunction(x, l, 0) def solve_for_reaction_loads(self, *reactions): """ Solves for the reaction forces. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) # Reaction force at x = 10 >>> b.apply_load(R2, 30, -1) # Reaction force at x = 30 >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.load R1*SingularityFunction(x, 10, -1) + R2*SingularityFunction(x, 30, -1) - 8*SingularityFunction(x, 0, -1) + 120*SingularityFunction(x, 30, -2) >>> b.solve_for_reaction_loads(R1, R2) >>> b.reaction_loads {R1: 6, R2: 2} >>> b.load -8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1) + 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1) """ if self._composite_type == "hinge": return self._solve_hinge_beams(*reactions) x = self.variable l = self.length C3 = Symbol('C3') C4 = Symbol('C4') shear_curve = limit(self.shear_force(), x, l) moment_curve = limit(self.bending_moment(), x, l) slope_eqs = [] deflection_eqs = [] slope_curve = integrate(self.bending_moment(), x) + C3 for position, value in self._boundary_conditions['slope']: eqs = slope_curve.subs(x, position) - value slope_eqs.append(eqs) deflection_curve = integrate(slope_curve, x) + C4 for position, value in self._boundary_conditions['deflection']: eqs = deflection_curve.subs(x, position) - value deflection_eqs.append(eqs) solution = list((linsolve([shear_curve, moment_curve] + slope_eqs + deflection_eqs, (C3, C4) + reactions).args)[0]) solution = solution[2:] self._reaction_loads = dict(zip(reactions, solution)) self._load = self._load.subs(self._reaction_loads) def shear_force(self): """ Returns a Singularity Function expression which represents the shear force curve of the Beam object. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.shear_force() 8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) - 120*SingularityFunction(x, 30, -1) - 2*SingularityFunction(x, 30, 0) """ x = self.variable return -integrate(self.load, x) def max_shear_force(self): """Returns maximum Shear force and its coordinate in the Beam object.""" shear_curve = self.shear_force() x = self.variable terms = shear_curve.args singularity = [] # Points at which shear function changes for term in terms: if isinstance(term, Mul): term = term.args[-1] # SingularityFunction in the term singularity.append(term.args[1]) singularity.sort() singularity = list(set(singularity)) intervals = [] # List of Intervals with discrete value of shear force shear_values = [] # List of values of shear force in each interval for i, s in enumerate(singularity): if s == 0: continue try: shear_slope = Piecewise((float("nan"), x<=singularity[i-1]),(self._load.rewrite(Piecewise), x<s), (float("nan"), True)) points = solve(shear_slope, x) val = [] for point in points: val.append(abs(shear_curve.subs(x, point))) points.extend([singularity[i-1], s]) val += [abs(limit(shear_curve, x, singularity[i-1], '+')), abs(limit(shear_curve, x, s, '-'))] max_shear = max(val) shear_values.append(max_shear) intervals.append(points[val.index(max_shear)]) # If shear force in a particular Interval has zero or constant # slope, then above block gives NotImplementedError as # solve can't represent Interval solutions. except NotImplementedError: initial_shear = limit(shear_curve, x, singularity[i-1], '+') final_shear = limit(shear_curve, x, s, '-') # If shear_curve has a constant slope(it is a line). if shear_curve.subs(x, (singularity[i-1] + s)/2) == (initial_shear + final_shear)/2 and initial_shear != final_shear: shear_values.extend([initial_shear, final_shear]) intervals.extend([singularity[i-1], s]) else: # shear_curve has same value in whole Interval shear_values.append(final_shear) intervals.append(Interval(singularity[i-1], s)) shear_values = list(map(abs, shear_values)) maximum_shear = max(shear_values) point = intervals[shear_values.index(maximum_shear)] return (point, maximum_shear) def bending_moment(self): """ Returns a Singularity Function expression which represents the bending moment curve of the Beam object. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.bending_moment() 8*SingularityFunction(x, 0, 1) - 6*SingularityFunction(x, 10, 1) - 120*SingularityFunction(x, 30, 0) - 2*SingularityFunction(x, 30, 1) """ x = self.variable return integrate(self.shear_force(), x) def max_bmoment(self): """Returns maximum Shear force and its coordinate in the Beam object.""" bending_curve = self.bending_moment() x = self.variable terms = bending_curve.args singularity = [] # Points at which bending moment changes for term in terms: if isinstance(term, Mul): term = term.args[-1] # SingularityFunction in the term singularity.append(term.args[1]) singularity.sort() singularity = list(set(singularity)) intervals = [] # List of Intervals with discrete value of bending moment moment_values = [] # List of values of bending moment in each interval for i, s in enumerate(singularity): if s == 0: continue try: moment_slope = Piecewise((float("nan"), x<=singularity[i-1]),(self.shear_force().rewrite(Piecewise), x<s), (float("nan"), True)) points = solve(moment_slope, x) val = [] for point in points: val.append(abs(bending_curve.subs(x, point))) points.extend([singularity[i-1], s]) val += [abs(limit(bending_curve, x, singularity[i-1], '+')), abs(limit(bending_curve, x, s, '-'))] max_moment = max(val) moment_values.append(max_moment) intervals.append(points[val.index(max_moment)]) # If bending moment in a particular Interval has zero or constant # slope, then above block gives NotImplementedError as solve # can't represent Interval solutions. except NotImplementedError: initial_moment = limit(bending_curve, x, singularity[i-1], '+') final_moment = limit(bending_curve, x, s, '-') # If bending_curve has a constant slope(it is a line). if bending_curve.subs(x, (singularity[i-1] + s)/2) == (initial_moment + final_moment)/2 and initial_moment != final_moment: moment_values.extend([initial_moment, final_moment]) intervals.extend([singularity[i-1], s]) else: # bending_curve has same value in whole Interval moment_values.append(final_moment) intervals.append(Interval(singularity[i-1], s)) moment_values = list(map(abs, moment_values)) maximum_moment = max(moment_values) point = intervals[moment_values.index(maximum_moment)] return (point, maximum_moment) def point_cflexure(self): """ Returns a Set of point(s) with zero bending moment and where bending moment curve of the beam object changes its sign from negative to positive or vice versa. Examples ======== There is is 10 meter long overhanging beam. There are two simple supports below the beam. One at the start and another one at a distance of 6 meters from the start. Point loads of magnitude 10KN and 20KN are applied at 2 meters and 4 meters from start respectively. A Uniformly distribute load of magnitude of magnitude 3KN/m is also applied on top starting from 6 meters away from starting point till end. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(10, E, I) >>> b.apply_load(-4, 0, -1) >>> b.apply_load(-46, 6, -1) >>> b.apply_load(10, 2, -1) >>> b.apply_load(20, 4, -1) >>> b.apply_load(3, 6, 0) >>> b.point_cflexure() [10/3] """ # To restrict the range within length of the Beam moment_curve = Piecewise((float("nan"), self.variable<=0), (self.bending_moment(), self.variable<self.length), (float("nan"), True)) points = solve(moment_curve.rewrite(Piecewise), self.variable, domain=S.Reals) return points def slope(self): """ Returns a Singularity Function expression which represents the slope the elastic curve of the Beam object. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.slope() (-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2) + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + 4000/3)/(E*I) """ x = self.variable E = self.elastic_modulus I = self.second_moment if self._composite_type == "hinge": return self._hinge_beam_slope if not self._boundary_conditions['slope']: return diff(self.deflection(), x) if isinstance(I, Piecewise) and self._composite_type == "fixed": args = I.args slope = 0 prev_slope = 0 prev_end = 0 for i in range(len(args)): if i != 0: prev_end = args[i-1][1].args[1] slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x)) if i != len(args) - 1: slope += (prev_slope + slope_value)*SingularityFunction(x, prev_end, 0) - \ (prev_slope + slope_value)*SingularityFunction(x, args[i][1].args[1], 0) else: slope += (prev_slope + slope_value)*SingularityFunction(x, prev_end, 0) prev_slope = slope_value.subs(x, args[i][1].args[1]) return slope C3 = Symbol('C3') slope_curve = -integrate(S.One/(E*I)*self.bending_moment(), x) + C3 bc_eqs = [] for position, value in self._boundary_conditions['slope']: eqs = slope_curve.subs(x, position) - value bc_eqs.append(eqs) constants = list(linsolve(bc_eqs, C3)) slope_curve = slope_curve.subs({C3: constants[0][0]}) return slope_curve def deflection(self): """ Returns a Singularity Function expression which represents the elastic curve or deflection of the Beam object. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.deflection() (4000*x/3 - 4*SingularityFunction(x, 0, 3)/3 + SingularityFunction(x, 10, 3) + 60*SingularityFunction(x, 30, 2) + SingularityFunction(x, 30, 3)/3 - 12000)/(E*I) """ x = self.variable E = self.elastic_modulus I = self.second_moment if self._composite_type == "hinge": return self._hinge_beam_deflection if not self._boundary_conditions['deflection'] and not self._boundary_conditions['slope']: if isinstance(I, Piecewise) and self._composite_type == "fixed": args = I.args prev_slope = 0 prev_def = 0 prev_end = 0 deflection = 0 for i in range(len(args)): if i != 0: prev_end = args[i-1][1].args[1] slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x)) recent_segment_slope = prev_slope + slope_value deflection_value = integrate(recent_segment_slope, (x, prev_end, x)) if i != len(args) - 1: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \ - (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0) else: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) prev_slope = slope_value.subs(x, args[i][1].args[1]) prev_def = deflection_value.subs(x, args[i][1].args[1]) return deflection base_char = self._base_char constants = symbols(base_char + '3:5') return S.One/(E*I)*integrate(-integrate(self.bending_moment(), x), x) + constants[0]*x + constants[1] elif not self._boundary_conditions['deflection']: base_char = self._base_char constant = symbols(base_char + '4') return integrate(self.slope(), x) + constant elif not self._boundary_conditions['slope'] and self._boundary_conditions['deflection']: if isinstance(I, Piecewise) and self._composite_type == "fixed": args = I.args prev_slope = 0 prev_def = 0 prev_end = 0 deflection = 0 for i in range(len(args)): if i != 0: prev_end = args[i-1][1].args[1] slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x)) recent_segment_slope = prev_slope + slope_value deflection_value = integrate(recent_segment_slope, (x, prev_end, x)) if i != len(args) - 1: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \ - (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0) else: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) prev_slope = slope_value.subs(x, args[i][1].args[1]) prev_def = deflection_value.subs(x, args[i][1].args[1]) return deflection base_char = self._base_char C3, C4 = symbols(base_char + '3:5') # Integration constants slope_curve = -integrate(self.bending_moment(), x) + C3 deflection_curve = integrate(slope_curve, x) + C4 bc_eqs = [] for position, value in self._boundary_conditions['deflection']: eqs = deflection_curve.subs(x, position) - value bc_eqs.append(eqs) constants = list(linsolve(bc_eqs, (C3, C4))) deflection_curve = deflection_curve.subs({C3: constants[0][0], C4: constants[0][1]}) return S.One/(E*I)*deflection_curve if isinstance(I, Piecewise) and self._composite_type == "fixed": args = I.args prev_slope = 0 prev_def = 0 prev_end = 0 deflection = 0 for i in range(len(args)): if i != 0: prev_end = args[i-1][1].args[1] slope_value = S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x)) recent_segment_slope = prev_slope + slope_value deflection_value = integrate(recent_segment_slope, (x, prev_end, x)) if i != len(args) - 1: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \ - (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0) else: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) prev_slope = slope_value.subs(x, args[i][1].args[1]) prev_def = deflection_value.subs(x, args[i][1].args[1]) return deflection C4 = Symbol('C4') deflection_curve = integrate(self.slope(), x) + C4 bc_eqs = [] for position, value in self._boundary_conditions['deflection']: eqs = deflection_curve.subs(x, position) - value bc_eqs.append(eqs) constants = list(linsolve(bc_eqs, C4)) deflection_curve = deflection_curve.subs({C4: constants[0][0]}) return deflection_curve def max_deflection(self): """ Returns point of max deflection and its corresponding deflection value in a Beam object. """ # To restrict the range within length of the Beam slope_curve = Piecewise((float("nan"), self.variable<=0), (self.slope(), self.variable<self.length), (float("nan"), True)) points = solve(slope_curve.rewrite(Piecewise), self.variable, domain=S.Reals) deflection_curve = self.deflection() deflections = [deflection_curve.subs(self.variable, x) for x in points] deflections = list(map(abs, deflections)) if len(deflections) != 0: max_def = max(deflections) return (points[deflections.index(max_def)], max_def) else: return None def shear_stress(self): """ Returns an expression representing the Shear Stress curve of the Beam object. """ return self.shear_force()/self._area def plot_shear_stress(self, subs=None): """ Returns a plot of shear stress present in the beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters and area of cross section 2 square meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6), 2) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_shear_stress() Plot object containing: [0]: cartesian line: 6875*SingularityFunction(x, 0, 0) - 2500*SingularityFunction(x, 2, 0) - 5000*SingularityFunction(x, 4, 1) + 15625*SingularityFunction(x, 8, 0) + 5000*SingularityFunction(x, 8, 1) for x over (0.0, 8.0) """ shear_stress = self.shear_stress() x = self.variable length = self.length if subs is None: subs = {} for sym in shear_stress.atoms(Symbol): if sym != x and sym not in subs: raise ValueError('value of %s was not passed.' %sym) if length in subs: length = subs[length] # Returns Plot of Shear Stress return plot (shear_stress.subs(subs), (x, 0, length), title='Shear Stress', xlabel=r'$\mathrm{x}$', ylabel=r'$\tau$', line_color='r') def plot_shear_force(self, subs=None): """ Returns a plot for Shear force present in the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_shear_force() Plot object containing: [0]: cartesian line: 13750*SingularityFunction(x, 0, 0) - 5000*SingularityFunction(x, 2, 0) - 10000*SingularityFunction(x, 4, 1) + 31250*SingularityFunction(x, 8, 0) + 10000*SingularityFunction(x, 8, 1) for x over (0.0, 8.0) """ shear_force = self.shear_force() if subs is None: subs = {} for sym in shear_force.atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(shear_force.subs(subs), (self.variable, 0, length), title='Shear Force', xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{V}$', line_color='g') def plot_bending_moment(self, subs=None): """ Returns a plot for Bending moment present in the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_bending_moment() Plot object containing: [0]: cartesian line: 13750*SingularityFunction(x, 0, 1) - 5000*SingularityFunction(x, 2, 1) - 5000*SingularityFunction(x, 4, 2) + 31250*SingularityFunction(x, 8, 1) + 5000*SingularityFunction(x, 8, 2) for x over (0.0, 8.0) """ bending_moment = self.bending_moment() if subs is None: subs = {} for sym in bending_moment.atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(bending_moment.subs(subs), (self.variable, 0, length), title='Bending Moment', xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{M}$', line_color='b') def plot_slope(self, subs=None): """ Returns a plot for slope of deflection curve of the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_slope() Plot object containing: [0]: cartesian line: -8.59375e-5*SingularityFunction(x, 0, 2) + 3.125e-5*SingularityFunction(x, 2, 2) + 2.08333333333333e-5*SingularityFunction(x, 4, 3) - 0.0001953125*SingularityFunction(x, 8, 2) - 2.08333333333333e-5*SingularityFunction(x, 8, 3) + 0.00138541666666667 for x over (0.0, 8.0) """ slope = self.slope() if subs is None: subs = {} for sym in slope.atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(slope.subs(subs), (self.variable, 0, length), title='Slope', xlabel=r'$\mathrm{x}$', ylabel=r'$\theta$', line_color='m') def plot_deflection(self, subs=None): """ Returns a plot for deflection curve of the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_deflection() Plot object containing: [0]: cartesian line: 0.00138541666666667*x - 2.86458333333333e-5*SingularityFunction(x, 0, 3) + 1.04166666666667e-5*SingularityFunction(x, 2, 3) + 5.20833333333333e-6*SingularityFunction(x, 4, 4) - 6.51041666666667e-5*SingularityFunction(x, 8, 3) - 5.20833333333333e-6*SingularityFunction(x, 8, 4) for x over (0.0, 8.0) """ deflection = self.deflection() if subs is None: subs = {} for sym in deflection.atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(deflection.subs(subs), (self.variable, 0, length), title='Deflection', xlabel=r'$\mathrm{x}$', ylabel=r'$\delta$', line_color='r') def plot_loading_results(self, subs=None): """ Returns a subplot of Shear Force, Bending Moment, Slope and Deflection of the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> axes = b.plot_loading_results() """ length = self.length variable = self.variable if subs is None: subs = {} for sym in self.deflection().atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if length in subs: length = subs[length] ax1 = plot(self.shear_force().subs(subs), (variable, 0, length), title="Shear Force", xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{V}$', line_color='g', show=False) ax2 = plot(self.bending_moment().subs(subs), (variable, 0, length), title="Bending Moment", xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{M}$', line_color='b', show=False) ax3 = plot(self.slope().subs(subs), (variable, 0, length), title="Slope", xlabel=r'$\mathrm{x}$', ylabel=r'$\theta$', line_color='m', show=False) ax4 = plot(self.deflection().subs(subs), (variable, 0, length), title="Deflection", xlabel=r'$\mathrm{x}$', ylabel=r'$\delta$', line_color='r', show=False) return PlotGrid(4, 1, ax1, ax2, ax3, ax4) def _solve_for_ild_equations(self): """ Helper function for I.L.D. It takes the unsubstituted copy of the load equation and uses it to calculate shear force and bending moment equations. """ x = self.variable shear_force = -integrate(self._original_load, x) bending_moment = integrate(shear_force, x) return shear_force, bending_moment def solve_for_ild_reactions(self, value, *reactions): """ Determines the Influence Line Diagram equations for reaction forces under the effect of a moving load. Parameters ========== value : Integer Magnitude of moving load reactions : The reaction forces applied on the beam. Examples ======== There is a beam of length 10 meters. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. Calculate the I.L.D. equations for reaction forces under the effect of a moving load of magnitude 1kN. .. image:: ildreaction.png Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.physics.continuum_mechanics.beam import Beam >>> E, I = symbols('E, I') >>> R_0, R_10 = symbols('R_0, R_10') >>> b = Beam(10, E, I) >>> b.apply_support(0, 'roller') >>> b.apply_support(10, 'roller') >>> b.solve_for_ild_reactions(1,R_0,R_10) >>> b.ild_reactions {R_0: x/10 - 1, R_10: -x/10} """ shear_force, bending_moment = self._solve_for_ild_equations() x = self.variable l = self.length C3 = Symbol('C3') C4 = Symbol('C4') shear_curve = limit(shear_force, x, l) - value moment_curve = limit(bending_moment, x, l) - value*(l-x) slope_eqs = [] deflection_eqs = [] slope_curve = integrate(bending_moment, x) + C3 for position, value in self._boundary_conditions['slope']: eqs = slope_curve.subs(x, position) - value slope_eqs.append(eqs) deflection_curve = integrate(slope_curve, x) + C4 for position, value in self._boundary_conditions['deflection']: eqs = deflection_curve.subs(x, position) - value deflection_eqs.append(eqs) solution = list((linsolve([shear_curve, moment_curve] + slope_eqs + deflection_eqs, (C3, C4) + reactions).args)[0]) solution = solution[2:] # Determining the equations and solving them. self._ild_reactions = dict(zip(reactions, solution)) def plot_ild_reactions(self, subs=None): """ Plots the Influence Line Diagram of Reaction Forces under the effect of a moving load. This function should be called after calling solve_for_ild_reactions(). Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 10 meters. A point load of magnitude 5KN is also applied from top of the beam, at a distance of 4 meters from the starting point. There are two simple supports below the beam, located at the starting point and at a distance of 7 meters from the starting point. Plot the I.L.D. equations for reactions at both support points under the effect of a moving load of magnitude 1kN. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.physics.continuum_mechanics.beam import Beam >>> E, I = symbols('E, I') >>> R_0, R_7 = symbols('R_0, R_7') >>> b = Beam(10, E, I) >>> b.apply_support(0, 'roller') >>> b.apply_support(7, 'roller') >>> b.apply_load(5,4,-1) >>> b.solve_for_ild_reactions(1,R_0,R_7) >>> b.ild_reactions {R_0: x/7 - 22/7, R_7: -x/7 - 20/7} >>> b.plot_ild_reactions() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: x/7 - 22/7 for x over (0.0, 10.0) Plot[1]:Plot object containing: [0]: cartesian line: -x/7 - 20/7 for x over (0.0, 10.0) """ if not self._ild_reactions: raise ValueError("I.L.D. reaction equations not found. Please use solve_for_ild_reactions() to generate the I.L.D. reaction equations.") x = self.variable ildplots = [] if subs is None: subs = {} for reaction in self._ild_reactions: for sym in self._ild_reactions[reaction].atoms(Symbol): if sym != x and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) for sym in self._length.atoms(Symbol): if sym != x and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) for reaction in self._ild_reactions: ildplots.append(plot(self._ild_reactions[reaction].subs(subs), (x, 0, self._length.subs(subs)), title='I.L.D. for Reactions', xlabel=x, ylabel=reaction, line_color='blue', show=False)) return PlotGrid(len(ildplots), 1, *ildplots) def solve_for_ild_shear(self, distance, value, *reactions): """ Determines the Influence Line Diagram equations for shear at a specified point under the effect of a moving load. Parameters ========== distance : Integer Distance of the point from the start of the beam for which equations are to be determined value : Integer Magnitude of moving load reactions : The reaction forces applied on the beam. Examples ======== There is a beam of length 12 meters. There are two simple supports below the beam, one at the starting point and another at a distance of 8 meters. Calculate the I.L.D. equations for Shear at a distance of 4 meters under the effect of a moving load of magnitude 1kN. .. image:: ildshear.png Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.physics.continuum_mechanics.beam import Beam >>> E, I = symbols('E, I') >>> R_0, R_8 = symbols('R_0, R_8') >>> b = Beam(12, E, I) >>> b.apply_support(0, 'roller') >>> b.apply_support(8, 'roller') >>> b.solve_for_ild_reactions(1, R_0, R_8) >>> b.solve_for_ild_shear(4, 1, R_0, R_8) >>> b.ild_shear Piecewise((x/8, x < 4), (x/8 - 1, x > 4)) """ x = self.variable l = self.length shear_force, _ = self._solve_for_ild_equations() shear_curve1 = value - limit(shear_force, x, distance) shear_curve2 = (limit(shear_force, x, l) - limit(shear_force, x, distance)) - value for reaction in reactions: shear_curve1 = shear_curve1.subs(reaction,self._ild_reactions[reaction]) shear_curve2 = shear_curve2.subs(reaction,self._ild_reactions[reaction]) shear_eq = Piecewise((shear_curve1, x < distance), (shear_curve2, x > distance)) self._ild_shear = shear_eq def plot_ild_shear(self,subs=None): """ Plots the Influence Line Diagram for Shear under the effect of a moving load. This function should be called after calling solve_for_ild_shear(). Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 12 meters. There are two simple supports below the beam, one at the starting point and another at a distance of 8 meters. Plot the I.L.D. for Shear at a distance of 4 meters under the effect of a moving load of magnitude 1kN. .. image:: ildshear.png Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.physics.continuum_mechanics.beam import Beam >>> E, I = symbols('E, I') >>> R_0, R_8 = symbols('R_0, R_8') >>> b = Beam(12, E, I) >>> b.apply_support(0, 'roller') >>> b.apply_support(8, 'roller') >>> b.solve_for_ild_reactions(1, R_0, R_8) >>> b.solve_for_ild_shear(4, 1, R_0, R_8) >>> b.ild_shear Piecewise((x/8, x < 4), (x/8 - 1, x > 4)) >>> b.plot_ild_shear() Plot object containing: [0]: cartesian line: Piecewise((x/8, x < 4), (x/8 - 1, x > 4)) for x over (0.0, 12.0) """ if not self._ild_shear: raise ValueError("I.L.D. shear equation not found. Please use solve_for_ild_shear() to generate the I.L.D. shear equations.") x = self.variable l = self._length if subs is None: subs = {} for sym in self._ild_shear.atoms(Symbol): if sym != x and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) for sym in self._length.atoms(Symbol): if sym != x and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) return plot(self._ild_shear.subs(subs), (x, 0, l), title='I.L.D. for Shear', xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{V}$', line_color='blue',show=True) def solve_for_ild_moment(self, distance, value, *reactions): """ Determines the Influence Line Diagram equations for moment at a specified point under the effect of a moving load. Parameters ========== distance : Integer Distance of the point from the start of the beam for which equations are to be determined value : Integer Magnitude of moving load reactions : The reaction forces applied on the beam. Examples ======== There is a beam of length 12 meters. There are two simple supports below the beam, one at the starting point and another at a distance of 8 meters. Calculate the I.L.D. equations for Moment at a distance of 4 meters under the effect of a moving load of magnitude 1kN. .. image:: ildshear.png Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.physics.continuum_mechanics.beam import Beam >>> E, I = symbols('E, I') >>> R_0, R_8 = symbols('R_0, R_8') >>> b = Beam(12, E, I) >>> b.apply_support(0, 'roller') >>> b.apply_support(8, 'roller') >>> b.solve_for_ild_reactions(1, R_0, R_8) >>> b.solve_for_ild_moment(4, 1, R_0, R_8) >>> b.ild_moment Piecewise((-x/2, x < 4), (x/2 - 4, x > 4)) """ x = self.variable l = self.length _, moment = self._solve_for_ild_equations() moment_curve1 = value*(distance-x) - limit(moment, x, distance) moment_curve2= (limit(moment, x, l)-limit(moment, x, distance))-value*(l-x) for reaction in reactions: moment_curve1 = moment_curve1.subs(reaction, self._ild_reactions[reaction]) moment_curve2 = moment_curve2.subs(reaction, self._ild_reactions[reaction]) moment_eq = Piecewise((moment_curve1, x < distance), (moment_curve2, x > distance)) self._ild_moment = moment_eq def plot_ild_moment(self,subs=None): """ Plots the Influence Line Diagram for Moment under the effect of a moving load. This function should be called after calling solve_for_ild_moment(). Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 12 meters. There are two simple supports below the beam, one at the starting point and another at a distance of 8 meters. Plot the I.L.D. for Moment at a distance of 4 meters under the effect of a moving load of magnitude 1kN. .. image:: ildshear.png Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.physics.continuum_mechanics.beam import Beam >>> E, I = symbols('E, I') >>> R_0, R_8 = symbols('R_0, R_8') >>> b = Beam(12, E, I) >>> b.apply_support(0, 'roller') >>> b.apply_support(8, 'roller') >>> b.solve_for_ild_reactions(1, R_0, R_8) >>> b.solve_for_ild_moment(4, 1, R_0, R_8) >>> b.ild_moment Piecewise((-x/2, x < 4), (x/2 - 4, x > 4)) >>> b.plot_ild_moment() Plot object containing: [0]: cartesian line: Piecewise((-x/2, x < 4), (x/2 - 4, x > 4)) for x over (0.0, 12.0) """ if not self._ild_moment: raise ValueError("I.L.D. moment equation not found. Please use solve_for_ild_moment() to generate the I.L.D. moment equations.") x = self.variable if subs is None: subs = {} for sym in self._ild_moment.atoms(Symbol): if sym != x and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) for sym in self._length.atoms(Symbol): if sym != x and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) return plot(self._ild_moment.subs(subs), (x, 0, self._length), title='I.L.D. for Moment', xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{M}$', line_color='blue', show=True) @doctest_depends_on(modules=('numpy',)) def draw(self, pictorial=True): """ Returns a plot object representing the beam diagram of the beam. .. note:: The user must be careful while entering load values. The draw function assumes a sign convention which is used for plotting loads. Given a right handed coordinate system with XYZ coordinates, the beam's length is assumed to be along the positive X axis. The draw function recognizes positve loads(with n>-2) as loads acting along negative Y direction and positve moments acting along positive Z direction. Parameters ========== pictorial: Boolean (default=True) Setting ``pictorial=True`` would simply create a pictorial (scaled) view of the beam diagram not with the exact dimensions. Although setting ``pictorial=False`` would create a beam diagram with the exact dimensions on the plot Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> E, I = symbols('E, I') >>> b = Beam(50, 20, 30) >>> b.apply_load(10, 2, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(90, 5, 0, 23) >>> b.apply_load(10, 30, 1, 50) >>> b.apply_support(50, "pin") >>> b.apply_support(0, "fixed") >>> b.apply_support(20, "roller") >>> p = b.draw() >>> p Plot object containing: [0]: cartesian line: 25*SingularityFunction(x, 5, 0) - 25*SingularityFunction(x, 23, 0) + SingularityFunction(x, 30, 1) - 20*SingularityFunction(x, 50, 0) - SingularityFunction(x, 50, 1) + 5 for x over (0.0, 50.0) [1]: cartesian line: 5 for x over (0.0, 50.0) >>> p.show() """ if not numpy: raise ImportError("To use this function numpy module is required") x = self.variable # checking whether length is an expression in terms of any Symbol. if isinstance(self.length, Expr): l = list(self.length.atoms(Symbol)) # assigning every Symbol a default value of 10 l = {i:10 for i in l} length = self.length.subs(l) else: l = {} length = self.length height = length/10 rectangles = [] rectangles.append({'xy':(0, 0), 'width':length, 'height': height, 'facecolor':"brown"}) annotations, markers, load_eq,load_eq1, fill = self._draw_load(pictorial, length, l) support_markers, support_rectangles = self._draw_supports(length, l) rectangles += support_rectangles markers += support_markers sing_plot = plot(height + load_eq, height + load_eq1, (x, 0, length), xlim=(-height, length + height), ylim=(-length, 1.25*length), annotations=annotations, markers=markers, rectangles=rectangles, line_color='brown', fill=fill, axis=False, show=False) return sing_plot def _draw_load(self, pictorial, length, l): loads = list(set(self.applied_loads) - set(self._support_as_loads)) height = length/10 x = self.variable annotations = [] markers = [] load_args = [] scaled_load = 0 load_args1 = [] scaled_load1 = 0 load_eq = 0 # For positive valued higher order loads load_eq1 = 0 # For negative valued higher order loads fill = None plus = 0 # For positive valued higher order loads minus = 0 # For negative valued higher order loads for load in loads: # check if the position of load is in terms of the beam length. if l: pos = load[1].subs(l) else: pos = load[1] # point loads if load[2] == -1: if isinstance(load[0], Symbol) or load[0].is_negative: annotations.append({'text':'', 'xy':(pos, 0), 'xytext':(pos, height - 4*height), 'arrowprops':dict(width= 1.5, headlength=5, headwidth=5, facecolor='black')}) else: annotations.append({'text':'', 'xy':(pos, height), 'xytext':(pos, height*4), 'arrowprops':dict(width= 1.5, headlength=4, headwidth=4, facecolor='black')}) # moment loads elif load[2] == -2: if load[0].is_negative: markers.append({'args':[[pos], [height/2]], 'marker': r'$\circlearrowright$', 'markersize':15}) else: markers.append({'args':[[pos], [height/2]], 'marker': r'$\circlearrowleft$', 'markersize':15}) # higher order loads elif load[2] >= 0: # `fill` will be assigned only when higher order loads are present value, start, order, end = load # Positive loads have their seperate equations if(value>0): plus = 1 # if pictorial is True we remake the load equation again with # some constant magnitude values. if pictorial: value = 10**(1-order) if order > 0 else length/2 scaled_load += value*SingularityFunction(x, start, order) if end: f2 = 10**(1-order)*x**order if order > 0 else length/2*x**order for i in range(0, order + 1): scaled_load -= (f2.diff(x, i).subs(x, end - start)* SingularityFunction(x, end, i)/factorial(i)) if pictorial: if isinstance(scaled_load, Add): load_args = scaled_load.args else: # when the load equation consists of only a single term load_args = (scaled_load,) load_eq = [i.subs(l) for i in load_args] else: if isinstance(self.load, Add): load_args = self.load.args else: load_args = (self.load,) load_eq = [i.subs(l) for i in load_args if list(i.atoms(SingularityFunction))[0].args[2] >= 0] load_eq = Add(*load_eq) # filling higher order loads with colour expr = height + load_eq.rewrite(Piecewise) y1 = lambdify(x, expr, 'numpy') # For loads with negative value else: minus = 1 # if pictorial is True we remake the load equation again with # some constant magnitude values. if pictorial: value = 10**(1-order) if order > 0 else length/2 scaled_load1 += value*SingularityFunction(x, start, order) if end: f2 = 10**(1-order)*x**order if order > 0 else length/2*x**order for i in range(0, order + 1): scaled_load1 -= (f2.diff(x, i).subs(x, end - start)* SingularityFunction(x, end, i)/factorial(i)) if pictorial: if isinstance(scaled_load1, Add): load_args1 = scaled_load1.args else: # when the load equation consists of only a single term load_args1 = (scaled_load1,) load_eq1 = [i.subs(l) for i in load_args1] else: if isinstance(self.load, Add): load_args1 = self.load.args1 else: load_args1 = (self.load,) load_eq1 = [i.subs(l) for i in load_args if list(i.atoms(SingularityFunction))[0].args[2] >= 0] load_eq1 = -Add(*load_eq1)-height # filling higher order loads with colour expr = height + load_eq1.rewrite(Piecewise) y1_ = lambdify(x, expr, 'numpy') y = numpy.arange(0, float(length), 0.001) y2 = float(height) if(plus == 1 and minus == 1): fill = {'x': y, 'y1': y1(y), 'y2': y1_(y), 'color':'darkkhaki'} elif(plus == 1): fill = {'x': y, 'y1': y1(y), 'y2': y2, 'color':'darkkhaki'} else: fill = {'x': y, 'y1': y1_(y), 'y2': y2, 'color':'darkkhaki'} return annotations, markers, load_eq, load_eq1, fill def _draw_supports(self, length, l): height = float(length/10) support_markers = [] support_rectangles = [] for support in self._applied_supports: if l: pos = support[0].subs(l) else: pos = support[0] if support[1] == "pin": support_markers.append({'args':[pos, [0]], 'marker':6, 'markersize':13, 'color':"black"}) elif support[1] == "roller": support_markers.append({'args':[pos, [-height/2.5]], 'marker':'o', 'markersize':11, 'color':"black"}) elif support[1] == "fixed": if pos == 0: support_rectangles.append({'xy':(0, -3*height), 'width':-length/20, 'height':6*height + height, 'fill':False, 'hatch':'/////'}) else: support_rectangles.append({'xy':(length, -3*height), 'width':length/20, 'height': 6*height + height, 'fill':False, 'hatch':'/////'}) return support_markers, support_rectangles class Beam3D(Beam): """ This class handles loads applied in any direction of a 3D space along with unequal values of Second moment along different axes. .. note:: A consistent sign convention must be used while solving a beam bending problem; the results will automatically follow the chosen sign convention. This class assumes that any kind of distributed load/moment is applied through out the span of a beam. Examples ======== There is a beam of l meters long. A constant distributed load of magnitude q is applied along y-axis from start till the end of beam. A constant distributed moment of magnitude m is also applied along z-axis from start till the end of beam. Beam is fixed at both of its end. So, deflection of the beam at the both ends is restricted. >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols, simplify, collect, factor >>> l, E, G, I, A = symbols('l, E, G, I, A') >>> b = Beam3D(l, E, G, I, A) >>> x, q, m = symbols('x, q, m') >>> b.apply_load(q, 0, 0, dir="y") >>> b.apply_moment_load(m, 0, -1, dir="z") >>> b.shear_force() [0, -q*x, 0] >>> b.bending_moment() [0, 0, -m*x + q*x**2/2] >>> b.bc_slope = [(0, [0, 0, 0]), (l, [0, 0, 0])] >>> b.bc_deflection = [(0, [0, 0, 0]), (l, [0, 0, 0])] >>> b.solve_slope_deflection() >>> factor(b.slope()) [0, 0, x*(-l + x)*(-A*G*l**3*q + 2*A*G*l**2*q*x - 12*E*I*l*q - 72*E*I*m + 24*E*I*q*x)/(12*E*I*(A*G*l**2 + 12*E*I))] >>> dx, dy, dz = b.deflection() >>> dy = collect(simplify(dy), x) >>> dx == dz == 0 True >>> dy == (x*(12*E*I*l*(A*G*l**2*q - 2*A*G*l*m + 12*E*I*q) ... + x*(A*G*l*(3*l*(A*G*l**2*q - 2*A*G*l*m + 12*E*I*q) + x*(-2*A*G*l**2*q + 4*A*G*l*m - 24*E*I*q)) ... + A*G*(A*G*l**2 + 12*E*I)*(-2*l**2*q + 6*l*m - 4*m*x + q*x**2) ... - 12*E*I*q*(A*G*l**2 + 12*E*I)))/(24*A*E*G*I*(A*G*l**2 + 12*E*I))) True References ========== .. [1] http://homes.civil.aau.dk/jc/FemteSemester/Beams3D.pdf """ def __init__(self, length, elastic_modulus, shear_modulus, second_moment, area, variable=Symbol('x')): """Initializes the class. Parameters ========== length : Sympifyable A Symbol or value representing the Beam's length. elastic_modulus : Sympifyable A SymPy expression representing the Beam's Modulus of Elasticity. It is a measure of the stiffness of the Beam material. shear_modulus : Sympifyable A SymPy expression representing the Beam's Modulus of rigidity. It is a measure of rigidity of the Beam material. second_moment : Sympifyable or list A list of two elements having SymPy expression representing the Beam's Second moment of area. First value represent Second moment across y-axis and second across z-axis. Single SymPy expression can be passed if both values are same area : Sympifyable A SymPy expression representing the Beam's cross-sectional area in a plane prependicular to length of the Beam. variable : Symbol, optional A Symbol object that will be used as the variable along the beam while representing the load, shear, moment, slope and deflection curve. By default, it is set to ``Symbol('x')``. """ super().__init__(length, elastic_modulus, second_moment, variable) self.shear_modulus = shear_modulus self.area = area self._load_vector = [0, 0, 0] self._moment_load_vector = [0, 0, 0] self._torsion_moment = {} self._load_Singularity = [0, 0, 0] self._slope = [0, 0, 0] self._deflection = [0, 0, 0] self._angular_deflection = 0 @property def shear_modulus(self): """Young's Modulus of the Beam. """ return self._shear_modulus @shear_modulus.setter def shear_modulus(self, e): self._shear_modulus = sympify(e) @property def second_moment(self): """Second moment of area of the Beam. """ return self._second_moment @second_moment.setter def second_moment(self, i): if isinstance(i, list): i = [sympify(x) for x in i] self._second_moment = i else: self._second_moment = sympify(i) @property def area(self): """Cross-sectional area of the Beam. """ return self._area @area.setter def area(self, a): self._area = sympify(a) @property def load_vector(self): """ Returns a three element list representing the load vector. """ return self._load_vector @property def moment_load_vector(self): """ Returns a three element list representing moment loads on Beam. """ return self._moment_load_vector @property def boundary_conditions(self): """ Returns a dictionary of boundary conditions applied on the beam. The dictionary has two keywords namely slope and deflection. The value of each keyword is a list of tuple, where each tuple contains location and value of a boundary condition in the format (location, value). Further each value is a list corresponding to slope or deflection(s) values along three axes at that location. Examples ======== There is a beam of length 4 meters. The slope at 0 should be 4 along the x-axis and 0 along others. At the other end of beam, deflection along all the three axes should be zero. >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(30, E, G, I, A, x) >>> b.bc_slope = [(0, (4, 0, 0))] >>> b.bc_deflection = [(4, [0, 0, 0])] >>> b.boundary_conditions {'deflection': [(4, [0, 0, 0])], 'slope': [(0, (4, 0, 0))]} Here the deflection of the beam should be ``0`` along all the three axes at ``4``. Similarly, the slope of the beam should be ``4`` along x-axis and ``0`` along y and z axis at ``0``. """ return self._boundary_conditions def polar_moment(self): """ Returns the polar moment of area of the beam about the X axis with respect to the centroid. Examples ======== >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A = symbols('l, E, G, I, A') >>> b = Beam3D(l, E, G, I, A) >>> b.polar_moment() 2*I >>> I1 = [9, 15] >>> b = Beam3D(l, E, G, I1, A) >>> b.polar_moment() 24 """ if not iterable(self.second_moment): return 2*self.second_moment return sum(self.second_moment) def apply_load(self, value, start, order, dir="y"): """ This method adds up the force load to a particular beam object. Parameters ========== value : Sympifyable The magnitude of an applied load. dir : String Axis along which load is applied. order : Integer The order of the applied load. - For point loads, order=-1 - For constant distributed load, order=0 - For ramp loads, order=1 - For parabolic ramp loads, order=2 - ... so on. """ x = self.variable value = sympify(value) start = sympify(start) order = sympify(order) if dir == "x": if not order == -1: self._load_vector[0] += value self._load_Singularity[0] += value*SingularityFunction(x, start, order) elif dir == "y": if not order == -1: self._load_vector[1] += value self._load_Singularity[1] += value*SingularityFunction(x, start, order) else: if not order == -1: self._load_vector[2] += value self._load_Singularity[2] += value*SingularityFunction(x, start, order) def apply_moment_load(self, value, start, order, dir="y"): """ This method adds up the moment loads to a particular beam object. Parameters ========== value : Sympifyable The magnitude of an applied moment. dir : String Axis along which moment is applied. order : Integer The order of the applied load. - For point moments, order=-2 - For constant distributed moment, order=-1 - For ramp moments, order=0 - For parabolic ramp moments, order=1 - ... so on. """ x = self.variable value = sympify(value) start = sympify(start) order = sympify(order) if dir == "x": if not order == -2: self._moment_load_vector[0] += value else: if start in list(self._torsion_moment): self._torsion_moment[start] += value else: self._torsion_moment[start] = value self._load_Singularity[0] += value*SingularityFunction(x, start, order) elif dir == "y": if not order == -2: self._moment_load_vector[1] += value self._load_Singularity[0] += value*SingularityFunction(x, start, order) else: if not order == -2: self._moment_load_vector[2] += value self._load_Singularity[0] += value*SingularityFunction(x, start, order) def apply_support(self, loc, type="fixed"): if type in ("pin", "roller"): reaction_load = Symbol('R_'+str(loc)) self._reaction_loads[reaction_load] = reaction_load self.bc_deflection.append((loc, [0, 0, 0])) else: reaction_load = Symbol('R_'+str(loc)) reaction_moment = Symbol('M_'+str(loc)) self._reaction_loads[reaction_load] = [reaction_load, reaction_moment] self.bc_deflection.append((loc, [0, 0, 0])) self.bc_slope.append((loc, [0, 0, 0])) def solve_for_reaction_loads(self, *reaction): """ Solves for the reaction forces. Examples ======== There is a beam of length 30 meters. It it supported by rollers at of its end. A constant distributed load of magnitude 8 N is applied from start till its end along y-axis. Another linear load having slope equal to 9 is applied along z-axis. >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(30, E, G, I, A, x) >>> b.apply_load(8, start=0, order=0, dir="y") >>> b.apply_load(9*x, start=0, order=0, dir="z") >>> b.bc_deflection = [(0, [0, 0, 0]), (30, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="y") >>> b.apply_load(R2, start=30, order=-1, dir="y") >>> b.apply_load(R3, start=0, order=-1, dir="z") >>> b.apply_load(R4, start=30, order=-1, dir="z") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.reaction_loads {R1: -120, R2: -120, R3: -1350, R4: -2700} """ x = self.variable l = self.length q = self._load_Singularity shear_curves = [integrate(load, x) for load in q] moment_curves = [integrate(shear, x) for shear in shear_curves] for i in range(3): react = [r for r in reaction if (shear_curves[i].has(r) or moment_curves[i].has(r))] if len(react) == 0: continue shear_curve = limit(shear_curves[i], x, l) moment_curve = limit(moment_curves[i], x, l) sol = list((linsolve([shear_curve, moment_curve], react).args)[0]) sol_dict = dict(zip(react, sol)) reaction_loads = self._reaction_loads # Check if any of the evaluated rection exists in another direction # and if it exists then it should have same value. for key in sol_dict: if key in reaction_loads and sol_dict[key] != reaction_loads[key]: raise ValueError("Ambiguous solution for %s in different directions." % key) self._reaction_loads.update(sol_dict) def shear_force(self): """ Returns a list of three expressions which represents the shear force curve of the Beam object along all three axes. """ x = self.variable q = self._load_vector return [integrate(-q[0], x), integrate(-q[1], x), integrate(-q[2], x)] def axial_force(self): """ Returns expression of Axial shear force present inside the Beam object. """ return self.shear_force()[0] def shear_stress(self): """ Returns a list of three expressions which represents the shear stress curve of the Beam object along all three axes. """ return [self.shear_force()[0]/self._area, self.shear_force()[1]/self._area, self.shear_force()[2]/self._area] def axial_stress(self): """ Returns expression of Axial stress present inside the Beam object. """ return self.axial_force()/self._area def bending_moment(self): """ Returns a list of three expressions which represents the bending moment curve of the Beam object along all three axes. """ x = self.variable m = self._moment_load_vector shear = self.shear_force() return [integrate(-m[0], x), integrate(-m[1] + shear[2], x), integrate(-m[2] - shear[1], x) ] def torsional_moment(self): """ Returns expression of Torsional moment present inside the Beam object. """ return self.bending_moment()[0] def solve_for_torsion(self): """ Solves for the angular deflection due to the torsional effects of moments being applied in the x-direction i.e. out of or into the beam. Here, a positive torque means the direction of the torque is positive i.e. out of the beam along the beam-axis. Likewise, a negative torque signifies a torque into the beam cross-section. Examples ======== >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, E, G, I, A, x) >>> b.apply_moment_load(4, 4, -2, dir='x') >>> b.apply_moment_load(4, 8, -2, dir='x') >>> b.apply_moment_load(4, 8, -2, dir='x') >>> b.solve_for_torsion() >>> b.angular_deflection().subs(x, 3) 18/(G*I) """ x = self.variable sum_moments = 0 for point in list(self._torsion_moment): sum_moments += self._torsion_moment[point] list(self._torsion_moment).sort() pointsList = list(self._torsion_moment) torque_diagram = Piecewise((sum_moments, x<=pointsList[0]), (0, x>=pointsList[0])) for i in range(len(pointsList))[1:]: sum_moments -= self._torsion_moment[pointsList[i-1]] torque_diagram += Piecewise((0, x<=pointsList[i-1]), (sum_moments, x<=pointsList[i]), (0, x>=pointsList[i])) integrated_torque_diagram = integrate(torque_diagram) self._angular_deflection = integrated_torque_diagram/(self.shear_modulus*self.polar_moment()) def solve_slope_deflection(self): x = self.variable l = self.length E = self.elastic_modulus G = self.shear_modulus I = self.second_moment if isinstance(I, list): I_y, I_z = I[0], I[1] else: I_y = I_z = I A = self._area load = self._load_vector moment = self._moment_load_vector defl = Function('defl') theta = Function('theta') # Finding deflection along x-axis(and corresponding slope value by differentiating it) # Equation used: Derivative(E*A*Derivative(def_x(x), x), x) + load_x = 0 eq = Derivative(E*A*Derivative(defl(x), x), x) + load[0] def_x = dsolve(Eq(eq, 0), defl(x)).args[1] # Solving constants originated from dsolve C1 = Symbol('C1') C2 = Symbol('C2') constants = list((linsolve([def_x.subs(x, 0), def_x.subs(x, l)], C1, C2).args)[0]) def_x = def_x.subs({C1:constants[0], C2:constants[1]}) slope_x = def_x.diff(x) self._deflection[0] = def_x self._slope[0] = slope_x # Finding deflection along y-axis and slope across z-axis. System of equation involved: # 1: Derivative(E*I_z*Derivative(theta_z(x), x), x) + G*A*(Derivative(defl_y(x), x) - theta_z(x)) + moment_z = 0 # 2: Derivative(G*A*(Derivative(defl_y(x), x) - theta_z(x)), x) + load_y = 0 C_i = Symbol('C_i') # Substitute value of `G*A*(Derivative(defl_y(x), x) - theta_z(x))` from (2) in (1) eq1 = Derivative(E*I_z*Derivative(theta(x), x), x) + (integrate(-load[1], x) + C_i) + moment[2] slope_z = dsolve(Eq(eq1, 0)).args[1] # Solve for constants originated from using dsolve on eq1 constants = list((linsolve([slope_z.subs(x, 0), slope_z.subs(x, l)], C1, C2).args)[0]) slope_z = slope_z.subs({C1:constants[0], C2:constants[1]}) # Put value of slope obtained back in (2) to solve for `C_i` and find deflection across y-axis eq2 = G*A*(Derivative(defl(x), x)) + load[1]*x - C_i - G*A*slope_z def_y = dsolve(Eq(eq2, 0), defl(x)).args[1] # Solve for constants originated from using dsolve on eq2 constants = list((linsolve([def_y.subs(x, 0), def_y.subs(x, l)], C1, C_i).args)[0]) self._deflection[1] = def_y.subs({C1:constants[0], C_i:constants[1]}) self._slope[2] = slope_z.subs(C_i, constants[1]) # Finding deflection along z-axis and slope across y-axis. System of equation involved: # 1: Derivative(E*I_y*Derivative(theta_y(x), x), x) - G*A*(Derivative(defl_z(x), x) + theta_y(x)) + moment_y = 0 # 2: Derivative(G*A*(Derivative(defl_z(x), x) + theta_y(x)), x) + load_z = 0 # Substitute value of `G*A*(Derivative(defl_y(x), x) + theta_z(x))` from (2) in (1) eq1 = Derivative(E*I_y*Derivative(theta(x), x), x) + (integrate(load[2], x) - C_i) + moment[1] slope_y = dsolve(Eq(eq1, 0)).args[1] # Solve for constants originated from using dsolve on eq1 constants = list((linsolve([slope_y.subs(x, 0), slope_y.subs(x, l)], C1, C2).args)[0]) slope_y = slope_y.subs({C1:constants[0], C2:constants[1]}) # Put value of slope obtained back in (2) to solve for `C_i` and find deflection across z-axis eq2 = G*A*(Derivative(defl(x), x)) + load[2]*x - C_i + G*A*slope_y def_z = dsolve(Eq(eq2,0)).args[1] # Solve for constants originated from using dsolve on eq2 constants = list((linsolve([def_z.subs(x, 0), def_z.subs(x, l)], C1, C_i).args)[0]) self._deflection[2] = def_z.subs({C1:constants[0], C_i:constants[1]}) self._slope[1] = slope_y.subs(C_i, constants[1]) def slope(self): """ Returns a three element list representing slope of deflection curve along all the three axes. """ return self._slope def deflection(self): """ Returns a three element list representing deflection curve along all the three axes. """ return self._deflection def angular_deflection(self): """ Returns a function in x depicting how the angular deflection, due to moments in the x-axis on the beam, varies with x. """ return self._angular_deflection def _plot_shear_force(self, dir, subs=None): shear_force = self.shear_force() if dir == 'x': dir_num = 0 color = 'r' elif dir == 'y': dir_num = 1 color = 'g' elif dir == 'z': dir_num = 2 color = 'b' if subs is None: subs = {} for sym in shear_force[dir_num].atoms(Symbol): if sym != self.variable and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(shear_force[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Shear Force along %c direction'%dir, xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{V(%c)}$'%dir, line_color=color) def plot_shear_force(self, dir="all", subs=None): """ Returns a plot for Shear force along all three directions present in the Beam object. Parameters ========== dir : string (default : "all") Direction along which shear force plot is required. If no direction is specified, all plots are displayed. subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, E, G, I, A, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.plot_shear_force() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: 0 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: -6*x**2 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: -15*x for x over (0.0, 20.0) """ dir = dir.lower() # For shear force along x direction if dir == "x": Px = self._plot_shear_force('x', subs) return Px.show() # For shear force along y direction elif dir == "y": Py = self._plot_shear_force('y', subs) return Py.show() # For shear force along z direction elif dir == "z": Pz = self._plot_shear_force('z', subs) return Pz.show() # For shear force along all direction else: Px = self._plot_shear_force('x', subs) Py = self._plot_shear_force('y', subs) Pz = self._plot_shear_force('z', subs) return PlotGrid(3, 1, Px, Py, Pz) def _plot_bending_moment(self, dir, subs=None): bending_moment = self.bending_moment() if dir == 'x': dir_num = 0 color = 'g' elif dir == 'y': dir_num = 1 color = 'c' elif dir == 'z': dir_num = 2 color = 'm' if subs is None: subs = {} for sym in bending_moment[dir_num].atoms(Symbol): if sym != self.variable and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(bending_moment[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Bending Moment along %c direction'%dir, xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{M(%c)}$'%dir, line_color=color) def plot_bending_moment(self, dir="all", subs=None): """ Returns a plot for bending moment along all three directions present in the Beam object. Parameters ========== dir : string (default : "all") Direction along which bending moment plot is required. If no direction is specified, all plots are displayed. subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, E, G, I, A, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.plot_bending_moment() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: 0 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: -15*x**2/2 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: 2*x**3 for x over (0.0, 20.0) """ dir = dir.lower() # For bending moment along x direction if dir == "x": Px = self._plot_bending_moment('x', subs) return Px.show() # For bending moment along y direction elif dir == "y": Py = self._plot_bending_moment('y', subs) return Py.show() # For bending moment along z direction elif dir == "z": Pz = self._plot_bending_moment('z', subs) return Pz.show() # For bending moment along all direction else: Px = self._plot_bending_moment('x', subs) Py = self._plot_bending_moment('y', subs) Pz = self._plot_bending_moment('z', subs) return PlotGrid(3, 1, Px, Py, Pz) def _plot_slope(self, dir, subs=None): slope = self.slope() if dir == 'x': dir_num = 0 color = 'b' elif dir == 'y': dir_num = 1 color = 'm' elif dir == 'z': dir_num = 2 color = 'g' if subs is None: subs = {} for sym in slope[dir_num].atoms(Symbol): if sym != self.variable and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(slope[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Slope along %c direction'%dir, xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{\theta(%c)}$'%dir, line_color=color) def plot_slope(self, dir="all", subs=None): """ Returns a plot for Slope along all three directions present in the Beam object. Parameters ========== dir : string (default : "all") Direction along which Slope plot is required. If no direction is specified, all plots are displayed. subs : dictionary Python dictionary containing Symbols as keys and their corresponding values. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, 40, 21, 100, 25, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.solve_slope_deflection() >>> b.plot_slope() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: 0 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: -x**3/1600 + 3*x**2/160 - x/8 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: x**4/8000 - 19*x**2/172 + 52*x/43 for x over (0.0, 20.0) """ dir = dir.lower() # For Slope along x direction if dir == "x": Px = self._plot_slope('x', subs) return Px.show() # For Slope along y direction elif dir == "y": Py = self._plot_slope('y', subs) return Py.show() # For Slope along z direction elif dir == "z": Pz = self._plot_slope('z', subs) return Pz.show() # For Slope along all direction else: Px = self._plot_slope('x', subs) Py = self._plot_slope('y', subs) Pz = self._plot_slope('z', subs) return PlotGrid(3, 1, Px, Py, Pz) def _plot_deflection(self, dir, subs=None): deflection = self.deflection() if dir == 'x': dir_num = 0 color = 'm' elif dir == 'y': dir_num = 1 color = 'r' elif dir == 'z': dir_num = 2 color = 'c' if subs is None: subs = {} for sym in deflection[dir_num].atoms(Symbol): if sym != self.variable and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(deflection[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Deflection along %c direction'%dir, xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{\delta(%c)}$'%dir, line_color=color) def plot_deflection(self, dir="all", subs=None): """ Returns a plot for Deflection along all three directions present in the Beam object. Parameters ========== dir : string (default : "all") Direction along which deflection plot is required. If no direction is specified, all plots are displayed. subs : dictionary Python dictionary containing Symbols as keys and their corresponding values. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, 40, 21, 100, 25, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.solve_slope_deflection() >>> b.plot_deflection() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: 0 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: x**5/40000 - 4013*x**3/90300 + 26*x**2/43 + 1520*x/903 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: x**4/6400 - x**3/160 + 27*x**2/560 + 2*x/7 for x over (0.0, 20.0) """ dir = dir.lower() # For deflection along x direction if dir == "x": Px = self._plot_deflection('x', subs) return Px.show() # For deflection along y direction elif dir == "y": Py = self._plot_deflection('y', subs) return Py.show() # For deflection along z direction elif dir == "z": Pz = self._plot_deflection('z', subs) return Pz.show() # For deflection along all direction else: Px = self._plot_deflection('x', subs) Py = self._plot_deflection('y', subs) Pz = self._plot_deflection('z', subs) return PlotGrid(3, 1, Px, Py, Pz) def plot_loading_results(self, dir='x', subs=None): """ Returns a subplot of Shear Force, Bending Moment, Slope and Deflection of the Beam object along the direction specified. Parameters ========== dir : string (default : "x") Direction along which plots are required. If no direction is specified, plots along x-axis are displayed. subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, E, G, I, A, x) >>> subs = {E:40, G:21, I:100, A:25} >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.solve_slope_deflection() >>> b.plot_loading_results('y',subs) PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: -6*x**2 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: -15*x**2/2 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: -x**3/1600 + 3*x**2/160 - x/8 for x over (0.0, 20.0) Plot[3]:Plot object containing: [0]: cartesian line: x**5/40000 - 4013*x**3/90300 + 26*x**2/43 + 1520*x/903 for x over (0.0, 20.0) """ dir = dir.lower() if subs is None: subs = {} ax1 = self._plot_shear_force(dir, subs) ax2 = self._plot_bending_moment(dir, subs) ax3 = self._plot_slope(dir, subs) ax4 = self._plot_deflection(dir, subs) return PlotGrid(4, 1, ax1, ax2, ax3, ax4) def _plot_shear_stress(self, dir, subs=None): shear_stress = self.shear_stress() if dir == 'x': dir_num = 0 color = 'r' elif dir == 'y': dir_num = 1 color = 'g' elif dir == 'z': dir_num = 2 color = 'b' if subs is None: subs = {} for sym in shear_stress[dir_num].atoms(Symbol): if sym != self.variable and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(shear_stress[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Shear stress along %c direction'%dir, xlabel=r'$\mathrm{X}$', ylabel=r'$\tau(%c)$'%dir, line_color=color) def plot_shear_stress(self, dir="all", subs=None): """ Returns a plot for Shear Stress along all three directions present in the Beam object. Parameters ========== dir : string (default : "all") Direction along which shear stress plot is required. If no direction is specified, all plots are displayed. subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 20 meters and area of cross section 2 square meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, E, G, I, 2, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.plot_shear_stress() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: 0 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: -3*x**2 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: -15*x/2 for x over (0.0, 20.0) """ dir = dir.lower() # For shear stress along x direction if dir == "x": Px = self._plot_shear_stress('x', subs) return Px.show() # For shear stress along y direction elif dir == "y": Py = self._plot_shear_stress('y', subs) return Py.show() # For shear stress along z direction elif dir == "z": Pz = self._plot_shear_stress('z', subs) return Pz.show() # For shear stress along all direction else: Px = self._plot_shear_stress('x', subs) Py = self._plot_shear_stress('y', subs) Pz = self._plot_shear_stress('z', subs) return PlotGrid(3, 1, Px, Py, Pz) def _max_shear_force(self, dir): """ Helper function for max_shear_force(). """ dir = dir.lower() if dir == 'x': dir_num = 0 elif dir == 'y': dir_num = 1 elif dir == 'z': dir_num = 2 if not self.shear_force()[dir_num]: return (0,0) # To restrict the range within length of the Beam load_curve = Piecewise((float("nan"), self.variable<=0), (self._load_vector[dir_num], self.variable<self.length), (float("nan"), True)) points = solve(load_curve.rewrite(Piecewise), self.variable, domain=S.Reals) points.append(0) points.append(self.length) shear_curve = self.shear_force()[dir_num] shear_values = [shear_curve.subs(self.variable, x) for x in points] shear_values = list(map(abs, shear_values)) max_shear = max(shear_values) return (points[shear_values.index(max_shear)], max_shear) def max_shear_force(self): """ Returns point of max shear force and its corresponding shear value along all directions in a Beam object as a list. solve_for_reaction_loads() must be called before using this function. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, 40, 21, 100, 25, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.max_shear_force() [(0, 0), (20, 2400), (20, 300)] """ max_shear = [] max_shear.append(self._max_shear_force('x')) max_shear.append(self._max_shear_force('y')) max_shear.append(self._max_shear_force('z')) return max_shear def _max_bending_moment(self, dir): """ Helper function for max_bending_moment(). """ dir = dir.lower() if dir == 'x': dir_num = 0 elif dir == 'y': dir_num = 1 elif dir == 'z': dir_num = 2 if not self.bending_moment()[dir_num]: return (0,0) # To restrict the range within length of the Beam shear_curve = Piecewise((float("nan"), self.variable<=0), (self.shear_force()[dir_num], self.variable<self.length), (float("nan"), True)) points = solve(shear_curve.rewrite(Piecewise), self.variable, domain=S.Reals) points.append(0) points.append(self.length) bending_moment_curve = self.bending_moment()[dir_num] bending_moments = [bending_moment_curve.subs(self.variable, x) for x in points] bending_moments = list(map(abs, bending_moments)) max_bending_moment = max(bending_moments) return (points[bending_moments.index(max_bending_moment)], max_bending_moment) def max_bending_moment(self): """ Returns point of max bending moment and its corresponding bending moment value along all directions in a Beam object as a list. solve_for_reaction_loads() must be called before using this function. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, 40, 21, 100, 25, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.max_bending_moment() [(0, 0), (20, 3000), (20, 16000)] """ max_bmoment = [] max_bmoment.append(self._max_bending_moment('x')) max_bmoment.append(self._max_bending_moment('y')) max_bmoment.append(self._max_bending_moment('z')) return max_bmoment max_bmoment = max_bending_moment def _max_deflection(self, dir): """ Helper function for max_Deflection() """ dir = dir.lower() if dir == 'x': dir_num = 0 elif dir == 'y': dir_num = 1 elif dir == 'z': dir_num = 2 if not self.deflection()[dir_num]: return (0,0) # To restrict the range within length of the Beam slope_curve = Piecewise((float("nan"), self.variable<=0), (self.slope()[dir_num], self.variable<self.length), (float("nan"), True)) points = solve(slope_curve.rewrite(Piecewise), self.variable, domain=S.Reals) points.append(0) points.append(self._length) deflection_curve = self.deflection()[dir_num] deflections = [deflection_curve.subs(self.variable, x) for x in points] deflections = list(map(abs, deflections)) max_def = max(deflections) return (points[deflections.index(max_def)], max_def) def max_deflection(self): """ Returns point of max deflection and its corresponding deflection value along all directions in a Beam object as a list. solve_for_reaction_loads() and solve_slope_deflection() must be called before using this function. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, 40, 21, 100, 25, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.solve_slope_deflection() >>> b.max_deflection() [(0, 0), (10, 495/14), (-10 + 10*sqrt(10793)/43, (10 - 10*sqrt(10793)/43)**3/160 - 20/7 + (10 - 10*sqrt(10793)/43)**4/6400 + 20*sqrt(10793)/301 + 27*(10 - 10*sqrt(10793)/43)**2/560)] """ max_def = [] max_def.append(self._max_deflection('x')) max_def.append(self._max_deflection('y')) max_def.append(self._max_deflection('z')) return max_def
aa7aebfca6af6ef2e1da7f1986723ad0a22b6c79f42b094120306d1a6b258373
""" This module can be used to solve problems related to 2D Trusses. """ from cmath import inf from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy import Matrix, pi from sympy.functions.elementary.miscellaneous import sqrt from sympy.matrices.dense import zeros from sympy import sin, cos class Truss: """ A Truss is an assembly of members such as beams, connected by nodes, that create a rigid structure. In engineering, a truss is a structure that consists of two-force members only. Trusses are extremely important in engineering applications and can be seen in numerous real-world applications like bridges. Examples ======== There is a Truss consisting of four nodes and five members connecting the nodes. A force P acts downward on the node D and there also exist pinned and roller joints on the nodes A and B respectively. .. image:: truss_example.png >>> from sympy.physics.continuum_mechanics.truss import Truss >>> t = Truss() >>> t.add_node("node_1", 0, 0) >>> t.add_node("node_2", 6, 0) >>> t.add_node("node_3", 2, 2) >>> t.add_node("node_4", 2, 0) >>> t.add_member("member_1", "node_1", "node_4") >>> t.add_member("member_2", "node_2", "node_4") >>> t.add_member("member_3", "node_1", "node_3") >>> t.add_member("member_4", "node_2", "node_3") >>> t.add_member("member_5", "node_3", "node_4") >>> t.apply_load("node_4", magnitude=10, direction=270) >>> t.apply_support("node_1", type="fixed") >>> t.apply_support("node_2", type="roller") """ def __init__(self): """ Initializes the class """ self._nodes = [] self._members = {} self._loads = {} self._supports = {} self._node_labels = [] self._node_positions = [] self._node_position_x = [] self._node_position_y = [] self._nodes_occupied = {} self._reaction_loads = {} self._internal_forces = {} self._node_coordinates = {} @property def nodes(self): """ Returns the nodes of the truss along with their positions. """ return self._nodes @property def node_labels(self): """ Returns the node labels of the truss. """ return self._node_labels @property def node_positions(self): """ Returns the positions of the nodes of the truss. """ return self._node_positions @property def members(self): """ Returns the members of the truss along with the start and end points. """ return self._members @property def member_labels(self): """ Returns the members of the truss along with the start and end points. """ return self._member_labels @property def supports(self): """ Returns the nodes with provided supports along with the kind of support provided i.e. pinned or roller. """ return self._supports @property def loads(self): """ Returns the loads acting on the truss. """ return self._loads @property def reaction_loads(self): """ Returns the reaction forces for all supports which are all initialized to 0. """ return self._reaction_loads @property def internal_forces(self): """ Returns the internal forces for all members which are all initialized to 0. """ return self._internal_forces def add_node(self, label, x, y): """ This method adds a node to the truss along with its name/label and its location. Parameters ========== label: String or a Symbol The label for a node. It is the only way to identify a particular node. x: Sympifyable The x-coordinate of the position of the node. y: Sympifyable The y-coordinate of the position of the node. Examples ======== >>> from sympy.physics.continuum_mechanics.truss import Truss >>> t = Truss() >>> t.add_node('A', 0, 0) >>> t.nodes [('A', 0, 0)] >>> t.add_node('B', 3, 0) >>> t.nodes [('A', 0, 0), ('B', 3, 0)] """ x = sympify(x) y = sympify(y) if label in self._node_labels: raise ValueError("Node needs to have a unique label") elif x in self._node_position_x and y in self._node_position_y and self._node_position_x.index(x)==self._node_position_y.index(y): raise ValueError("A node already exists at the given position") else : self._nodes.append((label, x, y)) self._node_labels.append(label) self._node_positions.append((x, y)) self._node_position_x.append(x) self._node_position_y.append(y) self._node_coordinates[label] = [x, y] def remove_node(self, label): """ This method removes a node from the truss. Parameters ========== label: String or Symbol The label of the node to be removed. Examples ======== >>> from sympy.physics.continuum_mechanics.truss import Truss >>> t = Truss() >>> t.add_node('A', 0, 0) >>> t.nodes [('A', 0, 0)] >>> t.add_node('B', 3, 0) >>> t.nodes [('A', 0, 0), ('B', 3, 0)] >>> t.remove_node('A') >>> t.nodes [('B', 3, 0)] """ for i in range(len(self.nodes)): if self._node_labels[i] == label: x = self._node_position_x[i] y = self._node_position_y[i] if label not in self._node_labels: raise ValueError("No such node exists in the truss") else: members_duplicate = self._members.copy() for member in members_duplicate: if label == self._members[member][0] or label == self._members[member][1]: raise ValueError("The node given has members already attached to it") self._nodes.remove((label, x, y)) self._node_labels.remove(label) self._node_positions.remove((x, y)) self._node_position_x.remove(x) self._node_position_y.remove(y) if label in list(self._loads): self._loads.pop(label) if label in list(self._supports): self._supports.pop(label) self._node_coordinates.pop(label) def add_member(self, label, start, end): """ This method adds a member between any two nodes in the given truss. Parameters ========== label: String or Symbol The label for a member. It is the only way to identify a particular member. start: String or Symbol The label of the starting point/node of the member. end: String or Symbol The label of the ending point/node of the member. Examples ======== >>> from sympy.physics.continuum_mechanics.truss import Truss >>> t = Truss() >>> t.add_node('A', 0, 0) >>> t.add_node('B', 3, 0) >>> t.add_node('C', 2, 2) >>> t.add_member('AB', 'A', 'B') >>> t.members {'AB': ['A', 'B']} """ if start not in self._node_labels or end not in self._node_labels or start==end: raise ValueError("The start and end points of the member must be unique nodes") elif label in list(self._members): raise ValueError("A member with the same label already exists for the truss") elif self._nodes_occupied.get(tuple([start, end])): raise ValueError("A member already exists between the two nodes") else: self._members[label] = [start, end] self._nodes_occupied[start, end] = True self._nodes_occupied[end, start] = True self._internal_forces[label] = 0 def remove_member(self, label): """ This method removes a member from the given truss. Parameters ========== label: String or Symbol The label for the member to be removed. Examples ======== >>> from sympy.physics.continuum_mechanics.truss import Truss >>> t = Truss() >>> t.add_node('A', 0, 0) >>> t.add_node('B', 3, 0) >>> t.add_node('C', 2, 2) >>> t.add_member('AB', 'A', 'B') >>> t.add_member('AC', 'A', 'C') >>> t.add_member('BC', 'B', 'C') >>> t.members {'AB': ['A', 'B'], 'AC': ['A', 'C'], 'BC': ['B', 'C']} >>> t.remove_member('AC') >>> t.members {'AB': ['A', 'B'], 'BC': ['B', 'C']} """ if label not in list(self._members): raise ValueError("No such member exists in the Truss") else: self._nodes_occupied.pop(tuple([self._members[label][0], self._members[label][1]])) self._nodes_occupied.pop(tuple([self._members[label][1], self._members[label][0]])) self._members.pop(label) self._internal_forces.pop(label) def change_node_label(self, label, new_label): """ This method changes the label of a node. Parameters ========== label: String or Symbol The label of the node for which the label has to be changed. new_label: String or Symbol The new label of the node. Examples ======== >>> from sympy.physics.continuum_mechanics.truss import Truss >>> t = Truss() >>> t.add_node('A', 0, 0) >>> t.add_node('B', 3, 0) >>> t.nodes [('A', 0, 0), ('B', 3, 0)] >>> t.change_node_label('A', 'C') >>> t.nodes [('C', 0, 0), ('B', 3, 0)] """ if label not in self._node_labels: raise ValueError("No such node exists for the Truss") elif new_label in self._node_labels: raise ValueError("A node with the given label already exists") else: for node in self._nodes: if node[0] == label: self._nodes[self._nodes.index((label, node[1], node[2]))] = (new_label, node[1], node[2]) self._node_labels[self._node_labels.index(node[0])] = new_label self._node_coordinates[new_label] = self._node_coordinates[label] self._node_coordinates.pop(label) if node[0] in list(self._supports): self._supports[new_label] = self._supports[node[0]] self._supports.pop(node[0]) if new_label in list(self._supports): if self._supports[new_label] == 'pinned': if 'R_'+str(label)+'_x' in list(self._reaction_loads) and 'R_'+str(label)+'_y' in list(self._reaction_loads): self._reaction_loads['R_'+str(new_label)+'_x'] = self._reaction_loads['R_'+str(label)+'_x'] self._reaction_loads['R_'+str(new_label)+'_y'] = self._reaction_loads['R_'+str(label)+'_y'] self._reaction_loads.pop('R_'+str(label)+'_x') self._reaction_loads.pop('R_'+str(label)+'_y') self._loads[new_label] = self._loads[label] for load in self._loads[new_label]: if load[1] == 90: load[0] -= Symbol('R_'+str(label)+'_y') if load[0] == 0: self._loads[label].remove(load) break for load in self._loads[new_label]: if load[1] == 0: load[0] -= Symbol('R_'+str(label)+'_x') if load[0] == 0: self._loads[label].remove(load) break self.apply_load(new_label, Symbol('R_'+str(new_label)+'_x'), 0) self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90) self._loads.pop(label) elif self._supports[new_label] == 'roller': self._loads[new_label] = self._loads[label] for load in self._loads[label]: if load[1] == 90: load[0] -= Symbol('R_'+str(label)+'_y') if load[0] == 0: self._loads[label].remove(load) break self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90) self._loads.pop(label) else: if label in list(self._loads): self._loads[new_label] = self._loads[label] self._loads.pop(label) for member in list(self._members): if self._members[member][0] == node[0]: self._members[member][0] = new_label self._nodes_occupied[(new_label, self._members[member][1])] = True self._nodes_occupied[(self._members[member][1], new_label)] = True self._nodes_occupied.pop(tuple([label, self._members[member][1]])) self._nodes_occupied.pop(tuple([self._members[member][1], label])) elif self._members[member][1] == node[0]: self._members[member][1] = new_label self._nodes_occupied[(self._members[member][0], new_label)] = True self._nodes_occupied[(new_label, self._members[member][0])] = True self._nodes_occupied.pop(tuple([self._members[member][0], label])) self._nodes_occupied.pop(tuple([label, self._members[member][0]])) def change_member_label(self, label, new_label): """ This method changes the label of a member. Parameters ========== label: String or Symbol The label of the member for which the label has to be changed. new_label: String or Symbol The new label of the member. Examples ======== >>> from sympy.physics.continuum_mechanics.truss import Truss >>> t = Truss() >>> t.add_node('A', 0, 0) >>> t.add_node('B', 3, 0) >>> t.nodes [('A', 0, 0), ('B', 3, 0)] >>> t.change_node_label('A', 'C') >>> t.nodes [('C', 0, 0), ('B', 3, 0)] >>> t.add_member('BC', 'B', 'C') >>> t.members {'BC': ['B', 'C']} >>> t.change_member_label('BC', 'BC_new') >>> t.members {'BC_new': ['B', 'C']} """ if label not in list(self._members): raise ValueError("No such member exists for the Truss") else: members_duplicate = list(self._members).copy() for member in members_duplicate: if member == label: self._members[new_label] = [self._members[member][0], self._members[member][1]] self._members.pop(label) self._internal_forces[new_label] = self._internal_forces[label] self._internal_forces.pop(label) def apply_load(self, location, magnitude, direction): """ This method applies an external load at a particular node Parameters ========== location: String or Symbol Label of the Node at which load is applied. magnitude: Sympifyable Magnitude of the load applied. It must always be positive and any changes in the direction of the load are not reflected here. direction: Sympifyable The angle, in degrees, that the load vector makes with the horizontal in the counter-clockwise direction. It takes the values 0 to 360, inclusive. Examples ======== >>> from sympy.physics.continuum_mechanics.truss import Truss >>> from sympy import symbols >>> t = Truss() >>> t.add_node('A', 0, 0) >>> t.add_node('B', 3, 0) >>> P = symbols('P') >>> t.apply_load('A', P, 90) >>> t.apply_load('A', P/2, 45) >>> t.apply_load('A', P/4, 90) >>> t.loads {'A': [[P, 90], [P/2, 45], [P/4, 90]]} """ magnitude = sympify(magnitude) direction = sympify(direction) if location not in self.node_labels: raise ValueError("Load must be applied at a known node") else: if location in list(self._loads): self._loads[location].append([magnitude, direction]) else: self._loads[location] = [[magnitude, direction]] def remove_load(self, location, magnitude, direction): """ This method removes an already present external load at a particular node Parameters ========== location: String or Symbol Label of the Node at which load is applied and is to be removed. magnitude: Sympifyable Magnitude of the load applied. direction: Sympifyable The angle, in degrees, that the load vector makes with the horizontal in the counter-clockwise direction. It takes the values 0 to 360, inclusive. Examples ======== >>> from sympy.physics.continuum_mechanics.truss import Truss >>> from sympy import symbols >>> t = Truss() >>> t.add_node('A', 0, 0) >>> t.add_node('B', 3, 0) >>> P = symbols('P') >>> t.apply_load('A', P, 90) >>> t.apply_load('A', P/2, 45) >>> t.apply_load('A', P/4, 90) >>> t.loads {'A': [[P, 90], [P/2, 45], [P/4, 90]]} >>> t.remove_load('A', P/4, 90) >>> t.loads {'A': [[P, 90], [P/2, 45]]} """ magnitude = sympify(magnitude) direction = sympify(direction) if location not in self.node_labels: raise ValueError("Load must be removed from a known node") else: if [magnitude, direction] not in self._loads[location]: raise ValueError("No load of this magnitude and direction has been applied at this node") else: self._loads[location].remove([magnitude, direction]) if self._loads[location] == []: self._loads.pop(location) def apply_support(self, location, type): """ This method adds a pinned or roller support at a particular node Parameters ========== location: String or Symbol Label of the Node at which support is added. type: String Type of the support being provided at the node. Examples ======== >>> from sympy.physics.continuum_mechanics.truss import Truss >>> t = Truss() >>> t.add_node('A', 0, 0) >>> t.add_node('B', 3, 0) >>> t.apply_support('A', 'pinned') >>> t.supports {'A': 'pinned'} """ if location not in self._node_labels: raise ValueError("Support must be added on a known node") else: if location not in list(self._supports): if type == 'pinned': self.apply_load(location, Symbol('R_'+str(location)+'_x'), 0) self.apply_load(location, Symbol('R_'+str(location)+'_y'), 90) elif type == 'roller': self.apply_load(location, Symbol('R_'+str(location)+'_y'), 90) elif self._supports[location] == 'pinned': if type == 'roller': self.remove_load(location, Symbol('R_'+str(location)+'_x'), 0) elif self._supports[location] == 'roller': if type == 'pinned': self.apply_load(location, Symbol('R_'+str(location)+'_x'), 0) self._supports[location] = type def remove_support(self, location): """ This method removes support from a particular node Parameters ========== location: String or Symbol Label of the Node at which support is to be removed. Examples ======== >>> from sympy.physics.continuum_mechanics.truss import Truss >>> t = Truss() >>> t.add_node('A', 0, 0) >>> t.add_node('B', 3, 0) >>> t.apply_support('A', 'pinned') >>> t.supports {'A': 'pinned'} >>> t.remove_support('A') >>> t.supports {} """ if location not in self._node_labels: raise ValueError("No such node exists in the Truss") elif location not in list(self._supports): raise ValueError("No support has been added to the given node") else: if self._supports[location] == 'pinned': self.remove_load(location, Symbol('R_'+str(location)+'_x'), 0) self.remove_load(location, Symbol('R_'+str(location)+'_y'), 90) elif self._supports[location] == 'roller': self.remove_load(location, Symbol('R_'+str(location)+'_y'), 90) self._supports.pop(location) def solve(self): """ This method solves for all reaction forces of all supports and all internal forces of all the members in the truss, provided the Truss is solvable. A Truss is solvable if the following condition is met, 2n >= r + m Where n is the number of nodes, r is the number of reaction forces, where each pinned support has 2 reaction forces and each roller has 1, and m is the number of members. The given condition is derived from the fact that a system of equations is solvable only when the number of variables is lesser than or equal to the number of equations. Equilibrium Equations in x and y directions give two equations per node giving 2n number equations. However, the truss needs to be stable as well and may be unstable if 2n > r + m. The number of variables is simply the sum of the number of reaction forces and member forces. .. note:: The sign convention for the internal forces present in a member revolves around whether each force is compressive or tensile. While forming equations for each node, internal force due to a member on the node is assumed to be away from the node i.e. each force is assumed to be compressive by default. Hence, a positive value for an internal force implies the presence of compressive force in the member and a negative value implies a tensile force. Examples ======== >>> from sympy.physics.continuum_mechanics.truss import Truss >>> t = Truss() >>> t.add_node("node_1", 0, 0) >>> t.add_node("node_2", 6, 0) >>> t.add_node("node_3", 2, 2) >>> t.add_node("node_4", 2, 0) >>> t.add_member("member_1", "node_1", "node_4") >>> t.add_member("member_2", "node_2", "node_4") >>> t.add_member("member_3", "node_1", "node_3") >>> t.add_member("member_4", "node_2", "node_3") >>> t.add_member("member_5", "node_3", "node_4") >>> t.apply_load("node_4", magnitude=10, direction=270) >>> t.apply_support("node_1", type="pinned") >>> t.apply_support("node_2", type="roller") >>> t.solve() >>> t.reaction_loads {'R_node_1_x': 0, 'R_node_1_y': 20/3, 'R_node_2_y': 10/3} >>> t.internal_forces {'member_1': 20/3, 'member_2': 20/3, 'member_3': -20*sqrt(2)/3, 'member_4': -10*sqrt(5)/3, 'member_5': 10} """ count_reaction_loads = 0 for node in self._nodes: if node[0] in list(self._supports): if self._supports[node[0]]=='pinned': count_reaction_loads += 2 elif self._supports[node[0]]=='roller': count_reaction_loads += 1 if 2*len(self._nodes) != len(self._members) + count_reaction_loads: raise ValueError("The given truss cannot be solved") coefficients_matrix = [[0 for i in range(2*len(self._nodes))] for j in range(2*len(self._nodes))] load_matrix = zeros(2*len(self.nodes), 1) load_matrix_row = 0 for node in self._nodes: if node[0] in list(self._loads): for load in self._loads[node[0]]: if load[0]!=Symbol('R_'+str(node[0])+'_x') and load[0]!=Symbol('R_'+str(node[0])+'_y'): load_matrix[load_matrix_row] -= load[0]*cos(pi*load[1]/180) load_matrix[load_matrix_row + 1] -= load[0]*sin(pi*load[1]/180) load_matrix_row += 2 cols = 0 row = 0 for node in self._nodes: if node[0] in list(self._supports): if self._supports[node[0]]=='pinned': coefficients_matrix[row][cols] += 1 coefficients_matrix[row+1][cols+1] += 1 cols += 2 elif self._supports[node[0]]=='roller': coefficients_matrix[row+1][cols] += 1 cols += 1 row += 2 for member in list(self._members): start = self._members[member][0] end = self._members[member][1] length = sqrt((self._node_coordinates[start][0]-self._node_coordinates[end][0])**2 + (self._node_coordinates[start][1]-self._node_coordinates[end][1])**2) start_index = self._node_labels.index(start) end_index = self._node_labels.index(end) horizontal_component_start = (self._node_coordinates[end][0]-self._node_coordinates[start][0])/length vertical_component_start = (self._node_coordinates[end][1]-self._node_coordinates[start][1])/length horizontal_component_end = (self._node_coordinates[start][0]-self._node_coordinates[end][0])/length vertical_component_end = (self._node_coordinates[start][1]-self._node_coordinates[end][1])/length coefficients_matrix[start_index*2][cols] += horizontal_component_start coefficients_matrix[start_index*2+1][cols] += vertical_component_start coefficients_matrix[end_index*2][cols] += horizontal_component_end coefficients_matrix[end_index*2+1][cols] += vertical_component_end cols += 1 forces_matrix = (Matrix(coefficients_matrix)**-1)*load_matrix self._reaction_loads = {} i = 0 min_load = inf for node in self._nodes: if node[0] in list(self._loads): for load in self._loads[node[0]]: if type(load[0]) not in [Symbol, Mul, Add]: min_load = min(min_load, load[0]) for j in range(len(forces_matrix)): if type(forces_matrix[j]) not in [Symbol, Mul, Add]: if abs(forces_matrix[j]/min_load) <1E-10: forces_matrix[j] = 0 for node in self._nodes: if node[0] in list(self._supports): if self._supports[node[0]]=='pinned': self._reaction_loads['R_'+str(node[0])+'_x'] = forces_matrix[i] self._reaction_loads['R_'+str(node[0])+'_y'] = forces_matrix[i+1] i += 2 elif self._supports[node[0]]=='roller': self._reaction_loads['R_'+str(node[0])+'_y'] = forces_matrix[i] i += 1 for member in list(self._members): self._internal_forces[member] = forces_matrix[i] i += 1 return
e6458800d927dc6c5bc204c6da3543435a917a3222ed9af03847553fcfeb14c4
from sympy.core.function import expand_mul from sympy.core.numbers import pi from sympy.core.singleton import S from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.core.backend import Matrix, _simplify_matrix from sympy.core.symbol import symbols from sympy.physics.mechanics import (dynamicsymbols, Body, PinJoint, PrismaticJoint, CylindricalJoint) from sympy.physics.mechanics.joint import Joint from sympy.physics.vector import Vector, ReferenceFrame, Point from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy Vector.simp = True t = dynamicsymbols._t # type: ignore def _generate_body(interframe=False): N = ReferenceFrame('N') A = ReferenceFrame('A') P = Body('P', frame=N) C = Body('C', frame=A) if interframe: Pint, Cint = ReferenceFrame('P_int'), ReferenceFrame('C_int') Pint.orient_axis(N, N.x, pi) Cint.orient_axis(A, A.y, -pi / 2) return N, A, P, C, Pint, Cint return N, A, P, C def test_Joint(): parent = Body('parent') child = Body('child') raises(TypeError, lambda: Joint('J', parent, child)) def test_coordinate_generation(): q, u, qj, uj = dynamicsymbols('q u q_J u_J') q0j, q1j, q2j, q3j, u0j, u1j, u2j, u3j = dynamicsymbols('q0:4_J u0:4_J') q0, q1, q2, q3, u0, u1, u2, u3 = dynamicsymbols('q0:4 u0:4') _, _, P, C = _generate_body() # Using PinJoint to access Joint's coordinate generation method J = PinJoint('J', P, C) # Test single given assert J._fill_coordinate_list(q, 1) == Matrix([q]) assert J._fill_coordinate_list([u], 1) == Matrix([u]) assert J._fill_coordinate_list([u], 1, offset=2) == Matrix([u]) # Test None assert J._fill_coordinate_list(None, 1) == Matrix([qj]) assert J._fill_coordinate_list([None], 1) == Matrix([qj]) assert J._fill_coordinate_list([q0, None], 3) == Matrix([q0, q1j, q2j]) # Test autofill assert J._fill_coordinate_list(None, 3) == Matrix([q0j, q1j, q2j]) assert J._fill_coordinate_list([], 3) == Matrix([q0j, q1j, q2j]) # Test offset assert J._fill_coordinate_list([], 3, offset=1) == Matrix([q1j, q2j, q3j]) assert J._fill_coordinate_list(q1, 3, offset=1) == Matrix([q1, q2j, q3j]) assert J._fill_coordinate_list([q1, None, q3], 3, offset=1) == Matrix( [q1, q2j, q3]) assert J._fill_coordinate_list(None, 2, offset=2) == Matrix([q2j, q3j]) # Test label assert J._fill_coordinate_list(None, 1, 'u') == Matrix([uj]) assert J._fill_coordinate_list([], 3, 'u') == Matrix([u0j, u1j, u2j]) assert J._fill_coordinate_list([u0], 3, 'u', 1) == Matrix([u0, u2j, u3j]) # Test single numbering assert J._fill_coordinate_list(None, 1, number_single=True) == Matrix([q0j]) assert J._fill_coordinate_list([], 1, 'u', 2, True) == Matrix([u2j]) assert J._fill_coordinate_list([], 3, 'q') == Matrix([q0j, q1j, q2j]) # Test too many coordinates supplied raises(ValueError, lambda: J._fill_coordinate_list([q0, q1], 1)) raises(ValueError, lambda: J._fill_coordinate_list([u0, u1, None], 2, 'u')) # Test incorrect coordinate type raises(TypeError, lambda: J._fill_coordinate_list([q0, symbols('q1')], 2)) raises(TypeError, lambda: J._fill_coordinate_list([q0 + q1, q1], 2)) def test_pin_joint(): P = Body('P') C = Body('C') l, m = symbols('l m') q, u = dynamicsymbols('q_J, u_J') Pj = PinJoint('J', P, C) assert Pj.name == 'J' assert Pj.parent == P assert Pj.child == C assert Pj.coordinates == Matrix([q]) assert Pj.speeds == Matrix([u]) assert Pj.kdes == Matrix([u - q.diff(t)]) assert Pj.joint_axis == P.frame.x assert Pj.child_point.pos_from(C.masscenter) == Vector(0) assert Pj.parent_point.pos_from(P.masscenter) == Vector(0) assert Pj.parent_point.pos_from(Pj._child_point) == Vector(0) assert C.masscenter.pos_from(P.masscenter) == Vector(0) assert Pj.parent_interframe == P.frame assert Pj.child_interframe == C.frame assert Pj.__str__() == 'PinJoint: J parent: P child: C' P1 = Body('P1') C1 = Body('C1') Pint = ReferenceFrame('P_int') Pint.orient_axis(P1.frame, P1.y, pi / 2) J1 = PinJoint('J1', P1, C1, parent_point=l*P1.frame.x, child_point=m*C1.frame.y, joint_axis=P1.frame.z, parent_interframe=Pint) assert J1._joint_axis == P1.frame.z assert J1._child_point.pos_from(C1.masscenter) == m * C1.frame.y assert J1._parent_point.pos_from(P1.masscenter) == l * P1.frame.x assert J1._parent_point.pos_from(J1._child_point) == Vector(0) assert (P1.masscenter.pos_from(C1.masscenter) == -l*P1.frame.x + m*C1.frame.y) assert J1.parent_interframe == Pint assert J1.child_interframe == C1.frame q, u = dynamicsymbols('q, u') N, A, P, C, Pint, Cint = _generate_body(True) parent_point = P.masscenter.locatenew('parent_point', N.x + N.y) child_point = C.masscenter.locatenew('child_point', C.y + C.z) J = PinJoint('J', P, C, q, u, parent_point=parent_point, child_point=child_point, parent_interframe=Pint, child_interframe=Cint, joint_axis=N.z) assert J.joint_axis == N.z assert J.parent_point.vel(N) == 0 assert J.parent_point == parent_point assert J.child_point == child_point assert J.child_point.pos_from(P.masscenter) == N.x + N.y assert J.parent_point.pos_from(C.masscenter) == C.y + C.z assert C.masscenter.pos_from(P.masscenter) == N.x + N.y - C.y - C.z assert C.masscenter.vel(N).express(N) == (u * sin(q) - u * cos(q)) * N.x + ( -u * sin(q) - u * cos(q)) * N.y assert J.parent_interframe == Pint assert J.child_interframe == Cint def test_pin_joint_double_pendulum(): q1, q2 = dynamicsymbols('q1 q2') u1, u2 = dynamicsymbols('u1 u2') m, l = symbols('m l') N = ReferenceFrame('N') A = ReferenceFrame('A') B = ReferenceFrame('B') C = Body('C', frame=N) # ceiling PartP = Body('P', frame=A, mass=m) PartR = Body('R', frame=B, mass=m) J1 = PinJoint('J1', C, PartP, speeds=u1, coordinates=q1, child_point=-l*A.x, joint_axis=C.frame.z) J2 = PinJoint('J2', PartP, PartR, speeds=u2, coordinates=q2, child_point=-l*B.x, joint_axis=PartP.frame.z) # Check orientation assert N.dcm(A) == Matrix([[cos(q1), -sin(q1), 0], [sin(q1), cos(q1), 0], [0, 0, 1]]) assert A.dcm(B) == Matrix([[cos(q2), -sin(q2), 0], [sin(q2), cos(q2), 0], [0, 0, 1]]) assert _simplify_matrix(N.dcm(B)) == Matrix([[cos(q1 + q2), -sin(q1 + q2), 0], [sin(q1 + q2), cos(q1 + q2), 0], [0, 0, 1]]) # Check Angular Velocity assert A.ang_vel_in(N) == u1 * N.z assert B.ang_vel_in(A) == u2 * A.z assert B.ang_vel_in(N) == u1 * N.z + u2 * A.z # Check kde assert J1.kdes == Matrix([u1 - q1.diff(t)]) assert J2.kdes == Matrix([u2 - q2.diff(t)]) # Check Linear Velocity assert PartP.masscenter.vel(N) == l*u1*A.y assert PartR.masscenter.vel(A) == l*u2*B.y assert PartR.masscenter.vel(N) == l*u1*A.y + l*(u1 + u2)*B.y def test_pin_joint_chaos_pendulum(): mA, mB, lA, lB, h = symbols('mA, mB, lA, lB, h') theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha') N = ReferenceFrame('N') A = ReferenceFrame('A') B = ReferenceFrame('B') lA = (lB - h / 2) / 2 lC = (lB/2 + h/4) rod = Body('rod', frame=A, mass=mA) plate = Body('plate', mass=mB, frame=B) C = Body('C', frame=N) J1 = PinJoint('J1', C, rod, coordinates=theta, speeds=omega, child_point=lA*A.z, joint_axis=N.y) J2 = PinJoint('J2', rod, plate, coordinates=phi, speeds=alpha, parent_point=lC*A.z, joint_axis=A.z) # Check orientation assert A.dcm(N) == Matrix([[cos(theta), 0, -sin(theta)], [0, 1, 0], [sin(theta), 0, cos(theta)]]) assert A.dcm(B) == Matrix([[cos(phi), -sin(phi), 0], [sin(phi), cos(phi), 0], [0, 0, 1]]) assert B.dcm(N) == Matrix([ [cos(phi)*cos(theta), sin(phi), -sin(theta)*cos(phi)], [-sin(phi)*cos(theta), cos(phi), sin(phi)*sin(theta)], [sin(theta), 0, cos(theta)]]) # Check Angular Velocity assert A.ang_vel_in(N) == omega*N.y assert A.ang_vel_in(B) == -alpha*A.z assert N.ang_vel_in(B) == -omega*N.y - alpha*A.z # Check kde assert J1.kdes == Matrix([omega - theta.diff(t)]) assert J2.kdes == Matrix([alpha - phi.diff(t)]) # Check pos of masscenters assert C.masscenter.pos_from(rod.masscenter) == lA*A.z assert rod.masscenter.pos_from(plate.masscenter) == - lC * A.z # Check Linear Velocities assert rod.masscenter.vel(N) == (h/4 - lB/2)*omega*A.x assert plate.masscenter.vel(N) == ((h/4 - lB/2)*omega + (h/4 + lB/2)*omega)*A.x @XFAIL def test_pin_joint_interframe(): q, u = dynamicsymbols('q, u') # Check not connected N, A, P, C = _generate_body() Pint, Cint = ReferenceFrame('Pint'), ReferenceFrame('Cint') raises(ValueError, lambda: PinJoint('J', P, C, parent_interframe=Pint)) raises(ValueError, lambda: PinJoint('J', P, C, child_interframe=Cint)) # Check not fixed interframe Pint.orient_axis(N, N.z, q) Cint.orient_axis(A, A.z, q) raises(ValueError, lambda: PinJoint('J', P, C, parent_interframe=Pint)) raises(ValueError, lambda: PinJoint('J', P, C, child_interframe=Cint)) # Check only parent_interframe N, A, P, C = _generate_body() Pint = ReferenceFrame('Pint') Pint.orient_body_fixed(N, (pi / 4, pi, pi / 3), 'xyz') PinJoint('J', P, C, q, u, parent_point=N.x, child_point=-C.y, parent_interframe=Pint, joint_axis=C.x) assert _simplify_matrix(N.dcm(A)) == Matrix([ [-1 / 2, sqrt(3) * cos(q) / 2, -sqrt(3) * sin(q) / 2], [sqrt(6) / 4, sqrt(2) * (2 * sin(q) + cos(q)) / 4, sqrt(2) * (-sin(q) + 2 * cos(q)) / 4], [sqrt(6) / 4, sqrt(2) * (-2 * sin(q) + cos(q)) / 4, -sqrt(2) * (sin(q) + 2 * cos(q)) / 4]]) assert A.ang_vel_in(N) == u * Pint.x assert C.masscenter.pos_from(P.masscenter) == N.x + A.y assert C.masscenter.vel(N) == u * A.z assert P.masscenter.vel(Pint) == Vector(0) assert C.masscenter.vel(Pint) == u * A.z # Check only child_interframe N, A, P, C = _generate_body() Cint = ReferenceFrame('Cint') Cint.orient_body_fixed(A, (2 * pi / 3, -pi, pi / 2), 'xyz') PinJoint('J', P, C, q, u, parent_point=-N.z, child_point=C.x, child_interframe=Cint, joint_axis=P.x + P.z) assert _simplify_matrix(N.dcm(A)) == Matrix([ [-sqrt(2) * sin(q) / 2, -sqrt(3) * (cos(q) - 1) / 4 - cos(q) / 4 - S(1) / 4, sqrt(3) * (cos(q) + 1) / 4 - cos(q) / 4 + S(1) / 4], [cos(q), (sqrt(2) + sqrt(6)) * -sin(q) / 4, (-sqrt(2) + sqrt(6)) * sin(q) / 4], [sqrt(2) * sin(q) / 2, sqrt(3) * (cos(q) + 1) / 4 + cos(q) / 4 - S(1) / 4, sqrt(3) * (1 - cos(q)) / 4 + cos(q) / 4 + S(1) / 4]]) assert A.ang_vel_in(N) == sqrt(2) * u / 2 * N.x + sqrt(2) * u / 2 * N.z assert C.masscenter.pos_from(P.masscenter) == - N.z - A.x assert C.masscenter.vel(N).simplify() == ( -sqrt(6) - sqrt(2)) * u / 4 * A.y + ( -sqrt(2) + sqrt(6)) * u / 4 * A.z assert C.masscenter.vel(Cint) == Vector(0) # Check combination N, A, P, C = _generate_body() Pint, Cint = ReferenceFrame('Pint'), ReferenceFrame('Cint') Pint.orient_body_fixed(N, (-pi / 2, pi, pi / 2), 'xyz') Cint.orient_body_fixed(A, (2 * pi / 3, -pi, pi / 2), 'xyz') PinJoint('J', P, C, q, u, parent_point=N.x - N.y, child_point=-C.z, parent_interframe=Pint, child_interframe=Cint, joint_axis=Cint.x + Cint.z) assert _simplify_matrix(N.dcm(A)) == Matrix([ [cos(q), (sqrt(2) + sqrt(6)) * -sin(q) / 4, (-sqrt(2) + sqrt(6)) * sin(q) / 4], [-sqrt(2) * sin(q) / 2, -sqrt(3) * (cos(q) + 1) / 4 - cos(q) / 4 + S(1) / 4, sqrt(3) * (cos(q) - 1) / 4 - cos(q) / 4 - S(1) / 4], [sqrt(2) * sin(q) / 2, sqrt(3) * (cos(q) - 1) / 4 + cos(q) / 4 + S(1) / 4, -sqrt(3) * (cos(q) + 1) / 4 + cos(q) / 4 - S(1) / 4]]) assert A.ang_vel_in(N) == sqrt(2) * u / 2 * Pint.x + sqrt( 2) * u / 2 * Pint.z assert C.masscenter.pos_from(P.masscenter) == N.x - N.y + A.z N_v_C = (-sqrt(2) + sqrt(6)) * u / 4 * A.x assert C.masscenter.vel(N).simplify() == N_v_C assert C.masscenter.vel(Pint).simplify() == N_v_C assert C.masscenter.vel(Cint) == Vector(0) def test_pin_joint_joint_axis(): q, u = dynamicsymbols('q, u') # Check parent as reference N, A, P, C, Pint, Cint = _generate_body(True) pin = PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint, joint_axis=P.y) assert pin.joint_axis == P.y assert N.dcm(A) == Matrix([[sin(q), 0, cos(q)], [0, -1, 0], [cos(q), 0, -sin(q)]]) # Check parent_interframe as reference N, A, P, C, Pint, Cint = _generate_body(True) pin = PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint, joint_axis=Pint.y) assert pin.joint_axis == Pint.y assert N.dcm(A) == Matrix([[-sin(q), 0, cos(q)], [0, -1, 0], [cos(q), 0, sin(q)]]) # Check child_interframe as reference N, A, P, C, Pint, Cint = _generate_body(True) pin = PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint, joint_axis=Cint.y) assert pin.joint_axis == Cint.y assert N.dcm(A) == Matrix([[-sin(q), 0, cos(q)], [0, -1, 0], [cos(q), 0, sin(q)]]) # Check child as reference N, A, P, C, Pint, Cint = _generate_body(True) pin = PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint, joint_axis=C.y) assert pin.joint_axis == C.y assert N.dcm(A) == Matrix([[-sin(q), 0, cos(q)], [0, -1, 0], [cos(q), 0, sin(q)]]) # Check combination of joint_axis with interframes supplied as vectors (2x) N, A, P, C = _generate_body() pin = PinJoint('J', P, C, q, u, parent_interframe=N.z, child_interframe=-C.z, joint_axis=N.z) assert pin.joint_axis == N.z assert N.dcm(A) == Matrix([[-cos(q), -sin(q), 0], [-sin(q), cos(q), 0], [0, 0, -1]]) N, A, P, C = _generate_body() pin = PinJoint('J', P, C, q, u, parent_interframe=N.z, child_interframe=-C.z, joint_axis=N.x) assert pin.joint_axis == N.x assert N.dcm(A) == Matrix([[-1, 0, 0], [0, cos(q), sin(q)], [0, sin(q), -cos(q)]]) # Check time varying axis N, A, P, C, Pint, Cint = _generate_body(True) raises(ValueError, lambda: PinJoint('J', P, C, joint_axis=cos(q) * N.x + sin(q) * N.y)) # Check some invalid combinations raises(ValueError, lambda: PinJoint('J', P, C, joint_axis=P.x + C.y)) raises(ValueError, lambda: PinJoint( 'J', P, C, parent_interframe=Pint, child_interframe=Cint, joint_axis=Pint.x + C.y)) raises(ValueError, lambda: PinJoint( 'J', P, C, parent_interframe=Pint, child_interframe=Cint, joint_axis=P.x + Cint.y)) # Check valid special combination N, A, P, C, Pint, Cint = _generate_body(True) PinJoint('J', P, C, parent_interframe=Pint, child_interframe=Cint, joint_axis=Pint.x + P.y) N, A, P, C, Pint, Cint = _generate_body(True) PinJoint('J', P, C, parent_interframe=Pint, child_interframe=Cint, joint_axis=Cint.x + C.y) # Check invalid zero vector raises(Exception, lambda: PinJoint( 'J', P, C, parent_interframe=Pint, child_interframe=Cint, joint_axis=Vector(0))) raises(ValueError, lambda: PinJoint( 'J', P, C, parent_interframe=Pint, child_interframe=Cint, joint_axis=C.z - Cint.x)) def test_pin_joint_arbitrary_axis(): q, u = dynamicsymbols('q_J, u_J') # When the bodies are attached though masscenters but axes are opposite. N, A, P, C = _generate_body() PinJoint('J', P, C, child_interframe=-A.x) assert (-A.x).angle_between(N.x) == 0 assert -A.x.express(N) == N.x assert A.dcm(N) == Matrix([[-1, 0, 0], [0, -cos(q), -sin(q)], [0, -sin(q), cos(q)]]) assert A.ang_vel_in(N) == u*N.x assert A.ang_vel_in(N).magnitude() == sqrt(u**2) assert C.masscenter.pos_from(P.masscenter) == 0 assert C.masscenter.pos_from(P.masscenter).express(N).simplify() == 0 assert C.masscenter.vel(N) == 0 # When axes are different and parent joint is at masscenter but child joint # is at a unit vector from child masscenter. N, A, P, C = _generate_body() PinJoint('J', P, C, child_interframe=A.y, child_point=A.x) assert A.y.angle_between(N.x) == 0 # Axis are aligned assert A.y.express(N) == N.x assert A.dcm(N) == Matrix([[0, -cos(q), -sin(q)], [1, 0, 0], [0, -sin(q), cos(q)]]) assert A.ang_vel_in(N) == u*N.x assert A.ang_vel_in(N).express(A) == u * A.y assert A.ang_vel_in(N).magnitude() == sqrt(u**2) assert A.ang_vel_in(N).cross(A.y) == 0 assert C.masscenter.vel(N) == u*A.z assert C.masscenter.pos_from(P.masscenter) == -A.x assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() == cos(q)*N.y + sin(q)*N.z) assert C.masscenter.vel(N).angle_between(A.x) == pi/2 # Similar to previous case but wrt parent body N, A, P, C = _generate_body() PinJoint('J', P, C, parent_interframe=N.y, parent_point=N.x) assert N.y.angle_between(A.x) == 0 # Axis are aligned assert N.y.express(A) == A.x assert A.dcm(N) == Matrix([[0, 1, 0], [-cos(q), 0, sin(q)], [sin(q), 0, cos(q)]]) assert A.ang_vel_in(N) == u*N.y assert A.ang_vel_in(N).express(A) == u*A.x assert A.ang_vel_in(N).magnitude() == sqrt(u**2) angle = A.ang_vel_in(N).angle_between(A.x) assert angle.xreplace({u: 1}) == 0 assert C.masscenter.vel(N) == 0 assert C.masscenter.pos_from(P.masscenter) == N.x # Both joint pos id defined but different axes N, A, P, C = _generate_body() PinJoint('J', P, C, parent_point=N.x, child_point=A.x, child_interframe=A.x + A.y) assert expand_mul(N.x.angle_between(A.x + A.y)) == 0 # Axis are aligned assert (A.x + A.y).express(N).simplify() == sqrt(2)*N.x assert _simplify_matrix(A.dcm(N)) == Matrix([ [sqrt(2)/2, -sqrt(2)*cos(q)/2, -sqrt(2)*sin(q)/2], [sqrt(2)/2, sqrt(2)*cos(q)/2, sqrt(2)*sin(q)/2], [0, -sin(q), cos(q)]]) assert A.ang_vel_in(N) == u*N.x assert (A.ang_vel_in(N).express(A).simplify() == (u*A.x + u*A.y)/sqrt(2)) assert A.ang_vel_in(N).magnitude() == sqrt(u**2) angle = A.ang_vel_in(N).angle_between(A.x + A.y) assert angle.xreplace({u: 1}) == 0 assert C.masscenter.vel(N).simplify() == (u * A.z)/sqrt(2) assert C.masscenter.pos_from(P.masscenter) == N.x - A.x assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() == (1 - sqrt(2)/2)*N.x + sqrt(2)*cos(q)/2*N.y + sqrt(2)*sin(q)/2*N.z) assert (C.masscenter.vel(N).express(N).simplify() == -sqrt(2)*u*sin(q)/2*N.y + sqrt(2)*u*cos(q)/2*N.z) assert C.masscenter.vel(N).angle_between(A.x) == pi/2 N, A, P, C = _generate_body() PinJoint('J', P, C, parent_point=N.x, child_point=A.x, child_interframe=A.x + A.y - A.z) assert expand_mul(N.x.angle_between(A.x + A.y - A.z)) == 0 # Axis aligned assert (A.x + A.y - A.z).express(N).simplify() == sqrt(3)*N.x assert _simplify_matrix(A.dcm(N)) == Matrix([ [sqrt(3)/3, -sqrt(6)*sin(q + pi/4)/3, sqrt(6)*cos(q + pi/4)/3], [sqrt(3)/3, sqrt(6)*cos(q + pi/12)/3, sqrt(6)*sin(q + pi/12)/3], [-sqrt(3)/3, sqrt(6)*cos(q + 5*pi/12)/3, sqrt(6)*sin(q + 5*pi/12)/3]]) assert A.ang_vel_in(N) == u*N.x assert A.ang_vel_in(N).express(A).simplify() == (u*A.x + u*A.y - u*A.z)/sqrt(3) assert A.ang_vel_in(N).magnitude() == sqrt(u**2) angle = A.ang_vel_in(N).angle_between(A.x + A.y-A.z) assert angle.xreplace({u: 1}) == 0 assert C.masscenter.vel(N).simplify() == (u*A.y + u*A.z)/sqrt(3) assert C.masscenter.pos_from(P.masscenter) == N.x - A.x assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() == (1 - sqrt(3)/3)*N.x + sqrt(6)*sin(q + pi/4)/3*N.y - sqrt(6)*cos(q + pi/4)/3*N.z) assert (C.masscenter.vel(N).express(N).simplify() == sqrt(6)*u*cos(q + pi/4)/3*N.y + sqrt(6)*u*sin(q + pi/4)/3*N.z) assert C.masscenter.vel(N).angle_between(A.x) == pi/2 N, A, P, C = _generate_body() m, n = symbols('m n') PinJoint('J', P, C, parent_point=m * N.x, child_point=n * A.x, child_interframe=A.x + A.y - A.z, parent_interframe=N.x - N.y + N.z) angle = (N.x - N.y + N.z).angle_between(A.x + A.y - A.z) assert expand_mul(angle) == 0 # Axis are aligned assert ((A.x-A.y+A.z).express(N).simplify() == (-4*cos(q)/3 - S(1)/3)*N.x + (S(1)/3 - 4*sin(q + pi/6)/3)*N.y + (4*cos(q + pi/3)/3 - S(1)/3)*N.z) assert _simplify_matrix(A.dcm(N)) == Matrix([ [S(1)/3 - 2*cos(q)/3, -2*sin(q + pi/6)/3 - S(1)/3, 2*cos(q + pi/3)/3 + S(1)/3], [2*cos(q + pi/3)/3 + S(1)/3, 2*cos(q)/3 - S(1)/3, 2*sin(q + pi/6)/3 + S(1)/3], [-2*sin(q + pi/6)/3 - S(1)/3, 2*cos(q + pi/3)/3 + S(1)/3, 2*cos(q)/3 - S(1)/3]]) assert A.ang_vel_in(N) == (u*N.x - u*N.y + u*N.z)/sqrt(3) assert A.ang_vel_in(N).express(A).simplify() == (u*A.x + u*A.y - u*A.z)/sqrt(3) assert A.ang_vel_in(N).magnitude() == sqrt(u**2) angle = A.ang_vel_in(N).angle_between(A.x+A.y-A.z) assert angle.xreplace({u: 1}) == 0 assert (C.masscenter.vel(N).simplify() == sqrt(3)*n*u/3*A.y + sqrt(3)*n*u/3*A.z) assert C.masscenter.pos_from(P.masscenter) == m*N.x - n*A.x assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() == (m + n*(2*cos(q) - 1)/3)*N.x + n*(2*sin(q + pi/6) + 1)/3*N.y - n*(2*cos(q + pi/3) + 1)/3*N.z) assert (C.masscenter.vel(N).express(N).simplify() == - 2*n*u*sin(q)/3*N.x + 2*n*u*cos(q + pi/6)/3*N.y + 2*n*u*sin(q + pi/3)/3*N.z) assert C.masscenter.vel(N).dot(N.x - N.y + N.z).simplify() == 0 def test_create_aligned_frame_pi(): N, A, P, C = _generate_body() f = Joint._create_aligned_interframe(P, -P.x, P.x) assert f.z == P.z f = Joint._create_aligned_interframe(P, -P.y, P.y) assert f.x == P.x f = Joint._create_aligned_interframe(P, -P.z, P.z) assert f.y == P.y f = Joint._create_aligned_interframe(P, -P.x - P.y, P.x + P.y) assert f.z == P.z f = Joint._create_aligned_interframe(P, -P.y - P.z, P.y + P.z) assert f.x == P.x f = Joint._create_aligned_interframe(P, -P.x - P.z, P.x + P.z) assert f.y == P.y f = Joint._create_aligned_interframe(P, -P.x - P.y - P.z, P.x + P.y + P.z) assert f.y - f.z == P.y - P.z def test_pin_joint_axis(): q, u = dynamicsymbols('q u') # Test default joint axis N, A, P, C, Pint, Cint = _generate_body(True) J = PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint) assert J.joint_axis == Pint.x # Test for the same joint axis expressed in different frames N_R_A = Matrix([[0, sin(q), cos(q)], [0, -cos(q), sin(q)], [1, 0, 0]]) N, A, P, C, Pint, Cint = _generate_body(True) PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint, joint_axis=N.z) assert N.dcm(A) == N_R_A N, A, P, C, Pint, Cint = _generate_body(True) PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint, joint_axis=-Pint.z) assert N.dcm(A) == N_R_A N, A, P, C, Pint, Cint = _generate_body(True) PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint, joint_axis=-Cint.z) assert N.dcm(A) == N_R_A N, A, P, C, Pint, Cint = _generate_body(True) PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint, joint_axis=A.x) assert N.dcm(A) == N_R_A # Test time varying joint axis N, A, P, C, Pint, Cint = _generate_body(True) raises(ValueError, lambda: PinJoint('J', P, C, joint_axis=q * N.z)) def test_locate_joint_pos(): # Test Vector and default N, A, P, C = _generate_body() joint = PinJoint('J', P, C, parent_point=N.y + N.z) assert joint.parent_point.name == 'J_P_joint' assert joint.parent_point.pos_from(P.masscenter) == N.y + N.z assert joint.child_point == C.masscenter # Test Point objects N, A, P, C = _generate_body() parent_point = P.masscenter.locatenew('p', N.y + N.z) joint = PinJoint('J', P, C, parent_point=parent_point, child_point=C.masscenter) assert joint.parent_point == parent_point assert joint.child_point == C.masscenter # Check invalid type N, A, P, C = _generate_body() raises(TypeError, lambda: PinJoint('J', P, C, parent_point=N.x.to_matrix(N))) # Test time varying positions q = dynamicsymbols('q') N, A, P, C = _generate_body() raises(ValueError, lambda: PinJoint('J', P, C, parent_point=q * N.x)) N, A, P, C = _generate_body() child_point = C.masscenter.locatenew('p', q * A.y) raises(ValueError, lambda: PinJoint('J', P, C, child_point=child_point)) # Test undefined position child_point = Point('p') raises(ValueError, lambda: PinJoint('J', P, C, child_point=child_point)) def test_locate_joint_frame(): # Test rotated frame and default N, A, P, C = _generate_body() parent_interframe = ReferenceFrame('int_frame') parent_interframe.orient_axis(N, N.z, 1) joint = PinJoint('J', P, C, parent_interframe=parent_interframe) assert joint.parent_interframe == parent_interframe assert joint.parent_interframe.ang_vel_in(N) == 0 assert joint.child_interframe == A # Test time varying orientations q = dynamicsymbols('q') N, A, P, C = _generate_body() parent_interframe = ReferenceFrame('int_frame') parent_interframe.orient_axis(N, N.z, q) raises(ValueError, lambda: PinJoint('J', P, C, parent_interframe=parent_interframe)) # Test undefined frame N, A, P, C = _generate_body() child_interframe = ReferenceFrame('int_frame') child_interframe.orient_axis(N, N.z, 1) # Defined with respect to parent raises(ValueError, lambda: PinJoint('J', P, C, child_interframe=child_interframe)) def test_sliding_joint(): _, _, P, C = _generate_body() q, u = dynamicsymbols('q_S, u_S') S = PrismaticJoint('S', P, C) assert S.name == 'S' assert S.parent == P assert S.child == C assert S.coordinates == Matrix([q]) assert S.speeds == Matrix([u]) assert S.kdes == Matrix([u - q.diff(t)]) assert S.joint_axis == P.frame.x assert S.child_point.pos_from(C.masscenter) == Vector(0) assert S.parent_point.pos_from(P.masscenter) == Vector(0) assert S.parent_point.pos_from(S.child_point) == - q * P.frame.x assert P.masscenter.pos_from(C.masscenter) == - q * P.frame.x assert C.masscenter.vel(P.frame) == u * P.frame.x assert P.ang_vel_in(C) == 0 assert C.ang_vel_in(P) == 0 assert S.__str__() == 'PrismaticJoint: S parent: P child: C' N, A, P, C = _generate_body() l, m = symbols('l m') Pint = ReferenceFrame('P_int') Pint.orient_axis(P.frame, P.y, pi / 2) S = PrismaticJoint('S', P, C, parent_point=l * P.frame.x, child_point=m * C.frame.y, joint_axis=P.frame.z, parent_interframe=Pint) assert S.joint_axis == P.frame.z assert S.child_point.pos_from(C.masscenter) == m * C.frame.y assert S.parent_point.pos_from(P.masscenter) == l * P.frame.x assert S.parent_point.pos_from(S.child_point) == - q * P.frame.z assert P.masscenter.pos_from(C.masscenter) == - l*N.x - q*N.z + m*A.y assert C.masscenter.vel(P.frame) == u * P.frame.z assert P.masscenter.vel(Pint) == Vector(0) assert C.ang_vel_in(P) == 0 assert P.ang_vel_in(C) == 0 _, _, P, C = _generate_body() Pint = ReferenceFrame('P_int') Pint.orient_axis(P.frame, P.y, pi / 2) S = PrismaticJoint('S', P, C, parent_point=l * P.frame.z, child_point=m * C.frame.x, joint_axis=P.frame.z, parent_interframe=Pint) assert S.joint_axis == P.frame.z assert S.child_point.pos_from(C.masscenter) == m * C.frame.x assert S.parent_point.pos_from(P.masscenter) == l * P.frame.z assert S.parent_point.pos_from(S.child_point) == - q * P.frame.z assert P.masscenter.pos_from(C.masscenter) == (-l - q)*P.frame.z + m*C.frame.x assert C.masscenter.vel(P.frame) == u * P.frame.z assert C.ang_vel_in(P) == 0 assert P.ang_vel_in(C) == 0 def test_sliding_joint_arbitrary_axis(): q, u = dynamicsymbols('q_S, u_S') N, A, P, C = _generate_body() PrismaticJoint('S', P, C, child_interframe=-A.x) assert (-A.x).angle_between(N.x) == 0 assert -A.x.express(N) == N.x assert A.dcm(N) == Matrix([[-1, 0, 0], [0, -1, 0], [0, 0, 1]]) assert C.masscenter.pos_from(P.masscenter) == q * N.x assert C.masscenter.pos_from(P.masscenter).express(A).simplify() == -q * A.x assert C.masscenter.vel(N) == u * N.x assert C.masscenter.vel(N).express(A) == -u * A.x assert A.ang_vel_in(N) == 0 assert N.ang_vel_in(A) == 0 #When axes are different and parent joint is at masscenter but child joint is at a unit vector from #child masscenter. N, A, P, C = _generate_body() PrismaticJoint('S', P, C, child_interframe=A.y, child_point=A.x) assert A.y.angle_between(N.x) == 0 #Axis are aligned assert A.y.express(N) == N.x assert A.dcm(N) == Matrix([[0, -1, 0], [1, 0, 0], [0, 0, 1]]) assert C.masscenter.vel(N) == u * N.x assert C.masscenter.vel(N).express(A) == u * A.y assert C.masscenter.pos_from(P.masscenter) == q*N.x - A.x assert C.masscenter.pos_from(P.masscenter).express(N).simplify() == q*N.x + N.y assert A.ang_vel_in(N) == 0 assert N.ang_vel_in(A) == 0 #Similar to previous case but wrt parent body N, A, P, C = _generate_body() PrismaticJoint('S', P, C, parent_interframe=N.y, parent_point=N.x) assert N.y.angle_between(A.x) == 0 #Axis are aligned assert N.y.express(A) == A.x assert A.dcm(N) == Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 1]]) assert C.masscenter.vel(N) == u * N.y assert C.masscenter.vel(N).express(A) == u * A.x assert C.masscenter.pos_from(P.masscenter) == N.x + q*N.y assert A.ang_vel_in(N) == 0 assert N.ang_vel_in(A) == 0 #Both joint pos is defined but different axes N, A, P, C = _generate_body() PrismaticJoint('S', P, C, parent_point=N.x, child_point=A.x, child_interframe=A.x + A.y) assert N.x.angle_between(A.x + A.y) == 0 #Axis are aligned assert (A.x + A.y).express(N) == sqrt(2)*N.x assert A.dcm(N) == Matrix([[sqrt(2)/2, -sqrt(2)/2, 0], [sqrt(2)/2, sqrt(2)/2, 0], [0, 0, 1]]) assert C.masscenter.pos_from(P.masscenter) == (q + 1)*N.x - A.x assert C.masscenter.pos_from(P.masscenter).express(N) == (q - sqrt(2)/2 + 1)*N.x + sqrt(2)/2*N.y assert C.masscenter.vel(N).express(A) == u * (A.x + A.y)/sqrt(2) assert C.masscenter.vel(N) == u*N.x assert A.ang_vel_in(N) == 0 assert N.ang_vel_in(A) == 0 N, A, P, C = _generate_body() PrismaticJoint('S', P, C, parent_point=N.x, child_point=A.x, child_interframe=A.x + A.y - A.z) assert N.x.angle_between(A.x + A.y - A.z) == 0 #Axis are aligned assert (A.x + A.y - A.z).express(N) == sqrt(3)*N.x assert _simplify_matrix(A.dcm(N)) == Matrix([[sqrt(3)/3, -sqrt(3)/3, sqrt(3)/3], [sqrt(3)/3, sqrt(3)/6 + S(1)/2, S(1)/2 - sqrt(3)/6], [-sqrt(3)/3, S(1)/2 - sqrt(3)/6, sqrt(3)/6 + S(1)/2]]) assert C.masscenter.pos_from(P.masscenter) == (q + 1)*N.x - A.x assert C.masscenter.pos_from(P.masscenter).express(N) == \ (q - sqrt(3)/3 + 1)*N.x + sqrt(3)/3*N.y - sqrt(3)/3*N.z assert C.masscenter.vel(N) == u*N.x assert C.masscenter.vel(N).express(A) == sqrt(3)*u/3*A.x + sqrt(3)*u/3*A.y - sqrt(3)*u/3*A.z assert A.ang_vel_in(N) == 0 assert N.ang_vel_in(A) == 0 N, A, P, C = _generate_body() m, n = symbols('m n') PrismaticJoint('S', P, C, parent_point=m*N.x, child_point=n*A.x, child_interframe=A.x + A.y - A.z, parent_interframe=N.x - N.y + N.z) # 0 angle means that the axis are aligned assert (N.x-N.y+N.z).angle_between(A.x+A.y-A.z).simplify() == 0 assert (A.x+A.y-A.z).express(N) == N.x - N.y + N.z assert _simplify_matrix(A.dcm(N)) == Matrix([[-S(1)/3, -S(2)/3, S(2)/3], [S(2)/3, S(1)/3, S(2)/3], [-S(2)/3, S(2)/3, S(1)/3]]) assert C.masscenter.pos_from(P.masscenter) == \ (m + sqrt(3)*q/3)*N.x - sqrt(3)*q/3*N.y + sqrt(3)*q/3*N.z - n*A.x assert C.masscenter.pos_from(P.masscenter).express(N) == \ (m + n/3 + sqrt(3)*q/3)*N.x + (2*n/3 - sqrt(3)*q/3)*N.y + (-2*n/3 + sqrt(3)*q/3)*N.z assert C.masscenter.vel(N) == sqrt(3)*u/3*N.x - sqrt(3)*u/3*N.y + sqrt(3)*u/3*N.z assert C.masscenter.vel(N).express(A) == sqrt(3)*u/3*A.x + sqrt(3)*u/3*A.y - sqrt(3)*u/3*A.z assert A.ang_vel_in(N) == 0 assert N.ang_vel_in(A) == 0 def test_cylindrical_joint(): N, A, P, C = _generate_body() q0_def, q1_def, u0_def, u1_def = dynamicsymbols('q0:2_J, u0:2_J') Cj = CylindricalJoint('J', P, C) assert Cj.name == 'J' assert Cj.parent == P assert Cj.child == C assert Cj.coordinates == Matrix([q0_def, q1_def]) assert Cj.speeds == Matrix([u0_def, u1_def]) assert Cj.rotation_coordinate == q0_def assert Cj.translation_coordinate == q1_def assert Cj.rotation_speed == u0_def assert Cj.translation_speed == u1_def assert Cj.kdes == Matrix([u0_def - q0_def.diff(t), u1_def - q1_def.diff(t)]) assert Cj.joint_axis == N.x assert Cj.child_point.pos_from(C.masscenter) == Vector(0) assert Cj.parent_point.pos_from(P.masscenter) == Vector(0) assert Cj.parent_point.pos_from(Cj._child_point) == -q1_def * N.x assert C.masscenter.pos_from(P.masscenter) == q1_def * N.x assert Cj.child_point.vel(N) == u1_def * N.x assert A.ang_vel_in(N) == u0_def * N.x assert Cj.parent_interframe == N assert Cj.child_interframe == A assert Cj.__str__() == 'CylindricalJoint: J parent: P child: C' q0, q1, u0, u1 = dynamicsymbols('q0:2, u0:2') l, m = symbols('l, m') N, A, P, C, Pint, Cint = _generate_body(True) Cj = CylindricalJoint('J', P, C, rotation_coordinate=q0, rotation_speed=u0, translation_speed=u1, parent_point=m * N.x, child_point=l * A.y, parent_interframe=Pint, child_interframe=Cint, joint_axis=2 * N.z) assert Cj.coordinates == Matrix([q0, q1_def]) assert Cj.speeds == Matrix([u0, u1]) assert Cj.rotation_coordinate == q0 assert Cj.translation_coordinate == q1_def assert Cj.rotation_speed == u0 assert Cj.translation_speed == u1 assert Cj.kdes == Matrix([u0 - q0.diff(t), u1 - q1_def.diff(t)]) assert Cj.joint_axis == 2 * N.z assert Cj.child_point.pos_from(C.masscenter) == l * A.y assert Cj.parent_point.pos_from(P.masscenter) == m * N.x assert Cj.parent_point.pos_from(Cj._child_point) == -q1_def * N.z assert C.masscenter.pos_from( P.masscenter) == m * N.x + q1_def * N.z - l * A.y assert C.masscenter.vel(N) == u1 * N.z - u0 * l * A.z assert A.ang_vel_in(N) == u0 * N.z def test_deprecated_parent_child_axis(): q, u = dynamicsymbols('q_J, u_J') N, A, P, C = _generate_body() with warns_deprecated_sympy(): PinJoint('J', P, C, child_axis=-A.x) assert (-A.x).angle_between(N.x) == 0 assert -A.x.express(N) == N.x assert A.dcm(N) == Matrix([[-1, 0, 0], [0, -cos(q), -sin(q)], [0, -sin(q), cos(q)]]) assert A.ang_vel_in(N) == u * N.x assert A.ang_vel_in(N).magnitude() == sqrt(u ** 2) N, A, P, C = _generate_body() with warns_deprecated_sympy(): PrismaticJoint('J', P, C, parent_axis=P.x + P.y) assert (A.x).angle_between(N.x + N.y) == 0 assert A.x.express(N) == (N.x + N.y) / sqrt(2) assert A.dcm(N) == Matrix([[sqrt(2) / 2, sqrt(2) / 2, 0], [-sqrt(2) / 2, sqrt(2) / 2, 0], [0, 0, 1]]) assert A.ang_vel_in(N) == Vector(0) def test_deprecated_joint_pos(): N, A, P, C = _generate_body() with warns_deprecated_sympy(): pin = PinJoint('J', P, C, parent_joint_pos=N.x + N.y, child_joint_pos=C.y - C.z) assert pin.parent_point.pos_from(P.masscenter) == N.x + N.y assert pin.child_point.pos_from(C.masscenter) == C.y - C.z N, A, P, C = _generate_body() with warns_deprecated_sympy(): slider = PrismaticJoint('J', P, C, parent_joint_pos=N.z + N.y, child_joint_pos=C.y - C.x) assert slider.parent_point.pos_from(P.masscenter) == N.z + N.y assert slider.child_point.pos_from(C.masscenter) == C.y - C.x
64be7f8d960440fa6df0609cfd5694d726c2d79cee5b0aa5b714dd42e9be2ed2
from sympy.core.backend import sin, cos, tan, pi, symbols, Matrix, S from sympy.physics.mechanics import (Particle, Point, ReferenceFrame, RigidBody) from sympy.physics.mechanics import (angular_momentum, dynamicsymbols, inertia, inertia_of_point_mass, kinetic_energy, linear_momentum, outer, potential_energy, msubs, find_dynamicsymbols, Lagrangian) from sympy.physics.mechanics.functions import gravity, center_of_mass from sympy.testing.pytest import raises q1, q2, q3, q4, q5 = symbols('q1 q2 q3 q4 q5') N = ReferenceFrame('N') A = N.orientnew('A', 'Axis', [q1, N.z]) B = A.orientnew('B', 'Axis', [q2, A.x]) C = B.orientnew('C', 'Axis', [q3, B.y]) def test_inertia(): N = ReferenceFrame('N') ixx, iyy, izz = symbols('ixx iyy izz') ixy, iyz, izx = symbols('ixy iyz izx') assert inertia(N, ixx, iyy, izz) == (ixx * (N.x | N.x) + iyy * (N.y | N.y) + izz * (N.z | N.z)) assert inertia(N, 0, 0, 0) == 0 * (N.x | N.x) raises(TypeError, lambda: inertia(0, 0, 0, 0)) assert inertia(N, ixx, iyy, izz, ixy, iyz, izx) == (ixx * (N.x | N.x) + ixy * (N.x | N.y) + izx * (N.x | N.z) + ixy * (N.y | N.x) + iyy * (N.y | N.y) + iyz * (N.y | N.z) + izx * (N.z | N.x) + iyz * (N.z | N.y) + izz * (N.z | N.z)) def test_inertia_of_point_mass(): r, s, t, m = symbols('r s t m') N = ReferenceFrame('N') px = r * N.x I = inertia_of_point_mass(m, px, N) assert I == m * r**2 * (N.y | N.y) + m * r**2 * (N.z | N.z) py = s * N.y I = inertia_of_point_mass(m, py, N) assert I == m * s**2 * (N.x | N.x) + m * s**2 * (N.z | N.z) pz = t * N.z I = inertia_of_point_mass(m, pz, N) assert I == m * t**2 * (N.x | N.x) + m * t**2 * (N.y | N.y) p = px + py + pz I = inertia_of_point_mass(m, p, N) assert I == (m * (s**2 + t**2) * (N.x | N.x) - m * r * s * (N.x | N.y) - m * r * t * (N.x | N.z) - m * r * s * (N.y | N.x) + m * (r**2 + t**2) * (N.y | N.y) - m * s * t * (N.y | N.z) - m * r * t * (N.z | N.x) - m * s * t * (N.z | N.y) + m * (r**2 + s**2) * (N.z | N.z)) def test_linear_momentum(): N = ReferenceFrame('N') Ac = Point('Ac') Ac.set_vel(N, 25 * N.y) I = outer(N.x, N.x) A = RigidBody('A', Ac, N, 20, (I, Ac)) P = Point('P') Pa = Particle('Pa', P, 1) Pa.point.set_vel(N, 10 * N.x) raises(TypeError, lambda: linear_momentum(A, A, Pa)) raises(TypeError, lambda: linear_momentum(N, N, Pa)) assert linear_momentum(N, A, Pa) == 10 * N.x + 500 * N.y def test_angular_momentum_and_linear_momentum(): """A rod with length 2l, centroidal inertia I, and mass M along with a particle of mass m fixed to the end of the rod rotate with an angular rate of omega about point O which is fixed to the non-particle end of the rod. The rod's reference frame is A and the inertial frame is N.""" m, M, l, I = symbols('m, M, l, I') omega = dynamicsymbols('omega') N = ReferenceFrame('N') a = ReferenceFrame('a') O = Point('O') Ac = O.locatenew('Ac', l * N.x) P = Ac.locatenew('P', l * N.x) O.set_vel(N, 0 * N.x) a.set_ang_vel(N, omega * N.z) Ac.v2pt_theory(O, N, a) P.v2pt_theory(O, N, a) Pa = Particle('Pa', P, m) A = RigidBody('A', Ac, a, M, (I * outer(N.z, N.z), Ac)) expected = 2 * m * omega * l * N.y + M * l * omega * N.y assert linear_momentum(N, A, Pa) == expected raises(TypeError, lambda: angular_momentum(N, N, A, Pa)) raises(TypeError, lambda: angular_momentum(O, O, A, Pa)) raises(TypeError, lambda: angular_momentum(O, N, O, Pa)) expected = (I + M * l**2 + 4 * m * l**2) * omega * N.z assert angular_momentum(O, N, A, Pa) == expected def test_kinetic_energy(): m, M, l1 = symbols('m M l1') omega = dynamicsymbols('omega') N = ReferenceFrame('N') O = Point('O') O.set_vel(N, 0 * N.x) Ac = O.locatenew('Ac', l1 * N.x) P = Ac.locatenew('P', l1 * N.x) a = ReferenceFrame('a') a.set_ang_vel(N, omega * N.z) Ac.v2pt_theory(O, N, a) P.v2pt_theory(O, N, a) Pa = Particle('Pa', P, m) I = outer(N.z, N.z) A = RigidBody('A', Ac, a, M, (I, Ac)) raises(TypeError, lambda: kinetic_energy(Pa, Pa, A)) raises(TypeError, lambda: kinetic_energy(N, N, A)) assert 0 == (kinetic_energy(N, Pa, A) - (M*l1**2*omega**2/2 + 2*l1**2*m*omega**2 + omega**2/2)).expand() def test_potential_energy(): m, M, l1, g, h, H = symbols('m M l1 g h H') omega = dynamicsymbols('omega') N = ReferenceFrame('N') O = Point('O') O.set_vel(N, 0 * N.x) Ac = O.locatenew('Ac', l1 * N.x) P = Ac.locatenew('P', l1 * N.x) a = ReferenceFrame('a') a.set_ang_vel(N, omega * N.z) Ac.v2pt_theory(O, N, a) P.v2pt_theory(O, N, a) Pa = Particle('Pa', P, m) I = outer(N.z, N.z) A = RigidBody('A', Ac, a, M, (I, Ac)) Pa.potential_energy = m * g * h A.potential_energy = M * g * H assert potential_energy(A, Pa) == m * g * h + M * g * H def test_Lagrangian(): M, m, g, h = symbols('M m g h') N = ReferenceFrame('N') O = Point('O') O.set_vel(N, 0 * N.x) P = O.locatenew('P', 1 * N.x) P.set_vel(N, 10 * N.x) Pa = Particle('Pa', P, 1) Ac = O.locatenew('Ac', 2 * N.y) Ac.set_vel(N, 5 * N.y) a = ReferenceFrame('a') a.set_ang_vel(N, 10 * N.z) I = outer(N.z, N.z) A = RigidBody('A', Ac, a, 20, (I, Ac)) Pa.potential_energy = m * g * h A.potential_energy = M * g * h raises(TypeError, lambda: Lagrangian(A, A, Pa)) raises(TypeError, lambda: Lagrangian(N, N, Pa)) def test_msubs(): a, b = symbols('a, b') x, y, z = dynamicsymbols('x, y, z') # Test simple substitution expr = Matrix([[a*x + b, x*y.diff() + y], [x.diff().diff(), z + sin(z.diff())]]) sol = Matrix([[a + b, y], [x.diff().diff(), 1]]) sd = {x: 1, z: 1, z.diff(): 0, y.diff(): 0} assert msubs(expr, sd) == sol # Test smart substitution expr = cos(x + y)*tan(x + y) + b*x.diff() sd = {x: 0, y: pi/2, x.diff(): 1} assert msubs(expr, sd, smart=True) == b + 1 N = ReferenceFrame('N') v = x*N.x + y*N.y d = x*(N.x|N.x) + y*(N.y|N.y) v_sol = 1*N.y d_sol = 1*(N.y|N.y) sd = {x: 0, y: 1} assert msubs(v, sd) == v_sol assert msubs(d, sd) == d_sol def test_find_dynamicsymbols(): a, b = symbols('a, b') x, y, z = dynamicsymbols('x, y, z') expr = Matrix([[a*x + b, x*y.diff() + y], [x.diff().diff(), z + sin(z.diff())]]) # Test finding all dynamicsymbols sol = {x, y.diff(), y, x.diff().diff(), z, z.diff()} assert find_dynamicsymbols(expr) == sol # Test finding all but those in sym_list exclude_list = [x, y, z] sol = {y.diff(), x.diff().diff(), z.diff()} assert find_dynamicsymbols(expr, exclude=exclude_list) == sol # Test finding all dynamicsymbols in a vector with a given reference frame d, e, f = dynamicsymbols('d, e, f') A = ReferenceFrame('A') v = d * A.x + e * A.y + f * A.z sol = {d, e, f} assert find_dynamicsymbols(v, reference_frame=A) == sol # Test if a ValueError is raised on supplying only a vector as input raises(ValueError, lambda: find_dynamicsymbols(v)) def test_gravity(): N = ReferenceFrame('N') m, M, g = symbols('m M g') F1, F2 = dynamicsymbols('F1 F2') po = Point('po') pa = Particle('pa', po, m) A = ReferenceFrame('A') P = Point('P') I = outer(A.x, A.x) B = RigidBody('B', P, A, M, (I, P)) forceList = [(po, F1), (P, F2)] forceList.extend(gravity(g*N.y, pa, B)) l = [(po, F1), (P, F2), (po, g*m*N.y), (P, g*M*N.y)] for i in range(len(l)): for j in range(len(l[i])): assert forceList[i][j] == l[i][j] # This function tests the center_of_mass() function # that was added in PR #14758 to compute the center of # mass of a system of bodies. def test_center_of_mass(): a = ReferenceFrame('a') m = symbols('m', real=True) p1 = Particle('p1', Point('p1_pt'), S.One) p2 = Particle('p2', Point('p2_pt'), S(2)) p3 = Particle('p3', Point('p3_pt'), S(3)) p4 = Particle('p4', Point('p4_pt'), m) b_f = ReferenceFrame('b_f') b_cm = Point('b_cm') mb = symbols('mb') b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm)) p2.point.set_pos(p1.point, a.x) p3.point.set_pos(p1.point, a.x + a.y) p4.point.set_pos(p1.point, a.y) b.masscenter.set_pos(p1.point, a.y + a.z) point_o=Point('o') point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b)) expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z assert point_o.pos_from(p1.point)-expr == 0
42f000b687c0a80e2841a62fc4dd602bb4097fa4c6ac8dd3a98e5f1e36cfdb4d
from sympy.core.symbol import symbols from sympy.physics.mechanics import Point, ReferenceFrame, Dyadic, RigidBody from sympy.physics.mechanics import dynamicsymbols, outer, inertia from sympy.physics.mechanics import inertia_of_point_mass from sympy.core.backend import expand, zeros, _simplify_matrix from sympy.testing.pytest import raises, warns_deprecated_sympy def test_rigidbody(): m, m2, v1, v2, v3, omega = symbols('m m2 v1 v2 v3 omega') A = ReferenceFrame('A') A2 = ReferenceFrame('A2') P = Point('P') P2 = Point('P2') I = Dyadic(0) I2 = Dyadic(0) B = RigidBody('B', P, A, m, (I, P)) assert B.mass == m assert B.frame == A assert B.masscenter == P assert B.inertia == (I, B.masscenter) B.mass = m2 B.frame = A2 B.masscenter = P2 B.inertia = (I2, B.masscenter) raises(TypeError, lambda: RigidBody(P, P, A, m, (I, P))) raises(TypeError, lambda: RigidBody('B', P, P, m, (I, P))) raises(TypeError, lambda: RigidBody('B', P, A, m, (P, P))) raises(TypeError, lambda: RigidBody('B', P, A, m, (I, I))) assert B.__str__() == 'B' assert B.mass == m2 assert B.frame == A2 assert B.masscenter == P2 assert B.inertia == (I2, B.masscenter) assert B.masscenter == P2 assert B.inertia == (I2, B.masscenter) # Testing linear momentum function assuming A2 is the inertial frame N = ReferenceFrame('N') P2.set_vel(N, v1 * N.x + v2 * N.y + v3 * N.z) assert B.linear_momentum(N) == m2 * (v1 * N.x + v2 * N.y + v3 * N.z) def test_rigidbody2(): M, v, r, omega, g, h = dynamicsymbols('M v r omega g h') N = ReferenceFrame('N') b = ReferenceFrame('b') b.set_ang_vel(N, omega * b.x) P = Point('P') I = outer(b.x, b.x) Inertia_tuple = (I, P) B = RigidBody('B', P, b, M, Inertia_tuple) P.set_vel(N, v * b.x) assert B.angular_momentum(P, N) == omega * b.x O = Point('O') O.set_vel(N, v * b.x) P.set_pos(O, r * b.y) assert B.angular_momentum(O, N) == omega * b.x - M*v*r*b.z B.potential_energy = M * g * h assert B.potential_energy == M * g * h assert expand(2 * B.kinetic_energy(N)) == omega**2 + M * v**2 def test_rigidbody3(): q1, q2, q3, q4 = dynamicsymbols('q1:5') p1, p2, p3 = symbols('p1:4') m = symbols('m') A = ReferenceFrame('A') B = A.orientnew('B', 'axis', [q1, A.x]) O = Point('O') O.set_vel(A, q2*A.x + q3*A.y + q4*A.z) P = O.locatenew('P', p1*B.x + p2*B.y + p3*B.z) P.v2pt_theory(O, A, B) I = outer(B.x, B.x) rb1 = RigidBody('rb1', P, B, m, (I, P)) # I_S/O = I_S/S* + I_S*/O rb2 = RigidBody('rb2', P, B, m, (I + inertia_of_point_mass(m, P.pos_from(O), B), O)) assert rb1.central_inertia == rb2.central_inertia assert rb1.angular_momentum(O, A) == rb2.angular_momentum(O, A) def test_pendulum_angular_momentum(): """Consider a pendulum of length OA = 2a, of mass m as a rigid body of center of mass G (OG = a) which turn around (O,z). The angle between the reference frame R and the rod is q. The inertia of the body is I = (G,0,ma^2/3,ma^2/3). """ m, a = symbols('m, a') q = dynamicsymbols('q') R = ReferenceFrame('R') R1 = R.orientnew('R1', 'Axis', [q, R.z]) R1.set_ang_vel(R, q.diff() * R.z) I = inertia(R1, 0, m * a**2 / 3, m * a**2 / 3) O = Point('O') A = O.locatenew('A', 2*a * R1.x) G = O.locatenew('G', a * R1.x) S = RigidBody('S', G, R1, m, (I, G)) O.set_vel(R, 0) A.v2pt_theory(O, R, R1) G.v2pt_theory(O, R, R1) assert (4 * m * a**2 / 3 * q.diff() * R.z - S.angular_momentum(O, R).express(R)) == 0 def test_rigidbody_inertia(): N = ReferenceFrame('N') m, Ix, Iy, Iz, a, b = symbols('m, I_x, I_y, I_z, a, b') Io = inertia(N, Ix, Iy, Iz) o = Point('o') p = o.locatenew('p', a * N.x + b * N.y) R = RigidBody('R', o, N, m, (Io, p)) I_check = inertia(N, Ix - b ** 2 * m, Iy - a ** 2 * m, Iz - m * (a ** 2 + b ** 2), m * a * b) assert R.inertia == (Io, p) assert R.central_inertia == I_check R.central_inertia = Io assert R.inertia == (Io, o) assert R.central_inertia == Io R.inertia = (Io, p) assert R.inertia == (Io, p) assert R.central_inertia == I_check def test_parallel_axis(): N = ReferenceFrame('N') m, Ix, Iy, Iz, a, b = symbols('m, I_x, I_y, I_z, a, b') Io = inertia(N, Ix, Iy, Iz) o = Point('o') p = o.locatenew('p', a * N.x + b * N.y) R = RigidBody('R', o, N, m, (Io, o)) Ip = R.parallel_axis(p) Ip_expected = inertia(N, Ix + m * b**2, Iy + m * a**2, Iz + m * (a**2 + b**2), ixy=-m * a * b) assert Ip == Ip_expected # Reference frame from which the parallel axis is viewed should not matter A = ReferenceFrame('A') A.orient_axis(N, N.z, 1) assert _simplify_matrix( (R.parallel_axis(p, A) - Ip_expected).to_matrix(A)) == zeros(3, 3) def test_deprecated_set_potential_energy(): m, g, h = symbols('m g h') A = ReferenceFrame('A') P = Point('P') I = Dyadic(0) B = RigidBody('B', P, A, m, (I, P)) with warns_deprecated_sympy(): B.set_potential_energy(m*g*h)
d2ca28ae5fe9fad570471d235ab79ec562d7064defd776675bdbc9d14eade8f8
from sympy.core.function import expand from sympy.core.symbol import symbols from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.matrices.dense import Matrix from sympy.simplify.trigsimp import trigsimp from sympy.physics.mechanics import (PinJoint, JointsMethod, Body, KanesMethod, PrismaticJoint, LagrangesMethod, inertia) from sympy.physics.vector import dynamicsymbols, ReferenceFrame from sympy.testing.pytest import raises from sympy.core.backend import zeros from sympy.utilities.lambdify import lambdify from sympy.solvers.solvers import solve t = dynamicsymbols._t # type: ignore def test_jointsmethod(): P = Body('P') C = Body('C') Pin = PinJoint('P1', P, C) C_ixx, g = symbols('C_ixx g') q, u = dynamicsymbols('q_P1, u_P1') P.apply_force(g*P.y) method = JointsMethod(P, Pin) assert method.frame == P.frame assert method.bodies == [C, P] assert method.loads == [(P.masscenter, g*P.frame.y)] assert method.q == Matrix([q]) assert method.u == Matrix([u]) assert method.kdes == Matrix([u - q.diff()]) soln = method.form_eoms() assert soln == Matrix([[-C_ixx*u.diff()]]) assert method.forcing_full == Matrix([[u], [0]]) assert method.mass_matrix_full == Matrix([[1, 0], [0, C_ixx]]) assert isinstance(method.method, KanesMethod) def test_jointmethod_duplicate_coordinates_speeds(): P = Body('P') C = Body('C') T = Body('T') q, u = dynamicsymbols('q u') P1 = PinJoint('P1', P, C, q) P2 = PrismaticJoint('P2', C, T, q) raises(ValueError, lambda: JointsMethod(P, P1, P2)) P1 = PinJoint('P1', P, C, speeds=u) P2 = PrismaticJoint('P2', C, T, speeds=u) raises(ValueError, lambda: JointsMethod(P, P1, P2)) P1 = PinJoint('P1', P, C, q, u) P2 = PrismaticJoint('P2', C, T, q, u) raises(ValueError, lambda: JointsMethod(P, P1, P2)) def test_complete_simple_double_pendulum(): q1, q2 = dynamicsymbols('q1 q2') u1, u2 = dynamicsymbols('u1 u2') m, l, g = symbols('m l g') C = Body('C') # ceiling PartP = Body('P', mass=m) PartR = Body('R', mass=m) J1 = PinJoint('J1', C, PartP, speeds=u1, coordinates=q1, child_point=-l*PartP.x, joint_axis=C.z) J2 = PinJoint('J2', PartP, PartR, speeds=u2, coordinates=q2, child_point=-l*PartR.x, joint_axis=PartP.z) PartP.apply_force(m*g*C.x) PartR.apply_force(m*g*C.x) method = JointsMethod(C, J1, J2) method.form_eoms() assert expand(method.mass_matrix_full) == Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2*l**2*m*cos(q2) + 3*l**2*m, l**2*m*cos(q2) + l**2*m], [0, 0, l**2*m*cos(q2) + l**2*m, l**2*m]]) assert trigsimp(method.forcing_full) == trigsimp(Matrix([[u1], [u2], [-g*l*m*(sin(q1 + q2) + sin(q1)) - g*l*m*sin(q1) + l**2*m*(2*u1 + u2)*u2*sin(q2)], [-g*l*m*sin(q1 + q2) - l**2*m*u1**2*sin(q2)]])) def test_two_dof_joints(): q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2') m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2') W = Body('W') B1 = Body('B1', mass=m) B2 = Body('B2', mass=m) J1 = PrismaticJoint('J1', W, B1, coordinates=q1, speeds=u1) J2 = PrismaticJoint('J2', B1, B2, coordinates=q2, speeds=u2) W.apply_force(k1*q1*W.x, reaction_body=B1) W.apply_force(c1*u1*W.x, reaction_body=B1) B1.apply_force(k2*q2*W.x, reaction_body=B2) B1.apply_force(c2*u2*W.x, reaction_body=B2) method = JointsMethod(W, J1, J2) method.form_eoms() MM = method.mass_matrix forcing = method.forcing rhs = MM.LUsolve(forcing) assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m) assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 * c2 * u2) / m) def test_simple_pedulum(): l, m, g = symbols('l m g') C = Body('C') b = Body('b', mass=m) q = dynamicsymbols('q') P = PinJoint('P', C, b, speeds=q.diff(t), coordinates=q, child_point=-l * b.x, joint_axis=C.z) b.potential_energy = - m * g * l * cos(q) method = JointsMethod(C, P) method.form_eoms(LagrangesMethod) rhs = method.rhs() assert rhs[1] == -g*sin(q)/l def test_chaos_pendulum(): #https://www.pydy.org/examples/chaos_pendulum.html mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g = symbols('mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g') theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha') A = ReferenceFrame('A') B = ReferenceFrame('B') rod = Body('rod', mass=mA, frame=A, central_inertia=inertia(A, IAxx, IAxx, 0)) plate = Body('plate', mass=mB, frame=B, central_inertia=inertia(B, IBxx, IByy, IBzz)) C = Body('C') J1 = PinJoint('J1', C, rod, coordinates=theta, speeds=omega, child_point=-lA * rod.z, joint_axis=C.y) J2 = PinJoint('J2', rod, plate, coordinates=phi, speeds=alpha, parent_point=(lB - lA) * rod.z, joint_axis=rod.z) rod.apply_force(mA*g*C.z) plate.apply_force(mB*g*C.z) method = JointsMethod(C, J1, J2) method.form_eoms() MM = method.mass_matrix forcing = method.forcing rhs = MM.LUsolve(forcing) xd = (-2 * IBxx * alpha * omega * sin(phi) * cos(phi) + 2 * IByy * alpha * omega * sin(phi) * cos(phi) - g * lA * mA * sin(theta) - g * lB * mB * sin(theta)) / (IAxx + IBxx * sin(phi)**2 + IByy * cos(phi)**2 + lA**2 * mA + lB**2 * mB) assert (rhs[0] - xd).simplify() == 0 xd = (IBxx - IByy) * omega**2 * sin(phi) * cos(phi) / IBzz assert (rhs[1] - xd).simplify() == 0 def test_four_bar_linkage_with_manual_constraints(): q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1:4, u1:4') l1, l2, l3, l4, rho = symbols('l1:5, rho') N = ReferenceFrame('N') inertias = [inertia(N, 0, 0, rho * l ** 3 / 12) for l in (l1, l2, l3, l4)] link1 = Body('Link1', frame=N, mass=rho * l1, central_inertia=inertias[0]) link2 = Body('Link2', mass=rho * l2, central_inertia=inertias[1]) link3 = Body('Link3', mass=rho * l3, central_inertia=inertias[2]) link4 = Body('Link4', mass=rho * l4, central_inertia=inertias[3]) joint1 = PinJoint( 'J1', link1, link2, coordinates=q1, speeds=u1, joint_axis=link1.z, parent_point=l1 / 2 * link1.x, child_point=-l2 / 2 * link2.x) joint2 = PinJoint( 'J2', link2, link3, coordinates=q2, speeds=u2, joint_axis=link2.z, parent_point=l2 / 2 * link2.x, child_point=-l3 / 2 * link3.x) joint3 = PinJoint( 'J3', link3, link4, coordinates=q3, speeds=u3, joint_axis=link3.z, parent_point=l3 / 2 * link3.x, child_point=-l4 / 2 * link4.x) loop = link4.masscenter.pos_from(link1.masscenter) \ + l1 / 2 * link1.x + l4 / 2 * link4.x fh = Matrix([loop.dot(link1.x), loop.dot(link1.y)]) method = JointsMethod(link1, joint1, joint2, joint3) t = dynamicsymbols._t qdots = solve(method.kdes, [q1.diff(t), q2.diff(t), q3.diff(t)]) fhd = fh.diff(t).subs(qdots) kane = KanesMethod(method.frame, q_ind=[q1], u_ind=[u1], q_dependent=[q2, q3], u_dependent=[u2, u3], kd_eqs=method.kdes, configuration_constraints=fh, velocity_constraints=fhd, forcelist=method.loads, bodies=method.bodies) fr, frs = kane.kanes_equations() assert fr == zeros(1) # Numerically check the mass- and forcing-matrix p = Matrix([l1, l2, l3, l4, rho]) q = Matrix([q1, q2, q3]) u = Matrix([u1, u2, u3]) eval_m = lambdify((q, p), kane.mass_matrix) eval_f = lambdify((q, u, p), kane.forcing) eval_fhd = lambdify((q, u, p), fhd) p_vals = [0.13, 0.24, 0.21, 0.34, 997] q_vals = [2.1, 0.6655470375077588, 2.527408138024188] # Satisfies fh u_vals = [0.2, -0.17963733938852067, 0.1309060540601612] # Satisfies fhd mass_check = Matrix([[3.452709815256506e+01, 7.003948798374735e+00, -4.939690970641498e+00], [-2.203792703880936e-14, 2.071702479957077e-01, 2.842917573033711e-01], [-1.300000000000123e-01, -8.836934896046506e-03, 1.864891330060847e-01]]) forcing_check = Matrix([[-0.031211821321648], [-0.00066022608181], [0.001813559741243]]) eps = 1e-10 assert all(abs(x) < eps for x in eval_fhd(q_vals, u_vals, p_vals)) assert all(abs(x) < eps for x in (Matrix(eval_m(q_vals, p_vals)) - mass_check)) assert all(abs(x) < eps for x in (Matrix(eval_f(q_vals, u_vals, p_vals)) - forcing_check))
7d5ddda7de2e15b13b6476fb0e40f47c9d5481b49d735355572d3246e6197ee9
from sympy.core.backend import (Symbol, symbols, sin, cos, Matrix, zeros, _simplify_matrix) from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols, Dyadic from sympy.physics.mechanics import inertia, Body from sympy.testing.pytest import raises def test_default(): body = Body('body') assert body.name == 'body' assert body.loads == [] point = Point('body_masscenter') point.set_vel(body.frame, 0) com = body.masscenter frame = body.frame assert com.vel(frame) == point.vel(frame) assert body.mass == Symbol('body_mass') ixx, iyy, izz = symbols('body_ixx body_iyy body_izz') ixy, iyz, izx = symbols('body_ixy body_iyz body_izx') assert body.inertia == (inertia(body.frame, ixx, iyy, izz, ixy, iyz, izx), body.masscenter) def test_custom_rigid_body(): # Body with RigidBody. rigidbody_masscenter = Point('rigidbody_masscenter') rigidbody_mass = Symbol('rigidbody_mass') rigidbody_frame = ReferenceFrame('rigidbody_frame') body_inertia = inertia(rigidbody_frame, 1, 0, 0) rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass, rigidbody_frame, body_inertia) com = rigid_body.masscenter frame = rigid_body.frame rigidbody_masscenter.set_vel(rigidbody_frame, 0) assert com.vel(frame) == rigidbody_masscenter.vel(frame) assert com.pos_from(com) == rigidbody_masscenter.pos_from(com) assert rigid_body.mass == rigidbody_mass assert rigid_body.inertia == (body_inertia, rigidbody_masscenter) assert rigid_body.is_rigidbody assert hasattr(rigid_body, 'masscenter') assert hasattr(rigid_body, 'mass') assert hasattr(rigid_body, 'frame') assert hasattr(rigid_body, 'inertia') def test_particle_body(): # Body with Particle particle_masscenter = Point('particle_masscenter') particle_mass = Symbol('particle_mass') particle_frame = ReferenceFrame('particle_frame') particle_body = Body('particle_body', particle_masscenter, particle_mass, particle_frame) com = particle_body.masscenter frame = particle_body.frame particle_masscenter.set_vel(particle_frame, 0) assert com.vel(frame) == particle_masscenter.vel(frame) assert com.pos_from(com) == particle_masscenter.pos_from(com) assert particle_body.mass == particle_mass assert not hasattr(particle_body, "_inertia") assert hasattr(particle_body, 'frame') assert hasattr(particle_body, 'masscenter') assert hasattr(particle_body, 'mass') assert particle_body.inertia == (Dyadic(0), particle_body.masscenter) assert particle_body.central_inertia == Dyadic(0) assert not particle_body.is_rigidbody particle_body.central_inertia = inertia(particle_frame, 1, 1, 1) assert particle_body.central_inertia == inertia(particle_frame, 1, 1, 1) assert particle_body.is_rigidbody particle_body = Body('particle_body', mass=particle_mass) assert not particle_body.is_rigidbody point = particle_body.masscenter.locatenew('point', particle_body.x) point_inertia = particle_mass * inertia(particle_body.frame, 0, 1, 1) particle_body.inertia = (point_inertia, point) assert particle_body.inertia == (point_inertia, point) assert particle_body.central_inertia == Dyadic(0) assert particle_body.is_rigidbody def test_particle_body_add_force(): # Body with Particle particle_masscenter = Point('particle_masscenter') particle_mass = Symbol('particle_mass') particle_frame = ReferenceFrame('particle_frame') particle_body = Body('particle_body', particle_masscenter, particle_mass, particle_frame) a = Symbol('a') force_vector = a * particle_body.frame.x particle_body.apply_force(force_vector, particle_body.masscenter) assert len(particle_body.loads) == 1 point = particle_body.masscenter.locatenew( particle_body._name + '_point0', 0) point.set_vel(particle_body.frame, 0) force_point = particle_body.loads[0][0] frame = particle_body.frame assert force_point.vel(frame) == point.vel(frame) assert force_point.pos_from(force_point) == point.pos_from(force_point) assert particle_body.loads[0][1] == force_vector def test_body_add_force(): # Body with RigidBody. rigidbody_masscenter = Point('rigidbody_masscenter') rigidbody_mass = Symbol('rigidbody_mass') rigidbody_frame = ReferenceFrame('rigidbody_frame') body_inertia = inertia(rigidbody_frame, 1, 0, 0) rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass, rigidbody_frame, body_inertia) l = Symbol('l') Fa = Symbol('Fa') point = rigid_body.masscenter.locatenew( 'rigidbody_body_point0', l * rigid_body.frame.x) point.set_vel(rigid_body.frame, 0) force_vector = Fa * rigid_body.frame.z # apply_force with point rigid_body.apply_force(force_vector, point) assert len(rigid_body.loads) == 1 force_point = rigid_body.loads[0][0] frame = rigid_body.frame assert force_point.vel(frame) == point.vel(frame) assert force_point.pos_from(force_point) == point.pos_from(force_point) assert rigid_body.loads[0][1] == force_vector # apply_force without point rigid_body.apply_force(force_vector) assert len(rigid_body.loads) == 2 assert rigid_body.loads[1][1] == force_vector # passing something else than point raises(TypeError, lambda: rigid_body.apply_force(force_vector, 0)) raises(TypeError, lambda: rigid_body.apply_force(0)) def test_body_add_torque(): body = Body('body') torque_vector = body.frame.x body.apply_torque(torque_vector) assert len(body.loads) == 1 assert body.loads[0] == (body.frame, torque_vector) raises(TypeError, lambda: body.apply_torque(0)) def test_body_masscenter_vel(): A = Body('A') N = ReferenceFrame('N') B = Body('B', frame=N) A.masscenter.set_vel(N, N.z) assert A.masscenter_vel(B) == N.z assert A.masscenter_vel(N) == N.z def test_body_ang_vel(): A = Body('A') N = ReferenceFrame('N') B = Body('B', frame=N) A.frame.set_ang_vel(N, N.y) assert A.ang_vel_in(B) == N.y assert B.ang_vel_in(A) == -N.y assert A.ang_vel_in(N) == N.y def test_body_dcm(): A = Body('A') B = Body('B') A.frame.orient_axis(B.frame, B.frame.z, 10) assert A.dcm(B) == Matrix([[cos(10), sin(10), 0], [-sin(10), cos(10), 0], [0, 0, 1]]) assert A.dcm(B.frame) == Matrix([[cos(10), sin(10), 0], [-sin(10), cos(10), 0], [0, 0, 1]]) def test_body_axis(): N = ReferenceFrame('N') B = Body('B', frame=N) assert B.x == N.x assert B.y == N.y assert B.z == N.z def test_apply_force_multiple_one_point(): a, b = symbols('a b') P = Point('P') B = Body('B') f1 = a*B.x f2 = b*B.y B.apply_force(f1, P) assert B.loads == [(P, f1)] B.apply_force(f2, P) assert B.loads == [(P, f1+f2)] def test_apply_force(): f, g = symbols('f g') q, x, v1, v2 = dynamicsymbols('q x v1 v2') P1 = Point('P1') P2 = Point('P2') B1 = Body('B1') B2 = Body('B2') N = ReferenceFrame('N') P1.set_vel(B1.frame, v1*B1.x) P2.set_vel(B2.frame, v2*B2.x) force = f*q*N.z # time varying force B1.apply_force(force, P1, B2, P2) #applying equal and opposite force on moving points assert B1.loads == [(P1, force)] assert B2.loads == [(P2, -force)] g1 = B1.mass*g*N.y g2 = B2.mass*g*N.y B1.apply_force(g1) #applying gravity on B1 masscenter B2.apply_force(g2) #applying gravity on B2 masscenter assert B1.loads == [(P1,force), (B1.masscenter, g1)] assert B2.loads == [(P2, -force), (B2.masscenter, g2)] force2 = x*N.x B1.apply_force(force2, reaction_body=B2) #Applying time varying force on masscenter assert B1.loads == [(P1, force), (B1.masscenter, force2+g1)] assert B2.loads == [(P2, -force), (B2.masscenter, -force2+g2)] def test_apply_torque(): t = symbols('t') q = dynamicsymbols('q') B1 = Body('B1') B2 = Body('B2') N = ReferenceFrame('N') torque = t*q*N.x B1.apply_torque(torque, B2) #Applying equal and opposite torque assert B1.loads == [(B1.frame, torque)] assert B2.loads == [(B2.frame, -torque)] torque2 = t*N.y B1.apply_torque(torque2) assert B1.loads == [(B1.frame, torque+torque2)] def test_clear_load(): a = symbols('a') P = Point('P') B = Body('B') force = a*B.z B.apply_force(force, P) assert B.loads == [(P, force)] B.clear_loads() assert B.loads == [] def test_remove_load(): P1 = Point('P1') P2 = Point('P2') B = Body('B') f1 = B.x f2 = B.y B.apply_force(f1, P1) B.apply_force(f2, P2) assert B.loads == [(P1, f1), (P2, f2)] B.remove_load(P2) assert B.loads == [(P1, f1)] B.apply_torque(f1.cross(f2)) assert B.loads == [(P1, f1), (B.frame, f1.cross(f2))] B.remove_load() assert B.loads == [(P1, f1)] def test_apply_loads_on_multi_degree_freedom_holonomic_system(): """Example based on: https://pydy.readthedocs.io/en/latest/examples/multidof-holonomic.html""" W = Body('W') #Wall B = Body('B') #Block P = Body('P') #Pendulum b = Body('b') #bob q1, q2 = dynamicsymbols('q1 q2') #generalized coordinates k, c, g, kT = symbols('k c g kT') #constants F, T = dynamicsymbols('F T') #Specified forces #Applying forces B.apply_force(F*W.x) W.apply_force(k*q1*W.x, reaction_body=B) #Spring force W.apply_force(c*q1.diff()*W.x, reaction_body=B) #dampner P.apply_force(P.mass*g*W.y) b.apply_force(b.mass*g*W.y) #Applying torques P.apply_torque(kT*q2*W.z, reaction_body=b) P.apply_torque(T*W.z) assert B.loads == [(B.masscenter, (F - k*q1 - c*q1.diff())*W.x)] assert P.loads == [(P.masscenter, P.mass*g*W.y), (P.frame, (T + kT*q2)*W.z)] assert b.loads == [(b.masscenter, b.mass*g*W.y), (b.frame, -kT*q2*W.z)] assert W.loads == [(W.masscenter, (c*q1.diff() + k*q1)*W.x)] def test_parallel_axis(): N = ReferenceFrame('N') m, Ix, Iy, Iz, a, b = symbols('m, I_x, I_y, I_z, a, b') Io = inertia(N, Ix, Iy, Iz) # Test RigidBody o = Point('o') p = o.locatenew('p', a * N.x + b * N.y) R = Body('R', masscenter=o, frame=N, mass=m, central_inertia=Io) Ip = R.parallel_axis(p) Ip_expected = inertia(N, Ix + m * b**2, Iy + m * a**2, Iz + m * (a**2 + b**2), ixy=-m * a * b) assert Ip == Ip_expected # Reference frame from which the parallel axis is viewed should not matter A = ReferenceFrame('A') A.orient_axis(N, N.z, 1) assert _simplify_matrix( (R.parallel_axis(p, A) - Ip_expected).to_matrix(A)) == zeros(3, 3) # Test Particle o = Point('o') p = o.locatenew('p', a * N.x + b * N.y) P = Body('P', masscenter=o, mass=m, frame=N) Ip = P.parallel_axis(p, N) Ip_expected = inertia(N, m * b ** 2, m * a ** 2, m * (a ** 2 + b ** 2), ixy=-m * a * b) assert not P.is_rigidbody assert Ip == Ip_expected
76c8ed5d0a015dc14369c29ce790db6524f52faf5718a3744ccb420671cde616
from sympy.core.symbol import Symbol, symbols from sympy.physics.continuum_mechanics.truss import Truss from sympy import sqrt def test_truss(): A = Symbol('A') B = Symbol('B') C = Symbol('C') AB, BC, AC = symbols('AB, BC, AC') P = Symbol('P') t = Truss() assert t.nodes == [] assert t.node_labels == [] assert t.node_positions == [] assert t.members == {} assert t.loads == {} assert t.supports == {} assert t.reaction_loads == {} assert t.internal_forces == {} # testing the add_node method t.add_node(A, 0, 0) t.add_node(B, 2, 2) t.add_node(C, 3, 0) assert t.nodes == [(A, 0, 0), (B, 2, 2), (C, 3, 0)] assert t.node_labels == [A, B, C] assert t.node_positions == [(0, 0), (2, 2), (3, 0)] assert t.loads == {} assert t.supports == {} assert t.reaction_loads == {} # testing the remove_node method t.remove_node(C) assert t.nodes == [(A, 0, 0), (B, 2, 2)] assert t.node_labels == [A, B] assert t.node_positions == [(0, 0), (2, 2)] assert t.loads == {} assert t.supports == {} t.add_node(C, 3, 0) # testing the add_member method t.add_member(AB, A, B) t.add_member(BC, B, C) t.add_member(AC, A, C) assert t.members == {AB: [A, B], BC: [B, C], AC: [A, C]} assert t.internal_forces == {AB: 0, BC: 0, AC: 0} # testing the remove_member method t.remove_member(BC) assert t.members == {AB: [A, B], AC: [A, C]} assert t.internal_forces == {AB: 0, AC: 0} t.add_member(BC, B, C) D, CD = symbols('D, CD') # testing the change_label methods t.change_node_label(B, D) assert t.nodes == [(A, 0, 0), (D, 2, 2), (C, 3, 0)] assert t.node_labels == [A, D, C] assert t.loads == {} assert t.supports == {} assert t.members == {AB: [A, D], BC: [D, C], AC: [A, C]} t.change_member_label(BC, CD) assert t.members == {AB: [A, D], CD: [D, C], AC: [A, C]} assert t.internal_forces == {AB: 0, CD: 0, AC: 0} # testing the apply_load method t.apply_load(A, P, 90) t.apply_load(A, P/4, 90) t.apply_load(A, 2*P,45) t.apply_load(D, P/2, 90) assert t.loads == {A: [[P, 90], [P/4, 90], [2*P, 45]], D: [[P/2, 90]]} assert t.loads[A] == [[P, 90], [P/4, 90], [2*P, 45]] # testing the remove_load method t.remove_load(A, P/4, 90) assert t.loads == {A: [[P, 90], [2*P, 45]], D: [[P/2, 90]]} assert t.loads[A] == [[P, 90], [2*P, 45]] # testing the apply_support method t.apply_support(A, "pinned") t.apply_support(D, "roller") assert t.supports == {A: 'pinned', D: 'roller'} assert t.reaction_loads == {} assert t.loads == {A: [[P, 90], [2*P, 45], [Symbol('R_A_x'), 0], [Symbol('R_A_y'), 90]], D: [[P/2, 90], [Symbol('R_D_y'), 90]]} # testing the remove_support method t.remove_support(A) assert t.supports == {D: 'roller'} assert t.reaction_loads == {} assert t.loads == {A: [[P, 90], [2*P, 45]], D: [[P/2, 90], [Symbol('R_D_y'), 90]]} t.apply_support(A, "pinned") # testing the solve method t.solve() assert t.reaction_loads['R_A_x'] == -sqrt(2)*P assert t.reaction_loads['R_A_y'] == -sqrt(2)*P - P assert t.reaction_loads['R_D_y'] == -P/2 assert t.internal_forces[AB]/P == 0 assert t.internal_forces[CD] == 0 assert t.internal_forces[AC] == 0
3943098d963b1ed5892f4ca0aa47560bc2dd0aa89b25984709f61e5eef9e0781
r""" Array expressions are expressions representing N-dimensional arrays, without evaluating them. These expressions represent in a certain way abstract syntax trees of operations on N-dimensional arrays. Every N-dimensional array operator has a corresponding array expression object. Table of correspondences: =============================== ============================= Array operator Array expression operator =============================== ============================= tensorproduct ArrayTensorProduct tensorcontraction ArrayContraction tensordiagonal ArrayDiagonal permutedims PermuteDims =============================== ============================= Examples ======== ``ArraySymbol`` objects are the N-dimensional equivalent of ``MatrixSymbol`` objects in the matrix module: >>> from sympy.tensor.array.expressions import ArraySymbol >>> from sympy.abc import i, j, k >>> A = ArraySymbol("A", (3, 2, 4)) >>> A.shape (3, 2, 4) >>> A[i, j, k] A[i, j, k] >>> A.as_explicit() [[[A[0, 0, 0], A[0, 0, 1], A[0, 0, 2], A[0, 0, 3]], [A[0, 1, 0], A[0, 1, 1], A[0, 1, 2], A[0, 1, 3]]], [[A[1, 0, 0], A[1, 0, 1], A[1, 0, 2], A[1, 0, 3]], [A[1, 1, 0], A[1, 1, 1], A[1, 1, 2], A[1, 1, 3]]], [[A[2, 0, 0], A[2, 0, 1], A[2, 0, 2], A[2, 0, 3]], [A[2, 1, 0], A[2, 1, 1], A[2, 1, 2], A[2, 1, 3]]]] Component-explicit arrays can be added inside array expressions: >>> from sympy import Array >>> from sympy import tensorproduct >>> from sympy.tensor.array.expressions import ArrayTensorProduct >>> a = Array([1, 2, 3]) >>> b = Array([i, j, k]) >>> expr = ArrayTensorProduct(a, b, b) >>> expr ArrayTensorProduct([1, 2, 3], [i, j, k], [i, j, k]) >>> expr.as_explicit() == tensorproduct(a, b, b) True Constructing array expressions from index-explicit forms -------------------------------------------------------- Array expressions are index-implicit. This means they do not use any indices to represent array operations. The function ``convert_indexed_to_array( ... )`` may be used to convert index-explicit expressions to array expressions. It takes as input two parameters: the index-explicit expression and the order of the indices: >>> from sympy.tensor.array.expressions import convert_indexed_to_array >>> from sympy import Sum >>> A = ArraySymbol("A", (3, 3)) >>> B = ArraySymbol("B", (3, 3)) >>> convert_indexed_to_array(A[i, j], [i, j]) A >>> convert_indexed_to_array(A[i, j], [j, i]) PermuteDims(A, (0 1)) >>> convert_indexed_to_array(A[i, j] + B[j, i], [i, j]) ArrayAdd(A, PermuteDims(B, (0 1))) >>> convert_indexed_to_array(Sum(A[i, j]*B[j, k], (j, 0, 2)), [i, k]) ArrayContraction(ArrayTensorProduct(A, B), (1, 2)) The diagonal of a matrix in the array expression form: >>> convert_indexed_to_array(A[i, i], [i]) ArrayDiagonal(A, (0, 1)) The trace of a matrix in the array expression form: >>> convert_indexed_to_array(Sum(A[i, i], (i, 0, 2)), [i]) ArrayContraction(A, (0, 1)) Compatibility with matrices --------------------------- Array expressions can be mixed with objects from the matrix module: >>> from sympy import MatrixSymbol >>> from sympy.tensor.array.expressions import ArrayContraction >>> M = MatrixSymbol("M", 3, 3) >>> N = MatrixSymbol("N", 3, 3) Express the matrix product in the array expression form: >>> from sympy.tensor.array.expressions import convert_matrix_to_array >>> expr = convert_matrix_to_array(M*N) >>> expr ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) The expression can be converted back to matrix form: >>> from sympy.tensor.array.expressions import convert_array_to_matrix >>> convert_array_to_matrix(expr) M*N Add a second contraction on the remaining axes in order to get the trace of `M \cdot N`: >>> expr_tr = ArrayContraction(expr, (0, 1)) >>> expr_tr ArrayContraction(ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), (0, 1)) Flatten the expression by calling ``.doit()`` and remove the nested array contraction operations: >>> expr_tr.doit() ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2)) Get the explicit form of the array expression: >>> expr.as_explicit() [[M[0, 0]*N[0, 0] + M[0, 1]*N[1, 0] + M[0, 2]*N[2, 0], M[0, 0]*N[0, 1] + M[0, 1]*N[1, 1] + M[0, 2]*N[2, 1], M[0, 0]*N[0, 2] + M[0, 1]*N[1, 2] + M[0, 2]*N[2, 2]], [M[1, 0]*N[0, 0] + M[1, 1]*N[1, 0] + M[1, 2]*N[2, 0], M[1, 0]*N[0, 1] + M[1, 1]*N[1, 1] + M[1, 2]*N[2, 1], M[1, 0]*N[0, 2] + M[1, 1]*N[1, 2] + M[1, 2]*N[2, 2]], [M[2, 0]*N[0, 0] + M[2, 1]*N[1, 0] + M[2, 2]*N[2, 0], M[2, 0]*N[0, 1] + M[2, 1]*N[1, 1] + M[2, 2]*N[2, 1], M[2, 0]*N[0, 2] + M[2, 1]*N[1, 2] + M[2, 2]*N[2, 2]]] Express the trace of a matrix: >>> from sympy import Trace >>> convert_matrix_to_array(Trace(M)) ArrayContraction(M, (0, 1)) >>> convert_matrix_to_array(Trace(M*N)) ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2)) Express the transposition of a matrix (will be expressed as a permutation of the axes: >>> convert_matrix_to_array(M.T) PermuteDims(M, (0 1)) Compute the derivative array expressions: >>> from sympy.tensor.array.expressions import array_derive >>> d = array_derive(M, M) >>> d PermuteDims(ArrayTensorProduct(I, I), (3)(1 2)) Verify that the derivative corresponds to the form computed with explicit matrices: >>> d.as_explicit() [[[[1, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 1], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 1, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [1, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 1, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 1]]]] >>> Me = M.as_explicit() >>> Me.diff(Me) [[[[1, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 1], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 1, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [1, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 1, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 1]]]] """ __all__ = [ "ArraySymbol", "ArrayElement", "ZeroArray", "OneArray", "ArrayTensorProduct", "ArrayContraction", "ArrayDiagonal", "PermuteDims", "ArrayAdd", "ArrayElementwiseApplyFunc", "Reshape", "convert_array_to_matrix", "convert_matrix_to_array", "convert_array_to_indexed", "convert_indexed_to_array", "array_derive", ] from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, PermuteDims, ArrayDiagonal, \ ArrayContraction, Reshape, ArraySymbol, ArrayElement, ZeroArray, OneArray, ArrayElementwiseApplyFunc from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive from sympy.tensor.array.expressions.from_array_to_indexed import convert_array_to_indexed from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
1325b9d93a65071231db99940ef23fe53cdcf0b0fa327a7a5cd5bdc08c3da47e
from sympy.tensor.array.expressions import from_indexed_to_array from sympy.tensor.array.expressions.conv_array_to_indexed import _conv_to_from_decorator convert_indexed_to_array = _conv_to_from_decorator(from_indexed_to_array.convert_indexed_to_array)
b2763c63374c8d47444d6a593470dcdfa3edaffd2ca784b923c9ec7412b6ba3d
from collections import defaultdict from sympy import Function from sympy.combinatorics.permutations import _af_invert from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.numbers import Integer from sympy.core.power import Pow from sympy.core.sorting import default_sort_key from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.tensor.array.expressions import ArrayElementwiseApplyFunc from sympy.tensor.indexed import (Indexed, IndexedBase) from sympy.combinatorics import Permutation from sympy.matrices.expressions.matexpr import MatrixElement from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal, \ get_shape, ArrayElement, _array_tensor_product, _array_diagonal, _array_contraction, _array_add, \ _permute_dims, OneArray, ArrayAdd from sympy.tensor.array.expressions.utils import _get_argindex, _get_diagonal_indices def convert_indexed_to_array(expr, first_indices=None): r""" Parse indexed expression into a form useful for code generation. Examples ======== >>> from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array >>> from sympy import MatrixSymbol, Sum, symbols >>> i, j, k, d = symbols("i j k d") >>> M = MatrixSymbol("M", d, d) >>> N = MatrixSymbol("N", d, d) Recognize the trace in summation form: >>> expr = Sum(M[i, i], (i, 0, d-1)) >>> convert_indexed_to_array(expr) ArrayContraction(M, (0, 1)) Recognize the extraction of the diagonal by using the same index `i` on both axes of the matrix: >>> expr = M[i, i] >>> convert_indexed_to_array(expr) ArrayDiagonal(M, (0, 1)) This function can help perform the transformation expressed in two different mathematical notations as: `\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}` Recognize the matrix multiplication in summation form: >>> expr = Sum(M[i, j]*N[j, k], (j, 0, d-1)) >>> convert_indexed_to_array(expr) ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) Specify that ``k`` has to be the starting index: >>> convert_indexed_to_array(expr, first_indices=[k]) ArrayContraction(ArrayTensorProduct(N, M), (0, 3)) """ result, indices = _convert_indexed_to_array(expr) if any(isinstance(i, (int, Integer)) for i in indices): result = ArrayElement(result, indices) indices = [] if not first_indices: return result def _check_is_in(elem, indices): if elem in indices: return True if any(elem in i for i in indices if isinstance(i, frozenset)): return True return False repl = {j: i for i in indices if isinstance(i, frozenset) for j in i} first_indices = [repl.get(i, i) for i in first_indices] for i in first_indices: if not _check_is_in(i, indices): first_indices.remove(i) first_indices.extend([i for i in indices if not _check_is_in(i, first_indices)]) def _get_pos(elem, indices): if elem in indices: return indices.index(elem) for i, e in enumerate(indices): if not isinstance(e, frozenset): continue if elem in e: return i raise ValueError("not found") permutation = _af_invert([_get_pos(i, first_indices) for i in indices]) if isinstance(result, ArrayAdd): return _array_add(*[_permute_dims(arg, permutation) for arg in result.args]) else: return _permute_dims(result, permutation) def _convert_indexed_to_array(expr): if isinstance(expr, Sum): function = expr.function summation_indices = expr.variables subexpr, subindices = _convert_indexed_to_array(function) subindicessets = {j: i for i in subindices if isinstance(i, frozenset) for j in i} summation_indices = sorted(set([subindicessets.get(i, i) for i in summation_indices]), key=default_sort_key) # TODO: check that Kronecker delta is only contracted to one other element: kronecker_indices = set([]) if isinstance(function, Mul): for arg in function.args: if not isinstance(arg, KroneckerDelta): continue arg_indices = sorted(set(arg.indices), key=default_sort_key) if len(arg_indices) == 2: kronecker_indices.update(arg_indices) kronecker_indices = sorted(kronecker_indices, key=default_sort_key) # Check dimensional consistency: shape = get_shape(subexpr) if shape: for ind, istart, iend in expr.limits: i = _get_argindex(subindices, ind) if istart != 0 or iend+1 != shape[i]: raise ValueError("summation index and array dimension mismatch: %s" % ind) contraction_indices = [] subindices = list(subindices) if isinstance(subexpr, ArrayDiagonal): diagonal_indices = list(subexpr.diagonal_indices) dindices = subindices[-len(diagonal_indices):] subindices = subindices[:-len(diagonal_indices)] for index in summation_indices: if index in dindices: position = dindices.index(index) contraction_indices.append(diagonal_indices[position]) diagonal_indices[position] = None diagonal_indices = [i for i in diagonal_indices if i is not None] for i, ind in enumerate(subindices): if ind in summation_indices: pass if diagonal_indices: subexpr = _array_diagonal(subexpr.expr, *diagonal_indices) else: subexpr = subexpr.expr axes_contraction = defaultdict(list) for i, ind in enumerate(subindices): include = all(j not in kronecker_indices for j in ind) if isinstance(ind, frozenset) else ind not in kronecker_indices if ind in summation_indices and include: axes_contraction[ind].append(i) subindices[i] = None for k, v in axes_contraction.items(): if any(i in kronecker_indices for i in k) if isinstance(k, frozenset) else k in kronecker_indices: continue contraction_indices.append(tuple(v)) free_indices = [i for i in subindices if i is not None] indices_ret = list(free_indices) indices_ret.sort(key=lambda x: free_indices.index(x)) return _array_contraction( subexpr, *contraction_indices, free_indices=free_indices ), tuple(indices_ret) if isinstance(expr, Mul): args, indices = zip(*[_convert_indexed_to_array(arg) for arg in expr.args]) # Check if there are KroneckerDelta objects: kronecker_delta_repl = {} for arg in args: if not isinstance(arg, KroneckerDelta): continue # Diagonalize two indices: i, j = arg.indices kindices = set(arg.indices) if i in kronecker_delta_repl: kindices.update(kronecker_delta_repl[i]) if j in kronecker_delta_repl: kindices.update(kronecker_delta_repl[j]) kindices = frozenset(kindices) for index in kindices: kronecker_delta_repl[index] = kindices # Remove KroneckerDelta objects, their relations should be handled by # ArrayDiagonal: newargs = [] newindices = [] for arg, loc_indices in zip(args, indices): if isinstance(arg, KroneckerDelta): continue newargs.append(arg) newindices.append(loc_indices) flattened_indices = [kronecker_delta_repl.get(j, j) for i in newindices for j in i] diagonal_indices, ret_indices = _get_diagonal_indices(flattened_indices) tp = _array_tensor_product(*newargs) if diagonal_indices: return _array_diagonal(tp, *diagonal_indices), ret_indices else: return tp, ret_indices if isinstance(expr, MatrixElement): indices = expr.args[1:] diagonal_indices, ret_indices = _get_diagonal_indices(indices) if diagonal_indices: return _array_diagonal(expr.args[0], *diagonal_indices), ret_indices else: return expr.args[0], ret_indices if isinstance(expr, ArrayElement): indices = expr.indices diagonal_indices, ret_indices = _get_diagonal_indices(indices) if diagonal_indices: return _array_diagonal(expr.name, *diagonal_indices), ret_indices else: return expr.name, ret_indices if isinstance(expr, Indexed): indices = expr.indices diagonal_indices, ret_indices = _get_diagonal_indices(indices) if diagonal_indices: return _array_diagonal(expr.base, *diagonal_indices), ret_indices else: return expr.args[0], ret_indices if isinstance(expr, IndexedBase): raise NotImplementedError if isinstance(expr, KroneckerDelta): return expr, expr.indices if isinstance(expr, Add): args, indices = zip(*[_convert_indexed_to_array(arg) for arg in expr.args]) args = list(args) # Check if all indices are compatible. Otherwise expand the dimensions: index0 = [] shape0 = [] for arg, arg_indices in zip(args, indices): arg_indices_set = set(arg_indices) arg_indices_missing = arg_indices_set.difference(index0) index0.extend([i for i in arg_indices if i in arg_indices_missing]) arg_shape = get_shape(arg) shape0.extend([arg_shape[i] for i, e in enumerate(arg_indices) if e in arg_indices_missing]) for i, (arg, arg_indices) in enumerate(zip(args, indices)): if len(arg_indices) < len(index0): missing_indices_pos = [i for i, e in enumerate(index0) if e not in arg_indices] missing_shape = [shape0[i] for i in missing_indices_pos] arg_indices = tuple(index0[j] for j in missing_indices_pos) + arg_indices args[i] = _array_tensor_product(OneArray(*missing_shape), args[i]) permutation = Permutation([arg_indices.index(j) for j in index0]) # Perform index permutations: args[i] = _permute_dims(args[i], permutation) return _array_add(*args), tuple(index0) if isinstance(expr, Pow): subexpr, subindices = _convert_indexed_to_array(expr.base) if isinstance(expr.exp, (int, Integer)): diags = zip(*[(2*i, 2*i + 1) for i in range(expr.exp)]) arr = _array_diagonal(_array_tensor_product(*[subexpr for i in range(expr.exp)]), *diags) return arr, subindices if isinstance(expr, Function): subexpr, subindices = _convert_indexed_to_array(expr.args[0]) return ArrayElementwiseApplyFunc(type(expr), subexpr), subindices return expr, ()
f39619053648e28f5d26d2832575ee83f94954b1bc753ff6d804fb97b0caa321
from sympy.tensor.array.expressions import from_array_to_matrix from sympy.tensor.array.expressions.conv_array_to_indexed import _conv_to_from_decorator convert_array_to_matrix = _conv_to_from_decorator(from_array_to_matrix.convert_array_to_matrix) _array2matrix = _conv_to_from_decorator(from_array_to_matrix._array2matrix) _remove_trivial_dims = _conv_to_from_decorator(from_array_to_matrix._remove_trivial_dims)
048c2542bed1282f1b64dde647c2020b94d8382f6e6ac61c57465cd5534a9a21
from sympy.tensor.array.expressions import from_array_to_indexed from sympy.utilities.decorator import deprecated _conv_to_from_decorator = deprecated( "module has been renamed by replacing 'conv_' with 'from_' in its name", deprecated_since_version="1.11", active_deprecations_target="deprecated-conv-array-expr-module-names", ) convert_array_to_indexed = _conv_to_from_decorator(from_array_to_indexed.convert_array_to_indexed)
5d8caab7436c412ae0369124afcc5319e52147b65878d9635457d5105d4aeef0
from sympy.tensor.array.expressions import from_matrix_to_array from sympy.tensor.array.expressions.conv_array_to_indexed import _conv_to_from_decorator convert_matrix_to_array = _conv_to_from_decorator(from_matrix_to_array.convert_matrix_to_array)
d770a4470454aac7a82c3bfc5d2010f8eec9c1bd391966479e4f7cc089683a79
import collections.abc import operator from collections import defaultdict, Counter from functools import reduce import itertools from itertools import accumulate from typing import Optional, List, Dict as tDict, Tuple as tTuple import typing from sympy.core.numbers import Integer from sympy.core.relational import Equality from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.function import (Function, Lambda) from sympy.core.mul import Mul from sympy.core.singleton import S from sympy.core.sorting import default_sort_key from sympy.core.symbol import (Dummy, Symbol) from sympy.matrices.common import MatrixCommon from sympy.matrices.expressions.diagonal import diagonalize_vector from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.matrices.expressions.special import ZeroMatrix from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensordiagonal, tensorproduct) from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray from sympy.tensor.array.ndim_array import NDimArray from sympy.tensor.indexed import (Indexed, IndexedBase) from sympy.matrices.expressions.matexpr import MatrixElement from sympy.tensor.array.expressions.utils import _apply_recursively_over_nested_lists, _sort_contraction_indices, \ _get_mapping_from_subranks, _build_push_indices_up_func_transformation, _get_contraction_links, \ _build_push_indices_down_func_transformation from sympy.combinatorics import Permutation from sympy.combinatorics.permutations import _af_invert from sympy.core.sympify import _sympify class _ArrayExpr(Expr): shape: tTuple[Expr, ...] def __getitem__(self, item): if not isinstance(item, collections.abc.Iterable): item = (item,) ArrayElement._check_shape(self, item) return self._get(item) def _get(self, item): return _get_array_element_or_slice(self, item) class ArraySymbol(_ArrayExpr): """ Symbol representing an array expression """ def __new__(cls, symbol, shape: typing.Iterable) -> "ArraySymbol": if isinstance(symbol, str): symbol = Symbol(symbol) # symbol = _sympify(symbol) shape = Tuple(*map(_sympify, shape)) obj = Expr.__new__(cls, symbol, shape) return obj @property def name(self): return self._args[0] @property def shape(self): return self._args[1] def as_explicit(self): if not all(i.is_Integer for i in self.shape): raise ValueError("cannot express explicit array with symbolic shape") data = [self[i] for i in itertools.product(*[range(j) for j in self.shape])] return ImmutableDenseNDimArray(data).reshape(*self.shape) class ArrayElement(Expr): """ An element of an array. """ _diff_wrt = True is_symbol = True is_commutative = True def __new__(cls, name, indices): if isinstance(name, str): name = Symbol(name) name = _sympify(name) if not isinstance(indices, collections.abc.Iterable): indices = (indices,) indices = _sympify(tuple(indices)) cls._check_shape(name, indices) obj = Expr.__new__(cls, name, indices) return obj @classmethod def _check_shape(cls, name, indices): indices = tuple(indices) if hasattr(name, "shape"): index_error = IndexError("number of indices does not match shape of the array") if len(indices) != len(name.shape): raise index_error if any((i >= s) == True for i, s in zip(indices, name.shape)): raise ValueError("shape is out of bounds") if any((i < 0) == True for i in indices): raise ValueError("shape contains negative values") @property def name(self): return self._args[0] @property def indices(self): return self._args[1] def _eval_derivative(self, s): if not isinstance(s, ArrayElement): return S.Zero if s == self: return S.One if s.name != self.name: return S.Zero return Mul.fromiter(KroneckerDelta(i, j) for i, j in zip(self.indices, s.indices)) class ZeroArray(_ArrayExpr): """ Symbolic array of zeros. Equivalent to ``ZeroMatrix`` for matrices. """ def __new__(cls, *shape): if len(shape) == 0: return S.Zero shape = map(_sympify, shape) obj = Expr.__new__(cls, *shape) return obj @property def shape(self): return self._args def as_explicit(self): if not all(i.is_Integer for i in self.shape): raise ValueError("Cannot return explicit form for symbolic shape.") return ImmutableDenseNDimArray.zeros(*self.shape) def _get(self, item): return S.Zero class OneArray(_ArrayExpr): """ Symbolic array of ones. """ def __new__(cls, *shape): if len(shape) == 0: return S.One shape = map(_sympify, shape) obj = Expr.__new__(cls, *shape) return obj @property def shape(self): return self._args def as_explicit(self): if not all(i.is_Integer for i in self.shape): raise ValueError("Cannot return explicit form for symbolic shape.") return ImmutableDenseNDimArray([S.One for i in range(reduce(operator.mul, self.shape))]).reshape(*self.shape) def _get(self, item): return S.One class _CodegenArrayAbstract(Basic): @property def subranks(self): """ Returns the ranks of the objects in the uppermost tensor product inside the current object. In case no tensor products are contained, return the atomic ranks. Examples ======== >>> from sympy.tensor.array import tensorproduct, tensorcontraction >>> from sympy import MatrixSymbol >>> M = MatrixSymbol("M", 3, 3) >>> N = MatrixSymbol("N", 3, 3) >>> P = MatrixSymbol("P", 3, 3) Important: do not confuse the rank of the matrix with the rank of an array. >>> tp = tensorproduct(M, N, P) >>> tp.subranks [2, 2, 2] >>> co = tensorcontraction(tp, (1, 2), (3, 4)) >>> co.subranks [2, 2, 2] """ return self._subranks[:] def subrank(self): """ The sum of ``subranks``. """ return sum(self.subranks) @property def shape(self): return self._shape def doit(self, **hints): deep = hints.get("deep", True) if deep: return self.func(*[arg.doit(**hints) for arg in self.args])._canonicalize() else: return self._canonicalize() class ArrayTensorProduct(_CodegenArrayAbstract): r""" Class to represent the tensor product of array-like objects. """ def __new__(cls, *args, **kwargs): args = [_sympify(arg) for arg in args] canonicalize = kwargs.pop("canonicalize", False) ranks = [get_rank(arg) for arg in args] obj = Basic.__new__(cls, *args) obj._subranks = ranks shapes = [get_shape(i) for i in args] if any(i is None for i in shapes): obj._shape = None else: obj._shape = tuple(j for i in shapes for j in i) if canonicalize: return obj._canonicalize() return obj def _canonicalize(self): args = self.args args = self._flatten(args) ranks = [get_rank(arg) for arg in args] # Check if there are nested permutation and lift them up: permutation_cycles = [] for i, arg in enumerate(args): if not isinstance(arg, PermuteDims): continue permutation_cycles.extend([[k + sum(ranks[:i]) for k in j] for j in arg.permutation.cyclic_form]) args[i] = arg.expr if permutation_cycles: return _permute_dims(_array_tensor_product(*args), Permutation(sum(ranks)-1)*Permutation(permutation_cycles)) if len(args) == 1: return args[0] # If any object is a ZeroArray, return a ZeroArray: if any(isinstance(arg, (ZeroArray, ZeroMatrix)) for arg in args): shapes = reduce(operator.add, [get_shape(i) for i in args], ()) return ZeroArray(*shapes) # If there are contraction objects inside, transform the whole # expression into `ArrayContraction`: contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayContraction)} if contractions: ranks = [_get_subrank(arg) if isinstance(arg, ArrayContraction) else get_rank(arg) for arg in args] cumulative_ranks = list(accumulate([0] + ranks))[:-1] tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayContraction) else arg for arg in args]) contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices] return _array_contraction(tp, *contraction_indices) diagonals = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayDiagonal)} if diagonals: inverse_permutation = [] last_perm = [] ranks = [get_rank(arg) for arg in args] cumulative_ranks = list(accumulate([0] + ranks))[:-1] for i, arg in enumerate(args): if isinstance(arg, ArrayDiagonal): i1 = get_rank(arg) - len(arg.diagonal_indices) i2 = len(arg.diagonal_indices) inverse_permutation.extend([cumulative_ranks[i] + j for j in range(i1)]) last_perm.extend([cumulative_ranks[i] + j for j in range(i1, i1 + i2)]) else: inverse_permutation.extend([cumulative_ranks[i] + j for j in range(get_rank(arg))]) inverse_permutation.extend(last_perm) tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayDiagonal) else arg for arg in args]) ranks2 = [_get_subrank(arg) if isinstance(arg, ArrayDiagonal) else get_rank(arg) for arg in args] cumulative_ranks2 = list(accumulate([0] + ranks2))[:-1] diagonal_indices = [tuple(cumulative_ranks2[i] + k for k in j) for i, arg in diagonals.items() for j in arg.diagonal_indices] return _permute_dims(_array_diagonal(tp, *diagonal_indices), _af_invert(inverse_permutation)) return self.func(*args, canonicalize=False) @classmethod def _flatten(cls, args): args = [i for arg in args for i in (arg.args if isinstance(arg, cls) else [arg])] return args def as_explicit(self): return tensorproduct(*[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args]) class ArrayAdd(_CodegenArrayAbstract): r""" Class for elementwise array additions. """ def __new__(cls, *args, **kwargs): args = [_sympify(arg) for arg in args] ranks = [get_rank(arg) for arg in args] ranks = list(set(ranks)) if len(ranks) != 1: raise ValueError("summing arrays of different ranks") shapes = [arg.shape for arg in args] if len({i for i in shapes if i is not None}) > 1: raise ValueError("mismatching shapes in addition") canonicalize = kwargs.pop("canonicalize", False) obj = Basic.__new__(cls, *args) obj._subranks = ranks if any(i is None for i in shapes): obj._shape = None else: obj._shape = shapes[0] if canonicalize: return obj._canonicalize() return obj def _canonicalize(self): args = self.args # Flatten: args = self._flatten_args(args) shapes = [get_shape(arg) for arg in args] args = [arg for arg in args if not isinstance(arg, (ZeroArray, ZeroMatrix))] if len(args) == 0: if any(i for i in shapes if i is None): raise NotImplementedError("cannot handle addition of ZeroMatrix/ZeroArray and undefined shape object") return ZeroArray(*shapes[0]) elif len(args) == 1: return args[0] return self.func(*args, canonicalize=False) @classmethod def _flatten_args(cls, args): new_args = [] for arg in args: if isinstance(arg, ArrayAdd): new_args.extend(arg.args) else: new_args.append(arg) return new_args def as_explicit(self): return reduce( operator.add, [arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args]) class PermuteDims(_CodegenArrayAbstract): r""" Class to represent permutation of axes of arrays. Examples ======== >>> from sympy.tensor.array import permutedims >>> from sympy import MatrixSymbol >>> M = MatrixSymbol("M", 3, 3) >>> cg = permutedims(M, [1, 0]) The object ``cg`` represents the transposition of ``M``, as the permutation ``[1, 0]`` will act on its indices by switching them: `M_{ij} \Rightarrow M_{ji}` This is evident when transforming back to matrix form: >>> from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix >>> convert_array_to_matrix(cg) M.T >>> N = MatrixSymbol("N", 3, 2) >>> cg = permutedims(N, [1, 0]) >>> cg.shape (2, 3) There are optional parameters that can be used as alternative to the permutation: >>> from sympy.tensor.array.expressions import ArraySymbol, PermuteDims >>> M = ArraySymbol("M", (1, 2, 3, 4, 5)) >>> expr = PermuteDims(M, index_order_old="ijklm", index_order_new="kijml") >>> expr PermuteDims(M, (0 2 1)(3 4)) >>> expr.shape (3, 1, 2, 5, 4) Permutations of tensor products are simplified in order to achieve a standard form: >>> from sympy.tensor.array import tensorproduct >>> M = MatrixSymbol("M", 4, 5) >>> tp = tensorproduct(M, N) >>> tp.shape (4, 5, 3, 2) >>> perm1 = permutedims(tp, [2, 3, 1, 0]) The args ``(M, N)`` have been sorted and the permutation has been simplified, the expression is equivalent: >>> perm1.expr.args (N, M) >>> perm1.shape (3, 2, 5, 4) >>> perm1.permutation (2 3) The permutation in its array form has been simplified from ``[2, 3, 1, 0]`` to ``[0, 1, 3, 2]``, as the arguments of the tensor product `M` and `N` have been switched: >>> perm1.permutation.array_form [0, 1, 3, 2] We can nest a second permutation: >>> perm2 = permutedims(perm1, [1, 0, 2, 3]) >>> perm2.shape (2, 3, 5, 4) >>> perm2.permutation.array_form [1, 0, 3, 2] """ def __new__(cls, expr, permutation=None, index_order_old=None, index_order_new=None, **kwargs): from sympy.combinatorics import Permutation expr = _sympify(expr) expr_rank = get_rank(expr) permutation = cls._get_permutation_from_arguments(permutation, index_order_old, index_order_new, expr_rank) permutation = Permutation(permutation) permutation_size = permutation.size if permutation_size != expr_rank: raise ValueError("Permutation size must be the length of the shape of expr") canonicalize = kwargs.pop("canonicalize", False) obj = Basic.__new__(cls, expr, permutation) obj._subranks = [get_rank(expr)] shape = get_shape(expr) if shape is None: obj._shape = None else: obj._shape = tuple(shape[permutation(i)] for i in range(len(shape))) if canonicalize: return obj._canonicalize() return obj def _canonicalize(self): expr = self.expr permutation = self.permutation if isinstance(expr, PermuteDims): subexpr = expr.expr subperm = expr.permutation permutation = permutation * subperm expr = subexpr if isinstance(expr, ArrayContraction): expr, permutation = self._PermuteDims_denestarg_ArrayContraction(expr, permutation) if isinstance(expr, ArrayTensorProduct): expr, permutation = self._PermuteDims_denestarg_ArrayTensorProduct(expr, permutation) if isinstance(expr, (ZeroArray, ZeroMatrix)): return ZeroArray(*[expr.shape[i] for i in permutation.array_form]) plist = permutation.array_form if plist == sorted(plist): return expr return self.func(expr, permutation, canonicalize=False) @property def expr(self): return self.args[0] @property def permutation(self): return self.args[1] @classmethod def _PermuteDims_denestarg_ArrayTensorProduct(cls, expr, permutation): # Get the permutation in its image-form: perm_image_form = _af_invert(permutation.array_form) args = list(expr.args) # Starting index global position for every arg: cumul = list(accumulate([0] + expr.subranks)) # Split `perm_image_form` into a list of list corresponding to the indices # of every argument: perm_image_form_in_components = [perm_image_form[cumul[i]:cumul[i+1]] for i in range(len(args))] # Create an index, target-position-key array: ps = [(i, sorted(comp)) for i, comp in enumerate(perm_image_form_in_components)] # Sort the array according to the target-position-key: # In this way, we define a canonical way to sort the arguments according # to the permutation. ps.sort(key=lambda x: x[1]) # Read the inverse-permutation (i.e. image-form) of the args: perm_args_image_form = [i[0] for i in ps] # Apply the args-permutation to the `args`: args_sorted = [args[i] for i in perm_args_image_form] # Apply the args-permutation to the array-form of the permutation of the axes (of `expr`): perm_image_form_sorted_args = [perm_image_form_in_components[i] for i in perm_args_image_form] new_permutation = Permutation(_af_invert([j for i in perm_image_form_sorted_args for j in i])) return _array_tensor_product(*args_sorted), new_permutation @classmethod def _PermuteDims_denestarg_ArrayContraction(cls, expr, permutation): if not isinstance(expr, ArrayContraction): return expr, permutation if not isinstance(expr.expr, ArrayTensorProduct): return expr, permutation args = expr.expr.args subranks = [get_rank(arg) for arg in expr.expr.args] contraction_indices = expr.contraction_indices contraction_indices_flat = [j for i in contraction_indices for j in i] cumul = list(accumulate([0] + subranks)) # Spread the permutation in its array form across the args in the corresponding # tensor-product arguments with free indices: permutation_array_blocks_up = [] image_form = _af_invert(permutation.array_form) counter = 0 for i, e in enumerate(subranks): current = [] for j in range(cumul[i], cumul[i+1]): if j in contraction_indices_flat: continue current.append(image_form[counter]) counter += 1 permutation_array_blocks_up.append(current) # Get the map of axis repositioning for every argument of tensor-product: index_blocks = [[j for j in range(cumul[i], cumul[i+1])] for i, e in enumerate(expr.subranks)] index_blocks_up = expr._push_indices_up(expr.contraction_indices, index_blocks) inverse_permutation = permutation**(-1) index_blocks_up_permuted = [[inverse_permutation(j) for j in i if j is not None] for i in index_blocks_up] # Sorting key is a list of tuple, first element is the index of `args`, second element of # the tuple is the sorting key to sort `args` of the tensor product: sorting_keys = list(enumerate(index_blocks_up_permuted)) sorting_keys.sort(key=lambda x: x[1]) # Now we can get the permutation acting on the args in its image-form: new_perm_image_form = [i[0] for i in sorting_keys] # Apply the args-level permutation to various elements: new_index_blocks = [index_blocks[i] for i in new_perm_image_form] new_index_perm_array_form = _af_invert([j for i in new_index_blocks for j in i]) new_args = [args[i] for i in new_perm_image_form] new_contraction_indices = [tuple(new_index_perm_array_form[j] for j in i) for i in contraction_indices] new_expr = _array_contraction(_array_tensor_product(*new_args), *new_contraction_indices) new_permutation = Permutation(_af_invert([j for i in [permutation_array_blocks_up[k] for k in new_perm_image_form] for j in i])) return new_expr, new_permutation @classmethod def _check_permutation_mapping(cls, expr, permutation): subranks = expr.subranks index2arg = [i for i, arg in enumerate(expr.args) for j in range(expr.subranks[i])] permuted_indices = [permutation(i) for i in range(expr.subrank())] new_args = list(expr.args) arg_candidate_index = index2arg[permuted_indices[0]] current_indices = [] new_permutation = [] inserted_arg_cand_indices = set([]) for i, idx in enumerate(permuted_indices): if index2arg[idx] != arg_candidate_index: new_permutation.extend(current_indices) current_indices = [] arg_candidate_index = index2arg[idx] current_indices.append(idx) arg_candidate_rank = subranks[arg_candidate_index] if len(current_indices) == arg_candidate_rank: new_permutation.extend(sorted(current_indices)) local_current_indices = [j - min(current_indices) for j in current_indices] i1 = index2arg[i] new_args[i1] = _permute_dims(new_args[i1], Permutation(local_current_indices)) inserted_arg_cand_indices.add(arg_candidate_index) current_indices = [] new_permutation.extend(current_indices) # TODO: swap args positions in order to simplify the expression: # TODO: this should be in a function args_positions = list(range(len(new_args))) # Get possible shifts: maps = {} cumulative_subranks = [0] + list(accumulate(subranks)) for i in range(len(subranks)): s = set([index2arg[new_permutation[j]] for j in range(cumulative_subranks[i], cumulative_subranks[i+1])]) if len(s) != 1: continue elem = next(iter(s)) if i != elem: maps[i] = elem # Find cycles in the map: lines = [] current_line = [] while maps: if len(current_line) == 0: k, v = maps.popitem() current_line.append(k) else: k = current_line[-1] if k not in maps: current_line = [] continue v = maps.pop(k) if v in current_line: lines.append(current_line) current_line = [] continue current_line.append(v) for line in lines: for i, e in enumerate(line): args_positions[line[(i + 1) % len(line)]] = e # TODO: function in order to permute the args: permutation_blocks = [[new_permutation[cumulative_subranks[i] + j] for j in range(e)] for i, e in enumerate(subranks)] new_args = [new_args[i] for i in args_positions] new_permutation_blocks = [permutation_blocks[i] for i in args_positions] new_permutation2 = [j for i in new_permutation_blocks for j in i] return _array_tensor_product(*new_args), Permutation(new_permutation2) # **(-1) @classmethod def _check_if_there_are_closed_cycles(cls, expr, permutation): args = list(expr.args) subranks = expr.subranks cyclic_form = permutation.cyclic_form cumulative_subranks = [0] + list(accumulate(subranks)) cyclic_min = [min(i) for i in cyclic_form] cyclic_max = [max(i) for i in cyclic_form] cyclic_keep = [] for i, cycle in enumerate(cyclic_form): flag = True for j in range(len(cumulative_subranks) - 1): if cyclic_min[i] >= cumulative_subranks[j] and cyclic_max[i] < cumulative_subranks[j+1]: # Found a sinkable cycle. args[j] = _permute_dims(args[j], Permutation([[k - cumulative_subranks[j] for k in cyclic_form[i]]])) flag = False break if flag: cyclic_keep.append(cyclic_form[i]) return _array_tensor_product(*args), Permutation(cyclic_keep, size=permutation.size) def nest_permutation(self): r""" DEPRECATED. """ ret = self._nest_permutation(self.expr, self.permutation) if ret is None: return self return ret @classmethod def _nest_permutation(cls, expr, permutation): if isinstance(expr, ArrayTensorProduct): return _permute_dims(*cls._check_if_there_are_closed_cycles(expr, permutation)) elif isinstance(expr, ArrayContraction): # Invert tree hierarchy: put the contraction above. cycles = permutation.cyclic_form newcycles = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *cycles) newpermutation = Permutation(newcycles) new_contr_indices = [tuple(newpermutation(j) for j in i) for i in expr.contraction_indices] return _array_contraction(PermuteDims(expr.expr, newpermutation), *new_contr_indices) elif isinstance(expr, ArrayAdd): return _array_add(*[PermuteDims(arg, permutation) for arg in expr.args]) return None def as_explicit(self): expr = self.expr if hasattr(expr, "as_explicit"): expr = expr.as_explicit() return permutedims(expr, self.permutation) @classmethod def _get_permutation_from_arguments(cls, permutation, index_order_old, index_order_new, dim): if permutation is None: if index_order_new is None or index_order_old is None: raise ValueError("Permutation not defined") return PermuteDims._get_permutation_from_index_orders(index_order_old, index_order_new, dim) else: if index_order_new is not None: raise ValueError("index_order_new cannot be defined with permutation") if index_order_old is not None: raise ValueError("index_order_old cannot be defined with permutation") return permutation @classmethod def _get_permutation_from_index_orders(cls, index_order_old, index_order_new, dim): if len(set(index_order_new)) != dim: raise ValueError("wrong number of indices in index_order_new") if len(set(index_order_old)) != dim: raise ValueError("wrong number of indices in index_order_old") if len(set.symmetric_difference(set(index_order_new), set(index_order_old))) > 0: raise ValueError("index_order_new and index_order_old must have the same indices") permutation = [index_order_old.index(i) for i in index_order_new] return permutation class ArrayDiagonal(_CodegenArrayAbstract): r""" Class to represent the diagonal operator. Explanation =========== In a 2-dimensional array it returns the diagonal, this looks like the operation: `A_{ij} \rightarrow A_{ii}` The diagonal over axes 1 and 2 (the second and third) of the tensor product of two 2-dimensional arrays `A \otimes B` is `\Big[ A_{ab} B_{cd} \Big]_{abcd} \rightarrow \Big[ A_{ai} B_{id} \Big]_{adi}` In this last example the array expression has been reduced from 4-dimensional to 3-dimensional. Notice that no contraction has occurred, rather there is a new index `i` for the diagonal, contraction would have reduced the array to 2 dimensions. Notice that the diagonalized out dimensions are added as new dimensions at the end of the indices. """ def __new__(cls, expr, *diagonal_indices, **kwargs): expr = _sympify(expr) diagonal_indices = [Tuple(*sorted(i)) for i in diagonal_indices] canonicalize = kwargs.get("canonicalize", False) shape = get_shape(expr) if shape is not None: cls._validate(expr, *diagonal_indices, **kwargs) # Get new shape: positions, shape = cls._get_positions_shape(shape, diagonal_indices) else: positions = None if len(diagonal_indices) == 0: return expr obj = Basic.__new__(cls, expr, *diagonal_indices) obj._positions = positions obj._subranks = _get_subranks(expr) obj._shape = shape if canonicalize: return obj._canonicalize() return obj def _canonicalize(self): expr = self.expr diagonal_indices = self.diagonal_indices trivial_diags = [i for i in diagonal_indices if len(i) == 1] if len(trivial_diags) > 0: trivial_pos = {e[0]: i for i, e in enumerate(diagonal_indices) if len(e) == 1} diag_pos = {e: i for i, e in enumerate(diagonal_indices) if len(e) > 1} diagonal_indices_short = [i for i in diagonal_indices if len(i) > 1] rank1 = get_rank(self) rank2 = len(diagonal_indices) rank3 = rank1 - rank2 inv_permutation = [] counter1: int = 0 indices_down = ArrayDiagonal._push_indices_down(diagonal_indices_short, list(range(rank1)), get_rank(expr)) for i in indices_down: if i in trivial_pos: inv_permutation.append(rank3 + trivial_pos[i]) elif isinstance(i, (Integer, int)): inv_permutation.append(counter1) counter1 += 1 else: inv_permutation.append(rank3 + diag_pos[i]) permutation = _af_invert(inv_permutation) if len(diagonal_indices_short) > 0: return _permute_dims(_array_diagonal(expr, *diagonal_indices_short), permutation) else: return _permute_dims(expr, permutation) if isinstance(expr, ArrayAdd): return self._ArrayDiagonal_denest_ArrayAdd(expr, *diagonal_indices) if isinstance(expr, ArrayDiagonal): return self._ArrayDiagonal_denest_ArrayDiagonal(expr, *diagonal_indices) if isinstance(expr, PermuteDims): return self._ArrayDiagonal_denest_PermuteDims(expr, *diagonal_indices) if isinstance(expr, (ZeroArray, ZeroMatrix)): positions, shape = self._get_positions_shape(expr.shape, diagonal_indices) return ZeroArray(*shape) return self.func(expr, *diagonal_indices, canonicalize=False) @staticmethod def _validate(expr, *diagonal_indices, **kwargs): # Check that no diagonalization happens on indices with mismatched # dimensions: shape = get_shape(expr) for i in diagonal_indices: if any(j >= len(shape) for j in i): raise ValueError("index is larger than expression shape") if len({shape[j] for j in i}) != 1: raise ValueError("diagonalizing indices of different dimensions") if not kwargs.get("allow_trivial_diags", False) and len(i) <= 1: raise ValueError("need at least two axes to diagonalize") if len(set(i)) != len(i): raise ValueError("axis index cannot be repeated") @staticmethod def _remove_trivial_dimensions(shape, *diagonal_indices): return [tuple(j for j in i) for i in diagonal_indices if shape[i[0]] != 1] @property def expr(self): return self.args[0] @property def diagonal_indices(self): return self.args[1:] @staticmethod def _flatten(expr, *outer_diagonal_indices): inner_diagonal_indices = expr.diagonal_indices all_inner = [j for i in inner_diagonal_indices for j in i] all_inner.sort() # TODO: add API for total rank and cumulative rank: total_rank = _get_subrank(expr) inner_rank = len(all_inner) outer_rank = total_rank - inner_rank shifts = [0 for i in range(outer_rank)] counter = 0 pointer = 0 for i in range(outer_rank): while pointer < inner_rank and counter >= all_inner[pointer]: counter += 1 pointer += 1 shifts[i] += pointer counter += 1 outer_diagonal_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_diagonal_indices) diagonal_indices = inner_diagonal_indices + outer_diagonal_indices return _array_diagonal(expr.expr, *diagonal_indices) @classmethod def _ArrayDiagonal_denest_ArrayAdd(cls, expr, *diagonal_indices): return _array_add(*[_array_diagonal(arg, *diagonal_indices) for arg in expr.args]) @classmethod def _ArrayDiagonal_denest_ArrayDiagonal(cls, expr, *diagonal_indices): return cls._flatten(expr, *diagonal_indices) @classmethod def _ArrayDiagonal_denest_PermuteDims(cls, expr: PermuteDims, *diagonal_indices): back_diagonal_indices = [[expr.permutation(j) for j in i] for i in diagonal_indices] nondiag = [i for i in range(get_rank(expr)) if not any(i in j for j in diagonal_indices)] back_nondiag = [expr.permutation(i) for i in nondiag] remap = {e: i for i, e in enumerate(sorted(back_nondiag))} new_permutation1 = [remap[i] for i in back_nondiag] shift = len(new_permutation1) diag_block_perm = [i + shift for i in range(len(back_diagonal_indices))] new_permutation = new_permutation1 + diag_block_perm return _permute_dims( _array_diagonal( expr.expr, *back_diagonal_indices ), new_permutation ) def _push_indices_down_nonstatic(self, indices): transform = lambda x: self._positions[x] if x < len(self._positions) else None return _apply_recursively_over_nested_lists(transform, indices) def _push_indices_up_nonstatic(self, indices): def transform(x): for i, e in enumerate(self._positions): if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e): return i return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _push_indices_down(cls, diagonal_indices, indices, rank): positions, shape = cls._get_positions_shape(range(rank), diagonal_indices) transform = lambda x: positions[x] if x < len(positions) else None return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _push_indices_up(cls, diagonal_indices, indices, rank): positions, shape = cls._get_positions_shape(range(rank), diagonal_indices) def transform(x): for i, e in enumerate(positions): if (isinstance(e, int) and x == e) or (isinstance(e, (tuple, Tuple)) and (x in e)): return i return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _get_positions_shape(cls, shape, diagonal_indices): data1 = tuple((i, shp) for i, shp in enumerate(shape) if not any(i in j for j in diagonal_indices)) pos1, shp1 = zip(*data1) if data1 else ((), ()) data2 = tuple((i, shape[i[0]]) for i in diagonal_indices) pos2, shp2 = zip(*data2) if data2 else ((), ()) positions = pos1 + pos2 shape = shp1 + shp2 return positions, shape def as_explicit(self): expr = self.expr if hasattr(expr, "as_explicit"): expr = expr.as_explicit() return tensordiagonal(expr, *self.diagonal_indices) class ArrayElementwiseApplyFunc(_CodegenArrayAbstract): def __new__(cls, function, element): if not isinstance(function, Lambda): d = Dummy('d') function = Lambda(d, function(d)) obj = _CodegenArrayAbstract.__new__(cls, function, element) obj._subranks = _get_subranks(element) return obj @property def function(self): return self.args[0] @property def expr(self): return self.args[1] @property def shape(self): return self.expr.shape def _get_function_fdiff(self): d = Dummy("d") function = self.function(d) fdiff = function.diff(d) if isinstance(fdiff, Function): fdiff = type(fdiff) else: fdiff = Lambda(d, fdiff) return fdiff def as_explicit(self): expr = self.expr if hasattr(expr, "as_explicit"): expr = expr.as_explicit() return expr.applyfunc(self.function) class ArrayContraction(_CodegenArrayAbstract): r""" This class is meant to represent contractions of arrays in a form easily processable by the code printers. """ def __new__(cls, expr, *contraction_indices, **kwargs): contraction_indices = _sort_contraction_indices(contraction_indices) expr = _sympify(expr) canonicalize = kwargs.get("canonicalize", False) obj = Basic.__new__(cls, expr, *contraction_indices) obj._subranks = _get_subranks(expr) obj._mapping = _get_mapping_from_subranks(obj._subranks) free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all(i not in cind for cind in contraction_indices)} obj._free_indices_to_position = free_indices_to_position shape = get_shape(expr) cls._validate(expr, *contraction_indices) if shape: shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices)) obj._shape = shape if canonicalize: return obj._canonicalize() return obj def _canonicalize(self): expr = self.expr contraction_indices = self.contraction_indices if len(contraction_indices) == 0: return expr if isinstance(expr, ArrayContraction): return self._ArrayContraction_denest_ArrayContraction(expr, *contraction_indices) if isinstance(expr, (ZeroArray, ZeroMatrix)): return self._ArrayContraction_denest_ZeroArray(expr, *contraction_indices) if isinstance(expr, PermuteDims): return self._ArrayContraction_denest_PermuteDims(expr, *contraction_indices) if isinstance(expr, ArrayTensorProduct): expr, contraction_indices = self._sort_fully_contracted_args(expr, contraction_indices) expr, contraction_indices = self._lower_contraction_to_addends(expr, contraction_indices) if len(contraction_indices) == 0: return expr if isinstance(expr, ArrayDiagonal): return self._ArrayContraction_denest_ArrayDiagonal(expr, *contraction_indices) if isinstance(expr, ArrayAdd): return self._ArrayContraction_denest_ArrayAdd(expr, *contraction_indices) # Check single index contractions on 1-dimensional axes: contraction_indices = [i for i in contraction_indices if len(i) > 1 or get_shape(expr)[i[0]] != 1] if len(contraction_indices) == 0: return expr return self.func(expr, *contraction_indices, canonicalize=False) def __mul__(self, other): if other == 1: return self else: raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.") def __rmul__(self, other): if other == 1: return self else: raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.") @staticmethod def _validate(expr, *contraction_indices): shape = get_shape(expr) if shape is None: return # Check that no contraction happens when the shape is mismatched: for i in contraction_indices: if len({shape[j] for j in i if shape[j] != -1}) != 1: raise ValueError("contracting indices of different dimensions") @classmethod def _push_indices_down(cls, contraction_indices, indices): flattened_contraction_indices = [j for i in contraction_indices for j in i] flattened_contraction_indices.sort() transform = _build_push_indices_down_func_transformation(flattened_contraction_indices) return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _push_indices_up(cls, contraction_indices, indices): flattened_contraction_indices = [j for i in contraction_indices for j in i] flattened_contraction_indices.sort() transform = _build_push_indices_up_func_transformation(flattened_contraction_indices) return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _lower_contraction_to_addends(cls, expr, contraction_indices): if isinstance(expr, ArrayAdd): raise NotImplementedError() if not isinstance(expr, ArrayTensorProduct): return expr, contraction_indices subranks = expr.subranks cumranks = list(accumulate([0] + subranks)) contraction_indices_remaining = [] contraction_indices_args = [[] for i in expr.args] backshift = set([]) for i, contraction_group in enumerate(contraction_indices): for j in range(len(expr.args)): if not isinstance(expr.args[j], ArrayAdd): continue if all(cumranks[j] <= k < cumranks[j+1] for k in contraction_group): contraction_indices_args[j].append([k - cumranks[j] for k in contraction_group]) backshift.update(contraction_group) break else: contraction_indices_remaining.append(contraction_group) if len(contraction_indices_remaining) == len(contraction_indices): return expr, contraction_indices total_rank = get_rank(expr) shifts = list(accumulate([1 if i in backshift else 0 for i in range(total_rank)])) contraction_indices_remaining = [Tuple.fromiter(j - shifts[j] for j in i) for i in contraction_indices_remaining] ret = _array_tensor_product(*[ _array_contraction(arg, *contr) for arg, contr in zip(expr.args, contraction_indices_args) ]) return ret, contraction_indices_remaining def split_multiple_contractions(self): """ Recognize multiple contractions and attempt at rewriting them as paired-contractions. This allows some contractions involving more than two indices to be rewritten as multiple contractions involving two indices, thus allowing the expression to be rewritten as a matrix multiplication line. Examples: * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C` Care for: - matrix being diagonalized (i.e. `A_ii`) - vectors being diagonalized (i.e. `a_i0`) Multiple contractions can be split into matrix multiplications if not more than two arguments are non-diagonals or non-vectors. Vectors get diagonalized while diagonal matrices remain diagonal. The non-diagonal matrices can be at the beginning or at the end of the final matrix multiplication line. """ editor = _EditArrayContraction(self) contraction_indices = self.contraction_indices onearray_insert = [] for indl, links in enumerate(contraction_indices): if len(links) <= 2: continue # Check multiple contractions: # # Examples: # # * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C \otimes OneArray(1)` with permutation (1 2) # # Care for: # - matrix being diagonalized (i.e. `A_ii`) # - vectors being diagonalized (i.e. `a_i0`) # Multiple contractions can be split into matrix multiplications if # not more than three arguments are non-diagonals or non-vectors. # # Vectors get diagonalized while diagonal matrices remain diagonal. # The non-diagonal matrices can be at the beginning or at the end # of the final matrix multiplication line. positions = editor.get_mapping_for_index(indl) # Also consider the case of diagonal matrices being contracted: current_dimension = self.expr.shape[links[0]] not_vectors: tTuple[_ArgE, int] = [] vectors: tTuple[_ArgE, int] = [] for arg_ind, rel_ind in positions: arg = editor.args_with_ind[arg_ind] mat = arg.element abs_arg_start, abs_arg_end = editor.get_absolute_range(arg) other_arg_pos = 1-rel_ind other_arg_abs = abs_arg_start + other_arg_pos if ((1 not in mat.shape) or ((current_dimension == 1) is True and mat.shape != (1, 1)) or any(other_arg_abs in l for li, l in enumerate(contraction_indices) if li != indl) ): not_vectors.append((arg, rel_ind)) else: vectors.append((arg, rel_ind)) if len(not_vectors) > 2: # If more than two arguments in the multiple contraction are # non-vectors and non-diagonal matrices, we cannot find a way # to split this contraction into a matrix multiplication line: continue # Three cases to handle: # - zero non-vectors # - one non-vector # - two non-vectors for v, rel_ind in vectors: v.element = diagonalize_vector(v.element) vectors_to_loop = not_vectors[:1] + vectors + not_vectors[1:] first_not_vector, rel_ind = vectors_to_loop[0] new_index = first_not_vector.indices[rel_ind] for v, rel_ind in vectors_to_loop[1:-1]: v.indices[rel_ind] = new_index new_index = editor.get_new_contraction_index() assert v.indices.index(None) == 1 - rel_ind v.indices[v.indices.index(None)] = new_index onearray_insert.append(v) last_vec, rel_ind = vectors_to_loop[-1] last_vec.indices[rel_ind] = new_index for v in onearray_insert: editor.insert_after(v, _ArgE(OneArray(1), [None])) return editor.to_array_contraction() def flatten_contraction_of_diagonal(self): if not isinstance(self.expr, ArrayDiagonal): return self contraction_down = self.expr._push_indices_down(self.expr.diagonal_indices, self.contraction_indices) new_contraction_indices = [] diagonal_indices = self.expr.diagonal_indices[:] for i in contraction_down: contraction_group = list(i) for j in i: diagonal_with = [k for k in diagonal_indices if j in k] contraction_group.extend([l for k in diagonal_with for l in k]) diagonal_indices = [k for k in diagonal_indices if k not in diagonal_with] new_contraction_indices.append(sorted(set(contraction_group))) new_contraction_indices = ArrayDiagonal._push_indices_up(diagonal_indices, new_contraction_indices) return _array_contraction( _array_diagonal( self.expr.expr, *diagonal_indices ), *new_contraction_indices ) @staticmethod def _get_free_indices_to_position_map(free_indices, contraction_indices): free_indices_to_position = {} flattened_contraction_indices = [j for i in contraction_indices for j in i] counter = 0 for ind in free_indices: while counter in flattened_contraction_indices: counter += 1 free_indices_to_position[ind] = counter counter += 1 return free_indices_to_position @staticmethod def _get_index_shifts(expr): """ Get the mapping of indices at the positions before the contraction occurs. Examples ======== >>> from sympy.tensor.array import tensorproduct, tensorcontraction >>> from sympy import MatrixSymbol >>> M = MatrixSymbol("M", 3, 3) >>> N = MatrixSymbol("N", 3, 3) >>> cg = tensorcontraction(tensorproduct(M, N), [1, 2]) >>> cg._get_index_shifts(cg) [0, 2] Indeed, ``cg`` after the contraction has two dimensions, 0 and 1. They need to be shifted by 0 and 2 to get the corresponding positions before the contraction (that is, 0 and 3). """ inner_contraction_indices = expr.contraction_indices all_inner = [j for i in inner_contraction_indices for j in i] all_inner.sort() # TODO: add API for total rank and cumulative rank: total_rank = _get_subrank(expr) inner_rank = len(all_inner) outer_rank = total_rank - inner_rank shifts = [0 for i in range(outer_rank)] counter = 0 pointer = 0 for i in range(outer_rank): while pointer < inner_rank and counter >= all_inner[pointer]: counter += 1 pointer += 1 shifts[i] += pointer counter += 1 return shifts @staticmethod def _convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices): shifts = ArrayContraction._get_index_shifts(expr) outer_contraction_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_contraction_indices) return outer_contraction_indices @staticmethod def _flatten(expr, *outer_contraction_indices): inner_contraction_indices = expr.contraction_indices outer_contraction_indices = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices) contraction_indices = inner_contraction_indices + outer_contraction_indices return _array_contraction(expr.expr, *contraction_indices) @classmethod def _ArrayContraction_denest_ArrayContraction(cls, expr, *contraction_indices): return cls._flatten(expr, *contraction_indices) @classmethod def _ArrayContraction_denest_ZeroArray(cls, expr, *contraction_indices): contraction_indices_flat = [j for i in contraction_indices for j in i] shape = [e for i, e in enumerate(expr.shape) if i not in contraction_indices_flat] return ZeroArray(*shape) @classmethod def _ArrayContraction_denest_ArrayAdd(cls, expr, *contraction_indices): return _array_add(*[_array_contraction(i, *contraction_indices) for i in expr.args]) @classmethod def _ArrayContraction_denest_PermuteDims(cls, expr, *contraction_indices): permutation = expr.permutation plist = permutation.array_form new_contraction_indices = [tuple(permutation(j) for j in i) for i in contraction_indices] new_plist = [i for i in plist if not any(i in j for j in new_contraction_indices)] new_plist = cls._push_indices_up(new_contraction_indices, new_plist) return _permute_dims( _array_contraction(expr.expr, *new_contraction_indices), Permutation(new_plist) ) @classmethod def _ArrayContraction_denest_ArrayDiagonal(cls, expr: 'ArrayDiagonal', *contraction_indices): diagonal_indices = list(expr.diagonal_indices) down_contraction_indices = expr._push_indices_down(expr.diagonal_indices, contraction_indices, get_rank(expr.expr)) # Flatten diagonally contracted indices: down_contraction_indices = [[k for j in i for k in (j if isinstance(j, (tuple, Tuple)) else [j])] for i in down_contraction_indices] new_contraction_indices = [] for contr_indgrp in down_contraction_indices: ind = contr_indgrp[:] for j, diag_indgrp in enumerate(diagonal_indices): if diag_indgrp is None: continue if any(i in diag_indgrp for i in contr_indgrp): ind.extend(diag_indgrp) diagonal_indices[j] = None new_contraction_indices.append(sorted(set(ind))) new_diagonal_indices_down = [i for i in diagonal_indices if i is not None] new_diagonal_indices = ArrayContraction._push_indices_up(new_contraction_indices, new_diagonal_indices_down) return _array_diagonal( _array_contraction(expr.expr, *new_contraction_indices), *new_diagonal_indices ) @classmethod def _sort_fully_contracted_args(cls, expr, contraction_indices): if expr.shape is None: return expr, contraction_indices cumul = list(accumulate([0] + expr.subranks)) index_blocks = [list(range(cumul[i], cumul[i+1])) for i in range(len(expr.args))] contraction_indices_flat = {j for i in contraction_indices for j in i} fully_contracted = [all(j in contraction_indices_flat for j in range(cumul[i], cumul[i+1])) for i, arg in enumerate(expr.args)] new_pos = sorted(range(len(expr.args)), key=lambda x: (0, default_sort_key(expr.args[x])) if fully_contracted[x] else (1,)) new_args = [expr.args[i] for i in new_pos] new_index_blocks_flat = [j for i in new_pos for j in index_blocks[i]] index_permutation_array_form = _af_invert(new_index_blocks_flat) new_contraction_indices = [tuple(index_permutation_array_form[j] for j in i) for i in contraction_indices] new_contraction_indices = _sort_contraction_indices(new_contraction_indices) return _array_tensor_product(*new_args), new_contraction_indices def _get_contraction_tuples(self): r""" Return tuples containing the argument index and position within the argument of the index position. Examples ======== >>> from sympy import MatrixSymbol >>> from sympy.abc import N >>> from sympy.tensor.array import tensorproduct, tensorcontraction >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> cg = tensorcontraction(tensorproduct(A, B), (1, 2)) >>> cg._get_contraction_tuples() [[(0, 1), (1, 0)]] Notes ===== Here the contraction pair `(1, 2)` meaning that the 2nd and 3rd indices of the tensor product `A\otimes B` are contracted, has been transformed into `(0, 1)` and `(1, 0)`, identifying the same indices in a different notation. `(0, 1)` is the second index (1) of the first argument (i.e. 0 or `A`). `(1, 0)` is the first index (i.e. 0) of the second argument (i.e. 1 or `B`). """ mapping = self._mapping return [[mapping[j] for j in i] for i in self.contraction_indices] @staticmethod def _contraction_tuples_to_contraction_indices(expr, contraction_tuples): # TODO: check that `expr` has `.subranks`: ranks = expr.subranks cumulative_ranks = [0] + list(accumulate(ranks)) return [tuple(cumulative_ranks[j]+k for j, k in i) for i in contraction_tuples] @property def free_indices(self): return self._free_indices[:] @property def free_indices_to_position(self): return dict(self._free_indices_to_position) @property def expr(self): return self.args[0] @property def contraction_indices(self): return self.args[1:] def _contraction_indices_to_components(self): expr = self.expr if not isinstance(expr, ArrayTensorProduct): raise NotImplementedError("only for contractions of tensor products") ranks = expr.subranks mapping = {} counter = 0 for i, rank in enumerate(ranks): for j in range(rank): mapping[counter] = (i, j) counter += 1 return mapping def sort_args_by_name(self): """ Sort arguments in the tensor product so that their order is lexicographical. Examples ======== >>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array >>> from sympy import MatrixSymbol >>> from sympy.abc import N >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> C = MatrixSymbol("C", N, N) >>> D = MatrixSymbol("D", N, N) >>> cg = convert_matrix_to_array(C*D*A*B) >>> cg ArrayContraction(ArrayTensorProduct(A, D, C, B), (0, 3), (1, 6), (2, 5)) >>> cg.sort_args_by_name() ArrayContraction(ArrayTensorProduct(A, D, B, C), (0, 3), (1, 4), (2, 7)) """ expr = self.expr if not isinstance(expr, ArrayTensorProduct): return self args = expr.args sorted_data = sorted(enumerate(args), key=lambda x: default_sort_key(x[1])) pos_sorted, args_sorted = zip(*sorted_data) reordering_map = {i: pos_sorted.index(i) for i, arg in enumerate(args)} contraction_tuples = self._get_contraction_tuples() contraction_tuples = [[(reordering_map[j], k) for j, k in i] for i in contraction_tuples] c_tp = _array_tensor_product(*args_sorted) new_contr_indices = self._contraction_tuples_to_contraction_indices( c_tp, contraction_tuples ) return _array_contraction(c_tp, *new_contr_indices) def _get_contraction_links(self): r""" Returns a dictionary of links between arguments in the tensor product being contracted. See the example for an explanation of the values. Examples ======== >>> from sympy import MatrixSymbol >>> from sympy.abc import N >>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> C = MatrixSymbol("C", N, N) >>> D = MatrixSymbol("D", N, N) Matrix multiplications are pairwise contractions between neighboring matrices: `A_{ij} B_{jk} C_{kl} D_{lm}` >>> cg = convert_matrix_to_array(A*B*C*D) >>> cg ArrayContraction(ArrayTensorProduct(B, C, A, D), (0, 5), (1, 2), (3, 6)) >>> cg._get_contraction_links() {0: {0: (2, 1), 1: (1, 0)}, 1: {0: (0, 1), 1: (3, 0)}, 2: {1: (0, 0)}, 3: {0: (1, 1)}} This dictionary is interpreted as follows: argument in position 0 (i.e. matrix `A`) has its second index (i.e. 1) contracted to `(1, 0)`, that is argument in position 1 (matrix `B`) on the first index slot of `B`, this is the contraction provided by the index `j` from `A`. The argument in position 1 (that is, matrix `B`) has two contractions, the ones provided by the indices `j` and `k`, respectively the first and second indices (0 and 1 in the sub-dict). The link `(0, 1)` and `(2, 0)` respectively. `(0, 1)` is the index slot 1 (the 2nd) of argument in position 0 (that is, `A_{\ldot j}`), and so on. """ args, dlinks = _get_contraction_links([self], self.subranks, *self.contraction_indices) return dlinks def as_explicit(self): expr = self.expr if hasattr(expr, "as_explicit"): expr = expr.as_explicit() return tensorcontraction(expr, *self.contraction_indices) class Reshape(_CodegenArrayAbstract): """ Reshape the dimensions of an array expression. Examples ======== >>> from sympy.tensor.array.expressions import ArraySymbol, Reshape >>> A = ArraySymbol("A", (6,)) >>> A.shape (6,) >>> Reshape(A, (3, 2)).shape (3, 2) Check the component-explicit forms: >>> A.as_explicit() [A[0], A[1], A[2], A[3], A[4], A[5]] >>> Reshape(A, (3, 2)).as_explicit() [[A[0], A[1]], [A[2], A[3]], [A[4], A[5]]] """ def __new__(cls, expr, shape): expr = _sympify(expr) if not isinstance(shape, Tuple): shape = Tuple(*shape) if Equality(Mul.fromiter(expr.shape), Mul.fromiter(shape)) == False: raise ValueError("shape mismatch") obj = Expr.__new__(cls, expr, shape) obj._shape = tuple(shape) obj._expr = expr return obj @property def shape(self): return self._shape @property def expr(self): return self._expr def doit(self, *args, **kwargs): if kwargs.get("deep", True): expr = self.expr.doit(*args, **kwargs) else: expr = self.expr if isinstance(expr, (MatrixCommon, NDimArray)): return expr.reshape(*self.shape) return Reshape(expr, self.shape) def as_explicit(self): ee = self.expr if hasattr(ee, "as_explicit"): ee = ee.as_explicit() if isinstance(ee, MatrixCommon): from sympy import Array ee = Array(ee) elif isinstance(ee, MatrixExpr): return self return ee.reshape(*self.shape) class _ArgE: """ The ``_ArgE`` object contains references to the array expression (``.element``) and a list containing the information about index contractions (``.indices``). Index contractions are numbered and contracted indices show the number of the contraction. Uncontracted indices have ``None`` value. For example: ``_ArgE(M, [None, 3])`` This object means that expression ``M`` is part of an array contraction and has two indices, the first is not contracted (value ``None``), the second index is contracted to the 4th (i.e. number ``3``) group of the array contraction object. """ indices: List[Optional[int]] def __init__(self, element, indices: Optional[List[Optional[int]]] = None): self.element = element if indices is None: self.indices = [None for i in range(get_rank(element))] else: self.indices = indices def __str__(self): return "_ArgE(%s, %s)" % (self.element, self.indices) __repr__ = __str__ class _IndPos: """ Index position, requiring two integers in the constructor: - arg: the position of the argument in the tensor product, - rel: the relative position of the index inside the argument. """ def __init__(self, arg: int, rel: int): self.arg = arg self.rel = rel def __str__(self): return "_IndPos(%i, %i)" % (self.arg, self.rel) __repr__ = __str__ def __iter__(self): yield from [self.arg, self.rel] class _EditArrayContraction: """ Utility class to help manipulate array contraction objects. This class takes as input an ``ArrayContraction`` object and turns it into an editable object. The field ``args_with_ind`` of this class is a list of ``_ArgE`` objects which can be used to easily edit the contraction structure of the expression. Once editing is finished, the ``ArrayContraction`` object may be recreated by calling the ``.to_array_contraction()`` method. """ def __init__(self, base_array: typing.Union[ArrayContraction, ArrayDiagonal, ArrayTensorProduct]): expr: Basic diagonalized: tTuple[tTuple[int, ...], ...] contraction_indices: List[tTuple[int]] if isinstance(base_array, ArrayContraction): mapping = _get_mapping_from_subranks(base_array.subranks) expr = base_array.expr contraction_indices = base_array.contraction_indices diagonalized = () elif isinstance(base_array, ArrayDiagonal): if isinstance(base_array.expr, ArrayContraction): mapping = _get_mapping_from_subranks(base_array.expr.subranks) expr = base_array.expr.expr diagonalized = ArrayContraction._push_indices_down(base_array.expr.contraction_indices, base_array.diagonal_indices) contraction_indices = base_array.expr.contraction_indices elif isinstance(base_array.expr, ArrayTensorProduct): mapping = {} expr = base_array.expr diagonalized = base_array.diagonal_indices contraction_indices = [] else: mapping = {} expr = base_array.expr diagonalized = base_array.diagonal_indices contraction_indices = [] elif isinstance(base_array, ArrayTensorProduct): expr = base_array contraction_indices = [] diagonalized = () else: raise NotImplementedError() if isinstance(expr, ArrayTensorProduct): args = list(expr.args) else: args = [expr] args_with_ind: List[_ArgE] = [_ArgE(arg) for arg in args] for i, contraction_tuple in enumerate(contraction_indices): for j in contraction_tuple: arg_pos, rel_pos = mapping[j] args_with_ind[arg_pos].indices[rel_pos] = i self.args_with_ind: List[_ArgE] = args_with_ind self.number_of_contraction_indices: int = len(contraction_indices) self._track_permutation: Optional[List[List[int]]] = None mapping = _get_mapping_from_subranks(base_array.subranks) # Trick: add diagonalized indices as negative indices into the editor object: for i, e in enumerate(diagonalized): for j in e: arg_pos, rel_pos = mapping[j] self.args_with_ind[arg_pos].indices[rel_pos] = -1 - i def insert_after(self, arg: _ArgE, new_arg: _ArgE): pos = self.args_with_ind.index(arg) self.args_with_ind.insert(pos + 1, new_arg) def get_new_contraction_index(self): self.number_of_contraction_indices += 1 return self.number_of_contraction_indices - 1 def refresh_indices(self): updates: tDict[int, int] = {} for arg_with_ind in self.args_with_ind: updates.update({i: -1 for i in arg_with_ind.indices if i is not None}) for i, e in enumerate(sorted(updates)): updates[e] = i self.number_of_contraction_indices: int = len(updates) for arg_with_ind in self.args_with_ind: arg_with_ind.indices = [updates.get(i, None) for i in arg_with_ind.indices] def merge_scalars(self): scalars = [] for arg_with_ind in self.args_with_ind: if len(arg_with_ind.indices) == 0: scalars.append(arg_with_ind) for i in scalars: self.args_with_ind.remove(i) scalar = Mul.fromiter([i.element for i in scalars]) if len(self.args_with_ind) == 0: self.args_with_ind.append(_ArgE(scalar)) else: from sympy.tensor.array.expressions.from_array_to_matrix import _a2m_tensor_product self.args_with_ind[0].element = _a2m_tensor_product(scalar, self.args_with_ind[0].element) def to_array_contraction(self): # Count the ranks of the arguments: counter = 0 # Create a collector for the new diagonal indices: diag_indices = defaultdict(list) count_index_freq = Counter() for arg_with_ind in self.args_with_ind: count_index_freq.update(Counter(arg_with_ind.indices)) free_index_count = count_index_freq[None] # Construct the inverse permutation: inv_perm1 = [] inv_perm2 = [] # Keep track of which diagonal indices have already been processed: done = set([]) # Counter for the diagonal indices: counter4 = 0 for arg_with_ind in self.args_with_ind: # If some diagonalization axes have been removed, they should be # permuted in order to keep the permutation. # Add permutation here counter2 = 0 # counter for the indices for i in arg_with_ind.indices: if i is None: inv_perm1.append(counter4) counter2 += 1 counter4 += 1 continue if i >= 0: continue # Reconstruct the diagonal indices: diag_indices[-1 - i].append(counter + counter2) if count_index_freq[i] == 1 and i not in done: inv_perm1.append(free_index_count - 1 - i) done.add(i) elif i not in done: inv_perm2.append(free_index_count - 1 - i) done.add(i) counter2 += 1 # Remove negative indices to restore a proper editor object: arg_with_ind.indices = [i if i is not None and i >= 0 else None for i in arg_with_ind.indices] counter += len([i for i in arg_with_ind.indices if i is None or i < 0]) inverse_permutation = inv_perm1 + inv_perm2 permutation = _af_invert(inverse_permutation) # Get the diagonal indices after the detection of HadamardProduct in the expression: diag_indices_filtered = [tuple(v) for v in diag_indices.values() if len(v) > 1] self.merge_scalars() self.refresh_indices() args = [arg.element for arg in self.args_with_ind] contraction_indices = self.get_contraction_indices() expr = _array_contraction(_array_tensor_product(*args), *contraction_indices) expr2 = _array_diagonal(expr, *diag_indices_filtered) if self._track_permutation is not None: permutation2 = _af_invert([j for i in self._track_permutation for j in i]) expr2 = _permute_dims(expr2, permutation2) expr3 = _permute_dims(expr2, permutation) return expr3 def get_contraction_indices(self) -> List[List[int]]: contraction_indices: List[List[int]] = [[] for i in range(self.number_of_contraction_indices)] current_position: int = 0 for i, arg_with_ind in enumerate(self.args_with_ind): for j in arg_with_ind.indices: if j is not None: contraction_indices[j].append(current_position) current_position += 1 return contraction_indices def get_mapping_for_index(self, ind) -> List[_IndPos]: if ind >= self.number_of_contraction_indices: raise ValueError("index value exceeding the index range") positions: List[_IndPos] = [] for i, arg_with_ind in enumerate(self.args_with_ind): for j, arg_ind in enumerate(arg_with_ind.indices): if ind == arg_ind: positions.append(_IndPos(i, j)) return positions def get_contraction_indices_to_ind_rel_pos(self) -> List[List[_IndPos]]: contraction_indices: List[List[_IndPos]] = [[] for i in range(self.number_of_contraction_indices)] for i, arg_with_ind in enumerate(self.args_with_ind): for j, ind in enumerate(arg_with_ind.indices): if ind is not None: contraction_indices[ind].append(_IndPos(i, j)) return contraction_indices def count_args_with_index(self, index: int) -> int: """ Count the number of arguments that have the given index. """ counter: int = 0 for arg_with_ind in self.args_with_ind: if index in arg_with_ind.indices: counter += 1 return counter def get_args_with_index(self, index: int) -> List[_ArgE]: """ Get a list of arguments having the given index. """ ret: List[_ArgE] = [i for i in self.args_with_ind if index in i.indices] return ret @property def number_of_diagonal_indices(self): data = set([]) for arg in self.args_with_ind: data.update({i for i in arg.indices if i is not None and i < 0}) return len(data) def track_permutation_start(self): permutation = [] perm_diag = [] counter: int = 0 counter2: int = -1 for arg_with_ind in self.args_with_ind: perm = [] for i in arg_with_ind.indices: if i is not None: if i < 0: perm_diag.append(counter2) counter2 -= 1 continue perm.append(counter) counter += 1 permutation.append(perm) max_ind = max([max(i) if i else -1 for i in permutation]) if permutation else -1 perm_diag = [max_ind - i for i in perm_diag] self._track_permutation = permutation + [perm_diag] def track_permutation_merge(self, destination: _ArgE, from_element: _ArgE): index_destination = self.args_with_ind.index(destination) index_element = self.args_with_ind.index(from_element) self._track_permutation[index_destination].extend(self._track_permutation[index_element]) # type: ignore self._track_permutation.pop(index_element) # type: ignore def get_absolute_free_range(self, arg: _ArgE) -> typing.Tuple[int, int]: """ Return the range of the free indices of the arg as absolute positions among all free indices. """ counter = 0 for arg_with_ind in self.args_with_ind: number_free_indices = len([i for i in arg_with_ind.indices if i is None]) if arg_with_ind == arg: return counter, counter + number_free_indices counter += number_free_indices raise IndexError("argument not found") def get_absolute_range(self, arg: _ArgE) -> typing.Tuple[int, int]: """ Return the absolute range of indices for arg, disregarding dummy indices. """ counter = 0 for arg_with_ind in self.args_with_ind: number_indices = len(arg_with_ind.indices) if arg_with_ind == arg: return counter, counter + number_indices counter += number_indices raise IndexError("argument not found") def get_rank(expr): if isinstance(expr, (MatrixExpr, MatrixElement)): return 2 if isinstance(expr, _CodegenArrayAbstract): return len(expr.shape) if isinstance(expr, NDimArray): return expr.rank() if isinstance(expr, Indexed): return expr.rank if isinstance(expr, IndexedBase): shape = expr.shape if shape is None: return -1 else: return len(shape) if hasattr(expr, "shape"): return len(expr.shape) return 0 def _get_subrank(expr): if isinstance(expr, _CodegenArrayAbstract): return expr.subrank() return get_rank(expr) def _get_subranks(expr): if isinstance(expr, _CodegenArrayAbstract): return expr.subranks else: return [get_rank(expr)] def get_shape(expr): if hasattr(expr, "shape"): return expr.shape return () def nest_permutation(expr): if isinstance(expr, PermuteDims): return expr.nest_permutation() else: return expr def _array_tensor_product(*args, **kwargs): return ArrayTensorProduct(*args, canonicalize=True, **kwargs) def _array_contraction(expr, *contraction_indices, **kwargs): return ArrayContraction(expr, *contraction_indices, canonicalize=True, **kwargs) def _array_diagonal(expr, *diagonal_indices, **kwargs): return ArrayDiagonal(expr, *diagonal_indices, canonicalize=True, **kwargs) def _permute_dims(expr, permutation, **kwargs): return PermuteDims(expr, permutation, canonicalize=True, **kwargs) def _array_add(*args, **kwargs): return ArrayAdd(*args, canonicalize=True, **kwargs) def _get_array_element_or_slice(expr, indices): return ArrayElement(expr, indices)
40ce654fbfc3ffc88d9bed391309240127bc9f156a523b3737b0ba0da80d3173
import operator from functools import reduce, singledispatch from sympy.core.expr import Expr from sympy.core.singleton import S from sympy.matrices.expressions.hadamard import HadamardProduct from sympy.matrices.expressions.inverse import Inverse from sympy.matrices.expressions.matexpr import (MatrixExpr, MatrixSymbol) from sympy.matrices.expressions.special import Identity from sympy.matrices.expressions.transpose import Transpose from sympy.combinatorics.permutations import _af_invert from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction from sympy.tensor.array.expressions.array_expressions import ( _ArrayExpr, ZeroArray, ArraySymbol, ArrayTensorProduct, ArrayAdd, PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, get_rank, get_shape, ArrayContraction, _array_tensor_product, _array_contraction, _array_diagonal, _array_add, _permute_dims, Reshape) from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array @singledispatch def array_derive(expr, x): raise NotImplementedError(f"not implemented for type {type(expr)}") @array_derive.register(Expr) def _(expr: Expr, x: _ArrayExpr): return ZeroArray(*x.shape) @array_derive.register(ArrayTensorProduct) def _(expr: ArrayTensorProduct, x: Expr): args = expr.args addend_list = [] for i, arg in enumerate(expr.args): darg = array_derive(arg, x) if darg == 0: continue args_prev = args[:i] args_succ = args[i+1:] shape_prev = reduce(operator.add, map(get_shape, args_prev), ()) shape_succ = reduce(operator.add, map(get_shape, args_succ), ()) addend = _array_tensor_product(*args_prev, darg, *args_succ) tot1 = len(get_shape(x)) tot2 = tot1 + len(shape_prev) tot3 = tot2 + len(get_shape(arg)) tot4 = tot3 + len(shape_succ) perm = [i for i in range(tot1, tot2)] + \ [i for i in range(tot1)] + [i for i in range(tot2, tot3)] + \ [i for i in range(tot3, tot4)] addend = _permute_dims(addend, _af_invert(perm)) addend_list.append(addend) if len(addend_list) == 1: return addend_list[0] elif len(addend_list) == 0: return S.Zero else: return _array_add(*addend_list) @array_derive.register(ArraySymbol) def _(expr: ArraySymbol, x: _ArrayExpr): if expr == x: return _permute_dims( ArrayTensorProduct.fromiter(Identity(i) for i in expr.shape), [2*i for i in range(len(expr.shape))] + [2*i+1 for i in range(len(expr.shape))] ) return ZeroArray(*(x.shape + expr.shape)) @array_derive.register(MatrixSymbol) def _(expr: MatrixSymbol, x: _ArrayExpr): m, n = expr.shape if expr == x: return _permute_dims( _array_tensor_product(Identity(m), Identity(n)), [0, 2, 1, 3] ) return ZeroArray(*(x.shape + expr.shape)) @array_derive.register(Identity) def _(expr: Identity, x: _ArrayExpr): return ZeroArray(*(x.shape + expr.shape)) @array_derive.register(Transpose) def _(expr: Transpose, x: Expr): # D(A.T, A) ==> (m,n,i,j) ==> D(A_ji, A_mn) = d_mj d_ni # D(B.T, A) ==> (m,n,i,j) ==> D(B_ji, A_mn) fd = array_derive(expr.arg, x) return _permute_dims(fd, [0, 1, 3, 2]) @array_derive.register(Inverse) def _(expr: Inverse, x: Expr): mat = expr.I dexpr = array_derive(mat, x) tp = _array_tensor_product(-expr, dexpr, expr) mp = _array_contraction(tp, (1, 4), (5, 6)) pp = _permute_dims(mp, [1, 2, 0, 3]) return pp @array_derive.register(ElementwiseApplyFunction) def _(expr: ElementwiseApplyFunction, x: Expr): assert get_rank(expr) == 2 assert get_rank(x) == 2 fdiff = expr._get_function_fdiff() dexpr = array_derive(expr.expr, x) tp = _array_tensor_product( ElementwiseApplyFunction(fdiff, expr.expr), dexpr ) td = _array_diagonal( tp, (0, 4), (1, 5) ) return td @array_derive.register(ArrayElementwiseApplyFunc) def _(expr: ArrayElementwiseApplyFunc, x: Expr): fdiff = expr._get_function_fdiff() subexpr = expr.expr dsubexpr = array_derive(subexpr, x) tp = _array_tensor_product( dsubexpr, ArrayElementwiseApplyFunc(fdiff, subexpr) ) b = get_rank(x) c = get_rank(expr) diag_indices = [(b + i, b + c + i) for i in range(c)] return _array_diagonal(tp, *diag_indices) @array_derive.register(MatrixExpr) def _(expr: MatrixExpr, x: Expr): cg = convert_matrix_to_array(expr) return array_derive(cg, x) @array_derive.register(HadamardProduct) def _(expr: HadamardProduct, x: Expr): raise NotImplementedError() @array_derive.register(ArrayContraction) def _(expr: ArrayContraction, x: Expr): fd = array_derive(expr.expr, x) rank_x = len(get_shape(x)) contraction_indices = expr.contraction_indices new_contraction_indices = [tuple(j + rank_x for j in i) for i in contraction_indices] return _array_contraction(fd, *new_contraction_indices) @array_derive.register(ArrayDiagonal) def _(expr: ArrayDiagonal, x: Expr): dsubexpr = array_derive(expr.expr, x) rank_x = len(get_shape(x)) diag_indices = [[j + rank_x for j in i] for i in expr.diagonal_indices] return _array_diagonal(dsubexpr, *diag_indices) @array_derive.register(ArrayAdd) def _(expr: ArrayAdd, x: Expr): return _array_add(*[array_derive(arg, x) for arg in expr.args]) @array_derive.register(PermuteDims) def _(expr: PermuteDims, x: Expr): de = array_derive(expr.expr, x) perm = [0, 1] + [i + 2 for i in expr.permutation.array_form] return _permute_dims(de, perm) @array_derive.register(Reshape) def _(expr: Reshape, x: Expr): de = array_derive(expr.expr, x) return Reshape(de, get_shape(x) + expr.shape) def matrix_derive(expr, x): from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix ce = convert_matrix_to_array(expr) dce = array_derive(ce, x) return convert_array_to_matrix(dce).doit()
b601a33b4c1f0e7ea28ad1efcd7c1e1e2c1934262fd386190e66051db6d19c8b
import itertools from collections import defaultdict from typing import Tuple as tTuple, Union as tUnion, FrozenSet, Dict as tDict, List, Optional from functools import singledispatch from itertools import accumulate from sympy import MatMul, Basic, Wild, KroneckerProduct from sympy.assumptions.ask import (Q, ask) from sympy.core.mul import Mul from sympy.core.singleton import S from sympy.matrices.expressions.diagonal import DiagMatrix from sympy.matrices.expressions.hadamard import hadamard_product, HadamardPower from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.matrices.expressions.special import (Identity, ZeroMatrix, OneMatrix) from sympy.matrices.expressions.trace import Trace from sympy.matrices.expressions.transpose import Transpose from sympy.combinatorics.permutations import _af_invert, Permutation from sympy.matrices.common import MatrixCommon from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction from sympy.matrices.expressions.matexpr import MatrixElement from sympy.tensor.array.expressions.array_expressions import PermuteDims, ArrayDiagonal, \ ArrayTensorProduct, OneArray, get_rank, _get_subrank, ZeroArray, ArrayContraction, \ ArrayAdd, _CodegenArrayAbstract, get_shape, ArrayElementwiseApplyFunc, _ArrayExpr, _EditArrayContraction, _ArgE, \ ArrayElement, _array_tensor_product, _array_contraction, _array_diagonal, _array_add, _permute_dims from sympy.tensor.array.expressions.utils import _get_mapping_from_subranks def _get_candidate_for_matmul_from_contraction(scan_indices: List[Optional[int]], remaining_args: List[_ArgE]) -> tTuple[Optional[_ArgE], bool, int]: scan_indices_int: List[int] = [i for i in scan_indices if i is not None] if len(scan_indices_int) == 0: return None, False, -1 transpose: bool = False candidate: Optional[_ArgE] = None candidate_index: int = -1 for arg_with_ind2 in remaining_args: if not isinstance(arg_with_ind2.element, MatrixExpr): continue for index in scan_indices_int: if candidate_index != -1 and candidate_index != index: # A candidate index has already been selected, check # repetitions only for that index: continue if index in arg_with_ind2.indices: if set(arg_with_ind2.indices) == {index}: # Index repeated twice in arg_with_ind2 candidate = None break if candidate is None: candidate = arg_with_ind2 candidate_index = index transpose = (index == arg_with_ind2.indices[1]) else: # Index repeated more than twice, break candidate = None break return candidate, transpose, candidate_index def _insert_candidate_into_editor(editor: _EditArrayContraction, arg_with_ind: _ArgE, candidate: _ArgE, transpose1: bool, transpose2: bool): other = candidate.element other_index: Optional[int] if transpose2: other = Transpose(other) other_index = candidate.indices[0] else: other_index = candidate.indices[1] new_element = (Transpose(arg_with_ind.element) if transpose1 else arg_with_ind.element) * other editor.args_with_ind.remove(candidate) new_arge = _ArgE(new_element) return new_arge, other_index def _support_function_tp1_recognize(contraction_indices, args): if len(contraction_indices) == 0: return _a2m_tensor_product(*args) ac = _array_contraction(_array_tensor_product(*args), *contraction_indices) editor = _EditArrayContraction(ac) editor.track_permutation_start() while True: flag_stop: bool = True for i, arg_with_ind in enumerate(editor.args_with_ind): if not isinstance(arg_with_ind.element, MatrixExpr): continue first_index = arg_with_ind.indices[0] second_index = arg_with_ind.indices[1] first_frequency = editor.count_args_with_index(first_index) second_frequency = editor.count_args_with_index(second_index) if first_index is not None and first_frequency == 1 and first_index == second_index: flag_stop = False arg_with_ind.element = Trace(arg_with_ind.element)._normalize() arg_with_ind.indices = [] break scan_indices = [] if first_frequency == 2: scan_indices.append(first_index) if second_frequency == 2: scan_indices.append(second_index) candidate, transpose, found_index = _get_candidate_for_matmul_from_contraction(scan_indices, editor.args_with_ind[i+1:]) if candidate is not None: flag_stop = False editor.track_permutation_merge(arg_with_ind, candidate) transpose1 = found_index == first_index new_arge, other_index = _insert_candidate_into_editor(editor, arg_with_ind, candidate, transpose1, transpose) if found_index == first_index: new_arge.indices = [second_index, other_index] else: new_arge.indices = [first_index, other_index] set_indices = set(new_arge.indices) if len(set_indices) == 1 and set_indices != {None}: # This is a trace: new_arge.element = Trace(new_arge.element)._normalize() new_arge.indices = [] editor.args_with_ind[i] = new_arge # TODO: is this break necessary? break if flag_stop: break editor.refresh_indices() return editor.to_array_contraction() def _find_trivial_matrices_rewrite(expr: ArrayTensorProduct): # If there are matrices of trivial shape in the tensor product (i.e. shape # (1, 1)), try to check if there is a suitable non-trivial MatMul where the # expression can be inserted. # For example, if "a" has shape (1, 1) and "b" has shape (k, 1), the # expressions "_array_tensor_product(a, b*b.T)" can be rewritten as # "b*a*b.T" trivial_matrices = [] pos: Optional[int] = None first: Optional[MatrixExpr] = None second: Optional[MatrixExpr] = None removed: List[int] = [] counter: int = 0 args: List[Optional[Basic]] = [i for i in expr.args] for i, arg in enumerate(expr.args): if isinstance(arg, MatrixExpr): if arg.shape == (1, 1): trivial_matrices.append(arg) args[i] = None removed.extend([counter, counter+1]) elif pos is None and isinstance(arg, MatMul): margs = arg.args for j, e in enumerate(margs): if isinstance(e, MatrixExpr) and e.shape[1] == 1: pos = i first = MatMul.fromiter(margs[:j+1]) second = MatMul.fromiter(margs[j+1:]) break counter += get_rank(arg) if pos is None: return expr, [] args[pos] = (first*MatMul.fromiter(i for i in trivial_matrices)*second).doit() return _array_tensor_product(*[i for i in args if i is not None]), removed def _find_trivial_kronecker_products_broadcast(expr: ArrayTensorProduct): newargs: List[Basic] = [] removed = [] count_dims = 0 for i, arg in enumerate(expr.args): count_dims += get_rank(arg) shape = get_shape(arg) current_range = [count_dims-i for i in range(len(shape), 0, -1)] if (shape == (1, 1) and len(newargs) > 0 and 1 not in get_shape(newargs[-1]) and isinstance(newargs[-1], MatrixExpr) and isinstance(arg, MatrixExpr)): # KroneckerProduct object allows the trick of broadcasting: newargs[-1] = KroneckerProduct(newargs[-1], arg) removed.extend(current_range) elif 1 not in shape and len(newargs) > 0 and get_shape(newargs[-1]) == (1, 1): # Broadcast: newargs[-1] = KroneckerProduct(newargs[-1], arg) prev_range = [i for i in range(min(current_range)) if i not in removed] removed.extend(prev_range[-2:]) else: newargs.append(arg) return _array_tensor_product(*newargs), removed @singledispatch def _array2matrix(expr): return expr @_array2matrix.register(ZeroArray) def _(expr: ZeroArray): if get_rank(expr) == 2: return ZeroMatrix(*expr.shape) else: return expr @_array2matrix.register(ArrayTensorProduct) def _(expr: ArrayTensorProduct): return _a2m_tensor_product(*[_array2matrix(arg) for arg in expr.args]) @_array2matrix.register(ArrayContraction) def _(expr: ArrayContraction): expr = expr.flatten_contraction_of_diagonal() expr = identify_removable_identity_matrices(expr) expr = expr.split_multiple_contractions() expr = identify_hadamard_products(expr) if not isinstance(expr, ArrayContraction): return _array2matrix(expr) subexpr = expr.expr contraction_indices: tTuple[tTuple[int]] = expr.contraction_indices if contraction_indices == ((0,), (1,)) or ( contraction_indices == ((0,),) and subexpr.shape[1] == 1 ) or ( contraction_indices == ((1,),) and subexpr.shape[0] == 1 ): shape = subexpr.shape subexpr = _array2matrix(subexpr) if isinstance(subexpr, MatrixExpr): return OneMatrix(1, shape[0])*subexpr*OneMatrix(shape[1], 1) if isinstance(subexpr, ArrayTensorProduct): newexpr = _array_contraction(_array2matrix(subexpr), *contraction_indices) contraction_indices = newexpr.contraction_indices if any(i > 2 for i in newexpr.subranks): addends = _array_add(*[_a2m_tensor_product(*j) for j in itertools.product(*[i.args if isinstance(i, ArrayAdd) else [i] for i in expr.expr.args])]) newexpr = _array_contraction(addends, *contraction_indices) if isinstance(newexpr, ArrayAdd): ret = _array2matrix(newexpr) return ret assert isinstance(newexpr, ArrayContraction) ret = _support_function_tp1_recognize(contraction_indices, list(newexpr.expr.args)) return ret elif not isinstance(subexpr, _CodegenArrayAbstract): ret = _array2matrix(subexpr) if isinstance(ret, MatrixExpr): assert expr.contraction_indices == ((0, 1),) return _a2m_trace(ret) else: return _array_contraction(ret, *expr.contraction_indices) @_array2matrix.register(ArrayDiagonal) def _(expr: ArrayDiagonal): pexpr = _array_diagonal(_array2matrix(expr.expr), *expr.diagonal_indices) pexpr = identify_hadamard_products(pexpr) if isinstance(pexpr, ArrayDiagonal): pexpr = _array_diag2contr_diagmatrix(pexpr) if expr == pexpr: return expr return _array2matrix(pexpr) @_array2matrix.register(PermuteDims) def _(expr: PermuteDims): if expr.permutation.array_form == [1, 0]: return _a2m_transpose(_array2matrix(expr.expr)) elif isinstance(expr.expr, ArrayTensorProduct): ranks = expr.expr.subranks inv_permutation = expr.permutation**(-1) newrange = [inv_permutation(i) for i in range(sum(ranks))] newpos = [] counter = 0 for rank in ranks: newpos.append(newrange[counter:counter+rank]) counter += rank newargs = [] newperm = [] scalars = [] for pos, arg in zip(newpos, expr.expr.args): if len(pos) == 0: scalars.append(_array2matrix(arg)) elif pos == sorted(pos): newargs.append((_array2matrix(arg), pos[0])) newperm.extend(pos) elif len(pos) == 2: newargs.append((_a2m_transpose(_array2matrix(arg)), pos[0])) newperm.extend(reversed(pos)) else: raise NotImplementedError() newargs = [i[0] for i in newargs] return _permute_dims(_a2m_tensor_product(*scalars, *newargs), _af_invert(newperm)) elif isinstance(expr.expr, ArrayContraction): mat_mul_lines = _array2matrix(expr.expr) if not isinstance(mat_mul_lines, ArrayTensorProduct): return _permute_dims(mat_mul_lines, expr.permutation) # TODO: this assumes that all arguments are matrices, it may not be the case: permutation = Permutation(2*len(mat_mul_lines.args)-1)*expr.permutation permuted = [permutation(i) for i in range(2*len(mat_mul_lines.args))] args_array = [None for i in mat_mul_lines.args] for i in range(len(mat_mul_lines.args)): p1 = permuted[2*i] p2 = permuted[2*i+1] if p1 // 2 != p2 // 2: return _permute_dims(mat_mul_lines, permutation) if p1 > p2: args_array[i] = _a2m_transpose(mat_mul_lines.args[p1 // 2]) else: args_array[i] = mat_mul_lines.args[p1 // 2] return _a2m_tensor_product(*args_array) else: return expr @_array2matrix.register(ArrayAdd) def _(expr: ArrayAdd): addends = [_array2matrix(arg) for arg in expr.args] return _a2m_add(*addends) @_array2matrix.register(ArrayElementwiseApplyFunc) def _(expr: ArrayElementwiseApplyFunc): subexpr = _array2matrix(expr.expr) if isinstance(subexpr, MatrixExpr): if subexpr.shape != (1, 1): d = expr.function.bound_symbols[0] w = Wild("w", exclude=[d]) p = Wild("p", exclude=[d]) m = expr.function.expr.match(w*d**p) if m is not None: return m[w]*HadamardPower(subexpr, m[p]) return ElementwiseApplyFunction(expr.function, subexpr) else: return ArrayElementwiseApplyFunc(expr.function, subexpr) @_array2matrix.register(ArrayElement) def _(expr: ArrayElement): ret = _array2matrix(expr.name) if isinstance(ret, MatrixExpr): return MatrixElement(ret, *expr.indices) return ArrayElement(ret, expr.indices) @singledispatch def _remove_trivial_dims(expr): return expr, [] @_remove_trivial_dims.register(ArrayTensorProduct) def _(expr: ArrayTensorProduct): # Recognize expressions like [x, y] with shape (k, 1, k, 1) as `x*y.T`. # The matrix expression has to be equivalent to the tensor product of the # matrices, with trivial dimensions (i.e. dim=1) dropped. # That is, add contractions over trivial dimensions: removed = [] newargs = [] cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args])) pending = None prev_i = None for i, arg in enumerate(expr.args): current_range = list(range(cumul[i], cumul[i+1])) if isinstance(arg, OneArray): removed.extend(current_range) continue if not isinstance(arg, (MatrixExpr, MatrixCommon)): rarg, rem = _remove_trivial_dims(arg) removed.extend(rem) newargs.append(rarg) continue elif getattr(arg, "is_Identity", False) and arg.shape == (1, 1): if arg.shape == (1, 1): # Ignore identity matrices of shape (1, 1) - they are equivalent to scalar 1. removed.extend(current_range) continue elif arg.shape == (1, 1): arg, _ = _remove_trivial_dims(arg) # Matrix is equivalent to scalar: if len(newargs) == 0: newargs.append(arg) elif 1 in get_shape(newargs[-1]): if newargs[-1].shape[1] == 1: newargs[-1] = newargs[-1]*arg else: newargs[-1] = arg*newargs[-1] removed.extend(current_range) else: newargs.append(arg) elif 1 in arg.shape: k = [i for i in arg.shape if i != 1][0] if pending is None: pending = k prev_i = i newargs.append(arg) elif pending == k: prev = newargs[-1] if prev.shape[0] == 1: d1 = cumul[prev_i] prev = _a2m_transpose(prev) else: d1 = cumul[prev_i] + 1 if arg.shape[1] == 1: d2 = cumul[i] + 1 arg = _a2m_transpose(arg) else: d2 = cumul[i] newargs[-1] = prev*arg pending = None removed.extend([d1, d2]) else: newargs.append(arg) pending = k prev_i = i else: newargs.append(arg) pending = None newexpr, newremoved = _a2m_tensor_product(*newargs), sorted(removed) if isinstance(newexpr, ArrayTensorProduct): newexpr, newremoved2 = _find_trivial_matrices_rewrite(newexpr) newremoved = _combine_removed(-1, newremoved, newremoved2) if isinstance(newexpr, ArrayTensorProduct): newexpr, newremoved2 = _find_trivial_kronecker_products_broadcast(newexpr) newremoved = _combine_removed(-1, newremoved, newremoved2) return newexpr, newremoved @_remove_trivial_dims.register(ArrayAdd) def _(expr: ArrayAdd): rec = [_remove_trivial_dims(arg) for arg in expr.args] newargs, removed = zip(*rec) if len(set([get_shape(i) for i in newargs])) > 1: return expr, [] if len(removed) == 0: return expr, removed removed1 = removed[0] return _a2m_add(*newargs), removed1 @_remove_trivial_dims.register(PermuteDims) def _(expr: PermuteDims): subexpr, subremoved = _remove_trivial_dims(expr.expr) p = expr.permutation.array_form pinv = _af_invert(expr.permutation.array_form) shift = list(accumulate([1 if i in subremoved else 0 for i in range(len(p))])) premoved = [pinv[i] for i in subremoved] p2 = [e - shift[e] for i, e in enumerate(p) if e not in subremoved] # TODO: check if subremoved should be permuted as well... newexpr = _permute_dims(subexpr, p2) premoved = sorted(premoved) if newexpr != expr: newexpr, removed2 = _remove_trivial_dims(_array2matrix(newexpr)) premoved = _combine_removed(-1, premoved, removed2) return newexpr, premoved @_remove_trivial_dims.register(ArrayContraction) def _(expr: ArrayContraction): new_expr, removed0 = _array_contraction_to_diagonal_multiple_identity(expr) if new_expr != expr: new_expr2, removed1 = _remove_trivial_dims(_array2matrix(new_expr)) removed = _combine_removed(-1, removed0, removed1) return new_expr2, removed rank1 = get_rank(expr) expr, removed1 = remove_identity_matrices(expr) if not isinstance(expr, ArrayContraction): expr2, removed2 = _remove_trivial_dims(expr) return expr2, _combine_removed(rank1, removed1, removed2) newexpr, removed2 = _remove_trivial_dims(expr.expr) shifts = list(accumulate([1 if i in removed2 else 0 for i in range(get_rank(expr.expr))])) new_contraction_indices = [tuple(j for j in i if j not in removed2) for i in expr.contraction_indices] # Remove possible empty tuples "()": new_contraction_indices = [i for i in new_contraction_indices if len(i) > 0] contraction_indices_flat = [j for i in expr.contraction_indices for j in i] removed2 = [i for i in removed2 if i not in contraction_indices_flat] new_contraction_indices = [tuple(j - shifts[j] for j in i) for i in new_contraction_indices] # Shift removed2: removed2 = ArrayContraction._push_indices_up(expr.contraction_indices, removed2) removed = _combine_removed(rank1, removed1, removed2) return _array_contraction(newexpr, *new_contraction_indices), list(removed) def _remove_diagonalized_identity_matrices(expr: ArrayDiagonal): assert isinstance(expr, ArrayDiagonal) editor = _EditArrayContraction(expr) mapping = {i: {j for j in editor.args_with_ind if i in j.indices} for i in range(-1, -1-editor.number_of_diagonal_indices, -1)} removed = [] counter: int = 0 for i, arg_with_ind in enumerate(editor.args_with_ind): counter += len(arg_with_ind.indices) if isinstance(arg_with_ind.element, Identity): if None in arg_with_ind.indices and any(i is not None and (i < 0) == True for i in arg_with_ind.indices): diag_ind = [j for j in arg_with_ind.indices if j is not None][0] other = [j for j in mapping[diag_ind] if j != arg_with_ind][0] if not isinstance(other.element, MatrixExpr): continue if 1 not in other.element.shape: continue if None not in other.indices: continue editor.args_with_ind[i].element = None none_index = other.indices.index(None) other.element = DiagMatrix(other.element) other_range = editor.get_absolute_range(other) removed.extend([other_range[0] + none_index]) editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None] removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, get_rank(expr.expr)) return editor.to_array_contraction(), removed @_remove_trivial_dims.register(ArrayDiagonal) def _(expr: ArrayDiagonal): newexpr, removed = _remove_trivial_dims(expr.expr) shifts = list(accumulate([0] + [1 if i in removed else 0 for i in range(get_rank(expr.expr))])) new_diag_indices_map = {i: tuple(j for j in i if j not in removed) for i in expr.diagonal_indices} for old_diag_tuple, new_diag_tuple in new_diag_indices_map.items(): if len(new_diag_tuple) == 1: removed = [i for i in removed if i not in old_diag_tuple] new_diag_indices = [tuple(j - shifts[j] for j in i) for i in new_diag_indices_map.values()] rank = get_rank(expr.expr) removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, rank) removed = sorted({i for i in removed}) # If there are single axes to diagonalize remaining, it means that their # corresponding dimension has been removed, they no longer need diagonalization: new_diag_indices = [i for i in new_diag_indices if len(i) > 0] if len(new_diag_indices) > 0: newexpr2 = _array_diagonal(newexpr, *new_diag_indices, allow_trivial_diags=True) else: newexpr2 = newexpr if isinstance(newexpr2, ArrayDiagonal): newexpr3, removed2 = _remove_diagonalized_identity_matrices(newexpr2) removed = _combine_removed(-1, removed, removed2) return newexpr3, removed else: return newexpr2, removed @_remove_trivial_dims.register(ElementwiseApplyFunction) def _(expr: ElementwiseApplyFunction): subexpr, removed = _remove_trivial_dims(expr.expr) if subexpr.shape == (1, 1): # TODO: move this to ElementwiseApplyFunction return expr.function(subexpr), removed + [0, 1] return ElementwiseApplyFunction(expr.function, subexpr), [] @_remove_trivial_dims.register(ArrayElementwiseApplyFunc) def _(expr: ArrayElementwiseApplyFunc): subexpr, removed = _remove_trivial_dims(expr.expr) return ArrayElementwiseApplyFunc(expr.function, subexpr), removed def convert_array_to_matrix(expr): r""" Recognize matrix expressions in codegen objects. If more than one matrix multiplication line have been detected, return a list with the matrix expressions. Examples ======== >>> from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array >>> from sympy.tensor.array import tensorcontraction, tensorproduct >>> from sympy import MatrixSymbol, Sum >>> from sympy.abc import i, j, k, l, N >>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array >>> from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> C = MatrixSymbol("C", N, N) >>> D = MatrixSymbol("D", N, N) >>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) A*B >>> cg = convert_indexed_to_array(expr, first_indices=[k]) >>> convert_array_to_matrix(cg) B.T*A.T Transposition is detected: >>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) A.T*B >>> cg = convert_indexed_to_array(expr, first_indices=[k]) >>> convert_array_to_matrix(cg) B.T*A Detect the trace: >>> expr = Sum(A[i, i], (i, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) Trace(A) Recognize some more complex traces: >>> expr = Sum(A[i, j]*B[j, i], (i, 0, N-1), (j, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) Trace(A*B) More complicated expressions: >>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) A*B.T*A.T Expressions constructed from matrix expressions do not contain literal indices, the positions of free indices are returned instead: >>> expr = A*B >>> cg = convert_matrix_to_array(expr) >>> convert_array_to_matrix(cg) A*B If more than one line of matrix multiplications is detected, return separate matrix multiplication factors embedded in a tensor product object: >>> cg = tensorcontraction(tensorproduct(A, B, C, D), (1, 2), (5, 6)) >>> convert_array_to_matrix(cg) ArrayTensorProduct(A*B, C*D) The two lines have free indices at axes 0, 3 and 4, 7, respectively. """ rec = _array2matrix(expr) rec, removed = _remove_trivial_dims(rec) return rec def _array_diag2contr_diagmatrix(expr: ArrayDiagonal): if isinstance(expr.expr, ArrayTensorProduct): args = list(expr.expr.args) diag_indices = list(expr.diagonal_indices) mapping = _get_mapping_from_subranks([_get_subrank(arg) for arg in args]) tuple_links = [[mapping[j] for j in i] for i in diag_indices] contr_indices = [] total_rank = get_rank(expr) replaced = [False for arg in args] for i, (abs_pos, rel_pos) in enumerate(zip(diag_indices, tuple_links)): if len(abs_pos) != 2: continue (pos1_outer, pos1_inner), (pos2_outer, pos2_inner) = rel_pos arg1 = args[pos1_outer] arg2 = args[pos2_outer] if get_rank(arg1) != 2 or get_rank(arg2) != 2: if replaced[pos1_outer]: diag_indices[i] = None if replaced[pos2_outer]: diag_indices[i] = None continue pos1_in2 = 1 - pos1_inner pos2_in2 = 1 - pos2_inner if arg1.shape[pos1_in2] == 1: if arg1.shape[pos1_inner] != 1: darg1 = DiagMatrix(arg1) else: darg1 = arg1 args.append(darg1) contr_indices.append(((pos2_outer, pos2_inner), (len(args)-1, pos1_inner))) total_rank += 1 diag_indices[i] = None args[pos1_outer] = OneArray(arg1.shape[pos1_in2]) replaced[pos1_outer] = True elif arg2.shape[pos2_in2] == 1: if arg2.shape[pos2_inner] != 1: darg2 = DiagMatrix(arg2) else: darg2 = arg2 args.append(darg2) contr_indices.append(((pos1_outer, pos1_inner), (len(args)-1, pos2_inner))) total_rank += 1 diag_indices[i] = None args[pos2_outer] = OneArray(arg2.shape[pos2_in2]) replaced[pos2_outer] = True diag_indices_new = [i for i in diag_indices if i is not None] cumul = list(accumulate([0] + [get_rank(arg) for arg in args])) contr_indices2 = [tuple(cumul[a] + b for a, b in i) for i in contr_indices] tc = _array_contraction( _array_tensor_product(*args), *contr_indices2 ) td = _array_diagonal(tc, *diag_indices_new) return td return expr def _a2m_mul(*args): if not any(isinstance(i, _CodegenArrayAbstract) for i in args): from sympy.matrices.expressions.matmul import MatMul return MatMul(*args).doit() else: return _array_contraction( _array_tensor_product(*args), *[(2*i-1, 2*i) for i in range(1, len(args))] ) def _a2m_tensor_product(*args): scalars = [] arrays = [] for arg in args: if isinstance(arg, (MatrixExpr, _ArrayExpr, _CodegenArrayAbstract)): arrays.append(arg) else: scalars.append(arg) scalar = Mul.fromiter(scalars) if len(arrays) == 0: return scalar if scalar != 1: if isinstance(arrays[0], _CodegenArrayAbstract): arrays = [scalar] + arrays else: arrays[0] *= scalar return _array_tensor_product(*arrays) def _a2m_add(*args): if not any(isinstance(i, _CodegenArrayAbstract) for i in args): from sympy.matrices.expressions.matadd import MatAdd return MatAdd(*args).doit() else: return _array_add(*args) def _a2m_trace(arg): if isinstance(arg, _CodegenArrayAbstract): return _array_contraction(arg, (0, 1)) else: from sympy.matrices.expressions.trace import Trace return Trace(arg) def _a2m_transpose(arg): if isinstance(arg, _CodegenArrayAbstract): return _permute_dims(arg, [1, 0]) else: from sympy.matrices.expressions.transpose import Transpose return Transpose(arg).doit() def identify_hadamard_products(expr: tUnion[ArrayContraction, ArrayDiagonal]): editor: _EditArrayContraction = _EditArrayContraction(expr) map_contr_to_args: tDict[FrozenSet, List[_ArgE]] = defaultdict(list) map_ind_to_inds: tDict[Optional[int], int] = defaultdict(int) for arg_with_ind in editor.args_with_ind: for ind in arg_with_ind.indices: map_ind_to_inds[ind] += 1 if None in arg_with_ind.indices: continue map_contr_to_args[frozenset(arg_with_ind.indices)].append(arg_with_ind) k: FrozenSet[int] v: List[_ArgE] for k, v in map_contr_to_args.items(): make_trace: bool = False if len(k) == 1 and next(iter(k)) >= 0 and sum([next(iter(k)) in i for i in map_contr_to_args]) == 1: # This is a trace: the arguments are fully contracted with only one # index, and the index isn't used anywhere else: make_trace = True first_element = S.One elif len(k) != 2: # Hadamard product only defined for matrices: continue if len(v) == 1: # Hadamard product with a single argument makes no sense: continue for ind in k: if map_ind_to_inds[ind] <= 2: # There is no other contraction, skip: continue def check_transpose(x): x = [i if i >= 0 else -1-i for i in x] return x == sorted(x) # Check if expression is a trace: if all([map_ind_to_inds[j] == len(v) and j >= 0 for j in k]) and all([j >= 0 for j in k]): # This is a trace make_trace = True first_element = v[0].element if not check_transpose(v[0].indices): first_element = first_element.T hadamard_factors = v[1:] else: hadamard_factors = v # This is a Hadamard product: hp = hadamard_product(*[i.element if check_transpose(i.indices) else Transpose(i.element) for i in hadamard_factors]) hp_indices = v[0].indices if not check_transpose(hadamard_factors[0].indices): hp_indices = list(reversed(hp_indices)) if make_trace: hp = Trace(first_element*hp.T)._normalize() hp_indices = [] editor.insert_after(v[0], _ArgE(hp, hp_indices)) for i in v: editor.args_with_ind.remove(i) return editor.to_array_contraction() def identify_removable_identity_matrices(expr): editor = _EditArrayContraction(expr) flag: bool = True while flag: flag = False for arg_with_ind in editor.args_with_ind: if isinstance(arg_with_ind.element, Identity): k = arg_with_ind.element.shape[0] # Candidate for removal: if arg_with_ind.indices == [None, None]: # Free identity matrix, will be cleared by _remove_trivial_dims: continue elif None in arg_with_ind.indices: ind = [j for j in arg_with_ind.indices if j is not None][0] counted = editor.count_args_with_index(ind) if counted == 1: # Identity matrix contracted only on one index with itself, # transform to a OneArray(k) element: editor.insert_after(arg_with_ind, OneArray(k)) editor.args_with_ind.remove(arg_with_ind) flag = True break elif counted > 2: # Case counted = 2 is a matrix multiplication by identity matrix, skip it. # Case counted > 2 is a multiple contraction, # this is a case where the contraction becomes a diagonalization if the # identity matrix is dropped. continue elif arg_with_ind.indices[0] == arg_with_ind.indices[1]: ind = arg_with_ind.indices[0] counted = editor.count_args_with_index(ind) if counted > 1: editor.args_with_ind.remove(arg_with_ind) flag = True break else: # This is a trace, skip it as it will be recognized somewhere else: pass elif ask(Q.diagonal(arg_with_ind.element)): if arg_with_ind.indices == [None, None]: continue elif None in arg_with_ind.indices: pass elif arg_with_ind.indices[0] == arg_with_ind.indices[1]: ind = arg_with_ind.indices[0] counted = editor.count_args_with_index(ind) if counted == 3: # A_ai B_bi D_ii ==> A_ai D_ij B_bj ind_new = editor.get_new_contraction_index() other_args = [j for j in editor.args_with_ind if j != arg_with_ind] other_args[1].indices = [ind_new if j == ind else j for j in other_args[1].indices] arg_with_ind.indices = [ind, ind_new] flag = True break return editor.to_array_contraction() def remove_identity_matrices(expr: ArrayContraction): editor = _EditArrayContraction(expr) removed: List[int] = [] permutation_map = {} free_indices = list(accumulate([0] + [sum([i is None for i in arg.indices]) for arg in editor.args_with_ind])) free_map = {k: v for k, v in zip(editor.args_with_ind, free_indices[:-1])} update_pairs = {} for ind in range(editor.number_of_contraction_indices): args = editor.get_args_with_index(ind) identity_matrices = [i for i in args if isinstance(i.element, Identity)] number_identity_matrices = len(identity_matrices) # If the contraction involves a non-identity matrix and multiple identity matrices: if number_identity_matrices != len(args) - 1 or number_identity_matrices == 0: continue # Get the non-identity element: non_identity = [i for i in args if not isinstance(i.element, Identity)][0] # Check that all identity matrices have at least one free index # (otherwise they would be contractions to some other elements) if any([None not in i.indices for i in identity_matrices]): continue # Mark the identity matrices for removal: for i in identity_matrices: i.element = None removed.extend(range(free_map[i], free_map[i] + len([j for j in i.indices if j is None]))) last_removed = removed.pop(-1) update_pairs[last_removed, ind] = non_identity.indices[:] # Remove the indices from the non-identity matrix, as the contraction # no longer exists: non_identity.indices = [None if i == ind else i for i in non_identity.indices] removed.sort() shifts = list(accumulate([1 if i in removed else 0 for i in range(get_rank(expr))])) for (last_removed, ind), non_identity_indices in update_pairs.items(): pos = [free_map[non_identity] + i for i, e in enumerate(non_identity_indices) if e == ind] assert len(pos) == 1 for j in pos: permutation_map[j] = last_removed editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None] ret_expr = editor.to_array_contraction() permutation = [] counter = 0 counter2 = 0 for j in range(get_rank(expr)): if j in removed: continue if counter2 in permutation_map: target = permutation_map[counter2] permutation.append(target - shifts[target]) counter2 += 1 else: while counter in permutation_map.values(): counter += 1 permutation.append(counter) counter += 1 counter2 += 1 ret_expr2 = _permute_dims(ret_expr, _af_invert(permutation)) return ret_expr2, removed def _combine_removed(dim: int, removed1: List[int], removed2: List[int]) -> List[int]: # Concatenate two axis removal operations as performed by # _remove_trivial_dims, removed1 = sorted(removed1) removed2 = sorted(removed2) i = 0 j = 0 removed = [] while True: if j >= len(removed2): while i < len(removed1): removed.append(removed1[i]) i += 1 break elif i < len(removed1) and removed1[i] <= i + removed2[j]: removed.append(removed1[i]) i += 1 else: removed.append(i + removed2[j]) j += 1 return removed def _array_contraction_to_diagonal_multiple_identity(expr: ArrayContraction): editor = _EditArrayContraction(expr) editor.track_permutation_start() removed: List[int] = [] diag_index_counter: int = 0 for i in range(editor.number_of_contraction_indices): identities = [] args = [] for j, arg in enumerate(editor.args_with_ind): if i not in arg.indices: continue if isinstance(arg.element, Identity): identities.append(arg) else: args.append(arg) if len(identities) == 0: continue if len(args) + len(identities) < 3: continue new_diag_ind = -1 - diag_index_counter diag_index_counter += 1 # Variable "flag" to control whether to skip this contraction set: flag: bool = True for i1, id1 in enumerate(identities): if None not in id1.indices: flag = True break free_pos = list(range(*editor.get_absolute_free_range(id1)))[0] editor._track_permutation[-1].append(free_pos) # type: ignore id1.element = None flag = False break if flag: continue for arg in identities[:i1] + identities[i1+1:]: arg.element = None removed.extend(range(*editor.get_absolute_free_range(arg))) for arg in args: arg.indices = [new_diag_ind if j == i else j for j in arg.indices] for j, e in enumerate(editor.args_with_ind): if e.element is None: editor._track_permutation[j] = None # type: ignore editor._track_permutation = [i for i in editor._track_permutation if i is not None] # type: ignore # Renumber permutation array form in order to deal with deleted positions: remap = {e: i for i, e in enumerate(sorted({k for j in editor._track_permutation for k in j}))} editor._track_permutation = [[remap[j] for j in i] for i in editor._track_permutation] editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None] new_expr = editor.to_array_contraction() return new_expr, removed
daf9127a9f423ca62b4104b4bbc0329ffb1cef27a4d73c338e30962b971f61ef
from sympy import Lambda, S, Dummy, KroneckerProduct from sympy.core.symbol import symbols from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import cos, sin from sympy.matrices.expressions.hadamard import HadamardProduct, HadamardPower from sympy.matrices.expressions.special import (Identity, OneMatrix, ZeroMatrix) from sympy.matrices.expressions.matexpr import MatrixElement from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array from sympy.tensor.array.expressions.from_array_to_matrix import _support_function_tp1_recognize, \ _array_diag2contr_diagmatrix, convert_array_to_matrix, _remove_trivial_dims, _array2matrix, \ _combine_removed, identify_removable_identity_matrices, _array_contraction_to_diagonal_multiple_identity from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.combinatorics import Permutation from sympy.matrices.expressions.diagonal import DiagMatrix, DiagonalMatrix from sympy.matrices import Trace, MatMul, Transpose from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, \ ArrayElement, ArraySymbol, ArrayElementwiseApplyFunc, _array_tensor_product, _array_contraction, \ _array_diagonal, _permute_dims, PermuteDims, ArrayAdd, ArrayDiagonal, ArrayContraction, ArrayTensorProduct from sympy.testing.pytest import raises i, j, k, l, m, n = symbols("i j k l m n") I = Identity(k) I1 = Identity(1) M = MatrixSymbol("M", k, k) N = MatrixSymbol("N", k, k) P = MatrixSymbol("P", k, k) Q = MatrixSymbol("Q", k, k) A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) D = MatrixSymbol("D", k, k) X = MatrixSymbol("X", k, k) Y = MatrixSymbol("Y", k, k) a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) d = MatrixSymbol("d", k, 1) x = MatrixSymbol("x", k, 1) y = MatrixSymbol("y", k, 1) def test_arrayexpr_convert_array_to_matrix(): cg = _array_contraction(_array_tensor_product(M), (0, 1)) assert convert_array_to_matrix(cg) == Trace(M) cg = _array_contraction(_array_tensor_product(M, N), (0, 1), (2, 3)) assert convert_array_to_matrix(cg) == Trace(M) * Trace(N) cg = _array_contraction(_array_tensor_product(M, N), (0, 3), (1, 2)) assert convert_array_to_matrix(cg) == Trace(M * N) cg = _array_contraction(_array_tensor_product(M, N), (0, 2), (1, 3)) assert convert_array_to_matrix(cg) == Trace(M * N.T) cg = convert_matrix_to_array(M * N * P) assert convert_array_to_matrix(cg) == M * N * P cg = convert_matrix_to_array(M * N.T * P) assert convert_array_to_matrix(cg) == M * N.T * P cg = _array_contraction(_array_tensor_product(M,N,P,Q), (1, 2), (5, 6)) assert convert_array_to_matrix(cg) == _array_tensor_product(M * N, P * Q) cg = _array_contraction(_array_tensor_product(-2, M, N), (1, 2)) assert convert_array_to_matrix(cg) == -2 * M * N a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) cg = PermuteDims( _array_contraction( _array_tensor_product( a, ArrayAdd( _array_tensor_product(b, c), _array_tensor_product(c, b), ) ), (2, 4)), [0, 1, 3, 2]) assert convert_array_to_matrix(cg) == a * (b.T * c + c.T * b) za = ZeroArray(m, n) assert convert_array_to_matrix(za) == ZeroMatrix(m, n) cg = _array_tensor_product(3, M) assert convert_array_to_matrix(cg) == 3 * M # Partial conversion to matrix multiplication: expr = _array_contraction(_array_tensor_product(M, N, P, Q), (0, 2), (1, 4, 6)) assert convert_array_to_matrix(expr) == _array_contraction(_array_tensor_product(M.T*N, P, Q), (0, 2, 4)) x = MatrixSymbol("x", k, 1) cg = PermuteDims( _array_contraction(_array_tensor_product(OneArray(1), x, OneArray(1), DiagMatrix(Identity(1))), (0, 5)), Permutation(1, 2, 3)) assert convert_array_to_matrix(cg) == x expr = ArrayAdd(M, PermuteDims(M, [1, 0])) assert convert_array_to_matrix(expr) == M + Transpose(M) def test_arrayexpr_convert_array_to_matrix2(): cg = _array_contraction(_array_tensor_product(M, N), (1, 3)) assert convert_array_to_matrix(cg) == M * N.T cg = PermuteDims(_array_tensor_product(M, N), Permutation([0, 1, 3, 2])) assert convert_array_to_matrix(cg) == _array_tensor_product(M, N.T) cg = _array_tensor_product(M, PermuteDims(N, Permutation([1, 0]))) assert convert_array_to_matrix(cg) == _array_tensor_product(M, N.T) cg = _array_contraction( PermuteDims( _array_tensor_product(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])), (1, 2), (3, 5) ) assert convert_array_to_matrix(cg) == _array_tensor_product(M * P.T * Trace(N), Q.T) cg = _array_contraction( _array_tensor_product(M, N, P, PermuteDims(Q, Permutation([1, 0]))), (1, 5), (2, 3) ) assert convert_array_to_matrix(cg) == _array_tensor_product(M * P.T * Trace(N), Q.T) cg = _array_tensor_product(M, PermuteDims(N, [1, 0])) assert convert_array_to_matrix(cg) == _array_tensor_product(M, N.T) cg = _array_tensor_product(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0])) assert convert_array_to_matrix(cg) == _array_tensor_product(M.T, N.T) cg = _array_tensor_product(PermuteDims(N, [1, 0]), PermuteDims(M, [1, 0])) assert convert_array_to_matrix(cg) == _array_tensor_product(N.T, M.T) cg = _array_contraction(M, (0,), (1,)) assert convert_array_to_matrix(cg) == OneMatrix(1, k)*M*OneMatrix(k, 1) cg = _array_contraction(x, (0,), (1,)) assert convert_array_to_matrix(cg) == OneMatrix(1, k)*x Xm = MatrixSymbol("Xm", m, n) cg = _array_contraction(Xm, (0,), (1,)) assert convert_array_to_matrix(cg) == OneMatrix(1, m)*Xm*OneMatrix(n, 1) def test_arrayexpr_convert_array_to_diagonalized_vector(): # Check matrix recognition over trivial dimensions: cg = _array_tensor_product(a, b) assert convert_array_to_matrix(cg) == a * b.T cg = _array_tensor_product(I1, a, b) assert convert_array_to_matrix(cg) == a * b.T # Recognize trace inside a tensor product: cg = _array_contraction(_array_tensor_product(A, B, C), (0, 3), (1, 2)) assert convert_array_to_matrix(cg) == Trace(A * B) * C # Transform diagonal operator to contraction: cg = _array_diagonal(_array_tensor_product(A, a), (1, 2)) assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(A, OneArray(1), DiagMatrix(a)), (1, 3)) assert convert_array_to_matrix(cg) == A * DiagMatrix(a) cg = _array_diagonal(_array_tensor_product(a, b), (0, 2)) assert _array_diag2contr_diagmatrix(cg) == _permute_dims( _array_contraction(_array_tensor_product(DiagMatrix(a), OneArray(1), b), (0, 3)), [1, 2, 0] ) assert convert_array_to_matrix(cg) == b.T * DiagMatrix(a) cg = _array_diagonal(_array_tensor_product(A, a), (0, 2)) assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(A, OneArray(1), DiagMatrix(a)), (0, 3)) assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) cg = _array_diagonal(_array_tensor_product(I, x, I1), (0, 2), (3, 5)) assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(I, OneArray(1), I1, DiagMatrix(x)), (0, 5)) assert convert_array_to_matrix(cg) == DiagMatrix(x) cg = _array_diagonal(_array_tensor_product(I, x, A, B), (1, 2), (5, 6)) assert _array_diag2contr_diagmatrix(cg) == _array_diagonal(_array_contraction(_array_tensor_product(I, OneArray(1), A, B, DiagMatrix(x)), (1, 7)), (5, 6)) # TODO: this is returning a wrong result: # convert_array_to_matrix(cg) cg = _array_diagonal(_array_tensor_product(I1, a, b), (1, 3, 5)) assert convert_array_to_matrix(cg) == a*b.T cg = _array_diagonal(_array_tensor_product(I1, a, b), (1, 3)) assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(OneArray(1), a, b, I1), (2, 6)) assert convert_array_to_matrix(cg) == a*b.T cg = _array_diagonal(_array_tensor_product(x, I1), (1, 2)) assert isinstance(cg, ArrayDiagonal) assert cg.diagonal_indices == ((1, 2),) assert convert_array_to_matrix(cg) == x cg = _array_diagonal(_array_tensor_product(x, I), (0, 2)) assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(OneArray(1), I, DiagMatrix(x)), (1, 3)) assert convert_array_to_matrix(cg).doit() == DiagMatrix(x) raises(ValueError, lambda: _array_diagonal(x, (1,))) # Ignore identity matrices with contractions: cg = _array_contraction(_array_tensor_product(I, A, I, I), (0, 2), (1, 3), (5, 7)) assert cg.split_multiple_contractions() == cg assert convert_array_to_matrix(cg) == Trace(A) * I cg = _array_contraction(_array_tensor_product(Trace(A) * I, I, I), (1, 5), (3, 4)) assert cg.split_multiple_contractions() == cg assert convert_array_to_matrix(cg).doit() == Trace(A) * I # Add DiagMatrix when required: cg = _array_contraction(_array_tensor_product(A, a), (1, 2)) assert cg.split_multiple_contractions() == cg assert convert_array_to_matrix(cg) == A * a cg = _array_contraction(_array_tensor_product(A, a, B), (1, 2, 4)) assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), B), (1, 2), (3, 5)) assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * B cg = _array_contraction(_array_tensor_product(A, a, B), (0, 2, 4)) assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), B), (0, 2), (3, 5)) assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) * B cg = _array_contraction(_array_tensor_product(A, a, b, a.T, B), (0, 2, 4, 7, 9)) assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), DiagMatrix(b), OneArray(1), DiagMatrix(a), OneArray(1), B), (0, 2), (3, 5), (6, 9), (8, 12)) assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) * DiagMatrix(b) * DiagMatrix(a) * B.T cg = _array_contraction(_array_tensor_product(I1, I1, I1), (1, 2, 4)) assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(I1, I1, OneArray(1), I1), (1, 2), (3, 5)) assert convert_array_to_matrix(cg) == 1 cg = _array_contraction(_array_tensor_product(I, I, I, I, A), (1, 2, 8), (5, 6, 9)) assert convert_array_to_matrix(cg.split_multiple_contractions()).doit() == A cg = _array_contraction(_array_tensor_product(A, a, C, a, B), (1, 2, 4), (5, 6, 8)) expected = _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), C, DiagMatrix(a), OneArray(1), B), (1, 3), (2, 5), (6, 7), (8, 10)) assert cg.split_multiple_contractions() == expected assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * C * DiagMatrix(a) * B cg = _array_contraction(_array_tensor_product(a, I1, b, I1, (a.T*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9)) expected = _array_contraction(_array_tensor_product(a, I1, OneArray(1), b, I1, OneArray(1), (a.T*b).applyfunc(cos)), (1, 3), (2, 10), (6, 8), (7, 11)) assert cg.split_multiple_contractions().dummy_eq(expected) assert convert_array_to_matrix(cg).doit().dummy_eq(MatMul(a, (a.T * b).applyfunc(cos), b.T)) def test_arrayexpr_convert_array_contraction_tp_additions(): a = ArrayAdd( _array_tensor_product(M, N), _array_tensor_product(N, M) ) tp = _array_tensor_product(P, a, Q) expr = _array_contraction(tp, (3, 4)) expected = _array_tensor_product( P, ArrayAdd( _array_contraction(_array_tensor_product(M, N), (1, 2)), _array_contraction(_array_tensor_product(N, M), (1, 2)), ), Q ) assert expr == expected assert convert_array_to_matrix(expr) == _array_tensor_product(P, M * N + N * M, Q) expr = _array_contraction(tp, (1, 2), (3, 4), (5, 6)) result = _array_contraction( _array_tensor_product( P, ArrayAdd( _array_contraction(_array_tensor_product(M, N), (1, 2)), _array_contraction(_array_tensor_product(N, M), (1, 2)), ), Q ), (1, 2), (3, 4)) assert expr == result assert convert_array_to_matrix(expr) == P * (M * N + N * M) * Q def test_arrayexpr_convert_array_to_implicit_matmul(): # Trivial dimensions are suppressed, so the result can be expressed in matrix form: cg = _array_tensor_product(a, b) assert convert_array_to_matrix(cg) == a * b.T cg = _array_tensor_product(a, b, I) assert convert_array_to_matrix(cg) == _array_tensor_product(a*b.T, I) cg = _array_tensor_product(I, a, b) assert convert_array_to_matrix(cg) == _array_tensor_product(I, a*b.T) cg = _array_tensor_product(a, I, b) assert convert_array_to_matrix(cg) == _array_tensor_product(a, I, b) cg = _array_contraction(_array_tensor_product(I, I), (1, 2)) assert convert_array_to_matrix(cg) == I cg = PermuteDims(_array_tensor_product(I, Identity(1)), [0, 2, 1, 3]) assert convert_array_to_matrix(cg) == I def test_arrayexpr_convert_array_to_matrix_remove_trivial_dims(): # Tensor Product: assert _remove_trivial_dims(_array_tensor_product(a, b)) == (a * b.T, [1, 3]) assert _remove_trivial_dims(_array_tensor_product(a.T, b)) == (a * b.T, [0, 3]) assert _remove_trivial_dims(_array_tensor_product(a, b.T)) == (a * b.T, [1, 2]) assert _remove_trivial_dims(_array_tensor_product(a.T, b.T)) == (a * b.T, [0, 2]) assert _remove_trivial_dims(_array_tensor_product(I, a.T, b.T)) == (_array_tensor_product(I, a * b.T), [2, 4]) assert _remove_trivial_dims(_array_tensor_product(a.T, I, b.T)) == (_array_tensor_product(a.T, I, b.T), []) assert _remove_trivial_dims(_array_tensor_product(a, I)) == (_array_tensor_product(a, I), []) assert _remove_trivial_dims(_array_tensor_product(I, a)) == (_array_tensor_product(I, a), []) assert _remove_trivial_dims(_array_tensor_product(a.T, b.T, c, d)) == ( _array_tensor_product(a * b.T, c * d.T), [0, 2, 5, 7]) assert _remove_trivial_dims(_array_tensor_product(a.T, I, b.T, c, d, I)) == ( _array_tensor_product(a.T, I, b*c.T, d, I), [4, 7]) # Addition: cg = ArrayAdd(_array_tensor_product(a, b), _array_tensor_product(c, d)) assert _remove_trivial_dims(cg) == (a * b.T + c * d.T, [1, 3]) # Permute Dims: cg = PermuteDims(_array_tensor_product(a, b), Permutation(3)(1, 2)) assert _remove_trivial_dims(cg) == (a * b.T, [2, 3]) cg = PermuteDims(_array_tensor_product(a, I, b), Permutation(5)(1, 2, 3, 4)) assert _remove_trivial_dims(cg) == (cg, []) cg = PermuteDims(_array_tensor_product(I, b, a), Permutation(5)(1, 2, 4, 5, 3)) assert _remove_trivial_dims(cg) == (PermuteDims(_array_tensor_product(I, b * a.T), [0, 2, 3, 1]), [4, 5]) # Diagonal: cg = _array_diagonal(_array_tensor_product(M, a), (1, 2)) assert _remove_trivial_dims(cg) == (cg, []) # Contraction: cg = _array_contraction(_array_tensor_product(M, a), (1, 2)) assert _remove_trivial_dims(cg) == (cg, []) # A few more cases to test the removal and shift of nested removed axes # with array contractions and array diagonals: tp = _array_tensor_product( OneMatrix(1, 1), M, x, OneMatrix(1, 1), Identity(1), ) expr = _array_contraction(tp, (1, 8)) rexpr, removed = _remove_trivial_dims(expr) assert removed == [0, 5, 6, 7] expr = _array_contraction(tp, (1, 8), (3, 4)) rexpr, removed = _remove_trivial_dims(expr) assert removed == [0, 3, 4, 5] expr = _array_diagonal(tp, (1, 8)) rexpr, removed = _remove_trivial_dims(expr) assert removed == [0, 5, 6, 7, 8] expr = _array_diagonal(tp, (1, 8), (3, 4)) rexpr, removed = _remove_trivial_dims(expr) assert removed == [0, 3, 4, 5, 6] expr = _array_diagonal(_array_contraction(_array_tensor_product(A, x, I, I1), (1, 2, 5)), (1, 4)) rexpr, removed = _remove_trivial_dims(expr) assert removed == [2, 3] cg = _array_diagonal(_array_tensor_product(PermuteDims(_array_tensor_product(x, I1), Permutation(1, 2, 3)), (x.T*x).applyfunc(sqrt)), (2, 4), (3, 5)) rexpr, removed = _remove_trivial_dims(cg) assert removed == [1, 2] # Contractions with identity matrices need to be followed by a permutation # in order cg = _array_contraction(_array_tensor_product(A, B, C, M, I), (1, 8)) ret, removed = _remove_trivial_dims(cg) assert ret == PermuteDims(_array_tensor_product(A, B, C, M), [0, 2, 3, 4, 5, 6, 7, 1]) assert removed == [] cg = _array_contraction(_array_tensor_product(A, B, C, M, I), (1, 8), (3, 4)) ret, removed = _remove_trivial_dims(cg) assert ret == PermuteDims(_array_contraction(_array_tensor_product(A, B, C, M), (3, 4)), [0, 2, 3, 4, 5, 1]) assert removed == [] # Trivial matrices are sometimes inserted into MatMul expressions: cg = _array_tensor_product(b*b.T, a.T*a) ret, removed = _remove_trivial_dims(cg) assert ret == b*a.T*a*b.T assert removed == [2, 3] Xs = ArraySymbol("X", (3, 2, k)) cg = _array_tensor_product(M, Xs, b.T*c, a*a.T, b*b.T, c.T*d) ret, removed = _remove_trivial_dims(cg) assert ret == _array_tensor_product(M, Xs, a*b.T*c*c.T*d*a.T, b*b.T) assert removed == [5, 6, 11, 12] cg = _array_diagonal(_array_tensor_product(I, I1, x), (1, 4), (3, 5)) assert _remove_trivial_dims(cg) == (PermuteDims(_array_diagonal(_array_tensor_product(I, x), (1, 2)), Permutation(1, 2)), [1]) expr = _array_diagonal(_array_tensor_product(x, I, y), (0, 2)) assert _remove_trivial_dims(expr) == (PermuteDims(_array_tensor_product(DiagMatrix(x), y), [1, 2, 3, 0]), [0]) expr = _array_diagonal(_array_tensor_product(x, I, y), (0, 2), (3, 4)) assert _remove_trivial_dims(expr) == (expr, []) def test_arrayexpr_convert_array_to_matrix_diag2contraction_diagmatrix(): cg = _array_diagonal(_array_tensor_product(M, a), (1, 2)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == _array_contraction(_array_tensor_product(M, OneArray(1), DiagMatrix(a)), (1, 3)) raises(ValueError, lambda: _array_diagonal(_array_tensor_product(a, M), (1, 2))) cg = _array_diagonal(_array_tensor_product(a.T, M), (1, 2)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == _array_contraction(_array_tensor_product(OneArray(1), M, DiagMatrix(a.T)), (1, 4)) cg = _array_diagonal(_array_tensor_product(a.T, M, N, b.T), (1, 2), (4, 7)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == _array_contraction( _array_tensor_product(OneArray(1), M, N, OneArray(1), DiagMatrix(a.T), DiagMatrix(b.T)), (1, 7), (3, 9)) cg = _array_diagonal(_array_tensor_product(a, M, N, b.T), (0, 2), (4, 7)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == _array_contraction( _array_tensor_product(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (1, 6), (3, 9)) cg = _array_diagonal(_array_tensor_product(a, M, N, b.T), (0, 4), (3, 7)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == _array_contraction( _array_tensor_product(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (3, 6), (2, 9)) I1 = Identity(1) x = MatrixSymbol("x", k, 1) A = MatrixSymbol("A", k, k) cg = _array_diagonal(_array_tensor_product(x, A.T, I1), (0, 2)) assert _array_diag2contr_diagmatrix(cg).shape == cg.shape assert _array2matrix(cg).shape == cg.shape def test_arrayexpr_convert_array_to_matrix_support_function(): assert _support_function_tp1_recognize([], [2 * k]) == 2 * k assert _support_function_tp1_recognize([(1, 2)], [A, 2 * k, B, 3]) == 6 * k * A * B assert _support_function_tp1_recognize([(0, 3), (1, 2)], [A, B]) == Trace(A * B) assert _support_function_tp1_recognize([(1, 2)], [A, B]) == A * B assert _support_function_tp1_recognize([(0, 2)], [A, B]) == A.T * B assert _support_function_tp1_recognize([(1, 3)], [A, B]) == A * B.T assert _support_function_tp1_recognize([(0, 3)], [A, B]) == A.T * B.T assert _support_function_tp1_recognize([(1, 2), (5, 6)], [A, B, C, D]) == _array_tensor_product(A * B, C * D) assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims( _array_tensor_product(A * C, B * D), [0, 2, 1, 3]) assert _support_function_tp1_recognize([(0, 3), (1, 4)], [A, B, C]) == B * A * C assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4), (7, 8)], [X, Y, A, B, C, D]) == X * Y * A * B * C * D assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4)], [X, Y, A, B, C, D]) == _array_tensor_product(X * Y * A * B, C * D) assert _support_function_tp1_recognize([(1, 7), (3, 8), (4, 11)], [X, Y, A, B, C, D]) == PermuteDims( _array_tensor_product(X * B.T, Y * C, A.T * D.T), [0, 2, 4, 1, 3, 5] ) assert _support_function_tp1_recognize([(0, 1), (3, 6), (5, 8)], [X, A, B, C, D]) == PermuteDims( _array_tensor_product(Trace(X) * A * C, B * D), [0, 2, 1, 3]) assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [A, A, B, C, D]) == A ** 2 * B * C * D assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [X, A, B, C, D]) == X * A * B * C * D assert _support_function_tp1_recognize([(1, 6), (3, 8), (5, 10)], [X, Y, A, B, C, D]) == PermuteDims( _array_tensor_product(X * B, Y * C, A * D), [0, 2, 4, 1, 3, 5] ) assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims( _array_tensor_product(A * C, B * D), [0, 2, 1, 3]) assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D def test_convert_array_to_hadamard_products(): expr = HadamardProduct(M, N) cg = convert_matrix_to_array(expr) ret = convert_array_to_matrix(cg) assert ret == expr expr = HadamardProduct(M, N)*P cg = convert_matrix_to_array(expr) ret = convert_array_to_matrix(cg) assert ret == expr expr = Q*HadamardProduct(M, N)*P cg = convert_matrix_to_array(expr) ret = convert_array_to_matrix(cg) assert ret == expr expr = Q*HadamardProduct(M, N.T)*P cg = convert_matrix_to_array(expr) ret = convert_array_to_matrix(cg) assert ret == expr expr = HadamardProduct(M, N)*HadamardProduct(Q, P) cg = convert_matrix_to_array(expr) ret = convert_array_to_matrix(cg) assert expr == ret expr = P.T*HadamardProduct(M, N)*HadamardProduct(Q, P) cg = convert_matrix_to_array(expr) ret = convert_array_to_matrix(cg) assert expr == ret # ArrayDiagonal should be converted cg = _array_diagonal(_array_tensor_product(M, N, Q), (1, 3), (0, 2, 4)) ret = convert_array_to_matrix(cg) expected = PermuteDims(_array_diagonal(_array_tensor_product(HadamardProduct(M.T, N.T), Q), (1, 2)), [1, 0, 2]) assert expected == ret # Special case that should return the same expression: cg = _array_diagonal(_array_tensor_product(HadamardProduct(M, N), Q), (0, 2)) ret = convert_array_to_matrix(cg) assert ret == cg # Hadamard products with traces: expr = Trace(HadamardProduct(M, N)) cg = convert_matrix_to_array(expr) ret = convert_array_to_matrix(cg) assert ret == Trace(HadamardProduct(M.T, N.T)) expr = Trace(A*HadamardProduct(M, N)) cg = convert_matrix_to_array(expr) ret = convert_array_to_matrix(cg) assert ret == Trace(HadamardProduct(M, N)*A) expr = Trace(HadamardProduct(A, M)*N) cg = convert_matrix_to_array(expr) ret = convert_array_to_matrix(cg) assert ret == Trace(HadamardProduct(M.T, N)*A) # These should not be converted into Hadamard products: cg = _array_diagonal(_array_tensor_product(M, N), (0, 1, 2, 3)) ret = convert_array_to_matrix(cg) assert ret == cg cg = _array_diagonal(_array_tensor_product(A), (0, 1)) ret = convert_array_to_matrix(cg) assert ret == cg cg = _array_diagonal(_array_tensor_product(M, N, P), (0, 2, 4), (1, 3, 5)) assert convert_array_to_matrix(cg) == HadamardProduct(M, N, P) cg = _array_diagonal(_array_tensor_product(M, N, P), (0, 3, 4), (1, 2, 5)) assert convert_array_to_matrix(cg) == HadamardProduct(M, P, N.T) cg = _array_diagonal(_array_tensor_product(I, I1, x), (1, 4), (3, 5)) assert convert_array_to_matrix(cg) == DiagMatrix(x) def test_identify_removable_identity_matrices(): D = DiagonalMatrix(MatrixSymbol("D", k, k)) cg = _array_contraction(_array_tensor_product(A, B, I), (1, 2, 4, 5)) expected = _array_contraction(_array_tensor_product(A, B), (1, 2)) assert identify_removable_identity_matrices(cg) == expected cg = _array_contraction(_array_tensor_product(A, B, C, I), (1, 3, 5, 6, 7)) expected = _array_contraction(_array_tensor_product(A, B, C), (1, 3, 5)) assert identify_removable_identity_matrices(cg) == expected # Tests with diagonal matrices: cg = _array_contraction(_array_tensor_product(A, B, D), (1, 2, 4, 5)) ret = identify_removable_identity_matrices(cg) expected = _array_contraction(_array_tensor_product(A, B, D), (1, 4), (2, 5)) assert ret == expected cg = _array_contraction(_array_tensor_product(A, B, D, M, N), (1, 2, 4, 5, 6, 8)) ret = identify_removable_identity_matrices(cg) assert ret == cg def test_combine_removed(): assert _combine_removed(6, [0, 1, 2], [0, 1, 2]) == [0, 1, 2, 3, 4, 5] assert _combine_removed(8, [2, 5], [1, 3, 4]) == [1, 2, 4, 5, 6] assert _combine_removed(8, [7], []) == [7] def test_array_contraction_to_diagonal_multiple_identities(): expr = _array_contraction(_array_tensor_product(A, B, I, C), (1, 2, 4), (5, 6)) assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, []) assert convert_array_to_matrix(expr) == _array_contraction(_array_tensor_product(A, B, C), (1, 2, 4)) expr = _array_contraction(_array_tensor_product(A, I, I), (1, 2, 4)) assert _array_contraction_to_diagonal_multiple_identity(expr) == (A, [2]) assert convert_array_to_matrix(expr) == A expr = _array_contraction(_array_tensor_product(A, I, I, B), (1, 2, 4), (3, 6)) assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, []) expr = _array_contraction(_array_tensor_product(A, I, I, B), (1, 2, 3, 4, 6)) assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, []) def test_convert_array_element_to_matrix(): expr = ArrayElement(M, (i, j)) assert convert_array_to_matrix(expr) == MatrixElement(M, i, j) expr = ArrayElement(_array_contraction(_array_tensor_product(M, N), (1, 3)), (i, j)) assert convert_array_to_matrix(expr) == MatrixElement(M*N.T, i, j) expr = ArrayElement(_array_tensor_product(M, N), (i, j, m, n)) assert convert_array_to_matrix(expr) == expr def test_convert_array_elementwise_function_to_matrix(): d = Dummy("d") expr = ArrayElementwiseApplyFunc(Lambda(d, sin(d)), x.T*y) assert convert_array_to_matrix(expr) == sin(x.T*y) expr = ArrayElementwiseApplyFunc(Lambda(d, d**2), x.T*y) assert convert_array_to_matrix(expr) == (x.T*y)**2 expr = ArrayElementwiseApplyFunc(Lambda(d, sin(d)), x) assert convert_array_to_matrix(expr).dummy_eq(x.applyfunc(sin)) expr = ArrayElementwiseApplyFunc(Lambda(d, 1 / (2 * sqrt(d))), x) assert convert_array_to_matrix(expr) == S.Half * HadamardPower(x, -S.Half) def test_array2matrix(): # See issue https://github.com/sympy/sympy/pull/22877 expr = PermuteDims(ArrayContraction(ArrayTensorProduct(x, I, I1, x), (0, 3), (1, 7)), Permutation(2, 3)) expected = PermuteDims(ArrayTensorProduct(x*x.T, I1), Permutation(3)(1, 2)) assert _array2matrix(expr) == expected def test_recognize_broadcasting(): expr = ArrayTensorProduct(x.T*x, A) assert _remove_trivial_dims(expr) == (KroneckerProduct(x.T*x, A), [0, 1]) expr = ArrayTensorProduct(A, x.T*x) assert _remove_trivial_dims(expr) == (KroneckerProduct(A, x.T*x), [2, 3]) expr = ArrayTensorProduct(A, B, x.T*x, C) assert _remove_trivial_dims(expr) == (ArrayTensorProduct(A, KroneckerProduct(B, x.T*x), C), [4, 5]) # Always prefer matrix multiplication to Kronecker product, if possible: expr = ArrayTensorProduct(a, b, x.T*x) assert _remove_trivial_dims(expr) == (a*x.T*x*b.T, [1, 3, 4, 5])
455106fea52c5e2047f601ed5a9dbef69302e09d9a2dce2251dcc114cd10c93c
from sympy import tanh from sympy.concrete.summations import Sum from sympy.core.symbol import symbols from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.special import Identity from sympy.tensor.array.expressions import ArrayElementwiseApplyFunc from sympy.tensor.indexed import IndexedBase from sympy.combinatorics import Permutation from sympy.tensor.array.expressions.array_expressions import ArrayContraction, ArrayTensorProduct, \ ArrayDiagonal, ArrayAdd, PermuteDims, ArrayElement, _array_tensor_product, _array_contraction, _array_diagonal, \ _array_add, _permute_dims, ArraySymbol, OneArray from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array, _convert_indexed_to_array from sympy.testing.pytest import raises A, B = symbols("A B", cls=IndexedBase) i, j, k, l, m, n = symbols("i j k l m n") d0, d1, d2, d3 = symbols("d0:4") I = Identity(k) M = MatrixSymbol("M", k, k) N = MatrixSymbol("N", k, k) P = MatrixSymbol("P", k, k) Q = MatrixSymbol("Q", k, k) a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) d = MatrixSymbol("d", k, 1) def test_arrayexpr_convert_index_to_array_support_function(): expr = M[i, j] assert _convert_indexed_to_array(expr) == (M, (i, j)) expr = M[i, j]*N[k, l] assert _convert_indexed_to_array(expr) == (ArrayTensorProduct(M, N), (i, j, k, l)) expr = M[i, j]*N[j, k] assert _convert_indexed_to_array(expr) == (ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2)), (i, k, j)) expr = Sum(M[i, j]*N[j, k], (j, 0, k-1)) assert _convert_indexed_to_array(expr) == (ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), (i, k)) expr = M[i, j] + N[i, j] assert _convert_indexed_to_array(expr) == (ArrayAdd(M, N), (i, j)) expr = M[i, j] + N[j, i] assert _convert_indexed_to_array(expr) == (ArrayAdd(M, PermuteDims(N, Permutation([1, 0]))), (i, j)) expr = M[i, j] + M[j, i] assert _convert_indexed_to_array(expr) == (ArrayAdd(M, PermuteDims(M, Permutation([1, 0]))), (i, j)) expr = (M*N*P)[i, j] assert _convert_indexed_to_array(expr) == (_array_contraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)), (i, j)) expr = expr.function # Disregard summation in previous expression ret1, ret2 = _convert_indexed_to_array(expr) assert ret1 == ArrayDiagonal(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)) assert str(ret2) == "(i, j, _i_1, _i_2)" expr = KroneckerDelta(i, j)*M[i, k] assert _convert_indexed_to_array(expr) == (M, ({i, j}, k)) expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*M[i, l] assert _convert_indexed_to_array(expr) == (M, ({i, j, k}, l)) expr = KroneckerDelta(j, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l]) assert _convert_indexed_to_array(expr) == (_array_diagonal(_array_add( ArrayTensorProduct(M, N), _permute_dims(ArrayTensorProduct(M, N), Permutation(0, 2)(1, 3)) ), (1, 2)), (i, l, frozenset({j, k}))) expr = KroneckerDelta(j, m)*KroneckerDelta(m, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l]) assert _convert_indexed_to_array(expr) == (_array_diagonal(_array_add( ArrayTensorProduct(M, N), _permute_dims(ArrayTensorProduct(M, N), Permutation(0, 2)(1, 3)) ), (1, 2)), (i, l, frozenset({j, m, k}))) expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*KroneckerDelta(k,m)*M[i, 0]*KroneckerDelta(m, n) assert _convert_indexed_to_array(expr) == (M, ({i, j, k, m, n}, 0)) expr = M[i, i] assert _convert_indexed_to_array(expr) == (ArrayDiagonal(M, (0, 1)), (i,)) def test_arrayexpr_convert_indexed_to_array_expression(): s = Sum(A[i]*B[i], (i, 0, 3)) cg = convert_indexed_to_array(s) assert cg == ArrayContraction(ArrayTensorProduct(A, B), (0, 1)) expr = M*N result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) elem = expr[i, j] assert convert_indexed_to_array(elem) == result expr = M*N*M elem = expr[i, j] result = _array_contraction(_array_tensor_product(M, M, N), (1, 4), (2, 5)) cg = convert_indexed_to_array(elem) assert cg == result cg = convert_indexed_to_array((M * N * P)[i, j]) assert cg == _array_contraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)) cg = convert_indexed_to_array((M * N.T * P)[i, j]) assert cg == _array_contraction(ArrayTensorProduct(M, N, P), (1, 3), (2, 4)) expr = -2*M*N elem = expr[i, j] cg = convert_indexed_to_array(elem) assert cg == ArrayContraction(ArrayTensorProduct(-2, M, N), (1, 2)) def test_arrayexpr_convert_array_element_to_array_expression(): A = ArraySymbol("A", (k,)) B = ArraySymbol("B", (k,)) s = Sum(A[i]*B[i], (i, 0, k-1)) cg = convert_indexed_to_array(s) assert cg == ArrayContraction(ArrayTensorProduct(A, B), (0, 1)) s = A[i]*B[i] cg = convert_indexed_to_array(s) assert cg == ArrayDiagonal(ArrayTensorProduct(A, B), (0, 1)) s = A[i]*B[j] cg = convert_indexed_to_array(s, [i, j]) assert cg == ArrayTensorProduct(A, B) cg = convert_indexed_to_array(s, [j, i]) assert cg == ArrayTensorProduct(B, A) s = tanh(A[i]*B[j]) cg = convert_indexed_to_array(s, [i, j]) assert cg.dummy_eq(ArrayElementwiseApplyFunc(tanh, ArrayTensorProduct(A, B))) def test_arrayexpr_convert_indexed_to_array_and_back_to_matrix(): expr = a.T*b elem = expr[0, 0] cg = convert_indexed_to_array(elem) assert cg == ArrayElement(ArrayContraction(ArrayTensorProduct(a, b), (0, 2)), [0, 0]) expr = M[i,j] + N[i,j] p1, p2 = _convert_indexed_to_array(expr) assert convert_array_to_matrix(p1) == M + N expr = M[i,j] + N[j,i] p1, p2 = _convert_indexed_to_array(expr) assert convert_array_to_matrix(p1) == M + N.T expr = M[i,j]*N[k,l] + N[i,j]*M[k,l] p1, p2 = _convert_indexed_to_array(expr) assert convert_array_to_matrix(p1) == ArrayAdd( ArrayTensorProduct(M, N), ArrayTensorProduct(N, M)) expr = (M*N*P)[i, j] p1, p2 = _convert_indexed_to_array(expr) assert convert_array_to_matrix(p1) == M * N * P expr = Sum(M[i,j]*(N*P)[j,m], (j, 0, k-1)) p1, p2 = _convert_indexed_to_array(expr) assert convert_array_to_matrix(p1) == M * N * P expr = Sum((P[j, m] + P[m, j])*(M[i,j]*N[m,n] + N[i,j]*M[m,n]), (j, 0, k-1), (m, 0, k-1)) p1, p2 = _convert_indexed_to_array(expr) assert convert_array_to_matrix(p1) == M * P * N + M * P.T * N + N * P * M + N * P.T * M def test_arrayexpr_convert_indexed_to_array_out_of_bounds(): expr = Sum(M[i, i], (i, 0, 4)) raises(ValueError, lambda: convert_indexed_to_array(expr)) expr = Sum(M[i, i], (i, 0, k)) raises(ValueError, lambda: convert_indexed_to_array(expr)) expr = Sum(M[i, i], (i, 1, k-1)) raises(ValueError, lambda: convert_indexed_to_array(expr)) expr = Sum(M[i, j]*N[j,m], (j, 0, 4)) raises(ValueError, lambda: convert_indexed_to_array(expr)) expr = Sum(M[i, j]*N[j,m], (j, 0, k)) raises(ValueError, lambda: convert_indexed_to_array(expr)) expr = Sum(M[i, j]*N[j,m], (j, 1, k-1)) raises(ValueError, lambda: convert_indexed_to_array(expr)) def test_arrayexpr_convert_indexed_to_array_broadcast(): A = ArraySymbol("A", (3, 3)) B = ArraySymbol("B", (3, 3)) expr = A[i, j] + B[k, l] O2 = OneArray(3, 3) expected = ArrayAdd(ArrayTensorProduct(A, O2), ArrayTensorProduct(O2, B)) assert convert_indexed_to_array(expr) == expected assert convert_indexed_to_array(expr, [i, j, k, l]) == expected assert convert_indexed_to_array(expr, [l, k, i, j]) == ArrayAdd(PermuteDims(ArrayTensorProduct(O2, A), [1, 0, 2, 3]), PermuteDims(ArrayTensorProduct(B, O2), [1, 0, 2, 3])) expr = A[i, j] + B[j, k] O1 = OneArray(3) assert convert_indexed_to_array(expr, [i, j, k]) == ArrayAdd(ArrayTensorProduct(A, O1), ArrayTensorProduct(O1, B)) C = ArraySymbol("C", (d0, d1)) D = ArraySymbol("D", (d3, d1)) expr = C[i, j] + D[k, j] assert convert_indexed_to_array(expr, [i, j, k]) == ArrayAdd(ArrayTensorProduct(C, OneArray(d3)), PermuteDims(ArrayTensorProduct(OneArray(d0), D), [0, 2, 1])) X = ArraySymbol("X", (5, 3)) expr = X[i, n] - X[j, n] assert convert_indexed_to_array(expr, [i, j, n]) == ArrayAdd(ArrayTensorProduct(-1, OneArray(5), X), PermuteDims(ArrayTensorProduct(X, OneArray(5)), [0, 2, 1])) raises(ValueError, lambda: convert_indexed_to_array(C[i, j] + D[i, j]))
0c6f08a14b710b2d9a7168d41d450abb86d1b13c576de14b16328c2c0d8674b6
from sympy import MatrixSymbol, symbols, Sum from sympy.tensor.array.expressions import conv_array_to_indexed, from_array_to_indexed, ArrayTensorProduct, \ ArrayContraction, conv_array_to_matrix, from_array_to_matrix, conv_matrix_to_array, from_matrix_to_array, \ conv_indexed_to_array, from_indexed_to_array from sympy.testing.pytest import warns from sympy.utilities.exceptions import SymPyDeprecationWarning def test_deprecated_conv_module_results(): M = MatrixSymbol("M", 3, 3) N = MatrixSymbol("N", 3, 3) i, j, d = symbols("i j d") x = ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) y = Sum(M[i, d]*N[d, j], (d, 0, 2)) with warns(SymPyDeprecationWarning, test_stacklevel=False): assert conv_array_to_indexed.convert_array_to_indexed(x, [i, j]).dummy_eq(from_array_to_indexed.convert_array_to_indexed(x, [i, j])) assert conv_array_to_matrix.convert_array_to_matrix(x) == from_array_to_matrix.convert_array_to_matrix(x) assert conv_matrix_to_array.convert_matrix_to_array(M*N) == from_matrix_to_array.convert_matrix_to_array(M*N) assert conv_indexed_to_array.convert_indexed_to_array(y) == from_indexed_to_array.convert_indexed_to_array(y)
eb23711971fa057e7ad3b1538cc930476b7dc0d56512157c24c4a1e14216bb1f
from sympy import Sum, Dummy, sin from sympy.tensor.array.expressions import ArraySymbol, ArrayTensorProduct, ArrayContraction, PermuteDims, \ ArrayDiagonal, ArrayAdd, OneArray, ZeroArray, convert_indexed_to_array, ArrayElementwiseApplyFunc, Reshape from sympy.tensor.array.expressions.from_array_to_indexed import convert_array_to_indexed from sympy.abc import i, j, k, l, m, n, o def test_convert_array_to_indexed_main(): A = ArraySymbol("A", (3, 3, 3)) B = ArraySymbol("B", (3, 3)) C = ArraySymbol("C", (3, 3)) d_ = Dummy("d_") assert convert_array_to_indexed(A, [i, j, k]) == A[i, j, k] expr = ArrayTensorProduct(A, B, C) conv = convert_array_to_indexed(expr, [i,j,k,l,m,n,o]) assert conv == A[i,j,k]*B[l,m]*C[n,o] assert convert_indexed_to_array(conv, [i,j,k,l,m,n,o]) == expr expr = ArrayContraction(A, (0, 2)) assert convert_array_to_indexed(expr, [i]).dummy_eq(Sum(A[d_, i, d_], (d_, 0, 2))) expr = ArrayDiagonal(A, (0, 2)) assert convert_array_to_indexed(expr, [i, j]) == A[j, i, j] expr = PermuteDims(A, [1, 2, 0]) conv = convert_array_to_indexed(expr, [i, j, k]) assert conv == A[k, i, j] assert convert_indexed_to_array(conv, [i, j, k]) == expr expr = ArrayAdd(B, C, PermuteDims(C, [1, 0])) conv = convert_array_to_indexed(expr, [i, j]) assert conv == B[i, j] + C[i, j] + C[j, i] assert convert_indexed_to_array(conv, [i, j]) == expr expr = ArrayElementwiseApplyFunc(sin, A) conv = convert_array_to_indexed(expr, [i, j, k]) assert conv == sin(A[i, j, k]) assert convert_indexed_to_array(conv, [i, j, k]).dummy_eq(expr) assert convert_array_to_indexed(OneArray(3, 3), [i, j]) == 1 assert convert_array_to_indexed(ZeroArray(3, 3), [i, j]) == 0 expr = Reshape(A, (27,)) assert convert_array_to_indexed(expr, [i]) == A[i // 9, i // 3 % 3, i % 3] X = ArraySymbol("X", (2, 3, 4, 5, 6)) expr = Reshape(X, (2*3*4*5*6,)) assert convert_array_to_indexed(expr, [i]) == X[i // 360, i // 120 % 3, i // 30 % 4, i // 6 % 5, i % 6] expr = Reshape(X, (4, 9, 2, 2, 5)) one_index = 180*i + 20*j + 10*k + 5*l + m expected = X[one_index // (3*4*5*6), one_index // (4*5*6) % 3, one_index // (5*6) % 4, one_index // 6 % 5, one_index % 6] assert convert_array_to_indexed(expr, [i, j, k, l, m]) == expected X = ArraySymbol("X", (2*3*5,)) expr = Reshape(X, (2, 3, 5)) assert convert_array_to_indexed(expr, [i, j, k]) == X[15*i + 5*j + k]
1b683913497e140070632428c1b28abcb70423c3558895da60b5b779411cbe3c
from sympy import Lambda, KroneckerProduct from sympy.core.symbol import symbols, Dummy from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct) from sympy.matrices.expressions.inverse import Inverse from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.matpow import MatPow from sympy.matrices.expressions.special import Identity from sympy.matrices.expressions.trace import Trace from sympy.matrices.expressions.transpose import Transpose from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction, \ PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, _array_contraction, _array_tensor_product, Reshape from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array i, j, k, l, m, n = symbols("i j k l m n") I = Identity(k) M = MatrixSymbol("M", k, k) N = MatrixSymbol("N", k, k) P = MatrixSymbol("P", k, k) Q = MatrixSymbol("Q", k, k) A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) D = MatrixSymbol("D", k, k) X = MatrixSymbol("X", k, k) Y = MatrixSymbol("Y", k, k) a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) d = MatrixSymbol("d", k, 1) def test_arrayexpr_convert_matrix_to_array(): expr = M*N result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) assert convert_matrix_to_array(expr) == result expr = M*N*M result = _array_contraction(ArrayTensorProduct(M, N, M), (1, 2), (3, 4)) assert convert_matrix_to_array(expr) == result expr = Transpose(M) assert convert_matrix_to_array(expr) == PermuteDims(M, [1, 0]) expr = M*Transpose(N) assert convert_matrix_to_array(expr) == _array_contraction(_array_tensor_product(M, PermuteDims(N, [1, 0])), (1, 2)) expr = 3*M*N res = convert_matrix_to_array(expr) rexpr = convert_array_to_matrix(res) assert expr == rexpr expr = 3*M + N*M.T*M + 4*k*N res = convert_matrix_to_array(expr) rexpr = convert_array_to_matrix(res) assert expr == rexpr expr = Inverse(M)*N rexpr = convert_array_to_matrix(convert_matrix_to_array(expr)) assert expr == rexpr expr = M**2 rexpr = convert_array_to_matrix(convert_matrix_to_array(expr)) assert expr == rexpr expr = M*(2*N + 3*M) res = convert_matrix_to_array(expr) rexpr = convert_array_to_matrix(res) assert expr == rexpr expr = Trace(M) result = ArrayContraction(M, (0, 1)) assert convert_matrix_to_array(expr) == result expr = 3*Trace(M) result = ArrayContraction(ArrayTensorProduct(3, M), (0, 1)) assert convert_matrix_to_array(expr) == result expr = 3*Trace(Trace(M) * M) result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3)) assert convert_matrix_to_array(expr) == result expr = 3*Trace(M)**2 result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3)) assert convert_matrix_to_array(expr) == result expr = HadamardProduct(M, N) result = ArrayDiagonal(ArrayTensorProduct(M, N), (0, 2), (1, 3)) assert convert_matrix_to_array(expr) == result expr = HadamardProduct(M*N, N*M) result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, N, M), (1, 2), (5, 6)), (0, 2), (1, 3)) assert convert_matrix_to_array(expr) == result expr = HadamardPower(M, 2) result = ArrayDiagonal(ArrayTensorProduct(M, M), (0, 2), (1, 3)) assert convert_matrix_to_array(expr) == result expr = HadamardPower(M*N, 2) result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, M, N), (1, 2), (5, 6)), (0, 2), (1, 3)) assert convert_matrix_to_array(expr) == result expr = HadamardPower(M, n) d0 = Dummy("d0") result = ArrayElementwiseApplyFunc(Lambda(d0, d0**n), M) assert convert_matrix_to_array(expr).dummy_eq(result) expr = M**2 assert isinstance(expr, MatPow) assert convert_matrix_to_array(expr) == ArrayContraction(ArrayTensorProduct(M, M), (1, 2)) expr = a.T*b cg = convert_matrix_to_array(expr) assert cg == ArrayContraction(ArrayTensorProduct(a, b), (0, 2)) expr = KroneckerProduct(A, B) cg = convert_matrix_to_array(expr) assert cg == Reshape(PermuteDims(ArrayTensorProduct(A, B), [0, 2, 1, 3]), (k**2, k**2)) expr = KroneckerProduct(A, B, C, D) cg = convert_matrix_to_array(expr) assert cg == Reshape(PermuteDims(ArrayTensorProduct(A, B, C, D), [0, 2, 4, 6, 1, 3, 5, 7]), (k**4, k**4))
5ae7391b4d88cba300c0a7e2854b9042b36ed5590d554fd6e18c7730d0e2ca0d
from sympy.assumptions.ask import Q from sympy.assumptions.refine import refine from sympy.core.numbers import oo from sympy.core.relational import Equality, Eq, Ne from sympy.core.singleton import S from sympy.core.symbol import (Dummy, symbols) from sympy.functions import Piecewise from sympy.functions.elementary.trigonometric import cos, sin from sympy.sets.sets import (Interval, Union) from sympy.simplify.simplify import simplify from sympy.logic.boolalg import ( And, Boolean, Equivalent, ITE, Implies, Nand, Nor, Not, Or, POSform, SOPform, Xor, Xnor, conjuncts, disjuncts, distribute_or_over_and, distribute_and_over_or, eliminate_implications, is_nnf, is_cnf, is_dnf, simplify_logic, to_nnf, to_cnf, to_dnf, to_int_repr, bool_map, true, false, BooleanAtom, is_literal, term_to_integer, truth_table, as_Boolean, to_anf, is_anf, distribute_xor_over_and, anf_coeffs, ANFform, bool_minterm, bool_maxterm, bool_monomial, _check_pair, _convert_to_varsSOP, _convert_to_varsPOS, Exclusive, gateinputcount) from sympy.assumptions.cnf import CNF from sympy.testing.pytest import raises, XFAIL, slow from itertools import combinations, permutations, product A, B, C, D = symbols('A:D') a, b, c, d, e, w, x, y, z = symbols('a:e w:z') def test_overloading(): """Test that |, & are overloaded as expected""" assert A & B == And(A, B) assert A | B == Or(A, B) assert (A & B) | C == Or(And(A, B), C) assert A >> B == Implies(A, B) assert A << B == Implies(B, A) assert ~A == Not(A) assert A ^ B == Xor(A, B) def test_And(): assert And() is true assert And(A) == A assert And(True) is true assert And(False) is false assert And(True, True) is true assert And(True, False) is false assert And(False, False) is false assert And(True, A) == A assert And(False, A) is false assert And(True, True, True) is true assert And(True, True, A) == A assert And(True, False, A) is false assert And(1, A) == A raises(TypeError, lambda: And(2, A)) raises(TypeError, lambda: And(A < 2, A)) assert And(A < 1, A >= 1) is false e = A > 1 assert And(e, e.canonical) == e.canonical g, l, ge, le = A > B, B < A, A >= B, B <= A assert And(g, l, ge, le) == And(ge, g) assert {And(*i) for i in permutations((l,g,le,ge))} == {And(ge, g)} assert And(And(Eq(a, 0), Eq(b, 0)), And(Ne(a, 0), Eq(c, 0))) is false def test_Or(): assert Or() is false assert Or(A) == A assert Or(True) is true assert Or(False) is false assert Or(True, True) is true assert Or(True, False) is true assert Or(False, False) is false assert Or(True, A) is true assert Or(False, A) == A assert Or(True, False, False) is true assert Or(True, False, A) is true assert Or(False, False, A) == A assert Or(1, A) is true raises(TypeError, lambda: Or(2, A)) raises(TypeError, lambda: Or(A < 2, A)) assert Or(A < 1, A >= 1) is true e = A > 1 assert Or(e, e.canonical) == e g, l, ge, le = A > B, B < A, A >= B, B <= A assert Or(g, l, ge, le) == Or(g, ge) def test_Xor(): assert Xor() is false assert Xor(A) == A assert Xor(A, A) is false assert Xor(True, A, A) is true assert Xor(A, A, A, A, A) == A assert Xor(True, False, False, A, B) == ~Xor(A, B) assert Xor(True) is true assert Xor(False) is false assert Xor(True, True) is false assert Xor(True, False) is true assert Xor(False, False) is false assert Xor(True, A) == ~A assert Xor(False, A) == A assert Xor(True, False, False) is true assert Xor(True, False, A) == ~A assert Xor(False, False, A) == A assert isinstance(Xor(A, B), Xor) assert Xor(A, B, Xor(C, D)) == Xor(A, B, C, D) assert Xor(A, B, Xor(B, C)) == Xor(A, C) assert Xor(A < 1, A >= 1, B) == Xor(0, 1, B) == Xor(1, 0, B) e = A > 1 assert Xor(e, e.canonical) == Xor(0, 0) == Xor(1, 1) def test_rewrite_as_And(): expr = x ^ y assert expr.rewrite(And) == (x | y) & (~x | ~y) def test_rewrite_as_Or(): expr = x ^ y assert expr.rewrite(Or) == (x & ~y) | (y & ~x) def test_rewrite_as_Nand(): expr = (y & z) | (z & ~w) assert expr.rewrite(Nand) == ~(~(y & z) & ~(z & ~w)) def test_rewrite_as_Nor(): expr = z & (y | ~w) assert expr.rewrite(Nor) == ~(~z | ~(y | ~w)) def test_Not(): raises(TypeError, lambda: Not(True, False)) assert Not(True) is false assert Not(False) is true assert Not(0) is true assert Not(1) is false assert Not(2) is false def test_Nand(): assert Nand() is false assert Nand(A) == ~A assert Nand(True) is false assert Nand(False) is true assert Nand(True, True) is false assert Nand(True, False) is true assert Nand(False, False) is true assert Nand(True, A) == ~A assert Nand(False, A) is true assert Nand(True, True, True) is false assert Nand(True, True, A) == ~A assert Nand(True, False, A) is true def test_Nor(): assert Nor() is true assert Nor(A) == ~A assert Nor(True) is false assert Nor(False) is true assert Nor(True, True) is false assert Nor(True, False) is false assert Nor(False, False) is true assert Nor(True, A) is false assert Nor(False, A) == ~A assert Nor(True, True, True) is false assert Nor(True, True, A) is false assert Nor(True, False, A) is false def test_Xnor(): assert Xnor() is true assert Xnor(A) == ~A assert Xnor(A, A) is true assert Xnor(True, A, A) is false assert Xnor(A, A, A, A, A) == ~A assert Xnor(True) is false assert Xnor(False) is true assert Xnor(True, True) is true assert Xnor(True, False) is false assert Xnor(False, False) is true assert Xnor(True, A) == A assert Xnor(False, A) == ~A assert Xnor(True, False, False) is false assert Xnor(True, False, A) == A assert Xnor(False, False, A) == ~A def test_Implies(): raises(ValueError, lambda: Implies(A, B, C)) assert Implies(True, True) is true assert Implies(True, False) is false assert Implies(False, True) is true assert Implies(False, False) is true assert Implies(0, A) is true assert Implies(1, 1) is true assert Implies(1, 0) is false assert A >> B == B << A assert (A < 1) >> (A >= 1) == (A >= 1) assert (A < 1) >> (S.One > A) is true assert A >> A is true def test_Equivalent(): assert Equivalent(A, B) == Equivalent(B, A) == Equivalent(A, B, A) assert Equivalent() is true assert Equivalent(A, A) == Equivalent(A) is true assert Equivalent(True, True) == Equivalent(False, False) is true assert Equivalent(True, False) == Equivalent(False, True) is false assert Equivalent(A, True) == A assert Equivalent(A, False) == Not(A) assert Equivalent(A, B, True) == A & B assert Equivalent(A, B, False) == ~A & ~B assert Equivalent(1, A) == A assert Equivalent(0, A) == Not(A) assert Equivalent(A, Equivalent(B, C)) != Equivalent(Equivalent(A, B), C) assert Equivalent(A < 1, A >= 1) is false assert Equivalent(A < 1, A >= 1, 0) is false assert Equivalent(A < 1, A >= 1, 1) is false assert Equivalent(A < 1, S.One > A) == Equivalent(1, 1) == Equivalent(0, 0) assert Equivalent(Equality(A, B), Equality(B, A)) is true def test_Exclusive(): assert Exclusive(False, False, False) is true assert Exclusive(True, False, False) is true assert Exclusive(True, True, False) is false assert Exclusive(True, True, True) is false def test_equals(): assert Not(Or(A, B)).equals(And(Not(A), Not(B))) is True assert Equivalent(A, B).equals((A >> B) & (B >> A)) is True assert ((A | ~B) & (~A | B)).equals((~A & ~B) | (A & B)) is True assert (A >> B).equals(~A >> ~B) is False assert (A >> (B >> A)).equals(A >> (C >> A)) is False raises(NotImplementedError, lambda: (A & B).equals(A > B)) def test_simplification_boolalg(): """ Test working of simplification methods. """ set1 = [[0, 0, 1], [0, 1, 1], [1, 0, 0], [1, 1, 0]] set2 = [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1]] assert SOPform([x, y, z], set1) == Or(And(Not(x), z), And(Not(z), x)) assert Not(SOPform([x, y, z], set2)) == \ Not(Or(And(Not(x), Not(z)), And(x, z))) assert POSform([x, y, z], set1 + set2) is true assert SOPform([x, y, z], set1 + set2) is true assert SOPform([Dummy(), Dummy(), Dummy()], set1 + set2) is true minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]] dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]] assert ( SOPform([w, x, y, z], minterms, dontcares) == Or(And(y, z), And(Not(w), Not(x)))) assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z) minterms = [1, 3, 7, 11, 15] dontcares = [0, 2, 5] assert ( SOPform([w, x, y, z], minterms, dontcares) == Or(And(y, z), And(Not(w), Not(x)))) assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z) minterms = [1, [0, 0, 1, 1], 7, [1, 0, 1, 1], [1, 1, 1, 1]] dontcares = [0, [0, 0, 1, 0], 5] assert ( SOPform([w, x, y, z], minterms, dontcares) == Or(And(y, z), And(Not(w), Not(x)))) assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z) minterms = [1, {y: 1, z: 1}] dontcares = [0, [0, 0, 1, 0], 5] assert ( SOPform([w, x, y, z], minterms, dontcares) == Or(And(y, z), And(Not(w), Not(x)))) assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z) minterms = [{y: 1, z: 1}, 1] dontcares = [[0, 0, 0, 0]] minterms = [[0, 0, 0]] raises(ValueError, lambda: SOPform([w, x, y, z], minterms)) raises(ValueError, lambda: POSform([w, x, y, z], minterms)) raises(TypeError, lambda: POSform([w, x, y, z], ["abcdefg"])) # test simplification ans = And(A, Or(B, C)) assert simplify_logic(A & (B | C)) == ans assert simplify_logic((A & B) | (A & C)) == ans assert simplify_logic(Implies(A, B)) == Or(Not(A), B) assert simplify_logic(Equivalent(A, B)) == \ Or(And(A, B), And(Not(A), Not(B))) assert simplify_logic(And(Equality(A, 2), C)) == And(Equality(A, 2), C) assert simplify_logic(And(Equality(A, 2), A)) is S.false assert simplify_logic(And(Equality(A, 2), A)) == And(Equality(A, 2), A) assert simplify_logic(And(Equality(A, B), C)) == And(Equality(A, B), C) assert simplify_logic(Or(And(Equality(A, 3), B), And(Equality(A, 3), C))) \ == And(Equality(A, 3), Or(B, C)) b = (~x & ~y & ~z) | (~x & ~y & z) e = And(A, b) assert simplify_logic(e) == A & ~x & ~y raises(ValueError, lambda: simplify_logic(A & (B | C), form='blabla')) assert simplify(Or(x <= y, And(x < y, z))) == (x <= y) assert simplify(Or(x <= y, And(y > x, z))) == (x <= y) assert simplify(Or(x >= y, And(y < x, z))) == (x >= y) # Check that expressions with nine variables or more are not simplified # (without the force-flag) a, b, c, d, e, f, g, h, j = symbols('a b c d e f g h j') expr = a & b & c & d & e & f & g & h & j | \ a & b & c & d & e & f & g & h & ~j # This expression can be simplified to get rid of the j variables assert simplify_logic(expr) == expr # Test dontcare assert simplify_logic((a & b) | c | d, dontcare=(a & b)) == c | d # check input ans = SOPform([x, y], [[1, 0]]) assert SOPform([x, y], [[1, 0]]) == ans assert POSform([x, y], [[1, 0]]) == ans raises(ValueError, lambda: SOPform([x], [[1]], [[1]])) assert SOPform([x], [[1]], [[0]]) is true assert SOPform([x], [[0]], [[1]]) is true assert SOPform([x], [], []) is false raises(ValueError, lambda: POSform([x], [[1]], [[1]])) assert POSform([x], [[1]], [[0]]) is true assert POSform([x], [[0]], [[1]]) is true assert POSform([x], [], []) is false # check working of simplify assert simplify((A & B) | (A & C)) == And(A, Or(B, C)) assert simplify(And(x, Not(x))) == False assert simplify(Or(x, Not(x))) == True assert simplify(And(Eq(x, 0), Eq(x, y))) == And(Eq(x, 0), Eq(y, 0)) assert And(Eq(x - 1, 0), Eq(x, y)).simplify() == And(Eq(x, 1), Eq(y, 1)) assert And(Ne(x - 1, 0), Ne(x, y)).simplify() == And(Ne(x, 1), Ne(x, y)) assert And(Eq(x - 1, 0), Ne(x, y)).simplify() == And(Eq(x, 1), Ne(y, 1)) assert And(Eq(x - 1, 0), Eq(x, z + y), Eq(y + x, 0)).simplify( ) == And(Eq(x, 1), Eq(y, -1), Eq(z, 2)) assert And(Eq(x - 1, 0), Eq(x + 2, 3)).simplify() == Eq(x, 1) assert And(Ne(x - 1, 0), Ne(x + 2, 3)).simplify() == Ne(x, 1) assert And(Eq(x - 1, 0), Eq(x + 2, 2)).simplify() == False assert And(Ne(x - 1, 0), Ne(x + 2, 2)).simplify( ) == And(Ne(x, 1), Ne(x, 0)) def test_bool_map(): """ Test working of bool_map function. """ minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]] assert bool_map(Not(Not(a)), a) == (a, {a: a}) assert bool_map(SOPform([w, x, y, z], minterms), POSform([w, x, y, z], minterms)) == \ (And(Or(Not(w), y), Or(Not(x), y), z), {x: x, w: w, z: z, y: y}) assert bool_map(SOPform([x, z, y], [[1, 0, 1]]), SOPform([a, b, c], [[1, 0, 1]])) != False function1 = SOPform([x, z, y], [[1, 0, 1], [0, 0, 1]]) function2 = SOPform([a, b, c], [[1, 0, 1], [1, 0, 0]]) assert bool_map(function1, function2) == \ (function1, {y: a, z: b}) assert bool_map(Xor(x, y), ~Xor(x, y)) == False assert bool_map(And(x, y), Or(x, y)) is None assert bool_map(And(x, y), And(x, y, z)) is None # issue 16179 assert bool_map(Xor(x, y, z), ~Xor(x, y, z)) == False assert bool_map(Xor(a, x, y, z), ~Xor(a, x, y, z)) == False def test_bool_symbol(): """Test that mixing symbols with boolean values works as expected""" assert And(A, True) == A assert And(A, True, True) == A assert And(A, False) is false assert And(A, True, False) is false assert Or(A, True) is true assert Or(A, False) == A def test_is_boolean(): assert isinstance(True, Boolean) is False assert isinstance(true, Boolean) is True assert 1 == True assert 1 != true assert (1 == true) is False assert 0 == False assert 0 != false assert (0 == false) is False assert true.is_Boolean is True assert (A & B).is_Boolean assert (A | B).is_Boolean assert (~A).is_Boolean assert (A ^ B).is_Boolean assert A.is_Boolean != isinstance(A, Boolean) assert isinstance(A, Boolean) def test_subs(): assert (A & B).subs(A, True) == B assert (A & B).subs(A, False) is false assert (A & B).subs(B, True) == A assert (A & B).subs(B, False) is false assert (A & B).subs({A: True, B: True}) is true assert (A | B).subs(A, True) is true assert (A | B).subs(A, False) == B assert (A | B).subs(B, True) is true assert (A | B).subs(B, False) == A assert (A | B).subs({A: True, B: True}) is true """ we test for axioms of boolean algebra see https://en.wikipedia.org/wiki/Boolean_algebra_(structure) """ def test_commutative(): """Test for commutativity of And and Or""" A, B = map(Boolean, symbols('A,B')) assert A & B == B & A assert A | B == B | A def test_and_associativity(): """Test for associativity of And""" assert (A & B) & C == A & (B & C) def test_or_assicativity(): assert ((A | B) | C) == (A | (B | C)) def test_double_negation(): a = Boolean() assert ~(~a) == a # test methods def test_eliminate_implications(): assert eliminate_implications(Implies(A, B, evaluate=False)) == (~A) | B assert eliminate_implications( A >> (C >> Not(B))) == Or(Or(Not(B), Not(C)), Not(A)) assert eliminate_implications(Equivalent(A, B, C, D)) == \ (~A | B) & (~B | C) & (~C | D) & (~D | A) def test_conjuncts(): assert conjuncts(A & B & C) == {A, B, C} assert conjuncts((A | B) & C) == {A | B, C} assert conjuncts(A) == {A} assert conjuncts(True) == {True} assert conjuncts(False) == {False} def test_disjuncts(): assert disjuncts(A | B | C) == {A, B, C} assert disjuncts((A | B) & C) == {(A | B) & C} assert disjuncts(A) == {A} assert disjuncts(True) == {True} assert disjuncts(False) == {False} def test_distribute(): assert distribute_and_over_or(Or(And(A, B), C)) == And(Or(A, C), Or(B, C)) assert distribute_or_over_and(And(A, Or(B, C))) == Or(And(A, B), And(A, C)) assert distribute_xor_over_and(And(A, Xor(B, C))) == Xor(And(A, B), And(A, C)) def test_to_anf(): x, y, z = symbols('x,y,z') assert to_anf(And(x, y)) == And(x, y) assert to_anf(Or(x, y)) == Xor(x, y, And(x, y)) assert to_anf(Or(Implies(x, y), And(x, y), y)) == \ Xor(x, True, x & y, remove_true=False) assert to_anf(Or(Nand(x, y), Nor(x, y), Xnor(x, y), Implies(x, y))) == True assert to_anf(Or(x, Not(y), Nor(x,z), And(x, y), Nand(y, z))) == \ Xor(True, And(y, z), And(x, y, z), remove_true=False) assert to_anf(Xor(x, y)) == Xor(x, y) assert to_anf(Not(x)) == Xor(x, True, remove_true=False) assert to_anf(Nand(x, y)) == Xor(True, And(x, y), remove_true=False) assert to_anf(Nor(x, y)) == Xor(x, y, True, And(x, y), remove_true=False) assert to_anf(Implies(x, y)) == Xor(x, True, And(x, y), remove_true=False) assert to_anf(Equivalent(x, y)) == Xor(x, y, True, remove_true=False) assert to_anf(Nand(x | y, x >> y), deep=False) == \ Xor(True, And(Or(x, y), Implies(x, y)), remove_true=False) assert to_anf(Nor(x ^ y, x & y), deep=False) == \ Xor(True, Or(Xor(x, y), And(x, y)), remove_true=False) def test_to_nnf(): assert to_nnf(true) is true assert to_nnf(false) is false assert to_nnf(A) == A assert to_nnf(A | ~A | B) is true assert to_nnf(A & ~A & B) is false assert to_nnf(A >> B) == ~A | B assert to_nnf(Equivalent(A, B, C)) == (~A | B) & (~B | C) & (~C | A) assert to_nnf(A ^ B ^ C) == \ (A | B | C) & (~A | ~B | C) & (A | ~B | ~C) & (~A | B | ~C) assert to_nnf(ITE(A, B, C)) == (~A | B) & (A | C) assert to_nnf(Not(A | B | C)) == ~A & ~B & ~C assert to_nnf(Not(A & B & C)) == ~A | ~B | ~C assert to_nnf(Not(A >> B)) == A & ~B assert to_nnf(Not(Equivalent(A, B, C))) == And(Or(A, B, C), Or(~A, ~B, ~C)) assert to_nnf(Not(A ^ B ^ C)) == \ (~A | B | C) & (A | ~B | C) & (A | B | ~C) & (~A | ~B | ~C) assert to_nnf(Not(ITE(A, B, C))) == (~A | ~B) & (A | ~C) assert to_nnf((A >> B) ^ (B >> A)) == (A & ~B) | (~A & B) assert to_nnf((A >> B) ^ (B >> A), False) == \ (~A | ~B | A | B) & ((A & ~B) | (~A & B)) assert ITE(A, 1, 0).to_nnf() == A assert ITE(A, 0, 1).to_nnf() == ~A # although ITE can hold non-Boolean, it will complain if # an attempt is made to convert the ITE to Boolean nnf raises(TypeError, lambda: ITE(A < 1, [1], B).to_nnf()) def test_to_cnf(): assert to_cnf(~(B | C)) == And(Not(B), Not(C)) assert to_cnf((A & B) | C) == And(Or(A, C), Or(B, C)) assert to_cnf(A >> B) == (~A) | B assert to_cnf(A >> (B & C)) == (~A | B) & (~A | C) assert to_cnf(A & (B | C) | ~A & (B | C), True) == B | C assert to_cnf(A & B) == And(A, B) assert to_cnf(Equivalent(A, B)) == And(Or(A, Not(B)), Or(B, Not(A))) assert to_cnf(Equivalent(A, B & C)) == \ (~A | B) & (~A | C) & (~B | ~C | A) assert to_cnf(Equivalent(A, B | C), True) == \ And(Or(Not(B), A), Or(Not(C), A), Or(B, C, Not(A))) assert to_cnf(A + 1) == A + 1 def test_issue_18904(): x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15 = symbols('x1:16') eq = (( x1 & x2 & x3 & x4 & x5 & x6 & x7 & x8 & x9 ) | ( x1 & x2 & x3 & x4 & x5 & x6 & x7 & x10 & x9 ) | ( x1 & x11 & x3 & x12 & x5 & x13 & x14 & x15 & x9 )) assert is_cnf(to_cnf(eq)) raises(ValueError, lambda: to_cnf(eq, simplify=True)) for f, t in zip((And, Or), (to_cnf, to_dnf)): eq = f(x1, x2, x3, x4, x5, x6, x7, x8, x9) raises(ValueError, lambda: to_cnf(eq, simplify=True)) assert t(eq, simplify=True, force=True) == eq def test_issue_9949(): assert is_cnf(to_cnf((b > -5) | (a > 2) & (a < 4))) def test_to_CNF(): assert CNF.CNF_to_cnf(CNF.to_CNF(~(B | C))) == to_cnf(~(B | C)) assert CNF.CNF_to_cnf(CNF.to_CNF((A & B) | C)) == to_cnf((A & B) | C) assert CNF.CNF_to_cnf(CNF.to_CNF(A >> B)) == to_cnf(A >> B) assert CNF.CNF_to_cnf(CNF.to_CNF(A >> (B & C))) == to_cnf(A >> (B & C)) assert CNF.CNF_to_cnf(CNF.to_CNF(A & (B | C) | ~A & (B | C))) == to_cnf(A & (B | C) | ~A & (B | C)) assert CNF.CNF_to_cnf(CNF.to_CNF(A & B)) == to_cnf(A & B) def test_to_dnf(): assert to_dnf(~(B | C)) == And(Not(B), Not(C)) assert to_dnf(A & (B | C)) == Or(And(A, B), And(A, C)) assert to_dnf(A >> B) == (~A) | B assert to_dnf(A >> (B & C)) == (~A) | (B & C) assert to_dnf(A | B) == A | B assert to_dnf(Equivalent(A, B), True) == \ Or(And(A, B), And(Not(A), Not(B))) assert to_dnf(Equivalent(A, B & C), True) == \ Or(And(A, B, C), And(Not(A), Not(B)), And(Not(A), Not(C))) assert to_dnf(A + 1) == A + 1 def test_to_int_repr(): x, y, z = map(Boolean, symbols('x,y,z')) def sorted_recursive(arg): try: return sorted(sorted_recursive(x) for x in arg) except TypeError: # arg is not a sequence return arg assert sorted_recursive(to_int_repr([x | y, z | x], [x, y, z])) == \ sorted_recursive([[1, 2], [1, 3]]) assert sorted_recursive(to_int_repr([x | y, z | ~x], [x, y, z])) == \ sorted_recursive([[1, 2], [3, -1]]) def test_is_anf(): x, y = symbols('x,y') assert is_anf(true) is True assert is_anf(false) is True assert is_anf(x) is True assert is_anf(And(x, y)) is True assert is_anf(Xor(x, y, And(x, y))) is True assert is_anf(Xor(x, y, Or(x, y))) is False assert is_anf(Xor(Not(x), y)) is False def test_is_nnf(): assert is_nnf(true) is True assert is_nnf(A) is True assert is_nnf(~A) is True assert is_nnf(A & B) is True assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), False) is True assert is_nnf((A | B) & (~A | ~B)) is True assert is_nnf(Not(Or(A, B))) is False assert is_nnf(A ^ B) is False assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), True) is False def test_is_cnf(): assert is_cnf(x) is True assert is_cnf(x | y | z) is True assert is_cnf(x & y & z) is True assert is_cnf((x | y) & z) is True assert is_cnf((x & y) | z) is False assert is_cnf(~(x & y) | z) is False def test_is_dnf(): assert is_dnf(x) is True assert is_dnf(x | y | z) is True assert is_dnf(x & y & z) is True assert is_dnf((x & y) | z) is True assert is_dnf((x | y) & z) is False assert is_dnf(~(x | y) & z) is False def test_ITE(): A, B, C = symbols('A:C') assert ITE(True, False, True) is false assert ITE(True, True, False) is true assert ITE(False, True, False) is false assert ITE(False, False, True) is true assert isinstance(ITE(A, B, C), ITE) A = True assert ITE(A, B, C) == B A = False assert ITE(A, B, C) == C B = True assert ITE(And(A, B), B, C) == C assert ITE(Or(A, False), And(B, True), False) is false assert ITE(x, A, B) == Not(x) assert ITE(x, B, A) == x assert ITE(1, x, y) == x assert ITE(0, x, y) == y raises(TypeError, lambda: ITE(2, x, y)) raises(TypeError, lambda: ITE(1, [], y)) raises(TypeError, lambda: ITE(1, (), y)) raises(TypeError, lambda: ITE(1, y, [])) assert ITE(1, 1, 1) is S.true assert isinstance(ITE(1, 1, 1, evaluate=False), ITE) raises(TypeError, lambda: ITE(x > 1, y, x)) assert ITE(Eq(x, True), y, x) == ITE(x, y, x) assert ITE(Eq(x, False), y, x) == ITE(~x, y, x) assert ITE(Ne(x, True), y, x) == ITE(~x, y, x) assert ITE(Ne(x, False), y, x) == ITE(x, y, x) assert ITE(Eq(S. true, x), y, x) == ITE(x, y, x) assert ITE(Eq(S.false, x), y, x) == ITE(~x, y, x) assert ITE(Ne(S.true, x), y, x) == ITE(~x, y, x) assert ITE(Ne(S.false, x), y, x) == ITE(x, y, x) # 0 and 1 in the context are not treated as True/False # so the equality must always be False since dissimilar # objects cannot be equal assert ITE(Eq(x, 0), y, x) == x assert ITE(Eq(x, 1), y, x) == x assert ITE(Ne(x, 0), y, x) == y assert ITE(Ne(x, 1), y, x) == y assert ITE(Eq(x, 0), y, z).subs(x, 0) == y assert ITE(Eq(x, 0), y, z).subs(x, 1) == z raises(ValueError, lambda: ITE(x > 1, y, x, z)) def test_is_literal(): assert is_literal(True) is True assert is_literal(False) is True assert is_literal(A) is True assert is_literal(~A) is True assert is_literal(Or(A, B)) is False assert is_literal(Q.zero(A)) is True assert is_literal(Not(Q.zero(A))) is True assert is_literal(Or(A, B)) is False assert is_literal(And(Q.zero(A), Q.zero(B))) is False assert is_literal(x < 3) assert not is_literal(x + y < 3) def test_operators(): # Mostly test __and__, __rand__, and so on assert True & A == A & True == A assert False & A == A & False == False assert A & B == And(A, B) assert True | A == A | True == True assert False | A == A | False == A assert A | B == Or(A, B) assert ~A == Not(A) assert True >> A == A << True == A assert False >> A == A << False == True assert A >> True == True << A == True assert A >> False == False << A == ~A assert A >> B == B << A == Implies(A, B) assert True ^ A == A ^ True == ~A assert False ^ A == A ^ False == A assert A ^ B == Xor(A, B) def test_true_false(): assert true is S.true assert false is S.false assert true is not True assert false is not False assert true assert not false assert true == True assert false == False assert not (true == False) assert not (false == True) assert not (true == false) assert hash(true) == hash(True) assert hash(false) == hash(False) assert len({true, True}) == len({false, False}) == 1 assert isinstance(true, BooleanAtom) assert isinstance(false, BooleanAtom) # We don't want to subclass from bool, because bool subclasses from # int. But operators like &, |, ^, <<, >>, and ~ act differently on 0 and # 1 then we want them to on true and false. See the docstrings of the # various And, Or, etc. functions for examples. assert not isinstance(true, bool) assert not isinstance(false, bool) # Note: using 'is' comparison is important here. We want these to return # true and false, not True and False assert Not(true) is false assert Not(True) is false assert Not(false) is true assert Not(False) is true assert ~true is false assert ~false is true for T, F in product((True, true), (False, false)): assert And(T, F) is false assert And(F, T) is false assert And(F, F) is false assert And(T, T) is true assert And(T, x) == x assert And(F, x) is false if not (T is True and F is False): assert T & F is false assert F & T is false if F is not False: assert F & F is false if T is not True: assert T & T is true assert Or(T, F) is true assert Or(F, T) is true assert Or(F, F) is false assert Or(T, T) is true assert Or(T, x) is true assert Or(F, x) == x if not (T is True and F is False): assert T | F is true assert F | T is true if F is not False: assert F | F is false if T is not True: assert T | T is true assert Xor(T, F) is true assert Xor(F, T) is true assert Xor(F, F) is false assert Xor(T, T) is false assert Xor(T, x) == ~x assert Xor(F, x) == x if not (T is True and F is False): assert T ^ F is true assert F ^ T is true if F is not False: assert F ^ F is false if T is not True: assert T ^ T is false assert Nand(T, F) is true assert Nand(F, T) is true assert Nand(F, F) is true assert Nand(T, T) is false assert Nand(T, x) == ~x assert Nand(F, x) is true assert Nor(T, F) is false assert Nor(F, T) is false assert Nor(F, F) is true assert Nor(T, T) is false assert Nor(T, x) is false assert Nor(F, x) == ~x assert Implies(T, F) is false assert Implies(F, T) is true assert Implies(F, F) is true assert Implies(T, T) is true assert Implies(T, x) == x assert Implies(F, x) is true assert Implies(x, T) is true assert Implies(x, F) == ~x if not (T is True and F is False): assert T >> F is false assert F << T is false assert F >> T is true assert T << F is true if F is not False: assert F >> F is true assert F << F is true if T is not True: assert T >> T is true assert T << T is true assert Equivalent(T, F) is false assert Equivalent(F, T) is false assert Equivalent(F, F) is true assert Equivalent(T, T) is true assert Equivalent(T, x) == x assert Equivalent(F, x) == ~x assert Equivalent(x, T) == x assert Equivalent(x, F) == ~x assert ITE(T, T, T) is true assert ITE(T, T, F) is true assert ITE(T, F, T) is false assert ITE(T, F, F) is false assert ITE(F, T, T) is true assert ITE(F, T, F) is false assert ITE(F, F, T) is true assert ITE(F, F, F) is false assert all(i.simplify(1, 2) is i for i in (S.true, S.false)) def test_bool_as_set(): assert ITE(y <= 0, False, y >= 1).as_set() == Interval(1, oo) assert And(x <= 2, x >= -2).as_set() == Interval(-2, 2) assert Or(x >= 2, x <= -2).as_set() == Interval(-oo, -2) + Interval(2, oo) assert Not(x > 2).as_set() == Interval(-oo, 2) # issue 10240 assert Not(And(x > 2, x < 3)).as_set() == \ Union(Interval(-oo, 2), Interval(3, oo)) assert true.as_set() == S.UniversalSet assert false.as_set() is S.EmptySet assert x.as_set() == S.UniversalSet assert And(Or(x < 1, x > 3), x < 2).as_set() == Interval.open(-oo, 1) assert And(x < 1, sin(x) < 3).as_set() == (x < 1).as_set() raises(NotImplementedError, lambda: (sin(x) < 1).as_set()) # watch for object morph in as_set assert Eq(-1, cos(2*x)**2/sin(2*x)**2).as_set() is S.EmptySet @XFAIL def test_multivariate_bool_as_set(): x, y = symbols('x,y') assert And(x >= 0, y >= 0).as_set() == Interval(0, oo)*Interval(0, oo) assert Or(x >= 0, y >= 0).as_set() == S.Reals*S.Reals - \ Interval(-oo, 0, True, True)*Interval(-oo, 0, True, True) def test_all_or_nothing(): x = symbols('x', extended_real=True) args = x >= -oo, x <= oo v = And(*args) if v.func is And: assert len(v.args) == len(args) - args.count(S.true) else: assert v == True v = Or(*args) if v.func is Or: assert len(v.args) == 2 else: assert v == True def test_canonical_atoms(): assert true.canonical == true assert false.canonical == false def test_negated_atoms(): assert true.negated == false assert false.negated == true def test_issue_8777(): assert And(x > 2, x < oo).as_set() == Interval(2, oo, left_open=True) assert And(x >= 1, x < oo).as_set() == Interval(1, oo) assert (x < oo).as_set() == Interval(-oo, oo) assert (x > -oo).as_set() == Interval(-oo, oo) def test_issue_8975(): assert Or(And(-oo < x, x <= -2), And(2 <= x, x < oo)).as_set() == \ Interval(-oo, -2) + Interval(2, oo) def test_term_to_integer(): assert term_to_integer([1, 0, 1, 0, 0, 1, 0]) == 82 assert term_to_integer('0010101000111001') == 10809 def test_issue_21971(): a, b, c, d = symbols('a b c d') f = a & b & c | a & c assert f.subs(a & c, d) == b & d | d assert f.subs(a & b & c, d) == a & c | d f = (a | b | c) & (a | c) assert f.subs(a | c, d) == (b | d) & d assert f.subs(a | b | c, d) == (a | c) & d f = (a ^ b ^ c) & (a ^ c) assert f.subs(a ^ c, d) == (b ^ d) & d assert f.subs(a ^ b ^ c, d) == (a ^ c) & d def test_truth_table(): assert list(truth_table(And(x, y), [x, y], input=False)) == \ [False, False, False, True] assert list(truth_table(x | y, [x, y], input=False)) == \ [False, True, True, True] assert list(truth_table(x >> y, [x, y], input=False)) == \ [True, True, False, True] assert list(truth_table(And(x, y), [x, y])) == \ [([0, 0], False), ([0, 1], False), ([1, 0], False), ([1, 1], True)] def test_issue_8571(): for t in (S.true, S.false): raises(TypeError, lambda: +t) raises(TypeError, lambda: -t) raises(TypeError, lambda: abs(t)) # use int(bool(t)) to get 0 or 1 raises(TypeError, lambda: int(t)) for o in [S.Zero, S.One, x]: for _ in range(2): raises(TypeError, lambda: o + t) raises(TypeError, lambda: o - t) raises(TypeError, lambda: o % t) raises(TypeError, lambda: o*t) raises(TypeError, lambda: o/t) raises(TypeError, lambda: o**t) o, t = t, o # do again in reversed order def test_expand_relational(): n = symbols('n', negative=True) p, q = symbols('p q', positive=True) r = ((n + q*(-n/q + 1))/(q*(-n/q + 1)) < 0) assert r is not S.false assert r.expand() is S.false assert (q > 0).expand() is S.true def test_issue_12717(): assert S.true.is_Atom == True assert S.false.is_Atom == True def test_as_Boolean(): nz = symbols('nz', nonzero=True) assert all(as_Boolean(i) is S.true for i in (True, S.true, 1, nz)) z = symbols('z', zero=True) assert all(as_Boolean(i) is S.false for i in (False, S.false, 0, z)) assert all(as_Boolean(i) == i for i in (x, x < 0)) for i in (2, S(2), x + 1, []): raises(TypeError, lambda: as_Boolean(i)) def test_binary_symbols(): assert ITE(x < 1, y, z).binary_symbols == {y, z} for f in (Eq, Ne): assert f(x, 1).binary_symbols == set() assert f(x, True).binary_symbols == {x} assert f(x, False).binary_symbols == {x} assert S.true.binary_symbols == set() assert S.false.binary_symbols == set() assert x.binary_symbols == {x} assert And(x, Eq(y, False), Eq(z, 1)).binary_symbols == {x, y} assert Q.prime(x).binary_symbols == set() assert Q.lt(x, 1).binary_symbols == set() assert Q.is_true(x).binary_symbols == {x} assert Q.eq(x, True).binary_symbols == {x} assert Q.prime(x).binary_symbols == set() def test_BooleanFunction_diff(): assert And(x, y).diff(x) == Piecewise((0, Eq(y, False)), (1, True)) def test_issue_14700(): A, B, C, D, E, F, G, H = symbols('A B C D E F G H') q = ((B & D & H & ~F) | (B & H & ~C & ~D) | (B & H & ~C & ~F) | (B & H & ~D & ~G) | (B & H & ~F & ~G) | (C & G & ~B & ~D) | (C & G & ~D & ~H) | (C & G & ~F & ~H) | (D & F & H & ~B) | (D & F & ~G & ~H) | (B & D & F & ~C & ~H) | (D & E & F & ~B & ~C) | (D & F & ~A & ~B & ~C) | (D & F & ~A & ~C & ~H) | (A & B & D & F & ~E & ~H)) soldnf = ((B & D & H & ~F) | (D & F & H & ~B) | (B & H & ~C & ~D) | (B & H & ~D & ~G) | (C & G & ~B & ~D) | (C & G & ~D & ~H) | (C & G & ~F & ~H) | (D & F & ~G & ~H) | (D & E & F & ~C & ~H) | (D & F & ~A & ~C & ~H) | (A & B & D & F & ~E & ~H)) solcnf = ((B | C | D) & (B | D | G) & (C | D | H) & (C | F | H) & (D | G | H) & (F | G | H) & (B | F | ~D | ~H) & (~B | ~D | ~F | ~H) & (D | ~B | ~C | ~G | ~H) & (A | H | ~C | ~D | ~F | ~G) & (H | ~C | ~D | ~E | ~F | ~G) & (B | E | H | ~A | ~D | ~F | ~G)) assert simplify_logic(q, "dnf") == soldnf assert simplify_logic(q, "cnf") == solcnf minterms = [[0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [0, 0, 1, 1], [1, 0, 1, 1]] dontcares = [[1, 0, 0, 0], [1, 0, 0, 1], [1, 1, 0, 0], [1, 1, 0, 1]] assert SOPform([w, x, y, z], minterms) == (x & ~w) | (y & z & ~x) # Should not be more complicated with don't cares assert SOPform([w, x, y, z], minterms, dontcares) == \ (x & ~w) | (y & z & ~x) def test_relational_simplification(): w, x, y, z = symbols('w x y z', real=True) d, e = symbols('d e', real=False) # Test all combinations or sign and order assert Or(x >= y, x < y).simplify() == S.true assert Or(x >= y, y > x).simplify() == S.true assert Or(x >= y, -x > -y).simplify() == S.true assert Or(x >= y, -y < -x).simplify() == S.true assert Or(-x <= -y, x < y).simplify() == S.true assert Or(-x <= -y, -x > -y).simplify() == S.true assert Or(-x <= -y, y > x).simplify() == S.true assert Or(-x <= -y, -y < -x).simplify() == S.true assert Or(y <= x, x < y).simplify() == S.true assert Or(y <= x, y > x).simplify() == S.true assert Or(y <= x, -x > -y).simplify() == S.true assert Or(y <= x, -y < -x).simplify() == S.true assert Or(-y >= -x, x < y).simplify() == S.true assert Or(-y >= -x, y > x).simplify() == S.true assert Or(-y >= -x, -x > -y).simplify() == S.true assert Or(-y >= -x, -y < -x).simplify() == S.true assert Or(x < y, x >= y).simplify() == S.true assert Or(y > x, x >= y).simplify() == S.true assert Or(-x > -y, x >= y).simplify() == S.true assert Or(-y < -x, x >= y).simplify() == S.true assert Or(x < y, -x <= -y).simplify() == S.true assert Or(-x > -y, -x <= -y).simplify() == S.true assert Or(y > x, -x <= -y).simplify() == S.true assert Or(-y < -x, -x <= -y).simplify() == S.true assert Or(x < y, y <= x).simplify() == S.true assert Or(y > x, y <= x).simplify() == S.true assert Or(-x > -y, y <= x).simplify() == S.true assert Or(-y < -x, y <= x).simplify() == S.true assert Or(x < y, -y >= -x).simplify() == S.true assert Or(y > x, -y >= -x).simplify() == S.true assert Or(-x > -y, -y >= -x).simplify() == S.true assert Or(-y < -x, -y >= -x).simplify() == S.true # Some other tests assert Or(x >= y, w < z, x <= y).simplify() == S.true assert And(x >= y, x < y).simplify() == S.false assert Or(x >= y, Eq(y, x)).simplify() == (x >= y) assert And(x >= y, Eq(y, x)).simplify() == Eq(x, y) assert And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \ (Eq(x, y) & (x >= 1) & (y >= 5) & (y > z)) assert Or(Eq(x, y), x >= y, w < y, z < y).simplify() == \ (x >= y) | (y > z) | (w < y) assert And(Eq(x, y), x >= y, w < y, y >= z, z < y).simplify() == \ Eq(x, y) & (y > z) & (w < y) # assert And(Eq(x, y), x >= y, w < y, y >= z, z < y).simplify(relational_minmax=True) == \ # And(Eq(x, y), y > Max(w, z)) # assert Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify(relational_minmax=True) == \ # (Eq(x, y) | (x >= 1) | (y > Min(2, z))) assert And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \ (Eq(x, y) & (x >= 1) & (y >= 5) & (y > z)) assert (Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)).simplify() == \ (Eq(x, y) & Eq(d, e) & (d >= e)) assert And(Eq(x, y), Eq(x, -y)).simplify() == And(Eq(x, 0), Eq(y, 0)) assert Xor(x >= y, x <= y).simplify() == Ne(x, y) assert And(x > 1, x < -1, Eq(x, y)).simplify() == S.false # From #16690 assert And(x >= y, Eq(y, 0)).simplify() == And(x >= 0, Eq(y, 0)) assert Or(Ne(x, 1), Ne(x, 2)).simplify() == S.true assert And(Eq(x, 1), Ne(2, x)).simplify() == Eq(x, 1) assert Or(Eq(x, 1), Ne(2, x)).simplify() == Ne(x, 2) def test_issue_8373(): x = symbols('x', real=True) assert Or(x < 1, x > -1).simplify() == S.true assert Or(x < 1, x >= 1).simplify() == S.true assert And(x < 1, x >= 1).simplify() == S.false assert Or(x <= 1, x >= 1).simplify() == S.true def test_issue_7950(): x = symbols('x', real=True) assert And(Eq(x, 1), Eq(x, 2)).simplify() == S.false @slow def test_relational_simplification_numerically(): def test_simplification_numerically_function(original, simplified): symb = original.free_symbols n = len(symb) valuelist = list(set(list(combinations(list(range(-(n-1), n))*n, n)))) for values in valuelist: sublist = dict(zip(symb, values)) originalvalue = original.subs(sublist) simplifiedvalue = simplified.subs(sublist) assert originalvalue == simplifiedvalue, "Original: {}\nand"\ " simplified: {}\ndo not evaluate to the same value for {}"\ "".format(original, simplified, sublist) w, x, y, z = symbols('w x y z', real=True) d, e = symbols('d e', real=False) expressions = (And(Eq(x, y), x >= y, w < y, y >= z, z < y), And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y), Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y), And(x >= y, Eq(y, x)), Or(And(Eq(x, y), x >= y, w < y, Or(y >= z, z < y)), And(Eq(x, y), x >= 1, 2 < y, y >= -1, z < y)), (Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)), ) for expression in expressions: test_simplification_numerically_function(expression, expression.simplify()) def test_relational_simplification_patterns_numerically(): from sympy.core import Wild from sympy.logic.boolalg import _simplify_patterns_and, \ _simplify_patterns_or, _simplify_patterns_xor a = Wild('a') b = Wild('b') c = Wild('c') symb = [a, b, c] patternlists = [[And, _simplify_patterns_and()], [Or, _simplify_patterns_or()], [Xor, _simplify_patterns_xor()]] valuelist = list(set(list(combinations(list(range(-2, 3))*3, 3)))) # Skip combinations of +/-2 and 0, except for all 0 valuelist = [v for v in valuelist if any([w % 2 for w in v]) or not any(v)] for func, patternlist in patternlists: for pattern in patternlist: original = func(*pattern[0].args) simplified = pattern[1] for values in valuelist: sublist = dict(zip(symb, values)) originalvalue = original.xreplace(sublist) simplifiedvalue = simplified.xreplace(sublist) assert originalvalue == simplifiedvalue, "Original: {}\nand"\ " simplified: {}\ndo not evaluate to the same value for"\ "{}".format(pattern[0], simplified, sublist) def test_issue_16803(): n = symbols('n') # No simplification done, but should not raise an exception assert ((n > 3) | (n < 0) | ((n > 0) & (n < 3))).simplify() == \ (n > 3) | (n < 0) | ((n > 0) & (n < 3)) def test_issue_17530(): r = {x: oo, y: oo} assert Or(x + y > 0, x - y < 0).subs(r) assert not And(x + y < 0, x - y < 0).subs(r) raises(TypeError, lambda: Or(x + y < 0, x - y < 0).subs(r)) raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r)) raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r)) def test_anf_coeffs(): assert anf_coeffs([1, 0]) == [1, 1] assert anf_coeffs([0, 0, 0, 1]) == [0, 0, 0, 1] assert anf_coeffs([0, 1, 1, 1]) == [0, 1, 1, 1] assert anf_coeffs([1, 1, 1, 0]) == [1, 0, 0, 1] assert anf_coeffs([1, 0, 0, 0]) == [1, 1, 1, 1] assert anf_coeffs([1, 0, 0, 1]) == [1, 1, 1, 0] assert anf_coeffs([1, 1, 0, 1]) == [1, 0, 1, 1] def test_ANFform(): x, y = symbols('x,y') assert ANFform([x], [1, 1]) == True assert ANFform([x], [0, 0]) == False assert ANFform([x], [1, 0]) == Xor(x, True, remove_true=False) assert ANFform([x, y], [1, 1, 1, 0]) == \ Xor(True, And(x, y), remove_true=False) def test_bool_minterm(): x, y = symbols('x,y') assert bool_minterm(3, [x, y]) == And(x, y) assert bool_minterm([1, 0], [x, y]) == And(Not(y), x) def test_bool_maxterm(): x, y = symbols('x,y') assert bool_maxterm(2, [x, y]) == Or(Not(x), y) assert bool_maxterm([0, 1], [x, y]) == Or(Not(y), x) def test_bool_monomial(): x, y = symbols('x,y') assert bool_monomial(1, [x, y]) == y assert bool_monomial([1, 1], [x, y]) == And(x, y) def test_check_pair(): assert _check_pair([0, 1, 0], [0, 1, 1]) == 2 assert _check_pair([0, 1, 0], [1, 1, 1]) == -1 def test_issue_19114(): expr = (B & C) | (A & ~C) | (~A & ~B) # Expression is minimal, but there are multiple minimal forms possible res1 = (A & B) | (C & ~A) | (~B & ~C) result = to_dnf(expr, simplify=True) assert result in (expr, res1) def test_issue_20870(): result = SOPform([a, b, c, d], [1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15]) expected = ((d & ~b) | (a & b & c) | (a & ~c & ~d) | (b & ~a & ~c) | (c & ~a & ~d)) assert result == expected def test_convert_to_varsSOP(): assert _convert_to_varsSOP([0, 1, 0], [x, y, z]) == And(Not(x), y, Not(z)) assert _convert_to_varsSOP([3, 1, 0], [x, y, z]) == And(y, Not(z)) def test_convert_to_varsPOS(): assert _convert_to_varsPOS([0, 1, 0], [x, y, z]) == Or(x, Not(y), z) assert _convert_to_varsPOS([3, 1, 0], [x, y, z]) == Or(Not(y), z) def test_gateinputcount(): a, b, c, d, e = symbols('a:e') assert gateinputcount(And(a, b)) == 2 assert gateinputcount(a | b & c & d ^ (e | a)) == 9 assert gateinputcount(And(a, True)) == 0 raises(TypeError, lambda: gateinputcount(a*b)) def test_refine(): # relational assert not refine(x < 0, ~(x < 0)) assert refine(x < 0, (x < 0)) assert refine(x < 0, (0 > x)) is S.true assert refine(x < 0, (y < 0)) == (x < 0) assert not refine(x <= 0, ~(x <= 0)) assert refine(x <= 0, (x <= 0)) assert refine(x <= 0, (0 >= x)) is S.true assert refine(x <= 0, (y <= 0)) == (x <= 0) assert not refine(x > 0, ~(x > 0)) assert refine(x > 0, (x > 0)) assert refine(x > 0, (0 < x)) is S.true assert refine(x > 0, (y > 0)) == (x > 0) assert not refine(x >= 0, ~(x >= 0)) assert refine(x >= 0, (x >= 0)) assert refine(x >= 0, (0 <= x)) is S.true assert refine(x >= 0, (y >= 0)) == (x >= 0) assert not refine(Eq(x, 0), ~(Eq(x, 0))) assert refine(Eq(x, 0), (Eq(x, 0))) assert refine(Eq(x, 0), (Eq(0, x))) is S.true assert refine(Eq(x, 0), (Eq(y, 0))) == Eq(x, 0) assert not refine(Ne(x, 0), ~(Ne(x, 0))) assert refine(Ne(x, 0), (Ne(0, x))) is S.true assert refine(Ne(x, 0), (Ne(x, 0))) assert refine(Ne(x, 0), (Ne(y, 0))) == (Ne(x, 0)) # boolean functions assert refine(And(x > 0, y > 0), (x > 0)) == (y > 0) assert refine(And(x > 0, y > 0), (x > 0) & (y > 0)) is S.true # predicates assert refine(Q.positive(x), Q.positive(x)) is S.true assert refine(Q.positive(x), Q.negative(x)) is S.false assert refine(Q.positive(x), Q.real(x)) == Q.positive(x) def test_relational_threeterm_simplification_patterns_numerically(): from sympy.core import Wild from sympy.logic.boolalg import _simplify_patterns_and3 a = Wild('a') b = Wild('b') c = Wild('c') symb = [a, b, c] patternlists = [[And, _simplify_patterns_and3()]] valuelist = list(set(list(combinations(list(range(-2, 3))*3, 3)))) # Skip combinations of +/-2 and 0, except for all 0 valuelist = [v for v in valuelist if any([w % 2 for w in v]) or not any(v)] for func, patternlist in patternlists: for pattern in patternlist: original = func(*pattern[0].args) simplified = pattern[1] for values in valuelist: sublist = dict(zip(symb, values)) originalvalue = original.xreplace(sublist) simplifiedvalue = simplified.xreplace(sublist) assert originalvalue == simplifiedvalue, "Original: {}\nand"\ " simplified: {}\ndo not evaluate to the same value for"\ "{}".format(pattern[0], simplified, sublist)
8f7fc1abbecfb7284b3e50085cbf523c65a7abda7940f97d760d44e5276ac7c1
from typing import Tuple as tTuple from functools import wraps from sympy.core import S, Integer, Basic, Mul, Add from sympy.core.assumptions import check_assumptions from sympy.core.decorators import call_highest_priority from sympy.core.expr import Expr, ExprBuilder from sympy.core.logic import FuzzyBool from sympy.core.symbol import Str, Dummy, symbols, Symbol from sympy.core.sympify import SympifyError, _sympify from sympy.external.gmpy import SYMPY_INTS from sympy.functions import conjugate, adjoint from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices.common import NonSquareMatrixError from sympy.matrices.matrices import MatrixKind, MatrixBase from sympy.multipledispatch import dispatch from sympy.utilities.misc import filldedent def _sympifyit(arg, retval=None): # This version of _sympifyit sympifies MutableMatrix objects def deco(func): @wraps(func) def __sympifyit_wrapper(a, b): try: b = _sympify(b) return func(a, b) except SympifyError: return retval return __sympifyit_wrapper return deco class MatrixExpr(Expr): """Superclass for Matrix Expressions MatrixExprs represent abstract matrices, linear transformations represented within a particular basis. Examples ======== >>> from sympy import MatrixSymbol >>> A = MatrixSymbol('A', 3, 3) >>> y = MatrixSymbol('y', 3, 1) >>> x = (A.T*A).I * A * y See Also ======== MatrixSymbol, MatAdd, MatMul, Transpose, Inverse """ __slots__ = () # type: tTuple[str, ...] # Should not be considered iterable by the # sympy.utilities.iterables.iterable function. Subclass that actually are # iterable (i.e., explicit matrices) should set this to True. _iterable = False _op_priority = 11.0 is_Matrix = True # type: bool is_MatrixExpr = True # type: bool is_Identity = None # type: FuzzyBool is_Inverse = False is_Transpose = False is_ZeroMatrix = False is_MatAdd = False is_MatMul = False is_commutative = False is_number = False is_symbol = False is_scalar = False kind: MatrixKind = MatrixKind() def __new__(cls, *args, **kwargs): args = map(_sympify, args) return Basic.__new__(cls, *args, **kwargs) # The following is adapted from the core Expr object @property def shape(self) -> tTuple[Expr, Expr]: raise NotImplementedError @property def _add_handler(self): return MatAdd @property def _mul_handler(self): return MatMul def __neg__(self): return MatMul(S.NegativeOne, self).doit() def __abs__(self): raise NotImplementedError @_sympifyit('other', NotImplemented) @call_highest_priority('__radd__') def __add__(self, other): return MatAdd(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__add__') def __radd__(self, other): return MatAdd(other, self).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rsub__') def __sub__(self, other): return MatAdd(self, -other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__sub__') def __rsub__(self, other): return MatAdd(other, -self).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rmul__') def __mul__(self, other): return MatMul(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rmul__') def __matmul__(self, other): return MatMul(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__mul__') def __rmul__(self, other): return MatMul(other, self).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__mul__') def __rmatmul__(self, other): return MatMul(other, self).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rpow__') def __pow__(self, other): return MatPow(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__pow__') def __rpow__(self, other): raise NotImplementedError("Matrix Power not defined") @_sympifyit('other', NotImplemented) @call_highest_priority('__rtruediv__') def __truediv__(self, other): return self * other**S.NegativeOne @_sympifyit('other', NotImplemented) @call_highest_priority('__truediv__') def __rtruediv__(self, other): raise NotImplementedError() #return MatMul(other, Pow(self, S.NegativeOne)) @property def rows(self): return self.shape[0] @property def cols(self): return self.shape[1] @property def is_square(self): return self.rows == self.cols def _eval_conjugate(self): from sympy.matrices.expressions.adjoint import Adjoint return Adjoint(Transpose(self)) def as_real_imag(self, deep=True, **hints): return self._eval_as_real_imag() def _eval_as_real_imag(self): real = S.Half * (self + self._eval_conjugate()) im = (self - self._eval_conjugate())/(2*S.ImaginaryUnit) return (real, im) def _eval_inverse(self): return Inverse(self) def _eval_determinant(self): return Determinant(self) def _eval_transpose(self): return Transpose(self) def _eval_power(self, exp): """ Override this in sub-classes to implement simplification of powers. The cases where the exponent is -1, 0, 1 are already covered in MatPow.doit(), so implementations can exclude these cases. """ return MatPow(self, exp) def _eval_simplify(self, **kwargs): if self.is_Atom: return self else: from sympy.simplify import simplify return self.func(*[simplify(x, **kwargs) for x in self.args]) def _eval_adjoint(self): from sympy.matrices.expressions.adjoint import Adjoint return Adjoint(self) def _eval_derivative_n_times(self, x, n): return Basic._eval_derivative_n_times(self, x, n) def _eval_derivative(self, x): # `x` is a scalar: if self.has(x): # See if there are other methods using it: return super()._eval_derivative(x) else: return ZeroMatrix(*self.shape) @classmethod def _check_dim(cls, dim): """Helper function to check invalid matrix dimensions""" ok = check_assumptions(dim, integer=True, nonnegative=True) if ok is False: raise ValueError( "The dimension specification {} should be " "a nonnegative integer.".format(dim)) def _entry(self, i, j, **kwargs): raise NotImplementedError( "Indexing not implemented for %s" % self.__class__.__name__) def adjoint(self): return adjoint(self) def as_coeff_Mul(self, rational=False): """Efficiently extract the coefficient of a product. """ return S.One, self def conjugate(self): return conjugate(self) def transpose(self): from sympy.matrices.expressions.transpose import transpose return transpose(self) @property def T(self): '''Matrix transposition''' return self.transpose() def inverse(self): if not self.is_square: raise NonSquareMatrixError('Inverse of non-square matrix') return self._eval_inverse() def inv(self): return self.inverse() def det(self): from sympy.matrices.expressions.determinant import det return det(self) @property def I(self): return self.inverse() def valid_index(self, i, j): def is_valid(idx): return isinstance(idx, (int, Integer, Symbol, Expr)) return (is_valid(i) and is_valid(j) and (self.rows is None or (i >= -self.rows) != False and (i < self.rows) != False) and (j >= -self.cols) != False and (j < self.cols) != False) def __getitem__(self, key): if not isinstance(key, tuple) and isinstance(key, slice): from sympy.matrices.expressions.slice import MatrixSlice return MatrixSlice(self, key, (0, None, 1)) if isinstance(key, tuple) and len(key) == 2: i, j = key if isinstance(i, slice) or isinstance(j, slice): from sympy.matrices.expressions.slice import MatrixSlice return MatrixSlice(self, i, j) i, j = _sympify(i), _sympify(j) if self.valid_index(i, j) != False: return self._entry(i, j) else: raise IndexError("Invalid indices (%s, %s)" % (i, j)) elif isinstance(key, (SYMPY_INTS, Integer)): # row-wise decomposition of matrix rows, cols = self.shape # allow single indexing if number of columns is known if not isinstance(cols, Integer): raise IndexError(filldedent(''' Single indexing is only supported when the number of columns is known.''')) key = _sympify(key) i = key // cols j = key % cols if self.valid_index(i, j) != False: return self._entry(i, j) else: raise IndexError("Invalid index %s" % key) elif isinstance(key, (Symbol, Expr)): raise IndexError(filldedent(''' Only integers may be used when addressing the matrix with a single index.''')) raise IndexError("Invalid index, wanted %s[i,j]" % self) def _is_shape_symbolic(self) -> bool: return (not isinstance(self.rows, (SYMPY_INTS, Integer)) or not isinstance(self.cols, (SYMPY_INTS, Integer))) def as_explicit(self): """ Returns a dense Matrix with elements represented explicitly Returns an object of type ImmutableDenseMatrix. Examples ======== >>> from sympy import Identity >>> I = Identity(3) >>> I I >>> I.as_explicit() Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) See Also ======== as_mutable: returns mutable Matrix type """ if self._is_shape_symbolic(): raise ValueError( 'Matrix with symbolic shape ' 'cannot be represented explicitly.') from sympy.matrices.immutable import ImmutableDenseMatrix return ImmutableDenseMatrix([[self[i, j] for j in range(self.cols)] for i in range(self.rows)]) def as_mutable(self): """ Returns a dense, mutable matrix with elements represented explicitly Examples ======== >>> from sympy import Identity >>> I = Identity(3) >>> I I >>> I.shape (3, 3) >>> I.as_mutable() Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) See Also ======== as_explicit: returns ImmutableDenseMatrix """ return self.as_explicit().as_mutable() def __array__(self): from numpy import empty a = empty(self.shape, dtype=object) for i in range(self.rows): for j in range(self.cols): a[i, j] = self[i, j] return a def equals(self, other): """ Test elementwise equality between matrices, potentially of different types >>> from sympy import Identity, eye >>> Identity(3).equals(eye(3)) True """ return self.as_explicit().equals(other) def canonicalize(self): return self def as_coeff_mmul(self): return S.One, MatMul(self) @staticmethod def from_index_summation(expr, first_index=None, last_index=None, dimensions=None): r""" Parse expression of matrices with explicitly summed indices into a matrix expression without indices, if possible. This transformation expressed in mathematical notation: `\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}` Optional parameter ``first_index``: specify which free index to use as the index starting the expression. Examples ======== >>> from sympy import MatrixSymbol, MatrixExpr, Sum >>> from sympy.abc import i, j, k, l, N >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) A*B Transposition is detected: >>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) A.T*B Detect the trace: >>> expr = Sum(A[i, i], (i, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) Trace(A) More complicated expressions: >>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) A*B.T*A.T """ from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix first_indices = [] if first_index is not None: first_indices.append(first_index) if last_index is not None: first_indices.append(last_index) arr = convert_indexed_to_array(expr, first_indices=first_indices) return convert_array_to_matrix(arr) def applyfunc(self, func): from .applyfunc import ElementwiseApplyFunction return ElementwiseApplyFunction(func, self) @dispatch(MatrixExpr, Expr) def _eval_is_eq(lhs, rhs): # noqa:F811 return False @dispatch(MatrixExpr, MatrixExpr) # type: ignore def _eval_is_eq(lhs, rhs): # noqa:F811 if lhs.shape != rhs.shape: return False if (lhs - rhs).is_ZeroMatrix: return True def get_postprocessor(cls): def _postprocessor(expr): # To avoid circular imports, we can't have MatMul/MatAdd on the top level mat_class = {Mul: MatMul, Add: MatAdd}[cls] nonmatrices = [] matrices = [] for term in expr.args: if isinstance(term, MatrixExpr): matrices.append(term) else: nonmatrices.append(term) if not matrices: return cls._from_args(nonmatrices) if nonmatrices: if cls == Mul: for i in range(len(matrices)): if not matrices[i].is_MatrixExpr: # If one of the matrices explicit, absorb the scalar into it # (doit will combine all explicit matrices into one, so it # doesn't matter which) matrices[i] = matrices[i].__mul__(cls._from_args(nonmatrices)) nonmatrices = [] break else: # Maintain the ability to create Add(scalar, matrix) without # raising an exception. That way different algorithms can # replace matrix expressions with non-commutative symbols to # manipulate them like non-commutative scalars. return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)]) if mat_class == MatAdd: return mat_class(*matrices).doit(deep=False) return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False) return _postprocessor Basic._constructor_postprocessor_mapping[MatrixExpr] = { "Mul": [get_postprocessor(Mul)], "Add": [get_postprocessor(Add)], } def _matrix_derivative(expr, x, old_algorithm=False): if isinstance(expr, MatrixBase) or isinstance(x, MatrixBase): # Do not use array expressions for explicit matrices: old_algorithm = True if old_algorithm: return _matrix_derivative_old_algorithm(expr, x) from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix array_expr = convert_matrix_to_array(expr) diff_array_expr = array_derive(array_expr, x) diff_matrix_expr = convert_array_to_matrix(diff_array_expr) return diff_matrix_expr def _matrix_derivative_old_algorithm(expr, x): from sympy.tensor.array.array_derivatives import ArrayDerivative lines = expr._eval_derivative_matrix_lines(x) parts = [i.build() for i in lines] from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix parts = [[convert_array_to_matrix(j) for j in i] for i in parts] def _get_shape(elem): if isinstance(elem, MatrixExpr): return elem.shape return 1, 1 def get_rank(parts): return sum([j not in (1, None) for i in parts for j in _get_shape(i)]) ranks = [get_rank(i) for i in parts] rank = ranks[0] def contract_one_dims(parts): if len(parts) == 1: return parts[0] else: p1, p2 = parts[:2] if p2.is_Matrix: p2 = p2.T if p1 == Identity(1): pbase = p2 elif p2 == Identity(1): pbase = p1 else: pbase = p1*p2 if len(parts) == 2: return pbase else: # len(parts) > 2 if pbase.is_Matrix: raise ValueError("") return pbase*Mul.fromiter(parts[2:]) if rank <= 2: return Add.fromiter([contract_one_dims(i) for i in parts]) return ArrayDerivative(expr, x) class MatrixElement(Expr): parent = property(lambda self: self.args[0]) i = property(lambda self: self.args[1]) j = property(lambda self: self.args[2]) _diff_wrt = True is_symbol = True is_commutative = True def __new__(cls, name, n, m): n, m = map(_sympify, (n, m)) from sympy.matrices.matrices import MatrixBase if isinstance(name, str): name = Symbol(name) else: if isinstance(name, MatrixBase): if n.is_Integer and m.is_Integer: return name[n, m] name = _sympify(name) # change mutable into immutable else: name = _sympify(name) if not isinstance(name.kind, MatrixKind): raise TypeError("First argument of MatrixElement should be a matrix") if not getattr(name, 'valid_index', lambda n, m: True)(n, m): raise IndexError('indices out of range') obj = Expr.__new__(cls, name, n, m) return obj @property def symbol(self): return self.args[0] def doit(self, **hints): deep = hints.get('deep', True) if deep: args = [arg.doit(**hints) for arg in self.args] else: args = self.args return args[0][args[1], args[2]] @property def indices(self): return self.args[1:] def _eval_derivative(self, v): if not isinstance(v, MatrixElement): from sympy.matrices.matrices import MatrixBase if isinstance(self.parent, MatrixBase): return self.parent.diff(v)[self.i, self.j] return S.Zero M = self.args[0] m, n = self.parent.shape if M == v.args[0]: return KroneckerDelta(self.args[1], v.args[1], (0, m-1)) * \ KroneckerDelta(self.args[2], v.args[2], (0, n-1)) if isinstance(M, Inverse): from sympy.concrete.summations import Sum i, j = self.args[1:] i1, i2 = symbols("z1, z2", cls=Dummy) Y = M.args[0] r1, r2 = Y.shape return -Sum(M[i, i1]*Y[i1, i2].diff(v)*M[i2, j], (i1, 0, r1-1), (i2, 0, r2-1)) if self.has(v.args[0]): return None return S.Zero class MatrixSymbol(MatrixExpr): """Symbolic representation of a Matrix object Creates a SymPy Symbol to represent a Matrix. This matrix has a shape and can be included in Matrix Expressions Examples ======== >>> from sympy import MatrixSymbol, Identity >>> A = MatrixSymbol('A', 3, 4) # A 3 by 4 Matrix >>> B = MatrixSymbol('B', 4, 3) # A 4 by 3 Matrix >>> A.shape (3, 4) >>> 2*A*B + Identity(3) I + 2*A*B """ is_commutative = False is_symbol = True _diff_wrt = True def __new__(cls, name, n, m): n, m = _sympify(n), _sympify(m) cls._check_dim(m) cls._check_dim(n) if isinstance(name, str): name = Str(name) obj = Basic.__new__(cls, name, n, m) return obj @property def shape(self): return self.args[1], self.args[2] @property def name(self): return self.args[0].name def _entry(self, i, j, **kwargs): return MatrixElement(self, i, j) @property def free_symbols(self): return {self} def _eval_simplify(self, **kwargs): return self def _eval_derivative(self, x): # x is a scalar: return ZeroMatrix(self.shape[0], self.shape[1]) def _eval_derivative_matrix_lines(self, x): if self != x: first = ZeroMatrix(x.shape[0], self.shape[0]) if self.shape[0] != 1 else S.Zero second = ZeroMatrix(x.shape[1], self.shape[1]) if self.shape[1] != 1 else S.Zero return [_LeftRightArgs( [first, second], )] else: first = Identity(self.shape[0]) if self.shape[0] != 1 else S.One second = Identity(self.shape[1]) if self.shape[1] != 1 else S.One return [_LeftRightArgs( [first, second], )] def matrix_symbols(expr): return [sym for sym in expr.free_symbols if sym.is_Matrix] class _LeftRightArgs: r""" Helper class to compute matrix derivatives. The logic: when an expression is derived by a matrix `X_{mn}`, two lines of matrix multiplications are created: the one contracted to `m` (first line), and the one contracted to `n` (second line). Transposition flips the side by which new matrices are connected to the lines. The trace connects the end of the two lines. """ def __init__(self, lines, higher=S.One): self._lines = [i for i in lines] self._first_pointer_parent = self._lines self._first_pointer_index = 0 self._first_line_index = 0 self._second_pointer_parent = self._lines self._second_pointer_index = 1 self._second_line_index = 1 self.higher = higher @property def first_pointer(self): return self._first_pointer_parent[self._first_pointer_index] @first_pointer.setter def first_pointer(self, value): self._first_pointer_parent[self._first_pointer_index] = value @property def second_pointer(self): return self._second_pointer_parent[self._second_pointer_index] @second_pointer.setter def second_pointer(self, value): self._second_pointer_parent[self._second_pointer_index] = value def __repr__(self): built = [self._build(i) for i in self._lines] return "_LeftRightArgs(lines=%s, higher=%s)" % ( built, self.higher, ) def transpose(self): self._first_pointer_parent, self._second_pointer_parent = self._second_pointer_parent, self._first_pointer_parent self._first_pointer_index, self._second_pointer_index = self._second_pointer_index, self._first_pointer_index self._first_line_index, self._second_line_index = self._second_line_index, self._first_line_index return self @staticmethod def _build(expr): if isinstance(expr, ExprBuilder): return expr.build() if isinstance(expr, list): if len(expr) == 1: return expr[0] else: return expr[0](*[_LeftRightArgs._build(i) for i in expr[1]]) else: return expr def build(self): data = [self._build(i) for i in self._lines] if self.higher != 1: data += [self._build(self.higher)] data = [i for i in data] return data def matrix_form(self): if self.first != 1 and self.higher != 1: raise ValueError("higher dimensional array cannot be represented") def _get_shape(elem): if isinstance(elem, MatrixExpr): return elem.shape return (None, None) if _get_shape(self.first)[1] != _get_shape(self.second)[1]: # Remove one-dimensional identity matrices: # (this is needed by `a.diff(a)` where `a` is a vector) if _get_shape(self.second) == (1, 1): return self.first*self.second[0, 0] if _get_shape(self.first) == (1, 1): return self.first[1, 1]*self.second.T raise ValueError("incompatible shapes") if self.first != 1: return self.first*self.second.T else: return self.higher def rank(self): """ Number of dimensions different from trivial (warning: not related to matrix rank). """ rank = 0 if self.first != 1: rank += sum([i != 1 for i in self.first.shape]) if self.second != 1: rank += sum([i != 1 for i in self.second.shape]) if self.higher != 1: rank += 2 return rank def _multiply_pointer(self, pointer, other): from ...tensor.array.expressions.array_expressions import ArrayTensorProduct from ...tensor.array.expressions.array_expressions import ArrayContraction subexpr = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ pointer, other ] ), (1, 2) ], validator=ArrayContraction._validate ) return subexpr def append_first(self, other): self.first_pointer *= other def append_second(self, other): self.second_pointer *= other def _make_matrix(x): from sympy.matrices.immutable import ImmutableDenseMatrix if isinstance(x, MatrixExpr): return x return ImmutableDenseMatrix([[x]]) from .matmul import MatMul from .matadd import MatAdd from .matpow import MatPow from .transpose import Transpose from .inverse import Inverse from .special import ZeroMatrix, Identity from .determinant import Determinant
3c3d52453dbab7b4b9b7ba33e067465d43768b2a08500b6e7a3b9e4bf6809781
#!/usr/bin/env python3 from subprocess import check_output import sys import os.path def main(tarname, gitroot): """Run this as ./compare_tar_against_git.py TARFILE GITROOT Args ==== TARFILE: Path to the built sdist (sympy-xx.tar.gz) GITROOT: Path ro root of git (dir containing .git) """ compare_tar_against_git(tarname, gitroot) ## TARBALL WHITELISTS # If a file does not end up in the tarball that should, add it to setup.py if # it is Python, or MANIFEST.in if it is not. (There is a command at the top # of setup.py to gather all the things that should be there). # TODO: Also check that this whitelist isn't growing out of date from files # removed from git. # Files that are in git that should not be in the tarball git_whitelist = { # Git specific dotfiles '.gitattributes', '.gitignore', '.mailmap', # Travis and CI '.travis.yml', '.github/workflows/runtests.yml', '.github/workflows/ci-sage.yml', '.github/workflows/comment-on-pr.yml', '.github/workflows/release.yml', '.github/workflows/docs-preview.yml', '.github/workflows/checkconflict.yml', '.ci/durations.json', '.ci/generate_durations_log.sh', '.ci/parse_durations_log.py', '.ci/blacklisted.json', '.ci/README.rst', '.circleci/config.yml', '.github/FUNDING.yml', '.editorconfig', '.coveragerc', 'CODEOWNERS', 'asv.conf.actions.json', 'asv.conf.travis.json', 'coveragerc_travis', 'codecov.yml', 'pytest.ini', 'MANIFEST.in', 'banner.svg', # Code of conduct 'CODE_OF_CONDUCT.md', # Pull request template 'PULL_REQUEST_TEMPLATE.md', # Contributing guide 'CONTRIBUTING.md', # Nothing from bin/ should be shipped unless we intend to install it. Most # of this stuff is for development anyway. To run the tests from the # tarball, use setup.py test, or import sympy and run sympy.test() or # sympy.doctest(). 'bin/adapt_paths.py', 'bin/ask_update.py', 'bin/authors_update.py', 'bin/build_doc.sh', 'bin/coverage_doctest.py', 'bin/coverage_report.py', 'bin/deploy_doc.sh', 'bin/diagnose_imports', 'bin/doctest', 'bin/generate_module_list.py', 'bin/generate_test_list.py', 'bin/get_sympy.py', 'bin/mailmap_update.py', 'bin/py.bench', 'bin/strip_whitespace', 'bin/sympy_time.py', 'bin/sympy_time_cache.py', 'bin/test', 'bin/test_external_imports.py', 'bin/test_executable.py', 'bin/test_import', 'bin/test_import.py', 'bin/test_isolated', 'bin/test_py2_import.py', 'bin/test_setup.py', 'bin/test_submodule_imports.py', 'bin/test_travis.sh', 'bin/test_optional_dependencies.py', 'bin/test_sphinx.sh', 'bin/mailmap_check.py', 'bin/test_symengine.py', 'bin/test_tensorflow.py', 'bin/test_pyodide.mjs', # The notebooks are not ready for shipping yet. They need to be cleaned # up, and preferably doctested. See also # https://github.com/sympy/sympy/issues/6039. 'examples/advanced/identitysearch_example.ipynb', 'examples/beginner/plot_advanced.ipynb', 'examples/beginner/plot_colors.ipynb', 'examples/beginner/plot_discont.ipynb', 'examples/beginner/plot_gallery.ipynb', 'examples/beginner/plot_intro.ipynb', 'examples/intermediate/limit_examples_advanced.ipynb', 'examples/intermediate/schwarzschild.ipynb', 'examples/notebooks/density.ipynb', 'examples/notebooks/fidelity.ipynb', 'examples/notebooks/fresnel_integrals.ipynb', 'examples/notebooks/qubits.ipynb', 'examples/notebooks/sho1d_example.ipynb', 'examples/notebooks/spin.ipynb', 'examples/notebooks/trace.ipynb', 'examples/notebooks/Bezout_Dixon_resultant.ipynb', 'examples/notebooks/IntegrationOverPolytopes.ipynb', 'examples/notebooks/Macaulay_resultant.ipynb', 'examples/notebooks/Sylvester_resultant.ipynb', 'examples/notebooks/README.txt', # This stuff :) 'release/.gitignore', 'release/README.md', 'release/compare_tar_against_git.py', 'release/update_docs.py', 'release/build_docs.py', 'release/github_release.py', 'release/helpers.py', 'release/releasecheck.py', 'release/sha256.py', 'release/authors.py', 'release/ci_release_script.sh', # This is just a distribute version of setup.py. Used mainly for setup.py # develop, which we don't care about in the release tarball 'setupegg.py', # pytest stuff 'conftest.py', # Encrypted deploy key for deploying dev docs to GitHub 'github_deploy_key.enc', } # Files that should be in the tarball should not be in git tarball_whitelist = { # Generated by setup.py. Contains metadata for PyPI. "PKG-INFO", # Generated by setuptools. More metadata. 'setup.cfg', 'sympy.egg-info/PKG-INFO', 'sympy.egg-info/SOURCES.txt', 'sympy.egg-info/dependency_links.txt', 'sympy.egg-info/requires.txt', 'sympy.egg-info/top_level.txt', 'sympy.egg-info/not-zip-safe', 'sympy.egg-info/entry_points.txt', # Not sure where this is generated from... 'doc/commit_hash.txt', } def blue(text): return "\033[34m%s\033[0m" % text def red(text): return "\033[31m%s\033[0m" % text def run(*cmdline, cwd=None): """ Run command in subprocess and get lines of output """ return check_output(cmdline, encoding='utf-8', cwd=cwd).splitlines() def full_path_split(path): """ Function to do a full split on a path. """ # Based on https://stackoverflow.com/a/13505966/161801 rest, tail = os.path.split(path) if not rest or rest == os.path.sep: return (tail,) return full_path_split(rest) + (tail,) def compare_tar_against_git(tarname, gitroot): """ Compare the contents of the tarball against git ls-files See the bottom of the file for the whitelists. """ git_lsfiles = set(i.strip() for i in run('git', 'ls-files', cwd=gitroot)) tar_output_orig = set(run('tar', 'tf', tarname)) tar_output = set() for file in tar_output_orig: # The tar files are like sympy-0.7.3/sympy/__init__.py, and the git # files are like sympy/__init__.py. split_path = full_path_split(file) if split_path[-1]: # Exclude directories, as git ls-files does not include them tar_output.add(os.path.join(*split_path[1:])) # print tar_output # print git_lsfiles fail = False print() print(blue("Files in the tarball from git that should not be there:")) print() for line in sorted(tar_output.intersection(git_whitelist)): fail = True print(line) print() print(blue("Files in git but not in the tarball:")) print() for line in sorted(git_lsfiles - tar_output - git_whitelist): fail = True print(line) print() print(blue("Files in the tarball but not in git:")) print() for line in sorted(tar_output - git_lsfiles - tarball_whitelist): fail = True print(line) print() if fail: sys.exit(red("Non-whitelisted files found or not found in the tarball")) if __name__ == "__main__": main(*sys.argv[1:])
cfd05d58144dc0c536f37f1f32a95a747e6e7b004176bb14e8241975203e24bd
# # SymPy documentation build configuration file, created by # sphinx-quickstart.py on Sat Mar 22 19:34:32 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default value; values that are commented out # serve to show the default value. import sys import inspect import os import subprocess from datetime import datetime # Make sure we import sympy from git sys.path.insert(0, os.path.abspath('../..')) import sympy # If your extensions are in another directory, add it here. sys.path = ['ext'] + sys.path # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.addons.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.linkcode', 'sphinx_math_dollar', 'sphinx.ext.mathjax', 'numpydoc', 'sphinx_reredirects', 'sphinx_copybutton', 'sphinx.ext.graphviz', 'matplotlib.sphinxext.plot_directive', 'myst_parser', 'convert-svg-to-pdf', 'sphinx.ext.intersphinx', ] # Add redirects here. This should be done whenever a page that is in the # existing release docs is moved somewhere else so that the URLs don't break. # The format is # "page/path/without/extension": "../relative_path_with.html" # Note that the html path is relative to the redirected page. Always test the # redirect manually (they aren't tested automatically). See # https://documatt.gitlab.io/sphinx-reredirects/usage.html redirects = { "guides/getting_started/install": "../../install.html", "documentation-style-guide": "contributing/documentation-style-guide.html", "gotchas": "explanation/gotchas.html", "special_topics/classification": "../explanation/classification.html", "special_topics/finite_diff_derivatives": "../explanation/finite_diff_derivatives.html", "special_topics/intro": "../explanation/index.html", "special_topics/index": "../explanation/index.html", "modules/index": "../reference/index.html", "modules/physics/index": "../../reference/public/physics/index.html", "guides/contributing/index": "../../contributing/index.html", "guides/contributing/dev-setup": "../../contributing/dev-setup.html", "guides/contributing/dependencies": "../../contributing/dependencies.html", "guides/contributing/build-docs": "../../contributing/build-docs.html", "guides/contributing/debug": "../../contributing/debug.html", "guides/contributing/docstring": "../../contributing/docstring.html", "guides/documentation-style-guide": "../../contributing/contributing/documentation-style-guide.html", "guides/make-a-contribution": "../../contributing/make-a-contribution.html", "guides/contributing/deprecations": "../../contributing/deprecations.html", "tutorial/preliminaries": "../tutorials/intro-tutorial/preliminaries.html", "tutorial/intro": "../tutorials/intro-tutorial/intro.html", "tutorial/index": "../tutorials/intro-tutorial/index.html", "tutorial/gotchas": "../tutorials/intro-tutorial/gotchas.html", "tutorial/features": "../tutorials/intro-tutorial/features.html", "tutorial/next": "../tutorials/intro-tutorial/next.html", "tutorial/basic_operations": "../tutorials/intro-tutorial/basic_operations.html", "tutorial/printing": "../tutorials/intro-tutorial/printing.html", "tutorial/simplification": "../tutorials/intro-tutorial/simplification.html", "tutorial/calculus": "../tutorials/intro-tutorial/calculus.html", "tutorial/solvers": "../tutorials/intro-tutorial/solvers.html", "tutorial/matrices": "../tutorials/intro-tutorial/matrices.html", "tutorial/manipulation": "../tutorials/intro-tutorial/manipulation.html", } html_baseurl = "https://docs.sympy.org/latest/" # Configure Sphinx copybutton (see https://sphinx-copybutton.readthedocs.io/en/latest/use.html) copybutton_prompt_text = r">>> |\.\.\. |\$ |In \[\d*\]: | {2,5}\.\.\.: | {5,8}: " copybutton_prompt_is_regexp = True # Use this to use pngmath instead #extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.pngmath', ] # Enable warnings for all bad cross references. These are turned into errors # with the -W flag in the Makefile. nitpicky = True nitpick_ignore = [ ('py:class', 'sympy.logic.boolalg.Boolean') ] # To stop docstrings inheritance. autodoc_inherit_docstrings = False # See https://www.sympy.org/sphinx-math-dollar/ mathjax3_config = { "tex": { "inlineMath": [['\\(', '\\)']], "displayMath": [["\\[", "\\]"]], } } # Myst configuration (for .md files). See # https://myst-parser.readthedocs.io/en/latest/syntax/optional.html myst_enable_extensions = ["dollarmath", "linkify"] myst_heading_anchors = 6 # myst_update_mathjax = False # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' suppress_warnings = ['ref.citation', 'ref.footnote'] # General substitutions. project = 'SymPy' copyright = '{} SymPy Development Team'.format(datetime.utcnow().year) # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. version = sympy.__version__ # The full version, including alpha/beta/rc tags. release = version # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. sys.path.append(os.path.abspath("./_pygments")) pygments_style = 'styles.SphinxHighContrastStyle' pygments_dark_style = 'styles.NativeHighContrastStyle' # Don't show the source code hyperlinks when using matplotlib plot directive. plot_html_show_source_link = False # Options for HTML output # ----------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. # html_style = 'default.css' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # was classic # html_theme = "classic" html_theme = "furo" # Adjust the sidebar so that the entire sidebar is scrollable html_sidebars = { "**": [ "sidebar/scroll-start.html", "sidebar/brand.html", "sidebar/search.html", "sidebar/navigation.html", "sidebar/versions.html", "sidebar/scroll-end.html", ], } common_theme_variables = { # Main "SymPy green" colors. Many things uses these colors. "color-brand-primary": "#52833A", "color-brand-content": "#307748", # The left sidebar. "color-sidebar-background": "#3B5526", "color-sidebar-background-border": "var(--color-background-primary)", "color-sidebar-link-text": "#FFFFFF", "color-sidebar-brand-text": "var(--color-sidebar-link-text--top-level)", "color-sidebar-link-text--top-level": "#FFFFFF", "color-sidebar-item-background--hover": "var(--color-brand-primary)", "color-sidebar-item-expander-background--hover": "var(--color-brand-primary)", "color-link-underline--hover": "var(--color-link)", "color-api-keyword": "#000000bd", "color-api-name": "var(--color-brand-content)", "color-api-pre-name": "var(--color-brand-content)", "api-font-size": "var(--font-size--normal)", "color-foreground-secondary": "#53555B", # TODO: Add the other types of admonitions here if anyone uses them. "color-admonition-title-background--seealso": "#CCCCCC", "color-admonition-title--seealso": "black", "color-admonition-title-background--note": "#CCCCCC", "color-admonition-title--note": "black", "color-admonition-title-background--warning": "var(--color-problematic)", "color-admonition-title--warning": "white", "admonition-font-size": "var(--font-size--normal)", "admonition-title-font-size": "var(--font-size--normal)", # Note: this doesn't work. If we want to change this, we have to set # it as the .highlight background in custom.css. "color-code-background": "hsl(80deg 100% 95%)", "code-font-size": "var(--font-size--small)", "font-stack--monospace": 'DejaVu Sans Mono,"SFMono-Regular",Menlo,Consolas,Monaco,Liberation Mono,Lucida Console,monospace;' } html_theme_options = { "light_css_variables": common_theme_variables, # The dark variables automatically inherit values from the light variables "dark_css_variables": { **common_theme_variables, "color-brand-primary": "#33CB33", "color-brand-content": "#1DBD1D", "color-api-keyword": "#FFFFFFbd", "color-api-overall": "#FFFFFF90", "color-api-paren": "#FFFFFF90", "color-sidebar-item-background--hover": "#52833A", "color-sidebar-item-expander-background--hover": "#52833A", # This is the color of the text in the right sidebar "color-foreground-secondary": "#9DA1AC", "color-admonition-title-background--seealso": "#555555", "color-admonition-title-background--note": "#555555", "color-problematic": "#B30000", }, # See https://pradyunsg.me/furo/customisation/footer/ "footer_icons": [ { "name": "GitHub", "url": "https://github.com/sympy/sympy", "html": """ <svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"></path> </svg> """, "class": "", }, ], } # Add a header for PR preview builds. See the Circle CI configuration. if os.environ.get("CIRCLECI") == "true": PR_NUMBER = os.environ.get('CIRCLE_PR_NUMBER') SHA1 = os.environ.get('CIRCLE_SHA1') html_theme_options['announcement'] = f"""This is a preview build from SymPy pull request <a href="https://github.com/sympy/sympy/pull/{PR_NUMBER}"> #{PR_NUMBER}</a>. It was built against <a href="https://github.com/sympy/sympy/pull/{PR_NUMBER}/commits/{SHA1}">{SHA1[:7]}</a>. If you aren't looking for a PR preview, go to <a href="https://docs.sympy.org/">the main SymPy documentation</a>. """ # custom.css contains changes that aren't possible with the above because they # aren't specified in the Furo theme as CSS variables html_css_files = ['custom.css'] # html_js_files = [] # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Content template for the index page. #html_index = '' # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True html_domain_indices = ['py-modindex'] # If true, the reST sources are included in the HTML build as _sources/<name>. # html_copy_source = True # Output file base name for HTML help builder. htmlhelp_basename = 'SymPydoc' language = 'en' # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual], toctree_only). # toctree_only is set to True so that the start file document itself is not included in the # output, only the documents referenced by it via TOC trees. The extra stuff in the master # document is intended to show up in the HTML, but doesn't really belong in the LaTeX output. latex_documents = [('index', 'sympy-%s.tex' % release, 'SymPy Documentation', 'SymPy Development Team', 'manual', True)] # Additional stuff for the LaTeX preamble. # Tweaked to work with XeTeX. latex_elements = { 'babel': '', 'fontenc': r''' % Define version of \LaTeX that is usable in math mode \let\OldLaTeX\LaTeX \renewcommand{\LaTeX}{\text{\OldLaTeX}} \usepackage{bm} \usepackage{amssymb} \usepackage{fontspec} \usepackage[english]{babel} \defaultfontfeatures{Mapping=tex-text} \setmainfont{DejaVu Serif} \setsansfont{DejaVu Sans} \setmonofont{DejaVu Sans Mono} ''', 'fontpkg': '', 'inputenc': '', 'utf8extra': '', 'preamble': r''' ''' } # SymPy logo on title page html_logo = '_static/sympylogo.png' latex_logo = '_static/sympylogo_big.png' html_favicon = '../_build/logo/sympy-notailtext-favicon.ico' # Documents to append as an appendix to all manuals. #latex_appendices = [] # Show page numbers next to internal references latex_show_pagerefs = True # We use False otherwise the module index gets generated twice. latex_use_modindex = False default_role = 'math' pngmath_divpng_args = ['-gamma 1.5', '-D 110'] # Note, this is ignored by the mathjax extension # Any \newcommand should be defined in the file pngmath_latex_preamble = '\\usepackage{amsmath}\n' \ '\\usepackage{bm}\n' \ '\\usepackage{amsfonts}\n' \ '\\usepackage{amssymb}\n' \ '\\setlength{\\parindent}{0pt}\n' texinfo_documents = [ (master_doc, 'sympy', 'SymPy Documentation', 'SymPy Development Team', 'SymPy', 'Computer algebra system (CAS) in Python', 'Programming', 1), ] # Use svg for graphviz graphviz_output_format = 'svg' # Enable links to other packages intersphinx_mapping = { 'matplotlib': ('https://matplotlib.org/stable/', None), 'mpmath': ('https://mpmath.org/doc/current/', None), "scipy": ("https://docs.scipy.org/doc/scipy/", None), "numpy": ("https://numpy.org/doc/stable/", None), } # Require :external: to reference intersphinx. Prevents accidentally linking # to something from matplotlib. intersphinx_disabled_reftypes = ['*'] # Requried for linkcode extension. # Get commit hash from the external file. commit_hash_filepath = '../commit_hash.txt' commit_hash = None if os.path.isfile(commit_hash_filepath): with open(commit_hash_filepath) as f: commit_hash = f.readline() # Get commit hash from the external file. if not commit_hash: try: commit_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD']) commit_hash = commit_hash.decode('ascii') commit_hash = commit_hash.rstrip() except: import warnings warnings.warn( "Failed to get the git commit hash as the command " \ "'git rev-parse HEAD' is not working. The commit hash will be " \ "assumed as the SymPy master, but the lines may be misleading " \ "or nonexistent as it is not the correct branch the doc is " \ "built with. Check your installation of 'git' if you want to " \ "resolve this warning.") commit_hash = 'master' fork = 'sympy' blobpath = \ "https://github.com/{}/sympy/blob/{}/sympy/".format(fork, commit_hash) def linkcode_resolve(domain, info): """Determine the URL corresponding to Python object.""" if domain != 'py': return modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return obj = submod for part in fullname.split('.'): try: obj = getattr(obj, part) except Exception: return # strip decorators, which would resolve to the source of the decorator # possibly an upstream bug in getsourcefile, bpo-1764286 try: unwrap = inspect.unwrap except AttributeError: pass else: obj = unwrap(obj) try: fn = inspect.getsourcefile(obj) except Exception: fn = None if not fn: return try: source, lineno = inspect.getsourcelines(obj) except Exception: lineno = None if lineno: linespec = "#L%d-L%d" % (lineno, lineno + len(source) - 1) else: linespec = "" fn = os.path.relpath(fn, start=os.path.dirname(sympy.__file__)) return blobpath + fn + linespec
ee940f4f45746de3c0bf1dc791804b6b8661d5bcf62fbb4ee2041f2072cf57dc
""" Finite Discrete Random Variables - Prebuilt variable types Contains ======== FiniteRV DiscreteUniform Die Bernoulli Coin Binomial BetaBinomial Hypergeometric Rademacher IdealSoliton RobustSoliton """ from sympy.core.cache import cacheit from sympy.core.function import Lambda from sympy.core.numbers import (Integer, Rational) from sympy.core.relational import (Eq, Ge, Gt, Le, Lt) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol) from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import binomial from sympy.functions.elementary.exponential import log from sympy.functions.elementary.piecewise import Piecewise from sympy.logic.boolalg import Or from sympy.sets.contains import Contains from sympy.sets.fancysets import Range from sympy.sets.sets import (Intersection, Interval) from sympy.functions.special.beta_functions import beta as beta_fn from sympy.stats.frv import (SingleFiniteDistribution, SingleFinitePSpace) from sympy.stats.rv import _value_check, Density, is_random from sympy.utilities.iterables import multiset from sympy.utilities.misc import filldedent __all__ = ['FiniteRV', 'DiscreteUniform', 'Die', 'Bernoulli', 'Coin', 'Binomial', 'BetaBinomial', 'Hypergeometric', 'Rademacher', 'IdealSoliton', 'RobustSoliton', ] def rv(name, cls, *args, **kwargs): args = list(map(sympify, args)) dist = cls(*args) if kwargs.pop('check', True): dist.check(*args) pspace = SingleFinitePSpace(name, dist) if any(is_random(arg) for arg in args): from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution pspace = CompoundPSpace(name, CompoundDistribution(dist)) return pspace.value class FiniteDistributionHandmade(SingleFiniteDistribution): @property def dict(self): return self.args[0] def pmf(self, x): x = Symbol('x') return Lambda(x, Piecewise(*( [(v, Eq(k, x)) for k, v in self.dict.items()] + [(S.Zero, True)]))) @property def set(self): return set(self.dict.keys()) @staticmethod def check(density): for p in density.values(): _value_check((p >= 0, p <= 1), "Probability at a point must be between 0 and 1.") val = sum(density.values()) _value_check(Eq(val, 1) != S.false, "Total Probability must be 1.") def FiniteRV(name, density, **kwargs): r""" Create a Finite Random Variable given a dict representing the density. Parameters ========== name : Symbol Represents name of the random variable. density : dict Dictionary containing the pdf of finite distribution check : bool If True, it will check whether the given density integrates to 1 over the given set. If False, it will not perform this check. Default is False. Examples ======== >>> from sympy.stats import FiniteRV, P, E >>> density = {0: .1, 1: .2, 2: .3, 3: .4} >>> X = FiniteRV('X', density) >>> E(X) 2.00000000000000 >>> P(X >= 2) 0.700000000000000 Returns ======= RandomSymbol """ # have a default of False while `rv` should have a default of True kwargs['check'] = kwargs.pop('check', False) return rv(name, FiniteDistributionHandmade, density, **kwargs) class DiscreteUniformDistribution(SingleFiniteDistribution): @staticmethod def check(*args): # not using _value_check since there is a # suggestion for the user if len(set(args)) != len(args): weights = multiset(args) n = Integer(len(args)) for k in weights: weights[k] /= n raise ValueError(filldedent(""" Repeated args detected but set expected. For a distribution having different weights for each item use the following:""") + ( '\nS("FiniteRV(%s, %s)")' % ("'X'", weights))) @property def p(self): return Rational(1, len(self.args)) @property # type: ignore @cacheit def dict(self): return {k: self.p for k in self.set} @property def set(self): return set(self.args) def pmf(self, x): if x in self.args: return self.p else: return S.Zero def DiscreteUniform(name, items): r""" Create a Finite Random Variable representing a uniform distribution over the input set. Parameters ========== items : list/tuple Items over which Uniform distribution is to be made Examples ======== >>> from sympy.stats import DiscreteUniform, density >>> from sympy import symbols >>> X = DiscreteUniform('X', symbols('a b c')) # equally likely over a, b, c >>> density(X).dict {a: 1/3, b: 1/3, c: 1/3} >>> Y = DiscreteUniform('Y', list(range(5))) # distribution over a range >>> density(Y).dict {0: 1/5, 1: 1/5, 2: 1/5, 3: 1/5, 4: 1/5} Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Discrete_uniform_distribution .. [2] http://mathworld.wolfram.com/DiscreteUniformDistribution.html """ return rv(name, DiscreteUniformDistribution, *items) class DieDistribution(SingleFiniteDistribution): _argnames = ('sides',) @staticmethod def check(sides): _value_check((sides.is_positive, sides.is_integer), "number of sides must be a positive integer.") @property def is_symbolic(self): return not self.sides.is_number @property def high(self): return self.sides @property def low(self): return S.One @property def set(self): if self.is_symbolic: return Intersection(S.Naturals0, Interval(0, self.sides)) return set(map(Integer, range(1, self.sides + 1))) def pmf(self, x): x = sympify(x) if not (x.is_number or x.is_Symbol or is_random(x)): raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or " "'RandomSymbol' not %s" % (type(x))) cond = Ge(x, 1) & Le(x, self.sides) & Contains(x, S.Integers) return Piecewise((S.One/self.sides, cond), (S.Zero, True)) def Die(name, sides=6): r""" Create a Finite Random Variable representing a fair die. Parameters ========== sides : Integer Represents the number of sides of the Die, by default is 6 Examples ======== >>> from sympy.stats import Die, density >>> from sympy import Symbol >>> D6 = Die('D6', 6) # Six sided Die >>> density(D6).dict {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6} >>> D4 = Die('D4', 4) # Four sided Die >>> density(D4).dict {1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4} >>> n = Symbol('n', positive=True, integer=True) >>> Dn = Die('Dn', n) # n sided Die >>> density(Dn).dict Density(DieDistribution(n)) >>> density(Dn).dict.subs(n, 4).doit() {1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4} Returns ======= RandomSymbol """ return rv(name, DieDistribution, sides) class BernoulliDistribution(SingleFiniteDistribution): _argnames = ('p', 'succ', 'fail') @staticmethod def check(p, succ, fail): _value_check((p >= 0, p <= 1), "p should be in range [0, 1].") @property def set(self): return {self.succ, self.fail} def pmf(self, x): if isinstance(self.succ, Symbol) and isinstance(self.fail, Symbol): return Piecewise((self.p, x == self.succ), (1 - self.p, x == self.fail), (S.Zero, True)) return Piecewise((self.p, Eq(x, self.succ)), (1 - self.p, Eq(x, self.fail)), (S.Zero, True)) def Bernoulli(name, p, succ=1, fail=0): r""" Create a Finite Random Variable representing a Bernoulli process. Parameters ========== p : Rational number between 0 and 1 Represents probability of success succ : Integer/symbol/string Represents event of success fail : Integer/symbol/string Represents event of failure Examples ======== >>> from sympy.stats import Bernoulli, density >>> from sympy import S >>> X = Bernoulli('X', S(3)/4) # 1-0 Bernoulli variable, probability = 3/4 >>> density(X).dict {0: 1/4, 1: 3/4} >>> X = Bernoulli('X', S.Half, 'Heads', 'Tails') # A fair coin toss >>> density(X).dict {Heads: 1/2, Tails: 1/2} Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Bernoulli_distribution .. [2] http://mathworld.wolfram.com/BernoulliDistribution.html """ return rv(name, BernoulliDistribution, p, succ, fail) def Coin(name, p=S.Half): r""" Create a Finite Random Variable representing a Coin toss. Parameters ========== p : Rational Numeber between 0 and 1 Represents probability of getting "Heads", by default is Half Examples ======== >>> from sympy.stats import Coin, density >>> from sympy import Rational >>> C = Coin('C') # A fair coin toss >>> density(C).dict {H: 1/2, T: 1/2} >>> C2 = Coin('C2', Rational(3, 5)) # An unfair coin >>> density(C2).dict {H: 3/5, T: 2/5} Returns ======= RandomSymbol See Also ======== sympy.stats.Binomial References ========== .. [1] https://en.wikipedia.org/wiki/Coin_flipping """ return rv(name, BernoulliDistribution, p, 'H', 'T') class BinomialDistribution(SingleFiniteDistribution): _argnames = ('n', 'p', 'succ', 'fail') @staticmethod def check(n, p, succ, fail): _value_check((n.is_integer, n.is_nonnegative), "'n' must be nonnegative integer.") _value_check((p <= 1, p >= 0), "p should be in range [0, 1].") @property def high(self): return self.n @property def low(self): return S.Zero @property def is_symbolic(self): return not self.n.is_number @property def set(self): if self.is_symbolic: return Intersection(S.Naturals0, Interval(0, self.n)) return set(self.dict.keys()) def pmf(self, x): n, p = self.n, self.p x = sympify(x) if not (x.is_number or x.is_Symbol or is_random(x)): raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or " "'RandomSymbol' not %s" % (type(x))) cond = Ge(x, 0) & Le(x, n) & Contains(x, S.Integers) return Piecewise((binomial(n, x) * p**x * (1 - p)**(n - x), cond), (S.Zero, True)) @property # type: ignore @cacheit def dict(self): if self.is_symbolic: return Density(self) return {k*self.succ + (self.n-k)*self.fail: self.pmf(k) for k in range(0, self.n + 1)} def Binomial(name, n, p, succ=1, fail=0): r""" Create a Finite Random Variable representing a binomial distribution. Parameters ========== n : Positive Integer Represents number of trials p : Rational Number between 0 and 1 Represents probability of success succ : Integer/symbol/string Represents event of success, by default is 1 fail : Integer/symbol/string Represents event of failure, by default is 0 Examples ======== >>> from sympy.stats import Binomial, density >>> from sympy import S, Symbol >>> X = Binomial('X', 4, S.Half) # Four "coin flips" >>> density(X).dict {0: 1/16, 1: 1/4, 2: 3/8, 3: 1/4, 4: 1/16} >>> n = Symbol('n', positive=True, integer=True) >>> p = Symbol('p', positive=True) >>> X = Binomial('X', n, S.Half) # n "coin flips" >>> density(X).dict Density(BinomialDistribution(n, 1/2, 1, 0)) >>> density(X).dict.subs(n, 4).doit() {0: 1/16, 1: 1/4, 2: 3/8, 3: 1/4, 4: 1/16} Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Binomial_distribution .. [2] http://mathworld.wolfram.com/BinomialDistribution.html """ return rv(name, BinomialDistribution, n, p, succ, fail) #------------------------------------------------------------------------------- # Beta-binomial distribution ---------------------------------------------------------- class BetaBinomialDistribution(SingleFiniteDistribution): _argnames = ('n', 'alpha', 'beta') @staticmethod def check(n, alpha, beta): _value_check((n.is_integer, n.is_nonnegative), "'n' must be nonnegative integer. n = %s." % str(n)) _value_check((alpha > 0), "'alpha' must be: alpha > 0 . alpha = %s" % str(alpha)) _value_check((beta > 0), "'beta' must be: beta > 0 . beta = %s" % str(beta)) @property def high(self): return self.n @property def low(self): return S.Zero @property def is_symbolic(self): return not self.n.is_number @property def set(self): if self.is_symbolic: return Intersection(S.Naturals0, Interval(0, self.n)) return set(map(Integer, range(self.n + 1))) def pmf(self, k): n, a, b = self.n, self.alpha, self.beta return binomial(n, k) * beta_fn(k + a, n - k + b) / beta_fn(a, b) def BetaBinomial(name, n, alpha, beta): r""" Create a Finite Random Variable representing a Beta-binomial distribution. Parameters ========== n : Positive Integer Represents number of trials alpha : Real positive number beta : Real positive number Examples ======== >>> from sympy.stats import BetaBinomial, density >>> X = BetaBinomial('X', 2, 1, 1) >>> density(X).dict {0: 1/3, 1: 2*beta(2, 2), 2: 1/3} Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Beta-binomial_distribution .. [2] http://mathworld.wolfram.com/BetaBinomialDistribution.html """ return rv(name, BetaBinomialDistribution, n, alpha, beta) class HypergeometricDistribution(SingleFiniteDistribution): _argnames = ('N', 'm', 'n') @staticmethod def check(n, N, m): _value_check((N.is_integer, N.is_nonnegative), "'N' must be nonnegative integer. N = %s." % str(n)) _value_check((n.is_integer, n.is_nonnegative), "'n' must be nonnegative integer. n = %s." % str(n)) _value_check((m.is_integer, m.is_nonnegative), "'m' must be nonnegative integer. m = %s." % str(n)) @property def is_symbolic(self): return not all(x.is_number for x in (self.N, self.m, self.n)) @property def high(self): return Piecewise((self.n, Lt(self.n, self.m) != False), (self.m, True)) @property def low(self): return Piecewise((0, Gt(0, self.n + self.m - self.N) != False), (self.n + self.m - self.N, True)) @property def set(self): N, m, n = self.N, self.m, self.n if self.is_symbolic: return Intersection(S.Naturals0, Interval(self.low, self.high)) return {i for i in range(max(0, n + m - N), min(n, m) + 1)} def pmf(self, k): N, m, n = self.N, self.m, self.n return S(binomial(m, k) * binomial(N - m, n - k))/binomial(N, n) def Hypergeometric(name, N, m, n): r""" Create a Finite Random Variable representing a hypergeometric distribution. Parameters ========== N : Positive Integer Represents finite population of size N. m : Positive Integer Represents number of trials with required feature. n : Positive Integer Represents numbers of draws. Examples ======== >>> from sympy.stats import Hypergeometric, density >>> X = Hypergeometric('X', 10, 5, 3) # 10 marbles, 5 white (success), 3 draws >>> density(X).dict {0: 1/12, 1: 5/12, 2: 5/12, 3: 1/12} Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Hypergeometric_distribution .. [2] http://mathworld.wolfram.com/HypergeometricDistribution.html """ return rv(name, HypergeometricDistribution, N, m, n) class RademacherDistribution(SingleFiniteDistribution): @property def set(self): return {-1, 1} @property def pmf(self): k = Dummy('k') return Lambda(k, Piecewise((S.Half, Or(Eq(k, -1), Eq(k, 1))), (S.Zero, True))) def Rademacher(name): r""" Create a Finite Random Variable representing a Rademacher distribution. Examples ======== >>> from sympy.stats import Rademacher, density >>> X = Rademacher('X') >>> density(X).dict {-1: 1/2, 1: 1/2} Returns ======= RandomSymbol See Also ======== sympy.stats.Bernoulli References ========== .. [1] https://en.wikipedia.org/wiki/Rademacher_distribution """ return rv(name, RademacherDistribution) class IdealSolitonDistribution(SingleFiniteDistribution): _argnames = ('k',) @staticmethod def check(k): _value_check(k.is_integer and k.is_positive, "'k' must be a positive integer.") @property def low(self): return S.One @property def high(self): return self.k @property def set(self): return set(map(Integer, range(1, self.k + 1))) @property # type: ignore @cacheit def dict(self): if self.k.is_Symbol: return Density(self) d = {1: Rational(1, self.k)} d.update(dict((i, Rational(1, i*(i - 1))) for i in range(2, self.k + 1))) return d def pmf(self, x): x = sympify(x) if not (x.is_number or x.is_Symbol or is_random(x)): raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or " "'RandomSymbol' not %s" % (type(x))) cond1 = Eq(x, 1) & x.is_integer cond2 = Ge(x, 1) & Le(x, self.k) & x.is_integer return Piecewise((1/self.k, cond1), (1/(x*(x - 1)), cond2), (S.Zero, True)) def IdealSoliton(name, k): r""" Create a Finite Random Variable of Ideal Soliton Distribution Parameters ========== k : Positive Integer Represents the number of input symbols in an LT (Luby Transform) code. Examples ======== >>> from sympy.stats import IdealSoliton, density, P, E >>> sol = IdealSoliton('sol', 5) >>> density(sol).dict {1: 1/5, 2: 1/2, 3: 1/6, 4: 1/12, 5: 1/20} >>> density(sol).set {1, 2, 3, 4, 5} >>> from sympy import Symbol >>> k = Symbol('k', positive=True, integer=True) >>> sol = IdealSoliton('sol', k) >>> density(sol).dict Density(IdealSolitonDistribution(k)) >>> density(sol).dict.subs(k, 10).doit() {1: 1/10, 2: 1/2, 3: 1/6, 4: 1/12, 5: 1/20, 6: 1/30, 7: 1/42, 8: 1/56, 9: 1/72, 10: 1/90} >>> E(sol.subs(k, 10)) 7381/2520 >>> P(sol.subs(k, 4) > 2) 1/4 Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Soliton_distribution#Ideal_distribution .. [2] http://pages.cs.wisc.edu/~suman/courses/740/papers/luby02lt.pdf """ return rv(name, IdealSolitonDistribution, k) class RobustSolitonDistribution(SingleFiniteDistribution): _argnames= ('k', 'delta', 'c') @staticmethod def check(k, delta, c): _value_check(k.is_integer and k.is_positive, "'k' must be a positive integer") _value_check(Gt(delta, 0) and Le(delta, 1), "'delta' must be a real number in the interval (0,1)") _value_check(c.is_positive, "'c' must be a positive real number.") @property def R(self): return self.c * log(self.k/self.delta) * self.k**0.5 @property def Z(self): z = 0 for i in Range(1, round(self.k/self.R)): z += (1/i) z += log(self.R/self.delta) return 1 + z * self.R/self.k @property def low(self): return S.One @property def high(self): return self.k @property def set(self): return set(map(Integer, range(1, self.k + 1))) @property def is_symbolic(self): return not (self.k.is_number and self.c.is_number and self.delta.is_number) def pmf(self, x): x = sympify(x) if not (x.is_number or x.is_Symbol or is_random(x)): raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or " "'RandomSymbol' not %s" % (type(x))) cond1 = Eq(x, 1) & x.is_integer cond2 = Ge(x, 1) & Le(x, self.k) & x.is_integer rho = Piecewise((Rational(1, self.k), cond1), (Rational(1, x*(x-1)), cond2), (S.Zero, True)) cond1 = Ge(x, 1) & Le(x, round(self.k/self.R)-1) cond2 = Eq(x, round(self.k/self.R)) tau = Piecewise((self.R/(self.k * x), cond1), (self.R * log(self.R/self.delta)/self.k, cond2), (S.Zero, True)) return (rho + tau)/self.Z def RobustSoliton(name, k, delta, c): r''' Create a Finite Random Variable of Robust Soliton Distribution Parameters ========== k : Positive Integer Represents the number of input symbols in an LT (Luby Transform) code. delta : Positive Rational Number Represents the failure probability. Must be in the interval (0,1). c : Positive Rational Number Constant of proportionality. Values close to 1 are recommended Examples ======== >>> from sympy.stats import RobustSoliton, density, P, E >>> robSol = RobustSoliton('robSol', 5, 0.5, 0.01) >>> density(robSol).dict {1: 0.204253668152708, 2: 0.490631107897393, 3: 0.165210624506162, 4: 0.0834387731899302, 5: 0.0505633404760675} >>> density(robSol).set {1, 2, 3, 4, 5} >>> from sympy import Symbol >>> k = Symbol('k', positive=True, integer=True) >>> c = Symbol('c', positive=True) >>> robSol = RobustSoliton('robSol', k, 0.5, c) >>> density(robSol).dict Density(RobustSolitonDistribution(k, 0.5, c)) >>> density(robSol).dict.subs(k, 10).subs(c, 0.03).doit() {1: 0.116641095387194, 2: 0.467045731687165, 3: 0.159984123349381, 4: 0.0821431680681869, 5: 0.0505765646770100, 6: 0.0345781523420719, 7: 0.0253132820710503, 8: 0.0194459129233227, 9: 0.0154831166726115, 10: 0.0126733075238887} >>> E(robSol.subs(k, 10).subs(c, 0.05)) 2.91358846104106 >>> P(robSol.subs(k, 4).subs(c, 0.1) > 2) 0.243650614389834 Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Soliton_distribution#Robust_distribution .. [2] http://www.inference.org.uk/mackay/itprnn/ps/588.596.pdf .. [3] http://pages.cs.wisc.edu/~suman/courses/740/papers/luby02lt.pdf ''' return rv(name, RobustSolitonDistribution, k, delta, c)
87ed50007d000d274c4b3d7652fad6c3d20a0eeb60a259a06122acdc3d197aff
from sympy.core.numbers import oo from sympy.core.relational import Eq from sympy.core.symbol import symbols from sympy.polys.domains import FiniteField, QQ, RationalField, FF from sympy.solvers.solvers import solve from sympy.utilities.iterables import is_sequence from sympy.utilities.misc import as_int from .factor_ import divisors from .residue_ntheory import polynomial_congruence class EllipticCurve: """ Create the following Elliptic Curve over domain. `y^{2} + a_{1} x y + a_{3} y = x^{3} + a_{2} x^{2} + a_{4} x + a_{6}` The default domain is ``QQ``. If no coefficient ``a1``, ``a2``, ``a3``, it create curve as following form. `y^{2} = x^{3} + a_{4} x + a_{6}` Examples ======== References ========== .. [1] J. Silverman "A Friendly Introduction to Number Theory" Third Edition .. [2] http://mathworld.wolfram.com/EllipticDiscriminant.html .. [3] G. Hardy, E. Wright "An Introduction to the Theory of Numbers" Sixth Edition """ def __init__(self, a4, a6, a1=0, a2=0, a3=0, modulus = 0): if modulus == 0: domain = QQ else: domain = FF(modulus) a1, a2, a3, a4, a6 = map(domain.convert, (a1, a2, a3, a4, a6)) self._domain = domain self.modulus = modulus # Calculate discriminant b2 = a1**2 + 4 * a2 b4 = 2 * a4 + a1 * a3 b6 = a3**2 + 4 * a6 b8 = a1**2 * a6 + 4 * a2 * a6 - a1 * a3 * a4 + a2 * a3**2 - a4**2 self._b2, self._b4, self._b6, self._b8 = b2, b4, b6, b8 self._discrim = -b2**2 * b8 - 8 * b4**3 - 27 * b6**2 + 9 * b2 * b4 * b6 self._a1 = a1 self._a2 = a2 self._a3 = a3 self._a4 = a4 self._a6 = a6 x, y, z = symbols('x y z') self.x, self.y, self.z = x, y, z self._eq = Eq(y**2*z + a1*x*y*z + a3*y*z**2, x**3 + a2*x**2*z + a4*x*z**2 + a6*z**3) if isinstance(self._domain, FiniteField): self._rank = 0 elif isinstance(self._domain, RationalField): self._rank = None def __call__(self, x, y, z=1): return EllipticCurvePoint(x, y, z, self) def __contains__(self, point): if is_sequence(point): if len(point) == 2: z1 = 1 else: z1 = point[2] x1, y1 = point[:2] elif isinstance(point, EllipticCurvePoint): x1, y1, z1 = point.x, point.y, point.z else: raise ValueError('Invalid point.') if self.characteristic == 0 and z1 == 0: return True return self._eq.subs({self.x: x1, self.y: y1, self.z: z1}) def __repr__(self): return 'E({}): {}'.format(self._domain, self._eq) def minimal(self): """ Return minimal Weierstrass equation. Examples ======== >>> from sympy.ntheory.elliptic_curve import EllipticCurve >>> e1 = EllipticCurve(-10, -20, 0, -1, 1) >>> e1.minimal() E(QQ): Eq(y**2*z, x**3 - 13392*x*z**2 - 1080432*z**3) """ char = self.characteristic if char == 2: return self if char == 3: return EllipticCurve(self._b4/2, self._b6/4, a2=self._b2/4, modulus=self.modulus) c4 = self._b2**2 - 24*self._b4 c6 = -self._b2**3 + 36*self._b2*self._b4 - 216*self._b6 return EllipticCurve(-27*c4, -54*c6, modulus=self.modulus) def points(self): """ Return points of curve over Finite Field. Examples ======== >>> from sympy.ntheory.elliptic_curve import EllipticCurve >>> e2 = EllipticCurve(1, 1, 1, 1, 1, modulus=5) >>> e2.points() {(0, 2), (1, 4), (2, 0), (2, 2), (3, 0), (3, 1), (4, 0)} """ char = self.characteristic all_pt = set() if char >= 1: for i in range(char): congruence_eq = ((self._eq.lhs - self._eq.rhs).subs({self.x: i, self.z: 1})) sol = polynomial_congruence(congruence_eq, char) for num in sol: all_pt.add((i, num)) return all_pt else: raise ValueError("Infinitely many points") def points_x(self, x): "Returns points on with curve where xcoordinate = x" pt = [] if self._domain == QQ: for y in solve(self._eq.subs(self.x, x)): pt.append((x, y)) congruence_eq = ((self._eq.lhs - self._eq.rhs).subs({self.x: x, self.z: 1})) for y in polynomial_congruence(congruence_eq, self.characteristic): pt.append((x, y)) return pt def torsion_points(self): """ Return torsion points of curve over Rational number. Return point objects those are finite order. According to Nagell-Lutz theorem, torsion point p(x, y) x and y are integers, either y = 0 or y**2 is divisor of discriminent. According to Mazur's theorem, there are at most 15 points in torsion collection. Examples ======== >>> from sympy.ntheory.elliptic_curve import EllipticCurve >>> e2 = EllipticCurve(-43, 166) >>> sorted(e2.torsion_points()) [(-5, -16), (-5, 16), O, (3, -8), (3, 8), (11, -32), (11, 32)] """ if self.characteristic > 0: raise ValueError("No torsion point for Finite Field.") l = [EllipticCurvePoint.point_at_infinity(self)] for xx in solve(self._eq.subs({self.y: 0, self.z: 1})): if xx.is_rational: l.append(self(xx, 0)) for i in divisors(self.discriminant, generator=True): j = int(i**.5) if j**2 == i: for xx in solve(self._eq.subs({self.y: j, self.z: 1})): if not xx.is_rational: continue p = self(xx, j) if p.order() != oo: l.extend([p, -p]) return l @property def characteristic(self): """ Return domain characteristic. Examples ======== >>> from sympy.ntheory.elliptic_curve import EllipticCurve >>> e2 = EllipticCurve(-43, 166) >>> e2.characteristic 0 """ return self._domain.characteristic() @property def discriminant(self): """ Return curve discriminant. Examples ======== >>> from sympy.ntheory.elliptic_curve import EllipticCurve >>> e2 = EllipticCurve(0, 17) >>> e2.discriminant -124848 """ return int(self._discrim) @property def is_singular(self): """ Return True if curve discriminant is equal to zero. """ return self.discriminant == 0 @property def j_invariant(self): """ Return curve j-invariant. Examples ======== >>> from sympy.ntheory.elliptic_curve import EllipticCurve >>> e1 = EllipticCurve(-2, 0, 0, 1, 1) >>> e1.j_invariant 1404928/389 """ c4 = self._b2**2 - 24*self._b4 return self._domain.to_sympy(c4**3 / self._discrim) @property def order(self): """ Number of points in Finite field. Examples ======== >>> from sympy.ntheory.elliptic_curve import EllipticCurve >>> e2 = EllipticCurve(1, 0, modulus=19) >>> e2.order 19 """ if self.characteristic == 0: raise NotImplementedError("Still not implemented") return len(self.points()) @property def rank(self): """ Number of independent points of infinite order. For Finite field, it must be 0. """ if self._rank is not None: return self._rank raise NotImplementedError("Still not implemented") class EllipticCurvePoint: """ Point of Elliptic Curve Examples ======== >>> from sympy.ntheory.elliptic_curve import EllipticCurve >>> e1 = EllipticCurve(-17, 16) >>> p1 = e1(0, -4, 1) >>> p2 = e1(1, 0) >>> p1 + p2 (15, -56) >>> e3 = EllipticCurve(-1, 9) >>> e3(1, -3) * 3 (664/169, 17811/2197) >>> (e3(1, -3) * 3).order() oo >>> e2 = EllipticCurve(-2, 0, 0, 1, 1) >>> p = e2(-1,1) >>> q = e2(0, -1) >>> p+q (4, 8) >>> p-q (1, 0) >>> 3*p-5*q (328/361, -2800/6859) """ @staticmethod def point_at_infinity(curve): return EllipticCurvePoint(0, 1, 0, curve) def __init__(self, x, y, z, curve): dom = curve._domain.convert self.x = dom(x) self.y = dom(y) self.z = dom(z) self._curve = curve self._domain = self._curve._domain if not self._curve.__contains__(self): raise ValueError("The curve does not contain this point") def __add__(self, p): if self.z == 0: return p if p.z == 0: return self x1, y1 = self.x/self.z, self.y/self.z x2, y2 = p.x/p.z, p.y/p.z a1 = self._curve._a1 a2 = self._curve._a2 a3 = self._curve._a3 a4 = self._curve._a4 a6 = self._curve._a6 if x1 != x2: slope = (y1 - y2) / (x1 - x2) yint = (y1 * x2 - y2 * x1) / (x2 - x1) else: if (y1 + y2) == 0: return self.point_at_infinity(self._curve) slope = (3 * x1**2 + 2*a2*x1 + a4 - a1*y1) / (a1 * x1 + a3 + 2 * y1) yint = (-x1**3 + a4*x1 + 2*a6 - a3*y1) / (a1*x1 + a3 + 2*y1) x3 = slope**2 + a1*slope - a2 - x1 - x2 y3 = -(slope + a1) * x3 - yint - a3 return self._curve(x3, y3, 1) def __lt__(self, other): return (self.x, self.y, self.z) < (other.x, other.y, other.z) def __mul__(self, n): n = as_int(n) r = self.point_at_infinity(self._curve) if n == 0: return r if n < 0: return -self * -n p = self while n: if n & 1: r = r + p n >>= 1 p = p + p return r def __rmul__(self, n): return self * n def __neg__(self): return EllipticCurvePoint(self.x, -self.y - self._curve._a1*self.x - self._curve._a3, self.z, self._curve) def __repr__(self): if self.z == 0: return 'O' dom = self._curve._domain try: return '({}, {})'.format(dom.to_sympy(self.x), dom.to_sympy(self.y)) except TypeError: pass return '({}, {})'.format(self.x, self.y) def __sub__(self, other): return self.__add__(-other) def order(self): """ Return point order n where nP = 0. """ if self.z == 0: return 1 if self.y == 0: # P = -P return 2 p = self * 2 if p.y == -self.y: # 2P = -P return 3 i = 2 if self._domain != QQ: while int(p.x) == p.x and int(p.y) == p.y: p = self + p i += 1 if p.z == 0: return i return oo while p.x.numerator == p.x and p.y.numerator == p.y: p = self + p i += 1 if i > 12: return oo if p.z == 0: return i return oo
f7f00dd3e3397be52990493e89c4a28d7327fa544f6f78485bcdb90518fb6be2
from math import factorial as _factorial, log, prod from itertools import chain, islice, product from sympy.combinatorics import Permutation from sympy.combinatorics.permutations import (_af_commutes_with, _af_invert, _af_rmul, _af_rmuln, _af_pow, Cycle) from sympy.combinatorics.util import (_check_cycles_alt_sym, _distribute_gens_by_base, _orbits_transversals_from_bsgs, _handle_precomputed_bsgs, _base_ordering, _strong_gens_from_distr, _strip, _strip_af) from sympy.core import Basic from sympy.core.random import _randrange, randrange, choice from sympy.core.symbol import Symbol from sympy.core.sympify import _sympify from sympy.functions.combinatorial.factorials import factorial from sympy.ntheory import primefactors, sieve from sympy.ntheory.factor_ import (factorint, multiplicity) from sympy.ntheory.primetest import isprime from sympy.utilities.iterables import has_variety, is_sequence, uniq rmul = Permutation.rmul_with_af _af_new = Permutation._af_new class PermutationGroup(Basic): r"""The class defining a Permutation group. Explanation =========== ``PermutationGroup([p1, p2, ..., pn])`` returns the permutation group generated by the list of permutations. This group can be supplied to Polyhedron if one desires to decorate the elements to which the indices of the permutation refer. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> from sympy.combinatorics import Polyhedron The permutations corresponding to motion of the front, right and bottom face of a $2 \times 2$ Rubik's cube are defined: >>> F = Permutation(2, 19, 21, 8)(3, 17, 20, 10)(4, 6, 7, 5) >>> R = Permutation(1, 5, 21, 14)(3, 7, 23, 12)(8, 10, 11, 9) >>> D = Permutation(6, 18, 14, 10)(7, 19, 15, 11)(20, 22, 23, 21) These are passed as permutations to PermutationGroup: >>> G = PermutationGroup(F, R, D) >>> G.order() 3674160 The group can be supplied to a Polyhedron in order to track the objects being moved. An example involving the $2 \times 2$ Rubik's cube is given there, but here is a simple demonstration: >>> a = Permutation(2, 1) >>> b = Permutation(1, 0) >>> G = PermutationGroup(a, b) >>> P = Polyhedron(list('ABC'), pgroup=G) >>> P.corners (A, B, C) >>> P.rotate(0) # apply permutation 0 >>> P.corners (A, C, B) >>> P.reset() >>> P.corners (A, B, C) Or one can make a permutation as a product of selected permutations and apply them to an iterable directly: >>> P10 = G.make_perm([0, 1]) >>> P10('ABC') ['C', 'A', 'B'] See Also ======== sympy.combinatorics.polyhedron.Polyhedron, sympy.combinatorics.permutations.Permutation References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" .. [2] Seress, A. "Permutation Group Algorithms" .. [3] https://en.wikipedia.org/wiki/Schreier_vector .. [4] https://en.wikipedia.org/wiki/Nielsen_transformation#Product_replacement_algorithm .. [5] Frank Celler, Charles R.Leedham-Green, Scott H.Murray, Alice C.Niemeyer, and E.A.O'Brien. "Generating Random Elements of a Finite Group" .. [6] https://en.wikipedia.org/wiki/Block_%28permutation_group_theory%29 .. [7] http://www.algorithmist.com/index.php/Union_Find .. [8] https://en.wikipedia.org/wiki/Multiply_transitive_group#Multiply_transitive_groups .. [9] https://en.wikipedia.org/wiki/Center_%28group_theory%29 .. [10] https://en.wikipedia.org/wiki/Centralizer_and_normalizer .. [11] http://groupprops.subwiki.org/wiki/Derived_subgroup .. [12] https://en.wikipedia.org/wiki/Nilpotent_group .. [13] http://www.math.colostate.edu/~hulpke/CGT/cgtnotes.pdf .. [14] https://www.gap-system.org/Manuals/doc/ref/manual.pdf """ is_group = True def __new__(cls, *args, dups=True, **kwargs): """The default constructor. Accepts Cycle and Permutation forms. Removes duplicates unless ``dups`` keyword is ``False``. """ if not args: args = [Permutation()] else: args = list(args[0] if is_sequence(args[0]) else args) if not args: args = [Permutation()] if any(isinstance(a, Cycle) for a in args): args = [Permutation(a) for a in args] if has_variety(a.size for a in args): degree = kwargs.pop('degree', None) if degree is None: degree = max(a.size for a in args) for i in range(len(args)): if args[i].size != degree: args[i] = Permutation(args[i], size=degree) if dups: args = list(uniq([_af_new(list(a)) for a in args])) if len(args) > 1: args = [g for g in args if not g.is_identity] return Basic.__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): self._generators = list(self.args) self._order = None self._center = [] self._is_abelian = None self._is_transitive = None self._is_sym = None self._is_alt = None self._is_primitive = None self._is_nilpotent = None self._is_solvable = None self._is_trivial = None self._transitivity_degree = None self._max_div = None self._is_perfect = None self._is_cyclic = None self._r = len(self._generators) self._degree = self._generators[0].size # these attributes are assigned after running schreier_sims self._base = [] self._strong_gens = [] self._strong_gens_slp = [] self._basic_orbits = [] self._transversals = [] self._transversal_slp = [] # these attributes are assigned after running _random_pr_init self._random_gens = [] # finite presentation of the group as an instance of `FpGroup` self._fp_presentation = None def __getitem__(self, i): return self._generators[i] def __contains__(self, i): """Return ``True`` if *i* is contained in PermutationGroup. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> p = Permutation(1, 2, 3) >>> Permutation(3) in PermutationGroup(p) True """ if not isinstance(i, Permutation): raise TypeError("A PermutationGroup contains only Permutations as " "elements, not elements of type %s" % type(i)) return self.contains(i) def __len__(self): return len(self._generators) def equals(self, other): """Return ``True`` if PermutationGroup generated by elements in the group are same i.e they represent the same PermutationGroup. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> p = Permutation(0, 1, 2, 3, 4, 5) >>> G = PermutationGroup([p, p**2]) >>> H = PermutationGroup([p**2, p]) >>> G.generators == H.generators False >>> G.equals(H) True """ if not isinstance(other, PermutationGroup): return False set_self_gens = set(self.generators) set_other_gens = set(other.generators) # before reaching the general case there are also certain # optimisation and obvious cases requiring less or no actual # computation. if set_self_gens == set_other_gens: return True # in the most general case it will check that each generator of # one group belongs to the other PermutationGroup and vice-versa for gen1 in set_self_gens: if not other.contains(gen1): return False for gen2 in set_other_gens: if not self.contains(gen2): return False return True def __mul__(self, other): """ Return the direct product of two permutation groups as a permutation group. Explanation =========== This implementation realizes the direct product by shifting the index set for the generators of the second group: so if we have ``G`` acting on ``n1`` points and ``H`` acting on ``n2`` points, ``G*H`` acts on ``n1 + n2`` points. Examples ======== >>> from sympy.combinatorics.named_groups import CyclicGroup >>> G = CyclicGroup(5) >>> H = G*G >>> H PermutationGroup([ (9)(0 1 2 3 4), (5 6 7 8 9)]) >>> H.order() 25 """ if isinstance(other, Permutation): return Coset(other, self, dir='+') gens1 = [perm._array_form for perm in self.generators] gens2 = [perm._array_form for perm in other.generators] n1 = self._degree n2 = other._degree start = list(range(n1)) end = list(range(n1, n1 + n2)) for i in range(len(gens2)): gens2[i] = [x + n1 for x in gens2[i]] gens2 = [start + gen for gen in gens2] gens1 = [gen + end for gen in gens1] together = gens1 + gens2 gens = [_af_new(x) for x in together] return PermutationGroup(gens) def _random_pr_init(self, r, n, _random_prec_n=None): r"""Initialize random generators for the product replacement algorithm. Explanation =========== The implementation uses a modification of the original product replacement algorithm due to Leedham-Green, as described in [1], pp. 69-71; also, see [2], pp. 27-29 for a detailed theoretical analysis of the original product replacement algorithm, and [4]. The product replacement algorithm is used for producing random, uniformly distributed elements of a group `G` with a set of generators `S`. For the initialization ``_random_pr_init``, a list ``R`` of `\max\{r, |S|\}` group generators is created as the attribute ``G._random_gens``, repeating elements of `S` if necessary, and the identity element of `G` is appended to ``R`` - we shall refer to this last element as the accumulator. Then the function ``random_pr()`` is called ``n`` times, randomizing the list ``R`` while preserving the generation of `G` by ``R``. The function ``random_pr()`` itself takes two random elements ``g, h`` among all elements of ``R`` but the accumulator and replaces ``g`` with a randomly chosen element from `\{gh, g(~h), hg, (~h)g\}`. Then the accumulator is multiplied by whatever ``g`` was replaced by. The new value of the accumulator is then returned by ``random_pr()``. The elements returned will eventually (for ``n`` large enough) become uniformly distributed across `G` ([5]). For practical purposes however, the values ``n = 50, r = 11`` are suggested in [1]. Notes ===== THIS FUNCTION HAS SIDE EFFECTS: it changes the attribute self._random_gens See Also ======== random_pr """ deg = self.degree random_gens = [x._array_form for x in self.generators] k = len(random_gens) if k < r: for i in range(k, r): random_gens.append(random_gens[i - k]) acc = list(range(deg)) random_gens.append(acc) self._random_gens = random_gens # handle randomized input for testing purposes if _random_prec_n is None: for i in range(n): self.random_pr() else: for i in range(n): self.random_pr(_random_prec=_random_prec_n[i]) def _union_find_merge(self, first, second, ranks, parents, not_rep): """Merges two classes in a union-find data structure. Explanation =========== Used in the implementation of Atkinson's algorithm as suggested in [1], pp. 83-87. The class merging process uses union by rank as an optimization. ([7]) Notes ===== THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives, ``parents``, the list of class sizes, ``ranks``, and the list of elements that are not representatives, ``not_rep``, are changed due to class merging. See Also ======== minimal_block, _union_find_rep References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" .. [7] http://www.algorithmist.com/index.php/Union_Find """ rep_first = self._union_find_rep(first, parents) rep_second = self._union_find_rep(second, parents) if rep_first != rep_second: # union by rank if ranks[rep_first] >= ranks[rep_second]: new_1, new_2 = rep_first, rep_second else: new_1, new_2 = rep_second, rep_first total_rank = ranks[new_1] + ranks[new_2] if total_rank > self.max_div: return -1 parents[new_2] = new_1 ranks[new_1] = total_rank not_rep.append(new_2) return 1 return 0 def _union_find_rep(self, num, parents): """Find representative of a class in a union-find data structure. Explanation =========== Used in the implementation of Atkinson's algorithm as suggested in [1], pp. 83-87. After the representative of the class to which ``num`` belongs is found, path compression is performed as an optimization ([7]). Notes ===== THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives, ``parents``, is altered due to path compression. See Also ======== minimal_block, _union_find_merge References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" .. [7] http://www.algorithmist.com/index.php/Union_Find """ rep, parent = num, parents[num] while parent != rep: rep = parent parent = parents[rep] # path compression temp, parent = num, parents[num] while parent != rep: parents[temp] = rep temp = parent parent = parents[temp] return rep @property def base(self): r"""Return a base from the Schreier-Sims algorithm. Explanation =========== For a permutation group `G`, a base is a sequence of points `B = (b_1, b_2, \dots, b_k)` such that no element of `G` apart from the identity fixes all the points in `B`. The concepts of a base and strong generating set and their applications are discussed in depth in [1], pp. 87-89 and [2], pp. 55-57. An alternative way to think of `B` is that it gives the indices of the stabilizer cosets that contain more than the identity permutation. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> G = PermutationGroup([Permutation(0, 1, 3)(2, 4)]) >>> G.base [0, 2] See Also ======== strong_gens, basic_transversals, basic_orbits, basic_stabilizers """ if self._base == []: self.schreier_sims() return self._base def baseswap(self, base, strong_gens, pos, randomized=False, transversals=None, basic_orbits=None, strong_gens_distr=None): r"""Swap two consecutive base points in base and strong generating set. Explanation =========== If a base for a group `G` is given by `(b_1, b_2, \dots, b_k)`, this function returns a base `(b_1, b_2, \dots, b_{i+1}, b_i, \dots, b_k)`, where `i` is given by ``pos``, and a strong generating set relative to that base. The original base and strong generating set are not modified. The randomized version (default) is of Las Vegas type. Parameters ========== base, strong_gens The base and strong generating set. pos The position at which swapping is performed. randomized A switch between randomized and deterministic version. transversals The transversals for the basic orbits, if known. basic_orbits The basic orbits, if known. strong_gens_distr The strong generators distributed by basic stabilizers, if known. Returns ======= (base, strong_gens) ``base`` is the new base, and ``strong_gens`` is a generating set relative to it. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> S = SymmetricGroup(4) >>> S.schreier_sims() >>> S.base [0, 1, 2] >>> base, gens = S.baseswap(S.base, S.strong_gens, 1, randomized=False) >>> base, gens ([0, 2, 1], [(0 1 2 3), (3)(0 1), (1 3 2), (2 3), (1 3)]) check that base, gens is a BSGS >>> S1 = PermutationGroup(gens) >>> _verify_bsgs(S1, base, gens) True See Also ======== schreier_sims Notes ===== The deterministic version of the algorithm is discussed in [1], pp. 102-103; the randomized version is discussed in [1], p.103, and [2], p.98. It is of Las Vegas type. Notice that [1] contains a mistake in the pseudocode and discussion of BASESWAP: on line 3 of the pseudocode, `|\beta_{i+1}^{\left\langle T\right\rangle}|` should be replaced by `|\beta_{i}^{\left\langle T\right\rangle}|`, and the same for the discussion of the algorithm. """ # construct the basic orbits, generators for the stabilizer chain # and transversal elements from whatever was provided transversals, basic_orbits, strong_gens_distr = \ _handle_precomputed_bsgs(base, strong_gens, transversals, basic_orbits, strong_gens_distr) base_len = len(base) degree = self.degree # size of orbit of base[pos] under the stabilizer we seek to insert # in the stabilizer chain at position pos + 1 size = len(basic_orbits[pos])*len(basic_orbits[pos + 1]) \ //len(_orbit(degree, strong_gens_distr[pos], base[pos + 1])) # initialize the wanted stabilizer by a subgroup if pos + 2 > base_len - 1: T = [] else: T = strong_gens_distr[pos + 2][:] # randomized version if randomized is True: stab_pos = PermutationGroup(strong_gens_distr[pos]) schreier_vector = stab_pos.schreier_vector(base[pos + 1]) # add random elements of the stabilizer until they generate it while len(_orbit(degree, T, base[pos])) != size: new = stab_pos.random_stab(base[pos + 1], schreier_vector=schreier_vector) T.append(new) # deterministic version else: Gamma = set(basic_orbits[pos]) Gamma.remove(base[pos]) if base[pos + 1] in Gamma: Gamma.remove(base[pos + 1]) # add elements of the stabilizer until they generate it by # ruling out member of the basic orbit of base[pos] along the way while len(_orbit(degree, T, base[pos])) != size: gamma = next(iter(Gamma)) x = transversals[pos][gamma] temp = x._array_form.index(base[pos + 1]) # (~x)(base[pos + 1]) if temp not in basic_orbits[pos + 1]: Gamma = Gamma - _orbit(degree, T, gamma) else: y = transversals[pos + 1][temp] el = rmul(x, y) if el(base[pos]) not in _orbit(degree, T, base[pos]): T.append(el) Gamma = Gamma - _orbit(degree, T, base[pos]) # build the new base and strong generating set strong_gens_new_distr = strong_gens_distr[:] strong_gens_new_distr[pos + 1] = T base_new = base[:] base_new[pos], base_new[pos + 1] = base_new[pos + 1], base_new[pos] strong_gens_new = _strong_gens_from_distr(strong_gens_new_distr) for gen in T: if gen not in strong_gens_new: strong_gens_new.append(gen) return base_new, strong_gens_new @property def basic_orbits(self): r""" Return the basic orbits relative to a base and strong generating set. Explanation =========== If `(b_1, b_2, \dots, b_k)` is a base for a group `G`, and `G^{(i)} = G_{b_1, b_2, \dots, b_{i-1}}` is the ``i``-th basic stabilizer (so that `G^{(1)} = G`), the ``i``-th basic orbit relative to this base is the orbit of `b_i` under `G^{(i)}`. See [1], pp. 87-89 for more information. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(4) >>> S.basic_orbits [[0, 1, 2, 3], [1, 2, 3], [2, 3]] See Also ======== base, strong_gens, basic_transversals, basic_stabilizers """ if self._basic_orbits == []: self.schreier_sims() return self._basic_orbits @property def basic_stabilizers(self): r""" Return a chain of stabilizers relative to a base and strong generating set. Explanation =========== The ``i``-th basic stabilizer `G^{(i)}` relative to a base `(b_1, b_2, \dots, b_k)` is `G_{b_1, b_2, \dots, b_{i-1}}`. For more information, see [1], pp. 87-89. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> A = AlternatingGroup(4) >>> A.schreier_sims() >>> A.base [0, 1] >>> for g in A.basic_stabilizers: ... print(g) ... PermutationGroup([ (3)(0 1 2), (1 2 3)]) PermutationGroup([ (1 2 3)]) See Also ======== base, strong_gens, basic_orbits, basic_transversals """ if self._transversals == []: self.schreier_sims() strong_gens = self._strong_gens base = self._base if not base: # e.g. if self is trivial return [] strong_gens_distr = _distribute_gens_by_base(base, strong_gens) basic_stabilizers = [] for gens in strong_gens_distr: basic_stabilizers.append(PermutationGroup(gens)) return basic_stabilizers @property def basic_transversals(self): """ Return basic transversals relative to a base and strong generating set. Explanation =========== The basic transversals are transversals of the basic orbits. They are provided as a list of dictionaries, each dictionary having keys - the elements of one of the basic orbits, and values - the corresponding transversal elements. See [1], pp. 87-89 for more information. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> A = AlternatingGroup(4) >>> A.basic_transversals [{0: (3), 1: (3)(0 1 2), 2: (3)(0 2 1), 3: (0 3 1)}, {1: (3), 2: (1 2 3), 3: (1 3 2)}] See Also ======== strong_gens, base, basic_orbits, basic_stabilizers """ if self._transversals == []: self.schreier_sims() return self._transversals def composition_series(self): r""" Return the composition series for a group as a list of permutation groups. Explanation =========== The composition series for a group `G` is defined as a subnormal series `G = H_0 > H_1 > H_2 \ldots` A composition series is a subnormal series such that each factor group `H(i+1) / H(i)` is simple. A subnormal series is a composition series only if it is of maximum length. The algorithm works as follows: Starting with the derived series the idea is to fill the gap between `G = der[i]` and `H = der[i+1]` for each `i` independently. Since, all subgroups of the abelian group `G/H` are normal so, first step is to take the generators `g` of `G` and add them to generators of `H` one by one. The factor groups formed are not simple in general. Each group is obtained from the previous one by adding one generator `g`, if the previous group is denoted by `H` then the next group `K` is generated by `g` and `H`. The factor group `K/H` is cyclic and it's order is `K.order()//G.order()`. The series is then extended between `K` and `H` by groups generated by powers of `g` and `H`. The series formed is then prepended to the already existing series. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.named_groups import CyclicGroup >>> S = SymmetricGroup(12) >>> G = S.sylow_subgroup(2) >>> C = G.composition_series() >>> [H.order() for H in C] [1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1] >>> G = S.sylow_subgroup(3) >>> C = G.composition_series() >>> [H.order() for H in C] [243, 81, 27, 9, 3, 1] >>> G = CyclicGroup(12) >>> C = G.composition_series() >>> [H.order() for H in C] [12, 6, 3, 1] """ der = self.derived_series() if not all(g.is_identity for g in der[-1].generators): raise NotImplementedError('Group should be solvable') series = [] for i in range(len(der)-1): H = der[i+1] up_seg = [] for g in der[i].generators: K = PermutationGroup([g] + H.generators) order = K.order() // H.order() down_seg = [] for p, e in factorint(order).items(): for _ in range(e): down_seg.append(PermutationGroup([g] + H.generators)) g = g**p up_seg = down_seg + up_seg H = K up_seg[0] = der[i] series.extend(up_seg) series.append(der[-1]) return series def coset_transversal(self, H): """Return a transversal of the right cosets of self by its subgroup H using the second method described in [1], Subsection 4.6.7 """ if not H.is_subgroup(self): raise ValueError("The argument must be a subgroup") if H.order() == 1: return self._elements self._schreier_sims(base=H.base) # make G.base an extension of H.base base = self.base base_ordering = _base_ordering(base, self.degree) identity = Permutation(self.degree - 1) transversals = self.basic_transversals[:] # transversals is a list of dictionaries. Get rid of the keys # so that it is a list of lists and sort each list in # the increasing order of base[l]^x for l, t in enumerate(transversals): transversals[l] = sorted(t.values(), key = lambda x: base_ordering[base[l]^x]) orbits = H.basic_orbits h_stabs = H.basic_stabilizers g_stabs = self.basic_stabilizers indices = [x.order()//y.order() for x, y in zip(g_stabs, h_stabs)] # T^(l) should be a right transversal of H^(l) in G^(l) for # 1<=l<=len(base). While H^(l) is the trivial group, T^(l) # contains all the elements of G^(l) so we might just as well # start with l = len(h_stabs)-1 if len(g_stabs) > len(h_stabs): T = g_stabs[len(h_stabs)]._elements else: T = [identity] l = len(h_stabs)-1 t_len = len(T) while l > -1: T_next = [] for u in transversals[l]: if u == identity: continue b = base_ordering[base[l]^u] for t in T: p = t*u if all(base_ordering[h^p] >= b for h in orbits[l]): T_next.append(p) if t_len + len(T_next) == indices[l]: break if t_len + len(T_next) == indices[l]: break T += T_next t_len += len(T_next) l -= 1 T.remove(identity) T = [identity] + T return T def _coset_representative(self, g, H): """Return the representative of Hg from the transversal that would be computed by ``self.coset_transversal(H)``. """ if H.order() == 1: return g # The base of self must be an extension of H.base. if not(self.base[:len(H.base)] == H.base): self._schreier_sims(base=H.base) orbits = H.basic_orbits[:] h_transversals = [list(_.values()) for _ in H.basic_transversals] transversals = [list(_.values()) for _ in self.basic_transversals] base = self.base base_ordering = _base_ordering(base, self.degree) def step(l, x): gamma = sorted(orbits[l], key = lambda y: base_ordering[y^x])[0] i = [base[l]^h for h in h_transversals[l]].index(gamma) x = h_transversals[l][i]*x if l < len(orbits)-1: for u in transversals[l]: if base[l]^u == base[l]^x: break x = step(l+1, x*u**-1)*u return x return step(0, g) def coset_table(self, H): """Return the standardised (right) coset table of self in H as a list of lists. """ # Maybe this should be made to return an instance of CosetTable # from fp_groups.py but the class would need to be changed first # to be compatible with PermutationGroups if not H.is_subgroup(self): raise ValueError("The argument must be a subgroup") T = self.coset_transversal(H) n = len(T) A = list(chain.from_iterable((gen, gen**-1) for gen in self.generators)) table = [] for i in range(n): row = [self._coset_representative(T[i]*x, H) for x in A] row = [T.index(r) for r in row] table.append(row) # standardize (this is the same as the algorithm used in coset_table) # If CosetTable is made compatible with PermutationGroups, this # should be replaced by table.standardize() A = range(len(A)) gamma = 1 for alpha, a in product(range(n), A): beta = table[alpha][a] if beta >= gamma: if beta > gamma: for x in A: z = table[gamma][x] table[gamma][x] = table[beta][x] table[beta][x] = z for i in range(n): if table[i][x] == beta: table[i][x] = gamma elif table[i][x] == gamma: table[i][x] = beta gamma += 1 if gamma >= n-1: return table def center(self): r""" Return the center of a permutation group. Explanation =========== The center for a group `G` is defined as `Z(G) = \{z\in G | \forall g\in G, zg = gz \}`, the set of elements of `G` that commute with all elements of `G`. It is equal to the centralizer of `G` inside `G`, and is naturally a subgroup of `G` ([9]). Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(4) >>> G = D.center() >>> G.order() 2 See Also ======== centralizer Notes ===== This is a naive implementation that is a straightforward application of ``.centralizer()`` """ return self.centralizer(self) def centralizer(self, other): r""" Return the centralizer of a group/set/element. Explanation =========== The centralizer of a set of permutations ``S`` inside a group ``G`` is the set of elements of ``G`` that commute with all elements of ``S``:: `C_G(S) = \{ g \in G | gs = sg \forall s \in S\}` ([10]) Usually, ``S`` is a subset of ``G``, but if ``G`` is a proper subgroup of the full symmetric group, we allow for ``S`` to have elements outside ``G``. It is naturally a subgroup of ``G``; the centralizer of a permutation group is equal to the centralizer of any set of generators for that group, since any element commuting with the generators commutes with any product of the generators. Parameters ========== other a permutation group/list of permutations/single permutation Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup) >>> S = SymmetricGroup(6) >>> C = CyclicGroup(6) >>> H = S.centralizer(C) >>> H.is_subgroup(C) True See Also ======== subgroup_search Notes ===== The implementation is an application of ``.subgroup_search()`` with tests using a specific base for the group ``G``. """ if hasattr(other, 'generators'): if other.is_trivial or self.is_trivial: return self degree = self.degree identity = _af_new(list(range(degree))) orbits = other.orbits() num_orbits = len(orbits) orbits.sort(key=lambda x: -len(x)) long_base = [] orbit_reps = [None]*num_orbits orbit_reps_indices = [None]*num_orbits orbit_descr = [None]*degree for i in range(num_orbits): orbit = list(orbits[i]) orbit_reps[i] = orbit[0] orbit_reps_indices[i] = len(long_base) for point in orbit: orbit_descr[point] = i long_base = long_base + orbit base, strong_gens = self.schreier_sims_incremental(base=long_base) strong_gens_distr = _distribute_gens_by_base(base, strong_gens) i = 0 for i in range(len(base)): if strong_gens_distr[i] == [identity]: break base = base[:i] base_len = i for j in range(num_orbits): if base[base_len - 1] in orbits[j]: break rel_orbits = orbits[: j + 1] num_rel_orbits = len(rel_orbits) transversals = [None]*num_rel_orbits for j in range(num_rel_orbits): rep = orbit_reps[j] transversals[j] = dict( other.orbit_transversal(rep, pairs=True)) trivial_test = lambda x: True tests = [None]*base_len for l in range(base_len): if base[l] in orbit_reps: tests[l] = trivial_test else: def test(computed_words, l=l): g = computed_words[l] rep_orb_index = orbit_descr[base[l]] rep = orbit_reps[rep_orb_index] im = g._array_form[base[l]] im_rep = g._array_form[rep] tr_el = transversals[rep_orb_index][base[l]] # using the definition of transversal, # base[l]^g = rep^(tr_el*g); # if g belongs to the centralizer, then # base[l]^g = (rep^g)^tr_el return im == tr_el._array_form[im_rep] tests[l] = test def prop(g): return [rmul(g, gen) for gen in other.generators] == \ [rmul(gen, g) for gen in other.generators] return self.subgroup_search(prop, base=base, strong_gens=strong_gens, tests=tests) elif hasattr(other, '__getitem__'): gens = list(other) return self.centralizer(PermutationGroup(gens)) elif hasattr(other, 'array_form'): return self.centralizer(PermutationGroup([other])) def commutator(self, G, H): """ Return the commutator of two subgroups. Explanation =========== For a permutation group ``K`` and subgroups ``G``, ``H``, the commutator of ``G`` and ``H`` is defined as the group generated by all the commutators `[g, h] = hgh^{-1}g^{-1}` for ``g`` in ``G`` and ``h`` in ``H``. It is naturally a subgroup of ``K`` ([1], p.27). Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> S = SymmetricGroup(5) >>> A = AlternatingGroup(5) >>> G = S.commutator(S, A) >>> G.is_subgroup(A) True See Also ======== derived_subgroup Notes ===== The commutator of two subgroups `H, G` is equal to the normal closure of the commutators of all the generators, i.e. `hgh^{-1}g^{-1}` for `h` a generator of `H` and `g` a generator of `G` ([1], p.28) """ ggens = G.generators hgens = H.generators commutators = [] for ggen in ggens: for hgen in hgens: commutator = rmul(hgen, ggen, ~hgen, ~ggen) if commutator not in commutators: commutators.append(commutator) res = self.normal_closure(commutators) return res def coset_factor(self, g, factor_index=False): """Return ``G``'s (self's) coset factorization of ``g`` Explanation =========== If ``g`` is an element of ``G`` then it can be written as the product of permutations drawn from the Schreier-Sims coset decomposition, The permutations returned in ``f`` are those for which the product gives ``g``: ``g = f[n]*...f[1]*f[0]`` where ``n = len(B)`` and ``B = G.base``. f[i] is one of the permutations in ``self._basic_orbits[i]``. If factor_index==True, returns a tuple ``[b[0],..,b[n]]``, where ``b[i]`` belongs to ``self._basic_orbits[i]`` Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5) >>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6) >>> G = PermutationGroup([a, b]) Define g: >>> g = Permutation(7)(1, 2, 4)(3, 6, 5) Confirm that it is an element of G: >>> G.contains(g) True Thus, it can be written as a product of factors (up to 3) drawn from u. See below that a factor from u1 and u2 and the Identity permutation have been used: >>> f = G.coset_factor(g) >>> f[2]*f[1]*f[0] == g True >>> f1 = G.coset_factor(g, True); f1 [0, 4, 4] >>> tr = G.basic_transversals >>> f[0] == tr[0][f1[0]] True If g is not an element of G then [] is returned: >>> c = Permutation(5, 6, 7) >>> G.coset_factor(c) [] See Also ======== sympy.combinatorics.util._strip """ if isinstance(g, (Cycle, Permutation)): g = g.list() if len(g) != self._degree: # this could either adjust the size or return [] immediately # but we don't choose between the two and just signal a possible # error raise ValueError('g should be the same size as permutations of G') I = list(range(self._degree)) basic_orbits = self.basic_orbits transversals = self._transversals factors = [] base = self.base h = g for i in range(len(base)): beta = h[base[i]] if beta == base[i]: factors.append(beta) continue if beta not in basic_orbits[i]: return [] u = transversals[i][beta]._array_form h = _af_rmul(_af_invert(u), h) factors.append(beta) if h != I: return [] if factor_index: return factors tr = self.basic_transversals factors = [tr[i][factors[i]] for i in range(len(base))] return factors def generator_product(self, g, original=False): r''' Return a list of strong generators `[s1, \dots, sn]` s.t `g = sn \times \dots \times s1`. If ``original=True``, make the list contain only the original group generators ''' product = [] if g.is_identity: return [] if g in self.strong_gens: if not original or g in self.generators: return [g] else: slp = self._strong_gens_slp[g] for s in slp: product.extend(self.generator_product(s, original=True)) return product elif g**-1 in self.strong_gens: g = g**-1 if not original or g in self.generators: return [g**-1] else: slp = self._strong_gens_slp[g] for s in slp: product.extend(self.generator_product(s, original=True)) l = len(product) product = [product[l-i-1]**-1 for i in range(l)] return product f = self.coset_factor(g, True) for i, j in enumerate(f): slp = self._transversal_slp[i][j] for s in slp: if not original: product.append(self.strong_gens[s]) else: s = self.strong_gens[s] product.extend(self.generator_product(s, original=True)) return product def coset_rank(self, g): """rank using Schreier-Sims representation. Explanation =========== The coset rank of ``g`` is the ordering number in which it appears in the lexicographic listing according to the coset decomposition The ordering is the same as in G.generate(method='coset'). If ``g`` does not belong to the group it returns None. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5) >>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6) >>> G = PermutationGroup([a, b]) >>> c = Permutation(7)(2, 4)(3, 5) >>> G.coset_rank(c) 16 >>> G.coset_unrank(16) (7)(2 4)(3 5) See Also ======== coset_factor """ factors = self.coset_factor(g, True) if not factors: return None rank = 0 b = 1 transversals = self._transversals base = self._base basic_orbits = self._basic_orbits for i in range(len(base)): k = factors[i] j = basic_orbits[i].index(k) rank += b*j b = b*len(transversals[i]) return rank def coset_unrank(self, rank, af=False): """unrank using Schreier-Sims representation coset_unrank is the inverse operation of coset_rank if 0 <= rank < order; otherwise it returns None. """ if rank < 0 or rank >= self.order(): return None base = self.base transversals = self.basic_transversals basic_orbits = self.basic_orbits m = len(base) v = [0]*m for i in range(m): rank, c = divmod(rank, len(transversals[i])) v[i] = basic_orbits[i][c] a = [transversals[i][v[i]]._array_form for i in range(m)] h = _af_rmuln(*a) if af: return h else: return _af_new(h) @property def degree(self): """Returns the size of the permutations in the group. Explanation =========== The number of permutations comprising the group is given by ``len(group)``; the number of permutations that can be generated by the group is given by ``group.order()``. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([1, 0, 2]) >>> G = PermutationGroup([a]) >>> G.degree 3 >>> len(G) 1 >>> G.order() 2 >>> list(G.generate()) [(2), (2)(0 1)] See Also ======== order """ return self._degree @property def identity(self): ''' Return the identity element of the permutation group. ''' return _af_new(list(range(self.degree))) @property def elements(self): """Returns all the elements of the permutation group as a set Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> p = PermutationGroup(Permutation(1, 3), Permutation(1, 2)) >>> p.elements {(1 2 3), (1 3 2), (1 3), (2 3), (3), (3)(1 2)} """ return set(self._elements) @property def _elements(self): """Returns all the elements of the permutation group as a list Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> p = PermutationGroup(Permutation(1, 3), Permutation(1, 2)) >>> p._elements [(3), (3)(1 2), (1 3), (2 3), (1 2 3), (1 3 2)] """ return list(islice(self.generate(), None)) def derived_series(self): r"""Return the derived series for the group. Explanation =========== The derived series for a group `G` is defined as `G = G_0 > G_1 > G_2 > \ldots` where `G_i = [G_{i-1}, G_{i-1}]`, i.e. `G_i` is the derived subgroup of `G_{i-1}`, for `i\in\mathbb{N}`. When we have `G_k = G_{k-1}` for some `k\in\mathbb{N}`, the series terminates. Returns ======= A list of permutation groups containing the members of the derived series in the order `G = G_0, G_1, G_2, \ldots`. Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup, DihedralGroup) >>> A = AlternatingGroup(5) >>> len(A.derived_series()) 1 >>> S = SymmetricGroup(4) >>> len(S.derived_series()) 4 >>> S.derived_series()[1].is_subgroup(AlternatingGroup(4)) True >>> S.derived_series()[2].is_subgroup(DihedralGroup(2)) True See Also ======== derived_subgroup """ res = [self] current = self nxt = self.derived_subgroup() while not current.is_subgroup(nxt): res.append(nxt) current = nxt nxt = nxt.derived_subgroup() return res def derived_subgroup(self): r"""Compute the derived subgroup. Explanation =========== The derived subgroup, or commutator subgroup is the subgroup generated by all commutators `[g, h] = hgh^{-1}g^{-1}` for `g, h\in G` ; it is equal to the normal closure of the set of commutators of the generators ([1], p.28, [11]). Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([1, 0, 2, 4, 3]) >>> b = Permutation([0, 1, 3, 2, 4]) >>> G = PermutationGroup([a, b]) >>> C = G.derived_subgroup() >>> list(C.generate(af=True)) [[0, 1, 2, 3, 4], [0, 1, 3, 4, 2], [0, 1, 4, 2, 3]] See Also ======== derived_series """ r = self._r gens = [p._array_form for p in self.generators] set_commutators = set() degree = self._degree rng = list(range(degree)) for i in range(r): for j in range(r): p1 = gens[i] p2 = gens[j] c = list(range(degree)) for k in rng: c[p2[p1[k]]] = p1[p2[k]] ct = tuple(c) if ct not in set_commutators: set_commutators.add(ct) cms = [_af_new(p) for p in set_commutators] G2 = self.normal_closure(cms) return G2 def generate(self, method="coset", af=False): """Return iterator to generate the elements of the group. Explanation =========== Iteration is done with one of these methods:: method='coset' using the Schreier-Sims coset representation method='dimino' using the Dimino method If ``af = True`` it yields the array form of the permutations Examples ======== >>> from sympy.combinatorics import PermutationGroup >>> from sympy.combinatorics.polyhedron import tetrahedron The permutation group given in the tetrahedron object is also true groups: >>> G = tetrahedron.pgroup >>> G.is_group True Also the group generated by the permutations in the tetrahedron pgroup -- even the first two -- is a proper group: >>> H = PermutationGroup(G[0], G[1]) >>> J = PermutationGroup(list(H.generate())); J PermutationGroup([ (0 1)(2 3), (1 2 3), (1 3 2), (0 3 1), (0 2 3), (0 3)(1 2), (0 1 3), (3)(0 2 1), (0 3 2), (3)(0 1 2), (0 2)(1 3)]) >>> _.is_group True """ if method == "coset": return self.generate_schreier_sims(af) elif method == "dimino": return self.generate_dimino(af) else: raise NotImplementedError('No generation defined for %s' % method) def generate_dimino(self, af=False): """Yield group elements using Dimino's algorithm. If ``af == True`` it yields the array form of the permutations. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([0, 2, 3, 1]) >>> g = PermutationGroup([a, b]) >>> list(g.generate_dimino(af=True)) [[0, 1, 2, 3], [0, 2, 1, 3], [0, 2, 3, 1], [0, 1, 3, 2], [0, 3, 2, 1], [0, 3, 1, 2]] References ========== .. [1] The Implementation of Various Algorithms for Permutation Groups in the Computer Algebra System: AXIOM, N.J. Doye, M.Sc. Thesis """ idn = list(range(self.degree)) order = 0 element_list = [idn] set_element_list = {tuple(idn)} if af: yield idn else: yield _af_new(idn) gens = [p._array_form for p in self.generators] for i in range(len(gens)): # D elements of the subgroup G_i generated by gens[:i] D = element_list[:] N = [idn] while N: A = N N = [] for a in A: for g in gens[:i + 1]: ag = _af_rmul(a, g) if tuple(ag) not in set_element_list: # produce G_i*g for d in D: order += 1 ap = _af_rmul(d, ag) if af: yield ap else: p = _af_new(ap) yield p element_list.append(ap) set_element_list.add(tuple(ap)) N.append(ap) self._order = len(element_list) def generate_schreier_sims(self, af=False): """Yield group elements using the Schreier-Sims representation in coset_rank order If ``af = True`` it yields the array form of the permutations Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([0, 2, 3, 1]) >>> g = PermutationGroup([a, b]) >>> list(g.generate_schreier_sims(af=True)) [[0, 1, 2, 3], [0, 2, 1, 3], [0, 3, 2, 1], [0, 1, 3, 2], [0, 2, 3, 1], [0, 3, 1, 2]] """ n = self._degree u = self.basic_transversals basic_orbits = self._basic_orbits if len(u) == 0: for x in self.generators: if af: yield x._array_form else: yield x return if len(u) == 1: for i in basic_orbits[0]: if af: yield u[0][i]._array_form else: yield u[0][i] return u = list(reversed(u)) basic_orbits = basic_orbits[::-1] # stg stack of group elements stg = [list(range(n))] posmax = [len(x) for x in u] n1 = len(posmax) - 1 pos = [0]*n1 h = 0 while 1: # backtrack when finished iterating over coset if pos[h] >= posmax[h]: if h == 0: return pos[h] = 0 h -= 1 stg.pop() continue p = _af_rmul(u[h][basic_orbits[h][pos[h]]]._array_form, stg[-1]) pos[h] += 1 stg.append(p) h += 1 if h == n1: if af: for i in basic_orbits[-1]: p = _af_rmul(u[-1][i]._array_form, stg[-1]) yield p else: for i in basic_orbits[-1]: p = _af_rmul(u[-1][i]._array_form, stg[-1]) p1 = _af_new(p) yield p1 stg.pop() h -= 1 @property def generators(self): """Returns the generators of the group. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.generators [(1 2), (2)(0 1)] """ return self._generators def contains(self, g, strict=True): """Test if permutation ``g`` belong to self, ``G``. Explanation =========== If ``g`` is an element of ``G`` it can be written as a product of factors drawn from the cosets of ``G``'s stabilizers. To see if ``g`` is one of the actual generators defining the group use ``G.has(g)``. If ``strict`` is not ``True``, ``g`` will be resized, if necessary, to match the size of permutations in ``self``. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation(1, 2) >>> b = Permutation(2, 3, 1) >>> G = PermutationGroup(a, b, degree=5) >>> G.contains(G[0]) # trivial check True >>> elem = Permutation([[2, 3]], size=5) >>> G.contains(elem) True >>> G.contains(Permutation(4)(0, 1, 2, 3)) False If strict is False, a permutation will be resized, if necessary: >>> H = PermutationGroup(Permutation(5)) >>> H.contains(Permutation(3)) False >>> H.contains(Permutation(3), strict=False) True To test if a given permutation is present in the group: >>> elem in G.generators False >>> G.has(elem) False See Also ======== coset_factor, sympy.core.basic.Basic.has, __contains__ """ if not isinstance(g, Permutation): return False if g.size != self.degree: if strict: return False g = Permutation(g, size=self.degree) if g in self.generators: return True return bool(self.coset_factor(g.array_form, True)) @property def is_perfect(self): """Return ``True`` if the group is perfect. A group is perfect if it equals to its derived subgroup. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation(1,2,3)(4,5) >>> b = Permutation(1,2,3,4,5) >>> G = PermutationGroup([a, b]) >>> G.is_perfect False """ if self._is_perfect is None: self._is_perfect = self.equals(self.derived_subgroup()) return self._is_perfect @property def is_abelian(self): """Test if the group is Abelian. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.is_abelian False >>> a = Permutation([0, 2, 1]) >>> G = PermutationGroup([a]) >>> G.is_abelian True """ if self._is_abelian is not None: return self._is_abelian self._is_abelian = True gens = [p._array_form for p in self.generators] for x in gens: for y in gens: if y <= x: continue if not _af_commutes_with(x, y): self._is_abelian = False return False return True def abelian_invariants(self): """ Returns the abelian invariants for the given group. Let ``G`` be a nontrivial finite abelian group. Then G is isomorphic to the direct product of finitely many nontrivial cyclic groups of prime-power order. Explanation =========== The prime-powers that occur as the orders of the factors are uniquely determined by G. More precisely, the primes that occur in the orders of the factors in any such decomposition of ``G`` are exactly the primes that divide ``|G|`` and for any such prime ``p``, if the orders of the factors that are p-groups in one such decomposition of ``G`` are ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``, then the orders of the factors that are p-groups in any such decomposition of ``G`` are ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``. The uniquely determined integers ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``, taken for all primes that divide ``|G|`` are called the invariants of the nontrivial group ``G`` as suggested in ([14], p. 542). Notes ===== We adopt the convention that the invariants of a trivial group are []. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.abelian_invariants() [2] >>> from sympy.combinatorics import CyclicGroup >>> G = CyclicGroup(7) >>> G.abelian_invariants() [7] """ if self.is_trivial: return [] gns = self.generators inv = [] G = self H = G.derived_subgroup() Hgens = H.generators for p in primefactors(G.order()): ranks = [] while True: pows = [] for g in gns: elm = g**p if not H.contains(elm): pows.append(elm) K = PermutationGroup(Hgens + pows) if pows else H r = G.order()//K.order() G = K gns = pows if r == 1: break ranks.append(multiplicity(p, r)) if ranks: pows = [1]*ranks[0] for i in ranks: for j in range(i): pows[j] = pows[j]*p inv.extend(pows) inv.sort() return inv def is_elementary(self, p): """Return ``True`` if the group is elementary abelian. An elementary abelian group is a finite abelian group, where every nontrivial element has order `p`, where `p` is a prime. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([0, 2, 1]) >>> G = PermutationGroup([a]) >>> G.is_elementary(2) True >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([3, 1, 2, 0]) >>> G = PermutationGroup([a, b]) >>> G.is_elementary(2) True >>> G.is_elementary(3) False """ return self.is_abelian and all(g.order() == p for g in self.generators) def _eval_is_alt_sym_naive(self, only_sym=False, only_alt=False): """A naive test using the group order.""" if only_sym and only_alt: raise ValueError( "Both {} and {} cannot be set to True" .format(only_sym, only_alt)) n = self.degree sym_order = _factorial(n) order = self.order() if order == sym_order: self._is_sym = True self._is_alt = False if only_alt: return False return True elif 2*order == sym_order: self._is_sym = False self._is_alt = True if only_sym: return False return True return False def _eval_is_alt_sym_monte_carlo(self, eps=0.05, perms=None): """A test using monte-carlo algorithm. Parameters ========== eps : float, optional The criterion for the incorrect ``False`` return. perms : list[Permutation], optional If explicitly given, it tests over the given candidats for testing. If ``None``, it randomly computes ``N_eps`` and chooses ``N_eps`` sample of the permutation from the group. See Also ======== _check_cycles_alt_sym """ if perms is None: n = self.degree if n < 17: c_n = 0.34 else: c_n = 0.57 d_n = (c_n*log(2))/log(n) N_eps = int(-log(eps)/d_n) perms = (self.random_pr() for i in range(N_eps)) return self._eval_is_alt_sym_monte_carlo(perms=perms) for perm in perms: if _check_cycles_alt_sym(perm): return True return False def is_alt_sym(self, eps=0.05, _random_prec=None): r"""Monte Carlo test for the symmetric/alternating group for degrees >= 8. Explanation =========== More specifically, it is one-sided Monte Carlo with the answer True (i.e., G is symmetric/alternating) guaranteed to be correct, and the answer False being incorrect with probability eps. For degree < 8, the order of the group is checked so the test is deterministic. Notes ===== The algorithm itself uses some nontrivial results from group theory and number theory: 1) If a transitive group ``G`` of degree ``n`` contains an element with a cycle of length ``n/2 < p < n-2`` for ``p`` a prime, ``G`` is the symmetric or alternating group ([1], pp. 81-82) 2) The proportion of elements in the symmetric/alternating group having the property described in 1) is approximately `\log(2)/\log(n)` ([1], p.82; [2], pp. 226-227). The helper function ``_check_cycles_alt_sym`` is used to go over the cycles in a permutation and look for ones satisfying 1). Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(10) >>> D.is_alt_sym() False See Also ======== _check_cycles_alt_sym """ if _random_prec is not None: N_eps = _random_prec['N_eps'] perms= (_random_prec[i] for i in range(N_eps)) return self._eval_is_alt_sym_monte_carlo(perms=perms) if self._is_sym or self._is_alt: return True if self._is_sym is False and self._is_alt is False: return False n = self.degree if n < 8: return self._eval_is_alt_sym_naive() elif self.is_transitive(): return self._eval_is_alt_sym_monte_carlo(eps=eps) self._is_sym, self._is_alt = False, False return False @property def is_nilpotent(self): """Test if the group is nilpotent. Explanation =========== A group `G` is nilpotent if it has a central series of finite length. Alternatively, `G` is nilpotent if its lower central series terminates with the trivial group. Every nilpotent group is also solvable ([1], p.29, [12]). Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup) >>> C = CyclicGroup(6) >>> C.is_nilpotent True >>> S = SymmetricGroup(5) >>> S.is_nilpotent False See Also ======== lower_central_series, is_solvable """ if self._is_nilpotent is None: lcs = self.lower_central_series() terminator = lcs[len(lcs) - 1] gens = terminator.generators degree = self.degree identity = _af_new(list(range(degree))) if all(g == identity for g in gens): self._is_solvable = True self._is_nilpotent = True return True else: self._is_nilpotent = False return False else: return self._is_nilpotent def is_normal(self, gr, strict=True): """Test if ``G=self`` is a normal subgroup of ``gr``. Explanation =========== G is normal in gr if for each g2 in G, g1 in gr, ``g = g1*g2*g1**-1`` belongs to G It is sufficient to check this for each g1 in gr.generators and g2 in G.generators. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([1, 2, 0]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G1 = PermutationGroup([a, Permutation([2, 0, 1])]) >>> G1.is_normal(G) True """ if not self.is_subgroup(gr, strict=strict): return False d_self = self.degree d_gr = gr.degree if self.is_trivial and (d_self == d_gr or not strict): return True if self._is_abelian: return True new_self = self.copy() if not strict and d_self != d_gr: if d_self < d_gr: new_self = PermGroup(new_self.generators + [Permutation(d_gr - 1)]) else: gr = PermGroup(gr.generators + [Permutation(d_self - 1)]) gens2 = [p._array_form for p in new_self.generators] gens1 = [p._array_form for p in gr.generators] for g1 in gens1: for g2 in gens2: p = _af_rmuln(g1, g2, _af_invert(g1)) if not new_self.coset_factor(p, True): return False return True def is_primitive(self, randomized=True): r"""Test if a group is primitive. Explanation =========== A permutation group ``G`` acting on a set ``S`` is called primitive if ``S`` contains no nontrivial block under the action of ``G`` (a block is nontrivial if its cardinality is more than ``1``). Notes ===== The algorithm is described in [1], p.83, and uses the function minimal_block to search for blocks of the form `\{0, k\}` for ``k`` ranging over representatives for the orbits of `G_0`, the stabilizer of ``0``. This algorithm has complexity `O(n^2)` where ``n`` is the degree of the group, and will perform badly if `G_0` is small. There are two implementations offered: one finds `G_0` deterministically using the function ``stabilizer``, and the other (default) produces random elements of `G_0` using ``random_stab``, hoping that they generate a subgroup of `G_0` with not too many more orbits than `G_0` (this is suggested in [1], p.83). Behavior is changed by the ``randomized`` flag. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(10) >>> D.is_primitive() False See Also ======== minimal_block, random_stab """ if self._is_primitive is not None: return self._is_primitive if self.is_transitive() is False: return False if randomized: random_stab_gens = [] v = self.schreier_vector(0) for _ in range(len(self)): random_stab_gens.append(self.random_stab(0, v)) stab = PermutationGroup(random_stab_gens) else: stab = self.stabilizer(0) orbits = stab.orbits() for orb in orbits: x = orb.pop() if x != 0 and any(e != 0 for e in self.minimal_block([0, x])): self._is_primitive = False return False self._is_primitive = True return True def minimal_blocks(self, randomized=True): ''' For a transitive group, return the list of all minimal block systems. If a group is intransitive, return `False`. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> from sympy.combinatorics.named_groups import DihedralGroup >>> DihedralGroup(6).minimal_blocks() [[0, 1, 0, 1, 0, 1], [0, 1, 2, 0, 1, 2]] >>> G = PermutationGroup(Permutation(1,2,5)) >>> G.minimal_blocks() False See Also ======== minimal_block, is_transitive, is_primitive ''' def _number_blocks(blocks): # number the blocks of a block system # in order and return the number of # blocks and the tuple with the # reordering n = len(blocks) appeared = {} m = 0 b = [None]*n for i in range(n): if blocks[i] not in appeared: appeared[blocks[i]] = m b[i] = m m += 1 else: b[i] = appeared[blocks[i]] return tuple(b), m if not self.is_transitive(): return False blocks = [] num_blocks = [] rep_blocks = [] if randomized: random_stab_gens = [] v = self.schreier_vector(0) for i in range(len(self)): random_stab_gens.append(self.random_stab(0, v)) stab = PermutationGroup(random_stab_gens) else: stab = self.stabilizer(0) orbits = stab.orbits() for orb in orbits: x = orb.pop() if x != 0: block = self.minimal_block([0, x]) num_block, _ = _number_blocks(block) # a representative block (containing 0) rep = {j for j in range(self.degree) if num_block[j] == 0} # check if the system is minimal with # respect to the already discovere ones minimal = True blocks_remove_mask = [False] * len(blocks) for i, r in enumerate(rep_blocks): if len(r) > len(rep) and rep.issubset(r): # i-th block system is not minimal blocks_remove_mask[i] = True elif len(r) < len(rep) and r.issubset(rep): # the system being checked is not minimal minimal = False break # remove non-minimal representative blocks blocks = [b for i, b in enumerate(blocks) if not blocks_remove_mask[i]] num_blocks = [n for i, n in enumerate(num_blocks) if not blocks_remove_mask[i]] rep_blocks = [r for i, r in enumerate(rep_blocks) if not blocks_remove_mask[i]] if minimal and num_block not in num_blocks: blocks.append(block) num_blocks.append(num_block) rep_blocks.append(rep) return blocks @property def is_solvable(self): """Test if the group is solvable. ``G`` is solvable if its derived series terminates with the trivial group ([1], p.29). Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(3) >>> S.is_solvable True See Also ======== is_nilpotent, derived_series """ if self._is_solvable is None: if self.order() % 2 != 0: return True ds = self.derived_series() terminator = ds[len(ds) - 1] gens = terminator.generators degree = self.degree identity = _af_new(list(range(degree))) if all(g == identity for g in gens): self._is_solvable = True return True else: self._is_solvable = False return False else: return self._is_solvable def is_subgroup(self, G, strict=True): """Return ``True`` if all elements of ``self`` belong to ``G``. If ``strict`` is ``False`` then if ``self``'s degree is smaller than ``G``'s, the elements will be resized to have the same degree. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> from sympy.combinatorics import SymmetricGroup, CyclicGroup Testing is strict by default: the degree of each group must be the same: >>> p = Permutation(0, 1, 2, 3, 4, 5) >>> G1 = PermutationGroup([Permutation(0, 1, 2), Permutation(0, 1)]) >>> G2 = PermutationGroup([Permutation(0, 2), Permutation(0, 1, 2)]) >>> G3 = PermutationGroup([p, p**2]) >>> assert G1.order() == G2.order() == G3.order() == 6 >>> G1.is_subgroup(G2) True >>> G1.is_subgroup(G3) False >>> G3.is_subgroup(PermutationGroup(G3[1])) False >>> G3.is_subgroup(PermutationGroup(G3[0])) True To ignore the size, set ``strict`` to ``False``: >>> S3 = SymmetricGroup(3) >>> S5 = SymmetricGroup(5) >>> S3.is_subgroup(S5, strict=False) True >>> C7 = CyclicGroup(7) >>> G = S5*C7 >>> S5.is_subgroup(G, False) True >>> C7.is_subgroup(G, 0) False """ if isinstance(G, SymmetricPermutationGroup): if self.degree != G.degree: return False return True if not isinstance(G, PermutationGroup): return False if self == G or self.generators[0]==Permutation(): return True if G.order() % self.order() != 0: return False if self.degree == G.degree or \ (self.degree < G.degree and not strict): gens = self.generators else: return False return all(G.contains(g, strict=strict) for g in gens) @property def is_polycyclic(self): """Return ``True`` if a group is polycyclic. A group is polycyclic if it has a subnormal series with cyclic factors. For finite groups, this is the same as if the group is solvable. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([2, 0, 1, 3]) >>> G = PermutationGroup([a, b]) >>> G.is_polycyclic True """ return self.is_solvable def is_transitive(self, strict=True): """Test if the group is transitive. Explanation =========== A group is transitive if it has a single orbit. If ``strict`` is ``False`` the group is transitive if it has a single orbit of length different from 1. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([2, 0, 1, 3]) >>> G1 = PermutationGroup([a, b]) >>> G1.is_transitive() False >>> G1.is_transitive(strict=False) True >>> c = Permutation([2, 3, 0, 1]) >>> G2 = PermutationGroup([a, c]) >>> G2.is_transitive() True >>> d = Permutation([1, 0, 2, 3]) >>> e = Permutation([0, 1, 3, 2]) >>> G3 = PermutationGroup([d, e]) >>> G3.is_transitive() or G3.is_transitive(strict=False) False """ if self._is_transitive: # strict or not, if True then True return self._is_transitive if strict: if self._is_transitive is not None: # we only store strict=True return self._is_transitive ans = len(self.orbit(0)) == self.degree self._is_transitive = ans return ans got_orb = False for x in self.orbits(): if len(x) > 1: if got_orb: return False got_orb = True return got_orb @property def is_trivial(self): """Test if the group is the trivial group. This is true if the group contains only the identity permutation. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> G = PermutationGroup([Permutation([0, 1, 2])]) >>> G.is_trivial True """ if self._is_trivial is None: self._is_trivial = len(self) == 1 and self[0].is_Identity return self._is_trivial def lower_central_series(self): r"""Return the lower central series for the group. The lower central series for a group `G` is the series `G = G_0 > G_1 > G_2 > \ldots` where `G_k = [G, G_{k-1}]`, i.e. every term after the first is equal to the commutator of `G` and the previous term in `G1` ([1], p.29). Returns ======= A list of permutation groups in the order `G = G_0, G_1, G_2, \ldots` Examples ======== >>> from sympy.combinatorics.named_groups import (AlternatingGroup, ... DihedralGroup) >>> A = AlternatingGroup(4) >>> len(A.lower_central_series()) 2 >>> A.lower_central_series()[1].is_subgroup(DihedralGroup(2)) True See Also ======== commutator, derived_series """ res = [self] current = self nxt = self.commutator(self, current) while not current.is_subgroup(nxt): res.append(nxt) current = nxt nxt = self.commutator(self, current) return res @property def max_div(self): """Maximum proper divisor of the degree of a permutation group. Explanation =========== Obviously, this is the degree divided by its minimal proper divisor (larger than ``1``, if one exists). As it is guaranteed to be prime, the ``sieve`` from ``sympy.ntheory`` is used. This function is also used as an optimization tool for the functions ``minimal_block`` and ``_union_find_merge``. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> G = PermutationGroup([Permutation([0, 2, 1, 3])]) >>> G.max_div 2 See Also ======== minimal_block, _union_find_merge """ if self._max_div is not None: return self._max_div n = self.degree if n == 1: return 1 for x in sieve: if n % x == 0: d = n//x self._max_div = d return d def minimal_block(self, points): r"""For a transitive group, finds the block system generated by ``points``. Explanation =========== If a group ``G`` acts on a set ``S``, a nonempty subset ``B`` of ``S`` is called a block under the action of ``G`` if for all ``g`` in ``G`` we have ``gB = B`` (``g`` fixes ``B``) or ``gB`` and ``B`` have no common points (``g`` moves ``B`` entirely). ([1], p.23; [6]). The distinct translates ``gB`` of a block ``B`` for ``g`` in ``G`` partition the set ``S`` and this set of translates is known as a block system. Moreover, we obviously have that all blocks in the partition have the same size, hence the block size divides ``|S|`` ([1], p.23). A ``G``-congruence is an equivalence relation ``~`` on the set ``S`` such that ``a ~ b`` implies ``g(a) ~ g(b)`` for all ``g`` in ``G``. For a transitive group, the equivalence classes of a ``G``-congruence and the blocks of a block system are the same thing ([1], p.23). The algorithm below checks the group for transitivity, and then finds the ``G``-congruence generated by the pairs ``(p_0, p_1), (p_0, p_2), ..., (p_0,p_{k-1})`` which is the same as finding the maximal block system (i.e., the one with minimum block size) such that ``p_0, ..., p_{k-1}`` are in the same block ([1], p.83). It is an implementation of Atkinson's algorithm, as suggested in [1], and manipulates an equivalence relation on the set ``S`` using a union-find data structure. The running time is just above `O(|points||S|)`. ([1], pp. 83-87; [7]). Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(10) >>> D.minimal_block([0, 5]) [0, 1, 2, 3, 4, 0, 1, 2, 3, 4] >>> D.minimal_block([0, 1]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] See Also ======== _union_find_rep, _union_find_merge, is_transitive, is_primitive """ if not self.is_transitive(): return False n = self.degree gens = self.generators # initialize the list of equivalence class representatives parents = list(range(n)) ranks = [1]*n not_rep = [] k = len(points) # the block size must divide the degree of the group if k > self.max_div: return [0]*n for i in range(k - 1): parents[points[i + 1]] = points[0] not_rep.append(points[i + 1]) ranks[points[0]] = k i = 0 len_not_rep = k - 1 while i < len_not_rep: gamma = not_rep[i] i += 1 for gen in gens: # find has side effects: performs path compression on the list # of representatives delta = self._union_find_rep(gamma, parents) # union has side effects: performs union by rank on the list # of representatives temp = self._union_find_merge(gen(gamma), gen(delta), ranks, parents, not_rep) if temp == -1: return [0]*n len_not_rep += temp for i in range(n): # force path compression to get the final state of the equivalence # relation self._union_find_rep(i, parents) # rewrite result so that block representatives are minimal new_reps = {} return [new_reps.setdefault(r, i) for i, r in enumerate(parents)] def conjugacy_class(self, x): r"""Return the conjugacy class of an element in the group. Explanation =========== The conjugacy class of an element ``g`` in a group ``G`` is the set of elements ``x`` in ``G`` that are conjugate with ``g``, i.e. for which ``g = xax^{-1}`` for some ``a`` in ``G``. Note that conjugacy is an equivalence relation, and therefore that conjugacy classes are partitions of ``G``. For a list of all the conjugacy classes of the group, use the conjugacy_classes() method. In a permutation group, each conjugacy class corresponds to a particular `cycle structure': for example, in ``S_3``, the conjugacy classes are: * the identity class, ``{()}`` * all transpositions, ``{(1 2), (1 3), (2 3)}`` * all 3-cycles, ``{(1 2 3), (1 3 2)}`` Examples ======== >>> from sympy.combinatorics import Permutation, SymmetricGroup >>> S3 = SymmetricGroup(3) >>> S3.conjugacy_class(Permutation(0, 1, 2)) {(0 1 2), (0 2 1)} Notes ===== This procedure computes the conjugacy class directly by finding the orbit of the element under conjugation in G. This algorithm is only feasible for permutation groups of relatively small order, but is like the orbit() function itself in that respect. """ # Ref: "Computing the conjugacy classes of finite groups"; Butler, G. # Groups '93 Galway/St Andrews; edited by Campbell, C. M. new_class = {x} last_iteration = new_class while len(last_iteration) > 0: this_iteration = set() for y in last_iteration: for s in self.generators: conjugated = s * y * (~s) if conjugated not in new_class: this_iteration.add(conjugated) new_class.update(last_iteration) last_iteration = this_iteration return new_class def conjugacy_classes(self): r"""Return the conjugacy classes of the group. Explanation =========== As described in the documentation for the .conjugacy_class() function, conjugacy is an equivalence relation on a group G which partitions the set of elements. This method returns a list of all these conjugacy classes of G. Examples ======== >>> from sympy.combinatorics import SymmetricGroup >>> SymmetricGroup(3).conjugacy_classes() [{(2)}, {(0 1 2), (0 2 1)}, {(0 2), (1 2), (2)(0 1)}] """ identity = _af_new(list(range(self.degree))) known_elements = {identity} classes = [known_elements.copy()] for x in self.generate(): if x not in known_elements: new_class = self.conjugacy_class(x) classes.append(new_class) known_elements.update(new_class) return classes def normal_closure(self, other, k=10): r"""Return the normal closure of a subgroup/set of permutations. Explanation =========== If ``S`` is a subset of a group ``G``, the normal closure of ``A`` in ``G`` is defined as the intersection of all normal subgroups of ``G`` that contain ``A`` ([1], p.14). Alternatively, it is the group generated by the conjugates ``x^{-1}yx`` for ``x`` a generator of ``G`` and ``y`` a generator of the subgroup ``\left\langle S\right\rangle`` generated by ``S`` (for some chosen generating set for ``\left\langle S\right\rangle``) ([1], p.73). Parameters ========== other a subgroup/list of permutations/single permutation k an implementation-specific parameter that determines the number of conjugates that are adjoined to ``other`` at once Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup, AlternatingGroup) >>> S = SymmetricGroup(5) >>> C = CyclicGroup(5) >>> G = S.normal_closure(C) >>> G.order() 60 >>> G.is_subgroup(AlternatingGroup(5)) True See Also ======== commutator, derived_subgroup, random_pr Notes ===== The algorithm is described in [1], pp. 73-74; it makes use of the generation of random elements for permutation groups by the product replacement algorithm. """ if hasattr(other, 'generators'): degree = self.degree identity = _af_new(list(range(degree))) if all(g == identity for g in other.generators): return other Z = PermutationGroup(other.generators[:]) base, strong_gens = Z.schreier_sims_incremental() strong_gens_distr = _distribute_gens_by_base(base, strong_gens) basic_orbits, basic_transversals = \ _orbits_transversals_from_bsgs(base, strong_gens_distr) self._random_pr_init(r=10, n=20) _loop = True while _loop: Z._random_pr_init(r=10, n=10) for _ in range(k): g = self.random_pr() h = Z.random_pr() conj = h^g res = _strip(conj, base, basic_orbits, basic_transversals) if res[0] != identity or res[1] != len(base) + 1: gens = Z.generators gens.append(conj) Z = PermutationGroup(gens) strong_gens.append(conj) temp_base, temp_strong_gens = \ Z.schreier_sims_incremental(base, strong_gens) base, strong_gens = temp_base, temp_strong_gens strong_gens_distr = \ _distribute_gens_by_base(base, strong_gens) basic_orbits, basic_transversals = \ _orbits_transversals_from_bsgs(base, strong_gens_distr) _loop = False for g in self.generators: for h in Z.generators: conj = h^g res = _strip(conj, base, basic_orbits, basic_transversals) if res[0] != identity or res[1] != len(base) + 1: _loop = True break if _loop: break return Z elif hasattr(other, '__getitem__'): return self.normal_closure(PermutationGroup(other)) elif hasattr(other, 'array_form'): return self.normal_closure(PermutationGroup([other])) def orbit(self, alpha, action='tuples'): r"""Compute the orbit of alpha `\{g(\alpha) | g \in G\}` as a set. Explanation =========== The time complexity of the algorithm used here is `O(|Orb|*r)` where `|Orb|` is the size of the orbit and ``r`` is the number of generators of the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21. Here alpha can be a single point, or a list of points. If alpha is a single point, the ordinary orbit is computed. if alpha is a list of points, there are three available options: 'union' - computes the union of the orbits of the points in the list 'tuples' - computes the orbit of the list interpreted as an ordered tuple under the group action ( i.e., g((1,2,3)) = (g(1), g(2), g(3)) ) 'sets' - computes the orbit of the list interpreted as a sets Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([1, 2, 0, 4, 5, 6, 3]) >>> G = PermutationGroup([a]) >>> G.orbit(0) {0, 1, 2} >>> G.orbit([0, 4], 'union') {0, 1, 2, 3, 4, 5, 6} See Also ======== orbit_transversal """ return _orbit(self.degree, self.generators, alpha, action) def orbit_rep(self, alpha, beta, schreier_vector=None): """Return a group element which sends ``alpha`` to ``beta``. Explanation =========== If ``beta`` is not in the orbit of ``alpha``, the function returns ``False``. This implementation makes use of the schreier vector. For a proof of correctness, see [1], p.80 Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> G = AlternatingGroup(5) >>> G.orbit_rep(0, 4) (0 4 1 2 3) See Also ======== schreier_vector """ if schreier_vector is None: schreier_vector = self.schreier_vector(alpha) if schreier_vector[beta] is None: return False k = schreier_vector[beta] gens = [x._array_form for x in self.generators] a = [] while k != -1: a.append(gens[k]) beta = gens[k].index(beta) # beta = (~gens[k])(beta) k = schreier_vector[beta] if a: return _af_new(_af_rmuln(*a)) else: return _af_new(list(range(self._degree))) def orbit_transversal(self, alpha, pairs=False): r"""Computes a transversal for the orbit of ``alpha`` as a set. Explanation =========== For a permutation group `G`, a transversal for the orbit `Orb = \{g(\alpha) | g \in G\}` is a set `\{g_\beta | g_\beta(\alpha) = \beta\}` for `\beta \in Orb`. Note that there may be more than one possible transversal. If ``pairs`` is set to ``True``, it returns the list of pairs `(\beta, g_\beta)`. For a proof of correctness, see [1], p.79 Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> G = DihedralGroup(6) >>> G.orbit_transversal(0) [(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)] See Also ======== orbit """ return _orbit_transversal(self._degree, self.generators, alpha, pairs) def orbits(self, rep=False): """Return the orbits of ``self``, ordered according to lowest element in each orbit. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation(1, 5)(2, 3)(4, 0, 6) >>> b = Permutation(1, 5)(3, 4)(2, 6, 0) >>> G = PermutationGroup([a, b]) >>> G.orbits() [{0, 2, 3, 4, 6}, {1, 5}] """ return _orbits(self._degree, self._generators) def order(self): """Return the order of the group: the number of permutations that can be generated from elements of the group. The number of permutations comprising the group is given by ``len(group)``; the length of each permutation in the group is given by ``group.size``. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([1, 0, 2]) >>> G = PermutationGroup([a]) >>> G.degree 3 >>> len(G) 1 >>> G.order() 2 >>> list(G.generate()) [(2), (2)(0 1)] >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.order() 6 See Also ======== degree """ if self._order is not None: return self._order if self._is_sym: n = self._degree self._order = factorial(n) return self._order if self._is_alt: n = self._degree self._order = factorial(n)/2 return self._order m = prod([len(x) for x in self.basic_transversals]) self._order = m return m def index(self, H): """ Returns the index of a permutation group. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation(1,2,3) >>> b =Permutation(3) >>> G = PermutationGroup([a]) >>> H = PermutationGroup([b]) >>> G.index(H) 3 """ if H.is_subgroup(self): return self.order()//H.order() @property def is_symmetric(self): """Return ``True`` if the group is symmetric. Examples ======== >>> from sympy.combinatorics import SymmetricGroup >>> g = SymmetricGroup(5) >>> g.is_symmetric True >>> from sympy.combinatorics import Permutation, PermutationGroup >>> g = PermutationGroup( ... Permutation(0, 1, 2, 3, 4), ... Permutation(2, 3)) >>> g.is_symmetric True Notes ===== This uses a naive test involving the computation of the full group order. If you need more quicker taxonomy for large groups, you can use :meth:`PermutationGroup.is_alt_sym`. However, :meth:`PermutationGroup.is_alt_sym` may not be accurate and is not able to distinguish between an alternating group and a symmetric group. See Also ======== is_alt_sym """ _is_sym = self._is_sym if _is_sym is not None: return _is_sym n = self.degree if n >= 8: if self.is_transitive(): _is_alt_sym = self._eval_is_alt_sym_monte_carlo() if _is_alt_sym: if any(g.is_odd for g in self.generators): self._is_sym, self._is_alt = True, False return True self._is_sym, self._is_alt = False, True return False return self._eval_is_alt_sym_naive(only_sym=True) self._is_sym, self._is_alt = False, False return False return self._eval_is_alt_sym_naive(only_sym=True) @property def is_alternating(self): """Return ``True`` if the group is alternating. Examples ======== >>> from sympy.combinatorics import AlternatingGroup >>> g = AlternatingGroup(5) >>> g.is_alternating True >>> from sympy.combinatorics import Permutation, PermutationGroup >>> g = PermutationGroup( ... Permutation(0, 1, 2, 3, 4), ... Permutation(2, 3, 4)) >>> g.is_alternating True Notes ===== This uses a naive test involving the computation of the full group order. If you need more quicker taxonomy for large groups, you can use :meth:`PermutationGroup.is_alt_sym`. However, :meth:`PermutationGroup.is_alt_sym` may not be accurate and is not able to distinguish between an alternating group and a symmetric group. See Also ======== is_alt_sym """ _is_alt = self._is_alt if _is_alt is not None: return _is_alt n = self.degree if n >= 8: if self.is_transitive(): _is_alt_sym = self._eval_is_alt_sym_monte_carlo() if _is_alt_sym: if all(g.is_even for g in self.generators): self._is_sym, self._is_alt = False, True return True self._is_sym, self._is_alt = True, False return False return self._eval_is_alt_sym_naive(only_alt=True) self._is_sym, self._is_alt = False, False return False return self._eval_is_alt_sym_naive(only_alt=True) @classmethod def _distinct_primes_lemma(cls, primes): """Subroutine to test if there is only one cyclic group for the order.""" primes = sorted(primes) l = len(primes) for i in range(l): for j in range(i+1, l): if primes[j] % primes[i] == 1: return None return True @property def is_cyclic(self): r""" Return ``True`` if the group is Cyclic. Examples ======== >>> from sympy.combinatorics.named_groups import AbelianGroup >>> G = AbelianGroup(3, 4) >>> G.is_cyclic True >>> G = AbelianGroup(4, 4) >>> G.is_cyclic False Notes ===== If the order of a group $n$ can be factored into the distinct primes $p_1, p_2, \dots , p_s$ and if .. math:: \forall i, j \in \{1, 2, \dots, s \}: p_i \not \equiv 1 \pmod {p_j} holds true, there is only one group of the order $n$ which is a cyclic group [1]_. This is a generalization of the lemma that the group of order $15, 35, \dots$ are cyclic. And also, these additional lemmas can be used to test if a group is cyclic if the order of the group is already found. - If the group is abelian and the order of the group is square-free, the group is cyclic. - If the order of the group is less than $6$ and is not $4$, the group is cyclic. - If the order of the group is prime, the group is cyclic. References ========== .. [1] 1978: John S. Rose: A Course on Group Theory, Introduction to Finite Group Theory: 1.4 """ if self._is_cyclic is not None: return self._is_cyclic if len(self.generators) == 1: self._is_cyclic = True self._is_abelian = True return True if self._is_abelian is False: self._is_cyclic = False return False order = self.order() if order < 6: self._is_abelian = True if order != 4: self._is_cyclic = True return True factors = factorint(order) if all(v == 1 for v in factors.values()): if self._is_abelian: self._is_cyclic = True return True primes = list(factors.keys()) if PermutationGroup._distinct_primes_lemma(primes) is True: self._is_cyclic = True self._is_abelian = True return True for p in factors: pgens = [] for g in self.generators: pgens.append(g**p) if self.index(self.subgroup(pgens)) != p: self._is_cyclic = False return False self._is_cyclic = True self._is_abelian = True return True def pointwise_stabilizer(self, points, incremental=True): r"""Return the pointwise stabilizer for a set of points. Explanation =========== For a permutation group `G` and a set of points `\{p_1, p_2,\ldots, p_k\}`, the pointwise stabilizer of `p_1, p_2, \ldots, p_k` is defined as `G_{p_1,\ldots, p_k} = \{g\in G | g(p_i) = p_i \forall i\in\{1, 2,\ldots,k\}\}` ([1],p20). It is a subgroup of `G`. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(7) >>> Stab = S.pointwise_stabilizer([2, 3, 5]) >>> Stab.is_subgroup(S.stabilizer(2).stabilizer(3).stabilizer(5)) True See Also ======== stabilizer, schreier_sims_incremental Notes ===== When incremental == True, rather than the obvious implementation using successive calls to ``.stabilizer()``, this uses the incremental Schreier-Sims algorithm to obtain a base with starting segment - the given points. """ if incremental: base, strong_gens = self.schreier_sims_incremental(base=points) stab_gens = [] degree = self.degree for gen in strong_gens: if [gen(point) for point in points] == points: stab_gens.append(gen) if not stab_gens: stab_gens = _af_new(list(range(degree))) return PermutationGroup(stab_gens) else: gens = self._generators degree = self.degree for x in points: gens = _stabilizer(degree, gens, x) return PermutationGroup(gens) def make_perm(self, n, seed=None): """ Multiply ``n`` randomly selected permutations from pgroup together, starting with the identity permutation. If ``n`` is a list of integers, those integers will be used to select the permutations and they will be applied in L to R order: make_perm((A, B, C)) will give CBA(I) where I is the identity permutation. ``seed`` is used to set the seed for the random selection of permutations from pgroup. If this is a list of integers, the corresponding permutations from pgroup will be selected in the order give. This is mainly used for testing purposes. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a, b = [Permutation([1, 0, 3, 2]), Permutation([1, 3, 0, 2])] >>> G = PermutationGroup([a, b]) >>> G.make_perm(1, [0]) (0 1)(2 3) >>> G.make_perm(3, [0, 1, 0]) (0 2 3 1) >>> G.make_perm([0, 1, 0]) (0 2 3 1) See Also ======== random """ if is_sequence(n): if seed is not None: raise ValueError('If n is a sequence, seed should be None') n, seed = len(n), n else: try: n = int(n) except TypeError: raise ValueError('n must be an integer or a sequence.') randomrange = _randrange(seed) # start with the identity permutation result = Permutation(list(range(self.degree))) m = len(self) for _ in range(n): p = self[randomrange(m)] result = rmul(result, p) return result def random(self, af=False): """Return a random group element """ rank = randrange(self.order()) return self.coset_unrank(rank, af) def random_pr(self, gen_count=11, iterations=50, _random_prec=None): """Return a random group element using product replacement. Explanation =========== For the details of the product replacement algorithm, see ``_random_pr_init`` In ``random_pr`` the actual 'product replacement' is performed. Notice that if the attribute ``_random_gens`` is empty, it needs to be initialized by ``_random_pr_init``. See Also ======== _random_pr_init """ if self._random_gens == []: self._random_pr_init(gen_count, iterations) random_gens = self._random_gens r = len(random_gens) - 1 # handle randomized input for testing purposes if _random_prec is None: s = randrange(r) t = randrange(r - 1) if t == s: t = r - 1 x = choice([1, 2]) e = choice([-1, 1]) else: s = _random_prec['s'] t = _random_prec['t'] if t == s: t = r - 1 x = _random_prec['x'] e = _random_prec['e'] if x == 1: random_gens[s] = _af_rmul(random_gens[s], _af_pow(random_gens[t], e)) random_gens[r] = _af_rmul(random_gens[r], random_gens[s]) else: random_gens[s] = _af_rmul(_af_pow(random_gens[t], e), random_gens[s]) random_gens[r] = _af_rmul(random_gens[s], random_gens[r]) return _af_new(random_gens[r]) def random_stab(self, alpha, schreier_vector=None, _random_prec=None): """Random element from the stabilizer of ``alpha``. The schreier vector for ``alpha`` is an optional argument used for speeding up repeated calls. The algorithm is described in [1], p.81 See Also ======== random_pr, orbit_rep """ if schreier_vector is None: schreier_vector = self.schreier_vector(alpha) if _random_prec is None: rand = self.random_pr() else: rand = _random_prec['rand'] beta = rand(alpha) h = self.orbit_rep(alpha, beta, schreier_vector) return rmul(~h, rand) def schreier_sims(self): """Schreier-Sims algorithm. Explanation =========== It computes the generators of the chain of stabilizers `G > G_{b_1} > .. > G_{b1,..,b_r} > 1` in which `G_{b_1,..,b_i}` stabilizes `b_1,..,b_i`, and the corresponding ``s`` cosets. An element of the group can be written as the product `h_1*..*h_s`. We use the incremental Schreier-Sims algorithm. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.schreier_sims() >>> G.basic_transversals [{0: (2)(0 1), 1: (2), 2: (1 2)}, {0: (2), 2: (0 2)}] """ if self._transversals: return self._schreier_sims() return def _schreier_sims(self, base=None): schreier = self.schreier_sims_incremental(base=base, slp_dict=True) base, strong_gens = schreier[:2] self._base = base self._strong_gens = strong_gens self._strong_gens_slp = schreier[2] if not base: self._transversals = [] self._basic_orbits = [] return strong_gens_distr = _distribute_gens_by_base(base, strong_gens) basic_orbits, transversals, slps = _orbits_transversals_from_bsgs(base,\ strong_gens_distr, slp=True) # rewrite the indices stored in slps in terms of strong_gens for i, slp in enumerate(slps): gens = strong_gens_distr[i] for k in slp: slp[k] = [strong_gens.index(gens[s]) for s in slp[k]] self._transversals = transversals self._basic_orbits = [sorted(x) for x in basic_orbits] self._transversal_slp = slps def schreier_sims_incremental(self, base=None, gens=None, slp_dict=False): """Extend a sequence of points and generating set to a base and strong generating set. Parameters ========== base The sequence of points to be extended to a base. Optional parameter with default value ``[]``. gens The generating set to be extended to a strong generating set relative to the base obtained. Optional parameter with default value ``self.generators``. slp_dict If `True`, return a dictionary `{g: gens}` for each strong generator `g` where `gens` is a list of strong generators coming before `g` in `strong_gens`, such that the product of the elements of `gens` is equal to `g`. Returns ======= (base, strong_gens) ``base`` is the base obtained, and ``strong_gens`` is the strong generating set relative to it. The original parameters ``base``, ``gens`` remain unchanged. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> A = AlternatingGroup(7) >>> base = [2, 3] >>> seq = [2, 3] >>> base, strong_gens = A.schreier_sims_incremental(base=seq) >>> _verify_bsgs(A, base, strong_gens) True >>> base[:2] [2, 3] Notes ===== This version of the Schreier-Sims algorithm runs in polynomial time. There are certain assumptions in the implementation - if the trivial group is provided, ``base`` and ``gens`` are returned immediately, as any sequence of points is a base for the trivial group. If the identity is present in the generators ``gens``, it is removed as it is a redundant generator. The implementation is described in [1], pp. 90-93. See Also ======== schreier_sims, schreier_sims_random """ if base is None: base = [] if gens is None: gens = self.generators[:] degree = self.degree id_af = list(range(degree)) # handle the trivial group if len(gens) == 1 and gens[0].is_Identity: if slp_dict: return base, gens, {gens[0]: [gens[0]]} return base, gens # prevent side effects _base, _gens = base[:], gens[:] # remove the identity as a generator _gens = [x for x in _gens if not x.is_Identity] # make sure no generator fixes all base points for gen in _gens: if all(x == gen._array_form[x] for x in _base): for new in id_af: if gen._array_form[new] != new: break else: assert None # can this ever happen? _base.append(new) # distribute generators according to basic stabilizers strong_gens_distr = _distribute_gens_by_base(_base, _gens) strong_gens_slp = [] # initialize the basic stabilizers, basic orbits and basic transversals orbs = {} transversals = {} slps = {} base_len = len(_base) for i in range(base_len): transversals[i], slps[i] = _orbit_transversal(degree, strong_gens_distr[i], _base[i], pairs=True, af=True, slp=True) transversals[i] = dict(transversals[i]) orbs[i] = list(transversals[i].keys()) # main loop: amend the stabilizer chain until we have generators # for all stabilizers i = base_len - 1 while i >= 0: # this flag is used to continue with the main loop from inside # a nested loop continue_i = False # test the generators for being a strong generating set db = {} for beta, u_beta in list(transversals[i].items()): for j, gen in enumerate(strong_gens_distr[i]): gb = gen._array_form[beta] u1 = transversals[i][gb] g1 = _af_rmul(gen._array_form, u_beta) slp = [(i, g) for g in slps[i][beta]] slp = [(i, j)] + slp if g1 != u1: # test if the schreier generator is in the i+1-th # would-be basic stabilizer y = True try: u1_inv = db[gb] except KeyError: u1_inv = db[gb] = _af_invert(u1) schreier_gen = _af_rmul(u1_inv, g1) u1_inv_slp = slps[i][gb][:] u1_inv_slp.reverse() u1_inv_slp = [(i, (g,)) for g in u1_inv_slp] slp = u1_inv_slp + slp h, j, slp = _strip_af(schreier_gen, _base, orbs, transversals, i, slp=slp, slps=slps) if j <= base_len: # new strong generator h at level j y = False elif h: # h fixes all base points y = False moved = 0 while h[moved] == moved: moved += 1 _base.append(moved) base_len += 1 strong_gens_distr.append([]) if y is False: # if a new strong generator is found, update the # data structures and start over h = _af_new(h) strong_gens_slp.append((h, slp)) for l in range(i + 1, j): strong_gens_distr[l].append(h) transversals[l], slps[l] =\ _orbit_transversal(degree, strong_gens_distr[l], _base[l], pairs=True, af=True, slp=True) transversals[l] = dict(transversals[l]) orbs[l] = list(transversals[l].keys()) i = j - 1 # continue main loop using the flag continue_i = True if continue_i is True: break if continue_i is True: break if continue_i is True: continue i -= 1 strong_gens = _gens[:] if slp_dict: # create the list of the strong generators strong_gens and # rewrite the indices of strong_gens_slp in terms of the # elements of strong_gens for k, slp in strong_gens_slp: strong_gens.append(k) for i in range(len(slp)): s = slp[i] if isinstance(s[1], tuple): slp[i] = strong_gens_distr[s[0]][s[1][0]]**-1 else: slp[i] = strong_gens_distr[s[0]][s[1]] strong_gens_slp = dict(strong_gens_slp) # add the original generators for g in _gens: strong_gens_slp[g] = [g] return (_base, strong_gens, strong_gens_slp) strong_gens.extend([k for k, _ in strong_gens_slp]) return _base, strong_gens def schreier_sims_random(self, base=None, gens=None, consec_succ=10, _random_prec=None): r"""Randomized Schreier-Sims algorithm. Explanation =========== The randomized Schreier-Sims algorithm takes the sequence ``base`` and the generating set ``gens``, and extends ``base`` to a base, and ``gens`` to a strong generating set relative to that base with probability of a wrong answer at most `2^{-consec\_succ}`, provided the random generators are sufficiently random. Parameters ========== base The sequence to be extended to a base. gens The generating set to be extended to a strong generating set. consec_succ The parameter defining the probability of a wrong answer. _random_prec An internal parameter used for testing purposes. Returns ======= (base, strong_gens) ``base`` is the base and ``strong_gens`` is the strong generating set relative to it. Examples ======== >>> from sympy.combinatorics.testutil import _verify_bsgs >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(5) >>> base, strong_gens = S.schreier_sims_random(consec_succ=5) >>> _verify_bsgs(S, base, strong_gens) #doctest: +SKIP True Notes ===== The algorithm is described in detail in [1], pp. 97-98. It extends the orbits ``orbs`` and the permutation groups ``stabs`` to basic orbits and basic stabilizers for the base and strong generating set produced in the end. The idea of the extension process is to "sift" random group elements through the stabilizer chain and amend the stabilizers/orbits along the way when a sift is not successful. The helper function ``_strip`` is used to attempt to decompose a random group element according to the current state of the stabilizer chain and report whether the element was fully decomposed (successful sift) or not (unsuccessful sift). In the latter case, the level at which the sift failed is reported and used to amend ``stabs``, ``base``, ``gens`` and ``orbs`` accordingly. The halting condition is for ``consec_succ`` consecutive successful sifts to pass. This makes sure that the current ``base`` and ``gens`` form a BSGS with probability at least `1 - 1/\text{consec\_succ}`. See Also ======== schreier_sims """ if base is None: base = [] if gens is None: gens = self.generators base_len = len(base) n = self.degree # make sure no generator fixes all base points for gen in gens: if all(gen(x) == x for x in base): new = 0 while gen._array_form[new] == new: new += 1 base.append(new) base_len += 1 # distribute generators according to basic stabilizers strong_gens_distr = _distribute_gens_by_base(base, gens) # initialize the basic stabilizers, basic transversals and basic orbits transversals = {} orbs = {} for i in range(base_len): transversals[i] = dict(_orbit_transversal(n, strong_gens_distr[i], base[i], pairs=True)) orbs[i] = list(transversals[i].keys()) # initialize the number of consecutive elements sifted c = 0 # start sifting random elements while the number of consecutive sifts # is less than consec_succ while c < consec_succ: if _random_prec is None: g = self.random_pr() else: g = _random_prec['g'].pop() h, j = _strip(g, base, orbs, transversals) y = True # determine whether a new base point is needed if j <= base_len: y = False elif not h.is_Identity: y = False moved = 0 while h(moved) == moved: moved += 1 base.append(moved) base_len += 1 strong_gens_distr.append([]) # if the element doesn't sift, amend the strong generators and # associated stabilizers and orbits if y is False: for l in range(1, j): strong_gens_distr[l].append(h) transversals[l] = dict(_orbit_transversal(n, strong_gens_distr[l], base[l], pairs=True)) orbs[l] = list(transversals[l].keys()) c = 0 else: c += 1 # build the strong generating set strong_gens = strong_gens_distr[0][:] for gen in strong_gens_distr[1]: if gen not in strong_gens: strong_gens.append(gen) return base, strong_gens def schreier_vector(self, alpha): """Computes the schreier vector for ``alpha``. Explanation =========== The Schreier vector efficiently stores information about the orbit of ``alpha``. It can later be used to quickly obtain elements of the group that send ``alpha`` to a particular element in the orbit. Notice that the Schreier vector depends on the order in which the group generators are listed. For a definition, see [3]. Since list indices start from zero, we adopt the convention to use "None" instead of 0 to signify that an element does not belong to the orbit. For the algorithm and its correctness, see [2], pp.78-80. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([2, 4, 6, 3, 1, 5, 0]) >>> b = Permutation([0, 1, 3, 5, 4, 6, 2]) >>> G = PermutationGroup([a, b]) >>> G.schreier_vector(0) [-1, None, 0, 1, None, 1, 0] See Also ======== orbit """ n = self.degree v = [None]*n v[alpha] = -1 orb = [alpha] used = [False]*n used[alpha] = True gens = self.generators r = len(gens) for b in orb: for i in range(r): temp = gens[i]._array_form[b] if used[temp] is False: orb.append(temp) used[temp] = True v[temp] = i return v def stabilizer(self, alpha): r"""Return the stabilizer subgroup of ``alpha``. Explanation =========== The stabilizer of `\alpha` is the group `G_\alpha = \{g \in G | g(\alpha) = \alpha\}`. For a proof of correctness, see [1], p.79. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> G = DihedralGroup(6) >>> G.stabilizer(5) PermutationGroup([ (5)(0 4)(1 3)]) See Also ======== orbit """ return PermGroup(_stabilizer(self._degree, self._generators, alpha)) @property def strong_gens(self): r"""Return a strong generating set from the Schreier-Sims algorithm. Explanation =========== A generating set `S = \{g_1, g_2, \dots, g_t\}` for a permutation group `G` is a strong generating set relative to the sequence of points (referred to as a "base") `(b_1, b_2, \dots, b_k)` if, for `1 \leq i \leq k` we have that the intersection of the pointwise stabilizer `G^{(i+1)} := G_{b_1, b_2, \dots, b_i}` with `S` generates the pointwise stabilizer `G^{(i+1)}`. The concepts of a base and strong generating set and their applications are discussed in depth in [1], pp. 87-89 and [2], pp. 55-57. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(4) >>> D.strong_gens [(0 1 2 3), (0 3)(1 2), (1 3)] >>> D.base [0, 1] See Also ======== base, basic_transversals, basic_orbits, basic_stabilizers """ if self._strong_gens == []: self.schreier_sims() return self._strong_gens def subgroup(self, gens): """ Return the subgroup generated by `gens` which is a list of elements of the group """ if not all(g in self for g in gens): raise ValueError("The group does not contain the supplied generators") G = PermutationGroup(gens) return G def subgroup_search(self, prop, base=None, strong_gens=None, tests=None, init_subgroup=None): """Find the subgroup of all elements satisfying the property ``prop``. Explanation =========== This is done by a depth-first search with respect to base images that uses several tests to prune the search tree. Parameters ========== prop The property to be used. Has to be callable on group elements and always return ``True`` or ``False``. It is assumed that all group elements satisfying ``prop`` indeed form a subgroup. base A base for the supergroup. strong_gens A strong generating set for the supergroup. tests A list of callables of length equal to the length of ``base``. These are used to rule out group elements by partial base images, so that ``tests[l](g)`` returns False if the element ``g`` is known not to satisfy prop base on where g sends the first ``l + 1`` base points. init_subgroup if a subgroup of the sought group is known in advance, it can be passed to the function as this parameter. Returns ======= res The subgroup of all elements satisfying ``prop``. The generating set for this group is guaranteed to be a strong generating set relative to the base ``base``. Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.combinatorics.testutil import _verify_bsgs >>> S = SymmetricGroup(7) >>> prop_even = lambda x: x.is_even >>> base, strong_gens = S.schreier_sims_incremental() >>> G = S.subgroup_search(prop_even, base=base, strong_gens=strong_gens) >>> G.is_subgroup(AlternatingGroup(7)) True >>> _verify_bsgs(G, base, G.generators) True Notes ===== This function is extremely lengthy and complicated and will require some careful attention. The implementation is described in [1], pp. 114-117, and the comments for the code here follow the lines of the pseudocode in the book for clarity. The complexity is exponential in general, since the search process by itself visits all members of the supergroup. However, there are a lot of tests which are used to prune the search tree, and users can define their own tests via the ``tests`` parameter, so in practice, and for some computations, it's not terrible. A crucial part in the procedure is the frequent base change performed (this is line 11 in the pseudocode) in order to obtain a new basic stabilizer. The book mentiones that this can be done by using ``.baseswap(...)``, however the current implementation uses a more straightforward way to find the next basic stabilizer - calling the function ``.stabilizer(...)`` on the previous basic stabilizer. """ # initialize BSGS and basic group properties def get_reps(orbits): # get the minimal element in the base ordering return [min(orbit, key = lambda x: base_ordering[x]) \ for orbit in orbits] def update_nu(l): temp_index = len(basic_orbits[l]) + 1 -\ len(res_basic_orbits_init_base[l]) # this corresponds to the element larger than all points if temp_index >= len(sorted_orbits[l]): nu[l] = base_ordering[degree] else: nu[l] = sorted_orbits[l][temp_index] if base is None: base, strong_gens = self.schreier_sims_incremental() base_len = len(base) degree = self.degree identity = _af_new(list(range(degree))) base_ordering = _base_ordering(base, degree) # add an element larger than all points base_ordering.append(degree) # add an element smaller than all points base_ordering.append(-1) # compute BSGS-related structures strong_gens_distr = _distribute_gens_by_base(base, strong_gens) basic_orbits, transversals = _orbits_transversals_from_bsgs(base, strong_gens_distr) # handle subgroup initialization and tests if init_subgroup is None: init_subgroup = PermutationGroup([identity]) if tests is None: trivial_test = lambda x: True tests = [] for i in range(base_len): tests.append(trivial_test) # line 1: more initializations. res = init_subgroup f = base_len - 1 l = base_len - 1 # line 2: set the base for K to the base for G res_base = base[:] # line 3: compute BSGS and related structures for K res_base, res_strong_gens = res.schreier_sims_incremental( base=res_base) res_strong_gens_distr = _distribute_gens_by_base(res_base, res_strong_gens) res_generators = res.generators res_basic_orbits_init_base = \ [_orbit(degree, res_strong_gens_distr[i], res_base[i])\ for i in range(base_len)] # initialize orbit representatives orbit_reps = [None]*base_len # line 4: orbit representatives for f-th basic stabilizer of K orbits = _orbits(degree, res_strong_gens_distr[f]) orbit_reps[f] = get_reps(orbits) # line 5: remove the base point from the representatives to avoid # getting the identity element as a generator for K orbit_reps[f].remove(base[f]) # line 6: more initializations c = [0]*base_len u = [identity]*base_len sorted_orbits = [None]*base_len for i in range(base_len): sorted_orbits[i] = basic_orbits[i][:] sorted_orbits[i].sort(key=lambda point: base_ordering[point]) # line 7: initializations mu = [None]*base_len nu = [None]*base_len # this corresponds to the element smaller than all points mu[l] = degree + 1 update_nu(l) # initialize computed words computed_words = [identity]*base_len # line 8: main loop while True: # apply all the tests while l < base_len - 1 and \ computed_words[l](base[l]) in orbit_reps[l] and \ base_ordering[mu[l]] < \ base_ordering[computed_words[l](base[l])] < \ base_ordering[nu[l]] and \ tests[l](computed_words): # line 11: change the (partial) base of K new_point = computed_words[l](base[l]) res_base[l] = new_point new_stab_gens = _stabilizer(degree, res_strong_gens_distr[l], new_point) res_strong_gens_distr[l + 1] = new_stab_gens # line 12: calculate minimal orbit representatives for the # l+1-th basic stabilizer orbits = _orbits(degree, new_stab_gens) orbit_reps[l + 1] = get_reps(orbits) # line 13: amend sorted orbits l += 1 temp_orbit = [computed_words[l - 1](point) for point in basic_orbits[l]] temp_orbit.sort(key=lambda point: base_ordering[point]) sorted_orbits[l] = temp_orbit # lines 14 and 15: update variables used minimality tests new_mu = degree + 1 for i in range(l): if base[l] in res_basic_orbits_init_base[i]: candidate = computed_words[i](base[i]) if base_ordering[candidate] > base_ordering[new_mu]: new_mu = candidate mu[l] = new_mu update_nu(l) # line 16: determine the new transversal element c[l] = 0 temp_point = sorted_orbits[l][c[l]] gamma = computed_words[l - 1]._array_form.index(temp_point) u[l] = transversals[l][gamma] # update computed words computed_words[l] = rmul(computed_words[l - 1], u[l]) # lines 17 & 18: apply the tests to the group element found g = computed_words[l] temp_point = g(base[l]) if l == base_len - 1 and \ base_ordering[mu[l]] < \ base_ordering[temp_point] < base_ordering[nu[l]] and \ temp_point in orbit_reps[l] and \ tests[l](computed_words) and \ prop(g): # line 19: reset the base of K res_generators.append(g) res_base = base[:] # line 20: recalculate basic orbits (and transversals) res_strong_gens.append(g) res_strong_gens_distr = _distribute_gens_by_base(res_base, res_strong_gens) res_basic_orbits_init_base = \ [_orbit(degree, res_strong_gens_distr[i], res_base[i]) \ for i in range(base_len)] # line 21: recalculate orbit representatives # line 22: reset the search depth orbit_reps[f] = get_reps(orbits) l = f # line 23: go up the tree until in the first branch not fully # searched while l >= 0 and c[l] == len(basic_orbits[l]) - 1: l = l - 1 # line 24: if the entire tree is traversed, return K if l == -1: return PermutationGroup(res_generators) # lines 25-27: update orbit representatives if l < f: # line 26 f = l c[l] = 0 # line 27 temp_orbits = _orbits(degree, res_strong_gens_distr[f]) orbit_reps[f] = get_reps(temp_orbits) # line 28: update variables used for minimality testing mu[l] = degree + 1 temp_index = len(basic_orbits[l]) + 1 - \ len(res_basic_orbits_init_base[l]) if temp_index >= len(sorted_orbits[l]): nu[l] = base_ordering[degree] else: nu[l] = sorted_orbits[l][temp_index] # line 29: set the next element from the current branch and update # accordingly c[l] += 1 if l == 0: gamma = sorted_orbits[l][c[l]] else: gamma = computed_words[l - 1]._array_form.index(sorted_orbits[l][c[l]]) u[l] = transversals[l][gamma] if l == 0: computed_words[l] = u[l] else: computed_words[l] = rmul(computed_words[l - 1], u[l]) @property def transitivity_degree(self): r"""Compute the degree of transitivity of the group. Explanation =========== A permutation group `G` acting on `\Omega = \{0, 1, \dots, n-1\}` is ``k``-fold transitive, if, for any `k` points `(a_1, a_2, \dots, a_k) \in \Omega` and any `k` points `(b_1, b_2, \dots, b_k) \in \Omega` there exists `g \in G` such that `g(a_1) = b_1, g(a_2) = b_2, \dots, g(a_k) = b_k` The degree of transitivity of `G` is the maximum ``k`` such that `G` is ``k``-fold transitive. ([8]) Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([1, 2, 0]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.transitivity_degree 3 See Also ======== is_transitive, orbit """ if self._transitivity_degree is None: n = self.degree G = self # if G is k-transitive, a tuple (a_0,..,a_k) # can be brought to (b_0,...,b_(k-1), b_k) # where b_0,...,b_(k-1) are fixed points; # consider the group G_k which stabilizes b_0,...,b_(k-1) # if G_k is transitive on the subset excluding b_0,...,b_(k-1) # then G is (k+1)-transitive for i in range(n): orb = G.orbit(i) if len(orb) != n - i: self._transitivity_degree = i return i G = G.stabilizer(i) self._transitivity_degree = n return n else: return self._transitivity_degree def _p_elements_group(self, p): ''' For an abelian p-group, return the subgroup consisting of all elements of order p (and the identity) ''' gens = self.generators[:] gens = sorted(gens, key=lambda x: x.order(), reverse=True) gens_p = [g**(g.order()/p) for g in gens] gens_r = [] for i in range(len(gens)): x = gens[i] x_order = x.order() # x_p has order p x_p = x**(x_order/p) if i > 0: P = PermutationGroup(gens_p[:i]) else: P = PermutationGroup(self.identity) if x**(x_order/p) not in P: gens_r.append(x**(x_order/p)) else: # replace x by an element of order (x.order()/p) # so that gens still generates G g = P.generator_product(x_p, original=True) for s in g: x = x*s**-1 x_order = x_order/p # insert x to gens so that the sorting is preserved del gens[i] del gens_p[i] j = i - 1 while j < len(gens) and gens[j].order() >= x_order: j += 1 gens = gens[:j] + [x] + gens[j:] gens_p = gens_p[:j] + [x] + gens_p[j:] return PermutationGroup(gens_r) def _sylow_alt_sym(self, p): ''' Return a p-Sylow subgroup of a symmetric or an alternating group. Explanation =========== The algorithm for this is hinted at in [1], Chapter 4, Exercise 4. For Sym(n) with n = p^i, the idea is as follows. Partition the interval [0..n-1] into p equal parts, each of length p^(i-1): [0..p^(i-1)-1], [p^(i-1)..2*p^(i-1)-1]...[(p-1)*p^(i-1)..p^i-1]. Find a p-Sylow subgroup of Sym(p^(i-1)) (treated as a subgroup of ``self``) acting on each of the parts. Call the subgroups P_1, P_2...P_p. The generators for the subgroups P_2...P_p can be obtained from those of P_1 by applying a "shifting" permutation to them, that is, a permutation mapping [0..p^(i-1)-1] to the second part (the other parts are obtained by using the shift multiple times). The union of this permutation and the generators of P_1 is a p-Sylow subgroup of ``self``. For n not equal to a power of p, partition [0..n-1] in accordance with how n would be written in base p. E.g. for p=2 and n=11, 11 = 2^3 + 2^2 + 1 so the partition is [[0..7], [8..9], {10}]. To generate a p-Sylow subgroup, take the union of the generators for each of the parts. For the above example, {(0 1), (0 2)(1 3), (0 4), (1 5)(2 7)} from the first part, {(8 9)} from the second part and nothing from the third. This gives 4 generators in total, and the subgroup they generate is p-Sylow. Alternating groups are treated the same except when p=2. In this case, (0 1)(s s+1) should be added for an appropriate s (the start of a part) for each part in the partitions. See Also ======== sylow_subgroup, is_alt_sym ''' n = self.degree gens = [] identity = Permutation(n-1) # the case of 2-sylow subgroups of alternating groups # needs special treatment alt = p == 2 and all(g.is_even for g in self.generators) # find the presentation of n in base p coeffs = [] m = n while m > 0: coeffs.append(m % p) m = m // p power = len(coeffs)-1 # for a symmetric group, gens[:i] is the generating # set for a p-Sylow subgroup on [0..p**(i-1)-1]. For # alternating groups, the same is given by gens[:2*(i-1)] for i in range(1, power+1): if i == 1 and alt: # (0 1) shouldn't be added for alternating groups continue gen = Permutation([(j + p**(i-1)) % p**i for j in range(p**i)]) gens.append(identity*gen) if alt: gen = Permutation(0, 1)*gen*Permutation(0, 1)*gen gens.append(gen) # the first point in the current part (see the algorithm # description in the docstring) start = 0 while power > 0: a = coeffs[power] # make the permutation shifting the start of the first # part ([0..p^i-1] for some i) to the current one for _ in range(a): shift = Permutation() if start > 0: for i in range(p**power): shift = shift(i, start + i) if alt: gen = Permutation(0, 1)*shift*Permutation(0, 1)*shift gens.append(gen) j = 2*(power - 1) else: j = power for i, gen in enumerate(gens[:j]): if alt and i % 2 == 1: continue # shift the generator to the start of the # partition part gen = shift*gen*shift gens.append(gen) start += p**power power = power-1 return gens def sylow_subgroup(self, p): ''' Return a p-Sylow subgroup of the group. The algorithm is described in [1], Chapter 4, Section 7 Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> D = DihedralGroup(6) >>> S = D.sylow_subgroup(2) >>> S.order() 4 >>> G = SymmetricGroup(6) >>> S = G.sylow_subgroup(5) >>> S.order() 5 >>> G1 = AlternatingGroup(3) >>> G2 = AlternatingGroup(5) >>> G3 = AlternatingGroup(9) >>> S1 = G1.sylow_subgroup(3) >>> S2 = G2.sylow_subgroup(3) >>> S3 = G3.sylow_subgroup(3) >>> len1 = len(S1.lower_central_series()) >>> len2 = len(S2.lower_central_series()) >>> len3 = len(S3.lower_central_series()) >>> len1 == len2 True >>> len1 < len3 True ''' from sympy.combinatorics.homomorphisms import ( orbit_homomorphism, block_homomorphism) if not isprime(p): raise ValueError("p must be a prime") def is_p_group(G): # check if the order of G is a power of p # and return the power m = G.order() n = 0 while m % p == 0: m = m/p n += 1 if m == 1: return True, n return False, n def _sylow_reduce(mu, nu): # reduction based on two homomorphisms # mu and nu with trivially intersecting # kernels Q = mu.image().sylow_subgroup(p) Q = mu.invert_subgroup(Q) nu = nu.restrict_to(Q) R = nu.image().sylow_subgroup(p) return nu.invert_subgroup(R) order = self.order() if order % p != 0: return PermutationGroup([self.identity]) p_group, n = is_p_group(self) if p_group: return self if self.is_alt_sym(): return PermutationGroup(self._sylow_alt_sym(p)) # if there is a non-trivial orbit with size not divisible # by p, the sylow subgroup is contained in its stabilizer # (by orbit-stabilizer theorem) orbits = self.orbits() non_p_orbits = [o for o in orbits if len(o) % p != 0 and len(o) != 1] if non_p_orbits: G = self.stabilizer(list(non_p_orbits[0]).pop()) return G.sylow_subgroup(p) if not self.is_transitive(): # apply _sylow_reduce to orbit actions orbits = sorted(orbits, key=len) omega1 = orbits.pop() omega2 = orbits[0].union(*orbits) mu = orbit_homomorphism(self, omega1) nu = orbit_homomorphism(self, omega2) return _sylow_reduce(mu, nu) blocks = self.minimal_blocks() if len(blocks) > 1: # apply _sylow_reduce to block system actions mu = block_homomorphism(self, blocks[0]) nu = block_homomorphism(self, blocks[1]) return _sylow_reduce(mu, nu) elif len(blocks) == 1: block = list(blocks)[0] if any(e != 0 for e in block): # self is imprimitive mu = block_homomorphism(self, block) if not is_p_group(mu.image())[0]: S = mu.image().sylow_subgroup(p) return mu.invert_subgroup(S).sylow_subgroup(p) # find an element of order p g = self.random() g_order = g.order() while g_order % p != 0 or g_order == 0: g = self.random() g_order = g.order() g = g**(g_order // p) if order % p**2 != 0: return PermutationGroup(g) C = self.centralizer(g) while C.order() % p**n != 0: S = C.sylow_subgroup(p) s_order = S.order() Z = S.center() P = Z._p_elements_group(p) h = P.random() C_h = self.centralizer(h) while C_h.order() % p*s_order != 0: h = P.random() C_h = self.centralizer(h) C = C_h return C.sylow_subgroup(p) def _block_verify(self, L, alpha): delta = sorted(list(self.orbit(alpha))) # p[i] will be the number of the block # delta[i] belongs to p = [-1]*len(delta) blocks = [-1]*len(delta) B = [[]] # future list of blocks u = [0]*len(delta) # u[i] in L s.t. alpha^u[i] = B[0][i] t = L.orbit_transversal(alpha, pairs=True) for a, beta in t: B[0].append(a) i_a = delta.index(a) p[i_a] = 0 blocks[i_a] = alpha u[i_a] = beta rho = 0 m = 0 # number of blocks - 1 while rho <= m: beta = B[rho][0] for g in self.generators: d = beta^g i_d = delta.index(d) sigma = p[i_d] if sigma < 0: # define a new block m += 1 sigma = m u[i_d] = u[delta.index(beta)]*g p[i_d] = sigma rep = d blocks[i_d] = rep newb = [rep] for gamma in B[rho][1:]: i_gamma = delta.index(gamma) d = gamma^g i_d = delta.index(d) if p[i_d] < 0: u[i_d] = u[i_gamma]*g p[i_d] = sigma blocks[i_d] = rep newb.append(d) else: # B[rho] is not a block s = u[i_gamma]*g*u[i_d]**(-1) return False, s B.append(newb) else: for h in B[rho][1:]: if h^g not in B[sigma]: # B[rho] is not a block s = u[delta.index(beta)]*g*u[i_d]**(-1) return False, s rho += 1 return True, blocks def _verify(H, K, phi, z, alpha): ''' Return a list of relators ``rels`` in generators ``gens`_h` that are mapped to ``H.generators`` by ``phi`` so that given a finite presentation <gens_k | rels_k> of ``K`` on a subset of ``gens_h`` <gens_h | rels_k + rels> is a finite presentation of ``H``. Explanation =========== ``H`` should be generated by the union of ``K.generators`` and ``z`` (a single generator), and ``H.stabilizer(alpha) == K``; ``phi`` is a canonical injection from a free group into a permutation group containing ``H``. The algorithm is described in [1], Chapter 6. Examples ======== >>> from sympy.combinatorics import free_group, Permutation, PermutationGroup >>> from sympy.combinatorics.homomorphisms import homomorphism >>> from sympy.combinatorics.fp_groups import FpGroup >>> H = PermutationGroup(Permutation(0, 2), Permutation (1, 5)) >>> K = PermutationGroup(Permutation(5)(0, 2)) >>> F = free_group("x_0 x_1")[0] >>> gens = F.generators >>> phi = homomorphism(F, H, F.generators, H.generators) >>> rels_k = [gens[0]**2] # relators for presentation of K >>> z= Permutation(1, 5) >>> check, rels_h = H._verify(K, phi, z, 1) >>> check True >>> rels = rels_k + rels_h >>> G = FpGroup(F, rels) # presentation of H >>> G.order() == H.order() True See also ======== strong_presentation, presentation, stabilizer ''' orbit = H.orbit(alpha) beta = alpha^(z**-1) K_beta = K.stabilizer(beta) # orbit representatives of K_beta gammas = [alpha, beta] orbits = list({tuple(K_beta.orbit(o)) for o in orbit}) orbit_reps = [orb[0] for orb in orbits] for rep in orbit_reps: if rep not in gammas: gammas.append(rep) # orbit transversal of K betas = [alpha, beta] transversal = {alpha: phi.invert(H.identity), beta: phi.invert(z**-1)} for s, g in K.orbit_transversal(beta, pairs=True): if s not in transversal: transversal[s] = transversal[beta]*phi.invert(g) union = K.orbit(alpha).union(K.orbit(beta)) while (len(union) < len(orbit)): for gamma in gammas: if gamma in union: r = gamma^z if r not in union: betas.append(r) transversal[r] = transversal[gamma]*phi.invert(z) for s, g in K.orbit_transversal(r, pairs=True): if s not in transversal: transversal[s] = transversal[r]*phi.invert(g) union = union.union(K.orbit(r)) break # compute relators rels = [] for b in betas: k_gens = K.stabilizer(b).generators for y in k_gens: new_rel = transversal[b] gens = K.generator_product(y, original=True) for g in gens[::-1]: new_rel = new_rel*phi.invert(g) new_rel = new_rel*transversal[b]**-1 perm = phi(new_rel) try: gens = K.generator_product(perm, original=True) except ValueError: return False, perm for g in gens: new_rel = new_rel*phi.invert(g)**-1 if new_rel not in rels: rels.append(new_rel) for gamma in gammas: new_rel = transversal[gamma]*phi.invert(z)*transversal[gamma^z]**-1 perm = phi(new_rel) try: gens = K.generator_product(perm, original=True) except ValueError: return False, perm for g in gens: new_rel = new_rel*phi.invert(g)**-1 if new_rel not in rels: rels.append(new_rel) return True, rels def strong_presentation(self): ''' Return a strong finite presentation of group. The generators of the returned group are in the same order as the strong generators of group. The algorithm is based on Sims' Verify algorithm described in [1], Chapter 6. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> P = DihedralGroup(4) >>> G = P.strong_presentation() >>> P.order() == G.order() True See Also ======== presentation, _verify ''' from sympy.combinatorics.fp_groups import (FpGroup, simplify_presentation) from sympy.combinatorics.free_groups import free_group from sympy.combinatorics.homomorphisms import (block_homomorphism, homomorphism, GroupHomomorphism) strong_gens = self.strong_gens[:] stabs = self.basic_stabilizers[:] base = self.base[:] # injection from a free group on len(strong_gens) # generators into G gen_syms = [('x_%d'%i) for i in range(len(strong_gens))] F = free_group(', '.join(gen_syms))[0] phi = homomorphism(F, self, F.generators, strong_gens) H = PermutationGroup(self.identity) while stabs: alpha = base.pop() K = H H = stabs.pop() new_gens = [g for g in H.generators if g not in K] if K.order() == 1: z = new_gens.pop() rels = [F.generators[-1]**z.order()] intermediate_gens = [z] K = PermutationGroup(intermediate_gens) # add generators one at a time building up from K to H while new_gens: z = new_gens.pop() intermediate_gens = [z] + intermediate_gens K_s = PermutationGroup(intermediate_gens) orbit = K_s.orbit(alpha) orbit_k = K.orbit(alpha) # split into cases based on the orbit of K_s if orbit_k == orbit: if z in K: rel = phi.invert(z) perm = z else: t = K.orbit_rep(alpha, alpha^z) rel = phi.invert(z)*phi.invert(t)**-1 perm = z*t**-1 for g in K.generator_product(perm, original=True): rel = rel*phi.invert(g)**-1 new_rels = [rel] elif len(orbit_k) == 1: # `success` is always true because `strong_gens` # and `base` are already a verified BSGS. Later # this could be changed to start with a randomly # generated (potential) BSGS, and then new elements # would have to be appended to it when `success` # is false. success, new_rels = K_s._verify(K, phi, z, alpha) else: # K.orbit(alpha) should be a block # under the action of K_s on K_s.orbit(alpha) check, block = K_s._block_verify(K, alpha) if check: # apply _verify to the action of K_s # on the block system; for convenience, # add the blocks as additional points # that K_s should act on t = block_homomorphism(K_s, block) m = t.codomain.degree # number of blocks d = K_s.degree # conjugating with p will shift # permutations in t.image() to # higher numbers, e.g. # p*(0 1)*p = (m m+1) p = Permutation() for i in range(m): p *= Permutation(i, i+d) t_img = t.images # combine generators of K_s with their # action on the block system images = {g: g*p*t_img[g]*p for g in t_img} for g in self.strong_gens[:-len(K_s.generators)]: images[g] = g K_s_act = PermutationGroup(list(images.values())) f = GroupHomomorphism(self, K_s_act, images) K_act = PermutationGroup([f(g) for g in K.generators]) success, new_rels = K_s_act._verify(K_act, f.compose(phi), f(z), d) for n in new_rels: if n not in rels: rels.append(n) K = K_s group = FpGroup(F, rels) return simplify_presentation(group) def presentation(self, eliminate_gens=True): ''' Return an `FpGroup` presentation of the group. The algorithm is described in [1], Chapter 6.1. ''' from sympy.combinatorics.fp_groups import (FpGroup, simplify_presentation) from sympy.combinatorics.coset_table import CosetTable from sympy.combinatorics.free_groups import free_group from sympy.combinatorics.homomorphisms import homomorphism if self._fp_presentation: return self._fp_presentation def _factor_group_by_rels(G, rels): if isinstance(G, FpGroup): rels.extend(G.relators) return FpGroup(G.free_group, list(set(rels))) return FpGroup(G, rels) gens = self.generators len_g = len(gens) if len_g == 1: order = gens[0].order() # handle the trivial group if order == 1: return free_group([])[0] F, x = free_group('x') return FpGroup(F, [x**order]) if self.order() > 20: half_gens = self.generators[0:(len_g+1)//2] else: half_gens = [] H = PermutationGroup(half_gens) H_p = H.presentation() len_h = len(H_p.generators) C = self.coset_table(H) n = len(C) # subgroup index gen_syms = [('x_%d'%i) for i in range(len(gens))] F = free_group(', '.join(gen_syms))[0] # mapping generators of H_p to those of F images = [F.generators[i] for i in range(len_h)] R = homomorphism(H_p, F, H_p.generators, images, check=False) # rewrite relators rels = R(H_p.relators) G_p = FpGroup(F, rels) # injective homomorphism from G_p into self T = homomorphism(G_p, self, G_p.generators, gens) C_p = CosetTable(G_p, []) C_p.table = [[None]*(2*len_g) for i in range(n)] # initiate the coset transversal transversal = [None]*n transversal[0] = G_p.identity # fill in the coset table as much as possible for i in range(2*len_h): C_p.table[0][i] = 0 gamma = 1 for alpha, x in product(range(n), range(2*len_g)): beta = C[alpha][x] if beta == gamma: gen = G_p.generators[x//2]**((-1)**(x % 2)) transversal[beta] = transversal[alpha]*gen C_p.table[alpha][x] = beta C_p.table[beta][x + (-1)**(x % 2)] = alpha gamma += 1 if gamma == n: break C_p.p = list(range(n)) beta = x = 0 while not C_p.is_complete(): # find the first undefined entry while C_p.table[beta][x] == C[beta][x]: x = (x + 1) % (2*len_g) if x == 0: beta = (beta + 1) % n # define a new relator gen = G_p.generators[x//2]**((-1)**(x % 2)) new_rel = transversal[beta]*gen*transversal[C[beta][x]]**-1 perm = T(new_rel) nxt = G_p.identity for s in H.generator_product(perm, original=True): nxt = nxt*T.invert(s)**-1 new_rel = new_rel*nxt # continue coset enumeration G_p = _factor_group_by_rels(G_p, [new_rel]) C_p.scan_and_fill(0, new_rel) C_p = G_p.coset_enumeration([], strategy="coset_table", draft=C_p, max_cosets=n, incomplete=True) self._fp_presentation = simplify_presentation(G_p) return self._fp_presentation def polycyclic_group(self): """ Return the PolycyclicGroup instance with below parameters: Explanation =========== * pc_sequence : Polycyclic sequence is formed by collecting all the missing generators between the adjacent groups in the derived series of given permutation group. * pc_series : Polycyclic series is formed by adding all the missing generators of ``der[i+1]`` in ``der[i]``, where ``der`` represents the derived series. * relative_order : A list, computed by the ratio of adjacent groups in pc_series. """ from sympy.combinatorics.pc_groups import PolycyclicGroup if not self.is_polycyclic: raise ValueError("The group must be solvable") der = self.derived_series() pc_series = [] pc_sequence = [] relative_order = [] pc_series.append(der[-1]) der.reverse() for i in range(len(der)-1): H = der[i] for g in der[i+1].generators: if g not in H: H = PermutationGroup([g] + H.generators) pc_series.insert(0, H) pc_sequence.insert(0, g) G1 = pc_series[0].order() G2 = pc_series[1].order() relative_order.insert(0, G1 // G2) return PolycyclicGroup(pc_sequence, pc_series, relative_order, collector=None) def _orbit(degree, generators, alpha, action='tuples'): r"""Compute the orbit of alpha `\{g(\alpha) | g \in G\}` as a set. Explanation =========== The time complexity of the algorithm used here is `O(|Orb|*r)` where `|Orb|` is the size of the orbit and ``r`` is the number of generators of the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21. Here alpha can be a single point, or a list of points. If alpha is a single point, the ordinary orbit is computed. if alpha is a list of points, there are three available options: 'union' - computes the union of the orbits of the points in the list 'tuples' - computes the orbit of the list interpreted as an ordered tuple under the group action ( i.e., g((1, 2, 3)) = (g(1), g(2), g(3)) ) 'sets' - computes the orbit of the list interpreted as a sets Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> from sympy.combinatorics.perm_groups import _orbit >>> a = Permutation([1, 2, 0, 4, 5, 6, 3]) >>> G = PermutationGroup([a]) >>> _orbit(G.degree, G.generators, 0) {0, 1, 2} >>> _orbit(G.degree, G.generators, [0, 4], 'union') {0, 1, 2, 3, 4, 5, 6} See Also ======== orbit, orbit_transversal """ if not hasattr(alpha, '__getitem__'): alpha = [alpha] gens = [x._array_form for x in generators] if len(alpha) == 1 or action == 'union': orb = alpha used = [False]*degree for el in alpha: used[el] = True for b in orb: for gen in gens: temp = gen[b] if used[temp] == False: orb.append(temp) used[temp] = True return set(orb) elif action == 'tuples': alpha = tuple(alpha) orb = [alpha] used = {alpha} for b in orb: for gen in gens: temp = tuple([gen[x] for x in b]) if temp not in used: orb.append(temp) used.add(temp) return set(orb) elif action == 'sets': alpha = frozenset(alpha) orb = [alpha] used = {alpha} for b in orb: for gen in gens: temp = frozenset([gen[x] for x in b]) if temp not in used: orb.append(temp) used.add(temp) return {tuple(x) for x in orb} def _orbits(degree, generators): """Compute the orbits of G. If ``rep=False`` it returns a list of sets else it returns a list of representatives of the orbits Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import _orbits >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> _orbits(a.size, [a, b]) [{0, 1, 2}] """ orbs = [] sorted_I = list(range(degree)) I = set(sorted_I) while I: i = sorted_I[0] orb = _orbit(degree, generators, i) orbs.append(orb) # remove all indices that are in this orbit I -= orb sorted_I = [i for i in sorted_I if i not in orb] return orbs def _orbit_transversal(degree, generators, alpha, pairs, af=False, slp=False): r"""Computes a transversal for the orbit of ``alpha`` as a set. Explanation =========== generators generators of the group ``G`` For a permutation group ``G``, a transversal for the orbit `Orb = \{g(\alpha) | g \in G\}` is a set `\{g_\beta | g_\beta(\alpha) = \beta\}` for `\beta \in Orb`. Note that there may be more than one possible transversal. If ``pairs`` is set to ``True``, it returns the list of pairs `(\beta, g_\beta)`. For a proof of correctness, see [1], p.79 if ``af`` is ``True``, the transversal elements are given in array form. If `slp` is `True`, a dictionary `{beta: slp_beta}` is returned for `\beta \in Orb` where `slp_beta` is a list of indices of the generators in `generators` s.t. if `slp_beta = [i_1 \dots i_n]` `g_\beta = generators[i_n] \times \dots \times generators[i_1]`. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> from sympy.combinatorics.perm_groups import _orbit_transversal >>> G = DihedralGroup(6) >>> _orbit_transversal(G.degree, G.generators, 0, False) [(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)] """ tr = [(alpha, list(range(degree)))] slp_dict = {alpha: []} used = [False]*degree used[alpha] = True gens = [x._array_form for x in generators] for x, px in tr: px_slp = slp_dict[x] for gen in gens: temp = gen[x] if used[temp] == False: slp_dict[temp] = [gens.index(gen)] + px_slp tr.append((temp, _af_rmul(gen, px))) used[temp] = True if pairs: if not af: tr = [(x, _af_new(y)) for x, y in tr] if not slp: return tr return tr, slp_dict if af: tr = [y for _, y in tr] if not slp: return tr return tr, slp_dict tr = [_af_new(y) for _, y in tr] if not slp: return tr return tr, slp_dict def _stabilizer(degree, generators, alpha): r"""Return the stabilizer subgroup of ``alpha``. Explanation =========== The stabilizer of `\alpha` is the group `G_\alpha = \{g \in G | g(\alpha) = \alpha\}`. For a proof of correctness, see [1], p.79. degree : degree of G generators : generators of G Examples ======== >>> from sympy.combinatorics.perm_groups import _stabilizer >>> from sympy.combinatorics.named_groups import DihedralGroup >>> G = DihedralGroup(6) >>> _stabilizer(G.degree, G.generators, 5) [(5)(0 4)(1 3), (5)] See Also ======== orbit """ orb = [alpha] table = {alpha: list(range(degree))} table_inv = {alpha: list(range(degree))} used = [False]*degree used[alpha] = True gens = [x._array_form for x in generators] stab_gens = [] for b in orb: for gen in gens: temp = gen[b] if used[temp] is False: gen_temp = _af_rmul(gen, table[b]) orb.append(temp) table[temp] = gen_temp table_inv[temp] = _af_invert(gen_temp) used[temp] = True else: schreier_gen = _af_rmuln(table_inv[temp], gen, table[b]) if schreier_gen not in stab_gens: stab_gens.append(schreier_gen) return [_af_new(x) for x in stab_gens] PermGroup = PermutationGroup class SymmetricPermutationGroup(Basic): """ The class defining the lazy form of SymmetricGroup. deg : int """ def __new__(cls, deg): deg = _sympify(deg) obj = Basic.__new__(cls, deg) return obj def __init__(self, *args, **kwargs): self._deg = self.args[0] self._order = None def __contains__(self, i): """Return ``True`` if *i* is contained in SymmetricPermutationGroup. Examples ======== >>> from sympy.combinatorics import Permutation, SymmetricPermutationGroup >>> G = SymmetricPermutationGroup(4) >>> Permutation(1, 2, 3) in G True """ if not isinstance(i, Permutation): raise TypeError("A SymmetricPermutationGroup contains only Permutations as " "elements, not elements of type %s" % type(i)) return i.size == self.degree def order(self): """ Return the order of the SymmetricPermutationGroup. Examples ======== >>> from sympy.combinatorics import SymmetricPermutationGroup >>> G = SymmetricPermutationGroup(4) >>> G.order() 24 """ if self._order is not None: return self._order n = self._deg self._order = factorial(n) return self._order @property def degree(self): """ Return the degree of the SymmetricPermutationGroup. Examples ======== >>> from sympy.combinatorics import SymmetricPermutationGroup >>> G = SymmetricPermutationGroup(4) >>> G.degree 4 """ return self._deg @property def identity(self): ''' Return the identity element of the SymmetricPermutationGroup. Examples ======== >>> from sympy.combinatorics import SymmetricPermutationGroup >>> G = SymmetricPermutationGroup(4) >>> G.identity() (3) ''' return _af_new(list(range(self._deg))) class Coset(Basic): """A left coset of a permutation group with respect to an element. Parameters ========== g : Permutation H : PermutationGroup dir : "+" or "-", If not specified by default it will be "+" here ``dir`` specified the type of coset "+" represent the right coset and "-" represent the left coset. G : PermutationGroup, optional The group which contains *H* as its subgroup and *g* as its element. If not specified, it would automatically become a symmetric group ``SymmetricPermutationGroup(g.size)`` and ``SymmetricPermutationGroup(H.degree)`` if ``g.size`` and ``H.degree`` are matching.``SymmetricPermutationGroup`` is a lazy form of SymmetricGroup used for representation purpose. """ def __new__(cls, g, H, G=None, dir="+"): g = _sympify(g) if not isinstance(g, Permutation): raise NotImplementedError H = _sympify(H) if not isinstance(H, PermutationGroup): raise NotImplementedError if G is not None: G = _sympify(G) if not isinstance(G, (PermutationGroup, SymmetricPermutationGroup)): raise NotImplementedError if not H.is_subgroup(G): raise ValueError("{} must be a subgroup of {}.".format(H, G)) if g not in G: raise ValueError("{} must be an element of {}.".format(g, G)) else: g_size = g.size h_degree = H.degree if g_size != h_degree: raise ValueError( "The size of the permutation {} and the degree of " "the permutation group {} should be matching " .format(g, H)) G = SymmetricPermutationGroup(g.size) if isinstance(dir, str): dir = Symbol(dir) elif not isinstance(dir, Symbol): raise TypeError("dir must be of type basestring or " "Symbol, not %s" % type(dir)) if str(dir) not in ('+', '-'): raise ValueError("dir must be one of '+' or '-' not %s" % dir) obj = Basic.__new__(cls, g, H, G, dir) return obj def __init__(self, *args, **kwargs): self._dir = self.args[3] @property def is_left_coset(self): """ Check if the coset is left coset that is ``gH``. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup, Coset >>> a = Permutation(1, 2) >>> b = Permutation(0, 1) >>> G = PermutationGroup([a, b]) >>> cst = Coset(a, G, dir="-") >>> cst.is_left_coset True """ return str(self._dir) == '-' @property def is_right_coset(self): """ Check if the coset is right coset that is ``Hg``. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup, Coset >>> a = Permutation(1, 2) >>> b = Permutation(0, 1) >>> G = PermutationGroup([a, b]) >>> cst = Coset(a, G, dir="+") >>> cst.is_right_coset True """ return str(self._dir) == '+' def as_list(self): """ Return all the elements of coset in the form of list. """ g = self.args[0] H = self.args[1] cst = [] if str(self._dir) == '+': for h in H.elements: cst.append(h*g) else: for h in H.elements: cst.append(g*h) return cst
943889f46e2ce42787d28a8e98f6da23518b5078c3d28a1d3a86e424787d45b7
from sympy.combinatorics.permutations import Permutation from sympy.core.symbol import symbols from sympy.matrices import Matrix from sympy.utilities.iterables import variations, rotate_left def symmetric(n): """ Generates the symmetric group of order n, Sn. Examples ======== >>> from sympy.combinatorics.generators import symmetric >>> list(symmetric(3)) [(2), (1 2), (2)(0 1), (0 1 2), (0 2 1), (0 2)] """ for perm in variations(range(n), n): yield Permutation(perm) def cyclic(n): """ Generates the cyclic group of order n, Cn. Examples ======== >>> from sympy.combinatorics.generators import cyclic >>> list(cyclic(5)) [(4), (0 1 2 3 4), (0 2 4 1 3), (0 3 1 4 2), (0 4 3 2 1)] See Also ======== dihedral """ gen = list(range(n)) for i in range(n): yield Permutation(gen) gen = rotate_left(gen, 1) def alternating(n): """ Generates the alternating group of order n, An. Examples ======== >>> from sympy.combinatorics.generators import alternating >>> list(alternating(3)) [(2), (0 1 2), (0 2 1)] """ for perm in variations(range(n), n): p = Permutation(perm) if p.is_even: yield p def dihedral(n): """ Generates the dihedral group of order 2n, Dn. The result is given as a subgroup of Sn, except for the special cases n=1 (the group S2) and n=2 (the Klein 4-group) where that's not possible and embeddings in S2 and S4 respectively are given. Examples ======== >>> from sympy.combinatorics.generators import dihedral >>> list(dihedral(3)) [(2), (0 2), (0 1 2), (1 2), (0 2 1), (2)(0 1)] See Also ======== cyclic """ if n == 1: yield Permutation([0, 1]) yield Permutation([1, 0]) elif n == 2: yield Permutation([0, 1, 2, 3]) yield Permutation([1, 0, 3, 2]) yield Permutation([2, 3, 0, 1]) yield Permutation([3, 2, 1, 0]) else: gen = list(range(n)) for i in range(n): yield Permutation(gen) yield Permutation(gen[::-1]) gen = rotate_left(gen, 1) def rubik_cube_generators(): """Return the permutations of the 3x3 Rubik's cube, see http://www.gap-system.org/Doc/Examples/rubik.html """ a = [ [(1, 3, 8, 6), (2, 5, 7, 4), (9, 33, 25, 17), (10, 34, 26, 18), (11, 35, 27, 19)], [(9, 11, 16, 14), (10, 13, 15, 12), (1, 17, 41, 40), (4, 20, 44, 37), (6, 22, 46, 35)], [(17, 19, 24, 22), (18, 21, 23, 20), (6, 25, 43, 16), (7, 28, 42, 13), (8, 30, 41, 11)], [(25, 27, 32, 30), (26, 29, 31, 28), (3, 38, 43, 19), (5, 36, 45, 21), (8, 33, 48, 24)], [(33, 35, 40, 38), (34, 37, 39, 36), (3, 9, 46, 32), (2, 12, 47, 29), (1, 14, 48, 27)], [(41, 43, 48, 46), (42, 45, 47, 44), (14, 22, 30, 38), (15, 23, 31, 39), (16, 24, 32, 40)] ] return [Permutation([[i - 1 for i in xi] for xi in x], size=48) for x in a] def rubik(n): """Return permutations for an nxn Rubik's cube. Permutations returned are for rotation of each of the slice from the face up to the last face for each of the 3 sides (in this order): front, right and bottom. Hence, the first n - 1 permutations are for the slices from the front. """ if n < 2: raise ValueError('dimension of cube must be > 1') # 1-based reference to rows and columns in Matrix def getr(f, i): return faces[f].col(n - i) def getl(f, i): return faces[f].col(i - 1) def getu(f, i): return faces[f].row(i - 1) def getd(f, i): return faces[f].row(n - i) def setr(f, i, s): faces[f][:, n - i] = Matrix(n, 1, s) def setl(f, i, s): faces[f][:, i - 1] = Matrix(n, 1, s) def setu(f, i, s): faces[f][i - 1, :] = Matrix(1, n, s) def setd(f, i, s): faces[f][n - i, :] = Matrix(1, n, s) # motion of a single face def cw(F, r=1): for _ in range(r): face = faces[F] rv = [] for c in range(n): for r in range(n - 1, -1, -1): rv.append(face[r, c]) faces[F] = Matrix(n, n, rv) def ccw(F): cw(F, 3) # motion of plane i from the F side; # fcw(0) moves the F face, fcw(1) moves the plane # just behind the front face, etc... def fcw(i, r=1): for _ in range(r): if i == 0: cw(F) i += 1 temp = getr(L, i) setr(L, i, list(getu(D, i))) setu(D, i, list(reversed(getl(R, i)))) setl(R, i, list(getd(U, i))) setd(U, i, list(reversed(temp))) i -= 1 def fccw(i): fcw(i, 3) # motion of the entire cube from the F side def FCW(r=1): for _ in range(r): cw(F) ccw(B) cw(U) t = faces[U] cw(L) faces[U] = faces[L] cw(D) faces[L] = faces[D] cw(R) faces[D] = faces[R] faces[R] = t def FCCW(): FCW(3) # motion of the entire cube from the U side def UCW(r=1): for _ in range(r): cw(U) ccw(D) t = faces[F] faces[F] = faces[R] faces[R] = faces[B] faces[B] = faces[L] faces[L] = t def UCCW(): UCW(3) # defining the permutations for the cube U, F, R, B, L, D = names = symbols('U, F, R, B, L, D') # the faces are represented by nxn matrices faces = {} count = 0 for fi in range(6): f = [] for a in range(n**2): f.append(count) count += 1 faces[names[fi]] = Matrix(n, n, f) # this will either return the value of the current permutation # (show != 1) or else append the permutation to the group, g def perm(show=0): # add perm to the list of perms p = [] for f in names: p.extend(faces[f]) if show: return p g.append(Permutation(p)) g = [] # container for the group's permutations I = list(range(6*n**2)) # the identity permutation used for checking # define permutations corresponding to cw rotations of the planes # up TO the last plane from that direction; by not including the # last plane, the orientation of the cube is maintained. # F slices for i in range(n - 1): fcw(i) perm() fccw(i) # restore assert perm(1) == I # R slices # bring R to front UCW() for i in range(n - 1): fcw(i) # put it back in place UCCW() # record perm() # restore # bring face to front UCW() fccw(i) # restore UCCW() assert perm(1) == I # D slices # bring up bottom FCW() UCCW() FCCW() for i in range(n - 1): # turn strip fcw(i) # put bottom back on the bottom FCW() UCW() FCCW() # record perm() # restore # bring up bottom FCW() UCCW() FCCW() # turn strip fccw(i) # put bottom back on the bottom FCW() UCW() FCCW() assert perm(1) == I return g
87a353687f7da06d20d6557185284163615ce08c17c8c51cd08877d4a23a905c
from sympy.combinatorics.permutations import Permutation, _af_rmul, \ _af_invert, _af_new from sympy.combinatorics.perm_groups import PermutationGroup, _orbit, \ _orbit_transversal from sympy.combinatorics.util import _distribute_gens_by_base, \ _orbits_transversals_from_bsgs """ References for tensor canonicalization: [1] R. Portugal "Algorithmic simplification of tensor expressions", J. Phys. A 32 (1999) 7779-7789 [2] R. Portugal, B.F. Svaiter "Group-theoretic Approach for Symbolic Tensor Manipulation: I. Free Indices" arXiv:math-ph/0107031v1 [3] L.R.U. Manssur, R. Portugal "Group-theoretic Approach for Symbolic Tensor Manipulation: II. Dummy Indices" arXiv:math-ph/0107032v1 [4] xperm.c part of XPerm written by J. M. Martin-Garcia http://www.xact.es/index.html """ def dummy_sgs(dummies, sym, n): """ Return the strong generators for dummy indices. Parameters ========== dummies : List of dummy indices. `dummies[2k], dummies[2k+1]` are paired indices. In base form, the dummy indices are always in consecutive positions. sym : symmetry under interchange of contracted dummies:: * None no symmetry * 0 commuting * 1 anticommuting n : number of indices Examples ======== >>> from sympy.combinatorics.tensor_can import dummy_sgs >>> dummy_sgs(list(range(2, 8)), 0, 8) [[0, 1, 3, 2, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 5, 4, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 7, 6, 8, 9], [0, 1, 4, 5, 2, 3, 6, 7, 8, 9], [0, 1, 2, 3, 6, 7, 4, 5, 8, 9]] """ if len(dummies) > n: raise ValueError("List too large") res = [] # exchange of contravariant and covariant indices if sym is not None: for j in dummies[::2]: a = list(range(n + 2)) if sym == 1: a[n] = n + 1 a[n + 1] = n a[j], a[j + 1] = a[j + 1], a[j] res.append(a) # rename dummy indices for j in dummies[:-3:2]: a = list(range(n + 2)) a[j:j + 4] = a[j + 2], a[j + 3], a[j], a[j + 1] res.append(a) return res def _min_dummies(dummies, sym, indices): """ Return list of minima of the orbits of indices in group of dummies. See ``double_coset_can_rep`` for the description of ``dummies`` and ``sym``. ``indices`` is the initial list of dummy indices. Examples ======== >>> from sympy.combinatorics.tensor_can import _min_dummies >>> _min_dummies([list(range(2, 8))], [0], list(range(10))) [0, 1, 2, 2, 2, 2, 2, 2, 8, 9] """ num_types = len(sym) m = [min(dx) if dx else None for dx in dummies] res = indices[:] for i in range(num_types): for c, i in enumerate(indices): for j in range(num_types): if i in dummies[j]: res[c] = m[j] break return res def _trace_S(s, j, b, S_cosets): """ Return the representative h satisfying s[h[b]] == j If there is not such a representative return None """ for h in S_cosets[b]: if s[h[b]] == j: return h return None def _trace_D(gj, p_i, Dxtrav): """ Return the representative h satisfying h[gj] == p_i If there is not such a representative return None """ for h in Dxtrav: if h[gj] == p_i: return h return None def _dumx_remove(dumx, dumx_flat, p0): """ remove p0 from dumx """ res = [] for dx in dumx: if p0 not in dx: res.append(dx) continue k = dx.index(p0) if k % 2 == 0: p0_paired = dx[k + 1] else: p0_paired = dx[k - 1] dx.remove(p0) dx.remove(p0_paired) dumx_flat.remove(p0) dumx_flat.remove(p0_paired) res.append(dx) def transversal2coset(size, base, transversal): a = [] j = 0 for i in range(size): if i in base: a.append(sorted(transversal[j].values())) j += 1 else: a.append([list(range(size))]) j = len(a) - 1 while a[j] == [list(range(size))]: j -= 1 return a[:j + 1] def double_coset_can_rep(dummies, sym, b_S, sgens, S_transversals, g): r""" Butler-Portugal algorithm for tensor canonicalization with dummy indices. Parameters ========== dummies list of lists of dummy indices, one list for each type of index; the dummy indices are put in order contravariant, covariant [d0, -d0, d1, -d1, ...]. sym list of the symmetries of the index metric for each type. possible symmetries of the metrics * 0 symmetric * 1 antisymmetric * None no symmetry b_S base of a minimal slot symmetry BSGS. sgens generators of the slot symmetry BSGS. S_transversals transversals for the slot BSGS. g permutation representing the tensor. Returns ======= Return 0 if the tensor is zero, else return the array form of the permutation representing the canonical form of the tensor. Notes ===== A tensor with dummy indices can be represented in a number of equivalent ways which typically grows exponentially with the number of indices. To be able to establish if two tensors with many indices are equal becomes computationally very slow in absence of an efficient algorithm. The Butler-Portugal algorithm [3] is an efficient algorithm to put tensors in canonical form, solving the above problem. Portugal observed that a tensor can be represented by a permutation, and that the class of tensors equivalent to it under slot and dummy symmetries is equivalent to the double coset `D*g*S` (Note: in this documentation we use the conventions for multiplication of permutations p, q with (p*q)(i) = p[q[i]] which is opposite to the one used in the Permutation class) Using the algorithm by Butler to find a representative of the double coset one can find a canonical form for the tensor. To see this correspondence, let `g` be a permutation in array form; a tensor with indices `ind` (the indices including both the contravariant and the covariant ones) can be written as `t = T(ind[g[0]], \dots, ind[g[n-1]])`, where `n = len(ind)`; `g` has size `n + 2`, the last two indices for the sign of the tensor (trick introduced in [4]). A slot symmetry transformation `s` is a permutation acting on the slots `t \rightarrow T(ind[(g*s)[0]], \dots, ind[(g*s)[n-1]])` A dummy symmetry transformation acts on `ind` `t \rightarrow T(ind[(d*g)[0]], \dots, ind[(d*g)[n-1]])` Being interested only in the transformations of the tensor under these symmetries, one can represent the tensor by `g`, which transforms as `g -> d*g*s`, so it belongs to the coset `D*g*S`, or in other words to the set of all permutations allowed by the slot and dummy symmetries. Let us explain the conventions by an example. Given a tensor `T^{d3 d2 d1}{}_{d1 d2 d3}` with the slot symmetries `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}` `T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}` and symmetric metric, find the tensor equivalent to it which is the lowest under the ordering of indices: lexicographic ordering `d1, d2, d3` and then contravariant before covariant index; that is the canonical form of the tensor. The canonical form is `-T^{d1 d2 d3}{}_{d1 d2 d3}` obtained using `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`. To convert this problem in the input for this function, use the following ordering of the index names (- for covariant for short) `d1, -d1, d2, -d2, d3, -d3` `T^{d3 d2 d1}{}_{d1 d2 d3}` corresponds to `g = [4, 2, 0, 1, 3, 5, 6, 7]` where the last two indices are for the sign `sgens = [Permutation(0, 2)(6, 7), Permutation(0, 4)(6, 7)]` sgens[0] is the slot symmetry `-(0, 2)` `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}` sgens[1] is the slot symmetry `-(0, 4)` `T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}` The dummy symmetry group D is generated by the strong base generators `[(0, 1), (2, 3), (4, 5), (0, 2)(1, 3), (0, 4)(1, 5)]` where the first three interchange covariant and contravariant positions of the same index (d1 <-> -d1) and the last two interchange the dummy indices themselves (d1 <-> d2). The dummy symmetry acts from the left `d = [1, 0, 2, 3, 4, 5, 6, 7]` exchange `d1 \leftrightarrow -d1` `T^{d3 d2 d1}{}_{d1 d2 d3} == T^{d3 d2}{}_{d1}{}^{d1}{}_{d2 d3}` `g=[4, 2, 0, 1, 3, 5, 6, 7] -> [4, 2, 1, 0, 3, 5, 6, 7] = _af_rmul(d, g)` which differs from `_af_rmul(g, d)`. The slot symmetry acts from the right `s = [2, 1, 0, 3, 4, 5, 7, 6]` exchanges slots 0 and 2 and changes sign `T^{d3 d2 d1}{}_{d1 d2 d3} == -T^{d1 d2 d3}{}_{d1 d2 d3}` `g=[4,2,0,1,3,5,6,7] -> [0, 2, 4, 1, 3, 5, 7, 6] = _af_rmul(g, s)` Example in which the tensor is zero, same slot symmetries as above: `T^{d2}{}_{d1 d3}{}^{d1 d3}{}_{d2}` `= -T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}` under slot symmetry `-(0,4)`; `= T_{d3 d1}{}^{d3}{}^{d1 d2}{}_{d2}` under slot symmetry `-(0,2)`; `= T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}` symmetric metric; `= 0` since two of these lines have tensors differ only for the sign. The double coset D*g*S consists of permutations `h = d*g*s` corresponding to equivalent tensors; if there are two `h` which are the same apart from the sign, return zero; otherwise choose as representative the tensor with indices ordered lexicographically according to `[d1, -d1, d2, -d2, d3, -d3]` that is ``rep = min(D*g*S) = min([d*g*s for d in D for s in S])`` The indices are fixed one by one; first choose the lowest index for slot 0, then the lowest remaining index for slot 1, etc. Doing this one obtains a chain of stabilizers `S \rightarrow S_{b0} \rightarrow S_{b0,b1} \rightarrow \dots` and `D \rightarrow D_{p0} \rightarrow D_{p0,p1} \rightarrow \dots` where ``[b0, b1, ...] = range(b)`` is a base of the symmetric group; the strong base `b_S` of S is an ordered sublist of it; therefore it is sufficient to compute once the strong base generators of S using the Schreier-Sims algorithm; the stabilizers of the strong base generators are the strong base generators of the stabilizer subgroup. ``dbase = [p0, p1, ...]`` is not in general in lexicographic order, so that one must recompute the strong base generators each time; however this is trivial, there is no need to use the Schreier-Sims algorithm for D. The algorithm keeps a TAB of elements `(s_i, d_i, h_i)` where `h_i = d_i \times g \times s_i` satisfying `h_i[j] = p_j` for `0 \le j < i` starting from `s_0 = id, d_0 = id, h_0 = g`. The equations `h_0[0] = p_0, h_1[1] = p_1, \dots` are solved in this order, choosing each time the lowest possible value of p_i For `j < i` `d_i*g*s_i*S_{b_0, \dots, b_{i-1}}*b_j = D_{p_0, \dots, p_{i-1}}*p_j` so that for dx in `D_{p_0,\dots,p_{i-1}}` and sx in `S_{base[0], \dots, base[i-1]}` one has `dx*d_i*g*s_i*sx*b_j = p_j` Search for dx, sx such that this equation holds for `j = i`; it can be written as `s_i*sx*b_j = J, dx*d_i*g*J = p_j` `sx*b_j = s_i**-1*J; sx = trace(s_i**-1, S_{b_0,...,b_{i-1}})` `dx**-1*p_j = d_i*g*J; dx = trace(d_i*g*J, D_{p_0,...,p_{i-1}})` `s_{i+1} = s_i*trace(s_i**-1*J, S_{b_0,...,b_{i-1}})` `d_{i+1} = trace(d_i*g*J, D_{p_0,...,p_{i-1}})**-1*d_i` `h_{i+1}*b_i = d_{i+1}*g*s_{i+1}*b_i = p_i` `h_n*b_j = p_j` for all j, so that `h_n` is the solution. Add the found `(s, d, h)` to TAB1. At the end of the iteration sort TAB1 with respect to the `h`; if there are two consecutive `h` in TAB1 which differ only for the sign, the tensor is zero, so return 0; if there are two consecutive `h` which are equal, keep only one. Then stabilize the slot generators under `i` and the dummy generators under `p_i`. Assign `TAB = TAB1` at the end of the iteration step. At the end `TAB` contains a unique `(s, d, h)`, since all the slots of the tensor `h` have been fixed to have the minimum value according to the symmetries. The algorithm returns `h`. It is important that the slot BSGS has lexicographic minimal base, otherwise there is an `i` which does not belong to the slot base for which `p_i` is fixed by the dummy symmetry only, while `i` is not invariant from the slot stabilizer, so `p_i` is not in general the minimal value. This algorithm differs slightly from the original algorithm [3]: the canonical form is minimal lexicographically, and the BSGS has minimal base under lexicographic order. Equal tensors `h` are eliminated from TAB. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.tensor_can import double_coset_can_rep, get_transversals >>> gens = [Permutation(x) for x in [[2, 1, 0, 3, 4, 5, 7, 6], [4, 1, 2, 3, 0, 5, 7, 6]]] >>> base = [0, 2] >>> g = Permutation([4, 2, 0, 1, 3, 5, 6, 7]) >>> transversals = get_transversals(base, gens) >>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g) [0, 1, 2, 3, 4, 5, 7, 6] >>> g = Permutation([4, 1, 3, 0, 5, 2, 6, 7]) >>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g) 0 """ size = g.size g = g.array_form num_dummies = size - 2 indices = list(range(num_dummies)) all_metrics_with_sym = not any(_ is None for _ in sym) num_types = len(sym) dumx = dummies[:] dumx_flat = [] for dx in dumx: dumx_flat.extend(dx) b_S = b_S[:] sgensx = [h._array_form for h in sgens] if b_S: S_transversals = transversal2coset(size, b_S, S_transversals) # strong generating set for D dsgsx = [] for i in range(num_types): dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies)) idn = list(range(size)) # TAB = list of entries (s, d, h) where h = _af_rmuln(d,g,s) # for short, in the following d*g*s means _af_rmuln(d,g,s) TAB = [(idn, idn, g)] for i in range(size - 2): b = i testb = b in b_S and sgensx if testb: sgensx1 = [_af_new(_) for _ in sgensx] deltab = _orbit(size, sgensx1, b) else: deltab = {b} # p1 = min(IMAGES) = min(Union D_p*h*deltab for h in TAB) if all_metrics_with_sym: md = _min_dummies(dumx, sym, indices) else: md = [min(_orbit(size, [_af_new( ddx) for ddx in dsgsx], ii)) for ii in range(size - 2)] p_i = min([min([md[h[x]] for x in deltab]) for s, d, h in TAB]) dsgsx1 = [_af_new(_) for _ in dsgsx] Dxtrav = _orbit_transversal(size, dsgsx1, p_i, False, af=True) \ if dsgsx else None if Dxtrav: Dxtrav = [_af_invert(x) for x in Dxtrav] # compute the orbit of p_i for ii in range(num_types): if p_i in dumx[ii]: # the orbit is made by all the indices in dum[ii] if sym[ii] is not None: deltap = dumx[ii] else: # the orbit is made by all the even indices if p_i # is even, by all the odd indices if p_i is odd p_i_index = dumx[ii].index(p_i) % 2 deltap = dumx[ii][p_i_index::2] break else: deltap = [p_i] TAB1 = [] while TAB: s, d, h = TAB.pop() if min([md[h[x]] for x in deltab]) != p_i: continue deltab1 = [x for x in deltab if md[h[x]] == p_i] # NEXT = s*deltab1 intersection (d*g)**-1*deltap dg = _af_rmul(d, g) dginv = _af_invert(dg) sdeltab = [s[x] for x in deltab1] gdeltap = [dginv[x] for x in deltap] NEXT = [x for x in sdeltab if x in gdeltap] # d, s satisfy # d*g*s*base[i-1] = p_{i-1}; using the stabilizers # d*g*s*S_{base[0],...,base[i-1]}*base[i-1] = # D_{p_0,...,p_{i-1}}*p_{i-1} # so that to find d1, s1 satisfying d1*g*s1*b = p_i # one can look for dx in D_{p_0,...,p_{i-1}} and # sx in S_{base[0],...,base[i-1]} # d1 = dx*d; s1 = s*sx # d1*g*s1*b = dx*d*g*s*sx*b = p_i for j in NEXT: if testb: # solve s1*b = j with s1 = s*sx for some element sx # of the stabilizer of ..., base[i-1] # sx*b = s**-1*j; sx = _trace_S(s, j,...) # s1 = s*trace_S(s**-1*j,...) s1 = _trace_S(s, j, b, S_transversals) if not s1: continue else: s1 = [s[ix] for ix in s1] else: s1 = s # assert s1[b] == j # invariant # solve d1*g*j = p_i with d1 = dx*d for some element dg # of the stabilizer of ..., p_{i-1} # dx**-1*p_i = d*g*j; dx**-1 = trace_D(d*g*j,...) # d1 = trace_D(d*g*j,...)**-1*d # to save an inversion in the inner loop; notice we did # Dxtrav = [perm_af_invert(x) for x in Dxtrav] out of the loop if Dxtrav: d1 = _trace_D(dg[j], p_i, Dxtrav) if not d1: continue else: if p_i != dg[j]: continue d1 = idn assert d1[dg[j]] == p_i # invariant d1 = [d1[ix] for ix in d] h1 = [d1[g[ix]] for ix in s1] # assert h1[b] == p_i # invariant TAB1.append((s1, d1, h1)) # if TAB contains equal permutations, keep only one of them; # if TAB contains equal permutations up to the sign, return 0 TAB1.sort(key=lambda x: x[-1]) prev = [0] * size while TAB1: s, d, h = TAB1.pop() if h[:-2] == prev[:-2]: if h[-1] != prev[-1]: return 0 else: TAB.append((s, d, h)) prev = h # stabilize the SGS sgensx = [h for h in sgensx if h[b] == b] if b in b_S: b_S.remove(b) _dumx_remove(dumx, dumx_flat, p_i) dsgsx = [] for i in range(num_types): dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies)) return TAB[0][-1] def canonical_free(base, gens, g, num_free): """ Canonicalization of a tensor with respect to free indices choosing the minimum with respect to lexicographical ordering in the free indices. Explanation =========== ``base``, ``gens`` BSGS for slot permutation group ``g`` permutation representing the tensor ``num_free`` number of free indices The indices must be ordered with first the free indices See explanation in double_coset_can_rep The algorithm is a variation of the one given in [2]. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.tensor_can import canonical_free >>> gens = [[1, 0, 2, 3, 5, 4], [2, 3, 0, 1, 4, 5],[0, 1, 3, 2, 5, 4]] >>> gens = [Permutation(h) for h in gens] >>> base = [0, 2] >>> g = Permutation([2, 1, 0, 3, 4, 5]) >>> canonical_free(base, gens, g, 4) [0, 3, 1, 2, 5, 4] Consider the product of Riemann tensors ``T = R^{a}_{d0}^{d1,d2}*R_{d2,d1}^{d0,b}`` The order of the indices is ``[a, b, d0, -d0, d1, -d1, d2, -d2]`` The permutation corresponding to the tensor is ``g = [0, 3, 4, 6, 7, 5, 2, 1, 8, 9]`` In particular ``a`` is position ``0``, ``b`` is in position ``9``. Use the slot symmetries to get `T` is a form which is the minimal in lexicographic order in the free indices ``a`` and ``b``, e.g. ``-R^{a}_{d0}^{d1,d2}*R^{b,d0}_{d2,d1}`` corresponding to ``[0, 3, 4, 6, 1, 2, 7, 5, 9, 8]`` >>> from sympy.combinatorics.tensor_can import riemann_bsgs, tensor_gens >>> base, gens = riemann_bsgs >>> size, sbase, sgens = tensor_gens(base, gens, [[], []], 0) >>> g = Permutation([0, 3, 4, 6, 7, 5, 2, 1, 8, 9]) >>> canonical_free(sbase, [Permutation(h) for h in sgens], g, 2) [0, 3, 4, 6, 1, 2, 7, 5, 9, 8] """ g = g.array_form size = len(g) if not base: return g[:] transversals = get_transversals(base, gens) for x in sorted(g[:-2]): if x not in base: base.append(x) h = g for i, transv in enumerate(transversals): h_i = [size]*num_free # find the element s in transversals[i] such that # _af_rmul(h, s) has its free elements with the lowest position in h s = None for sk in transv.values(): h1 = _af_rmul(h, sk) hi = [h1.index(ix) for ix in range(num_free)] if hi < h_i: h_i = hi s = sk if s: h = _af_rmul(h, s) return h def _get_map_slots(size, fixed_slots): res = list(range(size)) pos = 0 for i in range(size): if i in fixed_slots: continue res[i] = pos pos += 1 return res def _lift_sgens(size, fixed_slots, free, s): a = [] j = k = 0 fd = list(zip(fixed_slots, free)) fd = [y for x, y in sorted(fd)] num_free = len(free) for i in range(size): if i in fixed_slots: a.append(fd[k]) k += 1 else: a.append(s[j] + num_free) j += 1 return a def canonicalize(g, dummies, msym, *v): """ canonicalize tensor formed by tensors Parameters ========== g : permutation representing the tensor dummies : list representing the dummy indices it can be a list of dummy indices of the same type or a list of lists of dummy indices, one list for each type of index; the dummy indices must come after the free indices, and put in order contravariant, covariant [d0, -d0, d1,-d1,...] msym : symmetry of the metric(s) it can be an integer or a list; in the first case it is the symmetry of the dummy index metric; in the second case it is the list of the symmetries of the index metric for each type v : list, (base_i, gens_i, n_i, sym_i) for tensors of type `i` base_i, gens_i : BSGS for tensors of this type. The BSGS should have minimal base under lexicographic ordering; if not, an attempt is made do get the minimal BSGS; in case of failure, canonicalize_naive is used, which is much slower. n_i : number of tensors of type `i`. sym_i : symmetry under exchange of component tensors of type `i`. Both for msym and sym_i the cases are * None no symmetry * 0 commuting * 1 anticommuting Returns ======= 0 if the tensor is zero, else return the array form of the permutation representing the canonical form of the tensor. Algorithm ========= First one uses canonical_free to get the minimum tensor under lexicographic order, using only the slot symmetries. If the component tensors have not minimal BSGS, it is attempted to find it; if the attempt fails canonicalize_naive is used instead. Compute the residual slot symmetry keeping fixed the free indices using tensor_gens(base, gens, list_free_indices, sym). Reduce the problem eliminating the free indices. Then use double_coset_can_rep and lift back the result reintroducing the free indices. Examples ======== one type of index with commuting metric; `A_{a b}` and `B_{a b}` antisymmetric and commuting `T = A_{d0 d1} * B^{d0}{}_{d2} * B^{d2 d1}` `ord = [d0,-d0,d1,-d1,d2,-d2]` order of the indices g = [1, 3, 0, 5, 4, 2, 6, 7] `T_c = 0` >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize, bsgs_direct_product >>> from sympy.combinatorics import Permutation >>> base2a, gens2a = get_symmetric_group_sgs(2, 1) >>> t0 = (base2a, gens2a, 1, 0) >>> t1 = (base2a, gens2a, 2, 0) >>> g = Permutation([1, 3, 0, 5, 4, 2, 6, 7]) >>> canonicalize(g, range(6), 0, t0, t1) 0 same as above, but with `B_{a b}` anticommuting `T_c = -A^{d0 d1} * B_{d0}{}^{d2} * B_{d1 d2}` can = [0,2,1,4,3,5,7,6] >>> t1 = (base2a, gens2a, 2, 1) >>> canonicalize(g, range(6), 0, t0, t1) [0, 2, 1, 4, 3, 5, 7, 6] two types of indices `[a,b,c,d,e,f]` and `[m,n]`, in this order, both with commuting metric `f^{a b c}` antisymmetric, commuting `A_{m a}` no symmetry, commuting `T = f^c{}_{d a} * f^f{}_{e b} * A_m{}^d * A^{m b} * A_n{}^a * A^{n e}` ord = [c,f,a,-a,b,-b,d,-d,e,-e,m,-m,n,-n] g = [0,7,3, 1,9,5, 11,6, 10,4, 13,2, 12,8, 14,15] The canonical tensor is `T_c = -f^{c a b} * f^{f d e} * A^m{}_a * A_{m d} * A^n{}_b * A_{n e}` can = [0,2,4, 1,6,8, 10,3, 11,7, 12,5, 13,9, 15,14] >>> base_f, gens_f = get_symmetric_group_sgs(3, 1) >>> base1, gens1 = get_symmetric_group_sgs(1) >>> base_A, gens_A = bsgs_direct_product(base1, gens1, base1, gens1) >>> t0 = (base_f, gens_f, 2, 0) >>> t1 = (base_A, gens_A, 4, 0) >>> dummies = [range(2, 10), range(10, 14)] >>> g = Permutation([0, 7, 3, 1, 9, 5, 11, 6, 10, 4, 13, 2, 12, 8, 14, 15]) >>> canonicalize(g, dummies, [0, 0], t0, t1) [0, 2, 4, 1, 6, 8, 10, 3, 11, 7, 12, 5, 13, 9, 15, 14] """ from sympy.combinatorics.testutil import canonicalize_naive if not isinstance(msym, list): if msym not in (0, 1, None): raise ValueError('msym must be 0, 1 or None') num_types = 1 else: num_types = len(msym) if not all(msymx in (0, 1, None) for msymx in msym): raise ValueError('msym entries must be 0, 1 or None') if len(dummies) != num_types: raise ValueError( 'dummies and msym must have the same number of elements') size = g.size num_tensors = 0 v1 = [] for base_i, gens_i, n_i, sym_i in v: # check that the BSGS is minimal; # this property is used in double_coset_can_rep; # if it is not minimal use canonicalize_naive if not _is_minimal_bsgs(base_i, gens_i): mbsgs = get_minimal_bsgs(base_i, gens_i) if not mbsgs: can = canonicalize_naive(g, dummies, msym, *v) return can base_i, gens_i = mbsgs v1.append((base_i, gens_i, [[]] * n_i, sym_i)) num_tensors += n_i if num_types == 1 and not isinstance(msym, list): dummies = [dummies] msym = [msym] flat_dummies = [] for dumx in dummies: flat_dummies.extend(dumx) if flat_dummies and flat_dummies != list(range(flat_dummies[0], flat_dummies[-1] + 1)): raise ValueError('dummies is not valid') # slot symmetry of the tensor size1, sbase, sgens = gens_products(*v1) if size != size1: raise ValueError( 'g has size %d, generators have size %d' % (size, size1)) free = [i for i in range(size - 2) if i not in flat_dummies] num_free = len(free) # g1 minimal tensor under slot symmetry g1 = canonical_free(sbase, sgens, g, num_free) if not flat_dummies: return g1 # save the sign of g1 sign = 0 if g1[-1] == size - 1 else 1 # the free indices are kept fixed. # Determine free_i, the list of slots of tensors which are fixed # since they are occupied by free indices, which are fixed. start = 0 for i, (base_i, gens_i, n_i, sym_i) in enumerate(v): free_i = [] len_tens = gens_i[0].size - 2 # for each component tensor get a list od fixed islots for j in range(n_i): # get the elements corresponding to the component tensor h = g1[start:(start + len_tens)] fr = [] # get the positions of the fixed elements in h for k in free: if k in h: fr.append(h.index(k)) free_i.append(fr) start += len_tens v1[i] = (base_i, gens_i, free_i, sym_i) # BSGS of the tensor with fixed free indices # if tensor_gens fails in gens_product, use canonicalize_naive size, sbase, sgens = gens_products(*v1) # reduce the permutations getting rid of the free indices pos_free = [g1.index(x) for x in range(num_free)] size_red = size - num_free g1_red = [x - num_free for x in g1 if x in flat_dummies] if sign: g1_red.extend([size_red - 1, size_red - 2]) else: g1_red.extend([size_red - 2, size_red - 1]) map_slots = _get_map_slots(size, pos_free) sbase_red = [map_slots[i] for i in sbase if i not in pos_free] sgens_red = [_af_new([map_slots[i] for i in y._array_form if i not in pos_free]) for y in sgens] dummies_red = [[x - num_free for x in y] for y in dummies] transv_red = get_transversals(sbase_red, sgens_red) g1_red = _af_new(g1_red) g2 = double_coset_can_rep( dummies_red, msym, sbase_red, sgens_red, transv_red, g1_red) if g2 == 0: return 0 # lift to the case with the free indices g3 = _lift_sgens(size, pos_free, free, g2) return g3 def perm_af_direct_product(gens1, gens2, signed=True): """ Direct products of the generators gens1 and gens2. Examples ======== >>> from sympy.combinatorics.tensor_can import perm_af_direct_product >>> gens1 = [[1, 0, 2, 3], [0, 1, 3, 2]] >>> gens2 = [[1, 0]] >>> perm_af_direct_product(gens1, gens2, False) [[1, 0, 2, 3, 4, 5], [0, 1, 3, 2, 4, 5], [0, 1, 2, 3, 5, 4]] >>> gens1 = [[1, 0, 2, 3, 5, 4], [0, 1, 3, 2, 4, 5]] >>> gens2 = [[1, 0, 2, 3]] >>> perm_af_direct_product(gens1, gens2, True) [[1, 0, 2, 3, 4, 5, 7, 6], [0, 1, 3, 2, 4, 5, 6, 7], [0, 1, 2, 3, 5, 4, 6, 7]] """ gens1 = [list(x) for x in gens1] gens2 = [list(x) for x in gens2] s = 2 if signed else 0 n1 = len(gens1[0]) - s n2 = len(gens2[0]) - s start = list(range(n1)) end = list(range(n1, n1 + n2)) if signed: gens1 = [gen[:-2] + end + [gen[-2] + n2, gen[-1] + n2] for gen in gens1] gens2 = [start + [x + n1 for x in gen] for gen in gens2] else: gens1 = [gen + end for gen in gens1] gens2 = [start + [x + n1 for x in gen] for gen in gens2] res = gens1 + gens2 return res def bsgs_direct_product(base1, gens1, base2, gens2, signed=True): """ Direct product of two BSGS. Parameters ========== base1 : base of the first BSGS. gens1 : strong generating sequence of the first BSGS. base2, gens2 : similarly for the second BSGS. signed : flag for signed permutations. Examples ======== >>> from sympy.combinatorics.tensor_can import (get_symmetric_group_sgs, bsgs_direct_product) >>> base1, gens1 = get_symmetric_group_sgs(1) >>> base2, gens2 = get_symmetric_group_sgs(2) >>> bsgs_direct_product(base1, gens1, base2, gens2) ([1], [(4)(1 2)]) """ s = 2 if signed else 0 n1 = gens1[0].size - s base = list(base1) base += [x + n1 for x in base2] gens1 = [h._array_form for h in gens1] gens2 = [h._array_form for h in gens2] gens = perm_af_direct_product(gens1, gens2, signed) size = len(gens[0]) id_af = list(range(size)) gens = [h for h in gens if h != id_af] if not gens: gens = [id_af] return base, [_af_new(h) for h in gens] def get_symmetric_group_sgs(n, antisym=False): """ Return base, gens of the minimal BSGS for (anti)symmetric tensor Parameters ========== n : rank of the tensor antisym : bool ``antisym = False`` symmetric tensor ``antisym = True`` antisymmetric tensor Examples ======== >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs >>> get_symmetric_group_sgs(3) ([0, 1], [(4)(0 1), (4)(1 2)]) """ if n == 1: return [], [_af_new(list(range(3)))] gens = [Permutation(n - 1)(i, i + 1)._array_form for i in range(n - 1)] if antisym == 0: gens = [x + [n, n + 1] for x in gens] else: gens = [x + [n + 1, n] for x in gens] base = list(range(n - 1)) return base, [_af_new(h) for h in gens] riemann_bsgs = [0, 2], [Permutation(0, 1)(4, 5), Permutation(2, 3)(4, 5), Permutation(5)(0, 2)(1, 3)] def get_transversals(base, gens): """ Return transversals for the group with BSGS base, gens """ if not base: return [] stabs = _distribute_gens_by_base(base, gens) orbits, transversals = _orbits_transversals_from_bsgs(base, stabs) transversals = [{x: h._array_form for x, h in y.items()} for y in transversals] return transversals def _is_minimal_bsgs(base, gens): """ Check if the BSGS has minimal base under lexigographic order. base, gens BSGS Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.tensor_can import riemann_bsgs, _is_minimal_bsgs >>> _is_minimal_bsgs(*riemann_bsgs) True >>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)])) >>> _is_minimal_bsgs(*riemann_bsgs1) False """ base1 = [] sgs1 = gens[:] size = gens[0].size for i in range(size): if not all(h._array_form[i] == i for h in sgs1): base1.append(i) sgs1 = [h for h in sgs1 if h._array_form[i] == i] return base1 == base def get_minimal_bsgs(base, gens): """ Compute a minimal GSGS base, gens BSGS If base, gens is a minimal BSGS return it; else return a minimal BSGS if it fails in finding one, it returns None TODO: use baseswap in the case in which if it fails in finding a minimal BSGS Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.tensor_can import get_minimal_bsgs >>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)])) >>> get_minimal_bsgs(*riemann_bsgs1) ([0, 2], [(0 1)(4 5), (5)(0 2)(1 3), (2 3)(4 5)]) """ G = PermutationGroup(gens) base, gens = G.schreier_sims_incremental() if not _is_minimal_bsgs(base, gens): return None return base, gens def tensor_gens(base, gens, list_free_indices, sym=0): """ Returns size, res_base, res_gens BSGS for n tensors of the same type. Explanation =========== base, gens BSGS for tensors of this type list_free_indices list of the slots occupied by fixed indices for each of the tensors sym symmetry under commutation of two tensors sym None no symmetry sym 0 commuting sym 1 anticommuting Examples ======== >>> from sympy.combinatorics.tensor_can import tensor_gens, get_symmetric_group_sgs two symmetric tensors with 3 indices without free indices >>> base, gens = get_symmetric_group_sgs(3) >>> tensor_gens(base, gens, [[], []]) (8, [0, 1, 3, 4], [(7)(0 1), (7)(1 2), (7)(3 4), (7)(4 5), (7)(0 3)(1 4)(2 5)]) two symmetric tensors with 3 indices with free indices in slot 1 and 0 >>> tensor_gens(base, gens, [[1], [0]]) (8, [0, 4], [(7)(0 2), (7)(4 5)]) four symmetric tensors with 3 indices, two of which with free indices """ def _get_bsgs(G, base, gens, free_indices): """ return the BSGS for G.pointwise_stabilizer(free_indices) """ if not free_indices: return base[:], gens[:] else: H = G.pointwise_stabilizer(free_indices) base, sgs = H.schreier_sims_incremental() return base, sgs # if not base there is no slot symmetry for the component tensors # if list_free_indices.count([]) < 2 there is no commutation symmetry # so there is no resulting slot symmetry if not base and list_free_indices.count([]) < 2: n = len(list_free_indices) size = gens[0].size size = n * (size - 2) + 2 return size, [], [_af_new(list(range(size)))] # if any(list_free_indices) one needs to compute the pointwise # stabilizer, so G is needed if any(list_free_indices): G = PermutationGroup(gens) else: G = None # no_free list of lists of indices for component tensors without fixed # indices no_free = [] size = gens[0].size id_af = list(range(size)) num_indices = size - 2 if not list_free_indices[0]: no_free.append(list(range(num_indices))) res_base, res_gens = _get_bsgs(G, base, gens, list_free_indices[0]) for i in range(1, len(list_free_indices)): base1, gens1 = _get_bsgs(G, base, gens, list_free_indices[i]) res_base, res_gens = bsgs_direct_product(res_base, res_gens, base1, gens1, 1) if not list_free_indices[i]: no_free.append(list(range(size - 2, size - 2 + num_indices))) size += num_indices nr = size - 2 res_gens = [h for h in res_gens if h._array_form != id_af] # if sym there are no commuting tensors stop here if sym is None or not no_free: if not res_gens: res_gens = [_af_new(id_af)] return size, res_base, res_gens # if the component tensors have moinimal BSGS, so is their direct # product P; the slot symmetry group is S = P*C, where C is the group # to (anti)commute the component tensors with no free indices # a stabilizer has the property S_i = P_i*C_i; # the BSGS of P*C has SGS_P + SGS_C and the base is # the ordered union of the bases of P and C. # If P has minimal BSGS, so has S with this base. base_comm = [] for i in range(len(no_free) - 1): ind1 = no_free[i] ind2 = no_free[i + 1] a = list(range(ind1[0])) a.extend(ind2) a.extend(ind1) base_comm.append(ind1[0]) a.extend(list(range(ind2[-1] + 1, nr))) if sym == 0: a.extend([nr, nr + 1]) else: a.extend([nr + 1, nr]) res_gens.append(_af_new(a)) res_base = list(res_base) # each base is ordered; order the union of the two bases for i in base_comm: if i not in res_base: res_base.append(i) res_base.sort() if not res_gens: res_gens = [_af_new(id_af)] return size, res_base, res_gens def gens_products(*v): """ Returns size, res_base, res_gens BSGS for n tensors of different types. Explanation =========== v is a sequence of (base_i, gens_i, free_i, sym_i) where base_i, gens_i BSGS of tensor of type `i` free_i list of the fixed slots for each of the tensors of type `i`; if there are `n_i` tensors of type `i` and none of them have fixed slots, `free = [[]]*n_i` sym 0 (1) if the tensors of type `i` (anti)commute among themselves Examples ======== >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, gens_products >>> base, gens = get_symmetric_group_sgs(2) >>> gens_products((base, gens, [[], []], 0)) (6, [0, 2], [(5)(0 1), (5)(2 3), (5)(0 2)(1 3)]) >>> gens_products((base, gens, [[1], []], 0)) (6, [2], [(5)(2 3)]) """ res_size, res_base, res_gens = tensor_gens(*v[0]) for i in range(1, len(v)): size, base, gens = tensor_gens(*v[i]) res_base, res_gens = bsgs_direct_product(res_base, res_gens, base, gens, 1) res_size = res_gens[0].size id_af = list(range(res_size)) res_gens = [h for h in res_gens if h != id_af] if not res_gens: res_gens = [id_af] return res_size, res_base, res_gens
2113822cceb7a780136b35ac2bda91c66c7c6d98e83215b13ab4e6d10e51469a
from sympy.ntheory.primetest import isprime from sympy.combinatorics.perm_groups import PermutationGroup from sympy.printing.defaults import DefaultPrinting from sympy.combinatorics.free_groups import free_group class PolycyclicGroup(DefaultPrinting): is_group = True is_solvable = True def __init__(self, pc_sequence, pc_series, relative_order, collector=None): """ Parameters ========== pc_sequence : list A sequence of elements whose classes generate the cyclic factor groups of pc_series. pc_series : list A subnormal sequence of subgroups where each factor group is cyclic. relative_order : list The orders of factor groups of pc_series. collector : Collector By default, it is None. Collector class provides the polycyclic presentation with various other functionalities. """ self.pcgs = pc_sequence self.pc_series = pc_series self.relative_order = relative_order self.collector = Collector(self.pcgs, pc_series, relative_order) if not collector else collector def is_prime_order(self): return all(isprime(order) for order in self.relative_order) def length(self): return len(self.pcgs) class Collector(DefaultPrinting): """ References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" Section 8.1.3 """ def __init__(self, pcgs, pc_series, relative_order, free_group_=None, pc_presentation=None): """ Most of the parameters for the Collector class are the same as for PolycyclicGroup. Others are described below. Parameters ========== free_group_ : tuple free_group_ provides the mapping of polycyclic generating sequence with the free group elements. pc_presentation : dict Provides the presentation of polycyclic groups with the help of power and conjugate relators. See Also ======== PolycyclicGroup """ self.pcgs = pcgs self.pc_series = pc_series self.relative_order = relative_order self.free_group = free_group('x:{}'.format(len(pcgs)))[0] if not free_group_ else free_group_ self.index = {s: i for i, s in enumerate(self.free_group.symbols)} self.pc_presentation = self.pc_relators() def minimal_uncollected_subword(self, word): r""" Returns the minimal uncollected subwords. Explanation =========== A word ``v`` defined on generators in ``X`` is a minimal uncollected subword of the word ``w`` if ``v`` is a subword of ``w`` and it has one of the following form * `v = {x_{i+1}}^{a_j}x_i` * `v = {x_{i+1}}^{a_j}{x_i}^{-1}` * `v = {x_i}^{a_j}` for `a_j` not in `\{1, \ldots, s-1\}`. Where, ``s`` is the power exponent of the corresponding generator. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics import free_group >>> G = SymmetricGroup(4) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> F, x1, x2 = free_group("x1, x2") >>> word = x2**2*x1**7 >>> collector.minimal_uncollected_subword(word) ((x2, 2),) """ # To handle the case word = <identity> if not word: return None array = word.array_form re = self.relative_order index = self.index for i in range(len(array)): s1, e1 = array[i] if re[index[s1]] and (e1 < 0 or e1 > re[index[s1]]-1): return ((s1, e1), ) for i in range(len(array)-1): s1, e1 = array[i] s2, e2 = array[i+1] if index[s1] > index[s2]: e = 1 if e2 > 0 else -1 return ((s1, e1), (s2, e)) return None def relations(self): """ Separates the given relators of pc presentation in power and conjugate relations. Returns ======= (power_rel, conj_rel) Separates pc presentation into power and conjugate relations. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> G = SymmetricGroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> power_rel, conj_rel = collector.relations() >>> power_rel {x0**2: (), x1**3: ()} >>> conj_rel {x0**-1*x1*x0: x1**2} See Also ======== pc_relators """ power_relators = {} conjugate_relators = {} for key, value in self.pc_presentation.items(): if len(key.array_form) == 1: power_relators[key] = value else: conjugate_relators[key] = value return power_relators, conjugate_relators def subword_index(self, word, w): """ Returns the start and ending index of a given subword in a word. Parameters ========== word : FreeGroupElement word defined on free group elements for a polycyclic group. w : FreeGroupElement subword of a given word, whose starting and ending index to be computed. Returns ======= (i, j) A tuple containing starting and ending index of ``w`` in the given word. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics import free_group >>> G = SymmetricGroup(4) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> F, x1, x2 = free_group("x1, x2") >>> word = x2**2*x1**7 >>> w = x2**2*x1 >>> collector.subword_index(word, w) (0, 3) >>> w = x1**7 >>> collector.subword_index(word, w) (2, 9) """ low = -1 high = -1 for i in range(len(word)-len(w)+1): if word.subword(i, i+len(w)) == w: low = i high = i+len(w) break if low == high == -1: return -1, -1 return low, high def map_relation(self, w): """ Return a conjugate relation. Explanation =========== Given a word formed by two free group elements, the corresponding conjugate relation with those free group elements is formed and mapped with the collected word in the polycyclic presentation. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics import free_group >>> G = SymmetricGroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> F, x0, x1 = free_group("x0, x1") >>> w = x1*x0 >>> collector.map_relation(w) x1**2 See Also ======== pc_presentation """ array = w.array_form s1 = array[0][0] s2 = array[1][0] key = ((s2, -1), (s1, 1), (s2, 1)) key = self.free_group.dtype(key) return self.pc_presentation[key] def collected_word(self, word): r""" Return the collected form of a word. Explanation =========== A word ``w`` is called collected, if `w = {x_{i_1}}^{a_1} * \ldots * {x_{i_r}}^{a_r}` with `i_1 < i_2< \ldots < i_r` and `a_j` is in `\{1, \ldots, {s_j}-1\}`. Otherwise w is uncollected. Parameters ========== word : FreeGroupElement An uncollected word. Returns ======= word A collected word of form `w = {x_{i_1}}^{a_1}, \ldots, {x_{i_r}}^{a_r}` with `i_1, i_2, \ldots, i_r` and `a_j \in \{1, \ldots, {s_j}-1\}`. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics import free_group >>> G = SymmetricGroup(4) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> F, x0, x1, x2, x3 = free_group("x0, x1, x2, x3") >>> word = x3*x2*x1*x0 >>> collected_word = collector.collected_word(word) >>> free_to_perm = {} >>> free_group = collector.free_group >>> for sym, gen in zip(free_group.symbols, collector.pcgs): ... free_to_perm[sym] = gen >>> G1 = PermutationGroup() >>> for w in word: ... sym = w[0] ... perm = free_to_perm[sym] ... G1 = PermutationGroup([perm] + G1.generators) >>> G2 = PermutationGroup() >>> for w in collected_word: ... sym = w[0] ... perm = free_to_perm[sym] ... G2 = PermutationGroup([perm] + G2.generators) The two are not identical, but they are equivalent: >>> G1.equals(G2), G1 == G2 (True, False) See Also ======== minimal_uncollected_subword """ free_group = self.free_group while True: w = self.minimal_uncollected_subword(word) if not w: break low, high = self.subword_index(word, free_group.dtype(w)) if low == -1: continue s1, e1 = w[0] if len(w) == 1: re = self.relative_order[self.index[s1]] q = e1 // re r = e1-q*re key = ((w[0][0], re), ) key = free_group.dtype(key) if self.pc_presentation[key]: presentation = self.pc_presentation[key].array_form sym, exp = presentation[0] word_ = ((w[0][0], r), (sym, q*exp)) word_ = free_group.dtype(word_) else: if r != 0: word_ = ((w[0][0], r), ) word_ = free_group.dtype(word_) else: word_ = None word = word.eliminate_word(free_group.dtype(w), word_) if len(w) == 2 and w[1][1] > 0: s2, e2 = w[1] s2 = ((s2, 1), ) s2 = free_group.dtype(s2) word_ = self.map_relation(free_group.dtype(w)) word_ = s2*word_**e1 word_ = free_group.dtype(word_) word = word.substituted_word(low, high, word_) elif len(w) == 2 and w[1][1] < 0: s2, e2 = w[1] s2 = ((s2, 1), ) s2 = free_group.dtype(s2) word_ = self.map_relation(free_group.dtype(w)) word_ = s2**-1*word_**e1 word_ = free_group.dtype(word_) word = word.substituted_word(low, high, word_) return word def pc_relators(self): r""" Return the polycyclic presentation. Explanation =========== There are two types of relations used in polycyclic presentation. * Power relations : Power relators are of the form `x_i^{re_i}`, where `i \in \{0, \ldots, \mathrm{len(pcgs)}\}`, ``x`` represents polycyclic generator and ``re`` is the corresponding relative order. * Conjugate relations : Conjugate relators are of the form `x_j^-1x_ix_j`, where `j < i \in \{0, \ldots, \mathrm{len(pcgs)}\}`. Returns ======= A dictionary with power and conjugate relations as key and their collected form as corresponding values. Notes ===== Identity Permutation is mapped with empty ``()``. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.permutations import Permutation >>> S = SymmetricGroup(49).sylow_subgroup(7) >>> der = S.derived_series() >>> G = der[len(der)-2] >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> pcgs = PcGroup.pcgs >>> len(pcgs) 6 >>> free_group = collector.free_group >>> pc_resentation = collector.pc_presentation >>> free_to_perm = {} >>> for s, g in zip(free_group.symbols, pcgs): ... free_to_perm[s] = g >>> for k, v in pc_resentation.items(): ... k_array = k.array_form ... if v != (): ... v_array = v.array_form ... lhs = Permutation() ... for gen in k_array: ... s = gen[0] ... e = gen[1] ... lhs = lhs*free_to_perm[s]**e ... if v == (): ... assert lhs.is_identity ... continue ... rhs = Permutation() ... for gen in v_array: ... s = gen[0] ... e = gen[1] ... rhs = rhs*free_to_perm[s]**e ... assert lhs == rhs """ free_group = self.free_group rel_order = self.relative_order pc_relators = {} perm_to_free = {} pcgs = self.pcgs for gen, s in zip(pcgs, free_group.generators): perm_to_free[gen**-1] = s**-1 perm_to_free[gen] = s pcgs = pcgs[::-1] series = self.pc_series[::-1] rel_order = rel_order[::-1] collected_gens = [] for i, gen in enumerate(pcgs): re = rel_order[i] relation = perm_to_free[gen]**re G = series[i] l = G.generator_product(gen**re, original = True) l.reverse() word = free_group.identity for g in l: word = word*perm_to_free[g] word = self.collected_word(word) pc_relators[relation] = word if word else () self.pc_presentation = pc_relators collected_gens.append(gen) if len(collected_gens) > 1: conj = collected_gens[len(collected_gens)-1] conjugator = perm_to_free[conj] for j in range(len(collected_gens)-1): conjugated = perm_to_free[collected_gens[j]] relation = conjugator**-1*conjugated*conjugator gens = conj**-1*collected_gens[j]*conj l = G.generator_product(gens, original = True) l.reverse() word = free_group.identity for g in l: word = word*perm_to_free[g] word = self.collected_word(word) pc_relators[relation] = word if word else () self.pc_presentation = pc_relators return pc_relators def exponent_vector(self, element): r""" Return the exponent vector of length equal to the length of polycyclic generating sequence. Explanation =========== For a given generator/element ``g`` of the polycyclic group, it can be represented as `g = {x_1}^{e_1}, \ldots, {x_n}^{e_n}`, where `x_i` represents polycyclic generators and ``n`` is the number of generators in the free_group equal to the length of pcgs. Parameters ========== element : Permutation Generator of a polycyclic group. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.permutations import Permutation >>> G = SymmetricGroup(4) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> pcgs = PcGroup.pcgs >>> collector.exponent_vector(G[0]) [1, 0, 0, 0] >>> exp = collector.exponent_vector(G[1]) >>> g = Permutation() >>> for i in range(len(exp)): ... g = g*pcgs[i]**exp[i] if exp[i] else g >>> assert g == G[1] References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" Section 8.1.1, Definition 8.4 """ free_group = self.free_group G = PermutationGroup() for g in self.pcgs: G = PermutationGroup([g] + G.generators) gens = G.generator_product(element, original = True) gens.reverse() perm_to_free = {} for sym, g in zip(free_group.generators, self.pcgs): perm_to_free[g**-1] = sym**-1 perm_to_free[g] = sym w = free_group.identity for g in gens: w = w*perm_to_free[g] word = self.collected_word(w) index = self.index exp_vector = [0]*len(free_group) word = word.array_form for t in word: exp_vector[index[t[0]]] = t[1] return exp_vector def depth(self, element): r""" Return the depth of a given element. Explanation =========== The depth of a given element ``g`` is defined by `\mathrm{dep}[g] = i` if `e_1 = e_2 = \ldots = e_{i-1} = 0` and `e_i != 0`, where ``e`` represents the exponent-vector. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> G = SymmetricGroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> collector.depth(G[0]) 2 >>> collector.depth(G[1]) 1 References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" Section 8.1.1, Definition 8.5 """ exp_vector = self.exponent_vector(element) return next((i+1 for i, x in enumerate(exp_vector) if x), len(self.pcgs)+1) def leading_exponent(self, element): r""" Return the leading non-zero exponent. Explanation =========== The leading exponent for a given element `g` is defined by `\mathrm{leading\_exponent}[g]` `= e_i`, if `\mathrm{depth}[g] = i`. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> G = SymmetricGroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> collector.leading_exponent(G[1]) 1 """ exp_vector = self.exponent_vector(element) depth = self.depth(element) if depth != len(self.pcgs)+1: return exp_vector[depth-1] return None def _sift(self, z, g): h = g d = self.depth(h) while d < len(self.pcgs) and z[d-1] != 1: k = z[d-1] e = self.leading_exponent(h)*(self.leading_exponent(k))**-1 e = e % self.relative_order[d-1] h = k**-e*h d = self.depth(h) return h def induced_pcgs(self, gens): """ Parameters ========== gens : list A list of generators on which polycyclic subgroup is to be defined. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(8) >>> G = S.sylow_subgroup(2) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> gens = [G[0], G[1]] >>> ipcgs = collector.induced_pcgs(gens) >>> [gen.order() for gen in ipcgs] [2, 2, 2] >>> G = S.sylow_subgroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> gens = [G[0], G[1]] >>> ipcgs = collector.induced_pcgs(gens) >>> [gen.order() for gen in ipcgs] [3] """ z = [1]*len(self.pcgs) G = gens while G: g = G.pop(0) h = self._sift(z, g) d = self.depth(h) if d < len(self.pcgs): for gen in z: if gen != 1: G.append(h**-1*gen**-1*h*gen) z[d-1] = h; z = [gen for gen in z if gen != 1] return z def constructive_membership_test(self, ipcgs, g): """ Return the exponent vector for induced pcgs. """ e = [0]*len(ipcgs) h = g d = self.depth(h) for i, gen in enumerate(ipcgs): while self.depth(gen) == d: f = self.leading_exponent(h)*self.leading_exponent(gen) f = f % self.relative_order[d-1] h = gen**(-f)*h e[i] = f d = self.depth(h) if h == 1: return e return False
2c8bbff3ffd128cbfc11f5c07e4af4f1429848cab98462412c7c83492e6777ef
from sympy.combinatorics.permutations import Permutation, _af_invert, _af_rmul from sympy.ntheory import isprime rmul = Permutation.rmul _af_new = Permutation._af_new ############################################ # # Utilities for computational group theory # ############################################ def _base_ordering(base, degree): r""" Order `\{0, 1, \dots, n-1\}` so that base points come first and in order. Parameters ========== base : the base degree : the degree of the associated permutation group Returns ======= A list ``base_ordering`` such that ``base_ordering[point]`` is the number of ``point`` in the ordering. Examples ======== >>> from sympy.combinatorics import SymmetricGroup >>> from sympy.combinatorics.util import _base_ordering >>> S = SymmetricGroup(4) >>> S.schreier_sims() >>> _base_ordering(S.base, S.degree) [0, 1, 2, 3] Notes ===== This is used in backtrack searches, when we define a relation `\ll` on the underlying set for a permutation group of degree `n`, `\{0, 1, \dots, n-1\}`, so that if `(b_1, b_2, \dots, b_k)` is a base we have `b_i \ll b_j` whenever `i<j` and `b_i \ll a` for all `i\in\{1,2, \dots, k\}` and `a` is not in the base. The idea is developed and applied to backtracking algorithms in [1], pp.108-132. The points that are not in the base are taken in increasing order. References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" """ base_len = len(base) ordering = [0]*degree for i in range(base_len): ordering[base[i]] = i current = base_len for i in range(degree): if i not in base: ordering[i] = current current += 1 return ordering def _check_cycles_alt_sym(perm): """ Checks for cycles of prime length p with n/2 < p < n-2. Explanation =========== Here `n` is the degree of the permutation. This is a helper function for the function is_alt_sym from sympy.combinatorics.perm_groups. Examples ======== >>> from sympy.combinatorics.util import _check_cycles_alt_sym >>> from sympy.combinatorics import Permutation >>> a = Permutation([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12]]) >>> _check_cycles_alt_sym(a) False >>> b = Permutation([[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10]]) >>> _check_cycles_alt_sym(b) True See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.is_alt_sym """ n = perm.size af = perm.array_form current_len = 0 total_len = 0 used = set() for i in range(n//2): if i not in used and i < n//2 - total_len: current_len = 1 used.add(i) j = i while af[j] != i: current_len += 1 j = af[j] used.add(j) total_len += current_len if current_len > n//2 and current_len < n - 2 and isprime(current_len): return True return False def _distribute_gens_by_base(base, gens): r""" Distribute the group elements ``gens`` by membership in basic stabilizers. Explanation =========== Notice that for a base `(b_1, b_2, \dots, b_k)`, the basic stabilizers are defined as `G^{(i)} = G_{b_1, \dots, b_{i-1}}` for `i \in\{1, 2, \dots, k\}`. Parameters ========== base : a sequence of points in `\{0, 1, \dots, n-1\}` gens : a list of elements of a permutation group of degree `n`. Returns ======= List of length `k`, where `k` is the length of ``base``. The `i`-th entry contains those elements in ``gens`` which fix the first `i` elements of ``base`` (so that the `0`-th entry is equal to ``gens`` itself). If no element fixes the first `i` elements of ``base``, the `i`-th element is set to a list containing the identity element. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> from sympy.combinatorics.util import _distribute_gens_by_base >>> D = DihedralGroup(3) >>> D.schreier_sims() >>> D.strong_gens [(0 1 2), (0 2), (1 2)] >>> D.base [0, 1] >>> _distribute_gens_by_base(D.base, D.strong_gens) [[(0 1 2), (0 2), (1 2)], [(1 2)]] See Also ======== _strong_gens_from_distr, _orbits_transversals_from_bsgs, _handle_precomputed_bsgs """ base_len = len(base) degree = gens[0].size stabs = [[] for _ in range(base_len)] max_stab_index = 0 for gen in gens: j = 0 while j < base_len - 1 and gen._array_form[base[j]] == base[j]: j += 1 if j > max_stab_index: max_stab_index = j for k in range(j + 1): stabs[k].append(gen) for i in range(max_stab_index + 1, base_len): stabs[i].append(_af_new(list(range(degree)))) return stabs def _handle_precomputed_bsgs(base, strong_gens, transversals=None, basic_orbits=None, strong_gens_distr=None): """ Calculate BSGS-related structures from those present. Explanation =========== The base and strong generating set must be provided; if any of the transversals, basic orbits or distributed strong generators are not provided, they will be calculated from the base and strong generating set. Parameters ========== ``base`` - the base ``strong_gens`` - the strong generators ``transversals`` - basic transversals ``basic_orbits`` - basic orbits ``strong_gens_distr`` - strong generators distributed by membership in basic stabilizers Returns ======= ``(transversals, basic_orbits, strong_gens_distr)`` where ``transversals`` are the basic transversals, ``basic_orbits`` are the basic orbits, and ``strong_gens_distr`` are the strong generators distributed by membership in basic stabilizers. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> from sympy.combinatorics.util import _handle_precomputed_bsgs >>> D = DihedralGroup(3) >>> D.schreier_sims() >>> _handle_precomputed_bsgs(D.base, D.strong_gens, ... basic_orbits=D.basic_orbits) ([{0: (2), 1: (0 1 2), 2: (0 2)}, {1: (2), 2: (1 2)}], [[0, 1, 2], [1, 2]], [[(0 1 2), (0 2), (1 2)], [(1 2)]]) See Also ======== _orbits_transversals_from_bsgs, _distribute_gens_by_base """ if strong_gens_distr is None: strong_gens_distr = _distribute_gens_by_base(base, strong_gens) if transversals is None: if basic_orbits is None: basic_orbits, transversals = \ _orbits_transversals_from_bsgs(base, strong_gens_distr) else: transversals = \ _orbits_transversals_from_bsgs(base, strong_gens_distr, transversals_only=True) else: if basic_orbits is None: base_len = len(base) basic_orbits = [None]*base_len for i in range(base_len): basic_orbits[i] = list(transversals[i].keys()) return transversals, basic_orbits, strong_gens_distr def _orbits_transversals_from_bsgs(base, strong_gens_distr, transversals_only=False, slp=False): """ Compute basic orbits and transversals from a base and strong generating set. Explanation =========== The generators are provided as distributed across the basic stabilizers. If the optional argument ``transversals_only`` is set to True, only the transversals are returned. Parameters ========== ``base`` - The base. ``strong_gens_distr`` - Strong generators distributed by membership in basic stabilizers. ``transversals_only`` - bool A flag switching between returning only the transversals and both orbits and transversals. ``slp`` - If ``True``, return a list of dictionaries containing the generator presentations of the elements of the transversals, i.e. the list of indices of generators from ``strong_gens_distr[i]`` such that their product is the relevant transversal element. Examples ======== >>> from sympy.combinatorics import SymmetricGroup >>> from sympy.combinatorics.util import _distribute_gens_by_base >>> S = SymmetricGroup(3) >>> S.schreier_sims() >>> strong_gens_distr = _distribute_gens_by_base(S.base, S.strong_gens) >>> (S.base, strong_gens_distr) ([0, 1], [[(0 1 2), (2)(0 1), (1 2)], [(1 2)]]) See Also ======== _distribute_gens_by_base, _handle_precomputed_bsgs """ from sympy.combinatorics.perm_groups import _orbit_transversal base_len = len(base) degree = strong_gens_distr[0][0].size transversals = [None]*base_len slps = [None]*base_len if transversals_only is False: basic_orbits = [None]*base_len for i in range(base_len): transversals[i], slps[i] = _orbit_transversal(degree, strong_gens_distr[i], base[i], pairs=True, slp=True) transversals[i] = dict(transversals[i]) if transversals_only is False: basic_orbits[i] = list(transversals[i].keys()) if transversals_only: return transversals else: if not slp: return basic_orbits, transversals return basic_orbits, transversals, slps def _remove_gens(base, strong_gens, basic_orbits=None, strong_gens_distr=None): """ Remove redundant generators from a strong generating set. Parameters ========== ``base`` - a base ``strong_gens`` - a strong generating set relative to ``base`` ``basic_orbits`` - basic orbits ``strong_gens_distr`` - strong generators distributed by membership in basic stabilizers Returns ======= A strong generating set with respect to ``base`` which is a subset of ``strong_gens``. Examples ======== >>> from sympy.combinatorics import SymmetricGroup >>> from sympy.combinatorics.util import _remove_gens >>> from sympy.combinatorics.testutil import _verify_bsgs >>> S = SymmetricGroup(15) >>> base, strong_gens = S.schreier_sims_incremental() >>> new_gens = _remove_gens(base, strong_gens) >>> len(new_gens) 14 >>> _verify_bsgs(S, base, new_gens) True Notes ===== This procedure is outlined in [1],p.95. References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" """ from sympy.combinatorics.perm_groups import _orbit base_len = len(base) degree = strong_gens[0].size if strong_gens_distr is None: strong_gens_distr = _distribute_gens_by_base(base, strong_gens) if basic_orbits is None: basic_orbits = [] for i in range(base_len): basic_orbit = _orbit(degree, strong_gens_distr[i], base[i]) basic_orbits.append(basic_orbit) strong_gens_distr.append([]) res = strong_gens[:] for i in range(base_len - 1, -1, -1): gens_copy = strong_gens_distr[i][:] for gen in strong_gens_distr[i]: if gen not in strong_gens_distr[i + 1]: temp_gens = gens_copy[:] temp_gens.remove(gen) if temp_gens == []: continue temp_orbit = _orbit(degree, temp_gens, base[i]) if temp_orbit == basic_orbits[i]: gens_copy.remove(gen) res.remove(gen) return res def _strip(g, base, orbits, transversals): """ Attempt to decompose a permutation using a (possibly partial) BSGS structure. Explanation =========== This is done by treating the sequence ``base`` as an actual base, and the orbits ``orbits`` and transversals ``transversals`` as basic orbits and transversals relative to it. This process is called "sifting". A sift is unsuccessful when a certain orbit element is not found or when after the sift the decomposition does not end with the identity element. The argument ``transversals`` is a list of dictionaries that provides transversal elements for the orbits ``orbits``. Parameters ========== ``g`` - permutation to be decomposed ``base`` - sequence of points ``orbits`` - a list in which the ``i``-th entry is an orbit of ``base[i]`` under some subgroup of the pointwise stabilizer of ` `base[0], base[1], ..., base[i - 1]``. The groups themselves are implicit in this function since the only information we need is encoded in the orbits and transversals ``transversals`` - a list of orbit transversals associated with the orbits ``orbits``. Examples ======== >>> from sympy.combinatorics import Permutation, SymmetricGroup >>> from sympy.combinatorics.util import _strip >>> S = SymmetricGroup(5) >>> S.schreier_sims() >>> g = Permutation([0, 2, 3, 1, 4]) >>> _strip(g, S.base, S.basic_orbits, S.basic_transversals) ((4), 5) Notes ===== The algorithm is described in [1],pp.89-90. The reason for returning both the current state of the element being decomposed and the level at which the sifting ends is that they provide important information for the randomized version of the Schreier-Sims algorithm. References ========== .. [1] Holt, D., Eick, B., O'Brien, E."Handbook of computational group theory" See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims_random """ h = g._array_form base_len = len(base) for i in range(base_len): beta = h[base[i]] if beta == base[i]: continue if beta not in orbits[i]: return _af_new(h), i + 1 u = transversals[i][beta]._array_form h = _af_rmul(_af_invert(u), h) return _af_new(h), base_len + 1 def _strip_af(h, base, orbits, transversals, j, slp=[], slps={}): """ optimized _strip, with h, transversals and result in array form if the stripped elements is the identity, it returns False, base_len + 1 j h[base[i]] == base[i] for i <= j """ base_len = len(base) for i in range(j+1, base_len): beta = h[base[i]] if beta == base[i]: continue if beta not in orbits[i]: if not slp: return h, i + 1 return h, i + 1, slp u = transversals[i][beta] if h == u: if not slp: return False, base_len + 1 return False, base_len + 1, slp h = _af_rmul(_af_invert(u), h) if slp: u_slp = slps[i][beta][:] u_slp.reverse() u_slp = [(i, (g,)) for g in u_slp] slp = u_slp + slp if not slp: return h, base_len + 1 return h, base_len + 1, slp def _strong_gens_from_distr(strong_gens_distr): """ Retrieve strong generating set from generators of basic stabilizers. This is just the union of the generators of the first and second basic stabilizers. Parameters ========== ``strong_gens_distr`` - strong generators distributed by membership in basic stabilizers Examples ======== >>> from sympy.combinatorics import SymmetricGroup >>> from sympy.combinatorics.util import (_strong_gens_from_distr, ... _distribute_gens_by_base) >>> S = SymmetricGroup(3) >>> S.schreier_sims() >>> S.strong_gens [(0 1 2), (2)(0 1), (1 2)] >>> strong_gens_distr = _distribute_gens_by_base(S.base, S.strong_gens) >>> _strong_gens_from_distr(strong_gens_distr) [(0 1 2), (2)(0 1), (1 2)] See Also ======== _distribute_gens_by_base """ if len(strong_gens_distr) == 1: return strong_gens_distr[0][:] else: result = strong_gens_distr[0] for gen in strong_gens_distr[1]: if gen not in result: result.append(gen) return result
0c0c081a4ca1bc4cdebfd78b7c144702762de3a0d7e3274031c8fedaa9d65459
from collections import defaultdict from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.core import (Basic, S, Add, Mul, Pow, Symbol, sympify, expand_func, Function, Dummy, Expr, factor_terms, expand_power_exp, Eq) from sympy.core.exprtools import factor_nc from sympy.core.parameters import global_parameters from sympy.core.function import (expand_log, count_ops, _mexpand, nfloat, expand_mul, expand) from sympy.core.numbers import Float, I, pi, Rational from sympy.core.relational import Relational from sympy.core.rules import Transform from sympy.core.sorting import ordered from sympy.core.sympify import _sympify from sympy.core.traversal import bottom_up as _bottom_up, walk as _walk from sympy.functions import gamma, exp, sqrt, log, exp_polar, re from sympy.functions.combinatorial.factorials import CombinatorialFunction from sympy.functions.elementary.complexes import unpolarify, Abs, sign from sympy.functions.elementary.exponential import ExpBase from sympy.functions.elementary.hyperbolic import HyperbolicFunction from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.piecewise import (Piecewise, piecewise_fold, piecewise_simplify) from sympy.functions.elementary.trigonometric import TrigonometricFunction from sympy.functions.special.bessel import (BesselBase, besselj, besseli, besselk, bessely, jn) from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.integrals.integrals import Integral from sympy.matrices.expressions import (MatrixExpr, MatAdd, MatMul, MatPow, MatrixSymbol) from sympy.polys import together, cancel, factor from sympy.polys.numberfields.minpoly import _is_sum_surds, _minimal_polynomial_sq from sympy.simplify.combsimp import combsimp from sympy.simplify.cse_opts import sub_pre, sub_post from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.powsimp import powsimp from sympy.simplify.radsimp import radsimp, fraction, collect_abs from sympy.simplify.sqrtdenest import sqrtdenest from sympy.simplify.trigsimp import trigsimp, exptrigsimp from sympy.utilities.decorator import deprecated from sympy.utilities.iterables import has_variety, sift, subsets, iterable from sympy.utilities.misc import as_int import mpmath def separatevars(expr, symbols=[], dict=False, force=False): """ Separates variables in an expression, if possible. By default, it separates with respect to all symbols in an expression and collects constant coefficients that are independent of symbols. Explanation =========== If ``dict=True`` then the separated terms will be returned in a dictionary keyed to their corresponding symbols. By default, all symbols in the expression will appear as keys; if symbols are provided, then all those symbols will be used as keys, and any terms in the expression containing other symbols or non-symbols will be returned keyed to the string 'coeff'. (Passing None for symbols will return the expression in a dictionary keyed to 'coeff'.) If ``force=True``, then bases of powers will be separated regardless of assumptions on the symbols involved. Notes ===== The order of the factors is determined by Mul, so that the separated expressions may not necessarily be grouped together. Although factoring is necessary to separate variables in some expressions, it is not necessary in all cases, so one should not count on the returned factors being factored. Examples ======== >>> from sympy.abc import x, y, z, alpha >>> from sympy import separatevars, sin >>> separatevars((x*y)**y) (x*y)**y >>> separatevars((x*y)**y, force=True) x**y*y**y >>> e = 2*x**2*z*sin(y)+2*z*x**2 >>> separatevars(e) 2*x**2*z*(sin(y) + 1) >>> separatevars(e, symbols=(x, y), dict=True) {'coeff': 2*z, x: x**2, y: sin(y) + 1} >>> separatevars(e, [x, y, alpha], dict=True) {'coeff': 2*z, alpha: 1, x: x**2, y: sin(y) + 1} If the expression is not really separable, or is only partially separable, separatevars will do the best it can to separate it by using factoring. >>> separatevars(x + x*y - 3*x**2) -x*(3*x - y - 1) If the expression is not separable then expr is returned unchanged or (if dict=True) then None is returned. >>> eq = 2*x + y*sin(x) >>> separatevars(eq) == eq True >>> separatevars(2*x + y*sin(x), symbols=(x, y), dict=True) is None True """ expr = sympify(expr) if dict: return _separatevars_dict(_separatevars(expr, force), symbols) else: return _separatevars(expr, force) def _separatevars(expr, force): if isinstance(expr, Abs): arg = expr.args[0] if arg.is_Mul and not arg.is_number: s = separatevars(arg, dict=True, force=force) if s is not None: return Mul(*map(expr.func, s.values())) else: return expr if len(expr.free_symbols) < 2: return expr # don't destroy a Mul since much of the work may already be done if expr.is_Mul: args = list(expr.args) changed = False for i, a in enumerate(args): args[i] = separatevars(a, force) changed = changed or args[i] != a if changed: expr = expr.func(*args) return expr # get a Pow ready for expansion if expr.is_Pow and expr.base != S.Exp1: expr = Pow(separatevars(expr.base, force=force), expr.exp) # First try other expansion methods expr = expr.expand(mul=False, multinomial=False, force=force) _expr, reps = posify(expr) if force else (expr, {}) expr = factor(_expr).subs(reps) if not expr.is_Add: return expr # Find any common coefficients to pull out args = list(expr.args) commonc = args[0].args_cnc(cset=True, warn=False)[0] for i in args[1:]: commonc &= i.args_cnc(cset=True, warn=False)[0] commonc = Mul(*commonc) commonc = commonc.as_coeff_Mul()[1] # ignore constants commonc_set = commonc.args_cnc(cset=True, warn=False)[0] # remove them for i, a in enumerate(args): c, nc = a.args_cnc(cset=True, warn=False) c = c - commonc_set args[i] = Mul(*c)*Mul(*nc) nonsepar = Add(*args) if len(nonsepar.free_symbols) > 1: _expr = nonsepar _expr, reps = posify(_expr) if force else (_expr, {}) _expr = (factor(_expr)).subs(reps) if not _expr.is_Add: nonsepar = _expr return commonc*nonsepar def _separatevars_dict(expr, symbols): if symbols: if not all(t.is_Atom for t in symbols): raise ValueError("symbols must be Atoms.") symbols = list(symbols) elif symbols is None: return {'coeff': expr} else: symbols = list(expr.free_symbols) if not symbols: return None ret = {i: [] for i in symbols + ['coeff']} for i in Mul.make_args(expr): expsym = i.free_symbols intersection = set(symbols).intersection(expsym) if len(intersection) > 1: return None if len(intersection) == 0: # There are no symbols, so it is part of the coefficient ret['coeff'].append(i) else: ret[intersection.pop()].append(i) # rebuild for k, v in ret.items(): ret[k] = Mul(*v) return ret def posify(eq): """Return ``eq`` (with generic symbols made positive) and a dictionary containing the mapping between the old and new symbols. Explanation =========== Any symbol that has positive=None will be replaced with a positive dummy symbol having the same name. This replacement will allow more symbolic processing of expressions, especially those involving powers and logarithms. A dictionary that can be sent to subs to restore ``eq`` to its original symbols is also returned. >>> from sympy import posify, Symbol, log, solve >>> from sympy.abc import x >>> posify(x + Symbol('p', positive=True) + Symbol('n', negative=True)) (_x + n + p, {_x: x}) >>> eq = 1/x >>> log(eq).expand() log(1/x) >>> log(posify(eq)[0]).expand() -log(_x) >>> p, rep = posify(eq) >>> log(p).expand().subs(rep) -log(x) It is possible to apply the same transformations to an iterable of expressions: >>> eq = x**2 - 4 >>> solve(eq, x) [-2, 2] >>> eq_x, reps = posify([eq, x]); eq_x [_x**2 - 4, _x] >>> solve(*eq_x) [2] """ eq = sympify(eq) if iterable(eq): f = type(eq) eq = list(eq) syms = set() for e in eq: syms = syms.union(e.atoms(Symbol)) reps = {} for s in syms: reps.update({v: k for k, v in posify(s)[1].items()}) for i, e in enumerate(eq): eq[i] = e.subs(reps) return f(eq), {r: s for s, r in reps.items()} reps = {s: Dummy(s.name, positive=True, **s.assumptions0) for s in eq.free_symbols if s.is_positive is None} eq = eq.subs(reps) return eq, {r: s for s, r in reps.items()} def hypersimp(f, k): """Given combinatorial term f(k) simplify its consecutive term ratio i.e. f(k+1)/f(k). The input term can be composed of functions and integer sequences which have equivalent representation in terms of gamma special function. Explanation =========== The algorithm performs three basic steps: 1. Rewrite all functions in terms of gamma, if possible. 2. Rewrite all occurrences of gamma in terms of products of gamma and rising factorial with integer, absolute constant exponent. 3. Perform simplification of nested fractions, powers and if the resulting expression is a quotient of polynomials, reduce their total degree. If f(k) is hypergeometric then as result we arrive with a quotient of polynomials of minimal degree. Otherwise None is returned. For more information on the implemented algorithm refer to: 1. W. Koepf, Algorithms for m-fold Hypergeometric Summation, Journal of Symbolic Computation (1995) 20, 399-417 """ f = sympify(f) g = f.subs(k, k + 1) / f g = g.rewrite(gamma) if g.has(Piecewise): g = piecewise_fold(g) g = g.args[-1][0] g = expand_func(g) g = powsimp(g, deep=True, combine='exp') if g.is_rational_function(k): return simplify(g, ratio=S.Infinity) else: return None def hypersimilar(f, g, k): """ Returns True if ``f`` and ``g`` are hyper-similar. Explanation =========== Similarity in hypergeometric sense means that a quotient of f(k) and g(k) is a rational function in ``k``. This procedure is useful in solving recurrence relations. For more information see hypersimp(). """ f, g = list(map(sympify, (f, g))) h = (f/g).rewrite(gamma) h = h.expand(func=True, basic=False) return h.is_rational_function(k) def signsimp(expr, evaluate=None): """Make all Add sub-expressions canonical wrt sign. Explanation =========== If an Add subexpression, ``a``, can have a sign extracted, as determined by could_extract_minus_sign, it is replaced with Mul(-1, a, evaluate=False). This allows signs to be extracted from powers and products. Examples ======== >>> from sympy import signsimp, exp, symbols >>> from sympy.abc import x, y >>> i = symbols('i', odd=True) >>> n = -1 + 1/x >>> n/x/(-n)**2 - 1/n/x (-1 + 1/x)/(x*(1 - 1/x)**2) - 1/(x*(-1 + 1/x)) >>> signsimp(_) 0 >>> x*n + x*-n x*(-1 + 1/x) + x*(1 - 1/x) >>> signsimp(_) 0 Since powers automatically handle leading signs >>> (-2)**i -2**i signsimp can be used to put the base of a power with an integer exponent into canonical form: >>> n**i (-1 + 1/x)**i By default, signsimp does not leave behind any hollow simplification: if making an Add canonical wrt sign didn't change the expression, the original Add is restored. If this is not desired then the keyword ``evaluate`` can be set to False: >>> e = exp(y - x) >>> signsimp(e) == e True >>> signsimp(e, evaluate=False) exp(-(x - y)) """ if evaluate is None: evaluate = global_parameters.evaluate expr = sympify(expr) if not isinstance(expr, (Expr, Relational)) or expr.is_Atom: return expr # get rid of an pre-existing unevaluation regarding sign e = expr.replace(lambda x: x.is_Mul and -(-x) != x, lambda x: -(-x)) e = sub_post(sub_pre(e)) if not isinstance(e, (Expr, Relational)) or e.is_Atom: return e if e.is_Add: rv = e.func(*[signsimp(a) for a in e.args]) if not evaluate and isinstance(rv, Add ) and rv.could_extract_minus_sign(): return Mul(S.NegativeOne, -rv, evaluate=False) return rv if evaluate: e = e.replace(lambda x: x.is_Mul and -(-x) != x, lambda x: -(-x)) return e def simplify(expr, ratio=1.7, measure=count_ops, rational=False, inverse=False, doit=True, **kwargs): """Simplifies the given expression. Explanation =========== Simplification is not a well defined term and the exact strategies this function tries can change in the future versions of SymPy. If your algorithm relies on "simplification" (whatever it is), try to determine what you need exactly - is it powsimp()?, radsimp()?, together()?, logcombine()?, or something else? And use this particular function directly, because those are well defined and thus your algorithm will be robust. Nonetheless, especially for interactive use, or when you do not know anything about the structure of the expression, simplify() tries to apply intelligent heuristics to make the input expression "simpler". For example: >>> from sympy import simplify, cos, sin >>> from sympy.abc import x, y >>> a = (x + x**2)/(x*sin(y)**2 + x*cos(y)**2) >>> a (x**2 + x)/(x*sin(y)**2 + x*cos(y)**2) >>> simplify(a) x + 1 Note that we could have obtained the same result by using specific simplification functions: >>> from sympy import trigsimp, cancel >>> trigsimp(a) (x**2 + x)/x >>> cancel(_) x + 1 In some cases, applying :func:`simplify` may actually result in some more complicated expression. The default ``ratio=1.7`` prevents more extreme cases: if (result length)/(input length) > ratio, then input is returned unmodified. The ``measure`` parameter lets you specify the function used to determine how complex an expression is. The function should take a single argument as an expression and return a number such that if expression ``a`` is more complex than expression ``b``, then ``measure(a) > measure(b)``. The default measure function is :func:`~.count_ops`, which returns the total number of operations in the expression. For example, if ``ratio=1``, ``simplify`` output cannot be longer than input. :: >>> from sympy import sqrt, simplify, count_ops, oo >>> root = 1/(sqrt(2)+3) Since ``simplify(root)`` would result in a slightly longer expression, root is returned unchanged instead:: >>> simplify(root, ratio=1) == root True If ``ratio=oo``, simplify will be applied anyway:: >>> count_ops(simplify(root, ratio=oo)) > count_ops(root) True Note that the shortest expression is not necessary the simplest, so setting ``ratio`` to 1 may not be a good idea. Heuristically, the default value ``ratio=1.7`` seems like a reasonable choice. You can easily define your own measure function based on what you feel should represent the "size" or "complexity" of the input expression. Note that some choices, such as ``lambda expr: len(str(expr))`` may appear to be good metrics, but have other problems (in this case, the measure function may slow down simplify too much for very large expressions). If you do not know what a good metric would be, the default, ``count_ops``, is a good one. For example: >>> from sympy import symbols, log >>> a, b = symbols('a b', positive=True) >>> g = log(a) + log(b) + log(a)*log(1/b) >>> h = simplify(g) >>> h log(a*b**(1 - log(a))) >>> count_ops(g) 8 >>> count_ops(h) 5 So you can see that ``h`` is simpler than ``g`` using the count_ops metric. However, we may not like how ``simplify`` (in this case, using ``logcombine``) has created the ``b**(log(1/a) + 1)`` term. A simple way to reduce this would be to give more weight to powers as operations in ``count_ops``. We can do this by using the ``visual=True`` option: >>> print(count_ops(g, visual=True)) 2*ADD + DIV + 4*LOG + MUL >>> print(count_ops(h, visual=True)) 2*LOG + MUL + POW + SUB >>> from sympy import Symbol, S >>> def my_measure(expr): ... POW = Symbol('POW') ... # Discourage powers by giving POW a weight of 10 ... count = count_ops(expr, visual=True).subs(POW, 10) ... # Every other operation gets a weight of 1 (the default) ... count = count.replace(Symbol, type(S.One)) ... return count >>> my_measure(g) 8 >>> my_measure(h) 14 >>> 15./8 > 1.7 # 1.7 is the default ratio True >>> simplify(g, measure=my_measure) -log(a)*log(b) + log(a) + log(b) Note that because ``simplify()`` internally tries many different simplification strategies and then compares them using the measure function, we get a completely different result that is still different from the input expression by doing this. If ``rational=True``, Floats will be recast as Rationals before simplification. If ``rational=None``, Floats will be recast as Rationals but the result will be recast as Floats. If rational=False(default) then nothing will be done to the Floats. If ``inverse=True``, it will be assumed that a composition of inverse functions, such as sin and asin, can be cancelled in any order. For example, ``asin(sin(x))`` will yield ``x`` without checking whether x belongs to the set where this relation is true. The default is False. Note that ``simplify()`` automatically calls ``doit()`` on the final expression. You can avoid this behavior by passing ``doit=False`` as an argument. Also, it should be noted that simplifying a boolean expression is not well defined. If the expression prefers automatic evaluation (such as :obj:`~.Eq()` or :obj:`~.Or()`), simplification will return ``True`` or ``False`` if truth value can be determined. If the expression is not evaluated by default (such as :obj:`~.Predicate()`), simplification will not reduce it and you should use :func:`~.refine()` or :func:`~.ask()` function. This inconsistency will be resolved in future version. See Also ======== sympy.assumptions.refine.refine : Simplification using assumptions. sympy.assumptions.ask.ask : Query for boolean expressions using assumptions. """ def shorter(*choices): """ Return the choice that has the fewest ops. In case of a tie, the expression listed first is selected. """ if not has_variety(choices): return choices[0] return min(choices, key=measure) def done(e): rv = e.doit() if doit else e return shorter(rv, collect_abs(rv)) expr = sympify(expr, rational=rational) kwargs = dict( ratio=kwargs.get('ratio', ratio), measure=kwargs.get('measure', measure), rational=kwargs.get('rational', rational), inverse=kwargs.get('inverse', inverse), doit=kwargs.get('doit', doit)) # no routine for Expr needs to check for is_zero if isinstance(expr, Expr) and expr.is_zero: return S.Zero if not expr.is_Number else expr _eval_simplify = getattr(expr, '_eval_simplify', None) if _eval_simplify is not None: return _eval_simplify(**kwargs) original_expr = expr = collect_abs(signsimp(expr)) if not isinstance(expr, Basic) or not expr.args: # XXX: temporary hack return expr if inverse and expr.has(Function): expr = inversecombine(expr) if not expr.args: # simplified to atomic return expr # do deep simplification handled = Add, Mul, Pow, ExpBase expr = expr.replace( # here, checking for x.args is not enough because Basic has # args but Basic does not always play well with replace, e.g. # when simultaneous is True found expressions will be masked # off with a Dummy but not all Basic objects in an expression # can be replaced with a Dummy lambda x: isinstance(x, Expr) and x.args and not isinstance( x, handled), lambda x: x.func(*[simplify(i, **kwargs) for i in x.args]), simultaneous=False) if not isinstance(expr, handled): return done(expr) if not expr.is_commutative: expr = nc_simplify(expr) # TODO: Apply different strategies, considering expression pattern: # is it a purely rational function? Is there any trigonometric function?... # See also https://github.com/sympy/sympy/pull/185. # rationalize Floats floats = False if rational is not False and expr.has(Float): floats = True expr = nsimplify(expr, rational=True) expr = _bottom_up(expr, lambda w: getattr(w, 'normal', lambda: w)()) expr = Mul(*powsimp(expr).as_content_primitive()) _e = cancel(expr) expr1 = shorter(_e, _mexpand(_e).cancel()) # issue 6829 expr2 = shorter(together(expr, deep=True), together(expr1, deep=True)) if ratio is S.Infinity: expr = expr2 else: expr = shorter(expr2, expr1, expr) if not isinstance(expr, Basic): # XXX: temporary hack return expr expr = factor_terms(expr, sign=False) # must come before `Piecewise` since this introduces more `Piecewise` terms if expr.has(sign): expr = expr.rewrite(Abs) # Deal with Piecewise separately to avoid recursive growth of expressions if expr.has(Piecewise): # Fold into a single Piecewise expr = piecewise_fold(expr) # Apply doit, if doit=True expr = done(expr) # Still a Piecewise? if expr.has(Piecewise): # Fold into a single Piecewise, in case doit lead to some # expressions being Piecewise expr = piecewise_fold(expr) # kroneckersimp also affects Piecewise if expr.has(KroneckerDelta): expr = kroneckersimp(expr) # Still a Piecewise? if expr.has(Piecewise): # Do not apply doit on the segments as it has already # been done above, but simplify expr = piecewise_simplify(expr, deep=True, doit=False) # Still a Piecewise? if expr.has(Piecewise): # Try factor common terms expr = shorter(expr, factor_terms(expr)) # As all expressions have been simplified above with the # complete simplify, nothing more needs to be done here return expr # hyperexpand automatically only works on hypergeometric terms # Do this after the Piecewise part to avoid recursive expansion expr = hyperexpand(expr) if expr.has(KroneckerDelta): expr = kroneckersimp(expr) if expr.has(BesselBase): expr = besselsimp(expr) if expr.has(TrigonometricFunction, HyperbolicFunction): expr = trigsimp(expr, deep=True) if expr.has(log): expr = shorter(expand_log(expr, deep=True), logcombine(expr)) if expr.has(CombinatorialFunction, gamma): # expression with gamma functions or non-integer arguments is # automatically passed to gammasimp expr = combsimp(expr) if expr.has(Sum): expr = sum_simplify(expr, **kwargs) if expr.has(Integral): expr = expr.xreplace({ i: factor_terms(i) for i in expr.atoms(Integral)}) if expr.has(Product): expr = product_simplify(expr, **kwargs) from sympy.physics.units import Quantity if expr.has(Quantity): from sympy.physics.units.util import quantity_simplify expr = quantity_simplify(expr) short = shorter(powsimp(expr, combine='exp', deep=True), powsimp(expr), expr) short = shorter(short, cancel(short)) short = shorter(short, factor_terms(short), expand_power_exp(expand_mul(short))) if short.has(TrigonometricFunction, HyperbolicFunction, ExpBase, exp): short = exptrigsimp(short) # get rid of hollow 2-arg Mul factorization hollow_mul = Transform( lambda x: Mul(*x.args), lambda x: x.is_Mul and len(x.args) == 2 and x.args[0].is_Number and x.args[1].is_Add and x.is_commutative) expr = short.xreplace(hollow_mul) numer, denom = expr.as_numer_denom() if denom.is_Add: n, d = fraction(radsimp(1/denom, symbolic=False, max_terms=1)) if n is not S.One: expr = (numer*n).expand()/d if expr.could_extract_minus_sign(): n, d = fraction(expr) if d != 0: expr = signsimp(-n/(-d)) if measure(expr) > ratio*measure(original_expr): expr = original_expr # restore floats if floats and rational is None: expr = nfloat(expr, exponent=False) return done(expr) def sum_simplify(s, **kwargs): """Main function for Sum simplification""" if not isinstance(s, Add): s = s.xreplace({a: sum_simplify(a, **kwargs) for a in s.atoms(Add) if a.has(Sum)}) s = expand(s) if not isinstance(s, Add): return s terms = s.args s_t = [] # Sum Terms o_t = [] # Other Terms for term in terms: sum_terms, other = sift(Mul.make_args(term), lambda i: isinstance(i, Sum), binary=True) if not sum_terms: o_t.append(term) continue other = [Mul(*other)] s_t.append(Mul(*(other + [s._eval_simplify(**kwargs) for s in sum_terms]))) result = Add(sum_combine(s_t), *o_t) return result def sum_combine(s_t): """Helper function for Sum simplification Attempts to simplify a list of sums, by combining limits / sum function's returns the simplified sum """ used = [False] * len(s_t) for method in range(2): for i, s_term1 in enumerate(s_t): if not used[i]: for j, s_term2 in enumerate(s_t): if not used[j] and i != j: temp = sum_add(s_term1, s_term2, method) if isinstance(temp, (Sum, Mul)): s_t[i] = temp s_term1 = s_t[i] used[j] = True result = S.Zero for i, s_term in enumerate(s_t): if not used[i]: result = Add(result, s_term) return result def factor_sum(self, limits=None, radical=False, clear=False, fraction=False, sign=True): """Return Sum with constant factors extracted. If ``limits`` is specified then ``self`` is the summand; the other keywords are passed to ``factor_terms``. Examples ======== >>> from sympy import Sum >>> from sympy.abc import x, y >>> from sympy.simplify.simplify import factor_sum >>> s = Sum(x*y, (x, 1, 3)) >>> factor_sum(s) y*Sum(x, (x, 1, 3)) >>> factor_sum(s.function, s.limits) y*Sum(x, (x, 1, 3)) """ # XXX deprecate in favor of direct call to factor_terms kwargs = dict(radical=radical, clear=clear, fraction=fraction, sign=sign) expr = Sum(self, *limits) if limits else self return factor_terms(expr, **kwargs) def sum_add(self, other, method=0): """Helper function for Sum simplification""" #we know this is something in terms of a constant * a sum #so we temporarily put the constants inside for simplification #then simplify the result def __refactor(val): args = Mul.make_args(val) sumv = next(x for x in args if isinstance(x, Sum)) constant = Mul(*[x for x in args if x != sumv]) return Sum(constant * sumv.function, *sumv.limits) if isinstance(self, Mul): rself = __refactor(self) else: rself = self if isinstance(other, Mul): rother = __refactor(other) else: rother = other if type(rself) is type(rother): if method == 0: if rself.limits == rother.limits: return factor_sum(Sum(rself.function + rother.function, *rself.limits)) elif method == 1: if simplify(rself.function - rother.function) == 0: if len(rself.limits) == len(rother.limits) == 1: i = rself.limits[0][0] x1 = rself.limits[0][1] y1 = rself.limits[0][2] j = rother.limits[0][0] x2 = rother.limits[0][1] y2 = rother.limits[0][2] if i == j: if x2 == y1 + 1: return factor_sum(Sum(rself.function, (i, x1, y2))) elif x1 == y2 + 1: return factor_sum(Sum(rself.function, (i, x2, y1))) return Add(self, other) def product_simplify(s, **kwargs): """Main function for Product simplification""" terms = Mul.make_args(s) p_t = [] # Product Terms o_t = [] # Other Terms deep = kwargs.get('deep', True) for term in terms: if isinstance(term, Product): if deep: p_t.append(Product(term.function.simplify(**kwargs), *term.limits)) else: p_t.append(term) else: o_t.append(term) used = [False] * len(p_t) for method in range(2): for i, p_term1 in enumerate(p_t): if not used[i]: for j, p_term2 in enumerate(p_t): if not used[j] and i != j: tmp_prod = product_mul(p_term1, p_term2, method) if isinstance(tmp_prod, Product): p_t[i] = tmp_prod used[j] = True result = Mul(*o_t) for i, p_term in enumerate(p_t): if not used[i]: result = Mul(result, p_term) return result def product_mul(self, other, method=0): """Helper function for Product simplification""" if type(self) is type(other): if method == 0: if self.limits == other.limits: return Product(self.function * other.function, *self.limits) elif method == 1: if simplify(self.function - other.function) == 0: if len(self.limits) == len(other.limits) == 1: i = self.limits[0][0] x1 = self.limits[0][1] y1 = self.limits[0][2] j = other.limits[0][0] x2 = other.limits[0][1] y2 = other.limits[0][2] if i == j: if x2 == y1 + 1: return Product(self.function, (i, x1, y2)) elif x1 == y2 + 1: return Product(self.function, (i, x2, y1)) return Mul(self, other) def _nthroot_solve(p, n, prec): """ helper function for ``nthroot`` It denests ``p**Rational(1, n)`` using its minimal polynomial """ from sympy.solvers import solve while n % 2 == 0: p = sqrtdenest(sqrt(p)) n = n // 2 if n == 1: return p pn = p**Rational(1, n) x = Symbol('x') f = _minimal_polynomial_sq(p, n, x) if f is None: return None sols = solve(f, x) for sol in sols: if abs(sol - pn).n() < 1./10**prec: sol = sqrtdenest(sol) if _mexpand(sol**n) == p: return sol def logcombine(expr, force=False): """ Takes logarithms and combines them using the following rules: - log(x) + log(y) == log(x*y) if both are positive - a*log(x) == log(x**a) if x is positive and a is real If ``force`` is ``True`` then the assumptions above will be assumed to hold if there is no assumption already in place on a quantity. For example, if ``a`` is imaginary or the argument negative, force will not perform a combination but if ``a`` is a symbol with no assumptions the change will take place. Examples ======== >>> from sympy import Symbol, symbols, log, logcombine, I >>> from sympy.abc import a, x, y, z >>> logcombine(a*log(x) + log(y) - log(z)) a*log(x) + log(y) - log(z) >>> logcombine(a*log(x) + log(y) - log(z), force=True) log(x**a*y/z) >>> x,y,z = symbols('x,y,z', positive=True) >>> a = Symbol('a', real=True) >>> logcombine(a*log(x) + log(y) - log(z)) log(x**a*y/z) The transformation is limited to factors and/or terms that contain logs, so the result depends on the initial state of expansion: >>> eq = (2 + 3*I)*log(x) >>> logcombine(eq, force=True) == eq True >>> logcombine(eq.expand(), force=True) log(x**2) + I*log(x**3) See Also ======== posify: replace all symbols with symbols having positive assumptions sympy.core.function.expand_log: expand the logarithms of products and powers; the opposite of logcombine """ def f(rv): if not (rv.is_Add or rv.is_Mul): return rv def gooda(a): # bool to tell whether the leading ``a`` in ``a*log(x)`` # could appear as log(x**a) return (a is not S.NegativeOne and # -1 *could* go, but we disallow (a.is_extended_real or force and a.is_extended_real is not False)) def goodlog(l): # bool to tell whether log ``l``'s argument can combine with others a = l.args[0] return a.is_positive or force and a.is_nonpositive is not False other = [] logs = [] log1 = defaultdict(list) for a in Add.make_args(rv): if isinstance(a, log) and goodlog(a): log1[()].append(([], a)) elif not a.is_Mul: other.append(a) else: ot = [] co = [] lo = [] for ai in a.args: if ai.is_Rational and ai < 0: ot.append(S.NegativeOne) co.append(-ai) elif isinstance(ai, log) and goodlog(ai): lo.append(ai) elif gooda(ai): co.append(ai) else: ot.append(ai) if len(lo) > 1: logs.append((ot, co, lo)) elif lo: log1[tuple(ot)].append((co, lo[0])) else: other.append(a) # if there is only one log in other, put it with the # good logs if len(other) == 1 and isinstance(other[0], log): log1[()].append(([], other.pop())) # if there is only one log at each coefficient and none have # an exponent to place inside the log then there is nothing to do if not logs and all(len(log1[k]) == 1 and log1[k][0] == [] for k in log1): return rv # collapse multi-logs as far as possible in a canonical way # TODO: see if x*log(a)+x*log(a)*log(b) -> x*log(a)*(1+log(b))? # -- in this case, it's unambiguous, but if it were were a log(c) in # each term then it's arbitrary whether they are grouped by log(a) or # by log(c). So for now, just leave this alone; it's probably better to # let the user decide for o, e, l in logs: l = list(ordered(l)) e = log(l.pop(0).args[0]**Mul(*e)) while l: li = l.pop(0) e = log(li.args[0]**e) c, l = Mul(*o), e if isinstance(l, log): # it should be, but check to be sure log1[(c,)].append(([], l)) else: other.append(c*l) # logs that have the same coefficient can multiply for k in list(log1.keys()): log1[Mul(*k)] = log(logcombine(Mul(*[ l.args[0]**Mul(*c) for c, l in log1.pop(k)]), force=force), evaluate=False) # logs that have oppositely signed coefficients can divide for k in ordered(list(log1.keys())): if k not in log1: # already popped as -k continue if -k in log1: # figure out which has the minus sign; the one with # more op counts should be the one num, den = k, -k if num.count_ops() > den.count_ops(): num, den = den, num other.append( num*log(log1.pop(num).args[0]/log1.pop(den).args[0], evaluate=False)) else: other.append(k*log1.pop(k)) return Add(*other) return _bottom_up(expr, f) def inversecombine(expr): """Simplify the composition of a function and its inverse. Explanation =========== No attention is paid to whether the inverse is a left inverse or a right inverse; thus, the result will in general not be equivalent to the original expression. Examples ======== >>> from sympy.simplify.simplify import inversecombine >>> from sympy import asin, sin, log, exp >>> from sympy.abc import x >>> inversecombine(asin(sin(x))) x >>> inversecombine(2*log(exp(3*x))) 6*x """ def f(rv): if isinstance(rv, log): if isinstance(rv.args[0], exp) or (rv.args[0].is_Pow and rv.args[0].base == S.Exp1): rv = rv.args[0].exp elif rv.is_Function and hasattr(rv, "inverse"): if (len(rv.args) == 1 and len(rv.args[0].args) == 1 and isinstance(rv.args[0], rv.inverse(argindex=1))): rv = rv.args[0].args[0] if rv.is_Pow and rv.base == S.Exp1: if isinstance(rv.exp, log): rv = rv.exp.args[0] return rv return _bottom_up(expr, f) def kroneckersimp(expr): """ Simplify expressions with KroneckerDelta. The only simplification currently attempted is to identify multiplicative cancellation: Examples ======== >>> from sympy import KroneckerDelta, kroneckersimp >>> from sympy.abc import i >>> kroneckersimp(1 + KroneckerDelta(0, i) * KroneckerDelta(1, i)) 1 """ def args_cancel(args1, args2): for i1 in range(2): for i2 in range(2): a1 = args1[i1] a2 = args2[i2] a3 = args1[(i1 + 1) % 2] a4 = args2[(i2 + 1) % 2] if Eq(a1, a2) is S.true and Eq(a3, a4) is S.false: return True return False def cancel_kronecker_mul(m): args = m.args deltas = [a for a in args if isinstance(a, KroneckerDelta)] for delta1, delta2 in subsets(deltas, 2): args1 = delta1.args args2 = delta2.args if args_cancel(args1, args2): return S.Zero * m # In case of oo etc return m if not expr.has(KroneckerDelta): return expr if expr.has(Piecewise): expr = expr.rewrite(KroneckerDelta) newexpr = expr expr = None while newexpr != expr: expr = newexpr newexpr = expr.replace(lambda e: isinstance(e, Mul), cancel_kronecker_mul) return expr def besselsimp(expr): """ Simplify bessel-type functions. Explanation =========== This routine tries to simplify bessel-type functions. Currently it only works on the Bessel J and I functions, however. It works by looking at all such functions in turn, and eliminating factors of "I" and "-1" (actually their polar equivalents) in front of the argument. Then, functions of half-integer order are rewritten using strigonometric functions and functions of integer order (> 1) are rewritten using functions of low order. Finally, if the expression was changed, compute factorization of the result with factor(). >>> from sympy import besselj, besseli, besselsimp, polar_lift, I, S >>> from sympy.abc import z, nu >>> besselsimp(besselj(nu, z*polar_lift(-1))) exp(I*pi*nu)*besselj(nu, z) >>> besselsimp(besseli(nu, z*polar_lift(-I))) exp(-I*pi*nu/2)*besselj(nu, z) >>> besselsimp(besseli(S(-1)/2, z)) sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z)) >>> besselsimp(z*besseli(0, z) + z*(besseli(2, z))/2 + besseli(1, z)) 3*z*besseli(0, z)/2 """ # TODO # - better algorithm? # - simplify (cos(pi*b)*besselj(b,z) - besselj(-b,z))/sin(pi*b) ... # - use contiguity relations? def replacer(fro, to, factors): factors = set(factors) def repl(nu, z): if factors.intersection(Mul.make_args(z)): return to(nu, z) return fro(nu, z) return repl def torewrite(fro, to): def tofunc(nu, z): return fro(nu, z).rewrite(to) return tofunc def tominus(fro): def tofunc(nu, z): return exp(I*pi*nu)*fro(nu, exp_polar(-I*pi)*z) return tofunc orig_expr = expr ifactors = [I, exp_polar(I*pi/2), exp_polar(-I*pi/2)] expr = expr.replace( besselj, replacer(besselj, torewrite(besselj, besseli), ifactors)) expr = expr.replace( besseli, replacer(besseli, torewrite(besseli, besselj), ifactors)) minusfactors = [-1, exp_polar(I*pi)] expr = expr.replace( besselj, replacer(besselj, tominus(besselj), minusfactors)) expr = expr.replace( besseli, replacer(besseli, tominus(besseli), minusfactors)) z0 = Dummy('z') def expander(fro): def repl(nu, z): if (nu % 1) == S.Half: return simplify(trigsimp(unpolarify( fro(nu, z0).rewrite(besselj).rewrite(jn).expand( func=True)).subs(z0, z))) elif nu.is_Integer and nu > 1: return fro(nu, z).expand(func=True) return fro(nu, z) return repl expr = expr.replace(besselj, expander(besselj)) expr = expr.replace(bessely, expander(bessely)) expr = expr.replace(besseli, expander(besseli)) expr = expr.replace(besselk, expander(besselk)) def _bessel_simp_recursion(expr): def _use_recursion(bessel, expr): while True: bessels = expr.find(lambda x: isinstance(x, bessel)) try: for ba in sorted(bessels, key=lambda x: re(x.args[0])): a, x = ba.args bap1 = bessel(a+1, x) bap2 = bessel(a+2, x) if expr.has(bap1) and expr.has(bap2): expr = expr.subs(ba, 2*(a+1)/x*bap1 - bap2) break else: return expr except (ValueError, TypeError): return expr if expr.has(besselj): expr = _use_recursion(besselj, expr) if expr.has(bessely): expr = _use_recursion(bessely, expr) return expr expr = _bessel_simp_recursion(expr) if expr != orig_expr: expr = expr.factor() return expr def nthroot(expr, n, max_len=4, prec=15): """ Compute a real nth-root of a sum of surds. Parameters ========== expr : sum of surds n : integer max_len : maximum number of surds passed as constants to ``nsimplify`` Algorithm ========= First ``nsimplify`` is used to get a candidate root; if it is not a root the minimal polynomial is computed; the answer is one of its roots. Examples ======== >>> from sympy.simplify.simplify import nthroot >>> from sympy import sqrt >>> nthroot(90 + 34*sqrt(7), 3) sqrt(7) + 3 """ expr = sympify(expr) n = sympify(n) p = expr**Rational(1, n) if not n.is_integer: return p if not _is_sum_surds(expr): return p surds = [] coeff_muls = [x.as_coeff_Mul() for x in expr.args] for x, y in coeff_muls: if not x.is_rational: return p if y is S.One: continue if not (y.is_Pow and y.exp == S.Half and y.base.is_integer): return p surds.append(y) surds.sort() surds = surds[:max_len] if expr < 0 and n % 2 == 1: p = (-expr)**Rational(1, n) a = nsimplify(p, constants=surds) res = a if _mexpand(a**n) == _mexpand(-expr) else p return -res a = nsimplify(p, constants=surds) if _mexpand(a) is not _mexpand(p) and _mexpand(a**n) == _mexpand(expr): return _mexpand(a) expr = _nthroot_solve(expr, n, prec) if expr is None: return p return expr def nsimplify(expr, constants=(), tolerance=None, full=False, rational=None, rational_conversion='base10'): """ Find a simple representation for a number or, if there are free symbols or if ``rational=True``, then replace Floats with their Rational equivalents. If no change is made and rational is not False then Floats will at least be converted to Rationals. Explanation =========== For numerical expressions, a simple formula that numerically matches the given numerical expression is sought (and the input should be possible to evalf to a precision of at least 30 digits). Optionally, a list of (rationally independent) constants to include in the formula may be given. A lower tolerance may be set to find less exact matches. If no tolerance is given then the least precise value will set the tolerance (e.g. Floats default to 15 digits of precision, so would be tolerance=10**-15). With ``full=True``, a more extensive search is performed (this is useful to find simpler numbers when the tolerance is set low). When converting to rational, if rational_conversion='base10' (the default), then convert floats to rationals using their base-10 (string) representation. When rational_conversion='exact' it uses the exact, base-2 representation. Examples ======== >>> from sympy import nsimplify, sqrt, GoldenRatio, exp, I, pi >>> nsimplify(4/(1+sqrt(5)), [GoldenRatio]) -2 + 2*GoldenRatio >>> nsimplify((1/(exp(3*pi*I/5)+1))) 1/2 - I*sqrt(sqrt(5)/10 + 1/4) >>> nsimplify(I**I, [pi]) exp(-pi/2) >>> nsimplify(pi, tolerance=0.01) 22/7 >>> nsimplify(0.333333333333333, rational=True, rational_conversion='exact') 6004799503160655/18014398509481984 >>> nsimplify(0.333333333333333, rational=True) 1/3 See Also ======== sympy.core.function.nfloat """ try: return sympify(as_int(expr)) except (TypeError, ValueError): pass expr = sympify(expr).xreplace({ Float('inf'): S.Infinity, Float('-inf'): S.NegativeInfinity, }) if expr is S.Infinity or expr is S.NegativeInfinity: return expr if rational or expr.free_symbols: return _real_to_rational(expr, tolerance, rational_conversion) # SymPy's default tolerance for Rationals is 15; other numbers may have # lower tolerances set, so use them to pick the largest tolerance if None # was given if tolerance is None: tolerance = 10**-min([15] + [mpmath.libmp.libmpf.prec_to_dps(n._prec) for n in expr.atoms(Float)]) # XXX should prec be set independent of tolerance or should it be computed # from tolerance? prec = 30 bprec = int(prec*3.33) constants_dict = {} for constant in constants: constant = sympify(constant) v = constant.evalf(prec) if not v.is_Float: raise ValueError("constants must be real-valued") constants_dict[str(constant)] = v._to_mpmath(bprec) exprval = expr.evalf(prec, chop=True) re, im = exprval.as_real_imag() # safety check to make sure that this evaluated to a number if not (re.is_Number and im.is_Number): return expr def nsimplify_real(x): orig = mpmath.mp.dps xv = x._to_mpmath(bprec) try: # We'll be happy with low precision if a simple fraction if not (tolerance or full): mpmath.mp.dps = 15 rat = mpmath.pslq([xv, 1]) if rat is not None: return Rational(-int(rat[1]), int(rat[0])) mpmath.mp.dps = prec newexpr = mpmath.identify(xv, constants=constants_dict, tol=tolerance, full=full) if not newexpr: raise ValueError if full: newexpr = newexpr[0] expr = sympify(newexpr) if x and not expr: # don't let x become 0 raise ValueError if expr.is_finite is False and xv not in [mpmath.inf, mpmath.ninf]: raise ValueError return expr finally: # even though there are returns above, this is executed # before leaving mpmath.mp.dps = orig try: if re: re = nsimplify_real(re) if im: im = nsimplify_real(im) except ValueError: if rational is None: return _real_to_rational(expr, rational_conversion=rational_conversion) return expr rv = re + im*S.ImaginaryUnit # if there was a change or rational is explicitly not wanted # return the value, else return the Rational representation if rv != expr or rational is False: return rv return _real_to_rational(expr, rational_conversion=rational_conversion) def _real_to_rational(expr, tolerance=None, rational_conversion='base10'): """ Replace all reals in expr with rationals. Examples ======== >>> from sympy.simplify.simplify import _real_to_rational >>> from sympy.abc import x >>> _real_to_rational(.76 + .1*x**.5) sqrt(x)/10 + 19/25 If rational_conversion='base10', this uses the base-10 string. If rational_conversion='exact', the exact, base-2 representation is used. >>> _real_to_rational(0.333333333333333, rational_conversion='exact') 6004799503160655/18014398509481984 >>> _real_to_rational(0.333333333333333) 1/3 """ expr = _sympify(expr) inf = Float('inf') p = expr reps = {} reduce_num = None if tolerance is not None and tolerance < 1: reduce_num = ceiling(1/tolerance) for fl in p.atoms(Float): key = fl if reduce_num is not None: r = Rational(fl).limit_denominator(reduce_num) elif (tolerance is not None and tolerance >= 1 and fl.is_Integer is False): r = Rational(tolerance*round(fl/tolerance) ).limit_denominator(int(tolerance)) else: if rational_conversion == 'exact': r = Rational(fl) reps[key] = r continue elif rational_conversion != 'base10': raise ValueError("rational_conversion must be 'base10' or 'exact'") r = nsimplify(fl, rational=False) # e.g. log(3).n() -> log(3) instead of a Rational if fl and not r: r = Rational(fl) elif not r.is_Rational: if fl in (inf, -inf): r = S.ComplexInfinity elif fl < 0: fl = -fl d = Pow(10, int(mpmath.log(fl)/mpmath.log(10))) r = -Rational(str(fl/d))*d elif fl > 0: d = Pow(10, int(mpmath.log(fl)/mpmath.log(10))) r = Rational(str(fl/d))*d else: r = S.Zero reps[key] = r return p.subs(reps, simultaneous=True) def clear_coefficients(expr, rhs=S.Zero): """Return `p, r` where `p` is the expression obtained when Rational additive and multiplicative coefficients of `expr` have been stripped away in a naive fashion (i.e. without simplification). The operations needed to remove the coefficients will be applied to `rhs` and returned as `r`. Examples ======== >>> from sympy.simplify.simplify import clear_coefficients >>> from sympy.abc import x, y >>> from sympy import Dummy >>> expr = 4*y*(6*x + 3) >>> clear_coefficients(expr - 2) (y*(2*x + 1), 1/6) When solving 2 or more expressions like `expr = a`, `expr = b`, etc..., it is advantageous to provide a Dummy symbol for `rhs` and simply replace it with `a`, `b`, etc... in `r`. >>> rhs = Dummy('rhs') >>> clear_coefficients(expr, rhs) (y*(2*x + 1), _rhs/12) >>> _[1].subs(rhs, 2) 1/6 """ was = None free = expr.free_symbols if expr.is_Rational: return (S.Zero, rhs - expr) while expr and was != expr: was = expr m, expr = ( expr.as_content_primitive() if free else factor_terms(expr).as_coeff_Mul(rational=True)) rhs /= m c, expr = expr.as_coeff_Add(rational=True) rhs -= c expr = signsimp(expr, evaluate = False) if expr.could_extract_minus_sign(): expr = -expr rhs = -rhs return expr, rhs def nc_simplify(expr, deep=True): ''' Simplify a non-commutative expression composed of multiplication and raising to a power by grouping repeated subterms into one power. Priority is given to simplifications that give the fewest number of arguments in the end (for example, in a*b*a*b*c*a*b*c simplifying to (a*b)**2*c*a*b*c gives 5 arguments while a*b*(a*b*c)**2 has 3). If ``expr`` is a sum of such terms, the sum of the simplified terms is returned. Keyword argument ``deep`` controls whether or not subexpressions nested deeper inside the main expression are simplified. See examples below. Setting `deep` to `False` can save time on nested expressions that do not need simplifying on all levels. Examples ======== >>> from sympy import symbols >>> from sympy.simplify.simplify import nc_simplify >>> a, b, c = symbols("a b c", commutative=False) >>> nc_simplify(a*b*a*b*c*a*b*c) a*b*(a*b*c)**2 >>> expr = a**2*b*a**4*b*a**4 >>> nc_simplify(expr) a**2*(b*a**4)**2 >>> nc_simplify(a*b*a*b*c**2*(a*b)**2*c**2) ((a*b)**2*c**2)**2 >>> nc_simplify(a*b*a*b + 2*a*c*a**2*c*a**2*c*a) (a*b)**2 + 2*(a*c*a)**3 >>> nc_simplify(b**-1*a**-1*(a*b)**2) a*b >>> nc_simplify(a**-1*b**-1*c*a) (b*a)**(-1)*c*a >>> expr = (a*b*a*b)**2*a*c*a*c >>> nc_simplify(expr) (a*b)**4*(a*c)**2 >>> nc_simplify(expr, deep=False) (a*b*a*b)**2*(a*c)**2 ''' if isinstance(expr, MatrixExpr): expr = expr.doit(inv_expand=False) _Add, _Mul, _Pow, _Symbol = MatAdd, MatMul, MatPow, MatrixSymbol else: _Add, _Mul, _Pow, _Symbol = Add, Mul, Pow, Symbol # =========== Auxiliary functions ======================== def _overlaps(args): # Calculate a list of lists m such that m[i][j] contains the lengths # of all possible overlaps between args[:i+1] and args[i+1+j:]. # An overlap is a suffix of the prefix that matches a prefix # of the suffix. # For example, let expr=c*a*b*a*b*a*b*a*b. Then m[3][0] contains # the lengths of overlaps of c*a*b*a*b with a*b*a*b. The overlaps # are a*b*a*b, a*b and the empty word so that m[3][0]=[4,2,0]. # All overlaps rather than only the longest one are recorded # because this information helps calculate other overlap lengths. m = [[([1, 0] if a == args[0] else [0]) for a in args[1:]]] for i in range(1, len(args)): overlaps = [] j = 0 for j in range(len(args) - i - 1): overlap = [] for v in m[i-1][j+1]: if j + i + 1 + v < len(args) and args[i] == args[j+i+1+v]: overlap.append(v + 1) overlap += [0] overlaps.append(overlap) m.append(overlaps) return m def _reduce_inverses(_args): # replace consecutive negative powers by an inverse # of a product of positive powers, e.g. a**-1*b**-1*c # will simplify to (a*b)**-1*c; # return that new args list and the number of negative # powers in it (inv_tot) inv_tot = 0 # total number of inverses inverses = [] args = [] for arg in _args: if isinstance(arg, _Pow) and arg.args[1] < 0: inverses = [arg**-1] + inverses inv_tot += 1 else: if len(inverses) == 1: args.append(inverses[0]**-1) elif len(inverses) > 1: args.append(_Pow(_Mul(*inverses), -1)) inv_tot -= len(inverses) - 1 inverses = [] args.append(arg) if inverses: args.append(_Pow(_Mul(*inverses), -1)) inv_tot -= len(inverses) - 1 return inv_tot, tuple(args) def get_score(s): # compute the number of arguments of s # (including in nested expressions) overall # but ignore exponents if isinstance(s, _Pow): return get_score(s.args[0]) elif isinstance(s, (_Add, _Mul)): return sum([get_score(a) for a in s.args]) return 1 def compare(s, alt_s): # compare two possible simplifications and return a # "better" one if s != alt_s and get_score(alt_s) < get_score(s): return alt_s return s # ======================================================== if not isinstance(expr, (_Add, _Mul, _Pow)) or expr.is_commutative: return expr args = expr.args[:] if isinstance(expr, _Pow): if deep: return _Pow(nc_simplify(args[0]), args[1]).doit() else: return expr elif isinstance(expr, _Add): return _Add(*[nc_simplify(a, deep=deep) for a in args]).doit() else: # get the non-commutative part c_args, args = expr.args_cnc() com_coeff = Mul(*c_args) if com_coeff != 1: return com_coeff*nc_simplify(expr/com_coeff, deep=deep) inv_tot, args = _reduce_inverses(args) # if most arguments are negative, work with the inverse # of the expression, e.g. a**-1*b*a**-1*c**-1 will become # (c*a*b**-1*a)**-1 at the end so can work with c*a*b**-1*a invert = False if inv_tot > len(args)/2: invert = True args = [a**-1 for a in args[::-1]] if deep: args = tuple(nc_simplify(a) for a in args) m = _overlaps(args) # simps will be {subterm: end} where `end` is the ending # index of a sequence of repetitions of subterm; # this is for not wasting time with subterms that are part # of longer, already considered sequences simps = {} post = 1 pre = 1 # the simplification coefficient is the number of # arguments by which contracting a given sequence # would reduce the word; e.g. in a*b*a*b*c*a*b*c, # contracting a*b*a*b to (a*b)**2 removes 3 arguments # while a*b*c*a*b*c to (a*b*c)**2 removes 6. It's # better to contract the latter so simplification # with a maximum simplification coefficient will be chosen max_simp_coeff = 0 simp = None # information about future simplification for i in range(1, len(args)): simp_coeff = 0 l = 0 # length of a subterm p = 0 # the power of a subterm if i < len(args) - 1: rep = m[i][0] start = i # starting index of the repeated sequence end = i+1 # ending index of the repeated sequence if i == len(args)-1 or rep == [0]: # no subterm is repeated at this stage, at least as # far as the arguments are concerned - there may be # a repetition if powers are taken into account if (isinstance(args[i], _Pow) and not isinstance(args[i].args[0], _Symbol)): subterm = args[i].args[0].args l = len(subterm) if args[i-l:i] == subterm: # e.g. a*b in a*b*(a*b)**2 is not repeated # in args (= [a, b, (a*b)**2]) but it # can be matched here p += 1 start -= l if args[i+1:i+1+l] == subterm: # e.g. a*b in (a*b)**2*a*b p += 1 end += l if p: p += args[i].args[1] else: continue else: l = rep[0] # length of the longest repeated subterm at this point start -= l - 1 subterm = args[start:end] p = 2 end += l if subterm in simps and simps[subterm] >= start: # the subterm is part of a sequence that # has already been considered continue # count how many times it's repeated while end < len(args): if l in m[end-1][0]: p += 1 end += l elif isinstance(args[end], _Pow) and args[end].args[0].args == subterm: # for cases like a*b*a*b*(a*b)**2*a*b p += args[end].args[1] end += 1 else: break # see if another match can be made, e.g. # for b*a**2 in b*a**2*b*a**3 or a*b in # a**2*b*a*b pre_exp = 0 pre_arg = 1 if start - l >= 0 and args[start-l+1:start] == subterm[1:]: if isinstance(subterm[0], _Pow): pre_arg = subterm[0].args[0] exp = subterm[0].args[1] else: pre_arg = subterm[0] exp = 1 if isinstance(args[start-l], _Pow) and args[start-l].args[0] == pre_arg: pre_exp = args[start-l].args[1] - exp start -= l p += 1 elif args[start-l] == pre_arg: pre_exp = 1 - exp start -= l p += 1 post_exp = 0 post_arg = 1 if end + l - 1 < len(args) and args[end:end+l-1] == subterm[:-1]: if isinstance(subterm[-1], _Pow): post_arg = subterm[-1].args[0] exp = subterm[-1].args[1] else: post_arg = subterm[-1] exp = 1 if isinstance(args[end+l-1], _Pow) and args[end+l-1].args[0] == post_arg: post_exp = args[end+l-1].args[1] - exp end += l p += 1 elif args[end+l-1] == post_arg: post_exp = 1 - exp end += l p += 1 # Consider a*b*a**2*b*a**2*b*a: # b*a**2 is explicitly repeated, but note # that in this case a*b*a is also repeated # so there are two possible simplifications: # a*(b*a**2)**3*a**-1 or (a*b*a)**3 # The latter is obviously simpler. # But in a*b*a**2*b**2*a**2 the simplifications are # a*(b*a**2)**2 and (a*b*a)**3*a in which case # it's better to stick with the shorter subterm if post_exp and exp % 2 == 0 and start > 0: exp = exp/2 _pre_exp = 1 _post_exp = 1 if isinstance(args[start-1], _Pow) and args[start-1].args[0] == post_arg: _post_exp = post_exp + exp _pre_exp = args[start-1].args[1] - exp elif args[start-1] == post_arg: _post_exp = post_exp + exp _pre_exp = 1 - exp if _pre_exp == 0 or _post_exp == 0: if not pre_exp: start -= 1 post_exp = _post_exp pre_exp = _pre_exp pre_arg = post_arg subterm = (post_arg**exp,) + subterm[:-1] + (post_arg**exp,) simp_coeff += end-start if post_exp: simp_coeff -= 1 if pre_exp: simp_coeff -= 1 simps[subterm] = end if simp_coeff > max_simp_coeff: max_simp_coeff = simp_coeff simp = (start, _Mul(*subterm), p, end, l) pre = pre_arg**pre_exp post = post_arg**post_exp if simp: subterm = _Pow(nc_simplify(simp[1], deep=deep), simp[2]) pre = nc_simplify(_Mul(*args[:simp[0]])*pre, deep=deep) post = post*nc_simplify(_Mul(*args[simp[3]:]), deep=deep) simp = pre*subterm*post if pre != 1 or post != 1: # new simplifications may be possible but no need # to recurse over arguments simp = nc_simplify(simp, deep=False) else: simp = _Mul(*args) if invert: simp = _Pow(simp, -1) # see if factor_nc(expr) is simplified better if not isinstance(expr, MatrixExpr): f_expr = factor_nc(expr) if f_expr != expr: alt_simp = nc_simplify(f_expr, deep=deep) simp = compare(simp, alt_simp) else: simp = simp.doit(inv_expand=False) return simp def dotprodsimp(expr, withsimp=False): """Simplification for a sum of products targeted at the kind of blowup that occurs during summation of products. Intended to reduce expression blowup during matrix multiplication or other similar operations. Only works with algebraic expressions and does not recurse into non. Parameters ========== withsimp : bool, optional Specifies whether a flag should be returned along with the expression to indicate roughly whether simplification was successful. It is used in ``MatrixArithmetic._eval_pow_by_recursion`` to avoid attempting to simplify an expression repetitively which does not simplify. """ def count_ops_alg(expr): """Optimized count algebraic operations with no recursion into non-algebraic args that ``core.function.count_ops`` does. Also returns whether rational functions may be present according to negative exponents of powers or non-number fractions. Returns ======= ops, ratfunc : int, bool ``ops`` is the number of algebraic operations starting at the top level expression (not recursing into non-alg children). ``ratfunc`` specifies whether the expression MAY contain rational functions which ``cancel`` MIGHT optimize. """ ops = 0 args = [expr] ratfunc = False while args: a = args.pop() if not isinstance(a, Basic): continue if a.is_Rational: if a is not S.One: # -1/3 = NEG + DIV ops += bool (a.p < 0) + bool (a.q != 1) elif a.is_Mul: if a.could_extract_minus_sign(): ops += 1 if a.args[0] is S.NegativeOne: a = a.as_two_terms()[1] else: a = -a n, d = fraction(a) if n.is_Integer: ops += 1 + bool (n < 0) args.append(d) # won't be -Mul but could be Add elif d is not S.One: if not d.is_Integer: args.append(d) ratfunc=True ops += 1 args.append(n) # could be -Mul else: ops += len(a.args) - 1 args.extend(a.args) elif a.is_Add: laargs = len(a.args) negs = 0 for ai in a.args: if ai.could_extract_minus_sign(): negs += 1 ai = -ai args.append(ai) ops += laargs - (negs != laargs) # -x - y = NEG + SUB elif a.is_Pow: ops += 1 args.append(a.base) if not ratfunc: ratfunc = a.exp.is_negative is not False return ops, ratfunc def nonalg_subs_dummies(expr, dummies): """Substitute dummy variables for non-algebraic expressions to avoid evaluation of non-algebraic terms that ``polys.polytools.cancel`` does. """ if not expr.args: return expr if expr.is_Add or expr.is_Mul or expr.is_Pow: args = None for i, a in enumerate(expr.args): c = nonalg_subs_dummies(a, dummies) if c is a: continue if args is None: args = list(expr.args) args[i] = c if args is None: return expr return expr.func(*args) return dummies.setdefault(expr, Dummy()) simplified = False # doesn't really mean simplified, rather "can simplify again" if isinstance(expr, Basic) and (expr.is_Add or expr.is_Mul or expr.is_Pow): expr2 = expr.expand(deep=True, modulus=None, power_base=False, power_exp=False, mul=True, log=False, multinomial=True, basic=False) if expr2 != expr: expr = expr2 simplified = True exprops, ratfunc = count_ops_alg(expr) if exprops >= 6: # empirically tested cutoff for expensive simplification if ratfunc: dummies = {} expr2 = nonalg_subs_dummies(expr, dummies) if expr2 is expr or count_ops_alg(expr2)[0] >= 6: # check again after substitution expr3 = cancel(expr2) if expr3 != expr2: expr = expr3.subs([(d, e) for e, d in dummies.items()]) simplified = True # very special case: x/(x-1) - 1/(x-1) -> 1 elif (exprops == 5 and expr.is_Add and expr.args [0].is_Mul and expr.args [1].is_Mul and expr.args [0].args [-1].is_Pow and expr.args [1].args [-1].is_Pow and expr.args [0].args [-1].exp is S.NegativeOne and expr.args [1].args [-1].exp is S.NegativeOne): expr2 = together (expr) expr2ops = count_ops_alg(expr2)[0] if expr2ops < exprops: expr = expr2 simplified = True else: simplified = True return (expr, simplified) if withsimp else expr bottom_up = deprecated( """ Using bottom_up from the sympy.simplify.simplify submodule is deprecated. Instead, use bottom_up from the top-level sympy namespace, like sympy.bottom_up """, deprecated_since_version="1.10", active_deprecations_target="deprecated-traversal-functions-moved", )(_bottom_up) # XXX: This function really should either be private API or exported in the # top-level sympy/__init__.py walk = deprecated( """ Using walk from the sympy.simplify.simplify submodule is deprecated. Instead, use walk from sympy.core.traversal.walk """, deprecated_since_version="1.10", active_deprecations_target="deprecated-traversal-functions-moved", )(_walk)
7e01324b9c56c2f1140d60e403b9dca3d93de8d0f19a37f7007acfe98735cec8
from collections import defaultdict from sympy.core.add import Add from sympy.core.expr import Expr from sympy.core.exprtools import Factors, gcd_terms, factor_terms from sympy.core.function import expand_mul from sympy.core.mul import Mul from sympy.core.numbers import pi, I from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.sorting import ordered from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.core.traversal import bottom_up from sympy.functions.combinatorial.factorials import binomial from sympy.functions.elementary.hyperbolic import ( cosh, sinh, tanh, coth, sech, csch, HyperbolicFunction) from sympy.functions.elementary.trigonometric import ( cos, sin, tan, cot, sec, csc, sqrt, TrigonometricFunction) from sympy.ntheory.factor_ import perfect_power from sympy.polys.polytools import factor from sympy.strategies.tree import greedy from sympy.strategies.core import identity, debug from sympy import SYMPY_DEBUG # ================== Fu-like tools =========================== def TR0(rv): """Simplification of rational polynomials, trying to simplify the expression, e.g. combine things like 3*x + 2*x, etc.... """ # although it would be nice to use cancel, it doesn't work # with noncommutatives return rv.normal().factor().expand() def TR1(rv): """Replace sec, csc with 1/cos, 1/sin Examples ======== >>> from sympy.simplify.fu import TR1, sec, csc >>> from sympy.abc import x >>> TR1(2*csc(x) + sec(x)) 1/cos(x) + 2/sin(x) """ def f(rv): if isinstance(rv, sec): a = rv.args[0] return S.One/cos(a) elif isinstance(rv, csc): a = rv.args[0] return S.One/sin(a) return rv return bottom_up(rv, f) def TR2(rv): """Replace tan and cot with sin/cos and cos/sin Examples ======== >>> from sympy.simplify.fu import TR2 >>> from sympy.abc import x >>> from sympy import tan, cot, sin, cos >>> TR2(tan(x)) sin(x)/cos(x) >>> TR2(cot(x)) cos(x)/sin(x) >>> TR2(tan(tan(x) - sin(x)/cos(x))) 0 """ def f(rv): if isinstance(rv, tan): a = rv.args[0] return sin(a)/cos(a) elif isinstance(rv, cot): a = rv.args[0] return cos(a)/sin(a) return rv return bottom_up(rv, f) def TR2i(rv, half=False): """Converts ratios involving sin and cos as follows:: sin(x)/cos(x) -> tan(x) sin(x)/(cos(x) + 1) -> tan(x/2) if half=True Examples ======== >>> from sympy.simplify.fu import TR2i >>> from sympy.abc import x, a >>> from sympy import sin, cos >>> TR2i(sin(x)/cos(x)) tan(x) Powers of the numerator and denominator are also recognized >>> TR2i(sin(x)**2/(cos(x) + 1)**2, half=True) tan(x/2)**2 The transformation does not take place unless assumptions allow (i.e. the base must be positive or the exponent must be an integer for both numerator and denominator) >>> TR2i(sin(x)**a/(cos(x) + 1)**a) sin(x)**a/(cos(x) + 1)**a """ def f(rv): if not rv.is_Mul: return rv n, d = rv.as_numer_denom() if n.is_Atom or d.is_Atom: return rv def ok(k, e): # initial filtering of factors return ( (e.is_integer or k.is_positive) and ( k.func in (sin, cos) or (half and k.is_Add and len(k.args) >= 2 and any(any(isinstance(ai, cos) or ai.is_Pow and ai.base is cos for ai in Mul.make_args(a)) for a in k.args)))) n = n.as_powers_dict() ndone = [(k, n.pop(k)) for k in list(n.keys()) if not ok(k, n[k])] if not n: return rv d = d.as_powers_dict() ddone = [(k, d.pop(k)) for k in list(d.keys()) if not ok(k, d[k])] if not d: return rv # factoring if necessary def factorize(d, ddone): newk = [] for k in d: if k.is_Add and len(k.args) > 1: knew = factor(k) if half else factor_terms(k) if knew != k: newk.append((k, knew)) if newk: for i, (k, knew) in enumerate(newk): del d[k] newk[i] = knew newk = Mul(*newk).as_powers_dict() for k in newk: v = d[k] + newk[k] if ok(k, v): d[k] = v else: ddone.append((k, v)) del newk factorize(n, ndone) factorize(d, ddone) # joining t = [] for k in n: if isinstance(k, sin): a = cos(k.args[0], evaluate=False) if a in d and d[a] == n[k]: t.append(tan(k.args[0])**n[k]) n[k] = d[a] = None elif half: a1 = 1 + a if a1 in d and d[a1] == n[k]: t.append((tan(k.args[0]/2))**n[k]) n[k] = d[a1] = None elif isinstance(k, cos): a = sin(k.args[0], evaluate=False) if a in d and d[a] == n[k]: t.append(tan(k.args[0])**-n[k]) n[k] = d[a] = None elif half and k.is_Add and k.args[0] is S.One and \ isinstance(k.args[1], cos): a = sin(k.args[1].args[0], evaluate=False) if a in d and d[a] == n[k] and (d[a].is_integer or \ a.is_positive): t.append(tan(a.args[0]/2)**-n[k]) n[k] = d[a] = None if t: rv = Mul(*(t + [b**e for b, e in n.items() if e]))/\ Mul(*[b**e for b, e in d.items() if e]) rv *= Mul(*[b**e for b, e in ndone])/Mul(*[b**e for b, e in ddone]) return rv return bottom_up(rv, f) def TR3(rv): """Induced formula: example sin(-a) = -sin(a) Examples ======== >>> from sympy.simplify.fu import TR3 >>> from sympy.abc import x, y >>> from sympy import pi >>> from sympy import cos >>> TR3(cos(y - x*(y - x))) cos(x*(x - y) + y) >>> cos(pi/2 + x) -sin(x) >>> cos(30*pi/2 + x) -cos(x) """ from sympy.simplify.simplify import signsimp # Negative argument (already automatic for funcs like sin(-x) -> -sin(x) # but more complicated expressions can use it, too). Also, trig angles # between pi/4 and pi/2 are not reduced to an angle between 0 and pi/4. # The following are automatically handled: # Argument of type: pi/2 +/- angle # Argument of type: pi +/- angle # Argument of type : 2k*pi +/- angle def f(rv): if not isinstance(rv, TrigonometricFunction): return rv rv = rv.func(signsimp(rv.args[0])) if not isinstance(rv, TrigonometricFunction): return rv if (rv.args[0] - S.Pi/4).is_positive is (S.Pi/2 - rv.args[0]).is_positive is True: fmap = {cos: sin, sin: cos, tan: cot, cot: tan, sec: csc, csc: sec} rv = fmap[type(rv)](S.Pi/2 - rv.args[0]) return rv return bottom_up(rv, f) def TR4(rv): """Identify values of special angles. a= 0 pi/6 pi/4 pi/3 pi/2 ---------------------------------------------------- sin(a) 0 1/2 sqrt(2)/2 sqrt(3)/2 1 cos(a) 1 sqrt(3)/2 sqrt(2)/2 1/2 0 tan(a) 0 sqt(3)/3 1 sqrt(3) -- Examples ======== >>> from sympy import pi >>> from sympy import cos, sin, tan, cot >>> for s in (0, pi/6, pi/4, pi/3, pi/2): ... print('%s %s %s %s' % (cos(s), sin(s), tan(s), cot(s))) ... 1 0 0 zoo sqrt(3)/2 1/2 sqrt(3)/3 sqrt(3) sqrt(2)/2 sqrt(2)/2 1 1 1/2 sqrt(3)/2 sqrt(3) sqrt(3)/3 0 1 zoo 0 """ # special values at 0, pi/6, pi/4, pi/3, pi/2 already handled return rv def _TR56(rv, f, g, h, max, pow): """Helper for TR5 and TR6 to replace f**2 with h(g**2) Options ======= max : controls size of exponent that can appear on f e.g. if max=4 then f**4 will be changed to h(g**2)**2. pow : controls whether the exponent must be a perfect power of 2 e.g. if pow=True (and max >= 6) then f**6 will not be changed but f**8 will be changed to h(g**2)**4 >>> from sympy.simplify.fu import _TR56 as T >>> from sympy.abc import x >>> from sympy import sin, cos >>> h = lambda x: 1 - x >>> T(sin(x)**3, sin, cos, h, 4, False) (1 - cos(x)**2)*sin(x) >>> T(sin(x)**6, sin, cos, h, 6, False) (1 - cos(x)**2)**3 >>> T(sin(x)**6, sin, cos, h, 6, True) sin(x)**6 >>> T(sin(x)**8, sin, cos, h, 10, True) (1 - cos(x)**2)**4 """ def _f(rv): # I'm not sure if this transformation should target all even powers # or only those expressible as powers of 2. Also, should it only # make the changes in powers that appear in sums -- making an isolated # change is not going to allow a simplification as far as I can tell. if not (rv.is_Pow and rv.base.func == f): return rv if not rv.exp.is_real: return rv if (rv.exp < 0) == True: return rv if (rv.exp > max) == True: return rv if rv.exp == 1: return rv if rv.exp == 2: return h(g(rv.base.args[0])**2) else: if rv.exp % 2 == 1: e = rv.exp//2 return f(rv.base.args[0])*h(g(rv.base.args[0])**2)**e elif rv.exp == 4: e = 2 elif not pow: if rv.exp % 2: return rv e = rv.exp//2 else: p = perfect_power(rv.exp) if not p: return rv e = rv.exp//2 return h(g(rv.base.args[0])**2)**e return bottom_up(rv, _f) def TR5(rv, max=4, pow=False): """Replacement of sin**2 with 1 - cos(x)**2. See _TR56 docstring for advanced use of ``max`` and ``pow``. Examples ======== >>> from sympy.simplify.fu import TR5 >>> from sympy.abc import x >>> from sympy import sin >>> TR5(sin(x)**2) 1 - cos(x)**2 >>> TR5(sin(x)**-2) # unchanged sin(x)**(-2) >>> TR5(sin(x)**4) (1 - cos(x)**2)**2 """ return _TR56(rv, sin, cos, lambda x: 1 - x, max=max, pow=pow) def TR6(rv, max=4, pow=False): """Replacement of cos**2 with 1 - sin(x)**2. See _TR56 docstring for advanced use of ``max`` and ``pow``. Examples ======== >>> from sympy.simplify.fu import TR6 >>> from sympy.abc import x >>> from sympy import cos >>> TR6(cos(x)**2) 1 - sin(x)**2 >>> TR6(cos(x)**-2) #unchanged cos(x)**(-2) >>> TR6(cos(x)**4) (1 - sin(x)**2)**2 """ return _TR56(rv, cos, sin, lambda x: 1 - x, max=max, pow=pow) def TR7(rv): """Lowering the degree of cos(x)**2. Examples ======== >>> from sympy.simplify.fu import TR7 >>> from sympy.abc import x >>> from sympy import cos >>> TR7(cos(x)**2) cos(2*x)/2 + 1/2 >>> TR7(cos(x)**2 + 1) cos(2*x)/2 + 3/2 """ def f(rv): if not (rv.is_Pow and rv.base.func == cos and rv.exp == 2): return rv return (1 + cos(2*rv.base.args[0]))/2 return bottom_up(rv, f) def TR8(rv, first=True): """Converting products of ``cos`` and/or ``sin`` to a sum or difference of ``cos`` and or ``sin`` terms. Examples ======== >>> from sympy.simplify.fu import TR8 >>> from sympy import cos, sin >>> TR8(cos(2)*cos(3)) cos(5)/2 + cos(1)/2 >>> TR8(cos(2)*sin(3)) sin(5)/2 + sin(1)/2 >>> TR8(sin(2)*sin(3)) -cos(5)/2 + cos(1)/2 """ def f(rv): if not ( rv.is_Mul or rv.is_Pow and rv.base.func in (cos, sin) and (rv.exp.is_integer or rv.base.is_positive)): return rv if first: n, d = [expand_mul(i) for i in rv.as_numer_denom()] newn = TR8(n, first=False) newd = TR8(d, first=False) if newn != n or newd != d: rv = gcd_terms(newn/newd) if rv.is_Mul and rv.args[0].is_Rational and \ len(rv.args) == 2 and rv.args[1].is_Add: rv = Mul(*rv.as_coeff_Mul()) return rv args = {cos: [], sin: [], None: []} for a in ordered(Mul.make_args(rv)): if a.func in (cos, sin): args[type(a)].append(a.args[0]) elif (a.is_Pow and a.exp.is_Integer and a.exp > 0 and \ a.base.func in (cos, sin)): # XXX this is ok but pathological expression could be handled # more efficiently as in TRmorrie args[type(a.base)].extend([a.base.args[0]]*a.exp) else: args[None].append(a) c = args[cos] s = args[sin] if not (c and s or len(c) > 1 or len(s) > 1): return rv args = args[None] n = min(len(c), len(s)) for i in range(n): a1 = s.pop() a2 = c.pop() args.append((sin(a1 + a2) + sin(a1 - a2))/2) while len(c) > 1: a1 = c.pop() a2 = c.pop() args.append((cos(a1 + a2) + cos(a1 - a2))/2) if c: args.append(cos(c.pop())) while len(s) > 1: a1 = s.pop() a2 = s.pop() args.append((-cos(a1 + a2) + cos(a1 - a2))/2) if s: args.append(sin(s.pop())) return TR8(expand_mul(Mul(*args))) return bottom_up(rv, f) def TR9(rv): """Sum of ``cos`` or ``sin`` terms as a product of ``cos`` or ``sin``. Examples ======== >>> from sympy.simplify.fu import TR9 >>> from sympy import cos, sin >>> TR9(cos(1) + cos(2)) 2*cos(1/2)*cos(3/2) >>> TR9(cos(1) + 2*sin(1) + 2*sin(2)) cos(1) + 4*sin(3/2)*cos(1/2) If no change is made by TR9, no re-arrangement of the expression will be made. For example, though factoring of common term is attempted, if the factored expression was not changed, the original expression will be returned: >>> TR9(cos(3) + cos(3)*cos(2)) cos(3) + cos(2)*cos(3) """ def f(rv): if not rv.is_Add: return rv def do(rv, first=True): # cos(a)+/-cos(b) can be combined into a product of cosines and # sin(a)+/-sin(b) can be combined into a product of cosine and # sine. # # If there are more than two args, the pairs which "work" will # have a gcd extractable and the remaining two terms will have # the above structure -- all pairs must be checked to find the # ones that work. args that don't have a common set of symbols # are skipped since this doesn't lead to a simpler formula and # also has the arbitrariness of combining, for example, the x # and y term instead of the y and z term in something like # cos(x) + cos(y) + cos(z). if not rv.is_Add: return rv args = list(ordered(rv.args)) if len(args) != 2: hit = False for i in range(len(args)): ai = args[i] if ai is None: continue for j in range(i + 1, len(args)): aj = args[j] if aj is None: continue was = ai + aj new = do(was) if new != was: args[i] = new # update in place args[j] = None hit = True break # go to next i if hit: rv = Add(*[_f for _f in args if _f]) if rv.is_Add: rv = do(rv) return rv # two-arg Add split = trig_split(*args) if not split: return rv gcd, n1, n2, a, b, iscos = split # application of rule if possible if iscos: if n1 == n2: return gcd*n1*2*cos((a + b)/2)*cos((a - b)/2) if n1 < 0: a, b = b, a return -2*gcd*sin((a + b)/2)*sin((a - b)/2) else: if n1 == n2: return gcd*n1*2*sin((a + b)/2)*cos((a - b)/2) if n1 < 0: a, b = b, a return 2*gcd*cos((a + b)/2)*sin((a - b)/2) return process_common_addends(rv, do) # DON'T sift by free symbols return bottom_up(rv, f) def TR10(rv, first=True): """Separate sums in ``cos`` and ``sin``. Examples ======== >>> from sympy.simplify.fu import TR10 >>> from sympy.abc import a, b, c >>> from sympy import cos, sin >>> TR10(cos(a + b)) -sin(a)*sin(b) + cos(a)*cos(b) >>> TR10(sin(a + b)) sin(a)*cos(b) + sin(b)*cos(a) >>> TR10(sin(a + b + c)) (-sin(a)*sin(b) + cos(a)*cos(b))*sin(c) + \ (sin(a)*cos(b) + sin(b)*cos(a))*cos(c) """ def f(rv): if rv.func not in (cos, sin): return rv f = rv.func arg = rv.args[0] if arg.is_Add: if first: args = list(ordered(arg.args)) else: args = list(arg.args) a = args.pop() b = Add._from_args(args) if b.is_Add: if f == sin: return sin(a)*TR10(cos(b), first=False) + \ cos(a)*TR10(sin(b), first=False) else: return cos(a)*TR10(cos(b), first=False) - \ sin(a)*TR10(sin(b), first=False) else: if f == sin: return sin(a)*cos(b) + cos(a)*sin(b) else: return cos(a)*cos(b) - sin(a)*sin(b) return rv return bottom_up(rv, f) def TR10i(rv): """Sum of products to function of sum. Examples ======== >>> from sympy.simplify.fu import TR10i >>> from sympy import cos, sin, sqrt >>> from sympy.abc import x >>> TR10i(cos(1)*cos(3) + sin(1)*sin(3)) cos(2) >>> TR10i(cos(1)*sin(3) + sin(1)*cos(3) + cos(3)) cos(3) + sin(4) >>> TR10i(sqrt(2)*cos(x)*x + sqrt(6)*sin(x)*x) 2*sqrt(2)*x*sin(x + pi/6) """ global _ROOT2, _ROOT3, _invROOT3 if _ROOT2 is None: _roots() def f(rv): if not rv.is_Add: return rv def do(rv, first=True): # args which can be expressed as A*(cos(a)*cos(b)+/-sin(a)*sin(b)) # or B*(cos(a)*sin(b)+/-cos(b)*sin(a)) can be combined into # A*f(a+/-b) where f is either sin or cos. # # If there are more than two args, the pairs which "work" will have # a gcd extractable and the remaining two terms will have the above # structure -- all pairs must be checked to find the ones that # work. if not rv.is_Add: return rv args = list(ordered(rv.args)) if len(args) != 2: hit = False for i in range(len(args)): ai = args[i] if ai is None: continue for j in range(i + 1, len(args)): aj = args[j] if aj is None: continue was = ai + aj new = do(was) if new != was: args[i] = new # update in place args[j] = None hit = True break # go to next i if hit: rv = Add(*[_f for _f in args if _f]) if rv.is_Add: rv = do(rv) return rv # two-arg Add split = trig_split(*args, two=True) if not split: return rv gcd, n1, n2, a, b, same = split # identify and get c1 to be cos then apply rule if possible if same: # coscos, sinsin gcd = n1*gcd if n1 == n2: return gcd*cos(a - b) return gcd*cos(a + b) else: #cossin, cossin gcd = n1*gcd if n1 == n2: return gcd*sin(a + b) return gcd*sin(b - a) rv = process_common_addends( rv, do, lambda x: tuple(ordered(x.free_symbols))) # need to check for inducible pairs in ratio of sqrt(3):1 that # appeared in different lists when sorting by coefficient while rv.is_Add: byrad = defaultdict(list) for a in rv.args: hit = 0 if a.is_Mul: for ai in a.args: if ai.is_Pow and ai.exp is S.Half and \ ai.base.is_Integer: byrad[ai].append(a) hit = 1 break if not hit: byrad[S.One].append(a) # no need to check all pairs -- just check for the onees # that have the right ratio args = [] for a in byrad: for b in [_ROOT3*a, _invROOT3]: if b in byrad: for i in range(len(byrad[a])): if byrad[a][i] is None: continue for j in range(len(byrad[b])): if byrad[b][j] is None: continue was = Add(byrad[a][i] + byrad[b][j]) new = do(was) if new != was: args.append(new) byrad[a][i] = None byrad[b][j] = None break if args: rv = Add(*(args + [Add(*[_f for _f in v if _f]) for v in byrad.values()])) else: rv = do(rv) # final pass to resolve any new inducible pairs break return rv return bottom_up(rv, f) def TR11(rv, base=None): """Function of double angle to product. The ``base`` argument can be used to indicate what is the un-doubled argument, e.g. if 3*pi/7 is the base then cosine and sine functions with argument 6*pi/7 will be replaced. Examples ======== >>> from sympy.simplify.fu import TR11 >>> from sympy import cos, sin, pi >>> from sympy.abc import x >>> TR11(sin(2*x)) 2*sin(x)*cos(x) >>> TR11(cos(2*x)) -sin(x)**2 + cos(x)**2 >>> TR11(sin(4*x)) 4*(-sin(x)**2 + cos(x)**2)*sin(x)*cos(x) >>> TR11(sin(4*x/3)) 4*(-sin(x/3)**2 + cos(x/3)**2)*sin(x/3)*cos(x/3) If the arguments are simply integers, no change is made unless a base is provided: >>> TR11(cos(2)) cos(2) >>> TR11(cos(4), 2) -sin(2)**2 + cos(2)**2 There is a subtle issue here in that autosimplification will convert some higher angles to lower angles >>> cos(6*pi/7) + cos(3*pi/7) -cos(pi/7) + cos(3*pi/7) The 6*pi/7 angle is now pi/7 but can be targeted with TR11 by supplying the 3*pi/7 base: >>> TR11(_, 3*pi/7) -sin(3*pi/7)**2 + cos(3*pi/7)**2 + cos(3*pi/7) """ def f(rv): if rv.func not in (cos, sin): return rv if base: f = rv.func t = f(base*2) co = S.One if t.is_Mul: co, t = t.as_coeff_Mul() if t.func not in (cos, sin): return rv if rv.args[0] == t.args[0]: c = cos(base) s = sin(base) if f is cos: return (c**2 - s**2)/co else: return 2*c*s/co return rv elif not rv.args[0].is_Number: # make a change if the leading coefficient's numerator is # divisible by 2 c, m = rv.args[0].as_coeff_Mul(rational=True) if c.p % 2 == 0: arg = c.p//2*m/c.q c = TR11(cos(arg)) s = TR11(sin(arg)) if rv.func == sin: rv = 2*s*c else: rv = c**2 - s**2 return rv return bottom_up(rv, f) def _TR11(rv): """ Helper for TR11 to find half-arguments for sin in factors of num/den that appear in cos or sin factors in the den/num. Examples ======== >>> from sympy.simplify.fu import TR11, _TR11 >>> from sympy import cos, sin >>> from sympy.abc import x >>> TR11(sin(x/3)/(cos(x/6))) sin(x/3)/cos(x/6) >>> _TR11(sin(x/3)/(cos(x/6))) 2*sin(x/6) >>> TR11(sin(x/6)/(sin(x/3))) sin(x/6)/sin(x/3) >>> _TR11(sin(x/6)/(sin(x/3))) 1/(2*cos(x/6)) """ def f(rv): if not isinstance(rv, Expr): return rv def sincos_args(flat): # find arguments of sin and cos that # appears as bases in args of flat # and have Integer exponents args = defaultdict(set) for fi in Mul.make_args(flat): b, e = fi.as_base_exp() if e.is_Integer and e > 0: if b.func in (cos, sin): args[type(b)].add(b.args[0]) return args num_args, den_args = map(sincos_args, rv.as_numer_denom()) def handle_match(rv, num_args, den_args): # for arg in sin args of num_args, look for arg/2 # in den_args and pass this half-angle to TR11 # for handling in rv for narg in num_args[sin]: half = narg/2 if half in den_args[cos]: func = cos elif half in den_args[sin]: func = sin else: continue rv = TR11(rv, half) den_args[func].remove(half) return rv # sin in num, sin or cos in den rv = handle_match(rv, num_args, den_args) # sin in den, sin or cos in num rv = handle_match(rv, den_args, num_args) return rv return bottom_up(rv, f) def TR12(rv, first=True): """Separate sums in ``tan``. Examples ======== >>> from sympy.abc import x, y >>> from sympy import tan >>> from sympy.simplify.fu import TR12 >>> TR12(tan(x + y)) (tan(x) + tan(y))/(-tan(x)*tan(y) + 1) """ def f(rv): if not rv.func == tan: return rv arg = rv.args[0] if arg.is_Add: if first: args = list(ordered(arg.args)) else: args = list(arg.args) a = args.pop() b = Add._from_args(args) if b.is_Add: tb = TR12(tan(b), first=False) else: tb = tan(b) return (tan(a) + tb)/(1 - tan(a)*tb) return rv return bottom_up(rv, f) def TR12i(rv): """Combine tan arguments as (tan(y) + tan(x))/(tan(x)*tan(y) - 1) -> -tan(x + y). Examples ======== >>> from sympy.simplify.fu import TR12i >>> from sympy import tan >>> from sympy.abc import a, b, c >>> ta, tb, tc = [tan(i) for i in (a, b, c)] >>> TR12i((ta + tb)/(-ta*tb + 1)) tan(a + b) >>> TR12i((ta + tb)/(ta*tb - 1)) -tan(a + b) >>> TR12i((-ta - tb)/(ta*tb - 1)) tan(a + b) >>> eq = (ta + tb)/(-ta*tb + 1)**2*(-3*ta - 3*tc)/(2*(ta*tc - 1)) >>> TR12i(eq.expand()) -3*tan(a + b)*tan(a + c)/(2*(tan(a) + tan(b) - 1)) """ def f(rv): if not (rv.is_Add or rv.is_Mul or rv.is_Pow): return rv n, d = rv.as_numer_denom() if not d.args or not n.args: return rv dok = {} def ok(di): m = as_f_sign_1(di) if m: g, f, s = m if s is S.NegativeOne and f.is_Mul and len(f.args) == 2 and \ all(isinstance(fi, tan) for fi in f.args): return g, f d_args = list(Mul.make_args(d)) for i, di in enumerate(d_args): m = ok(di) if m: g, t = m s = Add(*[_.args[0] for _ in t.args]) dok[s] = S.One d_args[i] = g continue if di.is_Add: di = factor(di) if di.is_Mul: d_args.extend(di.args) d_args[i] = S.One elif di.is_Pow and (di.exp.is_integer or di.base.is_positive): m = ok(di.base) if m: g, t = m s = Add(*[_.args[0] for _ in t.args]) dok[s] = di.exp d_args[i] = g**di.exp else: di = factor(di) if di.is_Mul: d_args.extend(di.args) d_args[i] = S.One if not dok: return rv def ok(ni): if ni.is_Add and len(ni.args) == 2: a, b = ni.args if isinstance(a, tan) and isinstance(b, tan): return a, b n_args = list(Mul.make_args(factor_terms(n))) hit = False for i, ni in enumerate(n_args): m = ok(ni) if not m: m = ok(-ni) if m: n_args[i] = S.NegativeOne else: if ni.is_Add: ni = factor(ni) if ni.is_Mul: n_args.extend(ni.args) n_args[i] = S.One continue elif ni.is_Pow and ( ni.exp.is_integer or ni.base.is_positive): m = ok(ni.base) if m: n_args[i] = S.One else: ni = factor(ni) if ni.is_Mul: n_args.extend(ni.args) n_args[i] = S.One continue else: continue else: n_args[i] = S.One hit = True s = Add(*[_.args[0] for _ in m]) ed = dok[s] newed = ed.extract_additively(S.One) if newed is not None: if newed: dok[s] = newed else: dok.pop(s) n_args[i] *= -tan(s) if hit: rv = Mul(*n_args)/Mul(*d_args)/Mul(*[(Add(*[ tan(a) for a in i.args]) - 1)**e for i, e in dok.items()]) return rv return bottom_up(rv, f) def TR13(rv): """Change products of ``tan`` or ``cot``. Examples ======== >>> from sympy.simplify.fu import TR13 >>> from sympy import tan, cot >>> TR13(tan(3)*tan(2)) -tan(2)/tan(5) - tan(3)/tan(5) + 1 >>> TR13(cot(3)*cot(2)) cot(2)*cot(5) + 1 + cot(3)*cot(5) """ def f(rv): if not rv.is_Mul: return rv # XXX handle products of powers? or let power-reducing handle it? args = {tan: [], cot: [], None: []} for a in ordered(Mul.make_args(rv)): if a.func in (tan, cot): args[type(a)].append(a.args[0]) else: args[None].append(a) t = args[tan] c = args[cot] if len(t) < 2 and len(c) < 2: return rv args = args[None] while len(t) > 1: t1 = t.pop() t2 = t.pop() args.append(1 - (tan(t1)/tan(t1 + t2) + tan(t2)/tan(t1 + t2))) if t: args.append(tan(t.pop())) while len(c) > 1: t1 = c.pop() t2 = c.pop() args.append(1 + cot(t1)*cot(t1 + t2) + cot(t2)*cot(t1 + t2)) if c: args.append(cot(c.pop())) return Mul(*args) return bottom_up(rv, f) def TRmorrie(rv): """Returns cos(x)*cos(2*x)*...*cos(2**(k-1)*x) -> sin(2**k*x)/(2**k*sin(x)) Examples ======== >>> from sympy.simplify.fu import TRmorrie, TR8, TR3 >>> from sympy.abc import x >>> from sympy import Mul, cos, pi >>> TRmorrie(cos(x)*cos(2*x)) sin(4*x)/(4*sin(x)) >>> TRmorrie(7*Mul(*[cos(x) for x in range(10)])) 7*sin(12)*sin(16)*cos(5)*cos(7)*cos(9)/(64*sin(1)*sin(3)) Sometimes autosimplification will cause a power to be not recognized. e.g. in the following, cos(4*pi/7) automatically simplifies to -cos(3*pi/7) so only 2 of the 3 terms are recognized: >>> TRmorrie(cos(pi/7)*cos(2*pi/7)*cos(4*pi/7)) -sin(3*pi/7)*cos(3*pi/7)/(4*sin(pi/7)) A touch by TR8 resolves the expression to a Rational >>> TR8(_) -1/8 In this case, if eq is unsimplified, the answer is obtained directly: >>> eq = cos(pi/9)*cos(2*pi/9)*cos(3*pi/9)*cos(4*pi/9) >>> TRmorrie(eq) 1/16 But if angles are made canonical with TR3 then the answer is not simplified without further work: >>> TR3(eq) sin(pi/18)*cos(pi/9)*cos(2*pi/9)/2 >>> TRmorrie(_) sin(pi/18)*sin(4*pi/9)/(8*sin(pi/9)) >>> TR8(_) cos(7*pi/18)/(16*sin(pi/9)) >>> TR3(_) 1/16 The original expression would have resolve to 1/16 directly with TR8, however: >>> TR8(eq) 1/16 References ========== .. [1] https://en.wikipedia.org/wiki/Morrie%27s_law """ def f(rv, first=True): if not rv.is_Mul: return rv if first: n, d = rv.as_numer_denom() return f(n, 0)/f(d, 0) args = defaultdict(list) coss = {} other = [] for c in rv.args: b, e = c.as_base_exp() if e.is_Integer and isinstance(b, cos): co, a = b.args[0].as_coeff_Mul() args[a].append(co) coss[b] = e else: other.append(c) new = [] for a in args: c = args[a] c.sort() while c: k = 0 cc = ci = c[0] while cc in c: k += 1 cc *= 2 if k > 1: newarg = sin(2**k*ci*a)/2**k/sin(ci*a) # see how many times this can be taken take = None ccs = [] for i in range(k): cc /= 2 key = cos(a*cc, evaluate=False) ccs.append(cc) take = min(coss[key], take or coss[key]) # update exponent counts for i in range(k): cc = ccs.pop() key = cos(a*cc, evaluate=False) coss[key] -= take if not coss[key]: c.remove(cc) new.append(newarg**take) else: b = cos(c.pop(0)*a) other.append(b**coss[b]) if new: rv = Mul(*(new + other + [ cos(k*a, evaluate=False) for a in args for k in args[a]])) return rv return bottom_up(rv, f) def TR14(rv, first=True): """Convert factored powers of sin and cos identities into simpler expressions. Examples ======== >>> from sympy.simplify.fu import TR14 >>> from sympy.abc import x, y >>> from sympy import cos, sin >>> TR14((cos(x) - 1)*(cos(x) + 1)) -sin(x)**2 >>> TR14((sin(x) - 1)*(sin(x) + 1)) -cos(x)**2 >>> p1 = (cos(x) + 1)*(cos(x) - 1) >>> p2 = (cos(y) - 1)*2*(cos(y) + 1) >>> p3 = (3*(cos(y) - 1))*(3*(cos(y) + 1)) >>> TR14(p1*p2*p3*(x - 1)) -18*(x - 1)*sin(x)**2*sin(y)**4 """ def f(rv): if not rv.is_Mul: return rv if first: # sort them by location in numerator and denominator # so the code below can just deal with positive exponents n, d = rv.as_numer_denom() if d is not S.One: newn = TR14(n, first=False) newd = TR14(d, first=False) if newn != n or newd != d: rv = newn/newd return rv other = [] process = [] for a in rv.args: if a.is_Pow: b, e = a.as_base_exp() if not (e.is_integer or b.is_positive): other.append(a) continue a = b else: e = S.One m = as_f_sign_1(a) if not m or m[1].func not in (cos, sin): if e is S.One: other.append(a) else: other.append(a**e) continue g, f, si = m process.append((g, e.is_Number, e, f, si, a)) # sort them to get like terms next to each other process = list(ordered(process)) # keep track of whether there was any change nother = len(other) # access keys keys = (g, t, e, f, si, a) = list(range(6)) while process: A = process.pop(0) if process: B = process[0] if A[e].is_Number and B[e].is_Number: # both exponents are numbers if A[f] == B[f]: if A[si] != B[si]: B = process.pop(0) take = min(A[e], B[e]) # reinsert any remainder # the B will likely sort after A so check it first if B[e] != take: rem = [B[i] for i in keys] rem[e] -= take process.insert(0, rem) elif A[e] != take: rem = [A[i] for i in keys] rem[e] -= take process.insert(0, rem) if isinstance(A[f], cos): t = sin else: t = cos other.append((-A[g]*B[g]*t(A[f].args[0])**2)**take) continue elif A[e] == B[e]: # both exponents are equal symbols if A[f] == B[f]: if A[si] != B[si]: B = process.pop(0) take = A[e] if isinstance(A[f], cos): t = sin else: t = cos other.append((-A[g]*B[g]*t(A[f].args[0])**2)**take) continue # either we are done or neither condition above applied other.append(A[a]**A[e]) if len(other) != nother: rv = Mul(*other) return rv return bottom_up(rv, f) def TR15(rv, max=4, pow=False): """Convert sin(x)**-2 to 1 + cot(x)**2. See _TR56 docstring for advanced use of ``max`` and ``pow``. Examples ======== >>> from sympy.simplify.fu import TR15 >>> from sympy.abc import x >>> from sympy import sin >>> TR15(1 - 1/sin(x)**2) -cot(x)**2 """ def f(rv): if not (isinstance(rv, Pow) and isinstance(rv.base, sin)): return rv e = rv.exp if e % 2 == 1: return TR15(rv.base**(e + 1))/rv.base ia = 1/rv a = _TR56(ia, sin, cot, lambda x: 1 + x, max=max, pow=pow) if a != ia: rv = a return rv return bottom_up(rv, f) def TR16(rv, max=4, pow=False): """Convert cos(x)**-2 to 1 + tan(x)**2. See _TR56 docstring for advanced use of ``max`` and ``pow``. Examples ======== >>> from sympy.simplify.fu import TR16 >>> from sympy.abc import x >>> from sympy import cos >>> TR16(1 - 1/cos(x)**2) -tan(x)**2 """ def f(rv): if not (isinstance(rv, Pow) and isinstance(rv.base, cos)): return rv e = rv.exp if e % 2 == 1: return TR15(rv.base**(e + 1))/rv.base ia = 1/rv a = _TR56(ia, cos, tan, lambda x: 1 + x, max=max, pow=pow) if a != ia: rv = a return rv return bottom_up(rv, f) def TR111(rv): """Convert f(x)**-i to g(x)**i where either ``i`` is an integer or the base is positive and f, g are: tan, cot; sin, csc; or cos, sec. Examples ======== >>> from sympy.simplify.fu import TR111 >>> from sympy.abc import x >>> from sympy import tan >>> TR111(1 - 1/tan(x)**2) 1 - cot(x)**2 """ def f(rv): if not ( isinstance(rv, Pow) and (rv.base.is_positive or rv.exp.is_integer and rv.exp.is_negative)): return rv if isinstance(rv.base, tan): return cot(rv.base.args[0])**-rv.exp elif isinstance(rv.base, sin): return csc(rv.base.args[0])**-rv.exp elif isinstance(rv.base, cos): return sec(rv.base.args[0])**-rv.exp return rv return bottom_up(rv, f) def TR22(rv, max=4, pow=False): """Convert tan(x)**2 to sec(x)**2 - 1 and cot(x)**2 to csc(x)**2 - 1. See _TR56 docstring for advanced use of ``max`` and ``pow``. Examples ======== >>> from sympy.simplify.fu import TR22 >>> from sympy.abc import x >>> from sympy import tan, cot >>> TR22(1 + tan(x)**2) sec(x)**2 >>> TR22(1 + cot(x)**2) csc(x)**2 """ def f(rv): if not (isinstance(rv, Pow) and rv.base.func in (cot, tan)): return rv rv = _TR56(rv, tan, sec, lambda x: x - 1, max=max, pow=pow) rv = _TR56(rv, cot, csc, lambda x: x - 1, max=max, pow=pow) return rv return bottom_up(rv, f) def TRpower(rv): """Convert sin(x)**n and cos(x)**n with positive n to sums. Examples ======== >>> from sympy.simplify.fu import TRpower >>> from sympy.abc import x >>> from sympy import cos, sin >>> TRpower(sin(x)**6) -15*cos(2*x)/32 + 3*cos(4*x)/16 - cos(6*x)/32 + 5/16 >>> TRpower(sin(x)**3*cos(2*x)**4) (3*sin(x)/4 - sin(3*x)/4)*(cos(4*x)/2 + cos(8*x)/8 + 3/8) References ========== .. [1] https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Power-reduction_formulae """ def f(rv): if not (isinstance(rv, Pow) and isinstance(rv.base, (sin, cos))): return rv b, n = rv.as_base_exp() x = b.args[0] if n.is_Integer and n.is_positive: if n.is_odd and isinstance(b, cos): rv = 2**(1-n)*Add(*[binomial(n, k)*cos((n - 2*k)*x) for k in range((n + 1)/2)]) elif n.is_odd and isinstance(b, sin): rv = 2**(1-n)*S.NegativeOne**((n-1)/2)*Add(*[binomial(n, k)* S.NegativeOne**k*sin((n - 2*k)*x) for k in range((n + 1)/2)]) elif n.is_even and isinstance(b, cos): rv = 2**(1-n)*Add(*[binomial(n, k)*cos((n - 2*k)*x) for k in range(n/2)]) elif n.is_even and isinstance(b, sin): rv = 2**(1-n)*S.NegativeOne**(n/2)*Add(*[binomial(n, k)* S.NegativeOne**k*cos((n - 2*k)*x) for k in range(n/2)]) if n.is_even: rv += 2**(-n)*binomial(n, n/2) return rv return bottom_up(rv, f) def L(rv): """Return count of trigonometric functions in expression. Examples ======== >>> from sympy.simplify.fu import L >>> from sympy.abc import x >>> from sympy import cos, sin >>> L(cos(x)+sin(x)) 2 """ return S(rv.count(TrigonometricFunction)) # ============== end of basic Fu-like tools ===================== if SYMPY_DEBUG: (TR0, TR1, TR2, TR3, TR4, TR5, TR6, TR7, TR8, TR9, TR10, TR11, TR12, TR13, TR2i, TRmorrie, TR14, TR15, TR16, TR12i, TR111, TR22 )= list(map(debug, (TR0, TR1, TR2, TR3, TR4, TR5, TR6, TR7, TR8, TR9, TR10, TR11, TR12, TR13, TR2i, TRmorrie, TR14, TR15, TR16, TR12i, TR111, TR22))) # tuples are chains -- (f, g) -> lambda x: g(f(x)) # lists are choices -- [f, g] -> lambda x: min(f(x), g(x), key=objective) CTR1 = [(TR5, TR0), (TR6, TR0), identity] CTR2 = (TR11, [(TR5, TR0), (TR6, TR0), TR0]) CTR3 = [(TRmorrie, TR8, TR0), (TRmorrie, TR8, TR10i, TR0), identity] CTR4 = [(TR4, TR10i), identity] RL1 = (TR4, TR3, TR4, TR12, TR4, TR13, TR4, TR0) # XXX it's a little unclear how this one is to be implemented # see Fu paper of reference, page 7. What is the Union symbol referring to? # The diagram shows all these as one chain of transformations, but the # text refers to them being applied independently. Also, a break # if L starts to increase has not been implemented. RL2 = [ (TR4, TR3, TR10, TR4, TR3, TR11), (TR5, TR7, TR11, TR4), (CTR3, CTR1, TR9, CTR2, TR4, TR9, TR9, CTR4), identity, ] def fu(rv, measure=lambda x: (L(x), x.count_ops())): """Attempt to simplify expression by using transformation rules given in the algorithm by Fu et al. :func:`fu` will try to minimize the objective function ``measure``. By default this first minimizes the number of trig terms and then minimizes the number of total operations. Examples ======== >>> from sympy.simplify.fu import fu >>> from sympy import cos, sin, tan, pi, S, sqrt >>> from sympy.abc import x, y, a, b >>> fu(sin(50)**2 + cos(50)**2 + sin(pi/6)) 3/2 >>> fu(sqrt(6)*cos(x) + sqrt(2)*sin(x)) 2*sqrt(2)*sin(x + pi/3) CTR1 example >>> eq = sin(x)**4 - cos(y)**2 + sin(y)**2 + 2*cos(x)**2 >>> fu(eq) cos(x)**4 - 2*cos(y)**2 + 2 CTR2 example >>> fu(S.Half - cos(2*x)/2) sin(x)**2 CTR3 example >>> fu(sin(a)*(cos(b) - sin(b)) + cos(a)*(sin(b) + cos(b))) sqrt(2)*sin(a + b + pi/4) CTR4 example >>> fu(sqrt(3)*cos(x)/2 + sin(x)/2) sin(x + pi/3) Example 1 >>> fu(1-sin(2*x)**2/4-sin(y)**2-cos(x)**4) -cos(x)**2 + cos(y)**2 Example 2 >>> fu(cos(4*pi/9)) sin(pi/18) >>> fu(cos(pi/9)*cos(2*pi/9)*cos(3*pi/9)*cos(4*pi/9)) 1/16 Example 3 >>> fu(tan(7*pi/18)+tan(5*pi/18)-sqrt(3)*tan(5*pi/18)*tan(7*pi/18)) -sqrt(3) Objective function example >>> fu(sin(x)/cos(x)) # default objective function tan(x) >>> fu(sin(x)/cos(x), measure=lambda x: -x.count_ops()) # maximize op count sin(x)/cos(x) References ========== .. [1] https://www.sciencedirect.com/science/article/pii/S0895717706001609 """ fRL1 = greedy(RL1, measure) fRL2 = greedy(RL2, measure) was = rv rv = sympify(rv) if not isinstance(rv, Expr): return rv.func(*[fu(a, measure=measure) for a in rv.args]) rv = TR1(rv) if rv.has(tan, cot): rv1 = fRL1(rv) if (measure(rv1) < measure(rv)): rv = rv1 if rv.has(tan, cot): rv = TR2(rv) if rv.has(sin, cos): rv1 = fRL2(rv) rv2 = TR8(TRmorrie(rv1)) rv = min([was, rv, rv1, rv2], key=measure) return min(TR2i(rv), rv, key=measure) def process_common_addends(rv, do, key2=None, key1=True): """Apply ``do`` to addends of ``rv`` that (if ``key1=True``) share at least a common absolute value of their coefficient and the value of ``key2`` when applied to the argument. If ``key1`` is False ``key2`` must be supplied and will be the only key applied. """ # collect by absolute value of coefficient and key2 absc = defaultdict(list) if key1: for a in rv.args: c, a = a.as_coeff_Mul() if c < 0: c = -c a = -a # put the sign on `a` absc[(c, key2(a) if key2 else 1)].append(a) elif key2: for a in rv.args: absc[(S.One, key2(a))].append(a) else: raise ValueError('must have at least one key') args = [] hit = False for k in absc: v = absc[k] c, _ = k if len(v) > 1: e = Add(*v, evaluate=False) new = do(e) if new != e: e = new hit = True args.append(c*e) else: args.append(c*v[0]) if hit: rv = Add(*args) return rv fufuncs = ''' TR0 TR1 TR2 TR3 TR4 TR5 TR6 TR7 TR8 TR9 TR10 TR10i TR11 TR12 TR13 L TR2i TRmorrie TR12i TR14 TR15 TR16 TR111 TR22'''.split() FU = dict(list(zip(fufuncs, list(map(locals().get, fufuncs))))) def _roots(): global _ROOT2, _ROOT3, _invROOT3 _ROOT2, _ROOT3 = sqrt(2), sqrt(3) _invROOT3 = 1/_ROOT3 _ROOT2 = None def trig_split(a, b, two=False): """Return the gcd, s1, s2, a1, a2, bool where If two is False (default) then:: a + b = gcd*(s1*f(a1) + s2*f(a2)) where f = cos if bool else sin else: if bool, a + b was +/- cos(a1)*cos(a2) +/- sin(a1)*sin(a2) and equals n1*gcd*cos(a - b) if n1 == n2 else n1*gcd*cos(a + b) else a + b was +/- cos(a1)*sin(a2) +/- sin(a1)*cos(a2) and equals n1*gcd*sin(a + b) if n1 = n2 else n1*gcd*sin(b - a) Examples ======== >>> from sympy.simplify.fu import trig_split >>> from sympy.abc import x, y, z >>> from sympy import cos, sin, sqrt >>> trig_split(cos(x), cos(y)) (1, 1, 1, x, y, True) >>> trig_split(2*cos(x), -2*cos(y)) (2, 1, -1, x, y, True) >>> trig_split(cos(x)*sin(y), cos(y)*sin(y)) (sin(y), 1, 1, x, y, True) >>> trig_split(cos(x), -sqrt(3)*sin(x), two=True) (2, 1, -1, x, pi/6, False) >>> trig_split(cos(x), sin(x), two=True) (sqrt(2), 1, 1, x, pi/4, False) >>> trig_split(cos(x), -sin(x), two=True) (sqrt(2), 1, -1, x, pi/4, False) >>> trig_split(sqrt(2)*cos(x), -sqrt(6)*sin(x), two=True) (2*sqrt(2), 1, -1, x, pi/6, False) >>> trig_split(-sqrt(6)*cos(x), -sqrt(2)*sin(x), two=True) (-2*sqrt(2), 1, 1, x, pi/3, False) >>> trig_split(cos(x)/sqrt(6), sin(x)/sqrt(2), two=True) (sqrt(6)/3, 1, 1, x, pi/6, False) >>> trig_split(-sqrt(6)*cos(x)*sin(y), -sqrt(2)*sin(x)*sin(y), two=True) (-2*sqrt(2)*sin(y), 1, 1, x, pi/3, False) >>> trig_split(cos(x), sin(x)) >>> trig_split(cos(x), sin(z)) >>> trig_split(2*cos(x), -sin(x)) >>> trig_split(cos(x), -sqrt(3)*sin(x)) >>> trig_split(cos(x)*cos(y), sin(x)*sin(z)) >>> trig_split(cos(x)*cos(y), sin(x)*sin(y)) >>> trig_split(-sqrt(6)*cos(x), sqrt(2)*sin(x)*sin(y), two=True) """ global _ROOT2, _ROOT3, _invROOT3 if _ROOT2 is None: _roots() a, b = [Factors(i) for i in (a, b)] ua, ub = a.normal(b) gcd = a.gcd(b).as_expr() n1 = n2 = 1 if S.NegativeOne in ua.factors: ua = ua.quo(S.NegativeOne) n1 = -n1 elif S.NegativeOne in ub.factors: ub = ub.quo(S.NegativeOne) n2 = -n2 a, b = [i.as_expr() for i in (ua, ub)] def pow_cos_sin(a, two): """Return ``a`` as a tuple (r, c, s) such that ``a = (r or 1)*(c or 1)*(s or 1)``. Three arguments are returned (radical, c-factor, s-factor) as long as the conditions set by ``two`` are met; otherwise None is returned. If ``two`` is True there will be one or two non-None values in the tuple: c and s or c and r or s and r or s or c with c being a cosine function (if possible) else a sine, and s being a sine function (if possible) else oosine. If ``two`` is False then there will only be a c or s term in the tuple. ``two`` also require that either two cos and/or sin be present (with the condition that if the functions are the same the arguments are different or vice versa) or that a single cosine or a single sine be present with an optional radical. If the above conditions dictated by ``two`` are not met then None is returned. """ c = s = None co = S.One if a.is_Mul: co, a = a.as_coeff_Mul() if len(a.args) > 2 or not two: return None if a.is_Mul: args = list(a.args) else: args = [a] a = args.pop(0) if isinstance(a, cos): c = a elif isinstance(a, sin): s = a elif a.is_Pow and a.exp is S.Half: # autoeval doesn't allow -1/2 co *= a else: return None if args: b = args[0] if isinstance(b, cos): if c: s = b else: c = b elif isinstance(b, sin): if s: c = b else: s = b elif b.is_Pow and b.exp is S.Half: co *= b else: return None return co if co is not S.One else None, c, s elif isinstance(a, cos): c = a elif isinstance(a, sin): s = a if c is None and s is None: return co = co if co is not S.One else None return co, c, s # get the parts m = pow_cos_sin(a, two) if m is None: return coa, ca, sa = m m = pow_cos_sin(b, two) if m is None: return cob, cb, sb = m # check them if (not ca) and cb or ca and isinstance(ca, sin): coa, ca, sa, cob, cb, sb = cob, cb, sb, coa, ca, sa n1, n2 = n2, n1 if not two: # need cos(x) and cos(y) or sin(x) and sin(y) c = ca or sa s = cb or sb if not isinstance(c, s.func): return None return gcd, n1, n2, c.args[0], s.args[0], isinstance(c, cos) else: if not coa and not cob: if (ca and cb and sa and sb): if isinstance(ca, sa.func) is not isinstance(cb, sb.func): return args = {j.args for j in (ca, sa)} if not all(i.args in args for i in (cb, sb)): return return gcd, n1, n2, ca.args[0], sa.args[0], isinstance(ca, sa.func) if ca and sa or cb and sb or \ two and (ca is None and sa is None or cb is None and sb is None): return c = ca or sa s = cb or sb if c.args != s.args: return if not coa: coa = S.One if not cob: cob = S.One if coa is cob: gcd *= _ROOT2 return gcd, n1, n2, c.args[0], pi/4, False elif coa/cob == _ROOT3: gcd *= 2*cob return gcd, n1, n2, c.args[0], pi/3, False elif coa/cob == _invROOT3: gcd *= 2*coa return gcd, n1, n2, c.args[0], pi/6, False def as_f_sign_1(e): """If ``e`` is a sum that can be written as ``g*(a + s)`` where ``s`` is ``+/-1``, return ``g``, ``a``, and ``s`` where ``a`` does not have a leading negative coefficient. Examples ======== >>> from sympy.simplify.fu import as_f_sign_1 >>> from sympy.abc import x >>> as_f_sign_1(x + 1) (1, x, 1) >>> as_f_sign_1(x - 1) (1, x, -1) >>> as_f_sign_1(-x + 1) (-1, x, -1) >>> as_f_sign_1(-x - 1) (-1, x, 1) >>> as_f_sign_1(2*x + 2) (2, x, 1) """ if not e.is_Add or len(e.args) != 2: return # exact match a, b = e.args if a in (S.NegativeOne, S.One): g = S.One if b.is_Mul and b.args[0].is_Number and b.args[0] < 0: a, b = -a, -b g = -g return g, b, a # gcd match a, b = [Factors(i) for i in e.args] ua, ub = a.normal(b) gcd = a.gcd(b).as_expr() if S.NegativeOne in ua.factors: ua = ua.quo(S.NegativeOne) n1 = -1 n2 = 1 elif S.NegativeOne in ub.factors: ub = ub.quo(S.NegativeOne) n1 = 1 n2 = -1 else: n1 = n2 = 1 a, b = [i.as_expr() for i in (ua, ub)] if a is S.One: a, b = b, a n1, n2 = n2, n1 if n1 == -1: gcd = -gcd n2 = -n2 if b is S.One: return gcd, a, n2 def _osborne(e, d): """Replace all hyperbolic functions with trig functions using the Osborne rule. Notes ===== ``d`` is a dummy variable to prevent automatic evaluation of trigonometric/hyperbolic functions. References ========== .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function """ def f(rv): if not isinstance(rv, HyperbolicFunction): return rv a = rv.args[0] a = a*d if not a.is_Add else Add._from_args([i*d for i in a.args]) if isinstance(rv, sinh): return I*sin(a) elif isinstance(rv, cosh): return cos(a) elif isinstance(rv, tanh): return I*tan(a) elif isinstance(rv, coth): return cot(a)/I elif isinstance(rv, sech): return sec(a) elif isinstance(rv, csch): return csc(a)/I else: raise NotImplementedError('unhandled %s' % rv.func) return bottom_up(e, f) def _osbornei(e, d): """Replace all trig functions with hyperbolic functions using the Osborne rule. Notes ===== ``d`` is a dummy variable to prevent automatic evaluation of trigonometric/hyperbolic functions. References ========== .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function """ def f(rv): if not isinstance(rv, TrigonometricFunction): return rv const, x = rv.args[0].as_independent(d, as_Add=True) a = x.xreplace({d: S.One}) + const*I if isinstance(rv, sin): return sinh(a)/I elif isinstance(rv, cos): return cosh(a) elif isinstance(rv, tan): return tanh(a)/I elif isinstance(rv, cot): return coth(a)*I elif isinstance(rv, sec): return sech(a) elif isinstance(rv, csc): return csch(a)*I else: raise NotImplementedError('unhandled %s' % rv.func) return bottom_up(e, f) def hyper_as_trig(rv): """Return an expression containing hyperbolic functions in terms of trigonometric functions. Any trigonometric functions initially present are replaced with Dummy symbols and the function to undo the masking and the conversion back to hyperbolics is also returned. It should always be true that:: t, f = hyper_as_trig(expr) expr == f(t) Examples ======== >>> from sympy.simplify.fu import hyper_as_trig, fu >>> from sympy.abc import x >>> from sympy import cosh, sinh >>> eq = sinh(x)**2 + cosh(x)**2 >>> t, f = hyper_as_trig(eq) >>> f(fu(t)) cosh(2*x) References ========== .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function """ from sympy.simplify.simplify import signsimp from sympy.simplify.radsimp import collect # mask off trig functions trigs = rv.atoms(TrigonometricFunction) reps = [(t, Dummy()) for t in trigs] masked = rv.xreplace(dict(reps)) # get inversion substitutions in place reps = [(v, k) for k, v in reps] d = Dummy() return _osborne(masked, d), lambda x: collect(signsimp( _osbornei(x, d).xreplace(dict(reps))), S.ImaginaryUnit) def sincos_to_sum(expr): """Convert products and powers of sin and cos to sums. Explanation =========== Applied power reduction TRpower first, then expands products, and converts products to sums with TR8. Examples ======== >>> from sympy.simplify.fu import sincos_to_sum >>> from sympy.abc import x >>> from sympy import cos, sin >>> sincos_to_sum(16*sin(x)**3*cos(2*x)**2) 7*sin(x) - 5*sin(3*x) + 3*sin(5*x) - sin(7*x) """ if not expr.has(cos, sin): return expr else: return TR8(expand_mul(TRpower(expr)))
c07c2bceb98e4f024ba72ccaa3367db773577643065df1c40896e130e6cda2b6
from itertools import combinations_with_replacement from sympy.core import symbols, Add, Dummy from sympy.core.numbers import Rational from sympy.polys import cancel, ComputationFailed, parallel_poly_from_expr, reduced, Poly from sympy.polys.monomials import Monomial, monomial_div from sympy.polys.polyerrors import DomainError, PolificationFailed from sympy.utilities.misc import debug def ratsimp(expr): """ Put an expression over a common denominator, cancel and reduce. Examples ======== >>> from sympy import ratsimp >>> from sympy.abc import x, y >>> ratsimp(1/x + 1/y) (x + y)/(x*y) """ f, g = cancel(expr).as_numer_denom() try: Q, r = reduced(f, [g], field=True, expand=False) except ComputationFailed: return f/g return Add(*Q) + cancel(r/g) def ratsimpmodprime(expr, G, *gens, quick=True, polynomial=False, **args): """ Simplifies a rational expression ``expr`` modulo the prime ideal generated by ``G``. ``G`` should be a Groebner basis of the ideal. Examples ======== >>> from sympy.simplify.ratsimp import ratsimpmodprime >>> from sympy.abc import x, y >>> eq = (x + y**5 + y)/(x - y) >>> ratsimpmodprime(eq, [x*y**5 - x - y], x, y, order='lex') (-x**2 - x*y - x - y)/(-x**2 + x*y) If ``polynomial`` is ``False``, the algorithm computes a rational simplification which minimizes the sum of the total degrees of the numerator and the denominator. If ``polynomial`` is ``True``, this function just brings numerator and denominator into a canonical form. This is much faster, but has potentially worse results. References ========== .. [1] M. Monagan, R. Pearce, Rational Simplification Modulo a Polynomial Ideal, https://dl.acm.org/doi/pdf/10.1145/1145768.1145809 (specifically, the second algorithm) """ from sympy.solvers.solvers import solve debug('ratsimpmodprime', expr) # usual preparation of polynomials: num, denom = cancel(expr).as_numer_denom() try: polys, opt = parallel_poly_from_expr([num, denom] + G, *gens, **args) except PolificationFailed: return expr domain = opt.domain if domain.has_assoc_Field: opt.domain = domain.get_field() else: raise DomainError( "Cannot compute rational simplification over %s" % domain) # compute only once leading_monomials = [g.LM(opt.order) for g in polys[2:]] tested = set() def staircase(n): """ Compute all monomials with degree less than ``n`` that are not divisible by any element of ``leading_monomials``. """ if n == 0: return [1] S = [] for mi in combinations_with_replacement(range(len(opt.gens)), n): m = [0]*len(opt.gens) for i in mi: m[i] += 1 if all(monomial_div(m, lmg) is None for lmg in leading_monomials): S.append(m) return [Monomial(s).as_expr(*opt.gens) for s in S] + staircase(n - 1) def _ratsimpmodprime(a, b, allsol, N=0, D=0): r""" Computes a rational simplification of ``a/b`` which minimizes the sum of the total degrees of the numerator and the denominator. Explanation =========== The algorithm proceeds by looking at ``a * d - b * c`` modulo the ideal generated by ``G`` for some ``c`` and ``d`` with degree less than ``a`` and ``b`` respectively. The coefficients of ``c`` and ``d`` are indeterminates and thus the coefficients of the normalform of ``a * d - b * c`` are linear polynomials in these indeterminates. If these linear polynomials, considered as system of equations, have a nontrivial solution, then `\frac{a}{b} \equiv \frac{c}{d}` modulo the ideal generated by ``G``. So, by construction, the degree of ``c`` and ``d`` is less than the degree of ``a`` and ``b``, so a simpler representation has been found. After a simpler representation has been found, the algorithm tries to reduce the degree of the numerator and denominator and returns the result afterwards. As an extension, if quick=False, we look at all possible degrees such that the total degree is less than *or equal to* the best current solution. We retain a list of all solutions of minimal degree, and try to find the best one at the end. """ c, d = a, b steps = 0 maxdeg = a.total_degree() + b.total_degree() if quick: bound = maxdeg - 1 else: bound = maxdeg while N + D <= bound: if (N, D) in tested: break tested.add((N, D)) M1 = staircase(N) M2 = staircase(D) debug('%s / %s: %s, %s' % (N, D, M1, M2)) Cs = symbols("c:%d" % len(M1), cls=Dummy) Ds = symbols("d:%d" % len(M2), cls=Dummy) ng = Cs + Ds c_hat = Poly( sum([Cs[i] * M1[i] for i in range(len(M1))]), opt.gens + ng) d_hat = Poly( sum([Ds[i] * M2[i] for i in range(len(M2))]), opt.gens + ng) r = reduced(a * d_hat - b * c_hat, G, opt.gens + ng, order=opt.order, polys=True)[1] S = Poly(r, gens=opt.gens).coeffs() sol = solve(S, Cs + Ds, particular=True, quick=True) if sol and not all(s == 0 for s in sol.values()): c = c_hat.subs(sol) d = d_hat.subs(sol) # The "free" variables occurring before as parameters # might still be in the substituted c, d, so set them # to the value chosen before: c = c.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))) d = d.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))) c = Poly(c, opt.gens) d = Poly(d, opt.gens) if d == 0: raise ValueError('Ideal not prime?') allsol.append((c_hat, d_hat, S, Cs + Ds)) if N + D != maxdeg: allsol = [allsol[-1]] break steps += 1 N += 1 D += 1 if steps > 0: c, d, allsol = _ratsimpmodprime(c, d, allsol, N, D - steps) c, d, allsol = _ratsimpmodprime(c, d, allsol, N - steps, D) return c, d, allsol # preprocessing. this improves performance a bit when deg(num) # and deg(denom) are large: num = reduced(num, G, opt.gens, order=opt.order)[1] denom = reduced(denom, G, opt.gens, order=opt.order)[1] if polynomial: return (num/denom).cancel() c, d, allsol = _ratsimpmodprime( Poly(num, opt.gens, domain=opt.domain), Poly(denom, opt.gens, domain=opt.domain), []) if not quick and allsol: debug('Looking for best minimal solution. Got: %s' % len(allsol)) newsol = [] for c_hat, d_hat, S, ng in allsol: sol = solve(S, ng, particular=True, quick=False) # all values of sol should be numbers; if not, solve is broken newsol.append((c_hat.subs(sol), d_hat.subs(sol))) c, d = min(newsol, key=lambda x: len(x[0].terms()) + len(x[1].terms())) if not domain.is_Field: cn, c = c.clear_denoms(convert=True) dn, d = d.clear_denoms(convert=True) r = Rational(cn, dn) else: r = Rational(1) return (c*r.q)/(d*r.p)
d7b059415961fa509c4170d1ad78671cb0665dd3427c0ce80f55a4de811a2e2b
from typing import Any, Set as tSet from functools import reduce from itertools import permutations from sympy.combinatorics import Permutation from sympy.core import ( Basic, Expr, Function, diff, Pow, Mul, Add, Lambda, S, Tuple, Dict ) from sympy.core.cache import cacheit from sympy.core.symbol import Symbol, Dummy from sympy.core.symbol import Str from sympy.core.sympify import _sympify from sympy.functions import factorial from sympy.matrices import ImmutableDenseMatrix as Matrix from sympy.solvers import solve from sympy.utilities.exceptions import (sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) # TODO you are a bit excessive in the use of Dummies # TODO dummy point, literal field # TODO too often one needs to call doit or simplify on the output, check the # tests and find out why from sympy.tensor.array import ImmutableDenseNDimArray class Manifold(Basic): """ A mathematical manifold. Explanation =========== A manifold is a topological space that locally resembles Euclidean space near each point [1]. This class does not provide any means to study the topological characteristics of the manifold that it represents, though. Parameters ========== name : str The name of the manifold. dim : int The dimension of the manifold. Examples ======== >>> from sympy.diffgeom import Manifold >>> m = Manifold('M', 2) >>> m M >>> m.dim 2 References ========== .. [1] https://en.wikipedia.org/wiki/Manifold """ def __new__(cls, name, dim, **kwargs): if not isinstance(name, Str): name = Str(name) dim = _sympify(dim) obj = super().__new__(cls, name, dim) obj.patches = _deprecated_list( """ Manifold.patches is deprecated. The Manifold object is now immutable. Instead use a separate list to keep track of the patches. """, []) return obj @property def name(self): return self.args[0] @property def dim(self): return self.args[1] class Patch(Basic): """ A patch on a manifold. Explanation =========== Coordinate patch, or patch in short, is a simply-connected open set around a point in the manifold [1]. On a manifold one can have many patches that do not always include the whole manifold. On these patches coordinate charts can be defined that permit the parameterization of any point on the patch in terms of a tuple of real numbers (the coordinates). This class does not provide any means to study the topological characteristics of the patch that it represents. Parameters ========== name : str The name of the patch. manifold : Manifold The manifold on which the patch is defined. Examples ======== >>> from sympy.diffgeom import Manifold, Patch >>> m = Manifold('M', 2) >>> p = Patch('P', m) >>> p P >>> p.dim 2 References ========== .. [1] G. Sussman, J. Wisdom, W. Farr, Functional Differential Geometry (2013) """ def __new__(cls, name, manifold, **kwargs): if not isinstance(name, Str): name = Str(name) obj = super().__new__(cls, name, manifold) obj.manifold.patches.append(obj) # deprecated obj.coord_systems = _deprecated_list( """ Patch.coord_systms is deprecated. The Patch class is now immutable. Instead use a separate list to keep track of coordinate systems. """, []) return obj @property def name(self): return self.args[0] @property def manifold(self): return self.args[1] @property def dim(self): return self.manifold.dim class CoordSystem(Basic): """ A coordinate system defined on the patch. Explanation =========== Coordinate system is a system that uses one or more coordinates to uniquely determine the position of the points or other geometric elements on a manifold [1]. By passing ``Symbols`` to *symbols* parameter, user can define the name and assumptions of coordinate symbols of the coordinate system. If not passed, these symbols are generated automatically and are assumed to be real valued. By passing *relations* parameter, user can define the tranform relations of coordinate systems. Inverse transformation and indirect transformation can be found automatically. If this parameter is not passed, coordinate transformation cannot be done. Parameters ========== name : str The name of the coordinate system. patch : Patch The patch where the coordinate system is defined. symbols : list of Symbols, optional Defines the names and assumptions of coordinate symbols. relations : dict, optional Key is a tuple of two strings, who are the names of the systems where the coordinates transform from and transform to. Value is a tuple of the symbols before transformation and a tuple of the expressions after transformation. Examples ======== We define two-dimensional Cartesian coordinate system and polar coordinate system. >>> from sympy import symbols, pi, sqrt, atan2, cos, sin >>> from sympy.diffgeom import Manifold, Patch, CoordSystem >>> m = Manifold('M', 2) >>> p = Patch('P', m) >>> x, y = symbols('x y', real=True) >>> r, theta = symbols('r theta', nonnegative=True) >>> relation_dict = { ... ('Car2D', 'Pol'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))], ... ('Pol', 'Car2D'): [(r, theta), (r*cos(theta), r*sin(theta))] ... } >>> Car2D = CoordSystem('Car2D', p, (x, y), relation_dict) >>> Pol = CoordSystem('Pol', p, (r, theta), relation_dict) ``symbols`` property returns ``CoordinateSymbol`` instances. These symbols are not same with the symbols used to construct the coordinate system. >>> Car2D Car2D >>> Car2D.dim 2 >>> Car2D.symbols (x, y) >>> _[0].func <class 'sympy.diffgeom.diffgeom.CoordinateSymbol'> ``transformation()`` method returns the transformation function from one coordinate system to another. ``transform()`` method returns the transformed coordinates. >>> Car2D.transformation(Pol) Lambda((x, y), Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]])) >>> Car2D.transform(Pol) Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]]) >>> Car2D.transform(Pol, [1, 2]) Matrix([ [sqrt(5)], [atan(2)]]) ``jacobian()`` method returns the Jacobian matrix of coordinate transformation between two systems. ``jacobian_determinant()`` method returns the Jacobian determinant of coordinate transformation between two systems. >>> Pol.jacobian(Car2D) Matrix([ [cos(theta), -r*sin(theta)], [sin(theta), r*cos(theta)]]) >>> Pol.jacobian(Car2D, [1, pi/2]) Matrix([ [0, -1], [1, 0]]) >>> Car2D.jacobian_determinant(Pol) 1/sqrt(x**2 + y**2) >>> Car2D.jacobian_determinant(Pol, [1,0]) 1 References ========== .. [1] https://en.wikipedia.org/wiki/Coordinate_system """ def __new__(cls, name, patch, symbols=None, relations={}, **kwargs): if not isinstance(name, Str): name = Str(name) # canonicallize the symbols if symbols is None: names = kwargs.get('names', None) if names is None: symbols = Tuple( *[Symbol('%s_%s' % (name.name, i), real=True) for i in range(patch.dim)] ) else: sympy_deprecation_warning( f""" The 'names' argument to CoordSystem is deprecated. Use 'symbols' instead. That is, replace CoordSystem(..., names={names}) with CoordSystem(..., symbols=[{', '.join(["Symbol(" + repr(n) + ", real=True)" for n in names])}]) """, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", ) symbols = Tuple( *[Symbol(n, real=True) for n in names] ) else: syms = [] for s in symbols: if isinstance(s, Symbol): syms.append(Symbol(s.name, **s._assumptions.generator)) elif isinstance(s, str): sympy_deprecation_warning( f""" Passing a string as the coordinate symbol name to CoordSystem is deprecated. Pass a Symbol with the appropriate name and assumptions instead. That is, replace {s} with Symbol({s!r}, real=True). """, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", ) syms.append(Symbol(s, real=True)) symbols = Tuple(*syms) # canonicallize the relations rel_temp = {} for k,v in relations.items(): s1, s2 = k if not isinstance(s1, Str): s1 = Str(s1) if not isinstance(s2, Str): s2 = Str(s2) key = Tuple(s1, s2) # Old version used Lambda as a value. if isinstance(v, Lambda): v = (tuple(v.signature), tuple(v.expr)) else: v = (tuple(v[0]), tuple(v[1])) rel_temp[key] = v relations = Dict(rel_temp) # construct the object obj = super().__new__(cls, name, patch, symbols, relations) # Add deprecated attributes obj.transforms = _deprecated_dict( """ CoordSystem.transforms is deprecated. The CoordSystem class is now immutable. Use the 'relations' keyword argument to the CoordSystems() constructor to specify relations. """, {}) obj._names = [str(n) for n in symbols] obj.patch.coord_systems.append(obj) # deprecated obj._dummies = [Dummy(str(n)) for n in symbols] # deprecated obj._dummy = Dummy() return obj @property def name(self): return self.args[0] @property def patch(self): return self.args[1] @property def manifold(self): return self.patch.manifold @property def symbols(self): return tuple(CoordinateSymbol(self, i, **s._assumptions.generator) for i,s in enumerate(self.args[2])) @property def relations(self): return self.args[3] @property def dim(self): return self.patch.dim ########################################################################## # Finding transformation relation ########################################################################## def transformation(self, sys): """ Return coordinate transformation function from *self* to *sys*. Parameters ========== sys : CoordSystem Returns ======= sympy.Lambda Examples ======== >>> from sympy.diffgeom.rn import R2_r, R2_p >>> R2_r.transformation(R2_p) Lambda((x, y), Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]])) """ signature = self.args[2] key = Tuple(self.name, sys.name) if self == sys: expr = Matrix(self.symbols) elif key in self.relations: expr = Matrix(self.relations[key][1]) elif key[::-1] in self.relations: expr = Matrix(self._inverse_transformation(sys, self)) else: expr = Matrix(self._indirect_transformation(self, sys)) return Lambda(signature, expr) @staticmethod def _solve_inverse(sym1, sym2, exprs, sys1_name, sys2_name): ret = solve( [t[0] - t[1] for t in zip(sym2, exprs)], list(sym1), dict=True) if len(ret) == 0: temp = "Cannot solve inverse relation from {} to {}." raise NotImplementedError(temp.format(sys1_name, sys2_name)) elif len(ret) > 1: temp = "Obtained multiple inverse relation from {} to {}." raise ValueError(temp.format(sys1_name, sys2_name)) return ret[0] @classmethod def _inverse_transformation(cls, sys1, sys2): # Find the transformation relation from sys2 to sys1 forward = sys1.transform(sys2) inv_results = cls._solve_inverse(sys1.symbols, sys2.symbols, forward, sys1.name, sys2.name) signature = tuple(sys1.symbols) return [inv_results[s] for s in signature] @classmethod @cacheit def _indirect_transformation(cls, sys1, sys2): # Find the transformation relation between two indirectly connected # coordinate systems rel = sys1.relations path = cls._dijkstra(sys1, sys2) transforms = [] for s1, s2 in zip(path, path[1:]): if (s1, s2) in rel: transforms.append(rel[(s1, s2)]) else: sym2, inv_exprs = rel[(s2, s1)] sym1 = tuple(Dummy() for i in sym2) ret = cls._solve_inverse(sym2, sym1, inv_exprs, s2, s1) ret = tuple(ret[s] for s in sym2) transforms.append((sym1, ret)) syms = sys1.args[2] exprs = syms for newsyms, newexprs in transforms: exprs = tuple(e.subs(zip(newsyms, exprs)) for e in newexprs) return exprs @staticmethod def _dijkstra(sys1, sys2): # Use Dijkstra algorithm to find the shortest path between two indirectly-connected # coordinate systems # return value is the list of the names of the systems. relations = sys1.relations graph = {} for s1, s2 in relations.keys(): if s1 not in graph: graph[s1] = {s2} else: graph[s1].add(s2) if s2 not in graph: graph[s2] = {s1} else: graph[s2].add(s1) path_dict = {sys:[0, [], 0] for sys in graph} # minimum distance, path, times of visited def visit(sys): path_dict[sys][2] = 1 for newsys in graph[sys]: distance = path_dict[sys][0] + 1 if path_dict[newsys][0] >= distance or not path_dict[newsys][1]: path_dict[newsys][0] = distance path_dict[newsys][1] = [i for i in path_dict[sys][1]] path_dict[newsys][1].append(sys) visit(sys1.name) while True: min_distance = max(path_dict.values(), key=lambda x:x[0])[0] newsys = None for sys, lst in path_dict.items(): if 0 < lst[0] <= min_distance and not lst[2]: min_distance = lst[0] newsys = sys if newsys is None: break visit(newsys) result = path_dict[sys2.name][1] result.append(sys2.name) if result == [sys2.name]: raise KeyError("Two coordinate systems are not connected.") return result def connect_to(self, to_sys, from_coords, to_exprs, inverse=True, fill_in_gaps=False): sympy_deprecation_warning( """ The CoordSystem.connect_to() method is deprecated. Instead, generate a new instance of CoordSystem with the 'relations' keyword argument (CoordSystem classes are now immutable). """, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", ) from_coords, to_exprs = dummyfy(from_coords, to_exprs) self.transforms[to_sys] = Matrix(from_coords), Matrix(to_exprs) if inverse: to_sys.transforms[self] = self._inv_transf(from_coords, to_exprs) if fill_in_gaps: self._fill_gaps_in_transformations() @staticmethod def _inv_transf(from_coords, to_exprs): # Will be removed when connect_to is removed inv_from = [i.as_dummy() for i in from_coords] inv_to = solve( [t[0] - t[1] for t in zip(inv_from, to_exprs)], list(from_coords), dict=True)[0] inv_to = [inv_to[fc] for fc in from_coords] return Matrix(inv_from), Matrix(inv_to) @staticmethod def _fill_gaps_in_transformations(): # Will be removed when connect_to is removed raise NotImplementedError ########################################################################## # Coordinate transformations ########################################################################## def transform(self, sys, coordinates=None): """ Return the result of coordinate transformation from *self* to *sys*. If coordinates are not given, coordinate symbols of *self* are used. Parameters ========== sys : CoordSystem coordinates : Any iterable, optional. Returns ======= sympy.ImmutableDenseMatrix containing CoordinateSymbol Examples ======== >>> from sympy.diffgeom.rn import R2_r, R2_p >>> R2_r.transform(R2_p) Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]]) >>> R2_r.transform(R2_p, [0, 1]) Matrix([ [ 1], [pi/2]]) """ if coordinates is None: coordinates = self.symbols if self != sys: transf = self.transformation(sys) coordinates = transf(*coordinates) else: coordinates = Matrix(coordinates) return coordinates def coord_tuple_transform_to(self, to_sys, coords): """Transform ``coords`` to coord system ``to_sys``.""" sympy_deprecation_warning( """ The CoordSystem.coord_tuple_transform_to() method is deprecated. Use the CoordSystem.transform() method instead. """, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", ) coords = Matrix(coords) if self != to_sys: with ignore_warnings(SymPyDeprecationWarning): transf = self.transforms[to_sys] coords = transf[1].subs(list(zip(transf[0], coords))) return coords def jacobian(self, sys, coordinates=None): """ Return the jacobian matrix of a transformation on given coordinates. If coordinates are not given, coordinate symbols of *self* are used. Parameters ========== sys : CoordSystem coordinates : Any iterable, optional. Returns ======= sympy.ImmutableDenseMatrix Examples ======== >>> from sympy.diffgeom.rn import R2_r, R2_p >>> R2_p.jacobian(R2_r) Matrix([ [cos(theta), -rho*sin(theta)], [sin(theta), rho*cos(theta)]]) >>> R2_p.jacobian(R2_r, [1, 0]) Matrix([ [1, 0], [0, 1]]) """ result = self.transform(sys).jacobian(self.symbols) if coordinates is not None: result = result.subs(list(zip(self.symbols, coordinates))) return result jacobian_matrix = jacobian def jacobian_determinant(self, sys, coordinates=None): """ Return the jacobian determinant of a transformation on given coordinates. If coordinates are not given, coordinate symbols of *self* are used. Parameters ========== sys : CoordSystem coordinates : Any iterable, optional. Returns ======= sympy.Expr Examples ======== >>> from sympy.diffgeom.rn import R2_r, R2_p >>> R2_r.jacobian_determinant(R2_p) 1/sqrt(x**2 + y**2) >>> R2_r.jacobian_determinant(R2_p, [1, 0]) 1 """ return self.jacobian(sys, coordinates).det() ########################################################################## # Points ########################################################################## def point(self, coords): """Create a ``Point`` with coordinates given in this coord system.""" return Point(self, coords) def point_to_coords(self, point): """Calculate the coordinates of a point in this coord system.""" return point.coords(self) ########################################################################## # Base fields. ########################################################################## def base_scalar(self, coord_index): """Return ``BaseScalarField`` that takes a point and returns one of the coordinates.""" return BaseScalarField(self, coord_index) coord_function = base_scalar def base_scalars(self): """Returns a list of all coordinate functions. For more details see the ``base_scalar`` method of this class.""" return [self.base_scalar(i) for i in range(self.dim)] coord_functions = base_scalars def base_vector(self, coord_index): """Return a basis vector field. The basis vector field for this coordinate system. It is also an operator on scalar fields.""" return BaseVectorField(self, coord_index) def base_vectors(self): """Returns a list of all base vectors. For more details see the ``base_vector`` method of this class.""" return [self.base_vector(i) for i in range(self.dim)] def base_oneform(self, coord_index): """Return a basis 1-form field. The basis one-form field for this coordinate system. It is also an operator on vector fields.""" return Differential(self.coord_function(coord_index)) def base_oneforms(self): """Returns a list of all base oneforms. For more details see the ``base_oneform`` method of this class.""" return [self.base_oneform(i) for i in range(self.dim)] class CoordinateSymbol(Symbol): """A symbol which denotes an abstract value of i-th coordinate of the coordinate system with given context. Explanation =========== Each coordinates in coordinate system are represented by unique symbol, such as x, y, z in Cartesian coordinate system. You may not construct this class directly. Instead, use `symbols` method of CoordSystem. Parameters ========== coord_sys : CoordSystem index : integer Examples ======== >>> from sympy import symbols, Lambda, Matrix, sqrt, atan2, cos, sin >>> from sympy.diffgeom import Manifold, Patch, CoordSystem >>> m = Manifold('M', 2) >>> p = Patch('P', m) >>> x, y = symbols('x y', real=True) >>> r, theta = symbols('r theta', nonnegative=True) >>> relation_dict = { ... ('Car2D', 'Pol'): Lambda((x, y), Matrix([sqrt(x**2 + y**2), atan2(y, x)])), ... ('Pol', 'Car2D'): Lambda((r, theta), Matrix([r*cos(theta), r*sin(theta)])) ... } >>> Car2D = CoordSystem('Car2D', p, [x, y], relation_dict) >>> Pol = CoordSystem('Pol', p, [r, theta], relation_dict) >>> x, y = Car2D.symbols ``CoordinateSymbol`` contains its coordinate symbol and index. >>> x.name 'x' >>> x.coord_sys == Car2D True >>> x.index 0 >>> x.is_real True You can transform ``CoordinateSymbol`` into other coordinate system using ``rewrite()`` method. >>> x.rewrite(Pol) r*cos(theta) >>> sqrt(x**2 + y**2).rewrite(Pol).simplify() r """ def __new__(cls, coord_sys, index, **assumptions): name = coord_sys.args[2][index].name obj = super().__new__(cls, name, **assumptions) obj.coord_sys = coord_sys obj.index = index return obj def __getnewargs__(self): return (self.coord_sys, self.index) def _hashable_content(self): return ( self.coord_sys, self.index ) + tuple(sorted(self.assumptions0.items())) def _eval_rewrite(self, rule, args, **hints): if isinstance(rule, CoordSystem): return rule.transform(self.coord_sys)[self.index] return super()._eval_rewrite(rule, args, **hints) class Point(Basic): """Point defined in a coordinate system. Explanation =========== Mathematically, point is defined in the manifold and does not have any coordinates by itself. Coordinate system is what imbues the coordinates to the point by coordinate chart. However, due to the difficulty of realizing such logic, you must supply a coordinate system and coordinates to define a Point here. The usage of this object after its definition is independent of the coordinate system that was used in order to define it, however due to limitations in the simplification routines you can arrive at complicated expressions if you use inappropriate coordinate systems. Parameters ========== coord_sys : CoordSystem coords : list The coordinates of the point. Examples ======== >>> from sympy import pi >>> from sympy.diffgeom import Point >>> from sympy.diffgeom.rn import R2, R2_r, R2_p >>> rho, theta = R2_p.symbols >>> p = Point(R2_p, [rho, 3*pi/4]) >>> p.manifold == R2 True >>> p.coords() Matrix([ [ rho], [3*pi/4]]) >>> p.coords(R2_r) Matrix([ [-sqrt(2)*rho/2], [ sqrt(2)*rho/2]]) """ def __new__(cls, coord_sys, coords, **kwargs): coords = Matrix(coords) obj = super().__new__(cls, coord_sys, coords) obj._coord_sys = coord_sys obj._coords = coords return obj @property def patch(self): return self._coord_sys.patch @property def manifold(self): return self._coord_sys.manifold @property def dim(self): return self.manifold.dim def coords(self, sys=None): """ Coordinates of the point in given coordinate system. If coordinate system is not passed, it returns the coordinates in the coordinate system in which the poin was defined. """ if sys is None: return self._coords else: return self._coord_sys.transform(sys, self._coords) @property def free_symbols(self): return self._coords.free_symbols class BaseScalarField(Expr): """Base scalar field over a manifold for a given coordinate system. Explanation =========== A scalar field takes a point as an argument and returns a scalar. A base scalar field of a coordinate system takes a point and returns one of the coordinates of that point in the coordinate system in question. To define a scalar field you need to choose the coordinate system and the index of the coordinate. The use of the scalar field after its definition is independent of the coordinate system in which it was defined, however due to limitations in the simplification routines you may arrive at more complicated expression if you use unappropriate coordinate systems. You can build complicated scalar fields by just building up SymPy expressions containing ``BaseScalarField`` instances. Parameters ========== coord_sys : CoordSystem index : integer Examples ======== >>> from sympy import Function, pi >>> from sympy.diffgeom import BaseScalarField >>> from sympy.diffgeom.rn import R2_r, R2_p >>> rho, _ = R2_p.symbols >>> point = R2_p.point([rho, 0]) >>> fx, fy = R2_r.base_scalars() >>> ftheta = BaseScalarField(R2_r, 1) >>> fx(point) rho >>> fy(point) 0 >>> (fx**2+fy**2).rcall(point) rho**2 >>> g = Function('g') >>> fg = g(ftheta-pi) >>> fg.rcall(point) g(-pi) """ is_commutative = True def __new__(cls, coord_sys, index, **kwargs): index = _sympify(index) obj = super().__new__(cls, coord_sys, index) obj._coord_sys = coord_sys obj._index = index return obj @property def coord_sys(self): return self.args[0] @property def index(self): return self.args[1] @property def patch(self): return self.coord_sys.patch @property def manifold(self): return self.coord_sys.manifold @property def dim(self): return self.manifold.dim def __call__(self, *args): """Evaluating the field at a point or doing nothing. If the argument is a ``Point`` instance, the field is evaluated at that point. The field is returned itself if the argument is any other object. It is so in order to have working recursive calling mechanics for all fields (check the ``__call__`` method of ``Expr``). """ point = args[0] if len(args) != 1 or not isinstance(point, Point): return self coords = point.coords(self._coord_sys) # XXX Calling doit is necessary with all the Subs expressions # XXX Calling simplify is necessary with all the trig expressions return simplify(coords[self._index]).doit() # XXX Workaround for limitations on the content of args free_symbols = set() # type: tSet[Any] class BaseVectorField(Expr): r"""Base vector field over a manifold for a given coordinate system. Explanation =========== A vector field is an operator taking a scalar field and returning a directional derivative (which is also a scalar field). A base vector field is the same type of operator, however the derivation is specifically done with respect to a chosen coordinate. To define a base vector field you need to choose the coordinate system and the index of the coordinate. The use of the vector field after its definition is independent of the coordinate system in which it was defined, however due to limitations in the simplification routines you may arrive at more complicated expression if you use unappropriate coordinate systems. Parameters ========== coord_sys : CoordSystem index : integer Examples ======== >>> from sympy import Function >>> from sympy.diffgeom.rn import R2_p, R2_r >>> from sympy.diffgeom import BaseVectorField >>> from sympy import pprint >>> x, y = R2_r.symbols >>> rho, theta = R2_p.symbols >>> fx, fy = R2_r.base_scalars() >>> point_p = R2_p.point([rho, theta]) >>> point_r = R2_r.point([x, y]) >>> g = Function('g') >>> s_field = g(fx, fy) >>> v = BaseVectorField(R2_r, 1) >>> pprint(v(s_field)) / d \| |---(g(x, xi))|| \dxi /|xi=y >>> pprint(v(s_field).rcall(point_r).doit()) d --(g(x, y)) dy >>> pprint(v(s_field).rcall(point_p)) / d \| |---(g(rho*cos(theta), xi))|| \dxi /|xi=rho*sin(theta) """ is_commutative = False def __new__(cls, coord_sys, index, **kwargs): index = _sympify(index) obj = super().__new__(cls, coord_sys, index) obj._coord_sys = coord_sys obj._index = index return obj @property def coord_sys(self): return self.args[0] @property def index(self): return self.args[1] @property def patch(self): return self.coord_sys.patch @property def manifold(self): return self.coord_sys.manifold @property def dim(self): return self.manifold.dim def __call__(self, scalar_field): """Apply on a scalar field. The action of a vector field on a scalar field is a directional differentiation. If the argument is not a scalar field an error is raised. """ if covariant_order(scalar_field) or contravariant_order(scalar_field): raise ValueError('Only scalar fields can be supplied as arguments to vector fields.') if scalar_field is None: return self base_scalars = list(scalar_field.atoms(BaseScalarField)) # First step: e_x(x+r**2) -> e_x(x) + 2*r*e_x(r) d_var = self._coord_sys._dummy # TODO: you need a real dummy function for the next line d_funcs = [Function('_#_%s' % i)(d_var) for i, b in enumerate(base_scalars)] d_result = scalar_field.subs(list(zip(base_scalars, d_funcs))) d_result = d_result.diff(d_var) # Second step: e_x(x) -> 1 and e_x(r) -> cos(atan2(x, y)) coords = self._coord_sys.symbols d_funcs_deriv = [f.diff(d_var) for f in d_funcs] d_funcs_deriv_sub = [] for b in base_scalars: jac = self._coord_sys.jacobian(b._coord_sys, coords) d_funcs_deriv_sub.append(jac[b._index, self._index]) d_result = d_result.subs(list(zip(d_funcs_deriv, d_funcs_deriv_sub))) # Remove the dummies result = d_result.subs(list(zip(d_funcs, base_scalars))) result = result.subs(list(zip(coords, self._coord_sys.coord_functions()))) return result.doit() def _find_coords(expr): # Finds CoordinateSystems existing in expr fields = expr.atoms(BaseScalarField, BaseVectorField) result = set() for f in fields: result.add(f._coord_sys) return result class Commutator(Expr): r"""Commutator of two vector fields. Explanation =========== The commutator of two vector fields `v_1` and `v_2` is defined as the vector field `[v_1, v_2]` that evaluated on each scalar field `f` is equal to `v_1(v_2(f)) - v_2(v_1(f))`. Examples ======== >>> from sympy.diffgeom.rn import R2_p, R2_r >>> from sympy.diffgeom import Commutator >>> from sympy import simplify >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> e_r = R2_p.base_vector(0) >>> c_xy = Commutator(e_x, e_y) >>> c_xr = Commutator(e_x, e_r) >>> c_xy 0 Unfortunately, the current code is not able to compute everything: >>> c_xr Commutator(e_x, e_rho) >>> simplify(c_xr(fy**2)) -2*cos(theta)*y**2/(x**2 + y**2) """ def __new__(cls, v1, v2): if (covariant_order(v1) or contravariant_order(v1) != 1 or covariant_order(v2) or contravariant_order(v2) != 1): raise ValueError( 'Only commutators of vector fields are supported.') if v1 == v2: return S.Zero coord_sys = set().union(*[_find_coords(v) for v in (v1, v2)]) if len(coord_sys) == 1: # Only one coordinate systems is used, hence it is easy enough to # actually evaluate the commutator. if all(isinstance(v, BaseVectorField) for v in (v1, v2)): return S.Zero bases_1, bases_2 = [list(v.atoms(BaseVectorField)) for v in (v1, v2)] coeffs_1 = [v1.expand().coeff(b) for b in bases_1] coeffs_2 = [v2.expand().coeff(b) for b in bases_2] res = 0 for c1, b1 in zip(coeffs_1, bases_1): for c2, b2 in zip(coeffs_2, bases_2): res += c1*b1(c2)*b2 - c2*b2(c1)*b1 return res else: obj = super().__new__(cls, v1, v2) obj._v1 = v1 # deprecated assignment obj._v2 = v2 # deprecated assignment return obj @property def v1(self): return self.args[0] @property def v2(self): return self.args[1] def __call__(self, scalar_field): """Apply on a scalar field. If the argument is not a scalar field an error is raised. """ return self.v1(self.v2(scalar_field)) - self.v2(self.v1(scalar_field)) class Differential(Expr): r"""Return the differential (exterior derivative) of a form field. Explanation =========== The differential of a form (i.e. the exterior derivative) has a complicated definition in the general case. The differential `df` of the 0-form `f` is defined for any vector field `v` as `df(v) = v(f)`. Examples ======== >>> from sympy import Function >>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import Differential >>> from sympy import pprint >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> g = Function('g') >>> s_field = g(fx, fy) >>> dg = Differential(s_field) >>> dg d(g(x, y)) >>> pprint(dg(e_x)) / d \| |---(g(xi, y))|| \dxi /|xi=x >>> pprint(dg(e_y)) / d \| |---(g(x, xi))|| \dxi /|xi=y Applying the exterior derivative operator twice always results in: >>> Differential(dg) 0 """ is_commutative = False def __new__(cls, form_field): if contravariant_order(form_field): raise ValueError( 'A vector field was supplied as an argument to Differential.') if isinstance(form_field, Differential): return S.Zero else: obj = super().__new__(cls, form_field) obj._form_field = form_field # deprecated assignment return obj @property def form_field(self): return self.args[0] def __call__(self, *vector_fields): """Apply on a list of vector_fields. Explanation =========== If the number of vector fields supplied is not equal to 1 + the order of the form field inside the differential the result is undefined. For 1-forms (i.e. differentials of scalar fields) the evaluation is done as `df(v)=v(f)`. However if `v` is ``None`` instead of a vector field, the differential is returned unchanged. This is done in order to permit partial contractions for higher forms. In the general case the evaluation is done by applying the form field inside the differential on a list with one less elements than the number of elements in the original list. Lowering the number of vector fields is achieved through replacing each pair of fields by their commutator. If the arguments are not vectors or ``None``s an error is raised. """ if any((contravariant_order(a) != 1 or covariant_order(a)) and a is not None for a in vector_fields): raise ValueError('The arguments supplied to Differential should be vector fields or Nones.') k = len(vector_fields) if k == 1: if vector_fields[0]: return vector_fields[0].rcall(self._form_field) return self else: # For higher form it is more complicated: # Invariant formula: # https://en.wikipedia.org/wiki/Exterior_derivative#Invariant_formula # df(v1, ... vn) = +/- vi(f(v1..no i..vn)) # +/- f([vi,vj],v1..no i, no j..vn) f = self._form_field v = vector_fields ret = 0 for i in range(k): t = v[i].rcall(f.rcall(*v[:i] + v[i + 1:])) ret += (-1)**i*t for j in range(i + 1, k): c = Commutator(v[i], v[j]) if c: # TODO this is ugly - the Commutator can be Zero and # this causes the next line to fail t = f.rcall(*(c,) + v[:i] + v[i + 1:j] + v[j + 1:]) ret += (-1)**(i + j)*t return ret class TensorProduct(Expr): """Tensor product of forms. Explanation =========== The tensor product permits the creation of multilinear functionals (i.e. higher order tensors) out of lower order fields (e.g. 1-forms and vector fields). However, the higher tensors thus created lack the interesting features provided by the other type of product, the wedge product, namely they are not antisymmetric and hence are not form fields. Examples ======== >>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import TensorProduct >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> dx, dy = R2_r.base_oneforms() >>> TensorProduct(dx, dy)(e_x, e_y) 1 >>> TensorProduct(dx, dy)(e_y, e_x) 0 >>> TensorProduct(dx, fx*dy)(fx*e_x, e_y) x**2 >>> TensorProduct(e_x, e_y)(fx**2, fy**2) 4*x*y >>> TensorProduct(e_y, dx)(fy) dx You can nest tensor products. >>> tp1 = TensorProduct(dx, dy) >>> TensorProduct(tp1, dx)(e_x, e_y, e_x) 1 You can make partial contraction for instance when 'raising an index'. Putting ``None`` in the second argument of ``rcall`` means that the respective position in the tensor product is left as it is. >>> TP = TensorProduct >>> metric = TP(dx, dx) + 3*TP(dy, dy) >>> metric.rcall(e_y, None) 3*dy Or automatically pad the args with ``None`` without specifying them. >>> metric.rcall(e_y) 3*dy """ def __new__(cls, *args): scalar = Mul(*[m for m in args if covariant_order(m) + contravariant_order(m) == 0]) multifields = [m for m in args if covariant_order(m) + contravariant_order(m)] if multifields: if len(multifields) == 1: return scalar*multifields[0] return scalar*super().__new__(cls, *multifields) else: return scalar def __call__(self, *fields): """Apply on a list of fields. If the number of input fields supplied is not equal to the order of the tensor product field, the list of arguments is padded with ``None``'s. The list of arguments is divided in sublists depending on the order of the forms inside the tensor product. The sublists are provided as arguments to these forms and the resulting expressions are given to the constructor of ``TensorProduct``. """ tot_order = covariant_order(self) + contravariant_order(self) tot_args = len(fields) if tot_args != tot_order: fields = list(fields) + [None]*(tot_order - tot_args) orders = [covariant_order(f) + contravariant_order(f) for f in self._args] indices = [sum(orders[:i + 1]) for i in range(len(orders) - 1)] fields = [fields[i:j] for i, j in zip([0] + indices, indices + [None])] multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, fields)] return TensorProduct(*multipliers) class WedgeProduct(TensorProduct): """Wedge product of forms. Explanation =========== In the context of integration only completely antisymmetric forms make sense. The wedge product permits the creation of such forms. Examples ======== >>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import WedgeProduct >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> dx, dy = R2_r.base_oneforms() >>> WedgeProduct(dx, dy)(e_x, e_y) 1 >>> WedgeProduct(dx, dy)(e_y, e_x) -1 >>> WedgeProduct(dx, fx*dy)(fx*e_x, e_y) x**2 >>> WedgeProduct(e_x, e_y)(fy, None) -e_x You can nest wedge products. >>> wp1 = WedgeProduct(dx, dy) >>> WedgeProduct(wp1, dx)(e_x, e_y, e_x) 0 """ # TODO the calculation of signatures is slow # TODO you do not need all these permutations (neither the prefactor) def __call__(self, *fields): """Apply on a list of vector_fields. The expression is rewritten internally in terms of tensor products and evaluated.""" orders = (covariant_order(e) + contravariant_order(e) for e in self.args) mul = 1/Mul(*(factorial(o) for o in orders)) perms = permutations(fields) perms_par = (Permutation( p).signature() for p in permutations(range(len(fields)))) tensor_prod = TensorProduct(*self.args) return mul*Add(*[tensor_prod(*p[0])*p[1] for p in zip(perms, perms_par)]) class LieDerivative(Expr): """Lie derivative with respect to a vector field. Explanation =========== The transport operator that defines the Lie derivative is the pushforward of the field to be derived along the integral curve of the field with respect to which one derives. Examples ======== >>> from sympy.diffgeom.rn import R2_r, R2_p >>> from sympy.diffgeom import (LieDerivative, TensorProduct) >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> e_rho, e_theta = R2_p.base_vectors() >>> dx, dy = R2_r.base_oneforms() >>> LieDerivative(e_x, fy) 0 >>> LieDerivative(e_x, fx) 1 >>> LieDerivative(e_x, e_x) 0 The Lie derivative of a tensor field by another tensor field is equal to their commutator: >>> LieDerivative(e_x, e_rho) Commutator(e_x, e_rho) >>> LieDerivative(e_x + e_y, fx) 1 >>> tp = TensorProduct(dx, dy) >>> LieDerivative(e_x, tp) LieDerivative(e_x, TensorProduct(dx, dy)) >>> LieDerivative(e_x, tp) LieDerivative(e_x, TensorProduct(dx, dy)) """ def __new__(cls, v_field, expr): expr_form_ord = covariant_order(expr) if contravariant_order(v_field) != 1 or covariant_order(v_field): raise ValueError('Lie derivatives are defined only with respect to' ' vector fields. The supplied argument was not a ' 'vector field.') if expr_form_ord > 0: obj = super().__new__(cls, v_field, expr) # deprecated assignments obj._v_field = v_field obj._expr = expr return obj if expr.atoms(BaseVectorField): return Commutator(v_field, expr) else: return v_field.rcall(expr) @property def v_field(self): return self.args[0] @property def expr(self): return self.args[1] def __call__(self, *args): v = self.v_field expr = self.expr lead_term = v(expr(*args)) rest = Add(*[Mul(*args[:i] + (Commutator(v, args[i]),) + args[i + 1:]) for i in range(len(args))]) return lead_term - rest class BaseCovarDerivativeOp(Expr): """Covariant derivative operator with respect to a base vector. Examples ======== >>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import BaseCovarDerivativeOp >>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct >>> TP = TensorProduct >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> dx, dy = R2_r.base_oneforms() >>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy)) >>> ch [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] >>> cvd = BaseCovarDerivativeOp(R2_r, 0, ch) >>> cvd(fx) 1 >>> cvd(fx*e_x) e_x """ def __new__(cls, coord_sys, index, christoffel): index = _sympify(index) christoffel = ImmutableDenseNDimArray(christoffel) obj = super().__new__(cls, coord_sys, index, christoffel) # deprecated assignments obj._coord_sys = coord_sys obj._index = index obj._christoffel = christoffel return obj @property def coord_sys(self): return self.args[0] @property def index(self): return self.args[1] @property def christoffel(self): return self.args[2] def __call__(self, field): """Apply on a scalar field. The action of a vector field on a scalar field is a directional differentiation. If the argument is not a scalar field the behaviour is undefined. """ if covariant_order(field) != 0: raise NotImplementedError() field = vectors_in_basis(field, self._coord_sys) wrt_vector = self._coord_sys.base_vector(self._index) wrt_scalar = self._coord_sys.coord_function(self._index) vectors = list(field.atoms(BaseVectorField)) # First step: replace all vectors with something susceptible to # derivation and do the derivation # TODO: you need a real dummy function for the next line d_funcs = [Function('_#_%s' % i)(wrt_scalar) for i, b in enumerate(vectors)] d_result = field.subs(list(zip(vectors, d_funcs))) d_result = wrt_vector(d_result) # Second step: backsubstitute the vectors in d_result = d_result.subs(list(zip(d_funcs, vectors))) # Third step: evaluate the derivatives of the vectors derivs = [] for v in vectors: d = Add(*[(self._christoffel[k, wrt_vector._index, v._index] *v._coord_sys.base_vector(k)) for k in range(v._coord_sys.dim)]) derivs.append(d) to_subs = [wrt_vector(d) for d in d_funcs] # XXX: This substitution can fail when there are Dummy symbols and the # cache is disabled: https://github.com/sympy/sympy/issues/17794 result = d_result.subs(list(zip(to_subs, derivs))) # Remove the dummies result = result.subs(list(zip(d_funcs, vectors))) return result.doit() class CovarDerivativeOp(Expr): """Covariant derivative operator. Examples ======== >>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import CovarDerivativeOp >>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct >>> TP = TensorProduct >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> dx, dy = R2_r.base_oneforms() >>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy)) >>> ch [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] >>> cvd = CovarDerivativeOp(fx*e_x, ch) >>> cvd(fx) x >>> cvd(fx*e_x) x*e_x """ def __new__(cls, wrt, christoffel): if len({v._coord_sys for v in wrt.atoms(BaseVectorField)}) > 1: raise NotImplementedError() if contravariant_order(wrt) != 1 or covariant_order(wrt): raise ValueError('Covariant derivatives are defined only with ' 'respect to vector fields. The supplied argument ' 'was not a vector field.') christoffel = ImmutableDenseNDimArray(christoffel) obj = super().__new__(cls, wrt, christoffel) # deprecated assigments obj._wrt = wrt obj._christoffel = christoffel return obj @property def wrt(self): return self.args[0] @property def christoffel(self): return self.args[1] def __call__(self, field): vectors = list(self._wrt.atoms(BaseVectorField)) base_ops = [BaseCovarDerivativeOp(v._coord_sys, v._index, self._christoffel) for v in vectors] return self._wrt.subs(list(zip(vectors, base_ops))).rcall(field) ############################################################################### # Integral curves on vector fields ############################################################################### def intcurve_series(vector_field, param, start_point, n=6, coord_sys=None, coeffs=False): r"""Return the series expansion for an integral curve of the field. Explanation =========== Integral curve is a function `\gamma` taking a parameter in `R` to a point in the manifold. It verifies the equation: `V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)` where the given ``vector_field`` is denoted as `V`. This holds for any value `t` for the parameter and any scalar field `f`. This equation can also be decomposed of a basis of coordinate functions `V(f_i)\big(\gamma(t)\big) = \frac{d}{dt}f_i\big(\gamma(t)\big) \quad \forall i` This function returns a series expansion of `\gamma(t)` in terms of the coordinate system ``coord_sys``. The equations and expansions are necessarily done in coordinate-system-dependent way as there is no other way to represent movement between points on the manifold (i.e. there is no such thing as a difference of points for a general manifold). Parameters ========== vector_field the vector field for which an integral curve will be given param the argument of the function `\gamma` from R to the curve start_point the point which corresponds to `\gamma(0)` n the order to which to expand coord_sys the coordinate system in which to expand coeffs (default False) - if True return a list of elements of the expansion Examples ======== Use the predefined R2 manifold: >>> from sympy.abc import t, x, y >>> from sympy.diffgeom.rn import R2_p, R2_r >>> from sympy.diffgeom import intcurve_series Specify a starting point and a vector field: >>> start_point = R2_r.point([x, y]) >>> vector_field = R2_r.e_x Calculate the series: >>> intcurve_series(vector_field, t, start_point, n=3) Matrix([ [t + x], [ y]]) Or get the elements of the expansion in a list: >>> series = intcurve_series(vector_field, t, start_point, n=3, coeffs=True) >>> series[0] Matrix([ [x], [y]]) >>> series[1] Matrix([ [t], [0]]) >>> series[2] Matrix([ [0], [0]]) The series in the polar coordinate system: >>> series = intcurve_series(vector_field, t, start_point, ... n=3, coord_sys=R2_p, coeffs=True) >>> series[0] Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]]) >>> series[1] Matrix([ [t*x/sqrt(x**2 + y**2)], [ -t*y/(x**2 + y**2)]]) >>> series[2] Matrix([ [t**2*(-x**2/(x**2 + y**2)**(3/2) + 1/sqrt(x**2 + y**2))/2], [ t**2*x*y/(x**2 + y**2)**2]]) See Also ======== intcurve_diffequ """ if contravariant_order(vector_field) != 1 or covariant_order(vector_field): raise ValueError('The supplied field was not a vector field.') def iter_vfield(scalar_field, i): """Return ``vector_field`` called `i` times on ``scalar_field``.""" return reduce(lambda s, v: v.rcall(s), [vector_field, ]*i, scalar_field) def taylor_terms_per_coord(coord_function): """Return the series for one of the coordinates.""" return [param**i*iter_vfield(coord_function, i).rcall(start_point)/factorial(i) for i in range(n)] coord_sys = coord_sys if coord_sys else start_point._coord_sys coord_functions = coord_sys.coord_functions() taylor_terms = [taylor_terms_per_coord(f) for f in coord_functions] if coeffs: return [Matrix(t) for t in zip(*taylor_terms)] else: return Matrix([sum(c) for c in taylor_terms]) def intcurve_diffequ(vector_field, param, start_point, coord_sys=None): r"""Return the differential equation for an integral curve of the field. Explanation =========== Integral curve is a function `\gamma` taking a parameter in `R` to a point in the manifold. It verifies the equation: `V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)` where the given ``vector_field`` is denoted as `V`. This holds for any value `t` for the parameter and any scalar field `f`. This function returns the differential equation of `\gamma(t)` in terms of the coordinate system ``coord_sys``. The equations and expansions are necessarily done in coordinate-system-dependent way as there is no other way to represent movement between points on the manifold (i.e. there is no such thing as a difference of points for a general manifold). Parameters ========== vector_field the vector field for which an integral curve will be given param the argument of the function `\gamma` from R to the curve start_point the point which corresponds to `\gamma(0)` coord_sys the coordinate system in which to give the equations Returns ======= a tuple of (equations, initial conditions) Examples ======== Use the predefined R2 manifold: >>> from sympy.abc import t >>> from sympy.diffgeom.rn import R2, R2_p, R2_r >>> from sympy.diffgeom import intcurve_diffequ Specify a starting point and a vector field: >>> start_point = R2_r.point([0, 1]) >>> vector_field = -R2.y*R2.e_x + R2.x*R2.e_y Get the equation: >>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point) >>> equations [f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)] >>> init_cond [f_0(0), f_1(0) - 1] The series in the polar coordinate system: >>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p) >>> equations [Derivative(f_0(t), t), Derivative(f_1(t), t) - 1] >>> init_cond [f_0(0) - 1, f_1(0) - pi/2] See Also ======== intcurve_series """ if contravariant_order(vector_field) != 1 or covariant_order(vector_field): raise ValueError('The supplied field was not a vector field.') coord_sys = coord_sys if coord_sys else start_point._coord_sys gammas = [Function('f_%d' % i)(param) for i in range( start_point._coord_sys.dim)] arbitrary_p = Point(coord_sys, gammas) coord_functions = coord_sys.coord_functions() equations = [simplify(diff(cf.rcall(arbitrary_p), param) - vector_field.rcall(cf).rcall(arbitrary_p)) for cf in coord_functions] init_cond = [simplify(cf.rcall(arbitrary_p).subs(param, 0) - cf.rcall(start_point)) for cf in coord_functions] return equations, init_cond ############################################################################### # Helpers ############################################################################### def dummyfy(args, exprs): # TODO Is this a good idea? d_args = Matrix([s.as_dummy() for s in args]) reps = dict(zip(args, d_args)) d_exprs = Matrix([_sympify(expr).subs(reps) for expr in exprs]) return d_args, d_exprs ############################################################################### # Helpers ############################################################################### def contravariant_order(expr, _strict=False): """Return the contravariant order of an expression. Examples ======== >>> from sympy.diffgeom import contravariant_order >>> from sympy.diffgeom.rn import R2 >>> from sympy.abc import a >>> contravariant_order(a) 0 >>> contravariant_order(a*R2.x + 2) 0 >>> contravariant_order(a*R2.x*R2.e_y + R2.e_x) 1 """ # TODO move some of this to class methods. # TODO rewrite using the .as_blah_blah methods if isinstance(expr, Add): orders = [contravariant_order(e) for e in expr.args] if len(set(orders)) != 1: raise ValueError('Misformed expression containing contravariant fields of varying order.') return orders[0] elif isinstance(expr, Mul): orders = [contravariant_order(e) for e in expr.args] not_zero = [o for o in orders if o != 0] if len(not_zero) > 1: raise ValueError('Misformed expression containing multiplication between vectors.') return 0 if not not_zero else not_zero[0] elif isinstance(expr, Pow): if covariant_order(expr.base) or covariant_order(expr.exp): raise ValueError( 'Misformed expression containing a power of a vector.') return 0 elif isinstance(expr, BaseVectorField): return 1 elif isinstance(expr, TensorProduct): return sum(contravariant_order(a) for a in expr.args) elif not _strict or expr.atoms(BaseScalarField): return 0 else: # If it does not contain anything related to the diffgeom module and it is _strict return -1 def covariant_order(expr, _strict=False): """Return the covariant order of an expression. Examples ======== >>> from sympy.diffgeom import covariant_order >>> from sympy.diffgeom.rn import R2 >>> from sympy.abc import a >>> covariant_order(a) 0 >>> covariant_order(a*R2.x + 2) 0 >>> covariant_order(a*R2.x*R2.dy + R2.dx) 1 """ # TODO move some of this to class methods. # TODO rewrite using the .as_blah_blah methods if isinstance(expr, Add): orders = [covariant_order(e) for e in expr.args] if len(set(orders)) != 1: raise ValueError('Misformed expression containing form fields of varying order.') return orders[0] elif isinstance(expr, Mul): orders = [covariant_order(e) for e in expr.args] not_zero = [o for o in orders if o != 0] if len(not_zero) > 1: raise ValueError('Misformed expression containing multiplication between forms.') return 0 if not not_zero else not_zero[0] elif isinstance(expr, Pow): if covariant_order(expr.base) or covariant_order(expr.exp): raise ValueError( 'Misformed expression containing a power of a form.') return 0 elif isinstance(expr, Differential): return covariant_order(*expr.args) + 1 elif isinstance(expr, TensorProduct): return sum(covariant_order(a) for a in expr.args) elif not _strict or expr.atoms(BaseScalarField): return 0 else: # If it does not contain anything related to the diffgeom module and it is _strict return -1 ############################################################################### # Coordinate transformation functions ############################################################################### def vectors_in_basis(expr, to_sys): """Transform all base vectors in base vectors of a specified coord basis. While the new base vectors are in the new coordinate system basis, any coefficients are kept in the old system. Examples ======== >>> from sympy.diffgeom import vectors_in_basis >>> from sympy.diffgeom.rn import R2_r, R2_p >>> vectors_in_basis(R2_r.e_x, R2_p) -y*e_theta/(x**2 + y**2) + x*e_rho/sqrt(x**2 + y**2) >>> vectors_in_basis(R2_p.e_r, R2_r) sin(theta)*e_y + cos(theta)*e_x """ vectors = list(expr.atoms(BaseVectorField)) new_vectors = [] for v in vectors: cs = v._coord_sys jac = cs.jacobian(to_sys, cs.coord_functions()) new = (jac.T*Matrix(to_sys.base_vectors()))[v._index] new_vectors.append(new) return expr.subs(list(zip(vectors, new_vectors))) ############################################################################### # Coordinate-dependent functions ############################################################################### def twoform_to_matrix(expr): """Return the matrix representing the twoform. For the twoform `w` return the matrix `M` such that `M[i,j]=w(e_i, e_j)`, where `e_i` is the i-th base vector field for the coordinate system in which the expression of `w` is given. Examples ======== >>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import twoform_to_matrix, TensorProduct >>> TP = TensorProduct >>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) Matrix([ [1, 0], [0, 1]]) >>> twoform_to_matrix(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) Matrix([ [x, 0], [0, 1]]) >>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy) - TP(R2.dx, R2.dy)/2) Matrix([ [ 1, 0], [-1/2, 1]]) """ if covariant_order(expr) != 2 or contravariant_order(expr): raise ValueError('The input expression is not a two-form.') coord_sys = _find_coords(expr) if len(coord_sys) != 1: raise ValueError('The input expression concerns more than one ' 'coordinate systems, hence there is no unambiguous ' 'way to choose a coordinate system for the matrix.') coord_sys = coord_sys.pop() vectors = coord_sys.base_vectors() expr = expr.expand() matrix_content = [[expr.rcall(v1, v2) for v1 in vectors] for v2 in vectors] return Matrix(matrix_content) def metric_to_Christoffel_1st(expr): """Return the nested list of Christoffel symbols for the given metric. This returns the Christoffel symbol of first kind that represents the Levi-Civita connection for the given metric. Examples ======== >>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import metric_to_Christoffel_1st, TensorProduct >>> TP = TensorProduct >>> metric_to_Christoffel_1st(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] >>> metric_to_Christoffel_1st(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[1/2, 0], [0, 0]], [[0, 0], [0, 0]]] """ matrix = twoform_to_matrix(expr) if not matrix.is_symmetric(): raise ValueError( 'The two-form representing the metric is not symmetric.') coord_sys = _find_coords(expr).pop() deriv_matrices = [matrix.applyfunc(d) for d in coord_sys.base_vectors()] indices = list(range(coord_sys.dim)) christoffel = [[[(deriv_matrices[k][i, j] + deriv_matrices[j][i, k] - deriv_matrices[i][j, k])/2 for k in indices] for j in indices] for i in indices] return ImmutableDenseNDimArray(christoffel) def metric_to_Christoffel_2nd(expr): """Return the nested list of Christoffel symbols for the given metric. This returns the Christoffel symbol of second kind that represents the Levi-Civita connection for the given metric. Examples ======== >>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct >>> TP = TensorProduct >>> metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] >>> metric_to_Christoffel_2nd(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[1/(2*x), 0], [0, 0]], [[0, 0], [0, 0]]] """ ch_1st = metric_to_Christoffel_1st(expr) coord_sys = _find_coords(expr).pop() indices = list(range(coord_sys.dim)) # XXX workaround, inverting a matrix does not work if it contains non # symbols #matrix = twoform_to_matrix(expr).inv() matrix = twoform_to_matrix(expr) s_fields = set() for e in matrix: s_fields.update(e.atoms(BaseScalarField)) s_fields = list(s_fields) dums = coord_sys.symbols matrix = matrix.subs(list(zip(s_fields, dums))).inv().subs(list(zip(dums, s_fields))) # XXX end of workaround christoffel = [[[Add(*[matrix[i, l]*ch_1st[l, j, k] for l in indices]) for k in indices] for j in indices] for i in indices] return ImmutableDenseNDimArray(christoffel) def metric_to_Riemann_components(expr): """Return the components of the Riemann tensor expressed in a given basis. Given a metric it calculates the components of the Riemann tensor in the canonical basis of the coordinate system in which the metric expression is given. Examples ======== >>> from sympy import exp >>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import metric_to_Riemann_components, TensorProduct >>> TP = TensorProduct >>> metric_to_Riemann_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]] >>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \ R2.r**2*TP(R2.dtheta, R2.dtheta) >>> non_trivial_metric exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta) >>> riemann = metric_to_Riemann_components(non_trivial_metric) >>> riemann[0, :, :, :] [[[0, 0], [0, 0]], [[0, exp(-2*rho)*rho], [-exp(-2*rho)*rho, 0]]] >>> riemann[1, :, :, :] [[[0, -1/rho], [1/rho, 0]], [[0, 0], [0, 0]]] """ ch_2nd = metric_to_Christoffel_2nd(expr) coord_sys = _find_coords(expr).pop() indices = list(range(coord_sys.dim)) deriv_ch = [[[[d(ch_2nd[i, j, k]) for d in coord_sys.base_vectors()] for k in indices] for j in indices] for i in indices] riemann_a = [[[[deriv_ch[rho][sig][nu][mu] - deriv_ch[rho][sig][mu][nu] for nu in indices] for mu in indices] for sig in indices] for rho in indices] riemann_b = [[[[Add(*[ch_2nd[rho, l, mu]*ch_2nd[l, sig, nu] - ch_2nd[rho, l, nu]*ch_2nd[l, sig, mu] for l in indices]) for nu in indices] for mu in indices] for sig in indices] for rho in indices] riemann = [[[[riemann_a[rho][sig][mu][nu] + riemann_b[rho][sig][mu][nu] for nu in indices] for mu in indices] for sig in indices] for rho in indices] return ImmutableDenseNDimArray(riemann) def metric_to_Ricci_components(expr): """Return the components of the Ricci tensor expressed in a given basis. Given a metric it calculates the components of the Ricci tensor in the canonical basis of the coordinate system in which the metric expression is given. Examples ======== >>> from sympy import exp >>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import metric_to_Ricci_components, TensorProduct >>> TP = TensorProduct >>> metric_to_Ricci_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[0, 0], [0, 0]] >>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \ R2.r**2*TP(R2.dtheta, R2.dtheta) >>> non_trivial_metric exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta) >>> metric_to_Ricci_components(non_trivial_metric) [[1/rho, 0], [0, exp(-2*rho)*rho]] """ riemann = metric_to_Riemann_components(expr) coord_sys = _find_coords(expr).pop() indices = list(range(coord_sys.dim)) ricci = [[Add(*[riemann[k, i, k, j] for k in indices]) for j in indices] for i in indices] return ImmutableDenseNDimArray(ricci) ############################################################################### # Classes for deprecation ############################################################################### class _deprecated_container: # This class gives deprecation warning. # When deprecated features are completely deleted, this should be removed as well. # See https://github.com/sympy/sympy/pull/19368 def __init__(self, message, data): super().__init__(data) self.message = message def warn(self): sympy_deprecation_warning( self.message, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", stacklevel=4 ) def __iter__(self): self.warn() return super().__iter__() def __getitem__(self, key): self.warn() return super().__getitem__(key) def __contains__(self, key): self.warn() return super().__contains__(key) class _deprecated_list(_deprecated_container, list): pass class _deprecated_dict(_deprecated_container, dict): pass # Import at end to avoid cyclic imports from sympy.simplify.simplify import simplify
8201158ed3a5499e8562efcd498f16755c821aff0fa56c6cf5bb0a9803bc30c1
""" This file contains some classical ciphers and routines implementing a linear-feedback shift register (LFSR) and the Diffie-Hellman key exchange. .. warning:: This module is intended for educational purposes only. Do not use the functions in this module for real cryptographic applications. If you wish to encrypt real data, we recommend using something like the `cryptography <https://cryptography.io/en/latest/>`_ module. """ from string import whitespace, ascii_uppercase as uppercase, printable from functools import reduce import warnings from itertools import cycle from sympy.core import Symbol from sympy.core.numbers import igcdex, mod_inverse, igcd, Rational from sympy.core.random import _randrange, _randint from sympy.matrices import Matrix from sympy.ntheory import isprime, primitive_root, factorint from sympy.ntheory import totient as _euler from sympy.ntheory import reduced_totient as _carmichael from sympy.ntheory.generate import nextprime from sympy.ntheory.modular import crt from sympy.polys.domains import FF from sympy.polys.polytools import gcd, Poly from sympy.utilities.misc import as_int, filldedent, translate from sympy.utilities.iterables import uniq, multiset class NonInvertibleCipherWarning(RuntimeWarning): """A warning raised if the cipher is not invertible.""" def __init__(self, msg): self.fullMessage = msg def __str__(self): return '\n\t' + self.fullMessage def warn(self, stacklevel=3): warnings.warn(self, stacklevel=stacklevel) def AZ(s=None): """Return the letters of ``s`` in uppercase. In case more than one string is passed, each of them will be processed and a list of upper case strings will be returned. Examples ======== >>> from sympy.crypto.crypto import AZ >>> AZ('Hello, world!') 'HELLOWORLD' >>> AZ('Hello, world!'.split()) ['HELLO', 'WORLD'] See Also ======== check_and_join """ if not s: return uppercase t = isinstance(s, str) if t: s = [s] rv = [check_and_join(i.upper().split(), uppercase, filter=True) for i in s] if t: return rv[0] return rv bifid5 = AZ().replace('J', '') bifid6 = AZ() + '0123456789' bifid10 = printable def padded_key(key, symbols): """Return a string of the distinct characters of ``symbols`` with those of ``key`` appearing first. A ValueError is raised if a) there are duplicate characters in ``symbols`` or b) there are characters in ``key`` that are not in ``symbols``. Examples ======== >>> from sympy.crypto.crypto import padded_key >>> padded_key('PUPPY', 'OPQRSTUVWXY') 'PUYOQRSTVWX' >>> padded_key('RSA', 'ARTIST') Traceback (most recent call last): ... ValueError: duplicate characters in symbols: T """ syms = list(uniq(symbols)) if len(syms) != len(symbols): extra = ''.join(sorted({ i for i in symbols if symbols.count(i) > 1})) raise ValueError('duplicate characters in symbols: %s' % extra) extra = set(key) - set(syms) if extra: raise ValueError( 'characters in key but not symbols: %s' % ''.join( sorted(extra))) key0 = ''.join(list(uniq(key))) # remove from syms characters in key0 return key0 + translate(''.join(syms), None, key0) def check_and_join(phrase, symbols=None, filter=None): """ Joins characters of ``phrase`` and if ``symbols`` is given, raises an error if any character in ``phrase`` is not in ``symbols``. Parameters ========== phrase String or list of strings to be returned as a string. symbols Iterable of characters allowed in ``phrase``. If ``symbols`` is ``None``, no checking is performed. Examples ======== >>> from sympy.crypto.crypto import check_and_join >>> check_and_join('a phrase') 'a phrase' >>> check_and_join('a phrase'.upper().split()) 'APHRASE' >>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True) 'ARAE' >>> check_and_join('a phrase!'.upper().split(), 'ARE') Traceback (most recent call last): ... ValueError: characters in phrase but not symbols: "!HPS" """ rv = ''.join(''.join(phrase)) if symbols is not None: symbols = check_and_join(symbols) missing = ''.join(list(sorted(set(rv) - set(symbols)))) if missing: if not filter: raise ValueError( 'characters in phrase but not symbols: "%s"' % missing) rv = translate(rv, None, missing) return rv def _prep(msg, key, alp, default=None): if not alp: if not default: alp = AZ() msg = AZ(msg) key = AZ(key) else: alp = default else: alp = ''.join(alp) key = check_and_join(key, alp, filter=True) msg = check_and_join(msg, alp, filter=True) return msg, key, alp def cycle_list(k, n): """ Returns the elements of the list ``range(n)`` shifted to the left by ``k`` (so the list starts with ``k`` (mod ``n``)). Examples ======== >>> from sympy.crypto.crypto import cycle_list >>> cycle_list(3, 10) [3, 4, 5, 6, 7, 8, 9, 0, 1, 2] """ k = k % n return list(range(k, n)) + list(range(k)) ######## shift cipher examples ############ def encipher_shift(msg, key, symbols=None): """ Performs shift cipher encryption on plaintext msg, and returns the ciphertext. Parameters ========== key : int The secret key. msg : str Plaintext of upper-case letters. Returns ======= str Ciphertext of upper-case letters. Examples ======== >>> from sympy.crypto.crypto import encipher_shift, decipher_shift >>> msg = "GONAVYBEATARMY" >>> ct = encipher_shift(msg, 1); ct 'HPOBWZCFBUBSNZ' To decipher the shifted text, change the sign of the key: >>> encipher_shift(ct, -1) 'GONAVYBEATARMY' There is also a convenience function that does this with the original key: >>> decipher_shift(ct, 1) 'GONAVYBEATARMY' Notes ===== ALGORITHM: STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L1`` of corresponding integers. 2. Compute from the list ``L1`` a new list ``L2``, given by adding ``(k mod 26)`` to each element in ``L1``. 3. Compute from the list ``L2`` a string ``ct`` of corresponding letters. The shift cipher is also called the Caesar cipher, after Julius Caesar, who, according to Suetonius, used it with a shift of three to protect messages of military significance. Caesar's nephew Augustus reportedly used a similar cipher, but with a right shift of 1. References ========== .. [1] https://en.wikipedia.org/wiki/Caesar_cipher .. [2] http://mathworld.wolfram.com/CaesarsMethod.html See Also ======== decipher_shift """ msg, _, A = _prep(msg, '', symbols) shift = len(A) - key % len(A) key = A[shift:] + A[:shift] return translate(msg, key, A) def decipher_shift(msg, key, symbols=None): """ Return the text by shifting the characters of ``msg`` to the left by the amount given by ``key``. Examples ======== >>> from sympy.crypto.crypto import encipher_shift, decipher_shift >>> msg = "GONAVYBEATARMY" >>> ct = encipher_shift(msg, 1); ct 'HPOBWZCFBUBSNZ' To decipher the shifted text, change the sign of the key: >>> encipher_shift(ct, -1) 'GONAVYBEATARMY' Or use this function with the original key: >>> decipher_shift(ct, 1) 'GONAVYBEATARMY' """ return encipher_shift(msg, -key, symbols) def encipher_rot13(msg, symbols=None): """ Performs the ROT13 encryption on a given plaintext ``msg``. Explanation =========== ROT13 is a substitution cipher which substitutes each letter in the plaintext message for the letter furthest away from it in the English alphabet. Equivalently, it is just a Caeser (shift) cipher with a shift key of 13 (midway point of the alphabet). References ========== .. [1] https://en.wikipedia.org/wiki/ROT13 See Also ======== decipher_rot13 encipher_shift """ return encipher_shift(msg, 13, symbols) def decipher_rot13(msg, symbols=None): """ Performs the ROT13 decryption on a given plaintext ``msg``. Explanation ============ ``decipher_rot13`` is equivalent to ``encipher_rot13`` as both ``decipher_shift`` with a key of 13 and ``encipher_shift`` key with a key of 13 will return the same results. Nonetheless, ``decipher_rot13`` has nonetheless been explicitly defined here for consistency. Examples ======== >>> from sympy.crypto.crypto import encipher_rot13, decipher_rot13 >>> msg = 'GONAVYBEATARMY' >>> ciphertext = encipher_rot13(msg);ciphertext 'TBANILORNGNEZL' >>> decipher_rot13(ciphertext) 'GONAVYBEATARMY' >>> encipher_rot13(msg) == decipher_rot13(msg) True >>> msg == decipher_rot13(ciphertext) True """ return decipher_shift(msg, 13, symbols) ######## affine cipher examples ############ def encipher_affine(msg, key, symbols=None, _inverse=False): r""" Performs the affine cipher encryption on plaintext ``msg``, and returns the ciphertext. Explanation =========== Encryption is based on the map `x \rightarrow ax+b` (mod `N`) where ``N`` is the number of characters in the alphabet. Decryption is based on the map `x \rightarrow cx+d` (mod `N`), where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`). In particular, for the map to be invertible, we need `\mathrm{gcd}(a, N) = 1` and an error will be raised if this is not true. Parameters ========== msg : str Characters that appear in ``symbols``. a, b : int, int A pair integers, with ``gcd(a, N) = 1`` (the secret key). symbols String of characters (default = uppercase letters). When no symbols are given, ``msg`` is converted to upper case letters and all other characters are ignored. Returns ======= ct String of characters (the ciphertext message) Notes ===== ALGORITHM: STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L1`` of corresponding integers. 2. Compute from the list ``L1`` a new list ``L2``, given by replacing ``x`` by ``a*x + b (mod N)``, for each element ``x`` in ``L1``. 3. Compute from the list ``L2`` a string ``ct`` of corresponding letters. This is a straightforward generalization of the shift cipher with the added complexity of requiring 2 characters to be deciphered in order to recover the key. References ========== .. [1] https://en.wikipedia.org/wiki/Affine_cipher See Also ======== decipher_affine """ msg, _, A = _prep(msg, '', symbols) N = len(A) a, b = key assert gcd(a, N) == 1 if _inverse: c = mod_inverse(a, N) d = -b*c a, b = c, d B = ''.join([A[(a*i + b) % N] for i in range(N)]) return translate(msg, A, B) def decipher_affine(msg, key, symbols=None): r""" Return the deciphered text that was made from the mapping, `x \rightarrow ax+b` (mod `N`), where ``N`` is the number of characters in the alphabet. Deciphering is done by reciphering with a new key: `x \rightarrow cx+d` (mod `N`), where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`). Examples ======== >>> from sympy.crypto.crypto import encipher_affine, decipher_affine >>> msg = "GO NAVY BEAT ARMY" >>> key = (3, 1) >>> encipher_affine(msg, key) 'TROBMVENBGBALV' >>> decipher_affine(_, key) 'GONAVYBEATARMY' See Also ======== encipher_affine """ return encipher_affine(msg, key, symbols, _inverse=True) def encipher_atbash(msg, symbols=None): r""" Enciphers a given ``msg`` into its Atbash ciphertext and returns it. Explanation =========== Atbash is a substitution cipher originally used to encrypt the Hebrew alphabet. Atbash works on the principle of mapping each alphabet to its reverse / counterpart (i.e. a would map to z, b to y etc.) Atbash is functionally equivalent to the affine cipher with ``a = 25`` and ``b = 25`` See Also ======== decipher_atbash """ return encipher_affine(msg, (25, 25), symbols) def decipher_atbash(msg, symbols=None): r""" Deciphers a given ``msg`` using Atbash cipher and returns it. Explanation =========== ``decipher_atbash`` is functionally equivalent to ``encipher_atbash``. However, it has still been added as a separate function to maintain consistency. Examples ======== >>> from sympy.crypto.crypto import encipher_atbash, decipher_atbash >>> msg = 'GONAVYBEATARMY' >>> encipher_atbash(msg) 'TLMZEBYVZGZINB' >>> decipher_atbash(msg) 'TLMZEBYVZGZINB' >>> encipher_atbash(msg) == decipher_atbash(msg) True >>> msg == encipher_atbash(encipher_atbash(msg)) True References ========== .. [1] https://en.wikipedia.org/wiki/Atbash See Also ======== encipher_atbash """ return decipher_affine(msg, (25, 25), symbols) #################### substitution cipher ########################### def encipher_substitution(msg, old, new=None): r""" Returns the ciphertext obtained by replacing each character that appears in ``old`` with the corresponding character in ``new``. If ``old`` is a mapping, then new is ignored and the replacements defined by ``old`` are used. Explanation =========== This is a more general than the affine cipher in that the key can only be recovered by determining the mapping for each symbol. Though in practice, once a few symbols are recognized the mappings for other characters can be quickly guessed. Examples ======== >>> from sympy.crypto.crypto import encipher_substitution, AZ >>> old = 'OEYAG' >>> new = '034^6' >>> msg = AZ("go navy! beat army!") >>> ct = encipher_substitution(msg, old, new); ct '60N^V4B3^T^RM4' To decrypt a substitution, reverse the last two arguments: >>> encipher_substitution(ct, new, old) 'GONAVYBEATARMY' In the special case where ``old`` and ``new`` are a permutation of order 2 (representing a transposition of characters) their order is immaterial: >>> old = 'NAVY' >>> new = 'ANYV' >>> encipher = lambda x: encipher_substitution(x, old, new) >>> encipher('NAVY') 'ANYV' >>> encipher(_) 'NAVY' The substitution cipher, in general, is a method whereby "units" (not necessarily single characters) of plaintext are replaced with ciphertext according to a regular system. >>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc'])) >>> print(encipher_substitution('abc', ords)) \97\98\99 References ========== .. [1] https://en.wikipedia.org/wiki/Substitution_cipher """ return translate(msg, old, new) ###################################################################### #################### Vigenere cipher examples ######################## ###################################################################### def encipher_vigenere(msg, key, symbols=None): """ Performs the Vigenere cipher encryption on plaintext ``msg``, and returns the ciphertext. Examples ======== >>> from sympy.crypto.crypto import encipher_vigenere, AZ >>> key = "encrypt" >>> msg = "meet me on monday" >>> encipher_vigenere(msg, key) 'QRGKKTHRZQEBPR' Section 1 of the Kryptos sculpture at the CIA headquarters uses this cipher and also changes the order of the alphabet [2]_. Here is the first line of that section of the sculpture: >>> from sympy.crypto.crypto import decipher_vigenere, padded_key >>> alp = padded_key('KRYPTOS', AZ()) >>> key = 'PALIMPSEST' >>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ' >>> decipher_vigenere(msg, key, alp) 'BETWEENSUBTLESHADINGANDTHEABSENC' Explanation =========== The Vigenere cipher is named after Blaise de Vigenere, a sixteenth century diplomat and cryptographer, by a historical accident. Vigenere actually invented a different and more complicated cipher. The so-called *Vigenere cipher* was actually invented by Giovan Batista Belaso in 1553. This cipher was used in the 1800's, for example, during the American Civil War. The Confederacy used a brass cipher disk to implement the Vigenere cipher (now on display in the NSA Museum in Fort Meade) [1]_. The Vigenere cipher is a generalization of the shift cipher. Whereas the shift cipher shifts each letter by the same amount (that amount being the key of the shift cipher) the Vigenere cipher shifts a letter by an amount determined by the key (which is a word or phrase known only to the sender and receiver). For example, if the key was a single letter, such as "C", then the so-called Vigenere cipher is actually a shift cipher with a shift of `2` (since "C" is the 2nd letter of the alphabet, if you start counting at `0`). If the key was a word with two letters, such as "CA", then the so-called Vigenere cipher will shift letters in even positions by `2` and letters in odd positions are left alone (shifted by `0`, since "A" is the 0th letter, if you start counting at `0`). ALGORITHM: INPUT: ``msg``: string of characters that appear in ``symbols`` (the plaintext) ``key``: a string of characters that appear in ``symbols`` (the secret key) ``symbols``: a string of letters defining the alphabet OUTPUT: ``ct``: string of characters (the ciphertext message) STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``key`` a list ``L1`` of corresponding integers. Let ``n1 = len(L1)``. 2. Compute from the string ``msg`` a list ``L2`` of corresponding integers. Let ``n2 = len(L2)``. 3. Break ``L2`` up sequentially into sublists of size ``n1``; the last sublist may be smaller than ``n1`` 4. For each of these sublists ``L`` of ``L2``, compute a new list ``C`` given by ``C[i] = L[i] + L1[i] (mod N)`` to the ``i``-th element in the sublist, for each ``i``. 5. Assemble these lists ``C`` by concatenation into a new list of length ``n2``. 6. Compute from the new list a string ``ct`` of corresponding letters. Once it is known that the key is, say, `n` characters long, frequency analysis can be applied to every `n`-th letter of the ciphertext to determine the plaintext. This method is called *Kasiski examination* (although it was first discovered by Babbage). If they key is as long as the message and is comprised of randomly selected characters -- a one-time pad -- the message is theoretically unbreakable. The cipher Vigenere actually discovered is an "auto-key" cipher described as follows. ALGORITHM: INPUT: ``key``: a string of letters (the secret key) ``msg``: string of letters (the plaintext message) OUTPUT: ``ct``: string of upper-case letters (the ciphertext message) STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L2`` of corresponding integers. Let ``n2 = len(L2)``. 2. Let ``n1`` be the length of the key. Append to the string ``key`` the first ``n2 - n1`` characters of the plaintext message. Compute from this string (also of length ``n2``) a list ``L1`` of integers corresponding to the letter numbers in the first step. 3. Compute a new list ``C`` given by ``C[i] = L1[i] + L2[i] (mod N)``. 4. Compute from the new list a string ``ct`` of letters corresponding to the new integers. To decipher the auto-key ciphertext, the key is used to decipher the first ``n1`` characters and then those characters become the key to decipher the next ``n1`` characters, etc...: >>> m = AZ('go navy, beat army! yes you can'); m 'GONAVYBEATARMYYESYOUCAN' >>> key = AZ('gold bug'); n1 = len(key); n2 = len(m) >>> auto_key = key + m[:n2 - n1]; auto_key 'GOLDBUGGONAVYBEATARMYYE' >>> ct = encipher_vigenere(m, auto_key); ct 'MCYDWSHKOGAMKZCELYFGAYR' >>> n1 = len(key) >>> pt = [] >>> while ct: ... part, ct = ct[:n1], ct[n1:] ... pt.append(decipher_vigenere(part, key)) ... key = pt[-1] ... >>> ''.join(pt) == m True References ========== .. [1] https://en.wikipedia.org/wiki/Vigenere_cipher .. [2] http://web.archive.org/web/20071116100808/ .. [3] http://web.archive.org/web/20071116100808/http://filebox.vt.edu/users/batman/kryptos.html (short URL: https://goo.gl/ijr22d) """ msg, key, A = _prep(msg, key, symbols) map = {c: i for i, c in enumerate(A)} key = [map[c] for c in key] N = len(map) k = len(key) rv = [] for i, m in enumerate(msg): rv.append(A[(map[m] + key[i % k]) % N]) rv = ''.join(rv) return rv def decipher_vigenere(msg, key, symbols=None): """ Decode using the Vigenere cipher. Examples ======== >>> from sympy.crypto.crypto import decipher_vigenere >>> key = "encrypt" >>> ct = "QRGK kt HRZQE BPR" >>> decipher_vigenere(ct, key) 'MEETMEONMONDAY' """ msg, key, A = _prep(msg, key, symbols) map = {c: i for i, c in enumerate(A)} N = len(A) # normally, 26 K = [map[c] for c in key] n = len(K) C = [map[c] for c in msg] rv = ''.join([A[(-K[i % n] + c) % N] for i, c in enumerate(C)]) return rv #################### Hill cipher ######################## def encipher_hill(msg, key, symbols=None, pad="Q"): r""" Return the Hill cipher encryption of ``msg``. Explanation =========== The Hill cipher [1]_, invented by Lester S. Hill in the 1920's [2]_, was the first polygraphic cipher in which it was practical (though barely) to operate on more than three symbols at once. The following discussion assumes an elementary knowledge of matrices. First, each letter is first encoded as a number starting with 0. Suppose your message `msg` consists of `n` capital letters, with no spaces. This may be regarded an `n`-tuple M of elements of `Z_{26}` (if the letters are those of the English alphabet). A key in the Hill cipher is a `k x k` matrix `K`, all of whose entries are in `Z_{26}`, such that the matrix `K` is invertible (i.e., the linear transformation `K: Z_{N}^k \rightarrow Z_{N}^k` is one-to-one). Parameters ========== msg Plaintext message of `n` upper-case letters. key A `k \times k` invertible matrix `K`, all of whose entries are in `Z_{26}` (or whatever number of symbols are being used). pad Character (default "Q") to use to make length of text be a multiple of ``k``. Returns ======= ct Ciphertext of upper-case letters. Notes ===== ALGORITHM: STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L`` of corresponding integers. Let ``n = len(L)``. 2. Break the list ``L`` up into ``t = ceiling(n/k)`` sublists ``L_1``, ..., ``L_t`` of size ``k`` (with the last list "padded" to ensure its size is ``k``). 3. Compute new list ``C_1``, ..., ``C_t`` given by ``C[i] = K*L_i`` (arithmetic is done mod N), for each ``i``. 4. Concatenate these into a list ``C = C_1 + ... + C_t``. 5. Compute from ``C`` a string ``ct`` of corresponding letters. This has length ``k*t``. References ========== .. [1] https://en.wikipedia.org/wiki/Hill_cipher .. [2] Lester S. Hill, Cryptography in an Algebraic Alphabet, The American Mathematical Monthly Vol.36, June-July 1929, pp.306-312. See Also ======== decipher_hill """ assert key.is_square assert len(pad) == 1 msg, pad, A = _prep(msg, pad, symbols) map = {c: i for i, c in enumerate(A)} P = [map[c] for c in msg] N = len(A) k = key.cols n = len(P) m, r = divmod(n, k) if r: P = P + [map[pad]]*(k - r) m += 1 rv = ''.join([A[c % N] for j in range(m) for c in list(key*Matrix(k, 1, [P[i] for i in range(k*j, k*(j + 1))]))]) return rv def decipher_hill(msg, key, symbols=None): """ Deciphering is the same as enciphering but using the inverse of the key matrix. Examples ======== >>> from sympy.crypto.crypto import encipher_hill, decipher_hill >>> from sympy import Matrix >>> key = Matrix([[1, 2], [3, 5]]) >>> encipher_hill("meet me on monday", key) 'UEQDUEODOCTCWQ' >>> decipher_hill(_, key) 'MEETMEONMONDAY' When the length of the plaintext (stripped of invalid characters) is not a multiple of the key dimension, extra characters will appear at the end of the enciphered and deciphered text. In order to decipher the text, those characters must be included in the text to be deciphered. In the following, the key has a dimension of 4 but the text is 2 short of being a multiple of 4 so two characters will be added. >>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0], ... [2, 2, 3, 4], [1, 1, 0, 1]]) >>> msg = "ST" >>> encipher_hill(msg, key) 'HJEB' >>> decipher_hill(_, key) 'STQQ' >>> encipher_hill(msg, key, pad="Z") 'ISPK' >>> decipher_hill(_, key) 'STZZ' If the last two characters of the ciphertext were ignored in either case, the wrong plaintext would be recovered: >>> decipher_hill("HD", key) 'ORMV' >>> decipher_hill("IS", key) 'UIKY' See Also ======== encipher_hill """ assert key.is_square msg, _, A = _prep(msg, '', symbols) map = {c: i for i, c in enumerate(A)} C = [map[c] for c in msg] N = len(A) k = key.cols n = len(C) m, r = divmod(n, k) if r: C = C + [0]*(k - r) m += 1 key_inv = key.inv_mod(N) rv = ''.join([A[p % N] for j in range(m) for p in list(key_inv*Matrix( k, 1, [C[i] for i in range(k*j, k*(j + 1))]))]) return rv #################### Bifid cipher ######################## def encipher_bifid(msg, key, symbols=None): r""" Performs the Bifid cipher encryption on plaintext ``msg``, and returns the ciphertext. This is the version of the Bifid cipher that uses an `n \times n` Polybius square. Parameters ========== msg Plaintext string. key Short string for key. Duplicate characters are ignored and then it is padded with the characters in ``symbols`` that were not in the short key. symbols `n \times n` characters defining the alphabet. (default is string.printable) Returns ======= ciphertext Ciphertext using Bifid5 cipher without spaces. See Also ======== decipher_bifid, encipher_bifid5, encipher_bifid6 References ========== .. [1] https://en.wikipedia.org/wiki/Bifid_cipher """ msg, key, A = _prep(msg, key, symbols, bifid10) long_key = ''.join(uniq(key)) or A n = len(A)**.5 if n != int(n): raise ValueError( 'Length of alphabet (%s) is not a square number.' % len(A)) N = int(n) if len(long_key) < N**2: long_key = list(long_key) + [x for x in A if x not in long_key] # the fractionalization row_col = {ch: divmod(i, N) for i, ch in enumerate(long_key)} r, c = zip(*[row_col[x] for x in msg]) rc = r + c ch = {i: ch for ch, i in row_col.items()} rv = ''.join(ch[i] for i in zip(rc[::2], rc[1::2])) return rv def decipher_bifid(msg, key, symbols=None): r""" Performs the Bifid cipher decryption on ciphertext ``msg``, and returns the plaintext. This is the version of the Bifid cipher that uses the `n \times n` Polybius square. Parameters ========== msg Ciphertext string. key Short string for key. Duplicate characters are ignored and then it is padded with the characters in symbols that were not in the short key. symbols `n \times n` characters defining the alphabet. (default=string.printable, a `10 \times 10` matrix) Returns ======= deciphered Deciphered text. Examples ======== >>> from sympy.crypto.crypto import ( ... encipher_bifid, decipher_bifid, AZ) Do an encryption using the bifid5 alphabet: >>> alp = AZ().replace('J', '') >>> ct = AZ("meet me on monday!") >>> key = AZ("gold bug") >>> encipher_bifid(ct, key, alp) 'IEILHHFSTSFQYE' When entering the text or ciphertext, spaces are ignored so it can be formatted as desired. Re-entering the ciphertext from the preceding, putting 4 characters per line and padding with an extra J, does not cause problems for the deciphering: >>> decipher_bifid(''' ... IEILH ... HFSTS ... FQYEJ''', key, alp) 'MEETMEONMONDAY' When no alphabet is given, all 100 printable characters will be used: >>> key = '' >>> encipher_bifid('hello world!', key) 'bmtwmg-bIo*w' >>> decipher_bifid(_, key) 'hello world!' If the key is changed, a different encryption is obtained: >>> key = 'gold bug' >>> encipher_bifid('hello world!', 'gold_bug') 'hg2sfuei7t}w' And if the key used to decrypt the message is not exact, the original text will not be perfectly obtained: >>> decipher_bifid(_, 'gold pug') 'heldo~wor6d!' """ msg, _, A = _prep(msg, '', symbols, bifid10) long_key = ''.join(uniq(key)) or A n = len(A)**.5 if n != int(n): raise ValueError( 'Length of alphabet (%s) is not a square number.' % len(A)) N = int(n) if len(long_key) < N**2: long_key = list(long_key) + [x for x in A if x not in long_key] # the reverse fractionalization row_col = { ch: divmod(i, N) for i, ch in enumerate(long_key)} rc = [i for c in msg for i in row_col[c]] n = len(msg) rc = zip(*(rc[:n], rc[n:])) ch = {i: ch for ch, i in row_col.items()} rv = ''.join(ch[i] for i in rc) return rv def bifid_square(key): """Return characters of ``key`` arranged in a square. Examples ======== >>> from sympy.crypto.crypto import ( ... bifid_square, AZ, padded_key, bifid5) >>> bifid_square(AZ().replace('J', '')) Matrix([ [A, B, C, D, E], [F, G, H, I, K], [L, M, N, O, P], [Q, R, S, T, U], [V, W, X, Y, Z]]) >>> bifid_square(padded_key(AZ('gold bug!'), bifid5)) Matrix([ [G, O, L, D, B], [U, A, C, E, F], [H, I, K, M, N], [P, Q, R, S, T], [V, W, X, Y, Z]]) See Also ======== padded_key """ A = ''.join(uniq(''.join(key))) n = len(A)**.5 if n != int(n): raise ValueError( 'Length of alphabet (%s) is not a square number.' % len(A)) n = int(n) f = lambda i, j: Symbol(A[n*i + j]) rv = Matrix(n, n, f) return rv def encipher_bifid5(msg, key): r""" Performs the Bifid cipher encryption on plaintext ``msg``, and returns the ciphertext. Explanation =========== This is the version of the Bifid cipher that uses the `5 \times 5` Polybius square. The letter "J" is ignored so it must be replaced with something else (traditionally an "I") before encryption. ALGORITHM: (5x5 case) STEPS: 0. Create the `5 \times 5` Polybius square ``S`` associated to ``key`` as follows: a) moving from left-to-right, top-to-bottom, place the letters of the key into a `5 \times 5` matrix, b) if the key has less than 25 letters, add the letters of the alphabet not in the key until the `5 \times 5` square is filled. 1. Create a list ``P`` of pairs of numbers which are the coordinates in the Polybius square of the letters in ``msg``. 2. Let ``L1`` be the list of all first coordinates of ``P`` (length of ``L1 = n``), let ``L2`` be the list of all second coordinates of ``P`` (so the length of ``L2`` is also ``n``). 3. Let ``L`` be the concatenation of ``L1`` and ``L2`` (length ``L = 2*n``), except that consecutive numbers are paired ``(L[2*i], L[2*i + 1])``. You can regard ``L`` as a list of pairs of length ``n``. 4. Let ``C`` be the list of all letters which are of the form ``S[i, j]``, for all ``(i, j)`` in ``L``. As a string, this is the ciphertext of ``msg``. Parameters ========== msg : str Plaintext string. Converted to upper case and filtered of anything but all letters except J. key Short string for key; non-alphabetic letters, J and duplicated characters are ignored and then, if the length is less than 25 characters, it is padded with other letters of the alphabet (in alphabetical order). Returns ======= ct Ciphertext (all caps, no spaces). Examples ======== >>> from sympy.crypto.crypto import ( ... encipher_bifid5, decipher_bifid5) "J" will be omitted unless it is replaced with something else: >>> round_trip = lambda m, k: \ ... decipher_bifid5(encipher_bifid5(m, k), k) >>> key = 'a' >>> msg = "JOSIE" >>> round_trip(msg, key) 'OSIE' >>> round_trip(msg.replace("J", "I"), key) 'IOSIE' >>> j = "QIQ" >>> round_trip(msg.replace("J", j), key).replace(j, "J") 'JOSIE' Notes ===== The Bifid cipher was invented around 1901 by Felix Delastelle. It is a *fractional substitution* cipher, where letters are replaced by pairs of symbols from a smaller alphabet. The cipher uses a `5 \times 5` square filled with some ordering of the alphabet, except that "J" is replaced with "I" (this is a so-called Polybius square; there is a `6 \times 6` analog if you add back in "J" and also append onto the usual 26 letter alphabet, the digits 0, 1, ..., 9). According to Helen Gaines' book *Cryptanalysis*, this type of cipher was used in the field by the German Army during World War I. See Also ======== decipher_bifid5, encipher_bifid """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5) key = padded_key(key, bifid5) return encipher_bifid(msg, '', key) def decipher_bifid5(msg, key): r""" Return the Bifid cipher decryption of ``msg``. Explanation =========== This is the version of the Bifid cipher that uses the `5 \times 5` Polybius square; the letter "J" is ignored unless a ``key`` of length 25 is used. Parameters ========== msg Ciphertext string. key Short string for key; duplicated characters are ignored and if the length is less then 25 characters, it will be padded with other letters from the alphabet omitting "J". Non-alphabetic characters are ignored. Returns ======= plaintext Plaintext from Bifid5 cipher (all caps, no spaces). Examples ======== >>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5 >>> key = "gold bug" >>> encipher_bifid5('meet me on friday', key) 'IEILEHFSTSFXEE' >>> encipher_bifid5('meet me on monday', key) 'IEILHHFSTSFQYE' >>> decipher_bifid5(_, key) 'MEETMEONMONDAY' """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5) key = padded_key(key, bifid5) return decipher_bifid(msg, '', key) def bifid5_square(key=None): r""" 5x5 Polybius square. Produce the Polybius square for the `5 \times 5` Bifid cipher. Examples ======== >>> from sympy.crypto.crypto import bifid5_square >>> bifid5_square("gold bug") Matrix([ [G, O, L, D, B], [U, A, C, E, F], [H, I, K, M, N], [P, Q, R, S, T], [V, W, X, Y, Z]]) """ if not key: key = bifid5 else: _, key, _ = _prep('', key.upper(), None, bifid5) key = padded_key(key, bifid5) return bifid_square(key) def encipher_bifid6(msg, key): r""" Performs the Bifid cipher encryption on plaintext ``msg``, and returns the ciphertext. This is the version of the Bifid cipher that uses the `6 \times 6` Polybius square. Parameters ========== msg Plaintext string (digits okay). key Short string for key (digits okay). If ``key`` is less than 36 characters long, the square will be filled with letters A through Z and digits 0 through 9. Returns ======= ciphertext Ciphertext from Bifid cipher (all caps, no spaces). See Also ======== decipher_bifid6, encipher_bifid """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6) key = padded_key(key, bifid6) return encipher_bifid(msg, '', key) def decipher_bifid6(msg, key): r""" Performs the Bifid cipher decryption on ciphertext ``msg``, and returns the plaintext. This is the version of the Bifid cipher that uses the `6 \times 6` Polybius square. Parameters ========== msg Ciphertext string (digits okay); converted to upper case key Short string for key (digits okay). If ``key`` is less than 36 characters long, the square will be filled with letters A through Z and digits 0 through 9. All letters are converted to uppercase. Returns ======= plaintext Plaintext from Bifid cipher (all caps, no spaces). Examples ======== >>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6 >>> key = "gold bug" >>> encipher_bifid6('meet me on monday at 8am', key) 'KFKLJJHF5MMMKTFRGPL' >>> decipher_bifid6(_, key) 'MEETMEONMONDAYAT8AM' """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6) key = padded_key(key, bifid6) return decipher_bifid(msg, '', key) def bifid6_square(key=None): r""" 6x6 Polybius square. Produces the Polybius square for the `6 \times 6` Bifid cipher. Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9". Examples ======== >>> from sympy.crypto.crypto import bifid6_square >>> key = "gold bug" >>> bifid6_square(key) Matrix([ [G, O, L, D, B, U], [A, C, E, F, H, I], [J, K, M, N, P, Q], [R, S, T, V, W, X], [Y, Z, 0, 1, 2, 3], [4, 5, 6, 7, 8, 9]]) """ if not key: key = bifid6 else: _, key, _ = _prep('', key.upper(), None, bifid6) key = padded_key(key, bifid6) return bifid_square(key) #################### RSA ############################# def _decipher_rsa_crt(i, d, factors): """Decipher RSA using chinese remainder theorem from the information of the relatively-prime factors of the modulus. Parameters ========== i : integer Ciphertext d : integer The exponent component. factors : list of relatively-prime integers The integers given must be coprime and the product must equal the modulus component of the original RSA key. Examples ======== How to decrypt RSA with CRT: >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key >>> primes = [61, 53] >>> e = 17 >>> args = primes + [e] >>> puk = rsa_public_key(*args) >>> prk = rsa_private_key(*args) >>> from sympy.crypto.crypto import encipher_rsa, _decipher_rsa_crt >>> msg = 65 >>> crt_primes = primes >>> encrypted = encipher_rsa(msg, puk) >>> decrypted = _decipher_rsa_crt(encrypted, prk[1], primes) >>> decrypted 65 """ moduluses = [pow(i, d, p) for p in factors] result = crt(factors, moduluses) if not result: raise ValueError("CRT failed") return result[0] def _rsa_key(*args, public=True, private=True, totient='Euler', index=None, multipower=None): r"""A private subroutine to generate RSA key Parameters ========== public, private : bool, optional Flag to generate either a public key, a private key. totient : 'Euler' or 'Carmichael' Different notation used for totient. multipower : bool, optional Flag to bypass warning for multipower RSA. """ if len(args) < 2: return False if totient not in ('Euler', 'Carmichael'): raise ValueError( "The argument totient={} should either be " \ "'Euler', 'Carmichalel'." \ .format(totient)) if totient == 'Euler': _totient = _euler else: _totient = _carmichael if index is not None: index = as_int(index) if totient != 'Carmichael': raise ValueError( "Setting the 'index' keyword argument requires totient" "notation to be specified as 'Carmichael'.") primes, e = args[:-1], args[-1] if not all(isprime(p) for p in primes): new_primes = [] for i in primes: new_primes.extend(factorint(i, multiple=True)) primes = new_primes n = reduce(lambda i, j: i*j, primes) tally = multiset(primes) if all(v == 1 for v in tally.values()): multiple = list(tally.keys()) phi = _totient._from_distinct_primes(*multiple) else: if not multipower: NonInvertibleCipherWarning( 'Non-distinctive primes found in the factors {}. ' 'The cipher may not be decryptable for some numbers ' 'in the complete residue system Z[{}], but the cipher ' 'can still be valid if you restrict the domain to be ' 'the reduced residue system Z*[{}]. You can pass ' 'the flag multipower=True if you want to suppress this ' 'warning.' .format(primes, n, n) # stacklevel=4 because most users will call a function that # calls this function ).warn(stacklevel=4) phi = _totient._from_factors(tally) if igcd(e, phi) == 1: if public and not private: if isinstance(index, int): e = e % phi e += index * phi return n, e if private and not public: d = mod_inverse(e, phi) if isinstance(index, int): d += index * phi return n, d return False def rsa_public_key(*args, **kwargs): r"""Return the RSA *public key* pair, `(n, e)` Parameters ========== args : naturals If specified as `p, q, e` where `p` and `q` are distinct primes and `e` is a desired public exponent of the RSA, `n = p q` and `e` will be verified against the totient `\phi(n)` (Euler totient) or `\lambda(n)` (Carmichael totient) to be `\gcd(e, \phi(n)) = 1` or `\gcd(e, \lambda(n)) = 1`. If specified as `p_1, p_2, \dots, p_n, e` where `p_1, p_2, \dots, p_n` are specified as primes, and `e` is specified as a desired public exponent of the RSA, it will be able to form a multi-prime RSA, which is a more generalized form of the popular 2-prime RSA. It can also be possible to form a single-prime RSA by specifying the argument as `p, e`, which can be considered a trivial case of a multiprime RSA. Furthermore, it can be possible to form a multi-power RSA by specifying two or more pairs of the primes to be same. However, unlike the two-distinct prime RSA or multi-prime RSA, not every numbers in the complete residue system (`\mathbb{Z}_n`) will be decryptable since the mapping `\mathbb{Z}_{n} \rightarrow \mathbb{Z}_{n}` will not be bijective. (Only except for the trivial case when `e = 1` or more generally, .. math:: e \in \left \{ 1 + k \lambda(n) \mid k \in \mathbb{Z} \land k \geq 0 \right \} when RSA reduces to the identity.) However, the RSA can still be decryptable for the numbers in the reduced residue system (`\mathbb{Z}_n^{\times}`), since the mapping `\mathbb{Z}_{n}^{\times} \rightarrow \mathbb{Z}_{n}^{\times}` can still be bijective. If you pass a non-prime integer to the arguments `p_1, p_2, \dots, p_n`, the particular number will be prime-factored and it will become either a multi-prime RSA or a multi-power RSA in its canonical form, depending on whether the product equals its radical or not. `p_1 p_2 \dots p_n = \text{rad}(p_1 p_2 \dots p_n)` totient : bool, optional If ``'Euler'``, it uses Euler's totient `\phi(n)` which is :meth:`sympy.ntheory.factor_.totient` in SymPy. If ``'Carmichael'``, it uses Carmichael's totient `\lambda(n)` which is :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy. Unlike private key generation, this is a trivial keyword for public key generation because `\gcd(e, \phi(n)) = 1 \iff \gcd(e, \lambda(n)) = 1`. index : nonnegative integer, optional Returns an arbitrary solution of a RSA public key at the index specified at `0, 1, 2, \dots`. This parameter needs to be specified along with ``totient='Carmichael'``. Similarly to the non-uniquenss of a RSA private key as described in the ``index`` parameter documentation in :meth:`rsa_private_key`, RSA public key is also not unique and there is an infinite number of RSA public exponents which can behave in the same manner. From any given RSA public exponent `e`, there are can be an another RSA public exponent `e + k \lambda(n)` where `k` is an integer, `\lambda` is a Carmichael's totient function. However, considering only the positive cases, there can be a principal solution of a RSA public exponent `e_0` in `0 < e_0 < \lambda(n)`, and all the other solutions can be canonicalzed in a form of `e_0 + k \lambda(n)`. ``index`` specifies the `k` notation to yield any possible value an RSA public key can have. An example of computing any arbitrary RSA public key: >>> from sympy.crypto.crypto import rsa_public_key >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=0) (3233, 17) >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=1) (3233, 797) >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=2) (3233, 1577) multipower : bool, optional Any pair of non-distinct primes found in the RSA specification will restrict the domain of the cryptosystem, as noted in the explanation of the parameter ``args``. SymPy RSA key generator may give a warning before dispatching it as a multi-power RSA, however, you can disable the warning if you pass ``True`` to this keyword. Returns ======= (n, e) : int, int `n` is a product of any arbitrary number of primes given as the argument. `e` is relatively prime (coprime) to the Euler totient `\phi(n)`. False Returned if less than two arguments are given, or `e` is not relatively prime to the modulus. Examples ======== >>> from sympy.crypto.crypto import rsa_public_key A public key of a two-prime RSA: >>> p, q, e = 3, 5, 7 >>> rsa_public_key(p, q, e) (15, 7) >>> rsa_public_key(p, q, 30) False A public key of a multiprime RSA: >>> primes = [2, 3, 5, 7, 11, 13] >>> e = 7 >>> args = primes + [e] >>> rsa_public_key(*args) (30030, 7) Notes ===== Although the RSA can be generalized over any modulus `n`, using two large primes had became the most popular specification because a product of two large primes is usually the hardest to factor relatively to the digits of `n` can have. However, it may need further understanding of the time complexities of each prime-factoring algorithms to verify the claim. See Also ======== rsa_private_key encipher_rsa decipher_rsa References ========== .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29 .. [2] http://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf .. [3] https://link.springer.com/content/pdf/10.1007%2FBFb0055738.pdf .. [4] http://www.itiis.org/digital-library/manuscript/1381 """ return _rsa_key(*args, public=True, private=False, **kwargs) def rsa_private_key(*args, **kwargs): r"""Return the RSA *private key* pair, `(n, d)` Parameters ========== args : naturals The keyword is identical to the ``args`` in :meth:`rsa_public_key`. totient : bool, optional If ``'Euler'``, it uses Euler's totient convention `\phi(n)` which is :meth:`sympy.ntheory.factor_.totient` in SymPy. If ``'Carmichael'``, it uses Carmichael's totient convention `\lambda(n)` which is :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy. There can be some output differences for private key generation as examples below. Example using Euler's totient: >>> from sympy.crypto.crypto import rsa_private_key >>> rsa_private_key(61, 53, 17, totient='Euler') (3233, 2753) Example using Carmichael's totient: >>> from sympy.crypto.crypto import rsa_private_key >>> rsa_private_key(61, 53, 17, totient='Carmichael') (3233, 413) index : nonnegative integer, optional Returns an arbitrary solution of a RSA private key at the index specified at `0, 1, 2, \dots`. This parameter needs to be specified along with ``totient='Carmichael'``. RSA private exponent is a non-unique solution of `e d \mod \lambda(n) = 1` and it is possible in any form of `d + k \lambda(n)`, where `d` is an another already-computed private exponent, and `\lambda` is a Carmichael's totient function, and `k` is any integer. However, considering only the positive cases, there can be a principal solution of a RSA private exponent `d_0` in `0 < d_0 < \lambda(n)`, and all the other solutions can be canonicalzed in a form of `d_0 + k \lambda(n)`. ``index`` specifies the `k` notation to yield any possible value an RSA private key can have. An example of computing any arbitrary RSA private key: >>> from sympy.crypto.crypto import rsa_private_key >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=0) (3233, 413) >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=1) (3233, 1193) >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=2) (3233, 1973) multipower : bool, optional The keyword is identical to the ``multipower`` in :meth:`rsa_public_key`. Returns ======= (n, d) : int, int `n` is a product of any arbitrary number of primes given as the argument. `d` is the inverse of `e` (mod `\phi(n)`) where `e` is the exponent given, and `\phi` is a Euler totient. False Returned if less than two arguments are given, or `e` is not relatively prime to the totient of the modulus. Examples ======== >>> from sympy.crypto.crypto import rsa_private_key A private key of a two-prime RSA: >>> p, q, e = 3, 5, 7 >>> rsa_private_key(p, q, e) (15, 7) >>> rsa_private_key(p, q, 30) False A private key of a multiprime RSA: >>> primes = [2, 3, 5, 7, 11, 13] >>> e = 7 >>> args = primes + [e] >>> rsa_private_key(*args) (30030, 823) See Also ======== rsa_public_key encipher_rsa decipher_rsa References ========== .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29 .. [2] http://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf .. [3] https://link.springer.com/content/pdf/10.1007%2FBFb0055738.pdf .. [4] http://www.itiis.org/digital-library/manuscript/1381 """ return _rsa_key(*args, public=False, private=True, **kwargs) def _encipher_decipher_rsa(i, key, factors=None): n, d = key if not factors: return pow(i, d, n) def _is_coprime_set(l): is_coprime_set = True for i in range(len(l)): for j in range(i+1, len(l)): if igcd(l[i], l[j]) != 1: is_coprime_set = False break return is_coprime_set prod = reduce(lambda i, j: i*j, factors) if prod == n and _is_coprime_set(factors): return _decipher_rsa_crt(i, d, factors) return _encipher_decipher_rsa(i, key, factors=None) def encipher_rsa(i, key, factors=None): r"""Encrypt the plaintext with RSA. Parameters ========== i : integer The plaintext to be encrypted for. key : (n, e) where n, e are integers `n` is the modulus of the key and `e` is the exponent of the key. The encryption is computed by `i^e \bmod n`. The key can either be a public key or a private key, however, the message encrypted by a public key can only be decrypted by a private key, and vice versa, as RSA is an asymmetric cryptography system. factors : list of coprime integers This is identical to the keyword ``factors`` in :meth:`decipher_rsa`. Notes ===== Some specifications may make the RSA not cryptographically meaningful. For example, `0`, `1` will remain always same after taking any number of exponentiation, thus, should be avoided. Furthermore, if `i^e < n`, `i` may easily be figured out by taking `e` th root. And also, specifying the exponent as `1` or in more generalized form as `1 + k \lambda(n)` where `k` is an nonnegative integer, `\lambda` is a carmichael totient, the RSA becomes an identity mapping. Examples ======== >>> from sympy.crypto.crypto import encipher_rsa >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key Public Key Encryption: >>> p, q, e = 3, 5, 7 >>> puk = rsa_public_key(p, q, e) >>> msg = 12 >>> encipher_rsa(msg, puk) 3 Private Key Encryption: >>> p, q, e = 3, 5, 7 >>> prk = rsa_private_key(p, q, e) >>> msg = 12 >>> encipher_rsa(msg, prk) 3 Encryption using chinese remainder theorem: >>> encipher_rsa(msg, prk, factors=[p, q]) 3 """ return _encipher_decipher_rsa(i, key, factors=factors) def decipher_rsa(i, key, factors=None): r"""Decrypt the ciphertext with RSA. Parameters ========== i : integer The ciphertext to be decrypted for. key : (n, d) where n, d are integers `n` is the modulus of the key and `d` is the exponent of the key. The decryption is computed by `i^d \bmod n`. The key can either be a public key or a private key, however, the message encrypted by a public key can only be decrypted by a private key, and vice versa, as RSA is an asymmetric cryptography system. factors : list of coprime integers As the modulus `n` created from RSA key generation is composed of arbitrary prime factors `n = {p_1}^{k_1}{p_2}^{k_2}\dots{p_n}^{k_n}` where `p_1, p_2, \dots, p_n` are distinct primes and `k_1, k_2, \dots, k_n` are positive integers, chinese remainder theorem can be used to compute `i^d \bmod n` from the fragmented modulo operations like .. math:: i^d \bmod {p_1}^{k_1}, i^d \bmod {p_2}^{k_2}, \dots, i^d \bmod {p_n}^{k_n} or like .. math:: i^d \bmod {p_1}^{k_1}{p_2}^{k_2}, i^d \bmod {p_3}^{k_3}, \dots , i^d \bmod {p_n}^{k_n} as long as every moduli does not share any common divisor each other. The raw primes used in generating the RSA key pair can be a good option. Note that the speed advantage of using this is only viable for very large cases (Like 2048-bit RSA keys) since the overhead of using pure Python implementation of :meth:`sympy.ntheory.modular.crt` may overcompensate the theoritical speed advantage. Notes ===== See the ``Notes`` section in the documentation of :meth:`encipher_rsa` Examples ======== >>> from sympy.crypto.crypto import decipher_rsa, encipher_rsa >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key Public Key Encryption and Decryption: >>> p, q, e = 3, 5, 7 >>> prk = rsa_private_key(p, q, e) >>> puk = rsa_public_key(p, q, e) >>> msg = 12 >>> new_msg = encipher_rsa(msg, prk) >>> new_msg 3 >>> decipher_rsa(new_msg, puk) 12 Private Key Encryption and Decryption: >>> p, q, e = 3, 5, 7 >>> prk = rsa_private_key(p, q, e) >>> puk = rsa_public_key(p, q, e) >>> msg = 12 >>> new_msg = encipher_rsa(msg, puk) >>> new_msg 3 >>> decipher_rsa(new_msg, prk) 12 Decryption using chinese remainder theorem: >>> decipher_rsa(new_msg, prk, factors=[p, q]) 12 See Also ======== encipher_rsa """ return _encipher_decipher_rsa(i, key, factors=factors) #################### kid krypto (kid RSA) ############################# def kid_rsa_public_key(a, b, A, B): r""" Kid RSA is a version of RSA useful to teach grade school children since it does not involve exponentiation. Explanation =========== Alice wants to talk to Bob. Bob generates keys as follows. Key generation: * Select positive integers `a, b, A, B` at random. * Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`, `n = (e d - 1)//M`. * The *public key* is `(n, e)`. Bob sends these to Alice. * The *private key* is `(n, d)`, which Bob keeps secret. Encryption: If `p` is the plaintext message then the ciphertext is `c = p e \pmod n`. Decryption: If `c` is the ciphertext message then the plaintext is `p = c d \pmod n`. Examples ======== >>> from sympy.crypto.crypto import kid_rsa_public_key >>> a, b, A, B = 3, 4, 5, 6 >>> kid_rsa_public_key(a, b, A, B) (369, 58) """ M = a*b - 1 e = A*M + a d = B*M + b n = (e*d - 1)//M return n, e def kid_rsa_private_key(a, b, A, B): """ Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`, `n = (e d - 1) / M`. The *private key* is `d`, which Bob keeps secret. Examples ======== >>> from sympy.crypto.crypto import kid_rsa_private_key >>> a, b, A, B = 3, 4, 5, 6 >>> kid_rsa_private_key(a, b, A, B) (369, 70) """ M = a*b - 1 e = A*M + a d = B*M + b n = (e*d - 1)//M return n, d def encipher_kid_rsa(msg, key): """ Here ``msg`` is the plaintext and ``key`` is the public key. Examples ======== >>> from sympy.crypto.crypto import ( ... encipher_kid_rsa, kid_rsa_public_key) >>> msg = 200 >>> a, b, A, B = 3, 4, 5, 6 >>> key = kid_rsa_public_key(a, b, A, B) >>> encipher_kid_rsa(msg, key) 161 """ n, e = key return (msg*e) % n def decipher_kid_rsa(msg, key): """ Here ``msg`` is the plaintext and ``key`` is the private key. Examples ======== >>> from sympy.crypto.crypto import ( ... kid_rsa_public_key, kid_rsa_private_key, ... decipher_kid_rsa, encipher_kid_rsa) >>> a, b, A, B = 3, 4, 5, 6 >>> d = kid_rsa_private_key(a, b, A, B) >>> msg = 200 >>> pub = kid_rsa_public_key(a, b, A, B) >>> pri = kid_rsa_private_key(a, b, A, B) >>> ct = encipher_kid_rsa(msg, pub) >>> decipher_kid_rsa(ct, pri) 200 """ n, d = key return (msg*d) % n #################### Morse Code ###################################### morse_char = { ".-": "A", "-...": "B", "-.-.": "C", "-..": "D", ".": "E", "..-.": "F", "--.": "G", "....": "H", "..": "I", ".---": "J", "-.-": "K", ".-..": "L", "--": "M", "-.": "N", "---": "O", ".--.": "P", "--.-": "Q", ".-.": "R", "...": "S", "-": "T", "..-": "U", "...-": "V", ".--": "W", "-..-": "X", "-.--": "Y", "--..": "Z", "-----": "0", ".----": "1", "..---": "2", "...--": "3", "....-": "4", ".....": "5", "-....": "6", "--...": "7", "---..": "8", "----.": "9", ".-.-.-": ".", "--..--": ",", "---...": ":", "-.-.-.": ";", "..--..": "?", "-....-": "-", "..--.-": "_", "-.--.": "(", "-.--.-": ")", ".----.": "'", "-...-": "=", ".-.-.": "+", "-..-.": "/", ".--.-.": "@", "...-..-": "$", "-.-.--": "!"} char_morse = {v: k for k, v in morse_char.items()} def encode_morse(msg, sep='|', mapping=None): """ Encodes a plaintext into popular Morse Code with letters separated by ``sep`` and words by a double ``sep``. Examples ======== >>> from sympy.crypto.crypto import encode_morse >>> msg = 'ATTACK RIGHT FLANK' >>> encode_morse(msg) '.-|-|-|.-|-.-.|-.-||.-.|..|--.|....|-||..-.|.-..|.-|-.|-.-' References ========== .. [1] https://en.wikipedia.org/wiki/Morse_code """ mapping = mapping or char_morse assert sep not in mapping word_sep = 2*sep mapping[" "] = word_sep suffix = msg and msg[-1] in whitespace # normalize whitespace msg = (' ' if word_sep else '').join(msg.split()) # omit unmapped chars chars = set(''.join(msg.split())) ok = set(mapping.keys()) msg = translate(msg, None, ''.join(chars - ok)) morsestring = [] words = msg.split() for word in words: morseword = [] for letter in word: morseletter = mapping[letter] morseword.append(morseletter) word = sep.join(morseword) morsestring.append(word) return word_sep.join(morsestring) + (word_sep if suffix else '') def decode_morse(msg, sep='|', mapping=None): """ Decodes a Morse Code with letters separated by ``sep`` (default is '|') and words by `word_sep` (default is '||) into plaintext. Examples ======== >>> from sympy.crypto.crypto import decode_morse >>> mc = '--|---|...-|.||.|.-|...|-' >>> decode_morse(mc) 'MOVE EAST' References ========== .. [1] https://en.wikipedia.org/wiki/Morse_code """ mapping = mapping or morse_char word_sep = 2*sep characterstring = [] words = msg.strip(word_sep).split(word_sep) for word in words: letters = word.split(sep) chars = [mapping[c] for c in letters] word = ''.join(chars) characterstring.append(word) rv = " ".join(characterstring) return rv #################### LFSRs ########################################## def lfsr_sequence(key, fill, n): r""" This function creates an LFSR sequence. Parameters ========== key : list A list of finite field elements, `[c_0, c_1, \ldots, c_k].` fill : list The list of the initial terms of the LFSR sequence, `[x_0, x_1, \ldots, x_k].` n Number of terms of the sequence that the function returns. Returns ======= L The LFSR sequence defined by `x_{n+1} = c_k x_n + \ldots + c_0 x_{n-k}`, for `n \leq k`. Notes ===== S. Golomb [G]_ gives a list of three statistical properties a sequence of numbers `a = \{a_n\}_{n=1}^\infty`, `a_n \in \{0,1\}`, should display to be considered "random". Define the autocorrelation of `a` to be .. math:: C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (-1)^{a_n + a_{n+k}}. In the case where `a` is periodic with period `P` then this reduces to .. math:: C(k) = {1\over P}\sum_{n=1}^P (-1)^{a_n + a_{n+k}}. Assume `a` is periodic with period `P`. - balance: .. math:: \left|\sum_{n=1}^P(-1)^{a_n}\right| \leq 1. - low autocorrelation: .. math:: C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right. (For sequences satisfying these first two properties, it is known that `\epsilon = -1/P` must hold.) - proportional runs property: In each period, half the runs have length `1`, one-fourth have length `2`, etc. Moreover, there are as many runs of `1`'s as there are of `0`'s. Examples ======== >>> from sympy.crypto.crypto import lfsr_sequence >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> lfsr_sequence(key, fill, 10) [1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2] References ========== .. [G] Solomon Golomb, Shift register sequences, Aegean Park Press, Laguna Hills, Ca, 1967 """ if not isinstance(key, list): raise TypeError("key must be a list") if not isinstance(fill, list): raise TypeError("fill must be a list") p = key[0].mod F = FF(p) s = fill k = len(fill) L = [] for i in range(n): s0 = s[:] L.append(s[0]) s = s[1:k] x = sum([int(key[i]*s0[i]) for i in range(k)]) s.append(F(x)) return L # use [x.to_int() for x in L] for int version def lfsr_autocorrelation(L, P, k): """ This function computes the LFSR autocorrelation function. Parameters ========== L A periodic sequence of elements of `GF(2)`. L must have length larger than P. P The period of L. k : int An integer `k` (`0 < k < P`). Returns ======= autocorrelation The k-th value of the autocorrelation of the LFSR L. Examples ======== >>> from sympy.crypto.crypto import ( ... lfsr_sequence, lfsr_autocorrelation) >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_autocorrelation(s, 15, 7) -1/15 >>> lfsr_autocorrelation(s, 15, 0) 1 """ if not isinstance(L, list): raise TypeError("L (=%s) must be a list" % L) P = int(P) k = int(k) L0 = L[:P] # slices makes a copy L1 = L0 + L0[:k] L2 = [(-1)**(L1[i].to_int() + L1[i + k].to_int()) for i in range(P)] tot = sum(L2) return Rational(tot, P) def lfsr_connection_polynomial(s): """ This function computes the LFSR connection polynomial. Parameters ========== s A sequence of elements of even length, with entries in a finite field. Returns ======= C(x) The connection polynomial of a minimal LFSR yielding s. This implements the algorithm in section 3 of J. L. Massey's article [M]_. Examples ======== >>> from sympy.crypto.crypto import ( ... lfsr_sequence, lfsr_connection_polynomial) >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**4 + x + 1 >>> fill = [F(1), F(0), F(0), F(1)] >>> key = [F(1), F(1), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + 1 >>> fill = [F(1), F(0), F(1)] >>> key = [F(1), F(1), F(0)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + x**2 + 1 >>> fill = [F(1), F(0), F(1)] >>> key = [F(1), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + x + 1 References ========== .. [M] James L. Massey, "Shift-Register Synthesis and BCH Decoding." IEEE Trans. on Information Theory, vol. 15(1), pp. 122-127, Jan 1969. """ # Initialization: p = s[0].mod x = Symbol("x") C = 1*x**0 B = 1*x**0 m = 1 b = 1*x**0 L = 0 N = 0 while N < len(s): if L > 0: dC = Poly(C).degree() r = min(L + 1, dC + 1) coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)] d = (s[N].to_int() + sum([coeffsC[i]*s[N - i].to_int() for i in range(1, r)])) % p if L == 0: d = s[N].to_int()*x**0 if d == 0: m += 1 N += 1 if d > 0: if 2*L > N: C = (C - d*((b**(p - 2)) % p)*x**m*B).expand() m += 1 N += 1 else: T = C C = (C - d*((b**(p - 2)) % p)*x**m*B).expand() L = N + 1 - L m = 1 b = d B = T N += 1 dC = Poly(C).degree() coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)] return sum([coeffsC[i] % p*x**i for i in range(dC + 1) if coeffsC[i] is not None]) #################### ElGamal ############################# def elgamal_private_key(digit=10, seed=None): r""" Return three number tuple as private key. Explanation =========== Elgamal encryption is based on the mathmatical problem called the Discrete Logarithm Problem (DLP). For example, `a^{b} \equiv c \pmod p` In general, if ``a`` and ``b`` are known, ``ct`` is easily calculated. If ``b`` is unknown, it is hard to use ``a`` and ``ct`` to get ``b``. Parameters ========== digit : int Minimum number of binary digits for key. Returns ======= tuple : (p, r, d) p = prime number. r = primitive root. d = random number. Notes ===== For testing purposes, the ``seed`` parameter may be set to control the output of this routine. See sympy.core.random._randrange. Examples ======== >>> from sympy.crypto.crypto import elgamal_private_key >>> from sympy.ntheory import is_primitive_root, isprime >>> a, b, _ = elgamal_private_key() >>> isprime(a) True >>> is_primitive_root(b, a) True """ randrange = _randrange(seed) p = nextprime(2**digit) return p, primitive_root(p), randrange(2, p) def elgamal_public_key(key): r""" Return three number tuple as public key. Parameters ========== key : (p, r, e) Tuple generated by ``elgamal_private_key``. Returns ======= tuple : (p, r, e) `e = r**d \bmod p` `d` is a random number in private key. Examples ======== >>> from sympy.crypto.crypto import elgamal_public_key >>> elgamal_public_key((1031, 14, 636)) (1031, 14, 212) """ p, r, e = key return p, r, pow(r, e, p) def encipher_elgamal(i, key, seed=None): r""" Encrypt message with public key. Explanation =========== ``i`` is a plaintext message expressed as an integer. ``key`` is public key (p, r, e). In order to encrypt a message, a random number ``a`` in ``range(2, p)`` is generated and the encryped message is returned as `c_{1}` and `c_{2}` where: `c_{1} \equiv r^{a} \pmod p` `c_{2} \equiv m e^{a} \pmod p` Parameters ========== msg int of encoded message. key Public key. Returns ======= tuple : (c1, c2) Encipher into two number. Notes ===== For testing purposes, the ``seed`` parameter may be set to control the output of this routine. See sympy.core.random._randrange. Examples ======== >>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key >>> pri = elgamal_private_key(5, seed=[3]); pri (37, 2, 3) >>> pub = elgamal_public_key(pri); pub (37, 2, 8) >>> msg = 36 >>> encipher_elgamal(msg, pub, seed=[3]) (8, 6) """ p, r, e = key if i < 0 or i >= p: raise ValueError( 'Message (%s) should be in range(%s)' % (i, p)) randrange = _randrange(seed) a = randrange(2, p) return pow(r, a, p), i*pow(e, a, p) % p def decipher_elgamal(msg, key): r""" Decrypt message with private key. `msg = (c_{1}, c_{2})` `key = (p, r, d)` According to extended Eucliden theorem, `u c_{1}^{d} + p n = 1` `u \equiv 1/{{c_{1}}^d} \pmod p` `u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p` `\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p` Examples ======== >>> from sympy.crypto.crypto import decipher_elgamal >>> from sympy.crypto.crypto import encipher_elgamal >>> from sympy.crypto.crypto import elgamal_private_key >>> from sympy.crypto.crypto import elgamal_public_key >>> pri = elgamal_private_key(5, seed=[3]) >>> pub = elgamal_public_key(pri); pub (37, 2, 8) >>> msg = 17 >>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg True """ p, _, d = key c1, c2 = msg u = igcdex(c1**d, p)[0] return u * c2 % p ################ Diffie-Hellman Key Exchange ######################### def dh_private_key(digit=10, seed=None): r""" Return three integer tuple as private key. Explanation =========== Diffie-Hellman key exchange is based on the mathematical problem called the Discrete Logarithm Problem (see ElGamal). Diffie-Hellman key exchange is divided into the following steps: * Alice and Bob agree on a base that consist of a prime ``p`` and a primitive root of ``p`` called ``g`` * Alice choses a number ``a`` and Bob choses a number ``b`` where ``a`` and ``b`` are random numbers in range `[2, p)`. These are their private keys. * Alice then publicly sends Bob `g^{a} \pmod p` while Bob sends Alice `g^{b} \pmod p` * They both raise the received value to their secretly chosen number (``a`` or ``b``) and now have both as their shared key `g^{ab} \pmod p` Parameters ========== digit Minimum number of binary digits required in key. Returns ======= tuple : (p, g, a) p = prime number. g = primitive root of p. a = random number from 2 through p - 1. Notes ===== For testing purposes, the ``seed`` parameter may be set to control the output of this routine. See sympy.core.random._randrange. Examples ======== >>> from sympy.crypto.crypto import dh_private_key >>> from sympy.ntheory import isprime, is_primitive_root >>> p, g, _ = dh_private_key() >>> isprime(p) True >>> is_primitive_root(g, p) True >>> p, g, _ = dh_private_key(5) >>> isprime(p) True >>> is_primitive_root(g, p) True """ p = nextprime(2**digit) g = primitive_root(p) randrange = _randrange(seed) a = randrange(2, p) return p, g, a def dh_public_key(key): r""" Return three number tuple as public key. This is the tuple that Alice sends to Bob. Parameters ========== key : (p, g, a) A tuple generated by ``dh_private_key``. Returns ======= tuple : int, int, int A tuple of `(p, g, g^a \mod p)` with `p`, `g` and `a` given as parameters.s Examples ======== >>> from sympy.crypto.crypto import dh_private_key, dh_public_key >>> p, g, a = dh_private_key(); >>> _p, _g, x = dh_public_key((p, g, a)) >>> p == _p and g == _g True >>> x == pow(g, a, p) True """ p, g, a = key return p, g, pow(g, a, p) def dh_shared_key(key, b): """ Return an integer that is the shared key. This is what Bob and Alice can both calculate using the public keys they received from each other and their private keys. Parameters ========== key : (p, g, x) Tuple `(p, g, x)` generated by ``dh_public_key``. b Random number in the range of `2` to `p - 1` (Chosen by second key exchange member (Bob)). Returns ======= int A shared key. Examples ======== >>> from sympy.crypto.crypto import ( ... dh_private_key, dh_public_key, dh_shared_key) >>> prk = dh_private_key(); >>> p, g, x = dh_public_key(prk); >>> sk = dh_shared_key((p, g, x), 1000) >>> sk == pow(x, 1000, p) True """ p, _, x = key if 1 >= b or b >= p: raise ValueError(filldedent(''' Value of b should be greater 1 and less than prime %s.''' % p)) return pow(x, b, p) ################ Goldwasser-Micali Encryption ######################### def _legendre(a, p): """ Returns the legendre symbol of a and p assuming that p is a prime. i.e. 1 if a is a quadratic residue mod p -1 if a is not a quadratic residue mod p 0 if a is divisible by p Parameters ========== a : int The number to test. p : prime The prime to test ``a`` against. Returns ======= int Legendre symbol (a / p). """ sig = pow(a, (p - 1)//2, p) if sig == 1: return 1 elif sig == 0: return 0 else: return -1 def _random_coprime_stream(n, seed=None): randrange = _randrange(seed) while True: y = randrange(n) if gcd(y, n) == 1: yield y def gm_private_key(p, q, a=None): r""" Check if ``p`` and ``q`` can be used as private keys for the Goldwasser-Micali encryption. The method works roughly as follows. Explanation =========== #. Pick two large primes $p$ and $q$. #. Call their product $N$. #. Given a message as an integer $i$, write $i$ in its bit representation $b_0, \dots, b_n$. #. For each $k$, if $b_k = 0$: let $a_k$ be a random square (quadratic residue) modulo $p q$ such that ``jacobi_symbol(a, p*q) = 1`` if $b_k = 1$: let $a_k$ be a random non-square (non-quadratic residue) modulo $p q$ such that ``jacobi_symbol(a, p*q) = 1`` returns $\left[a_1, a_2, \dots\right]$ $b_k$ can be recovered by checking whether or not $a_k$ is a residue. And from the $b_k$'s, the message can be reconstructed. The idea is that, while ``jacobi_symbol(a, p*q)`` can be easily computed (and when it is equal to $-1$ will tell you that $a$ is not a square mod $p q$), quadratic residuosity modulo a composite number is hard to compute without knowing its factorization. Moreover, approximately half the numbers coprime to $p q$ have :func:`~.jacobi_symbol` equal to $1$ . And among those, approximately half are residues and approximately half are not. This maximizes the entropy of the code. Parameters ========== p, q, a Initialization variables. Returns ======= tuple : (p, q) The input value ``p`` and ``q``. Raises ====== ValueError If ``p`` and ``q`` are not distinct odd primes. """ if p == q: raise ValueError("expected distinct primes, " "got two copies of %i" % p) elif not isprime(p) or not isprime(q): raise ValueError("first two arguments must be prime, " "got %i of %i" % (p, q)) elif p == 2 or q == 2: raise ValueError("first two arguments must not be even, " "got %i of %i" % (p, q)) return p, q def gm_public_key(p, q, a=None, seed=None): """ Compute public keys for ``p`` and ``q``. Note that in Goldwasser-Micali Encryption, public keys are randomly selected. Parameters ========== p, q, a : int, int, int Initialization variables. Returns ======= tuple : (a, N) ``a`` is the input ``a`` if it is not ``None`` otherwise some random integer coprime to ``p`` and ``q``. ``N`` is the product of ``p`` and ``q``. """ p, q = gm_private_key(p, q) N = p * q if a is None: randrange = _randrange(seed) while True: a = randrange(N) if _legendre(a, p) == _legendre(a, q) == -1: break else: if _legendre(a, p) != -1 or _legendre(a, q) != -1: return False return (a, N) def encipher_gm(i, key, seed=None): """ Encrypt integer 'i' using public_key 'key' Note that gm uses random encryption. Parameters ========== i : int The message to encrypt. key : (a, N) The public key. Returns ======= list : list of int The randomized encrypted message. """ if i < 0: raise ValueError( "message must be a non-negative " "integer: got %d instead" % i) a, N = key bits = [] while i > 0: bits.append(i % 2) i //= 2 gen = _random_coprime_stream(N, seed) rev = reversed(bits) encode = lambda b: next(gen)**2*pow(a, b) % N return [ encode(b) for b in rev ] def decipher_gm(message, key): """ Decrypt message 'message' using public_key 'key'. Parameters ========== message : list of int The randomized encrypted message. key : (p, q) The private key. Returns ======= int The encrypted message. """ p, q = key res = lambda m, p: _legendre(m, p) > 0 bits = [res(m, p) * res(m, q) for m in message] m = 0 for b in bits: m <<= 1 m += not b return m ########### RailFence Cipher ############# def encipher_railfence(message,rails): """ Performs Railfence Encryption on plaintext and returns ciphertext Examples ======== >>> from sympy.crypto.crypto import encipher_railfence >>> message = "hello world" >>> encipher_railfence(message,3) 'horel ollwd' Parameters ========== message : string, the message to encrypt. rails : int, the number of rails. Returns ======= The Encrypted string message. References ========== .. [1] https://en.wikipedia.org/wiki/Rail_fence_cipher """ r = list(range(rails)) p = cycle(r + r[-2:0:-1]) return ''.join(sorted(message, key=lambda i: next(p))) def decipher_railfence(ciphertext,rails): """ Decrypt the message using the given rails Examples ======== >>> from sympy.crypto.crypto import decipher_railfence >>> decipher_railfence("horel ollwd",3) 'hello world' Parameters ========== message : string, the message to encrypt. rails : int, the number of rails. Returns ======= The Decrypted string message. """ r = list(range(rails)) p = cycle(r + r[-2:0:-1]) idx = sorted(range(len(ciphertext)), key=lambda i: next(p)) res = [''] * len(ciphertext) for i, c in zip(idx, ciphertext): res[i] = c return ''.join(res) ################ Blum-Goldwasser cryptosystem ######################### def bg_private_key(p, q): """ Check if p and q can be used as private keys for the Blum-Goldwasser cryptosystem. Explanation =========== The three necessary checks for p and q to pass so that they can be used as private keys: 1. p and q must both be prime 2. p and q must be distinct 3. p and q must be congruent to 3 mod 4 Parameters ========== p, q The keys to be checked. Returns ======= p, q Input values. Raises ====== ValueError If p and q do not pass the above conditions. """ if not isprime(p) or not isprime(q): raise ValueError("the two arguments must be prime, " "got %i and %i" %(p, q)) elif p == q: raise ValueError("the two arguments must be distinct, " "got two copies of %i. " %p) elif (p - 3) % 4 != 0 or (q - 3) % 4 != 0: raise ValueError("the two arguments must be congruent to 3 mod 4, " "got %i and %i" %(p, q)) return p, q def bg_public_key(p, q): """ Calculates public keys from private keys. Explanation =========== The function first checks the validity of private keys passed as arguments and then returns their product. Parameters ========== p, q The private keys. Returns ======= N The public key. """ p, q = bg_private_key(p, q) N = p * q return N def encipher_bg(i, key, seed=None): """ Encrypts the message using public key and seed. Explanation =========== ALGORITHM: 1. Encodes i as a string of L bits, m. 2. Select a random element r, where 1 < r < key, and computes x = r^2 mod key. 3. Use BBS pseudo-random number generator to generate L random bits, b, using the initial seed as x. 4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L. 5. x_L = x^(2^L) mod key. 6. Return (c, x_L) Parameters ========== i Message, a non-negative integer key The public key Returns ======= Tuple (encrypted_message, x_L) Raises ====== ValueError If i is negative. """ if i < 0: raise ValueError( "message must be a non-negative " "integer: got %d instead" % i) enc_msg = [] while i > 0: enc_msg.append(i % 2) i //= 2 enc_msg.reverse() L = len(enc_msg) r = _randint(seed)(2, key - 1) x = r**2 % key x_L = pow(int(x), int(2**L), int(key)) rand_bits = [] for _ in range(L): rand_bits.append(x % 2) x = x**2 % key encrypt_msg = [m ^ b for (m, b) in zip(enc_msg, rand_bits)] return (encrypt_msg, x_L) def decipher_bg(message, key): """ Decrypts the message using private keys. Explanation =========== ALGORITHM: 1. Let, c be the encrypted message, y the second number received, and p and q be the private keys. 2. Compute, r_p = y^((p+1)/4 ^ L) mod p and r_q = y^((q+1)/4 ^ L) mod q. 3. Compute x_0 = (q(q^-1 mod p)r_p + p(p^-1 mod q)r_q) mod N. 4. From, recompute the bits using the BBS generator, as in the encryption algorithm. 5. Compute original message by XORing c and b. Parameters ========== message Tuple of encrypted message and a non-negative integer. key Tuple of private keys. Returns ======= orig_msg The original message """ p, q = key encrypt_msg, y = message public_key = p * q L = len(encrypt_msg) p_t = ((p + 1)/4)**L q_t = ((q + 1)/4)**L r_p = pow(int(y), int(p_t), int(p)) r_q = pow(int(y), int(q_t), int(q)) x = (q * mod_inverse(q, p) * r_p + p * mod_inverse(p, q) * r_q) % public_key orig_bits = [] for _ in range(L): orig_bits.append(x % 2) x = x**2 % public_key orig_msg = 0 for (m, b) in zip(encrypt_msg, orig_bits): orig_msg = orig_msg * 2 orig_msg += (m ^ b) return orig_msg
0df0110ad3be2bd9cf113e009e34e1697c2de5d7eab43b0840a90f0ae0cef853
""" The classes used here are for the internal use of assumptions system only and should not be used anywhere else as these do not possess the signatures common to SymPy objects. For general use of logic constructs please refer to sympy.logic classes And, Or, Not, etc. """ from itertools import combinations, product, zip_longest from sympy.assumptions.assume import AppliedPredicate, Predicate from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le from sympy.core.singleton import S from sympy.logic.boolalg import Or, And, Not, Xnor from sympy.logic.boolalg import (Equivalent, ITE, Implies, Nand, Nor, Xor) class Literal: """ The smallest element of a CNF object. Parameters ========== lit : Boolean expression is_Not : bool Examples ======== >>> from sympy import Q >>> from sympy.assumptions.cnf import Literal >>> from sympy.abc import x >>> Literal(Q.even(x)) Literal(Q.even(x), False) >>> Literal(~Q.even(x)) Literal(Q.even(x), True) """ def __new__(cls, lit, is_Not=False): if isinstance(lit, Not): lit = lit.args[0] is_Not = True elif isinstance(lit, (AND, OR, Literal)): return ~lit if is_Not else lit obj = super().__new__(cls) obj.lit = lit obj.is_Not = is_Not return obj @property def arg(self): return self.lit def rcall(self, expr): if callable(self.lit): lit = self.lit(expr) else: try: lit = self.lit.apply(expr) except AttributeError: lit = self.lit.rcall(expr) return type(self)(lit, self.is_Not) def __invert__(self): is_Not = not self.is_Not return Literal(self.lit, is_Not) def __str__(self): return '{}({}, {})'.format(type(self).__name__, self.lit, self.is_Not) __repr__ = __str__ def __eq__(self, other): return self.arg == other.arg and self.is_Not == other.is_Not def __hash__(self): h = hash((type(self).__name__, self.arg, self.is_Not)) return h class OR: """ A low-level implementation for Or """ def __init__(self, *args): self._args = args @property def args(self): return sorted(self._args, key=str) def rcall(self, expr): return type(self)(*[arg.rcall(expr) for arg in self._args ]) def __invert__(self): return AND(*[~arg for arg in self._args]) def __hash__(self): return hash((type(self).__name__,) + tuple(self.args)) def __eq__(self, other): return self.args == other.args def __str__(self): s = '(' + ' | '.join([str(arg) for arg in self.args]) + ')' return s __repr__ = __str__ class AND: """ A low-level implementation for And """ def __init__(self, *args): self._args = args def __invert__(self): return OR(*[~arg for arg in self._args]) @property def args(self): return sorted(self._args, key=str) def rcall(self, expr): return type(self)(*[arg.rcall(expr) for arg in self._args ]) def __hash__(self): return hash((type(self).__name__,) + tuple(self.args)) def __eq__(self, other): return self.args == other.args def __str__(self): s = '('+' & '.join([str(arg) for arg in self.args])+')' return s __repr__ = __str__ def to_NNF(expr, composite_map=None): """ Generates the Negation Normal Form of any boolean expression in terms of AND, OR, and Literal objects. Examples ======== >>> from sympy import Q, Eq >>> from sympy.assumptions.cnf import to_NNF >>> from sympy.abc import x, y >>> expr = Q.even(x) & ~Q.positive(x) >>> to_NNF(expr) (Literal(Q.even(x), False) & Literal(Q.positive(x), True)) Supported boolean objects are converted to corresponding predicates. >>> to_NNF(Eq(x, y)) Literal(Q.eq(x, y), False) If ``composite_map`` argument is given, ``to_NNF`` decomposes the specified predicate into a combination of primitive predicates. >>> cmap = {Q.nonpositive: Q.negative | Q.zero} >>> to_NNF(Q.nonpositive, cmap) (Literal(Q.negative, False) | Literal(Q.zero, False)) >>> to_NNF(Q.nonpositive(x), cmap) (Literal(Q.negative(x), False) | Literal(Q.zero(x), False)) """ from sympy.assumptions.ask import Q if composite_map is None: composite_map = {} binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} if type(expr) in binrelpreds: pred = binrelpreds[type(expr)] expr = pred(*expr.args) if isinstance(expr, Not): arg = expr.args[0] tmp = to_NNF(arg, composite_map) # Strategy: negate the NNF of expr return ~tmp if isinstance(expr, Or): return OR(*[to_NNF(x, composite_map) for x in Or.make_args(expr)]) if isinstance(expr, And): return AND(*[to_NNF(x, composite_map) for x in And.make_args(expr)]) if isinstance(expr, Nand): tmp = AND(*[to_NNF(x, composite_map) for x in expr.args]) return ~tmp if isinstance(expr, Nor): tmp = OR(*[to_NNF(x, composite_map) for x in expr.args]) return ~tmp if isinstance(expr, Xor): cnfs = [] for i in range(0, len(expr.args) + 1, 2): for neg in combinations(expr.args, i): clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map) for s in expr.args] cnfs.append(OR(*clause)) return AND(*cnfs) if isinstance(expr, Xnor): cnfs = [] for i in range(0, len(expr.args) + 1, 2): for neg in combinations(expr.args, i): clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map) for s in expr.args] cnfs.append(OR(*clause)) return ~AND(*cnfs) if isinstance(expr, Implies): L, R = to_NNF(expr.args[0], composite_map), to_NNF(expr.args[1], composite_map) return OR(~L, R) if isinstance(expr, Equivalent): cnfs = [] for a, b in zip_longest(expr.args, expr.args[1:], fillvalue=expr.args[0]): a = to_NNF(a, composite_map) b = to_NNF(b, composite_map) cnfs.append(OR(~a, b)) return AND(*cnfs) if isinstance(expr, ITE): L = to_NNF(expr.args[0], composite_map) M = to_NNF(expr.args[1], composite_map) R = to_NNF(expr.args[2], composite_map) return AND(OR(~L, M), OR(L, R)) if isinstance(expr, AppliedPredicate): pred, args = expr.function, expr.arguments newpred = composite_map.get(pred, None) if newpred is not None: return to_NNF(newpred.rcall(*args), composite_map) if isinstance(expr, Predicate): newpred = composite_map.get(expr, None) if newpred is not None: return to_NNF(newpred, composite_map) return Literal(expr) def distribute_AND_over_OR(expr): """ Distributes AND over OR in the NNF expression. Returns the result( Conjunctive Normal Form of expression) as a CNF object. """ if not isinstance(expr, (AND, OR)): tmp = set() tmp.add(frozenset((expr,))) return CNF(tmp) if isinstance(expr, OR): return CNF.all_or(*[distribute_AND_over_OR(arg) for arg in expr._args]) if isinstance(expr, AND): return CNF.all_and(*[distribute_AND_over_OR(arg) for arg in expr._args]) class CNF: """ Class to represent CNF of a Boolean expression. Consists of set of clauses, which themselves are stored as frozenset of Literal objects. Examples ======== >>> from sympy import Q >>> from sympy.assumptions.cnf import CNF >>> from sympy.abc import x >>> cnf = CNF.from_prop(Q.real(x) & ~Q.zero(x)) >>> cnf.clauses {frozenset({Literal(Q.zero(x), True)}), frozenset({Literal(Q.negative(x), False), Literal(Q.positive(x), False), Literal(Q.zero(x), False)})} """ def __init__(self, clauses=None): if not clauses: clauses = set() self.clauses = clauses def add(self, prop): clauses = CNF.to_CNF(prop).clauses self.add_clauses(clauses) def __str__(self): s = ' & '.join( ['(' + ' | '.join([str(lit) for lit in clause]) +')' for clause in self.clauses] ) return s def extend(self, props): for p in props: self.add(p) return self def copy(self): return CNF(set(self.clauses)) def add_clauses(self, clauses): self.clauses |= clauses @classmethod def from_prop(cls, prop): res = cls() res.add(prop) return res def __iand__(self, other): self.add_clauses(other.clauses) return self def all_predicates(self): predicates = set() for c in self.clauses: predicates |= {arg.lit for arg in c} return predicates def _or(self, cnf): clauses = set() for a, b in product(self.clauses, cnf.clauses): tmp = set(a) for t in b: tmp.add(t) clauses.add(frozenset(tmp)) return CNF(clauses) def _and(self, cnf): clauses = self.clauses.union(cnf.clauses) return CNF(clauses) def _not(self): clss = list(self.clauses) ll = set() for x in clss[-1]: ll.add(frozenset((~x,))) ll = CNF(ll) for rest in clss[:-1]: p = set() for x in rest: p.add(frozenset((~x,))) ll = ll._or(CNF(p)) return ll def rcall(self, expr): clause_list = list() for clause in self.clauses: lits = [arg.rcall(expr) for arg in clause] clause_list.append(OR(*lits)) expr = AND(*clause_list) return distribute_AND_over_OR(expr) @classmethod def all_or(cls, *cnfs): b = cnfs[0].copy() for rest in cnfs[1:]: b = b._or(rest) return b @classmethod def all_and(cls, *cnfs): b = cnfs[0].copy() for rest in cnfs[1:]: b = b._and(rest) return b @classmethod def to_CNF(cls, expr): from sympy.assumptions.facts import get_composite_predicates expr = to_NNF(expr, get_composite_predicates()) expr = distribute_AND_over_OR(expr) return expr @classmethod def CNF_to_cnf(cls, cnf): """ Converts CNF object to SymPy's boolean expression retaining the form of expression. """ def remove_literal(arg): return Not(arg.lit) if arg.is_Not else arg.lit return And(*(Or(*(remove_literal(arg) for arg in clause)) for clause in cnf.clauses)) class EncodedCNF: """ Class for encoding the CNF expression. """ def __init__(self, data=None, encoding=None): if not data and not encoding: data = [] encoding = {} self.data = data self.encoding = encoding self._symbols = list(encoding.keys()) def from_cnf(self, cnf): self._symbols = list(cnf.all_predicates()) n = len(self._symbols) self.encoding = dict(zip(self._symbols, range(1, n + 1))) self.data = [self.encode(clause) for clause in cnf.clauses] @property def symbols(self): return self._symbols @property def variables(self): return range(1, len(self._symbols) + 1) def copy(self): new_data = [set(clause) for clause in self.data] return EncodedCNF(new_data, dict(self.encoding)) def add_prop(self, prop): cnf = CNF.from_prop(prop) self.add_from_cnf(cnf) def add_from_cnf(self, cnf): clauses = [self.encode(clause) for clause in cnf.clauses] self.data += clauses def encode_arg(self, arg): literal = arg.lit value = self.encoding.get(literal, None) if value is None: n = len(self._symbols) self._symbols.append(literal) value = self.encoding[literal] = n + 1 if arg.is_Not: return -value else: return value def encode(self, clause): return {self.encode_arg(arg) if not arg.lit == S.false else 0 for arg in clause}
77d32bc068b44ad8a7a494fee88144f4b4510d5ab93da5ff0912607aaa6857bd
""" This module contain solvers for all kinds of equations: - algebraic or transcendental, use solve() - recurrence, use rsolve() - differential, use dsolve() - nonlinear (numerically), use nsolve() (you will need a good starting point) """ from sympy.core import (S, Add, Symbol, Dummy, Expr, Mul) from sympy.core.assumptions import check_assumptions from sympy.core.exprtools import factor_terms from sympy.core.function import (expand_mul, expand_log, Derivative, AppliedUndef, UndefinedFunction, nfloat, Function, expand_power_exp, _mexpand, expand, expand_func) from sympy.core.logic import fuzzy_not from sympy.core.numbers import ilcm, Float, Rational, _illegal from sympy.core.power import integer_log, Pow from sympy.core.relational import Eq, Ne from sympy.core.sorting import ordered, default_sort_key from sympy.core.sympify import sympify, _sympify from sympy.core.traversal import preorder_traversal from sympy.logic.boolalg import And, BooleanAtom from sympy.functions import (log, exp, LambertW, cos, sin, tan, acos, asin, atan, Abs, re, im, arg, sqrt, atan2) from sympy.functions.combinatorial.factorials import binomial from sympy.functions.elementary.hyperbolic import HyperbolicFunction from sympy.functions.elementary.piecewise import piecewise_fold, Piecewise from sympy.functions.elementary.trigonometric import TrigonometricFunction from sympy.integrals.integrals import Integral from sympy.ntheory.factor_ import divisors from sympy.simplify import (simplify, collect, powsimp, posify, # type: ignore powdenest, nsimplify, denom, logcombine, sqrtdenest, fraction, separatevars) from sympy.simplify.sqrtdenest import sqrt_depth from sympy.simplify.fu import TR1, TR2i from sympy.matrices.common import NonInvertibleMatrixError from sympy.matrices import Matrix, zeros from sympy.polys import roots, cancel, factor, Poly from sympy.polys.polyerrors import GeneratorsNeeded, PolynomialError from sympy.polys.solvers import sympy_eqs_to_ring, solve_lin_sys from sympy.utilities.lambdify import lambdify from sympy.utilities.misc import filldedent, debug from sympy.utilities.iterables import (connected_components, generate_bell, uniq, iterable, is_sequence, subsets, flatten) from sympy.utilities.decorator import conserve_mpmath_dps from mpmath import findroot from sympy.solvers.polysys import solve_poly_system from types import GeneratorType from collections import defaultdict from itertools import combinations, product import warnings def recast_to_symbols(eqs, symbols): """ Return (e, s, d) where e and s are versions of *eqs* and *symbols* in which any non-Symbol objects in *symbols* have been replaced with generic Dummy symbols and d is a dictionary that can be used to restore the original expressions. Examples ======== >>> from sympy.solvers.solvers import recast_to_symbols >>> from sympy import symbols, Function >>> x, y = symbols('x y') >>> fx = Function('f')(x) >>> eqs, syms = [fx + 1, x, y], [fx, y] >>> e, s, d = recast_to_symbols(eqs, syms); (e, s, d) ([_X0 + 1, x, y], [_X0, y], {_X0: f(x)}) The original equations and symbols can be restored using d: >>> assert [i.xreplace(d) for i in eqs] == eqs >>> assert [d.get(i, i) for i in s] == syms """ if not iterable(eqs) and iterable(symbols): raise ValueError('Both eqs and symbols must be iterable') orig = list(symbols) symbols = list(ordered(symbols)) swap_sym = {} i = 0 for j, s in enumerate(symbols): if not isinstance(s, Symbol) and s not in swap_sym: swap_sym[s] = Dummy('X%d' % i) i += 1 new_f = [] for i in eqs: isubs = getattr(i, 'subs', None) if isubs is not None: new_f.append(isubs(swap_sym)) else: new_f.append(i) restore = {v: k for k, v in swap_sym.items()} return new_f, [swap_sym.get(i, i) for i in orig], restore def _ispow(e): """Return True if e is a Pow or is exp.""" return isinstance(e, Expr) and (e.is_Pow or isinstance(e, exp)) def _simple_dens(f, symbols): # when checking if a denominator is zero, we can just check the # base of powers with nonzero exponents since if the base is zero # the power will be zero, too. To keep it simple and fast, we # limit simplification to exponents that are Numbers dens = set() for d in denoms(f, symbols): if d.is_Pow and d.exp.is_Number: if d.exp.is_zero: continue # foo**0 is never 0 d = d.base dens.add(d) return dens def denoms(eq, *symbols): """ Return (recursively) set of all denominators that appear in *eq* that contain any symbol in *symbols*; if *symbols* are not provided then all denominators will be returned. Examples ======== >>> from sympy.solvers.solvers import denoms >>> from sympy.abc import x, y, z >>> denoms(x/y) {y} >>> denoms(x/(y*z)) {y, z} >>> denoms(3/x + y/z) {x, z} >>> denoms(x/2 + y/z) {2, z} If *symbols* are provided then only denominators containing those symbols will be returned: >>> denoms(1/x + 1/y + 1/z, y, z) {y, z} """ pot = preorder_traversal(eq) dens = set() for p in pot: # Here p might be Tuple or Relational # Expr subtrees (e.g. lhs and rhs) will be traversed after by pot if not isinstance(p, Expr): continue den = denom(p) if den is S.One: continue for d in Mul.make_args(den): dens.add(d) if not symbols: return dens elif len(symbols) == 1: if iterable(symbols[0]): symbols = symbols[0] return {d for d in dens if any(s in d.free_symbols for s in symbols)} def checksol(f, symbol, sol=None, **flags): """ Checks whether sol is a solution of equation f == 0. Explanation =========== Input can be either a single symbol and corresponding value or a dictionary of symbols and values. When given as a dictionary and flag ``simplify=True``, the values in the dictionary will be simplified. *f* can be a single equation or an iterable of equations. A solution must satisfy all equations in *f* to be considered valid; if a solution does not satisfy any equation, False is returned; if one or more checks are inconclusive (and none are False) then None is returned. Examples ======== >>> from sympy import checksol, symbols >>> x, y = symbols('x,y') >>> checksol(x**4 - 1, x, 1) True >>> checksol(x**4 - 1, x, 0) False >>> checksol(x**2 + y**2 - 5**2, {x: 3, y: 4}) True To check if an expression is zero using ``checksol()``, pass it as *f* and send an empty dictionary for *symbol*: >>> checksol(x**2 + x - x*(x + 1), {}) True None is returned if ``checksol()`` could not conclude. flags: 'numerical=True (default)' do a fast numerical check if ``f`` has only one symbol. 'minimal=True (default is False)' a very fast, minimal testing. 'warn=True (default is False)' show a warning if checksol() could not conclude. 'simplify=True (default)' simplify solution before substituting into function and simplify the function before trying specific simplifications 'force=True (default is False)' make positive all symbols without assumptions regarding sign. """ from sympy.physics.units import Unit minimal = flags.get('minimal', False) if sol is not None: sol = {symbol: sol} elif isinstance(symbol, dict): sol = symbol else: msg = 'Expecting (sym, val) or ({sym: val}, None) but got (%s, %s)' raise ValueError(msg % (symbol, sol)) if iterable(f): if not f: raise ValueError('no functions to check') rv = True for fi in f: check = checksol(fi, sol, **flags) if check: continue if check is False: return False rv = None # don't return, wait to see if there's a False return rv f = _sympify(f) if f.is_number: return f.is_zero if isinstance(f, Poly): f = f.as_expr() elif isinstance(f, (Eq, Ne)): if f.rhs in (S.true, S.false): f = f.reversed B, E = f.args if isinstance(B, BooleanAtom): f = f.subs(sol) if not f.is_Boolean: return else: f = f.rewrite(Add, evaluate=False) if isinstance(f, BooleanAtom): return bool(f) elif not f.is_Relational and not f: return True illegal = set(_illegal) if any(sympify(v).atoms() & illegal for k, v in sol.items()): return False attempt = -1 numerical = flags.get('numerical', True) while 1: attempt += 1 if attempt == 0: val = f.subs(sol) if isinstance(val, Mul): val = val.as_independent(Unit)[0] if val.atoms() & illegal: return False elif attempt == 1: if not val.is_number: if not val.is_constant(*list(sol.keys()), simplify=not minimal): return False # there are free symbols -- simple expansion might work _, val = val.as_content_primitive() val = _mexpand(val.as_numer_denom()[0], recursive=True) elif attempt == 2: if minimal: return if flags.get('simplify', True): for k in sol: sol[k] = simplify(sol[k]) # start over without the failed expanded form, possibly # with a simplified solution val = simplify(f.subs(sol)) if flags.get('force', True): val, reps = posify(val) # expansion may work now, so try again and check exval = _mexpand(val, recursive=True) if exval.is_number: # we can decide now val = exval else: # if there are no radicals and no functions then this can't be # zero anymore -- can it? pot = preorder_traversal(expand_mul(val)) seen = set() saw_pow_func = False for p in pot: if p in seen: continue seen.add(p) if p.is_Pow and not p.exp.is_Integer: saw_pow_func = True elif p.is_Function: saw_pow_func = True elif isinstance(p, UndefinedFunction): saw_pow_func = True if saw_pow_func: break if saw_pow_func is False: return False if flags.get('force', True): # don't do a zero check with the positive assumptions in place val = val.subs(reps) nz = fuzzy_not(val.is_zero) if nz is not None: # issue 5673: nz may be True even when False # so these are just hacks to keep a false positive # from being returned # HACK 1: LambertW (issue 5673) if val.is_number and val.has(LambertW): # don't eval this to verify solution since if we got here, # numerical must be False return None # add other HACKs here if necessary, otherwise we assume # the nz value is correct return not nz break if val.is_Rational: return val == 0 if numerical and val.is_number: return (abs(val.n(18).n(12, chop=True)) < 1e-9) is S.true if flags.get('warn', False): warnings.warn("\n\tWarning: could not verify solution %s." % sol) # returns None if it can't conclude # TODO: improve solution testing def solve(f, *symbols, **flags): r""" Algebraically solves equations and systems of equations. Explanation =========== Currently supported: - polynomial - transcendental - piecewise combinations of the above - systems of linear and polynomial equations - systems containing relational expressions - systems implied by undetermined coefficients Examples ======== The default output varies according to the input and might be a list (possibly empty), a dictionary, a list of dictionaries or tuples, or an expression involving relationals. For specifics regarding different forms of output that may appear, see :ref:`solve_output`. Let it suffice here to say that to obtain a uniform output from `solve` use ``dict=True`` or ``set=True`` (see below). >>> from sympy import solve, Poly, Eq, Matrix, Symbol >>> from sympy.abc import x, y, z, a, b The expressions that are passed can be Expr, Equality, or Poly classes (or lists of the same); a Matrix is considered to be a list of all the elements of the matrix: >>> solve(x - 3, x) [3] >>> solve(Eq(x, 3), x) [3] >>> solve(Poly(x - 3), x) [3] >>> solve(Matrix([[x, x + y]]), x, y) == solve([x, x + y], x, y) True If no symbols are indicated to be of interest and the equation is univariate, a list of values is returned; otherwise, the keys in a dictionary will indicate which (of all the variables used in the expression(s)) variables and solutions were found: >>> solve(x**2 - 4) [-2, 2] >>> solve((x - a)*(y - b)) [{a: x}, {b: y}] >>> solve([x - 3, y - 1]) {x: 3, y: 1} >>> solve([x - 3, y**2 - 1]) [{x: 3, y: -1}, {x: 3, y: 1}] If you pass symbols for which solutions are sought, the output will vary depending on the number of symbols you passed, whether you are passing a list of expressions or not, and whether a linear system was solved. Uniform output is attained by using ``dict=True`` or ``set=True``. >>> #### *** feel free to skip to the stars below *** #### >>> from sympy import TableForm >>> h = [None, ';|;'.join(['e', 's', 'solve(e, s)', 'solve(e, s, dict=True)', ... 'solve(e, s, set=True)']).split(';')] >>> t = [] >>> for e, s in [ ... (x - y, y), ... (x - y, [x, y]), ... (x**2 - y, [x, y]), ... ([x - 3, y -1], [x, y]), ... ]: ... how = [{}, dict(dict=True), dict(set=True)] ... res = [solve(e, s, **f) for f in how] ... t.append([e, '|', s, '|'] + [res[0], '|', res[1], '|', res[2]]) ... >>> # ******************************************************* # >>> TableForm(t, headings=h, alignments="<") e | s | solve(e, s) | solve(e, s, dict=True) | solve(e, s, set=True) --------------------------------------------------------------------------------------- x - y | y | [x] | [{y: x}] | ([y], {(x,)}) x - y | [x, y] | [(y, y)] | [{x: y}] | ([x, y], {(y, y)}) x**2 - y | [x, y] | [(x, x**2)] | [{y: x**2}] | ([x, y], {(x, x**2)}) [x - 3, y - 1] | [x, y] | {x: 3, y: 1} | [{x: 3, y: 1}] | ([x, y], {(3, 1)}) * If any equation does not depend on the symbol(s) given, it will be eliminated from the equation set and an answer may be given implicitly in terms of variables that were not of interest: >>> solve([x - y, y - 3], x) {x: y} When you pass all but one of the free symbols, an attempt is made to find a single solution based on the method of undetermined coefficients. If it succeeds, a dictionary of values is returned. If you want an algebraic solutions for one or more of the symbols, pass the expression to be solved in a list: >>> e = a*x + b - 2*x - 3 >>> solve(e, [a, b]) {a: 2, b: 3} >>> solve([e], [a, b]) {a: -b/x + (2*x + 3)/x} When there is no solution for any given symbol which will make all expressions zero, the empty list is returned (or an empty set in the tuple when ``set=True``): >>> from sympy import sqrt >>> solve(3, x) [] >>> solve(x - 3, y) [] >>> solve(sqrt(x) + 1, x, set=True) ([x], set()) When an object other than a Symbol is given as a symbol, it is isolated algebraically and an implicit solution may be obtained. This is mostly provided as a convenience to save you from replacing the object with a Symbol and solving for that Symbol. It will only work if the specified object can be replaced with a Symbol using the subs method: >>> from sympy import exp, Function >>> f = Function('f') >>> solve(f(x) - x, f(x)) [x] >>> solve(f(x).diff(x) - f(x) - x, f(x).diff(x)) [x + f(x)] >>> solve(f(x).diff(x) - f(x) - x, f(x)) [-x + Derivative(f(x), x)] >>> solve(x + exp(x)**2, exp(x), set=True) ([exp(x)], {(-sqrt(-x),), (sqrt(-x),)}) >>> from sympy import Indexed, IndexedBase, Tuple >>> A = IndexedBase('A') >>> eqs = Tuple(A[1] + A[2] - 3, A[1] - A[2] + 1) >>> solve(eqs, eqs.atoms(Indexed)) {A[1]: 1, A[2]: 2} * To solve for a function within a derivative, use :func:`~.dsolve`. To solve for a symbol implicitly, use implicit=True: >>> solve(x + exp(x), x) [-LambertW(1)] >>> solve(x + exp(x), x, implicit=True) [-exp(x)] It is possible to solve for anything in an expression that can be replaced with a symbol using :obj:`~sympy.core.basic.Basic.subs`: >>> solve(x + 2 + sqrt(3), x + 2) [-sqrt(3)] >>> solve((x + 2 + sqrt(3), x + 4 + y), y, x + 2) {y: -2 + sqrt(3), x + 2: -sqrt(3)} * Nothing heroic is done in this implicit solving so you may end up with a symbol still in the solution: >>> eqs = (x*y + 3*y + sqrt(3), x + 4 + y) >>> solve(eqs, y, x + 2) {y: -sqrt(3)/(x + 3), x + 2: -2*x/(x + 3) - 6/(x + 3) + sqrt(3)/(x + 3)} >>> solve(eqs, y*x, x) {x: -y - 4, x*y: -3*y - sqrt(3)} * If you attempt to solve for a number, remember that the number you have obtained does not necessarily mean that the value is equivalent to the expression obtained: >>> solve(sqrt(2) - 1, 1) [sqrt(2)] >>> solve(x - y + 1, 1) # /!\ -1 is targeted, too [x/(y - 1)] >>> [_.subs(z, -1) for _ in solve((x - y + 1).subs(-1, z), 1)] [-x + y] **Additional Examples** ``solve()`` with check=True (default) will run through the symbol tags to eliminate unwanted solutions. If no assumptions are included, all possible solutions will be returned: >>> x = Symbol("x") >>> solve(x**2 - 1) [-1, 1] By setting the ``positive`` flag, only one solution will be returned: >>> pos = Symbol("pos", positive=True) >>> solve(pos**2 - 1) [1] When the solutions are checked, those that make any denominator zero are automatically excluded. If you do not want to exclude such solutions, then use the check=False option: >>> from sympy import sin, limit >>> solve(sin(x)/x) # 0 is excluded [pi] If ``check=False``, then a solution to the numerator being zero is found but the value of $x = 0$ is a spurious solution since $\sin(x)/x$ has the well known limit (without discontinuity) of 1 at $x = 0$: >>> solve(sin(x)/x, check=False) [0, pi] In the following case, however, the limit exists and is equal to the value of $x = 0$ that is excluded when check=True: >>> eq = x**2*(1/x - z**2/x) >>> solve(eq, x) [] >>> solve(eq, x, check=False) [0] >>> limit(eq, x, 0, '-') 0 >>> limit(eq, x, 0, '+') 0 **Solving Relationships** When one or more expressions passed to ``solve`` is a relational, a relational result is returned (and the ``dict`` and ``set`` flags are ignored): >>> solve(x < 3) (-oo < x) & (x < 3) >>> solve([x < 3, x**2 > 4], x) ((-oo < x) & (x < -2)) | ((2 < x) & (x < 3)) >>> solve([x + y - 3, x > 3], x) (3 < x) & (x < oo) & Eq(x, 3 - y) Although checking of assumptions on symbols in relationals is not done, setting assumptions will affect how certain relationals might automatically simplify: >>> solve(x**2 > 4) ((-oo < x) & (x < -2)) | ((2 < x) & (x < oo)) >>> r = Symbol('r', real=True) >>> solve(r**2 > 4) (2 < r) | (r < -2) There is currently no algorithm in SymPy that allows you to use relationships to resolve more than one variable. So the following does not determine that ``q < 0`` (and trying to solve for ``r`` and ``q`` will raise an error): >>> from sympy import symbols >>> r, q = symbols('r, q', real=True) >>> solve([r + q - 3, r > 3], r) (3 < r) & Eq(r, 3 - q) You can directly call the routine that ``solve`` calls when it encounters a relational: :func:`~.reduce_inequalities`. It treats Expr like Equality. >>> from sympy import reduce_inequalities >>> reduce_inequalities([x**2 - 4]) Eq(x, -2) | Eq(x, 2) If each relationship contains only one symbol of interest, the expressions can be processed for multiple symbols: >>> reduce_inequalities([0 <= x - 1, y < 3], [x, y]) (-oo < y) & (1 <= x) & (x < oo) & (y < 3) But an error is raised if any relationship has more than one symbol of interest: >>> reduce_inequalities([0 <= x*y - 1, y < 3], [x, y]) Traceback (most recent call last): ... NotImplementedError: inequality has more than one symbol of interest. **Disabling High-Order Explicit Solutions** When solving polynomial expressions, you might not want explicit solutions (which can be quite long). If the expression is univariate, ``CRootOf`` instances will be returned instead: >>> solve(x**3 - x + 1) [-1/((-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)) - (-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3, -(-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/((-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)), -(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/(3*sqrt(69)/2 + 27/2)**(1/3)] >>> solve(x**3 - x + 1, cubics=False) [CRootOf(x**3 - x + 1, 0), CRootOf(x**3 - x + 1, 1), CRootOf(x**3 - x + 1, 2)] If the expression is multivariate, no solution might be returned: >>> solve(x**3 - x + a, x, cubics=False) [] Sometimes solutions will be obtained even when a flag is False because the expression could be factored. In the following example, the equation can be factored as the product of a linear and a quadratic factor so explicit solutions (which did not require solving a cubic expression) are obtained: >>> eq = x**3 + 3*x**2 + x - 1 >>> solve(eq, cubics=False) [-1, -1 + sqrt(2), -sqrt(2) - 1] **Solving Equations Involving Radicals** Because of SymPy's use of the principle root, some solutions to radical equations will be missed unless check=False: >>> from sympy import root >>> eq = root(x**3 - 3*x**2, 3) + 1 - x >>> solve(eq) [] >>> solve(eq, check=False) [1/3] In the above example, there is only a single solution to the equation. Other expressions will yield spurious roots which must be checked manually; roots which give a negative argument to odd-powered radicals will also need special checking: >>> from sympy import real_root, S >>> eq = root(x, 3) - root(x, 5) + S(1)/7 >>> solve(eq) # this gives 2 solutions but misses a 3rd [CRootOf(7*x**5 - 7*x**3 + 1, 1)**15, CRootOf(7*x**5 - 7*x**3 + 1, 2)**15] >>> sol = solve(eq, check=False) >>> [abs(eq.subs(x,i).n(2)) for i in sol] [0.48, 0.e-110, 0.e-110, 0.052, 0.052] The first solution is negative so ``real_root`` must be used to see that it satisfies the expression: >>> abs(real_root(eq.subs(x, sol[0])).n(2)) 0.e-110 If the roots of the equation are not real then more care will be necessary to find the roots, especially for higher order equations. Consider the following expression: >>> expr = root(x, 3) - root(x, 5) We will construct a known value for this expression at x = 3 by selecting the 1-th root for each radical: >>> expr1 = root(x, 3, 1) - root(x, 5, 1) >>> v = expr1.subs(x, -3) The ``solve`` function is unable to find any exact roots to this equation: >>> eq = Eq(expr, v); eq1 = Eq(expr1, v) >>> solve(eq, check=False), solve(eq1, check=False) ([], []) The function ``unrad``, however, can be used to get a form of the equation for which numerical roots can be found: >>> from sympy.solvers.solvers import unrad >>> from sympy import nroots >>> e, (p, cov) = unrad(eq) >>> pvals = nroots(e) >>> inversion = solve(cov, x)[0] >>> xvals = [inversion.subs(p, i) for i in pvals] Although ``eq`` or ``eq1`` could have been used to find ``xvals``, the solution can only be verified with ``expr1``: >>> z = expr - v >>> [xi.n(chop=1e-9) for xi in xvals if abs(z.subs(x, xi).n()) < 1e-9] [] >>> z1 = expr1 - v >>> [xi.n(chop=1e-9) for xi in xvals if abs(z1.subs(x, xi).n()) < 1e-9] [-3.0] Parameters ========== f : - a single Expr or Poly that must be zero - an Equality - a Relational expression - a Boolean - iterable of one or more of the above symbols : (object(s) to solve for) specified as - none given (other non-numeric objects will be used) - single symbol - denested list of symbols (e.g., ``solve(f, x, y)``) - ordered iterable of symbols (e.g., ``solve(f, [x, y])``) flags : dict=True (default is False) Return list (perhaps empty) of solution mappings. set=True (default is False) Return list of symbols and set of tuple(s) of solution(s). exclude=[] (default) Do not try to solve for any of the free symbols in exclude; if expressions are given, the free symbols in them will be extracted automatically. check=True (default) If False, do not do any testing of solutions. This can be useful if you want to include solutions that make any denominator zero. numerical=True (default) Do a fast numerical check if *f* has only one symbol. minimal=True (default is False) A very fast, minimal testing. warn=True (default is False) Show a warning if ``checksol()`` could not conclude. simplify=True (default) Simplify all but polynomials of order 3 or greater before returning them and (if check is not False) use the general simplify function on the solutions and the expression obtained when they are substituted into the function which should be zero. force=True (default is False) Make positive all symbols without assumptions regarding sign. rational=True (default) Recast Floats as Rational; if this option is not used, the system containing Floats may fail to solve because of issues with polys. If rational=None, Floats will be recast as rationals but the answer will be recast as Floats. If the flag is False then nothing will be done to the Floats. manual=True (default is False) Do not use the polys/matrix method to solve a system of equations, solve them one at a time as you might "manually." implicit=True (default is False) Allows ``solve`` to return a solution for a pattern in terms of other functions that contain that pattern; this is only needed if the pattern is inside of some invertible function like cos, exp, ect. particular=True (default is False) Instructs ``solve`` to try to find a particular solution to a linear system with as many zeros as possible; this is very expensive. quick=True (default is False; ``particular`` must be True) Selects a fast heuristic to find a solution with many zeros whereas a value of False uses the very slow method guaranteed to find the largest number of zeros possible. cubics=True (default) Return explicit solutions when cubic expressions are encountered. When False, quartics and quintics are disabled, too. quartics=True (default) Return explicit solutions when quartic expressions are encountered. When False, quintics are disabled, too. quintics=True (default) Return explicit solutions (if possible) when quintic expressions are encountered. See Also ======== rsolve: For solving recurrence relationships dsolve: For solving differential equations """ from .inequalities import reduce_inequalities # checking/recording flags ########################################################################### # set solver types explicitly; as soon as one is False # all the rest will be False hints = ('cubics', 'quartics', 'quintics') default = True for k in hints: default = flags.setdefault(k, bool(flags.get(k, default))) # allow solution to contain symbol if True: implicit = flags.get('implicit', False) # record desire to see warnings warn = flags.get('warn', False) # this flag will be needed for quick exits below, so record # now -- but don't record `dict` yet since it might change as_set = flags.get('set', False) # keeping track of how f was passed bare_f = not iterable(f) # check flag usage for particular/quick which should only be used # with systems of equations if flags.get('quick', None) is not None: if not flags.get('particular', None): raise ValueError('when using `quick`, `particular` should be True') if flags.get('particular', False) and bare_f: raise ValueError(filldedent(""" The 'particular/quick' flag is usually used with systems of equations. Either pass your equation in a list or consider using a solver like `diophantine` if you are looking for a solution in integers.""")) # sympify everything, creating list of expressions and list of symbols ########################################################################### def _sympified_list(w): return list(map(sympify, w if iterable(w) else [w])) f, symbols = (_sympified_list(w) for w in [f, symbols]) # preprocess symbol(s) ########################################################################### ordered_symbols = None # were the symbols in a well defined order? if not symbols: # get symbols from equations symbols = set().union(*[fi.free_symbols for fi in f]) if len(symbols) < len(f): for fi in f: pot = preorder_traversal(fi) for p in pot: if isinstance(p, AppliedUndef): if not as_set: flags['dict'] = True # better show symbols symbols.add(p) pot.skip() # don't go any deeper ordered_symbols = False symbols = list(ordered(symbols)) # to make it canonical else: if len(symbols) == 1 and iterable(symbols[0]): symbols = symbols[0] ordered_symbols = symbols and is_sequence(symbols, include=GeneratorType) _symbols = list(uniq(symbols)) if len(_symbols) != len(symbols): ordered_symbols = False symbols = list(ordered(symbols)) else: symbols = _symbols # check for duplicates if len(symbols) != len(set(symbols)): raise ValueError('duplicate symbols given') # remove those not of interest exclude = flags.pop('exclude', set()) if exclude: if isinstance(exclude, Expr): exclude = [exclude] exclude = set().union(*[e.free_symbols for e in sympify(exclude)]) symbols = [s for s in symbols if s not in exclude] # preprocess equation(s) ########################################################################### # automatically ignore True values if isinstance(f, list): f = [s for s in f if s is not S.true] # handle canonicalization of equation types for i, fi in enumerate(f): if isinstance(fi, (Eq, Ne)): if 'ImmutableDenseMatrix' in [type(a).__name__ for a in fi.args]: fi = fi.lhs - fi.rhs else: L, R = fi.args if isinstance(R, BooleanAtom): L, R = R, L if isinstance(L, BooleanAtom): if isinstance(fi, Ne): L = ~L if R.is_Relational: fi = ~R if L is S.false else R elif R.is_Symbol: return L elif R.is_Boolean and (~R).is_Symbol: return ~L else: raise NotImplementedError(filldedent(''' Unanticipated argument of Eq when other arg is True or False. ''')) else: fi = fi.rewrite(Add, evaluate=False) f[i] = fi # *** dispatch and handle as a system of relationals # ************************************************** if fi.is_Relational: if len(symbols) != 1: raise ValueError("can only solve for one symbol at a time") if warn and symbols[0].assumptions0: warnings.warn(filldedent(""" \tWarning: assumptions about variable '%s' are not handled currently.""" % symbols[0])) return reduce_inequalities(f, symbols=symbols) # convert Poly to expression if isinstance(fi, Poly): f[i] = fi.as_expr() # rewrite hyperbolics in terms of exp if they have symbols of # interest f[i] = f[i].replace(lambda w: isinstance(w, HyperbolicFunction) and \ w.has_free(*symbols), lambda w: w.rewrite(exp)) # if we have a Matrix, we need to iterate over its elements again if f[i].is_Matrix: bare_f = False f.extend(list(f[i])) f[i] = S.Zero # if we can split it into real and imaginary parts then do so freei = f[i].free_symbols if freei and all(s.is_extended_real or s.is_imaginary for s in freei): fr, fi = f[i].as_real_imag() # accept as long as new re, im, arg or atan2 are not introduced had = f[i].atoms(re, im, arg, atan2) if fr and fi and fr != fi and not any( i.atoms(re, im, arg, atan2) - had for i in (fr, fi)): if bare_f: bare_f = False f[i: i + 1] = [fr, fi] # real/imag handling ----------------------------- if any(isinstance(fi, (bool, BooleanAtom)) for fi in f): if as_set: return [], set() return [] for i, fi in enumerate(f): # Abs while True: was = fi fi = fi.replace(Abs, lambda arg: separatevars(Abs(arg)).rewrite(Piecewise) if arg.has(*symbols) else Abs(arg)) if was == fi: break for e in fi.find(Abs): if e.has(*symbols): raise NotImplementedError('solving %s when the argument ' 'is not real or imaginary.' % e) # arg fi = fi.replace(arg, lambda a: arg(a).rewrite(atan2).rewrite(atan)) # save changes f[i] = fi # see if re(s) or im(s) appear freim = [fi for fi in f if fi.has(re, im)] if freim: irf = [] for s in symbols: if s.is_real or s.is_imaginary: continue # neither re(x) nor im(x) will appear # if re(s) or im(s) appear, the auxiliary equation must be present if any(fi.has(re(s), im(s)) for fi in freim): irf.append((s, re(s) + S.ImaginaryUnit*im(s))) if irf: for s, rhs in irf: f = [fi.xreplace({s: rhs}) for fi in f] + [s - rhs] symbols.extend([re(s), im(s)]) if bare_f: bare_f = False flags['dict'] = True # end of real/imag handling ----------------------------- # we can solve for non-symbol entities by replacing them with Dummy symbols f, symbols, swap_sym = recast_to_symbols(f, symbols) # this set of symbols (perhaps recast) is needed below symset = set(symbols) # get rid of equations that have no symbols of interest; we don't # try to solve them because the user didn't ask and they might be # hard to solve; this means that solutions may be given in terms # of the eliminated equations e.g. solve((x-y, y-3), x) -> {x: y} newf = [] for fi in f: # let the solver handle equations that.. # - have no symbols but are expressions # - have symbols of interest # - have no symbols of interest but are constant # but when an expression is not constant and has no symbols of # interest, it can't change what we obtain for a solution from # the remaining equations so we don't include it; and if it's # zero it can be removed and if it's not zero, there is no # solution for the equation set as a whole # # The reason for doing this filtering is to allow an answer # to be obtained to queries like solve((x - y, y), x); without # this mod the return value is [] ok = False if fi.free_symbols & symset: ok = True else: if fi.is_number: if fi.is_Number: if fi.is_zero: continue return [] ok = True else: if fi.is_constant(): ok = True if ok: newf.append(fi) if not newf: if as_set: return symbols, set() return [] f = newf del newf # mask off any Object that we aren't going to invert: Derivative, # Integral, etc... so that solving for anything that they contain will # give an implicit solution seen = set() non_inverts = set() for fi in f: pot = preorder_traversal(fi) for p in pot: if not isinstance(p, Expr) or isinstance(p, Piecewise): pass elif (isinstance(p, bool) or not p.args or p in symset or p.is_Add or p.is_Mul or p.is_Pow and not implicit or p.is_Function and not implicit) and p.func not in (re, im): continue elif p not in seen: seen.add(p) if p.free_symbols & symset: non_inverts.add(p) else: continue pot.skip() del seen non_inverts = dict(list(zip(non_inverts, [Dummy() for _ in non_inverts]))) f = [fi.subs(non_inverts) for fi in f] # Both xreplace and subs are needed below: xreplace to force substitution # inside Derivative, subs to handle non-straightforward substitutions non_inverts = [(v, k.xreplace(swap_sym).subs(swap_sym)) for k, v in non_inverts.items()] # rationalize Floats floats = False if flags.get('rational', True) is not False: for i, fi in enumerate(f): if fi.has(Float): floats = True f[i] = nsimplify(fi, rational=True) # capture any denominators before rewriting since # they may disappear after the rewrite, e.g. issue 14779 flags['_denominators'] = _simple_dens(f[0], symbols) # Any embedded piecewise functions need to be brought out to the # top level so that the appropriate strategy gets selected. # However, this is necessary only if one of the piecewise # functions depends on one of the symbols we are solving for. def _has_piecewise(e): if e.is_Piecewise: return e.has(*symbols) return any(_has_piecewise(a) for a in e.args) for i, fi in enumerate(f): if _has_piecewise(fi): f[i] = piecewise_fold(fi) # # try to get a solution ########################################################################### if bare_f: solution = None if len(symbols) != 1: solution = _solve_undetermined(f[0], symbols, flags) if not solution: solution = _solve(f[0], *symbols, **flags) else: linear, solution = _solve_system(f, symbols, **flags) assert type(solution) is list assert not solution or type(solution[0]) is dict, solution # # postprocessing ########################################################################### # capture as_dict flag now (as_set already captured) as_dict = flags.get('dict', False) # define how solution will get unpacked tuple_format = lambda s: [tuple([i.get(x, x) for x in symbols]) for i in s] if as_dict or as_set: unpack = None elif bare_f: if len(symbols) == 1: unpack = lambda s: [i[symbols[0]] for i in s] elif len(solution) == 1 and len(solution[0]) == len(symbols): # undetermined linear coeffs solution unpack = lambda s: s[0] elif ordered_symbols: unpack = tuple_format else: unpack = lambda s: s else: if solution: if linear and len(solution) == 1: # if you want the tuple solution for the linear # case, use `set=True` unpack = lambda s: s[0] elif ordered_symbols: unpack = tuple_format else: unpack = lambda s: s else: unpack = None # Restore masked-off objects if non_inverts and type(solution) is list: solution = [{k: v.subs(non_inverts) for k, v in s.items()} for s in solution] # Restore original "symbols" if a dictionary is returned. # This is not necessary for # - the single univariate equation case # since the symbol will have been removed from the solution; # - the nonlinear poly_system since that only supports zero-dimensional # systems and those results come back as a list # # ** unless there were Derivatives with the symbols, but those were handled # above. if swap_sym: symbols = [swap_sym.get(k, k) for k in symbols] for i, sol in enumerate(solution): solution[i] = {swap_sym.get(k, k): v.subs(swap_sym) for k, v in sol.items()} # Get assumptions about symbols, to filter solutions. # Note that if assumptions about a solution can't be verified, it is still # returned. check = flags.get('check', True) # restore floats if floats and solution and flags.get('rational', None) is None: solution = nfloat(solution, exponent=False) if check and solution: # assumption checking warn = flags.get('warn', False) got_None = [] # solutions for which one or more symbols gave None no_False = [] # solutions for which no symbols gave False for sol in solution: a_None = False for symb, val in sol.items(): test = check_assumptions(val, **symb.assumptions0) if test: continue if test is False: break a_None = True else: no_False.append(sol) if a_None: got_None.append(sol) solution = no_False if warn and got_None: warnings.warn(filldedent(""" \tWarning: assumptions concerning following solution(s) cannot be checked:""" + '\n\t' + ', '.join(str(s) for s in got_None))) # # done ########################################################################### if not solution: if as_set: return symbols, set() return [] # make orderings canonical for list of dictionaries if not as_set: # for set, no point in ordering solution = [{k: s[k] for k in ordered(s)} for s in solution] solution.sort(key=default_sort_key) if not (as_set or as_dict): return unpack(solution) if as_dict: return solution # set output: (symbols, {t1, t2, ...}) from list of dictionaries; # include all symbols for those that like a verbose solution # and to resolve any differences in dictionary keys. # # The set results can easily be used to make a verbose dict as # k, v = solve(eqs, syms, set=True) # sol = [dict(zip(k,i)) for i in v] # if ordered_symbols: k = symbols # keep preferred order else: # just unify the symbols for which solutions were found k = list(ordered(set(flatten(tuple(i.keys()) for i in solution)))) return k, {tuple([s.get(ki, ki) for ki in k]) for s in solution} def _solve_undetermined(g, symbols, flags): """solve helper to return a list with one dict (solution) else None A direct call to solve_undetermined_coeffs is more flexible and can return both multiple solutions and handle more than one independent variable. Here, we have to be more cautious to keep from solving something that does not look like an undetermined coeffs system -- to minimize the surprise factor since singularities that cancel are not prohibited in solve_undetermined_coeffs. """ if g.free_symbols - set(symbols): sol = solve_undetermined_coeffs(g, symbols, **dict(flags, dict=True, set=None)) if len(sol) == 1: return sol def _solve(f, *symbols, **flags): """Return a checked solution for *f* in terms of one or more of the symbols in the form of a list of dictionaries. If no method is implemented to solve the equation, a NotImplementedError will be raised. In the case that conversion of an expression to a Poly gives None a ValueError will be raised. """ not_impl_msg = "No algorithms are implemented to solve equation %s" if len(symbols) != 1: # look for solutions for desired symbols that are independent # of symbols already solved for, e.g. if we solve for x = y # then no symbol having x in its solution will be returned. # First solve for linear symbols (since that is easier and limits # solution size) and then proceed with symbols appearing # in a non-linear fashion. Ideally, if one is solving a single # expression for several symbols, they would have to be # appear in factors of an expression, but we do not here # attempt factorization. XXX perhaps handling a Mul # should come first in this routine whether there is # one or several symbols. nonlin_s = [] got_s = set() rhs_s = set() result = [] for s in symbols: xi, v = solve_linear(f, symbols=[s]) if xi == s: # no need to check but we should simplify if desired if flags.get('simplify', True): v = simplify(v) vfree = v.free_symbols if vfree & got_s: # was linear, but has redundant relationship # e.g. x - y = 0 has y == x is redundant for x == y # so ignore continue rhs_s |= vfree got_s.add(xi) result.append({xi: v}) elif xi: # there might be a non-linear solution if xi is not 0 nonlin_s.append(s) if not nonlin_s: return result for s in nonlin_s: try: soln = _solve(f, s, **flags) for sol in soln: if sol[s].free_symbols & got_s: # depends on previously solved symbols: ignore continue got_s.add(s) result.append(sol) except NotImplementedError: continue if got_s: return result else: raise NotImplementedError(not_impl_msg % f) # solve f for a single variable symbol = symbols[0] # expand binomials only if it has the unknown symbol f = f.replace(lambda e: isinstance(e, binomial) and e.has(symbol), lambda e: expand_func(e)) # checking will be done unless it is turned off before making a # recursive call; the variables `checkdens` and `check` are # captured here (for reference below) in case flag value changes flags['check'] = checkdens = check = flags.pop('check', True) # build up solutions if f is a Mul if f.is_Mul: result = set() for m in f.args: if m in {S.NegativeInfinity, S.ComplexInfinity, S.Infinity}: result = set() break soln = _vsolve(m, symbol, **flags) result.update(set(soln)) result = [{symbol: v} for v in result] if check: # all solutions have been checked but now we must # check that the solutions do not set denominators # in any factor to zero dens = flags.get('_denominators', _simple_dens(f, symbols)) result = [s for s in result if not any(checksol(den, s, **flags) for den in dens)] # set flags for quick exit at end; solutions for each # factor were already checked and simplified check = False flags['simplify'] = False elif f.is_Piecewise: result = set() for i, (expr, cond) in enumerate(f.args): if expr.is_zero: raise NotImplementedError( 'solve cannot represent interval solutions') candidates = _vsolve(expr, symbol, **flags) # the explicit condition for this expr is the current cond # and none of the previous conditions args = [~c for _, c in f.args[:i]] + [cond] cond = And(*args) for candidate in candidates: if candidate in result: # an unconditional value was already there continue try: v = cond.subs(symbol, candidate) _eval_simplify = getattr(v, '_eval_simplify', None) if _eval_simplify is not None: # unconditionally take the simpification of v v = _eval_simplify(ratio=2, measure=lambda x: 1) except TypeError: # incompatible type with condition(s) continue if v == False: continue if v == True: result.add(candidate) else: result.add(Piecewise( (candidate, v), (S.NaN, True))) # solutions already checked and simplified # **************************************** return [{symbol: r} for r in result] else: # first see if it really depends on symbol and whether there # is only a linear solution f_num, sol = solve_linear(f, symbols=symbols) if f_num.is_zero or sol is S.NaN: return [] elif f_num.is_Symbol: # no need to check but simplify if desired if flags.get('simplify', True): sol = simplify(sol) return [{f_num: sol}] poly = None # check for a single Add generator if not f_num.is_Add: add_args = [i for i in f_num.atoms(Add) if symbol in i.free_symbols] if len(add_args) == 1: gen = add_args[0] spart = gen.as_independent(symbol)[1].as_base_exp()[0] if spart == symbol: try: poly = Poly(f_num, spart) except PolynomialError: pass result = False # no solution was obtained msg = '' # there is no failure message # Poly is generally robust enough to convert anything to # a polynomial and tell us the different generators that it # contains, so we will inspect the generators identified by # polys to figure out what to do. # try to identify a single generator that will allow us to solve this # as a polynomial, followed (perhaps) by a change of variables if the # generator is not a symbol try: if poly is None: poly = Poly(f_num) if poly is None: raise ValueError('could not convert %s to Poly' % f_num) except GeneratorsNeeded: simplified_f = simplify(f_num) if simplified_f != f_num: return _solve(simplified_f, symbol, **flags) raise ValueError('expression appears to be a constant') gens = [g for g in poly.gens if g.has(symbol)] def _as_base_q(x): """Return (b**e, q) for x = b**(p*e/q) where p/q is the leading Rational of the exponent of x, e.g. exp(-2*x/3) -> (exp(x), 3) """ b, e = x.as_base_exp() if e.is_Rational: return b, e.q if not e.is_Mul: return x, 1 c, ee = e.as_coeff_Mul() if c.is_Rational and c is not S.One: # c could be a Float return b**ee, c.q return x, 1 if len(gens) > 1: # If there is more than one generator, it could be that the # generators have the same base but different powers, e.g. # >>> Poly(exp(x) + 1/exp(x)) # Poly(exp(-x) + exp(x), exp(-x), exp(x), domain='ZZ') # # If unrad was not disabled then there should be no rational # exponents appearing as in # >>> Poly(sqrt(x) + sqrt(sqrt(x))) # Poly(sqrt(x) + x**(1/4), sqrt(x), x**(1/4), domain='ZZ') bases, qs = list(zip(*[_as_base_q(g) for g in gens])) bases = set(bases) if len(bases) > 1 or not all(q == 1 for q in qs): funcs = {b for b in bases if b.is_Function} trig = {_ for _ in funcs if isinstance(_, TrigonometricFunction)} other = funcs - trig if not other and len(funcs.intersection(trig)) > 1: newf = None if f_num.is_Add and len(f_num.args) == 2: # check for sin(x)**p = cos(x)**p _args = f_num.args t = a, b = [i.atoms(Function).intersection( trig) for i in _args] if all(len(i) == 1 for i in t): a, b = [i.pop() for i in t] if isinstance(a, cos): a, b = b, a _args = _args[::-1] if isinstance(a, sin) and isinstance(b, cos ) and a.args[0] == b.args[0]: # sin(x) + cos(x) = 0 -> tan(x) + 1 = 0 newf, _d = (TR2i(_args[0]/_args[1]) + 1 ).as_numer_denom() if not _d.is_Number: newf = None if newf is None: newf = TR1(f_num).rewrite(tan) if newf != f_num: # don't check the rewritten form --check # solutions in the un-rewritten form below flags['check'] = False result = _solve(newf, symbol, **flags) flags['check'] = check # just a simple case - see if replacement of single function # clears all symbol-dependent functions, e.g. # log(x) - log(log(x) - 1) - 3 can be solved even though it has # two generators. if result is False and funcs: funcs = list(ordered(funcs)) # put shallowest function first f1 = funcs[0] t = Dummy('t') # perform the substitution ftry = f_num.subs(f1, t) # if no Functions left, we can proceed with usual solve if not ftry.has(symbol): cv_sols = _solve(ftry, t, **flags) cv_inv = list(ordered(_vsolve(t - f1, symbol, **flags)))[0] result = [{symbol: cv_inv.subs(sol)} for sol in cv_sols] if result is False: msg = 'multiple generators %s' % gens else: # e.g. case where gens are exp(x), exp(-x) u = bases.pop() t = Dummy('t') inv = _vsolve(u - t, symbol, **flags) if isinstance(u, (Pow, exp)): # this will be resolved by factor in _tsolve but we might # as well try a simple expansion here to get things in # order so something like the following will work now without # having to factor: # # >>> eq = (exp(I*(-x-2))+exp(I*(x+2))) # >>> eq.subs(exp(x),y) # fails # exp(I*(-x - 2)) + exp(I*(x + 2)) # >>> eq.expand().subs(exp(x),y) # works # y**I*exp(2*I) + y**(-I)*exp(-2*I) def _expand(p): b, e = p.as_base_exp() e = expand_mul(e) return expand_power_exp(b**e) ftry = f_num.replace( lambda w: w.is_Pow or isinstance(w, exp), _expand).subs(u, t) if not ftry.has(symbol): soln = _solve(ftry, t, **flags) result = [{symbol: i.subs(s)} for i in inv for s in soln] elif len(gens) == 1: # There is only one generator that we are interested in, but # there may have been more than one generator identified by # polys (e.g. for symbols other than the one we are interested # in) so recast the poly in terms of our generator of interest. # Also use composite=True with f_num since Poly won't update # poly as documented in issue 8810. poly = Poly(f_num, gens[0], composite=True) # if we aren't on the tsolve-pass, use roots if not flags.pop('tsolve', False): soln = None deg = poly.degree() flags['tsolve'] = True hints = ('cubics', 'quartics', 'quintics') solvers = {h: flags.get(h) for h in hints} soln = roots(poly, **solvers) if sum(soln.values()) < deg: # e.g. roots(32*x**5 + 400*x**4 + 2032*x**3 + # 5000*x**2 + 6250*x + 3189) -> {} # so all_roots is used and RootOf instances are # returned *unless* the system is multivariate # or high-order EX domain. try: soln = poly.all_roots() except NotImplementedError: if not flags.get('incomplete', True): raise NotImplementedError( filldedent(''' Neither high-order multivariate polynomials nor sorting of EX-domain polynomials is supported. If you want to see any results, pass keyword incomplete=True to solve; to see numerical values of roots for univariate expressions, use nroots. ''')) else: pass else: soln = list(soln.keys()) if soln is not None: u = poly.gen if u != symbol: try: t = Dummy('t') inv = _vsolve(u - t, symbol, **flags) soln = {i.subs(t, s) for i in inv for s in soln} except NotImplementedError: # perhaps _tsolve can handle f_num soln = None else: check = False # only dens need to be checked if soln is not None: if len(soln) > 2: # if the flag wasn't set then unset it since high-order # results are quite long. Perhaps one could base this # decision on a certain critical length of the # roots. In addition, wester test M2 has an expression # whose roots can be shown to be real with the # unsimplified form of the solution whereas only one of # the simplified forms appears to be real. flags['simplify'] = flags.get('simplify', False) if soln is not None: result = [{symbol: v} for v in soln] # fallback if above fails # ----------------------- if result is False: # try unrad if flags.pop('_unrad', True): try: u = unrad(f_num, symbol) except (ValueError, NotImplementedError): u = False if u: eq, cov = u if cov: isym, ieq = cov inv = _vsolve(ieq, symbol, **flags)[0] rv = {inv.subs(xi) for xi in _solve(eq, isym, **flags)} else: try: rv = set(_vsolve(eq, symbol, **flags)) except NotImplementedError: rv = None if rv is not None: result = [{symbol: v} for v in rv] # if the flag wasn't set then unset it since unrad results # can be quite long or of very high order flags['simplify'] = flags.get('simplify', False) else: pass # for coverage # try _tsolve if result is False: flags.pop('tsolve', None) # allow tsolve to be used on next pass try: soln = _tsolve(f_num, symbol, **flags) if soln is not None: result = [{symbol: v} for v in soln] except PolynomialError: pass # ----------- end of fallback ---------------------------- if result is False: raise NotImplementedError('\n'.join([msg, not_impl_msg % f])) if flags.get('simplify', True): result = [{k: d[k].simplify() for k in d} for d in result] # we just simplified the solution so we now set the flag to # False so the simplification doesn't happen again in checksol() flags['simplify'] = False if checkdens: # reject any result that makes any denom. affirmatively 0; # if in doubt, keep it dens = _simple_dens(f, symbols) result = [r for r in result if not any(checksol(d, r, **flags) for d in dens)] if check: # keep only results if the check is not False result = [r for r in result if checksol(f_num, r, **flags) is not False] return result def _solve_system(exprs, symbols, **flags): """return ``(linear, solution)`` where ``linear`` is True if the system was linear, else False; ``solution`` is a list of dictionaries giving solutions for the symbols """ if not exprs: return False, [] if flags.pop('_split', True): # Split the system into connected components V = exprs symsset = set(symbols) exprsyms = {e: e.free_symbols & symsset for e in exprs} E = [] sym_indices = {sym: i for i, sym in enumerate(symbols)} for n, e1 in enumerate(exprs): for e2 in exprs[:n]: # Equations are connected if they share a symbol if exprsyms[e1] & exprsyms[e2]: E.append((e1, e2)) G = V, E subexprs = connected_components(G) if len(subexprs) > 1: subsols = [] linear = True for subexpr in subexprs: subsyms = set() for e in subexpr: subsyms |= exprsyms[e] subsyms = list(sorted(subsyms, key = lambda x: sym_indices[x])) flags['_split'] = False # skip split step _linear, subsol = _solve_system(subexpr, subsyms, **flags) if linear: linear = linear and _linear if not isinstance(subsol, list): subsol = [subsol] subsols.append(subsol) # Full solution is cartesion product of subsystems sols = [] for soldicts in product(*subsols): sols.append(dict(item for sd in soldicts for item in sd.items())) return linear, sols polys = [] dens = set() failed = [] result = [] solved_syms = [] linear = True manual = flags.get('manual', False) checkdens = check = flags.get('check', True) for j, g in enumerate(exprs): dens.update(_simple_dens(g, symbols)) i, d = _invert(g, *symbols) if d in symbols: if linear: linear = solve_linear(g, 0, [d])[0] == d g = d - i g = g.as_numer_denom()[0] if manual: failed.append(g) continue poly = g.as_poly(*symbols, extension=True) if poly is not None: polys.append(poly) else: failed.append(g) if polys: if all(p.is_linear for p in polys): n, m = len(polys), len(symbols) matrix = zeros(n, m + 1) for i, poly in enumerate(polys): for monom, coeff in poly.terms(): try: j = monom.index(1) matrix[i, j] = coeff except ValueError: matrix[i, m] = -coeff # returns a dictionary ({symbols: values}) or None if flags.pop('particular', False): result = minsolve_linear_system(matrix, *symbols, **flags) else: result = solve_linear_system(matrix, *symbols, **flags) result = [result] if result else [] if failed: if result: solved_syms = list(result[0].keys()) # there is only one result dict else: solved_syms = [] # linear doesn't change else: linear = False if len(symbols) > len(polys): free = set().union(*[p.free_symbols for p in polys]) free = list(ordered(free.intersection(symbols))) got_s = set() result = [] for syms in subsets(free, len(polys)): try: # returns [], None or list of tuples res = solve_poly_system(polys, *syms) if res: for r in set(res): skip = False for r1 in r: if got_s and any(ss in r1.free_symbols for ss in got_s): # sol depends on previously # solved symbols: discard it skip = True if not skip: got_s.update(syms) result.append(dict(list(zip(syms, r)))) except NotImplementedError: pass if got_s: solved_syms = list(got_s) else: raise NotImplementedError('no valid subset found') else: try: result = solve_poly_system(polys, *symbols) if result: solved_syms = symbols result = [dict(list(zip(solved_syms, r))) for r in set(result)] except NotImplementedError: failed.extend([g.as_expr() for g in polys]) solved_syms = [] # convert None or [] to [{}] result = result or [{}] if failed: linear = False # For each failed equation, see if we can solve for one of the # remaining symbols from that equation. If so, we update the # solution set and continue with the next failed equation, # repeating until we are done or we get an equation that can't # be solved. def _ok_syms(e, sort=False): rv = e.free_symbols & legal # Solve first for symbols that have lower degree in the equation. # Ideally we want to solve firstly for symbols that appear linearly # with rational coefficients e.g. if e = x*y + z then we should # solve for z first. def key(sym): ep = e.as_poly(sym) if ep is None: complexity = (S.Infinity, S.Infinity, S.Infinity) else: coeff_syms = ep.LC().free_symbols complexity = (ep.degree(), len(coeff_syms & rv), len(coeff_syms)) return complexity + (default_sort_key(sym),) if sort: rv = sorted(rv, key=key) return rv legal = set(symbols) # what we are interested in # sort so equation with the fewest potential symbols is first u = Dummy() # used in solution checking for eq in ordered(failed, lambda _: len(_ok_syms(_))): newresult = [] bad_results = [] hit = False for r in result: got_s = set() # update eq with everything that is known so far eq2 = eq.subs(r) # if check is True then we see if it satisfies this # equation, otherwise we just accept it if check and r: b = checksol(u, u, eq2, minimal=True) if b is not None: # this solution is sufficient to know whether # it is valid or not so we either accept or # reject it, then continue if b: newresult.append(r) else: bad_results.append(r) continue # search for a symbol amongst those available that # can be solved for ok_syms = _ok_syms(eq2, sort=True) if not ok_syms: if r: newresult.append(r) break # skip as it's independent of desired symbols for s in ok_syms: try: soln = _vsolve(eq2, s, **flags) except NotImplementedError: continue # put each solution in r and append the now-expanded # result in the new result list; use copy since the # solution for s is being added in-place for sol in soln: if got_s and any(ss in sol.free_symbols for ss in got_s): # sol depends on previously solved symbols: discard it continue rnew = r.copy() for k, v in r.items(): rnew[k] = v.subs(s, sol) # and add this new solution rnew[s] = sol # check that it is independent of previous solutions iset = set(rnew.items()) for i in newresult: if len(i) < len(iset) and not set(i.items()) - iset: # this is a superset of a known solution that # is smaller break else: # keep it newresult.append(rnew) hit = True got_s.add(s) if not hit: raise NotImplementedError('could not solve %s' % eq2) else: result = newresult for b in bad_results: if b in result: result.remove(b) if not result: return False, [] # rely on linear/polynomial system solvers to simplify # XXX the following tests show that the expressions # returned are not the same as they would be if simplify # were applied to this: # sympy/solvers/ode/tests/test_systems/test__classify_linear_system # sympy/solvers/tests/test_solvers/test_issue_4886 # so the docs should be updated to reflect that or else # the following should be `bool(failed) or not linear` default_simplify = bool(failed) if flags.get('simplify', default_simplify): for r in result: for k in r: r[k] = simplify(r[k]) flags['simplify'] = False # don't need to do so in checksol now if checkdens: result = [r for r in result if not any(checksol(d, r, **flags) for d in dens)] if check and not linear: result = [r for r in result if not any(checksol(e, r, **flags) is False for e in exprs)] result = [r for r in result if r] return linear, result def solve_linear(lhs, rhs=0, symbols=[], exclude=[]): r""" Return a tuple derived from ``f = lhs - rhs`` that is one of the following: ``(0, 1)``, ``(0, 0)``, ``(symbol, solution)``, ``(n, d)``. Explanation =========== ``(0, 1)`` meaning that ``f`` is independent of the symbols in *symbols* that are not in *exclude*. ``(0, 0)`` meaning that there is no solution to the equation amongst the symbols given. If the first element of the tuple is not zero, then the function is guaranteed to be dependent on a symbol in *symbols*. ``(symbol, solution)`` where symbol appears linearly in the numerator of ``f``, is in *symbols* (if given), and is not in *exclude* (if given). No simplification is done to ``f`` other than a ``mul=True`` expansion, so the solution will correspond strictly to a unique solution. ``(n, d)`` where ``n`` and ``d`` are the numerator and denominator of ``f`` when the numerator was not linear in any symbol of interest; ``n`` will never be a symbol unless a solution for that symbol was found (in which case the second element is the solution, not the denominator). Examples ======== >>> from sympy import cancel, Pow ``f`` is independent of the symbols in *symbols* that are not in *exclude*: >>> from sympy import cos, sin, solve_linear >>> from sympy.abc import x, y, z >>> eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0 >>> solve_linear(eq) (0, 1) >>> eq = cos(x)**2 + sin(x)**2 # = 1 >>> solve_linear(eq) (0, 1) >>> solve_linear(x, exclude=[x]) (0, 1) The variable ``x`` appears as a linear variable in each of the following: >>> solve_linear(x + y**2) (x, -y**2) >>> solve_linear(1/x - y**2) (x, y**(-2)) When not linear in ``x`` or ``y`` then the numerator and denominator are returned: >>> solve_linear(x**2/y**2 - 3) (x**2 - 3*y**2, y**2) If the numerator of the expression is a symbol, then ``(0, 0)`` is returned if the solution for that symbol would have set any denominator to 0: >>> eq = 1/(1/x - 2) >>> eq.as_numer_denom() (x, 1 - 2*x) >>> solve_linear(eq) (0, 0) But automatic rewriting may cause a symbol in the denominator to appear in the numerator so a solution will be returned: >>> (1/x)**-1 x >>> solve_linear((1/x)**-1) (x, 0) Use an unevaluated expression to avoid this: >>> solve_linear(Pow(1/x, -1, evaluate=False)) (0, 0) If ``x`` is allowed to cancel in the following expression, then it appears to be linear in ``x``, but this sort of cancellation is not done by ``solve_linear`` so the solution will always satisfy the original expression without causing a division by zero error. >>> eq = x**2*(1/x - z**2/x) >>> solve_linear(cancel(eq)) (x, 0) >>> solve_linear(eq) (x**2*(1 - z**2), x) A list of symbols for which a solution is desired may be given: >>> solve_linear(x + y + z, symbols=[y]) (y, -x - z) A list of symbols to ignore may also be given: >>> solve_linear(x + y + z, exclude=[x]) (y, -x - z) (A solution for ``y`` is obtained because it is the first variable from the canonically sorted list of symbols that had a linear solution.) """ if isinstance(lhs, Eq): if rhs: raise ValueError(filldedent(''' If lhs is an Equality, rhs must be 0 but was %s''' % rhs)) rhs = lhs.rhs lhs = lhs.lhs dens = None eq = lhs - rhs n, d = eq.as_numer_denom() if not n: return S.Zero, S.One free = n.free_symbols if not symbols: symbols = free else: bad = [s for s in symbols if not s.is_Symbol] if bad: if len(bad) == 1: bad = bad[0] if len(symbols) == 1: eg = 'solve(%s, %s)' % (eq, symbols[0]) else: eg = 'solve(%s, *%s)' % (eq, list(symbols)) raise ValueError(filldedent(''' solve_linear only handles symbols, not %s. To isolate non-symbols use solve, e.g. >>> %s <<<. ''' % (bad, eg))) symbols = free.intersection(symbols) symbols = symbols.difference(exclude) if not symbols: return S.Zero, S.One # derivatives are easy to do but tricky to analyze to see if they # are going to disallow a linear solution, so for simplicity we # just evaluate the ones that have the symbols of interest derivs = defaultdict(list) for der in n.atoms(Derivative): csym = der.free_symbols & symbols for c in csym: derivs[c].append(der) all_zero = True for xi in sorted(symbols, key=default_sort_key): # canonical order # if there are derivatives in this var, calculate them now if isinstance(derivs[xi], list): derivs[xi] = {der: der.doit() for der in derivs[xi]} newn = n.subs(derivs[xi]) dnewn_dxi = newn.diff(xi) # dnewn_dxi can be nonzero if it survives differentation by any # of its free symbols free = dnewn_dxi.free_symbols if dnewn_dxi and (not free or any(dnewn_dxi.diff(s) for s in free) or free == symbols): all_zero = False if dnewn_dxi is S.NaN: break if xi not in dnewn_dxi.free_symbols: vi = -1/dnewn_dxi*(newn.subs(xi, 0)) if dens is None: dens = _simple_dens(eq, symbols) if not any(checksol(di, {xi: vi}, minimal=True) is True for di in dens): # simplify any trivial integral irep = [(i, i.doit()) for i in vi.atoms(Integral) if i.function.is_number] # do a slight bit of simplification vi = expand_mul(vi.subs(irep)) return xi, vi if all_zero: return S.Zero, S.One if n.is_Symbol: # no solution for this symbol was found return S.Zero, S.Zero return n, d def minsolve_linear_system(system, *symbols, **flags): r""" Find a particular solution to a linear system. Explanation =========== In particular, try to find a solution with the minimal possible number of non-zero variables using a naive algorithm with exponential complexity. If ``quick=True``, a heuristic is used. """ quick = flags.get('quick', False) # Check if there are any non-zero solutions at all s0 = solve_linear_system(system, *symbols, **flags) if not s0 or all(v == 0 for v in s0.values()): return s0 if quick: # We just solve the system and try to heuristically find a nice # solution. s = solve_linear_system(system, *symbols) def update(determined, solution): delete = [] for k, v in solution.items(): solution[k] = v.subs(determined) if not solution[k].free_symbols: delete.append(k) determined[k] = solution[k] for k in delete: del solution[k] determined = {} update(determined, s) while s: # NOTE sort by default_sort_key to get deterministic result k = max((k for k in s.values()), key=lambda x: (len(x.free_symbols), default_sort_key(x))) kfree = k.free_symbols x = next(reversed(list(ordered(kfree)))) if len(kfree) != 1: determined[x] = S.Zero else: val = _vsolve(k, x, check=False)[0] if not val and not any(v.subs(x, val) for v in s.values()): determined[x] = S.One else: determined[x] = val update(determined, s) return determined else: # We try to select n variables which we want to be non-zero. # All others will be assumed zero. We try to solve the modified system. # If there is a non-trivial solution, just set the free variables to # one. If we do this for increasing n, trying all combinations of # variables, we will find an optimal solution. # We speed up slightly by starting at one less than the number of # variables the quick method manages. N = len(symbols) bestsol = minsolve_linear_system(system, *symbols, quick=True) n0 = len([x for x in bestsol.values() if x != 0]) for n in range(n0 - 1, 1, -1): debug('minsolve: %s' % n) thissol = None for nonzeros in combinations(range(N), n): subm = Matrix([system.col(i).T for i in nonzeros] + [system.col(-1).T]).T s = solve_linear_system(subm, *[symbols[i] for i in nonzeros]) if s and not all(v == 0 for v in s.values()): subs = [(symbols[v], S.One) for v in nonzeros] for k, v in s.items(): s[k] = v.subs(subs) for sym in symbols: if sym not in s: if symbols.index(sym) in nonzeros: s[sym] = S.One else: s[sym] = S.Zero thissol = s break if thissol is None: break bestsol = thissol return bestsol def solve_linear_system(system, *symbols, **flags): r""" Solve system of $N$ linear equations with $M$ variables, which means both under- and overdetermined systems are supported. Explanation =========== The possible number of solutions is zero, one, or infinite. Respectively, this procedure will return None or a dictionary with solutions. In the case of underdetermined systems, all arbitrary parameters are skipped. This may cause a situation in which an empty dictionary is returned. In that case, all symbols can be assigned arbitrary values. Input to this function is a $N\times M + 1$ matrix, which means it has to be in augmented form. If you prefer to enter $N$ equations and $M$ unknowns then use ``solve(Neqs, *Msymbols)`` instead. Note: a local copy of the matrix is made by this routine so the matrix that is passed will not be modified. The algorithm used here is fraction-free Gaussian elimination, which results, after elimination, in an upper-triangular matrix. Then solutions are found using back-substitution. This approach is more efficient and compact than the Gauss-Jordan method. Examples ======== >>> from sympy import Matrix, solve_linear_system >>> from sympy.abc import x, y Solve the following system:: x + 4 y == 2 -2 x + y == 14 >>> system = Matrix(( (1, 4, 2), (-2, 1, 14))) >>> solve_linear_system(system, x, y) {x: -6, y: 2} A degenerate system returns an empty dictionary: >>> system = Matrix(( (0,0,0), (0,0,0) )) >>> solve_linear_system(system, x, y) {} """ assert system.shape[1] == len(symbols) + 1 # This is just a wrapper for solve_lin_sys eqs = list(system * Matrix(symbols + (-1,))) eqs, ring = sympy_eqs_to_ring(eqs, symbols) sol = solve_lin_sys(eqs, ring, _raw=False) if sol is not None: sol = {sym:val for sym, val in sol.items() if sym != val} return sol def solve_undetermined_coeffs(equ, coeffs, *syms, **flags): r""" Solve a system of equations in $k$ parameters that is formed by matching coefficients in variables ``coeffs`` that are on factors dependent on the remaining variables (or those given explicitly by ``syms``. Explanation =========== The result of this function is a dictionary with symbolic values of those parameters with respect to coefficients in $q$ -- empty if there is no solution or coefficients do not appear in the equation -- else None (if the system was not recognized). If there is more than one solution, the solutions are passed as a list. The output can be modified using the same semantics as for `solve` since the flags that are passed are sent directly to `solve` so, for example the flag ``dict=True`` will always return a list of solutions as dictionaries. This function accepts both Equality and Expr class instances. The solving process is most efficient when symbols are specified in addition to parameters to be determined, but an attempt to determine them (if absent) will be made. If an expected solution is not obtained (and symbols were not specified) try specifying them. Examples ======== >>> from sympy import Eq, solve_undetermined_coeffs >>> from sympy.abc import a, b, c, h, p, k, x, y >>> solve_undetermined_coeffs(Eq(a*x + a + b, x/2), [a, b], x) {a: 1/2, b: -1/2} >>> solve_undetermined_coeffs(a - 2, [a]) {a: 2} The equation can be nonlinear in the symbols: >>> X, Y, Z = y, x**y, y*x**y >>> eq = a*X + b*Y + c*Z - X - 2*Y - 3*Z >>> coeffs = a, b, c >>> syms = x, y >>> solve_undetermined_coeffs(eq, coeffs, syms) {a: 1, b: 2, c: 3} And the system can be nonlinear in coefficients, too, but if there is only a single solution, it will be returned as a dictionary: >>> eq = a*x**2 + b*x + c - ((x - h)**2 + 4*p*k)/4/p >>> solve_undetermined_coeffs(eq, (h, p, k), x) {h: -b/(2*a), k: (4*a*c - b**2)/(4*a), p: 1/(4*a)} Multiple solutions are always returned in a list: >>> solve_undetermined_coeffs(a**2*x + b - x, [a, b], x) [{a: -1, b: 0}, {a: 1, b: 0}] Using flag ``dict=True`` (in keeping with semantics in :func:`~.solve`) will force the result to always be a list with any solutions as elements in that list. >>> solve_undetermined_coeffs(a*x - 2*x, [a], dict=True) [{a: 2}] """ if not (coeffs and all(i.is_Symbol for i in coeffs)): raise ValueError('must provide symbols for coeffs') if isinstance(equ, Eq): eq = equ.lhs - equ.rhs else: eq = equ ceq = cancel(eq) xeq = _mexpand(ceq.as_numer_denom()[0], recursive=True) free = xeq.free_symbols coeffs = free & set(coeffs) if not coeffs: return ([], {}) if flags.get('set', None) else [] # solve(0, x) -> [] if not syms: # e.g. A*exp(x) + B - (exp(x) + y) separated into parts that # don't/do depend on coeffs gives # -(exp(x) + y), A*exp(x) + B # then see what symbols are common to both # {x} = {x, A, B} - {x, y} ind, dep = xeq.as_independent(*coeffs, as_Add=True) dfree = dep.free_symbols syms = dfree & ind.free_symbols if not syms: # but if the system looks like (a + b)*x + b - c # then {} = {a, b, x} - c # so calculate {x} = {a, b, x} - {a, b} syms = dfree - set(coeffs) if not syms: syms = [Dummy()] else: if len(syms) == 1 and iterable(syms[0]): syms = syms[0] e, s, _ = recast_to_symbols([xeq], syms) xeq = e[0] syms = s # find the functional forms in which symbols appear gens = set(xeq.as_coefficients_dict(*syms).keys()) - {1} cset = set(coeffs) if any(g.has_xfree(cset) for g in gens): return # a generator contained a coefficient symbol # make sure we are working with symbols for generators e, gens, _ = recast_to_symbols([xeq], list(gens)) xeq = e[0] # collect coefficients in front of generators system = list(collect(xeq, gens, evaluate=False).values()) # get a solution soln = solve(system, coeffs, **flags) # unpack unless told otherwise if length is 1 settings = flags.get('dict', None) or flags.get('set', None) if type(soln) is dict or settings or len(soln) != 1: return soln return soln[0] def solve_linear_system_LU(matrix, syms): """ Solves the augmented matrix system using ``LUsolve`` and returns a dictionary in which solutions are keyed to the symbols of *syms* as ordered. Explanation =========== The matrix must be invertible. Examples ======== >>> from sympy import Matrix, solve_linear_system_LU >>> from sympy.abc import x, y, z >>> solve_linear_system_LU(Matrix([ ... [1, 2, 0, 1], ... [3, 2, 2, 1], ... [2, 0, 0, 1]]), [x, y, z]) {x: 1/2, y: 1/4, z: -1/2} See Also ======== LUsolve """ if matrix.rows != matrix.cols - 1: raise ValueError("Rows should be equal to columns - 1") A = matrix[:matrix.rows, :matrix.rows] b = matrix[:, matrix.cols - 1:] soln = A.LUsolve(b) solutions = {} for i in range(soln.rows): solutions[syms[i]] = soln[i, 0] return solutions def det_perm(M): """ Return the determinant of *M* by using permutations to select factors. Explanation =========== For sizes larger than 8 the number of permutations becomes prohibitively large, or if there are no symbols in the matrix, it is better to use the standard determinant routines (e.g., ``M.det()``.) See Also ======== det_minor det_quick """ args = [] s = True n = M.rows list_ = M.flat() for perm in generate_bell(n): fac = [] idx = 0 for j in perm: fac.append(list_[idx + j]) idx += n term = Mul(*fac) # disaster with unevaluated Mul -- takes forever for n=7 args.append(term if s else -term) s = not s return Add(*args) def det_minor(M): """ Return the ``det(M)`` computed from minors without introducing new nesting in products. See Also ======== det_perm det_quick """ n = M.rows if n == 2: return M[0, 0]*M[1, 1] - M[1, 0]*M[0, 1] else: return sum([(1, -1)[i % 2]*Add(*[M[0, i]*d for d in Add.make_args(det_minor(M.minor_submatrix(0, i)))]) if M[0, i] else S.Zero for i in range(n)]) def det_quick(M, method=None): """ Return ``det(M)`` assuming that either there are lots of zeros or the size of the matrix is small. If this assumption is not met, then the normal Matrix.det function will be used with method = ``method``. See Also ======== det_minor det_perm """ if any(i.has(Symbol) for i in M): if M.rows < 8 and all(i.has(Symbol) for i in M): return det_perm(M) return det_minor(M) else: return M.det(method=method) if method else M.det() def inv_quick(M): """Return the inverse of ``M``, assuming that either there are lots of zeros or the size of the matrix is small. """ if not all(i.is_Number for i in M): if not any(i.is_Number for i in M): det = lambda _: det_perm(_) else: det = lambda _: det_minor(_) else: return M.inv() n = M.rows d = det(M) if d == S.Zero: raise NonInvertibleMatrixError("Matrix det == 0; not invertible") ret = zeros(n) s1 = -1 for i in range(n): s = s1 = -s1 for j in range(n): di = det(M.minor_submatrix(i, j)) ret[j, i] = s*di/d s = -s return ret # these are functions that have multiple inverse values per period multi_inverses = { sin: lambda x: (asin(x), S.Pi - asin(x)), cos: lambda x: (acos(x), 2*S.Pi - acos(x)), } def _vsolve(e, s, **flags): """return list of scalar values for the solution of e for symbol s""" return [i[s] for i in _solve(e, s, **flags)] def _tsolve(eq, sym, **flags): """ Helper for ``_solve`` that solves a transcendental equation with respect to the given symbol. Various equations containing powers and logarithms, can be solved. There is currently no guarantee that all solutions will be returned or that a real solution will be favored over a complex one. Either a list of potential solutions will be returned or None will be returned (in the case that no method was known to get a solution for the equation). All other errors (like the inability to cast an expression as a Poly) are unhandled. Examples ======== >>> from sympy import log, ordered >>> from sympy.solvers.solvers import _tsolve as tsolve >>> from sympy.abc import x >>> list(ordered(tsolve(3**(2*x + 5) - 4, x))) [-5/2 + log(2)/log(3), (-5*log(3)/2 + log(2) + I*pi)/log(3)] >>> tsolve(log(x) + 2*x, x) [LambertW(2)/2] """ if 'tsolve_saw' not in flags: flags['tsolve_saw'] = [] if eq in flags['tsolve_saw']: return None else: flags['tsolve_saw'].append(eq) rhs, lhs = _invert(eq, sym) if lhs == sym: return [rhs] try: if lhs.is_Add: # it's time to try factoring; powdenest is used # to try get powers in standard form for better factoring f = factor(powdenest(lhs - rhs)) if f.is_Mul: return _vsolve(f, sym, **flags) if rhs: f = logcombine(lhs, force=flags.get('force', True)) if f.count(log) != lhs.count(log): if isinstance(f, log): return _vsolve(f.args[0] - exp(rhs), sym, **flags) return _tsolve(f - rhs, sym, **flags) elif lhs.is_Pow: if lhs.exp.is_Integer: if lhs - rhs != eq: return _vsolve(lhs - rhs, sym, **flags) if sym not in lhs.exp.free_symbols: return _vsolve(lhs.base - rhs**(1/lhs.exp), sym, **flags) # _tsolve calls this with Dummy before passing the actual number in. if any(t.is_Dummy for t in rhs.free_symbols): raise NotImplementedError # _tsolve will call here again... # a ** g(x) == 0 if not rhs: # f(x)**g(x) only has solutions where f(x) == 0 and g(x) != 0 at # the same place sol_base = _vsolve(lhs.base, sym, **flags) return [s for s in sol_base if lhs.exp.subs(sym, s) != 0] # XXX use checksol here? # a ** g(x) == b if not lhs.base.has(sym): if lhs.base == 0: return _vsolve(lhs.exp, sym, **flags) if rhs != 0 else [] # Gets most solutions... if lhs.base == rhs.as_base_exp()[0]: # handles case when bases are equal sol = _vsolve(lhs.exp - rhs.as_base_exp()[1], sym, **flags) else: # handles cases when bases are not equal and exp # may or may not be equal f = exp(log(lhs.base)*lhs.exp) - exp(log(rhs)) sol = _vsolve(f, sym, **flags) # Check for duplicate solutions def equal(expr1, expr2): _ = Dummy() eq = checksol(expr1 - _, _, expr2) if eq is None: if nsimplify(expr1) != nsimplify(expr2): return False # they might be coincidentally the same # so check more rigorously eq = expr1.equals(expr2) # XXX expensive but necessary? return eq # Guess a rational exponent e_rat = nsimplify(log(abs(rhs))/log(abs(lhs.base))) e_rat = simplify(posify(e_rat)[0]) n, d = fraction(e_rat) if expand(lhs.base**n - rhs**d) == 0: sol = [s for s in sol if not equal(lhs.exp.subs(sym, s), e_rat)] sol.extend(_vsolve(lhs.exp - e_rat, sym, **flags)) return list(set(sol)) # f(x) ** g(x) == c else: sol = [] logform = lhs.exp*log(lhs.base) - log(rhs) if logform != lhs - rhs: try: sol.extend(_vsolve(logform, sym, **flags)) except NotImplementedError: pass # Collect possible solutions and check with substitution later. check = [] if rhs == 1: # f(x) ** g(x) = 1 -- g(x)=0 or f(x)=+-1 check.extend(_vsolve(lhs.exp, sym, **flags)) check.extend(_vsolve(lhs.base - 1, sym, **flags)) check.extend(_vsolve(lhs.base + 1, sym, **flags)) elif rhs.is_Rational: for d in (i for i in divisors(abs(rhs.p)) if i != 1): e, t = integer_log(rhs.p, d) if not t: continue # rhs.p != d**b for s in divisors(abs(rhs.q)): if s**e== rhs.q: r = Rational(d, s) check.extend(_vsolve(lhs.base - r, sym, **flags)) check.extend(_vsolve(lhs.base + r, sym, **flags)) check.extend(_vsolve(lhs.exp - e, sym, **flags)) elif rhs.is_irrational: b_l, e_l = lhs.base.as_base_exp() n, d = (e_l*lhs.exp).as_numer_denom() b, e = sqrtdenest(rhs).as_base_exp() check = [sqrtdenest(i) for i in (_vsolve(lhs.base - b, sym, **flags))] check.extend([sqrtdenest(i) for i in (_vsolve(lhs.exp - e, sym, **flags))]) if e_l*d != 1: check.extend(_vsolve(b_l**n - rhs**(e_l*d), sym, **flags)) for s in check: ok = checksol(eq, sym, s) if ok is None: ok = eq.subs(sym, s).equals(0) if ok: sol.append(s) return list(set(sol)) elif lhs.is_Function and len(lhs.args) == 1: if lhs.func in multi_inverses: # sin(x) = 1/3 -> x - asin(1/3) & x - (pi - asin(1/3)) soln = [] for i in multi_inverses[type(lhs)](rhs): soln.extend(_vsolve(lhs.args[0] - i, sym, **flags)) return list(set(soln)) elif lhs.func == LambertW: return _vsolve(lhs.args[0] - rhs*exp(rhs), sym, **flags) rewrite = lhs.rewrite(exp) if rewrite != lhs: return _vsolve(rewrite - rhs, sym, **flags) except NotImplementedError: pass # maybe it is a lambert pattern if flags.pop('bivariate', True): # lambert forms may need some help being recognized, e.g. changing # 2**(3*x) + x**3*log(2)**3 + 3*x**2*log(2)**2 + 3*x*log(2) + 1 # to 2**(3*x) + (x*log(2) + 1)**3 # make generator in log have exponent of 1 logs = eq.atoms(log) spow = min( {i.exp for j in logs for i in j.atoms(Pow) if i.base == sym} or {1}) if spow != 1: p = sym**spow u = Dummy('bivariate-cov') ueq = eq.subs(p, u) if not ueq.has_free(sym): sol = _vsolve(ueq, u, **flags) inv = _vsolve(p - u, sym) return [i.subs(u, s) for i in inv for s in sol] g = _filtered_gens(eq.as_poly(), sym) up_or_log = set() for gi in g: if isinstance(gi, (exp, log)) or (gi.is_Pow and gi.base == S.Exp1): up_or_log.add(gi) elif gi.is_Pow: gisimp = powdenest(expand_power_exp(gi)) if gisimp.is_Pow and sym in gisimp.exp.free_symbols: up_or_log.add(gi) eq_down = expand_log(expand_power_exp(eq)).subs( dict(list(zip(up_or_log, [0]*len(up_or_log))))) eq = expand_power_exp(factor(eq_down, deep=True) + (eq - eq_down)) rhs, lhs = _invert(eq, sym) if lhs.has(sym): try: poly = lhs.as_poly() g = _filtered_gens(poly, sym) _eq = lhs - rhs sols = _solve_lambert(_eq, sym, g) # use a simplified form if it satisfies eq # and has fewer operations for n, s in enumerate(sols): ns = nsimplify(s) if ns != s and ns.count_ops() <= s.count_ops(): ok = checksol(_eq, sym, ns) if ok is None: ok = _eq.subs(sym, ns).equals(0) if ok: sols[n] = ns return sols except NotImplementedError: # maybe it's a convoluted function if len(g) == 2: try: gpu = bivariate_type(lhs - rhs, *g) if gpu is None: raise NotImplementedError g, p, u = gpu flags['bivariate'] = False inversion = _tsolve(g - u, sym, **flags) if inversion: sol = _vsolve(p, u, **flags) return list({i.subs(u, s) for i in inversion for s in sol}) except NotImplementedError: pass else: pass if flags.pop('force', True): flags['force'] = False pos, reps = posify(lhs - rhs) if rhs == S.ComplexInfinity: return [] for u, s in reps.items(): if s == sym: break else: u = sym if pos.has(u): try: soln = _vsolve(pos, u, **flags) return [s.subs(reps) for s in soln] except NotImplementedError: pass else: pass # here for coverage return # here for coverage # TODO: option for calculating J numerically @conserve_mpmath_dps def nsolve(*args, dict=False, **kwargs): r""" Solve a nonlinear equation system numerically: ``nsolve(f, [args,] x0, modules=['mpmath'], **kwargs)``. Explanation =========== ``f`` is a vector function of symbolic expressions representing the system. *args* are the variables. If there is only one variable, this argument can be omitted. ``x0`` is a starting vector close to a solution. Use the modules keyword to specify which modules should be used to evaluate the function and the Jacobian matrix. Make sure to use a module that supports matrices. For more information on the syntax, please see the docstring of ``lambdify``. If the keyword arguments contain ``dict=True`` (default is False) ``nsolve`` will return a list (perhaps empty) of solution mappings. This might be especially useful if you want to use ``nsolve`` as a fallback to solve since using the dict argument for both methods produces return values of consistent type structure. Please note: to keep this consistent with ``solve``, the solution will be returned in a list even though ``nsolve`` (currently at least) only finds one solution at a time. Overdetermined systems are supported. Examples ======== >>> from sympy import Symbol, nsolve >>> import mpmath >>> mpmath.mp.dps = 15 >>> x1 = Symbol('x1') >>> x2 = Symbol('x2') >>> f1 = 3 * x1**2 - 2 * x2**2 - 1 >>> f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8 >>> print(nsolve((f1, f2), (x1, x2), (-1, 1))) Matrix([[-1.19287309935246], [1.27844411169911]]) For one-dimensional functions the syntax is simplified: >>> from sympy import sin, nsolve >>> from sympy.abc import x >>> nsolve(sin(x), x, 2) 3.14159265358979 >>> nsolve(sin(x), 2) 3.14159265358979 To solve with higher precision than the default, use the prec argument: >>> from sympy import cos >>> nsolve(cos(x) - x, 1) 0.739085133215161 >>> nsolve(cos(x) - x, 1, prec=50) 0.73908513321516064165531208767387340401341175890076 >>> cos(_) 0.73908513321516064165531208767387340401341175890076 To solve for complex roots of real functions, a nonreal initial point must be specified: >>> from sympy import I >>> nsolve(x**2 + 2, I) 1.4142135623731*I ``mpmath.findroot`` is used and you can find their more extensive documentation, especially concerning keyword parameters and available solvers. Note, however, that functions which are very steep near the root, the verification of the solution may fail. In this case you should use the flag ``verify=False`` and independently verify the solution. >>> from sympy import cos, cosh >>> f = cos(x)*cosh(x) - 1 >>> nsolve(f, 3.14*100) Traceback (most recent call last): ... ValueError: Could not find root within given tolerance. (1.39267e+230 > 2.1684e-19) >>> ans = nsolve(f, 3.14*100, verify=False); ans 312.588469032184 >>> f.subs(x, ans).n(2) 2.1e+121 >>> (f/f.diff(x)).subs(x, ans).n(2) 7.4e-15 One might safely skip the verification if bounds of the root are known and a bisection method is used: >>> bounds = lambda i: (3.14*i, 3.14*(i + 1)) >>> nsolve(f, bounds(100), solver='bisect', verify=False) 315.730061685774 Alternatively, a function may be better behaved when the denominator is ignored. Since this is not always the case, however, the decision of what function to use is left to the discretion of the user. >>> eq = x**2/(1 - x)/(1 - 2*x)**2 - 100 >>> nsolve(eq, 0.46) Traceback (most recent call last): ... ValueError: Could not find root within given tolerance. (10000 > 2.1684e-19) Try another starting point or tweak arguments. >>> nsolve(eq.as_numer_denom()[0], 0.46) 0.46792545969349058 """ # there are several other SymPy functions that use method= so # guard against that here if 'method' in kwargs: raise ValueError(filldedent(''' Keyword "method" should not be used in this context. When using some mpmath solvers directly, the keyword "method" is used, but when using nsolve (and findroot) the keyword to use is "solver".''')) if 'prec' in kwargs: import mpmath mpmath.mp.dps = kwargs.pop('prec') # keyword argument to return result as a dictionary as_dict = dict from builtins import dict # to unhide the builtin # interpret arguments if len(args) == 3: f = args[0] fargs = args[1] x0 = args[2] if iterable(fargs) and iterable(x0): if len(x0) != len(fargs): raise TypeError('nsolve expected exactly %i guess vectors, got %i' % (len(fargs), len(x0))) elif len(args) == 2: f = args[0] fargs = None x0 = args[1] if iterable(f): raise TypeError('nsolve expected 3 arguments, got 2') elif len(args) < 2: raise TypeError('nsolve expected at least 2 arguments, got %i' % len(args)) else: raise TypeError('nsolve expected at most 3 arguments, got %i' % len(args)) modules = kwargs.get('modules', ['mpmath']) if iterable(f): f = list(f) for i, fi in enumerate(f): if isinstance(fi, Eq): f[i] = fi.lhs - fi.rhs f = Matrix(f).T if iterable(x0): x0 = list(x0) if not isinstance(f, Matrix): # assume it's a SymPy expression if isinstance(f, Eq): f = f.lhs - f.rhs syms = f.free_symbols if fargs is None: fargs = syms.copy().pop() if not (len(syms) == 1 and (fargs in syms or fargs[0] in syms)): raise ValueError(filldedent(''' expected a one-dimensional and numerical function''')) # the function is much better behaved if there is no denominator # but sending the numerator is left to the user since sometimes # the function is better behaved when the denominator is present # e.g., issue 11768 f = lambdify(fargs, f, modules) x = sympify(findroot(f, x0, **kwargs)) if as_dict: return [{fargs: x}] return x if len(fargs) > f.cols: raise NotImplementedError(filldedent(''' need at least as many equations as variables''')) verbose = kwargs.get('verbose', False) if verbose: print('f(x):') print(f) # derive Jacobian J = f.jacobian(fargs) if verbose: print('J(x):') print(J) # create functions f = lambdify(fargs, f.T, modules) J = lambdify(fargs, J, modules) # solve the system numerically x = findroot(f, x0, J=J, **kwargs) if as_dict: return [dict(zip(fargs, [sympify(xi) for xi in x]))] return Matrix(x) def _invert(eq, *symbols, **kwargs): """ Return tuple (i, d) where ``i`` is independent of *symbols* and ``d`` contains symbols. Explanation =========== ``i`` and ``d`` are obtained after recursively using algebraic inversion until an uninvertible ``d`` remains. If there are no free symbols then ``d`` will be zero. Some (but not necessarily all) solutions to the expression ``i - d`` will be related to the solutions of the original expression. Examples ======== >>> from sympy.solvers.solvers import _invert as invert >>> from sympy import sqrt, cos >>> from sympy.abc import x, y >>> invert(x - 3) (3, x) >>> invert(3) (3, 0) >>> invert(2*cos(x) - 1) (1/2, cos(x)) >>> invert(sqrt(x) - 3) (3, sqrt(x)) >>> invert(sqrt(x) + y, x) (-y, sqrt(x)) >>> invert(sqrt(x) + y, y) (-sqrt(x), y) >>> invert(sqrt(x) + y, x, y) (0, sqrt(x) + y) If there is more than one symbol in a power's base and the exponent is not an Integer, then the principal root will be used for the inversion: >>> invert(sqrt(x + y) - 2) (4, x + y) >>> invert(sqrt(x + y) - 2) (4, x + y) If the exponent is an Integer, setting ``integer_power`` to True will force the principal root to be selected: >>> invert(x**2 - 4, integer_power=True) (2, x) """ eq = sympify(eq) if eq.args: # make sure we are working with flat eq eq = eq.func(*eq.args) free = eq.free_symbols if not symbols: symbols = free if not free & set(symbols): return eq, S.Zero dointpow = bool(kwargs.get('integer_power', False)) lhs = eq rhs = S.Zero while True: was = lhs while True: indep, dep = lhs.as_independent(*symbols) # dep + indep == rhs if lhs.is_Add: # this indicates we have done it all if indep.is_zero: break lhs = dep rhs -= indep # dep * indep == rhs else: # this indicates we have done it all if indep is S.One: break lhs = dep rhs /= indep # collect like-terms in symbols if lhs.is_Add: terms = {} for a in lhs.args: i, d = a.as_independent(*symbols) terms.setdefault(d, []).append(i) if any(len(v) > 1 for v in terms.values()): args = [] for d, i in terms.items(): if len(i) > 1: args.append(Add(*i)*d) else: args.append(i[0]*d) lhs = Add(*args) # if it's a two-term Add with rhs = 0 and two powers we can get the # dependent terms together, e.g. 3*f(x) + 2*g(x) -> f(x)/g(x) = -2/3 if lhs.is_Add and not rhs and len(lhs.args) == 2 and \ not lhs.is_polynomial(*symbols): a, b = ordered(lhs.args) ai, ad = a.as_independent(*symbols) bi, bd = b.as_independent(*symbols) if any(_ispow(i) for i in (ad, bd)): a_base, a_exp = ad.as_base_exp() b_base, b_exp = bd.as_base_exp() if a_base == b_base: # a = -b lhs = powsimp(powdenest(ad/bd)) rhs = -bi/ai else: rat = ad/bd _lhs = powsimp(ad/bd) if _lhs != rat: lhs = _lhs rhs = -bi/ai elif ai == -bi: if isinstance(ad, Function) and ad.func == bd.func: if len(ad.args) == len(bd.args) == 1: lhs = ad.args[0] - bd.args[0] elif len(ad.args) == len(bd.args): # should be able to solve # f(x, y) - f(2 - x, 0) == 0 -> x == 1 raise NotImplementedError( 'equal function with more than 1 argument') else: raise ValueError( 'function with different numbers of args') elif lhs.is_Mul and any(_ispow(a) for a in lhs.args): lhs = powsimp(powdenest(lhs)) if lhs.is_Function: if hasattr(lhs, 'inverse') and lhs.inverse() is not None and len(lhs.args) == 1: # -1 # f(x) = g -> x = f (g) # # /!\ inverse should not be defined if there are multiple values # for the function -- these are handled in _tsolve # rhs = lhs.inverse()(rhs) lhs = lhs.args[0] elif isinstance(lhs, atan2): y, x = lhs.args lhs = 2*atan(y/(sqrt(x**2 + y**2) + x)) elif lhs.func == rhs.func: if len(lhs.args) == len(rhs.args) == 1: lhs = lhs.args[0] rhs = rhs.args[0] elif len(lhs.args) == len(rhs.args): # should be able to solve # f(x, y) == f(2, 3) -> x == 2 # f(x, x + y) == f(2, 3) -> x == 2 raise NotImplementedError( 'equal function with more than 1 argument') else: raise ValueError( 'function with different numbers of args') if rhs and lhs.is_Pow and lhs.exp.is_Integer and lhs.exp < 0: lhs = 1/lhs rhs = 1/rhs # base**a = b -> base = b**(1/a) if # a is an Integer and dointpow=True (this gives real branch of root) # a is not an Integer and the equation is multivariate and the # base has more than 1 symbol in it # The rationale for this is that right now the multi-system solvers # doesn't try to resolve generators to see, for example, if the whole # system is written in terms of sqrt(x + y) so it will just fail, so we # do that step here. if lhs.is_Pow and ( lhs.exp.is_Integer and dointpow or not lhs.exp.is_Integer and len(symbols) > 1 and len(lhs.base.free_symbols & set(symbols)) > 1): rhs = rhs**(1/lhs.exp) lhs = lhs.base if lhs == was: break return rhs, lhs def unrad(eq, *syms, **flags): """ Remove radicals with symbolic arguments and return (eq, cov), None, or raise an error. Explanation =========== None is returned if there are no radicals to remove. NotImplementedError is raised if there are radicals and they cannot be removed or if the relationship between the original symbols and the change of variable needed to rewrite the system as a polynomial cannot be solved. Otherwise the tuple, ``(eq, cov)``, is returned where: *eq*, ``cov`` *eq* is an equation without radicals (in the symbol(s) of interest) whose solutions are a superset of the solutions to the original expression. *eq* might be rewritten in terms of a new variable; the relationship to the original variables is given by ``cov`` which is a list containing ``v`` and ``v**p - b`` where ``p`` is the power needed to clear the radical and ``b`` is the radical now expressed as a polynomial in the symbols of interest. For example, for sqrt(2 - x) the tuple would be ``(c, c**2 - 2 + x)``. The solutions of *eq* will contain solutions to the original equation (if there are any). *syms* An iterable of symbols which, if provided, will limit the focus of radical removal: only radicals with one or more of the symbols of interest will be cleared. All free symbols are used if *syms* is not set. *flags* are used internally for communication during recursive calls. Two options are also recognized: ``take``, when defined, is interpreted as a single-argument function that returns True if a given Pow should be handled. Radicals can be removed from an expression if: * All bases of the radicals are the same; a change of variables is done in this case. * If all radicals appear in one term of the expression. * There are only four terms with sqrt() factors or there are less than four terms having sqrt() factors. * There are only two terms with radicals. Examples ======== >>> from sympy.solvers.solvers import unrad >>> from sympy.abc import x >>> from sympy import sqrt, Rational, root >>> unrad(sqrt(x)*x**Rational(1, 3) + 2) (x**5 - 64, []) >>> unrad(sqrt(x) + root(x + 1, 3)) (-x**3 + x**2 + 2*x + 1, []) >>> eq = sqrt(x) + root(x, 3) - 2 >>> unrad(eq) (_p**3 + _p**2 - 2, [_p, _p**6 - x]) """ uflags = dict(check=False, simplify=False) def _cov(p, e): if cov: # XXX - uncovered oldp, olde = cov if Poly(e, p).degree(p) in (1, 2): cov[:] = [p, olde.subs(oldp, _vsolve(e, p, **uflags)[0])] else: raise NotImplementedError else: cov[:] = [p, e] def _canonical(eq, cov): if cov: # change symbol to vanilla so no solutions are eliminated p, e = cov rep = {p: Dummy(p.name)} eq = eq.xreplace(rep) cov = [p.xreplace(rep), e.xreplace(rep)] # remove constants and powers of factors since these don't change # the location of the root; XXX should factor or factor_terms be used? eq = factor_terms(_mexpand(eq.as_numer_denom()[0], recursive=True), clear=True) if eq.is_Mul: args = [] for f in eq.args: if f.is_number: continue if f.is_Pow: args.append(f.base) else: args.append(f) eq = Mul(*args) # leave as Mul for more efficient solving # make the sign canonical margs = list(Mul.make_args(eq)) changed = False for i, m in enumerate(margs): if m.could_extract_minus_sign(): margs[i] = -m changed = True if changed: eq = Mul(*margs, evaluate=False) return eq, cov def _Q(pow): # return leading Rational of denominator of Pow's exponent c = pow.as_base_exp()[1].as_coeff_Mul()[0] if not c.is_Rational: return S.One return c.q # define the _take method that will determine whether a term is of interest def _take(d): # return True if coefficient of any factor's exponent's den is not 1 for pow in Mul.make_args(d): if not pow.is_Pow: continue if _Q(pow) == 1: continue if pow.free_symbols & syms: return True return False _take = flags.setdefault('_take', _take) if isinstance(eq, Eq): eq = eq.lhs - eq.rhs # XXX legacy Eq as Eqn support elif not isinstance(eq, Expr): return cov, nwas, rpt = [flags.setdefault(k, v) for k, v in sorted(dict(cov=[], n=None, rpt=0).items())] # preconditioning eq = powdenest(factor_terms(eq, radical=True, clear=True)) eq = eq.as_numer_denom()[0] eq = _mexpand(eq, recursive=True) if eq.is_number: return # see if there are radicals in symbols of interest syms = set(syms) or eq.free_symbols # _take uses this poly = eq.as_poly() gens = [g for g in poly.gens if _take(g)] if not gens: return # recast poly in terms of eigen-gens poly = eq.as_poly(*gens) # not a polynomial e.g. 1 + sqrt(x)*exp(sqrt(x)) with gen sqrt(x) if poly is None: return # - an exponent has a symbol of interest (don't handle) if any(g.exp.has(*syms) for g in gens): return def _rads_bases_lcm(poly): # if all the bases are the same or all the radicals are in one # term, `lcm` will be the lcm of the denominators of the # exponents of the radicals lcm = 1 rads = set() bases = set() for g in poly.gens: q = _Q(g) if q != 1: rads.add(g) lcm = ilcm(lcm, q) bases.add(g.base) return rads, bases, lcm rads, bases, lcm = _rads_bases_lcm(poly) covsym = Dummy('p', nonnegative=True) # only keep in syms symbols that actually appear in radicals; # and update gens newsyms = set() for r in rads: newsyms.update(syms & r.free_symbols) if newsyms != syms: syms = newsyms # get terms together that have common generators drad = dict(zip(rads, range(len(rads)))) rterms = {(): []} args = Add.make_args(poly.as_expr()) for t in args: if _take(t): common = set(t.as_poly().gens).intersection(rads) key = tuple(sorted([drad[i] for i in common])) else: key = () rterms.setdefault(key, []).append(t) others = Add(*rterms.pop(())) rterms = [Add(*rterms[k]) for k in rterms.keys()] # the output will depend on the order terms are processed, so # make it canonical quickly rterms = list(reversed(list(ordered(rterms)))) ok = False # we don't have a solution yet depth = sqrt_depth(eq) if len(rterms) == 1 and not (rterms[0].is_Add and lcm > 2): eq = rterms[0]**lcm - ((-others)**lcm) ok = True else: if len(rterms) == 1 and rterms[0].is_Add: rterms = list(rterms[0].args) if len(bases) == 1: b = bases.pop() if len(syms) > 1: x = b.free_symbols else: x = syms x = list(ordered(x))[0] try: inv = _vsolve(covsym**lcm - b, x, **uflags) if not inv: raise NotImplementedError eq = poly.as_expr().subs(b, covsym**lcm).subs(x, inv[0]) _cov(covsym, covsym**lcm - b) return _canonical(eq, cov) except NotImplementedError: pass if len(rterms) == 2: if not others: eq = rterms[0]**lcm - (-rterms[1])**lcm ok = True elif not log(lcm, 2).is_Integer: # the lcm-is-power-of-two case is handled below r0, r1 = rterms if flags.get('_reverse', False): r1, r0 = r0, r1 i0 = _rads0, _bases0, lcm0 = _rads_bases_lcm(r0.as_poly()) i1 = _rads1, _bases1, lcm1 = _rads_bases_lcm(r1.as_poly()) for reverse in range(2): if reverse: i0, i1 = i1, i0 r0, r1 = r1, r0 _rads1, _, lcm1 = i1 _rads1 = Mul(*_rads1) t1 = _rads1**lcm1 c = covsym**lcm1 - t1 for x in syms: try: sol = _vsolve(c, x, **uflags) if not sol: raise NotImplementedError neweq = r0.subs(x, sol[0]) + covsym*r1/_rads1 + \ others tmp = unrad(neweq, covsym) if tmp: eq, newcov = tmp if newcov: newp, newc = newcov _cov(newp, c.subs(covsym, _vsolve(newc, covsym, **uflags)[0])) else: _cov(covsym, c) else: eq = neweq _cov(covsym, c) ok = True break except NotImplementedError: if reverse: raise NotImplementedError( 'no successful change of variable found') else: pass if ok: break elif len(rterms) == 3: # two cube roots and another with order less than 5 # (so an analytical solution can be found) or a base # that matches one of the cube root bases info = [_rads_bases_lcm(i.as_poly()) for i in rterms] RAD = 0 BASES = 1 LCM = 2 if info[0][LCM] != 3: info.append(info.pop(0)) rterms.append(rterms.pop(0)) elif info[1][LCM] != 3: info.append(info.pop(1)) rterms.append(rterms.pop(1)) if info[0][LCM] == info[1][LCM] == 3: if info[1][BASES] != info[2][BASES]: info[0], info[1] = info[1], info[0] rterms[0], rterms[1] = rterms[1], rterms[0] if info[1][BASES] == info[2][BASES]: eq = rterms[0]**3 + (rterms[1] + rterms[2] + others)**3 ok = True elif info[2][LCM] < 5: # a*root(A, 3) + b*root(B, 3) + others = c a, b, c, d, A, B = [Dummy(i) for i in 'abcdAB'] # zz represents the unraded expression into which the # specifics for this case are substituted zz = (c - d)*(A**3*a**9 + 3*A**2*B*a**6*b**3 - 3*A**2*a**6*c**3 + 9*A**2*a**6*c**2*d - 9*A**2*a**6*c*d**2 + 3*A**2*a**6*d**3 + 3*A*B**2*a**3*b**6 + 21*A*B*a**3*b**3*c**3 - 63*A*B*a**3*b**3*c**2*d + 63*A*B*a**3*b**3*c*d**2 - 21*A*B*a**3*b**3*d**3 + 3*A*a**3*c**6 - 18*A*a**3*c**5*d + 45*A*a**3*c**4*d**2 - 60*A*a**3*c**3*d**3 + 45*A*a**3*c**2*d**4 - 18*A*a**3*c*d**5 + 3*A*a**3*d**6 + B**3*b**9 - 3*B**2*b**6*c**3 + 9*B**2*b**6*c**2*d - 9*B**2*b**6*c*d**2 + 3*B**2*b**6*d**3 + 3*B*b**3*c**6 - 18*B*b**3*c**5*d + 45*B*b**3*c**4*d**2 - 60*B*b**3*c**3*d**3 + 45*B*b**3*c**2*d**4 - 18*B*b**3*c*d**5 + 3*B*b**3*d**6 - c**9 + 9*c**8*d - 36*c**7*d**2 + 84*c**6*d**3 - 126*c**5*d**4 + 126*c**4*d**5 - 84*c**3*d**6 + 36*c**2*d**7 - 9*c*d**8 + d**9) def _t(i): b = Mul(*info[i][RAD]) return cancel(rterms[i]/b), Mul(*info[i][BASES]) aa, AA = _t(0) bb, BB = _t(1) cc = -rterms[2] dd = others eq = zz.xreplace(dict(zip( (a, A, b, B, c, d), (aa, AA, bb, BB, cc, dd)))) ok = True # handle power-of-2 cases if not ok: if log(lcm, 2).is_Integer and (not others and len(rterms) == 4 or len(rterms) < 4): def _norm2(a, b): return a**2 + b**2 + 2*a*b if len(rterms) == 4: # (r0+r1)**2 - (r2+r3)**2 r0, r1, r2, r3 = rterms eq = _norm2(r0, r1) - _norm2(r2, r3) ok = True elif len(rterms) == 3: # (r1+r2)**2 - (r0+others)**2 r0, r1, r2 = rterms eq = _norm2(r1, r2) - _norm2(r0, others) ok = True elif len(rterms) == 2: # r0**2 - (r1+others)**2 r0, r1 = rterms eq = r0**2 - _norm2(r1, others) ok = True new_depth = sqrt_depth(eq) if ok else depth rpt += 1 # XXX how many repeats with others unchanging is enough? if not ok or ( nwas is not None and len(rterms) == nwas and new_depth is not None and new_depth == depth and rpt > 3): raise NotImplementedError('Cannot remove all radicals') flags.update(dict(cov=cov, n=len(rterms), rpt=rpt)) neq = unrad(eq, *syms, **flags) if neq: eq, cov = neq eq, cov = _canonical(eq, cov) return eq, cov # delayed imports from sympy.solvers.bivariate import ( bivariate_type, _solve_lambert, _filtered_gens)
34261bd25153641d16c8477f4f03d095a73175cd380824c0c9d3753936a3409b
from collections import defaultdict, OrderedDict from itertools import ( chain, combinations, combinations_with_replacement, cycle, islice, permutations, product ) # For backwards compatibility from itertools import product as cartes # noqa: F401 from operator import gt # this is the logical location of these functions from sympy.utilities.enumerative import ( multiset_partitions_taocp, list_visitor, MultisetPartitionTraverser) from sympy.utilities.misc import as_int from sympy.utilities.decorator import deprecated def is_palindromic(s, i=0, j=None): """ Return True if the sequence is the same from left to right as it is from right to left in the whole sequence (default) or in the Python slice ``s[i: j]``; else False. Examples ======== >>> from sympy.utilities.iterables import is_palindromic >>> is_palindromic([1, 0, 1]) True >>> is_palindromic('abcbb') False >>> is_palindromic('abcbb', 1) False Normal Python slicing is performed in place so there is no need to create a slice of the sequence for testing: >>> is_palindromic('abcbb', 1, -1) True >>> is_palindromic('abcbb', -4, -1) True See Also ======== sympy.ntheory.digits.is_palindromic: tests integers """ i, j, _ = slice(i, j).indices(len(s)) m = (j - i)//2 # if length is odd, middle element will be ignored return all(s[i + k] == s[j - 1 - k] for k in range(m)) def flatten(iterable, levels=None, cls=None): # noqa: F811 """ Recursively denest iterable containers. >>> from sympy import flatten >>> flatten([1, 2, 3]) [1, 2, 3] >>> flatten([1, 2, [3]]) [1, 2, 3] >>> flatten([1, [2, 3], [4, 5]]) [1, 2, 3, 4, 5] >>> flatten([1.0, 2, (1, None)]) [1.0, 2, 1, None] If you want to denest only a specified number of levels of nested containers, then set ``levels`` flag to the desired number of levels:: >>> ls = [[(-2, -1), (1, 2)], [(0, 0)]] >>> flatten(ls, levels=1) [(-2, -1), (1, 2), (0, 0)] If cls argument is specified, it will only flatten instances of that class, for example: >>> from sympy import Basic, S >>> class MyOp(Basic): ... pass ... >>> flatten([MyOp(S(1), MyOp(S(2), S(3)))], cls=MyOp) [1, 2, 3] adapted from https://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks """ from sympy.tensor.array import NDimArray if levels is not None: if not levels: return iterable elif levels > 0: levels -= 1 else: raise ValueError( "expected non-negative number of levels, got %s" % levels) if cls is None: reducible = lambda x: is_sequence(x, set) else: reducible = lambda x: isinstance(x, cls) result = [] for el in iterable: if reducible(el): if hasattr(el, 'args') and not isinstance(el, NDimArray): el = el.args result.extend(flatten(el, levels=levels, cls=cls)) else: result.append(el) return result def unflatten(iter, n=2): """Group ``iter`` into tuples of length ``n``. Raise an error if the length of ``iter`` is not a multiple of ``n``. """ if n < 1 or len(iter) % n: raise ValueError('iter length is not a multiple of %i' % n) return list(zip(*(iter[i::n] for i in range(n)))) def reshape(seq, how): """Reshape the sequence according to the template in ``how``. Examples ======== >>> from sympy.utilities import reshape >>> seq = list(range(1, 9)) >>> reshape(seq, [4]) # lists of 4 [[1, 2, 3, 4], [5, 6, 7, 8]] >>> reshape(seq, (4,)) # tuples of 4 [(1, 2, 3, 4), (5, 6, 7, 8)] >>> reshape(seq, (2, 2)) # tuples of 4 [(1, 2, 3, 4), (5, 6, 7, 8)] >>> reshape(seq, (2, [2])) # (i, i, [i, i]) [(1, 2, [3, 4]), (5, 6, [7, 8])] >>> reshape(seq, ((2,), [2])) # etc.... [((1, 2), [3, 4]), ((5, 6), [7, 8])] >>> reshape(seq, (1, [2], 1)) [(1, [2, 3], 4), (5, [6, 7], 8)] >>> reshape(tuple(seq), ([[1], 1, (2,)],)) (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],)) >>> reshape(tuple(seq), ([1], 1, (2,))) (([1], 2, (3, 4)), ([5], 6, (7, 8))) >>> reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]] """ m = sum(flatten(how)) n, rem = divmod(len(seq), m) if m < 0 or rem: raise ValueError('template must sum to positive number ' 'that divides the length of the sequence') i = 0 container = type(how) rv = [None]*n for k in range(len(rv)): _rv = [] for hi in how: if isinstance(hi, int): _rv.extend(seq[i: i + hi]) i += hi else: n = sum(flatten(hi)) hi_type = type(hi) _rv.append(hi_type(reshape(seq[i: i + n], hi)[0])) i += n rv[k] = container(_rv) return type(seq)(rv) def group(seq, multiple=True): """ Splits a sequence into a list of lists of equal, adjacent elements. Examples ======== >>> from sympy import group >>> group([1, 1, 1, 2, 2, 3]) [[1, 1, 1], [2, 2], [3]] >>> group([1, 1, 1, 2, 2, 3], multiple=False) [(1, 3), (2, 2), (3, 1)] >>> group([1, 1, 3, 2, 2, 1], multiple=False) [(1, 2), (3, 1), (2, 2), (1, 1)] See Also ======== multiset """ if not seq: return [] current, groups = [seq[0]], [] for elem in seq[1:]: if elem == current[-1]: current.append(elem) else: groups.append(current) current = [elem] groups.append(current) if multiple: return groups for i, current in enumerate(groups): groups[i] = (current[0], len(current)) return groups def _iproduct2(iterable1, iterable2): '''Cartesian product of two possibly infinite iterables''' it1 = iter(iterable1) it2 = iter(iterable2) elems1 = [] elems2 = [] sentinel = object() def append(it, elems): e = next(it, sentinel) if e is not sentinel: elems.append(e) n = 0 append(it1, elems1) append(it2, elems2) while n <= len(elems1) + len(elems2): for m in range(n-len(elems1)+1, len(elems2)): yield (elems1[n-m], elems2[m]) n += 1 append(it1, elems1) append(it2, elems2) def iproduct(*iterables): ''' Cartesian product of iterables. Generator of the Cartesian product of iterables. This is analogous to itertools.product except that it works with infinite iterables and will yield any item from the infinite product eventually. Examples ======== >>> from sympy.utilities.iterables import iproduct >>> sorted(iproduct([1,2], [3,4])) [(1, 3), (1, 4), (2, 3), (2, 4)] With an infinite iterator: >>> from sympy import S >>> (3,) in iproduct(S.Integers) True >>> (3, 4) in iproduct(S.Integers, S.Integers) True .. seealso:: `itertools.product <https://docs.python.org/3/library/itertools.html#itertools.product>`_ ''' if len(iterables) == 0: yield () return elif len(iterables) == 1: for e in iterables[0]: yield (e,) elif len(iterables) == 2: yield from _iproduct2(*iterables) else: first, others = iterables[0], iterables[1:] for ef, eo in _iproduct2(first, iproduct(*others)): yield (ef,) + eo def multiset(seq): """Return the hashable sequence in multiset form with values being the multiplicity of the item in the sequence. Examples ======== >>> from sympy.utilities.iterables import multiset >>> multiset('mississippi') {'i': 4, 'm': 1, 'p': 2, 's': 4} See Also ======== group """ rv = defaultdict(int) for s in seq: rv[s] += 1 return dict(rv) def ibin(n, bits=None, str=False): """Return a list of length ``bits`` corresponding to the binary value of ``n`` with small bits to the right (last). If bits is omitted, the length will be the number required to represent ``n``. If the bits are desired in reversed order, use the ``[::-1]`` slice of the returned list. If a sequence of all bits-length lists starting from ``[0, 0,..., 0]`` through ``[1, 1, ..., 1]`` are desired, pass a non-integer for bits, e.g. ``'all'``. If the bit *string* is desired pass ``str=True``. Examples ======== >>> from sympy.utilities.iterables import ibin >>> ibin(2) [1, 0] >>> ibin(2, 4) [0, 0, 1, 0] If all lists corresponding to 0 to 2**n - 1, pass a non-integer for bits: >>> bits = 2 >>> for i in ibin(2, 'all'): ... print(i) (0, 0) (0, 1) (1, 0) (1, 1) If a bit string is desired of a given length, use str=True: >>> n = 123 >>> bits = 10 >>> ibin(n, bits, str=True) '0001111011' >>> ibin(n, bits, str=True)[::-1] # small bits left '1101111000' >>> list(ibin(3, 'all', str=True)) ['000', '001', '010', '011', '100', '101', '110', '111'] """ if n < 0: raise ValueError("negative numbers are not allowed") n = as_int(n) if bits is None: bits = 0 else: try: bits = as_int(bits) except ValueError: bits = -1 else: if n.bit_length() > bits: raise ValueError( "`bits` must be >= {}".format(n.bit_length())) if not str: if bits >= 0: return [1 if i == "1" else 0 for i in bin(n)[2:].rjust(bits, "0")] else: return variations(range(2), n, repetition=True) else: if bits >= 0: return bin(n)[2:].rjust(bits, "0") else: return (bin(i)[2:].rjust(n, "0") for i in range(2**n)) def variations(seq, n, repetition=False): r"""Returns an iterator over the n-sized variations of ``seq`` (size N). ``repetition`` controls whether items in ``seq`` can appear more than once; Examples ======== ``variations(seq, n)`` will return `\frac{N!}{(N - n)!}` permutations without repetition of ``seq``'s elements: >>> from sympy import variations >>> list(variations([1, 2], 2)) [(1, 2), (2, 1)] ``variations(seq, n, True)`` will return the `N^n` permutations obtained by allowing repetition of elements: >>> list(variations([1, 2], 2, repetition=True)) [(1, 1), (1, 2), (2, 1), (2, 2)] If you ask for more items than are in the set you get the empty set unless you allow repetitions: >>> list(variations([0, 1], 3, repetition=False)) [] >>> list(variations([0, 1], 3, repetition=True))[:4] [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)] .. seealso:: `itertools.permutations <https://docs.python.org/3/library/itertools.html#itertools.permutations>`_, `itertools.product <https://docs.python.org/3/library/itertools.html#itertools.product>`_ """ if not repetition: seq = tuple(seq) if len(seq) < n: return iter(()) # 0 length iterator return permutations(seq, n) else: if n == 0: return iter(((),)) # yields 1 empty tuple else: return product(seq, repeat=n) def subsets(seq, k=None, repetition=False): r"""Generates all `k`-subsets (combinations) from an `n`-element set, ``seq``. A `k`-subset of an `n`-element set is any subset of length exactly `k`. The number of `k`-subsets of an `n`-element set is given by ``binomial(n, k)``, whereas there are `2^n` subsets all together. If `k` is ``None`` then all `2^n` subsets will be returned from shortest to longest. Examples ======== >>> from sympy import subsets ``subsets(seq, k)`` will return the `\frac{n!}{k!(n - k)!}` `k`-subsets (combinations) without repetition, i.e. once an item has been removed, it can no longer be "taken": >>> list(subsets([1, 2], 2)) [(1, 2)] >>> list(subsets([1, 2])) [(), (1,), (2,), (1, 2)] >>> list(subsets([1, 2, 3], 2)) [(1, 2), (1, 3), (2, 3)] ``subsets(seq, k, repetition=True)`` will return the `\frac{(n - 1 + k)!}{k!(n - 1)!}` combinations *with* repetition: >>> list(subsets([1, 2], 2, repetition=True)) [(1, 1), (1, 2), (2, 2)] If you ask for more items than are in the set you get the empty set unless you allow repetitions: >>> list(subsets([0, 1], 3, repetition=False)) [] >>> list(subsets([0, 1], 3, repetition=True)) [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] """ if k is None: if not repetition: return chain.from_iterable((combinations(seq, k) for k in range(len(seq) + 1))) else: return chain.from_iterable((combinations_with_replacement(seq, k) for k in range(len(seq) + 1))) else: if not repetition: return combinations(seq, k) else: return combinations_with_replacement(seq, k) def filter_symbols(iterator, exclude): """ Only yield elements from `iterator` that do not occur in `exclude`. Parameters ========== iterator : iterable iterator to take elements from exclude : iterable elements to exclude Returns ======= iterator : iterator filtered iterator """ exclude = set(exclude) for s in iterator: if s not in exclude: yield s def numbered_symbols(prefix='x', cls=None, start=0, exclude=(), *args, **assumptions): """ Generate an infinite stream of Symbols consisting of a prefix and increasing subscripts provided that they do not occur in ``exclude``. Parameters ========== prefix : str, optional The prefix to use. By default, this function will generate symbols of the form "x0", "x1", etc. cls : class, optional The class to use. By default, it uses ``Symbol``, but you can also use ``Wild`` or ``Dummy``. start : int, optional The start number. By default, it is 0. Returns ======= sym : Symbol The subscripted symbols. """ exclude = set(exclude or []) if cls is None: # We can't just make the default cls=Symbol because it isn't # imported yet. from sympy.core import Symbol cls = Symbol while True: name = '%s%s' % (prefix, start) s = cls(name, *args, **assumptions) if s not in exclude: yield s start += 1 def capture(func): """Return the printed output of func(). ``func`` should be a function without arguments that produces output with print statements. >>> from sympy.utilities.iterables import capture >>> from sympy import pprint >>> from sympy.abc import x >>> def foo(): ... print('hello world!') ... >>> 'hello' in capture(foo) # foo, not foo() True >>> capture(lambda: pprint(2/x)) '2\\n-\\nx\\n' """ from io import StringIO import sys stdout = sys.stdout sys.stdout = file = StringIO() try: func() finally: sys.stdout = stdout return file.getvalue() def sift(seq, keyfunc, binary=False): """ Sift the sequence, ``seq`` according to ``keyfunc``. Returns ======= When ``binary`` is ``False`` (default), the output is a dictionary where elements of ``seq`` are stored in a list keyed to the value of keyfunc for that element. If ``binary`` is True then a tuple with lists ``T`` and ``F`` are returned where ``T`` is a list containing elements of seq for which ``keyfunc`` was ``True`` and ``F`` containing those elements for which ``keyfunc`` was ``False``; a ValueError is raised if the ``keyfunc`` is not binary. Examples ======== >>> from sympy.utilities import sift >>> from sympy.abc import x, y >>> from sympy import sqrt, exp, pi, Tuple >>> sift(range(5), lambda x: x % 2) {0: [0, 2, 4], 1: [1, 3]} sift() returns a defaultdict() object, so any key that has no matches will give []. >>> sift([x], lambda x: x.is_commutative) {True: [x]} >>> _[False] [] Sometimes you will not know how many keys you will get: >>> sift([sqrt(x), exp(x), (y**x)**2], ... lambda x: x.as_base_exp()[0]) {E: [exp(x)], x: [sqrt(x)], y: [y**(2*x)]} Sometimes you expect the results to be binary; the results can be unpacked by setting ``binary`` to True: >>> sift(range(4), lambda x: x % 2, binary=True) ([1, 3], [0, 2]) >>> sift(Tuple(1, pi), lambda x: x.is_rational, binary=True) ([1], [pi]) A ValueError is raised if the predicate was not actually binary (which is a good test for the logic where sifting is used and binary results were expected): >>> unknown = exp(1) - pi # the rationality of this is unknown >>> args = Tuple(1, pi, unknown) >>> sift(args, lambda x: x.is_rational, binary=True) Traceback (most recent call last): ... ValueError: keyfunc gave non-binary output The non-binary sifting shows that there were 3 keys generated: >>> set(sift(args, lambda x: x.is_rational).keys()) {None, False, True} If you need to sort the sifted items it might be better to use ``ordered`` which can economically apply multiple sort keys to a sequence while sorting. See Also ======== ordered """ if not binary: m = defaultdict(list) for i in seq: m[keyfunc(i)].append(i) return m sift = F, T = [], [] for i in seq: try: sift[keyfunc(i)].append(i) except (IndexError, TypeError): raise ValueError('keyfunc gave non-binary output') return T, F def take(iter, n): """Return ``n`` items from ``iter`` iterator. """ return [ value for _, value in zip(range(n), iter) ] def dict_merge(*dicts): """Merge dictionaries into a single dictionary. """ merged = {} for dict in dicts: merged.update(dict) return merged def common_prefix(*seqs): """Return the subsequence that is a common start of sequences in ``seqs``. >>> from sympy.utilities.iterables import common_prefix >>> common_prefix(list(range(3))) [0, 1, 2] >>> common_prefix(list(range(3)), list(range(4))) [0, 1, 2] >>> common_prefix([1, 2, 3], [1, 2, 5]) [1, 2] >>> common_prefix([1, 2, 3], [1, 3, 5]) [1] """ if not all(seqs): return [] elif len(seqs) == 1: return seqs[0] i = 0 for i in range(min(len(s) for s in seqs)): if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))): break else: i += 1 return seqs[0][:i] def common_suffix(*seqs): """Return the subsequence that is a common ending of sequences in ``seqs``. >>> from sympy.utilities.iterables import common_suffix >>> common_suffix(list(range(3))) [0, 1, 2] >>> common_suffix(list(range(3)), list(range(4))) [] >>> common_suffix([1, 2, 3], [9, 2, 3]) [2, 3] >>> common_suffix([1, 2, 3], [9, 7, 3]) [3] """ if not all(seqs): return [] elif len(seqs) == 1: return seqs[0] i = 0 for i in range(-1, -min(len(s) for s in seqs) - 1, -1): if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))): break else: i -= 1 if i == -1: return [] else: return seqs[0][i + 1:] def prefixes(seq): """ Generate all prefixes of a sequence. Examples ======== >>> from sympy.utilities.iterables import prefixes >>> list(prefixes([1,2,3,4])) [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] """ n = len(seq) for i in range(n): yield seq[:i + 1] def postfixes(seq): """ Generate all postfixes of a sequence. Examples ======== >>> from sympy.utilities.iterables import postfixes >>> list(postfixes([1,2,3,4])) [[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]] """ n = len(seq) for i in range(n): yield seq[n - i - 1:] def topological_sort(graph, key=None): r""" Topological sort of graph's vertices. Parameters ========== graph : tuple[list, list[tuple[T, T]] A tuple consisting of a list of vertices and a list of edges of a graph to be sorted topologically. key : callable[T] (optional) Ordering key for vertices on the same level. By default the natural (e.g. lexicographic) ordering is used (in this case the base type must implement ordering relations). Examples ======== Consider a graph:: +---+ +---+ +---+ | 7 |\ | 5 | | 3 | +---+ \ +---+ +---+ | _\___/ ____ _/ | | / \___/ \ / | V V V V | +----+ +---+ | | 11 | | 8 | | +----+ +---+ | | | \____ ___/ _ | | \ \ / / \ | V \ V V / V V +---+ \ +---+ | +----+ | 2 | | | 9 | | | 10 | +---+ | +---+ | +----+ \________/ where vertices are integers. This graph can be encoded using elementary Python's data structures as follows:: >>> V = [2, 3, 5, 7, 8, 9, 10, 11] >>> E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10), ... (11, 2), (11, 9), (11, 10), (8, 9)] To compute a topological sort for graph ``(V, E)`` issue:: >>> from sympy.utilities.iterables import topological_sort >>> topological_sort((V, E)) [3, 5, 7, 8, 11, 2, 9, 10] If specific tie breaking approach is needed, use ``key`` parameter:: >>> topological_sort((V, E), key=lambda v: -v) [7, 5, 11, 3, 10, 8, 9, 2] Only acyclic graphs can be sorted. If the input graph has a cycle, then ``ValueError`` will be raised:: >>> topological_sort((V, E + [(10, 7)])) Traceback (most recent call last): ... ValueError: cycle detected References ========== .. [1] https://en.wikipedia.org/wiki/Topological_sorting """ V, E = graph L = [] S = set(V) E = list(E) for v, u in E: S.discard(u) if key is None: key = lambda value: value S = sorted(S, key=key, reverse=True) while S: node = S.pop() L.append(node) for u, v in list(E): if u == node: E.remove((u, v)) for _u, _v in E: if v == _v: break else: kv = key(v) for i, s in enumerate(S): ks = key(s) if kv > ks: S.insert(i, v) break else: S.append(v) if E: raise ValueError("cycle detected") else: return L def strongly_connected_components(G): r""" Strongly connected components of a directed graph in reverse topological order. Parameters ========== graph : tuple[list, list[tuple[T, T]] A tuple consisting of a list of vertices and a list of edges of a graph whose strongly connected components are to be found. Examples ======== Consider a directed graph (in dot notation):: digraph { A -> B A -> C B -> C C -> B B -> D } .. graphviz:: digraph { A -> B A -> C B -> C C -> B B -> D } where vertices are the letters A, B, C and D. This graph can be encoded using Python's elementary data structures as follows:: >>> V = ['A', 'B', 'C', 'D'] >>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'B'), ('B', 'D')] The strongly connected components of this graph can be computed as >>> from sympy.utilities.iterables import strongly_connected_components >>> strongly_connected_components((V, E)) [['D'], ['B', 'C'], ['A']] This also gives the components in reverse topological order. Since the subgraph containing B and C has a cycle they must be together in a strongly connected component. A and D are connected to the rest of the graph but not in a cyclic manner so they appear as their own strongly connected components. Notes ===== The vertices of the graph must be hashable for the data structures used. If the vertices are unhashable replace them with integer indices. This function uses Tarjan's algorithm to compute the strongly connected components in `O(|V|+|E|)` (linear) time. References ========== .. [1] https://en.wikipedia.org/wiki/Strongly_connected_component .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm See Also ======== sympy.utilities.iterables.connected_components """ # Map from a vertex to its neighbours V, E = G Gmap = {vi: [] for vi in V} for v1, v2 in E: Gmap[v1].append(v2) return _strongly_connected_components(V, Gmap) def _strongly_connected_components(V, Gmap): """More efficient internal routine for strongly_connected_components""" # # Here V is an iterable of vertices and Gmap is a dict mapping each vertex # to a list of neighbours e.g.: # # V = [0, 1, 2, 3] # Gmap = {0: [2, 3], 1: [0]} # # For a large graph these data structures can often be created more # efficiently then those expected by strongly_connected_components() which # in this case would be # # V = [0, 1, 2, 3] # Gmap = [(0, 2), (0, 3), (1, 0)] # # XXX: Maybe this should be the recommended function to use instead... # # Non-recursive Tarjan's algorithm: lowlink = {} indices = {} stack = OrderedDict() callstack = [] components = [] nomore = object() def start(v): index = len(stack) indices[v] = lowlink[v] = index stack[v] = None callstack.append((v, iter(Gmap[v]))) def finish(v1): # Finished a component? if lowlink[v1] == indices[v1]: component = [stack.popitem()[0]] while component[-1] is not v1: component.append(stack.popitem()[0]) components.append(component[::-1]) v2, _ = callstack.pop() if callstack: v1, _ = callstack[-1] lowlink[v1] = min(lowlink[v1], lowlink[v2]) for v in V: if v in indices: continue start(v) while callstack: v1, it1 = callstack[-1] v2 = next(it1, nomore) # Finished children of v1? if v2 is nomore: finish(v1) # Recurse on v2 elif v2 not in indices: start(v2) elif v2 in stack: lowlink[v1] = min(lowlink[v1], indices[v2]) # Reverse topological sort order: return components def connected_components(G): r""" Connected components of an undirected graph or weakly connected components of a directed graph. Parameters ========== graph : tuple[list, list[tuple[T, T]] A tuple consisting of a list of vertices and a list of edges of a graph whose connected components are to be found. Examples ======== Given an undirected graph:: graph { A -- B C -- D } .. graphviz:: graph { A -- B C -- D } We can find the connected components using this function if we include each edge in both directions:: >>> from sympy.utilities.iterables import connected_components >>> V = ['A', 'B', 'C', 'D'] >>> E = [('A', 'B'), ('B', 'A'), ('C', 'D'), ('D', 'C')] >>> connected_components((V, E)) [['A', 'B'], ['C', 'D']] The weakly connected components of a directed graph can found the same way. Notes ===== The vertices of the graph must be hashable for the data structures used. If the vertices are unhashable replace them with integer indices. This function uses Tarjan's algorithm to compute the connected components in `O(|V|+|E|)` (linear) time. References ========== .. [1] https://en.wikipedia.org/wiki/Connected_component_(graph_theory) .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm See Also ======== sympy.utilities.iterables.strongly_connected_components """ # Duplicate edges both ways so that the graph is effectively undirected # and return the strongly connected components: V, E = G E_undirected = [] for v1, v2 in E: E_undirected.extend([(v1, v2), (v2, v1)]) return strongly_connected_components((V, E_undirected)) def rotate_left(x, y): """ Left rotates a list x by the number of steps specified in y. Examples ======== >>> from sympy.utilities.iterables import rotate_left >>> a = [0, 1, 2] >>> rotate_left(a, 1) [1, 2, 0] """ if len(x) == 0: return [] y = y % len(x) return x[y:] + x[:y] def rotate_right(x, y): """ Right rotates a list x by the number of steps specified in y. Examples ======== >>> from sympy.utilities.iterables import rotate_right >>> a = [0, 1, 2] >>> rotate_right(a, 1) [2, 0, 1] """ if len(x) == 0: return [] y = len(x) - y % len(x) return x[y:] + x[:y] def least_rotation(x, key=None): ''' Returns the number of steps of left rotation required to obtain lexicographically minimal string/list/tuple, etc. Examples ======== >>> from sympy.utilities.iterables import least_rotation, rotate_left >>> a = [3, 1, 5, 1, 2] >>> least_rotation(a) 3 >>> rotate_left(a, _) [1, 2, 3, 1, 5] References ========== .. [1] https://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation ''' from sympy.functions.elementary.miscellaneous import Id if key is None: key = Id S = x + x # Concatenate string to it self to avoid modular arithmetic f = [-1] * len(S) # Failure function k = 0 # Least rotation of string found so far for j in range(1,len(S)): sj = S[j] i = f[j-k-1] while i != -1 and sj != S[k+i+1]: if key(sj) < key(S[k+i+1]): k = j-i-1 i = f[i] if sj != S[k+i+1]: if key(sj) < key(S[k]): k = j f[j-k] = -1 else: f[j-k] = i+1 return k def multiset_combinations(m, n, g=None): """ Return the unique combinations of size ``n`` from multiset ``m``. Examples ======== >>> from sympy.utilities.iterables import multiset_combinations >>> from itertools import combinations >>> [''.join(i) for i in multiset_combinations('baby', 3)] ['abb', 'aby', 'bby'] >>> def count(f, s): return len(list(f(s, 3))) The number of combinations depends on the number of letters; the number of unique combinations depends on how the letters are repeated. >>> s1 = 'abracadabra' >>> s2 = 'banana tree' >>> count(combinations, s1), count(multiset_combinations, s1) (165, 23) >>> count(combinations, s2), count(multiset_combinations, s2) (165, 54) """ from sympy.core.sorting import ordered if g is None: if isinstance(m, dict): if any(as_int(v) < 0 for v in m.values()): raise ValueError('counts cannot be negative') N = sum(m.values()) if n > N: return g = [[k, m[k]] for k in ordered(m)] else: m = list(m) N = len(m) if n > N: return try: m = multiset(m) g = [(k, m[k]) for k in ordered(m)] except TypeError: m = list(ordered(m)) g = [list(i) for i in group(m, multiple=False)] del m else: # not checking counts since g is intended for internal use N = sum(v for k, v in g) if n > N or not n: yield [] else: for i, (k, v) in enumerate(g): if v >= n: yield [k]*n v = n - 1 for v in range(min(n, v), 0, -1): for j in multiset_combinations(None, n - v, g[i + 1:]): rv = [k]*v + j if len(rv) == n: yield rv def multiset_permutations(m, size=None, g=None): """ Return the unique permutations of multiset ``m``. Examples ======== >>> from sympy.utilities.iterables import multiset_permutations >>> from sympy import factorial >>> [''.join(i) for i in multiset_permutations('aab')] ['aab', 'aba', 'baa'] >>> factorial(len('banana')) 720 >>> len(list(multiset_permutations('banana'))) 60 """ from sympy.core.sorting import ordered if g is None: if isinstance(m, dict): if any(as_int(v) < 0 for v in m.values()): raise ValueError('counts cannot be negative') g = [[k, m[k]] for k in ordered(m)] else: m = list(ordered(m)) g = [list(i) for i in group(m, multiple=False)] del m do = [gi for gi in g if gi[1] > 0] SUM = sum([gi[1] for gi in do]) if not do or size is not None and (size > SUM or size < 1): if not do and size is None or size == 0: yield [] return elif size == 1: for k, v in do: yield [k] elif len(do) == 1: k, v = do[0] v = v if size is None else (size if size <= v else 0) yield [k for i in range(v)] elif all(v == 1 for k, v in do): for p in permutations([k for k, v in do], size): yield list(p) else: size = size if size is not None else SUM for i, (k, v) in enumerate(do): do[i][1] -= 1 for j in multiset_permutations(None, size - 1, do): if j: yield [k] + j do[i][1] += 1 def _partition(seq, vector, m=None): """ Return the partition of seq as specified by the partition vector. Examples ======== >>> from sympy.utilities.iterables import _partition >>> _partition('abcde', [1, 0, 1, 2, 0]) [['b', 'e'], ['a', 'c'], ['d']] Specifying the number of bins in the partition is optional: >>> _partition('abcde', [1, 0, 1, 2, 0], 3) [['b', 'e'], ['a', 'c'], ['d']] The output of _set_partitions can be passed as follows: >>> output = (3, [1, 0, 1, 2, 0]) >>> _partition('abcde', *output) [['b', 'e'], ['a', 'c'], ['d']] See Also ======== combinatorics.partitions.Partition.from_rgs """ if m is None: m = max(vector) + 1 elif isinstance(vector, int): # entered as m, vector vector, m = m, vector p = [[] for i in range(m)] for i, v in enumerate(vector): p[v].append(seq[i]) return p def _set_partitions(n): """Cycle through all partions of n elements, yielding the current number of partitions, ``m``, and a mutable list, ``q`` such that ``element[i]`` is in part ``q[i]`` of the partition. NOTE: ``q`` is modified in place and generally should not be changed between function calls. Examples ======== >>> from sympy.utilities.iterables import _set_partitions, _partition >>> for m, q in _set_partitions(3): ... print('%s %s %s' % (m, q, _partition('abc', q, m))) 1 [0, 0, 0] [['a', 'b', 'c']] 2 [0, 0, 1] [['a', 'b'], ['c']] 2 [0, 1, 0] [['a', 'c'], ['b']] 2 [0, 1, 1] [['a'], ['b', 'c']] 3 [0, 1, 2] [['a'], ['b'], ['c']] Notes ===== This algorithm is similar to, and solves the same problem as, Algorithm 7.2.1.5H, from volume 4A of Knuth's The Art of Computer Programming. Knuth uses the term "restricted growth string" where this code refers to a "partition vector". In each case, the meaning is the same: the value in the ith element of the vector specifies to which part the ith set element is to be assigned. At the lowest level, this code implements an n-digit big-endian counter (stored in the array q) which is incremented (with carries) to get the next partition in the sequence. A special twist is that a digit is constrained to be at most one greater than the maximum of all the digits to the left of it. The array p maintains this maximum, so that the code can efficiently decide when a digit can be incremented in place or whether it needs to be reset to 0 and trigger a carry to the next digit. The enumeration starts with all the digits 0 (which corresponds to all the set elements being assigned to the same 0th part), and ends with 0123...n, which corresponds to each set element being assigned to a different, singleton, part. This routine was rewritten to use 0-based lists while trying to preserve the beauty and efficiency of the original algorithm. References ========== .. [1] Nijenhuis, Albert and Wilf, Herbert. (1978) Combinatorial Algorithms, 2nd Ed, p 91, algorithm "nexequ". Available online from https://www.math.upenn.edu/~wilf/website/CombAlgDownld.html (viewed November 17, 2012). """ p = [0]*n q = [0]*n nc = 1 yield nc, q while nc != n: m = n while 1: m -= 1 i = q[m] if p[i] != 1: break q[m] = 0 i += 1 q[m] = i m += 1 nc += m - n p[0] += n - m if i == nc: p[nc] = 0 nc += 1 p[i - 1] -= 1 p[i] += 1 yield nc, q def multiset_partitions(multiset, m=None): """ Return unique partitions of the given multiset (in list form). If ``m`` is None, all multisets will be returned, otherwise only partitions with ``m`` parts will be returned. If ``multiset`` is an integer, a range [0, 1, ..., multiset - 1] will be supplied. Examples ======== >>> from sympy.utilities.iterables import multiset_partitions >>> list(multiset_partitions([1, 2, 3, 4], 2)) [[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]], [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]], [[1], [2, 3, 4]]] >>> list(multiset_partitions([1, 2, 3, 4], 1)) [[[1, 2, 3, 4]]] Only unique partitions are returned and these will be returned in a canonical order regardless of the order of the input: >>> a = [1, 2, 2, 1] >>> ans = list(multiset_partitions(a, 2)) >>> a.sort() >>> list(multiset_partitions(a, 2)) == ans True >>> a = range(3, 1, -1) >>> (list(multiset_partitions(a)) == ... list(multiset_partitions(sorted(a)))) True If m is omitted then all partitions will be returned: >>> list(multiset_partitions([1, 1, 2])) [[[1, 1, 2]], [[1, 1], [2]], [[1, 2], [1]], [[1], [1], [2]]] >>> list(multiset_partitions([1]*3)) [[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]] Counting ======== The number of partitions of a set is given by the bell number: >>> from sympy import bell >>> len(list(multiset_partitions(5))) == bell(5) == 52 True The number of partitions of length k from a set of size n is given by the Stirling Number of the 2nd kind: >>> from sympy.functions.combinatorial.numbers import stirling >>> stirling(5, 2) == len(list(multiset_partitions(5, 2))) == 15 True These comments on counting apply to *sets*, not multisets. Notes ===== When all the elements are the same in the multiset, the order of the returned partitions is determined by the ``partitions`` routine. If one is counting partitions then it is better to use the ``nT`` function. See Also ======== partitions sympy.combinatorics.partitions.Partition sympy.combinatorics.partitions.IntegerPartition sympy.functions.combinatorial.numbers.nT """ # This function looks at the supplied input and dispatches to # several special-case routines as they apply. if isinstance(multiset, int): n = multiset if m and m > n: return multiset = list(range(n)) if m == 1: yield [multiset[:]] return # If m is not None, it can sometimes be faster to use # MultisetPartitionTraverser.enum_range() even for inputs # which are sets. Since the _set_partitions code is quite # fast, this is only advantageous when the overall set # partitions outnumber those with the desired number of parts # by a large factor. (At least 60.) Such a switch is not # currently implemented. for nc, q in _set_partitions(n): if m is None or nc == m: rv = [[] for i in range(nc)] for i in range(n): rv[q[i]].append(multiset[i]) yield rv return if len(multiset) == 1 and isinstance(multiset, str): multiset = [multiset] if not has_variety(multiset): # Only one component, repeated n times. The resulting # partitions correspond to partitions of integer n. n = len(multiset) if m and m > n: return if m == 1: yield [multiset[:]] return x = multiset[:1] for size, p in partitions(n, m, size=True): if m is None or size == m: rv = [] for k in sorted(p): rv.extend([x*k]*p[k]) yield rv else: from sympy.core.sorting import ordered multiset = list(ordered(multiset)) n = len(multiset) if m and m > n: return if m == 1: yield [multiset[:]] return # Split the information of the multiset into two lists - # one of the elements themselves, and one (of the same length) # giving the number of repeats for the corresponding element. elements, multiplicities = zip(*group(multiset, False)) if len(elements) < len(multiset): # General case - multiset with more than one distinct element # and at least one element repeated more than once. if m: mpt = MultisetPartitionTraverser() for state in mpt.enum_range(multiplicities, m-1, m): yield list_visitor(state, elements) else: for state in multiset_partitions_taocp(multiplicities): yield list_visitor(state, elements) else: # Set partitions case - no repeated elements. Pretty much # same as int argument case above, with same possible, but # currently unimplemented optimization for some cases when # m is not None for nc, q in _set_partitions(n): if m is None or nc == m: rv = [[] for i in range(nc)] for i in range(n): rv[q[i]].append(i) yield [[multiset[j] for j in i] for i in rv] def partitions(n, m=None, k=None, size=False): """Generate all partitions of positive integer, n. Parameters ========== m : integer (default gives partitions of all sizes) limits number of parts in partition (mnemonic: m, maximum parts) k : integer (default gives partitions number from 1 through n) limits the numbers that are kept in the partition (mnemonic: k, keys) size : bool (default False, only partition is returned) when ``True`` then (M, P) is returned where M is the sum of the multiplicities and P is the generated partition. Each partition is represented as a dictionary, mapping an integer to the number of copies of that integer in the partition. For example, the first partition of 4 returned is {4: 1}, "4: one of them". Examples ======== >>> from sympy.utilities.iterables import partitions The numbers appearing in the partition (the key of the returned dict) are limited with k: >>> for p in partitions(6, k=2): # doctest: +SKIP ... print(p) {2: 3} {1: 2, 2: 2} {1: 4, 2: 1} {1: 6} The maximum number of parts in the partition (the sum of the values in the returned dict) are limited with m (default value, None, gives partitions from 1 through n): >>> for p in partitions(6, m=2): # doctest: +SKIP ... print(p) ... {6: 1} {1: 1, 5: 1} {2: 1, 4: 1} {3: 2} References ========== .. [1] modified from Tim Peter's version to allow for k and m values: http://code.activestate.com/recipes/218332-generator-for-integer-partitions/ See Also ======== sympy.combinatorics.partitions.Partition sympy.combinatorics.partitions.IntegerPartition """ if (n <= 0 or m is not None and m < 1 or k is not None and k < 1 or m and k and m*k < n): # the empty set is the only way to handle these inputs # and returning {} to represent it is consistent with # the counting convention, e.g. nT(0) == 1. if size: yield 0, {} else: yield {} return if m is None: m = n else: m = min(m, n) k = min(k or n, n) n, m, k = as_int(n), as_int(m), as_int(k) q, r = divmod(n, k) ms = {k: q} keys = [k] # ms.keys(), from largest to smallest if r: ms[r] = 1 keys.append(r) room = m - q - bool(r) if size: yield sum(ms.values()), ms.copy() else: yield ms.copy() while keys != [1]: # Reuse any 1's. if keys[-1] == 1: del keys[-1] reuse = ms.pop(1) room += reuse else: reuse = 0 while 1: # Let i be the smallest key larger than 1. Reuse one # instance of i. i = keys[-1] newcount = ms[i] = ms[i] - 1 reuse += i if newcount == 0: del keys[-1], ms[i] room += 1 # Break the remainder into pieces of size i-1. i -= 1 q, r = divmod(reuse, i) need = q + bool(r) if need > room: if not keys: return continue ms[i] = q keys.append(i) if r: ms[r] = 1 keys.append(r) break room -= need if size: yield sum(ms.values()), ms.copy() else: yield ms.copy() def ordered_partitions(n, m=None, sort=True): """Generates ordered partitions of integer ``n``. Parameters ========== m : integer (default None) The default value gives partitions of all sizes else only those with size m. In addition, if ``m`` is not None then partitions are generated *in place* (see examples). sort : bool (default True) Controls whether partitions are returned in sorted order when ``m`` is not None; when False, the partitions are returned as fast as possible with elements sorted, but when m|n the partitions will not be in ascending lexicographical order. Examples ======== >>> from sympy.utilities.iterables import ordered_partitions All partitions of 5 in ascending lexicographical: >>> for p in ordered_partitions(5): ... print(p) [1, 1, 1, 1, 1] [1, 1, 1, 2] [1, 1, 3] [1, 2, 2] [1, 4] [2, 3] [5] Only partitions of 5 with two parts: >>> for p in ordered_partitions(5, 2): ... print(p) [1, 4] [2, 3] When ``m`` is given, a given list objects will be used more than once for speed reasons so you will not see the correct partitions unless you make a copy of each as it is generated: >>> [p for p in ordered_partitions(7, 3)] [[1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 2, 2]] >>> [list(p) for p in ordered_partitions(7, 3)] [[1, 1, 5], [1, 2, 4], [1, 3, 3], [2, 2, 3]] When ``n`` is a multiple of ``m``, the elements are still sorted but the partitions themselves will be *unordered* if sort is False; the default is to return them in ascending lexicographical order. >>> for p in ordered_partitions(6, 2): ... print(p) [1, 5] [2, 4] [3, 3] But if speed is more important than ordering, sort can be set to False: >>> for p in ordered_partitions(6, 2, sort=False): ... print(p) [1, 5] [3, 3] [2, 4] References ========== .. [1] Generating Integer Partitions, [online], Available: https://jeromekelleher.net/generating-integer-partitions.html .. [2] Jerome Kelleher and Barry O'Sullivan, "Generating All Partitions: A Comparison Of Two Encodings", [online], Available: https://arxiv.org/pdf/0909.2331v2.pdf """ if n < 1 or m is not None and m < 1: # the empty set is the only way to handle these inputs # and returning {} to represent it is consistent with # the counting convention, e.g. nT(0) == 1. yield [] return if m is None: # The list `a`'s leading elements contain the partition in which # y is the biggest element and x is either the same as y or the # 2nd largest element; v and w are adjacent element indices # to which x and y are being assigned, respectively. a = [1]*n y = -1 v = n while v > 0: v -= 1 x = a[v] + 1 while y >= 2 * x: a[v] = x y -= x v += 1 w = v + 1 while x <= y: a[v] = x a[w] = y yield a[:w + 1] x += 1 y -= 1 a[v] = x + y y = a[v] - 1 yield a[:w] elif m == 1: yield [n] elif n == m: yield [1]*n else: # recursively generate partitions of size m for b in range(1, n//m + 1): a = [b]*m x = n - b*m if not x: if sort: yield a elif not sort and x <= m: for ax in ordered_partitions(x, sort=False): mi = len(ax) a[-mi:] = [i + b for i in ax] yield a a[-mi:] = [b]*mi else: for mi in range(1, m): for ax in ordered_partitions(x, mi, sort=True): a[-mi:] = [i + b for i in ax] yield a a[-mi:] = [b]*mi def binary_partitions(n): """ Generates the binary partition of n. A binary partition consists only of numbers that are powers of two. Each step reduces a `2^{k+1}` to `2^k` and `2^k`. Thus 16 is converted to 8 and 8. Examples ======== >>> from sympy.utilities.iterables import binary_partitions >>> for i in binary_partitions(5): ... print(i) ... [4, 1] [2, 2, 1] [2, 1, 1, 1] [1, 1, 1, 1, 1] References ========== .. [1] TAOCP 4, section 7.2.1.5, problem 64 """ from math import ceil, log power = int(2**(ceil(log(n, 2)))) acc = 0 partition = [] while power: if acc + power <= n: partition.append(power) acc += power power >>= 1 last_num = len(partition) - 1 - (n & 1) while last_num >= 0: yield partition if partition[last_num] == 2: partition[last_num] = 1 partition.append(1) last_num -= 1 continue partition.append(1) partition[last_num] >>= 1 x = partition[last_num + 1] = partition[last_num] last_num += 1 while x > 1: if x <= len(partition) - last_num - 1: del partition[-x + 1:] last_num += 1 partition[last_num] = x else: x >>= 1 yield [1]*n def has_dups(seq): """Return True if there are any duplicate elements in ``seq``. Examples ======== >>> from sympy import has_dups, Dict, Set >>> has_dups((1, 2, 1)) True >>> has_dups(range(3)) False >>> all(has_dups(c) is False for c in (set(), Set(), dict(), Dict())) True """ from sympy.core.containers import Dict from sympy.sets.sets import Set if isinstance(seq, (dict, set, Dict, Set)): return False unique = set() try: return any(True for s in seq if s in unique or unique.add(s)) except TypeError: return len(seq) != len(list(uniq(seq))) def has_variety(seq): """Return True if there are any different elements in ``seq``. Examples ======== >>> from sympy import has_variety >>> has_variety((1, 2, 1)) True >>> has_variety((1, 1, 1)) False """ for i, s in enumerate(seq): if i == 0: sentinel = s else: if s != sentinel: return True return False def uniq(seq, result=None): """ Yield unique elements from ``seq`` as an iterator. The second parameter ``result`` is used internally; it is not necessary to pass anything for this. Note: changing the sequence during iteration will raise a RuntimeError if the size of the sequence is known; if you pass an iterator and advance the iterator you will change the output of this routine but there will be no warning. Examples ======== >>> from sympy.utilities.iterables import uniq >>> dat = [1, 4, 1, 5, 4, 2, 1, 2] >>> type(uniq(dat)) in (list, tuple) False >>> list(uniq(dat)) [1, 4, 5, 2] >>> list(uniq(x for x in dat)) [1, 4, 5, 2] >>> list(uniq([[1], [2, 1], [1]])) [[1], [2, 1]] """ try: n = len(seq) except TypeError: n = None def check(): # check that size of seq did not change during iteration; # if n == None the object won't support size changing, e.g. # an iterator can't be changed if n is not None and len(seq) != n: raise RuntimeError('sequence changed size during iteration') try: seen = set() result = result or [] for i, s in enumerate(seq): if not (s in seen or seen.add(s)): yield s check() except TypeError: if s not in result: yield s check() result.append(s) if hasattr(seq, '__getitem__'): yield from uniq(seq[i + 1:], result) else: yield from uniq(seq, result) def generate_bell(n): """Return permutations of [0, 1, ..., n - 1] such that each permutation differs from the last by the exchange of a single pair of neighbors. The ``n!`` permutations are returned as an iterator. In order to obtain the next permutation from a random starting permutation, use the ``next_trotterjohnson`` method of the Permutation class (which generates the same sequence in a different manner). Examples ======== >>> from itertools import permutations >>> from sympy.utilities.iterables import generate_bell >>> from sympy import zeros, Matrix This is the sort of permutation used in the ringing of physical bells, and does not produce permutations in lexicographical order. Rather, the permutations differ from each other by exactly one inversion, and the position at which the swapping occurs varies periodically in a simple fashion. Consider the first few permutations of 4 elements generated by ``permutations`` and ``generate_bell``: >>> list(permutations(range(4)))[:5] [(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2)] >>> list(generate_bell(4))[:5] [(0, 1, 2, 3), (0, 1, 3, 2), (0, 3, 1, 2), (3, 0, 1, 2), (3, 0, 2, 1)] Notice how the 2nd and 3rd lexicographical permutations have 3 elements out of place whereas each "bell" permutation always has only two elements out of place relative to the previous permutation (and so the signature (+/-1) of a permutation is opposite of the signature of the previous permutation). How the position of inversion varies across the elements can be seen by tracing out where the largest number appears in the permutations: >>> m = zeros(4, 24) >>> for i, p in enumerate(generate_bell(4)): ... m[:, i] = Matrix([j - 3 for j in list(p)]) # make largest zero >>> m.print_nonzero('X') [XXX XXXXXX XXXXXX XXX] [XX XX XXXX XX XXXX XX XX] [X XXXX XX XXXX XX XXXX X] [ XXXXXX XXXXXX XXXXXX ] See Also ======== sympy.combinatorics.permutations.Permutation.next_trotterjohnson References ========== .. [1] https://en.wikipedia.org/wiki/Method_ringing .. [2] https://stackoverflow.com/questions/4856615/recursive-permutation/4857018 .. [3] http://programminggeeks.com/bell-algorithm-for-permutation/ .. [4] https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm .. [5] Generating involutions, derangements, and relatives by ECO Vincent Vajnovszki, DMTCS vol 1 issue 12, 2010 """ n = as_int(n) if n < 1: raise ValueError('n must be a positive integer') if n == 1: yield (0,) elif n == 2: yield (0, 1) yield (1, 0) elif n == 3: yield from [(0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)] else: m = n - 1 op = [0] + [-1]*m l = list(range(n)) while True: yield tuple(l) # find biggest element with op big = None, -1 # idx, value for i in range(n): if op[i] and l[i] > big[1]: big = i, l[i] i, _ = big if i is None: break # there are no ops left # swap it with neighbor in the indicated direction j = i + op[i] l[i], l[j] = l[j], l[i] op[i], op[j] = op[j], op[i] # if it landed at the end or if the neighbor in the same # direction is bigger then turn off op if j == 0 or j == m or l[j + op[j]] > l[j]: op[j] = 0 # any element bigger to the left gets +1 op for i in range(j): if l[i] > l[j]: op[i] = 1 # any element bigger to the right gets -1 op for i in range(j + 1, n): if l[i] > l[j]: op[i] = -1 def generate_involutions(n): """ Generates involutions. An involution is a permutation that when multiplied by itself equals the identity permutation. In this implementation the involutions are generated using Fixed Points. Alternatively, an involution can be considered as a permutation that does not contain any cycles with a length that is greater than two. Examples ======== >>> from sympy.utilities.iterables import generate_involutions >>> list(generate_involutions(3)) [(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)] >>> len(list(generate_involutions(4))) 10 References ========== .. [1] http://mathworld.wolfram.com/PermutationInvolution.html """ idx = list(range(n)) for p in permutations(idx): for i in idx: if p[p[i]] != i: break else: yield p def multiset_derangements(s): """Generate derangements of the elements of s *in place*. Examples ======== >>> from sympy.utilities.iterables import multiset_derangements, uniq Because the derangements of multisets (not sets) are generated in place, copies of the return value must be made if a collection of derangements is desired or else all values will be the same: >>> list(uniq([i for i in multiset_derangements('1233')])) [[None, None, None, None]] >>> [i.copy() for i in multiset_derangements('1233')] [['3', '3', '1', '2'], ['3', '3', '2', '1']] >>> [''.join(i) for i in multiset_derangements('1233')] ['3312', '3321'] """ from sympy.core.sorting import ordered # create multiset dictionary of hashable elements or else # remap elements to integers try: ms = multiset(s) except TypeError: # give each element a canonical integer value key = dict(enumerate(ordered(uniq(s)))) h = [] for si in s: for k in key: if key[k] == si: h.append(k) break for i in multiset_derangements(h): yield [key[j] for j in i] return mx = max(ms.values()) # max repetition of any element n = len(s) # the number of elements ## special cases # 1) one element has more than half the total cardinality of s: no # derangements are possible. if mx*2 > n: return # 2) all elements appear once: singletons if len(ms) == n: yield from _set_derangements(s) return # find the first element that is repeated the most to place # in the following two special cases where the selection # is unambiguous: either there are two elements with multiplicity # of mx or else there is only one with multiplicity mx for M in ms: if ms[M] == mx: break inonM = [i for i in range(n) if s[i] != M] # location of non-M iM = [i for i in range(n) if s[i] == M] # locations of M rv = [None]*n # 3) half are the same if 2*mx == n: # M goes into non-M locations for i in inonM: rv[i] = M # permutations of non-M go to M locations for p in multiset_permutations([s[i] for i in inonM]): for i, pi in zip(iM, p): rv[i] = pi yield rv # clean-up (and encourages proper use of routine) rv[:] = [None]*n return # 4) single repeat covers all but 1 of the non-repeats: # if there is one repeat then the multiset of the values # of ms would be {mx: 1, 1: n - mx}, i.e. there would # be n - mx + 1 values with the condition that n - 2*mx = 1 if n - 2*mx == 1 and len(ms.values()) == n - mx + 1: for i, i1 in enumerate(inonM): ifill = inonM[:i] + inonM[i+1:] for j in ifill: rv[j] = M for p in permutations([s[j] for j in ifill]): rv[i1] = s[i1] for j, pi in zip(iM, p): rv[j] = pi k = i1 for j in iM: rv[j], rv[k] = rv[k], rv[j] yield rv k = j # clean-up (and encourages proper use of routine) rv[:] = [None]*n return ## general case is handled with 3 helpers: # 1) `finish_derangements` will place the last two elements # which have arbitrary multiplicities, e.g. for multiset # {c: 3, a: 2, b: 2}, the last two elements are a and b # 2) `iopen` will tell where a given element can be placed # 3) `do` will recursively place elements into subsets of # valid locations def finish_derangements(): """Place the last two elements into the partially completed derangement, and yield the results. """ a = take[1][0] # penultimate element a_ct = take[1][1] b = take[0][0] # last element to be placed b_ct = take[0][1] # split the indexes of the not-already-assigned elemements of rv into # three categories forced_a = [] # positions which must have an a forced_b = [] # positions which must have a b open_free = [] # positions which could take either for i in range(len(s)): if rv[i] is None: if s[i] == a: forced_b.append(i) elif s[i] == b: forced_a.append(i) else: open_free.append(i) if len(forced_a) > a_ct or len(forced_b) > b_ct: # No derangement possible return for i in forced_a: rv[i] = a for i in forced_b: rv[i] = b for a_place in combinations(open_free, a_ct - len(forced_a)): for a_pos in a_place: rv[a_pos] = a for i in open_free: if rv[i] is None: # anything not in the subset is set to b rv[i] = b yield rv # Clean up/undo the final placements for i in open_free: rv[i] = None # additional cleanup - clear forced_a, forced_b for i in forced_a: rv[i] = None for i in forced_b: rv[i] = None def iopen(v): # return indices at which element v can be placed in rv: # locations which are not already occupied if that location # does not already contain v in the same location of s return [i for i in range(n) if rv[i] is None and s[i] != v] def do(j): if j == 1: # handle the last two elements (regardless of multiplicity) # with a special method yield from finish_derangements() else: # place the mx elements of M into a subset of places # into which it can be replaced M, mx = take[j] for i in combinations(iopen(M), mx): # place M for ii in i: rv[ii] = M # recursively place the next element yield from do(j - 1) # mark positions where M was placed as once again # open for placement of other elements for ii in i: rv[ii] = None # process elements in order of canonically decreasing multiplicity take = sorted(ms.items(), key=lambda x:(x[1], x[0])) yield from do(len(take) - 1) rv[:] = [None]*n def random_derangement(t, choice=None, strict=True): """Return a list of elements in which none are in the same positions as they were originally. If an element fills more than half of the positions then an error will be raised since no derangement is possible. To obtain a derangement of as many items as possible--with some of the most numerous remaining in their original positions--pass `strict=False`. To produce a pseudorandom derangment, pass a pseudorandom selector like `choice` (see below). Examples ======== >>> from sympy.utilities.iterables import random_derangement >>> t = 'SymPy: a CAS in pure Python' >>> d = random_derangement(t) >>> all(i != j for i, j in zip(d, t)) True A predictable result can be obtained by using a pseudorandom generator for the choice: >>> from sympy.core.random import seed, choice as c >>> seed(1) >>> d = [''.join(random_derangement(t, c)) for i in range(5)] >>> assert len(set(d)) != 1 # we got different values By reseeding, the same sequence can be obtained: >>> seed(1) >>> d2 = [''.join(random_derangement(t, c)) for i in range(5)] >>> assert d == d2 """ if choice is None: import secrets choice = secrets.choice def shuffle(rv): '''Knuth shuffle''' for i in range(len(rv) - 1, 0, -1): x = choice(rv[:i + 1]) j = rv.index(x) rv[i], rv[j] = rv[j], rv[i] def pick(rv, n): '''shuffle rv and return the first n values ''' shuffle(rv) return rv[:n] ms = multiset(t) tot = len(t) ms = sorted(ms.items(), key=lambda x: x[1]) # if there are not enough spaces for the most # plentiful element to move to then some of them # will have to stay in place M, mx = ms[-1] n = len(t) xs = 2*mx - tot if xs > 0: if strict: raise ValueError('no derangement possible') opts = [i for (i, c) in enumerate(t) if c == ms[-1][0]] pick(opts, xs) stay = sorted(opts[:xs]) rv = list(t) for i in reversed(stay): rv.pop(i) rv = random_derangement(rv, choice) for i in stay: rv.insert(i, ms[-1][0]) return ''.join(rv) if type(t) is str else rv # the normal derangement calculated from here if n == len(ms): # approx 1/3 will succeed rv = list(t) while True: shuffle(rv) if all(i != j for i,j in zip(rv, t)): break else: # general case rv = [None]*n while True: j = 0 while j > -len(ms): # do most numerous first j -= 1 e, c = ms[j] opts = [i for i in range(n) if rv[i] is None and t[i] != e] if len(opts) < c: for i in range(n): rv[i] = None break # try again pick(opts, c) for i in range(c): rv[opts[i]] = e else: return rv return rv def _set_derangements(s): """ yield derangements of items in ``s`` which are assumed to contain no repeated elements """ if len(s) < 2: return if len(s) == 2: yield [s[1], s[0]] return if len(s) == 3: yield [s[1], s[2], s[0]] yield [s[2], s[0], s[1]] return for p in permutations(s): if not any(i == j for i, j in zip(p, s)): yield list(p) def generate_derangements(s): """ Return unique derangements of the elements of iterable ``s``. Examples ======== >>> from sympy.utilities.iterables import generate_derangements >>> list(generate_derangements([0, 1, 2])) [[1, 2, 0], [2, 0, 1]] >>> list(generate_derangements([0, 1, 2, 2])) [[2, 2, 0, 1], [2, 2, 1, 0]] >>> list(generate_derangements([0, 1, 1])) [] See Also ======== sympy.functions.combinatorial.factorials.subfactorial """ if not has_dups(s): yield from _set_derangements(s) else: for p in multiset_derangements(s): yield list(p) def necklaces(n, k, free=False): """ A routine to generate necklaces that may (free=True) or may not (free=False) be turned over to be viewed. The "necklaces" returned are comprised of ``n`` integers (beads) with ``k`` different values (colors). Only unique necklaces are returned. Examples ======== >>> from sympy.utilities.iterables import necklaces, bracelets >>> def show(s, i): ... return ''.join(s[j] for j in i) The "unrestricted necklace" is sometimes also referred to as a "bracelet" (an object that can be turned over, a sequence that can be reversed) and the term "necklace" is used to imply a sequence that cannot be reversed. So ACB == ABC for a bracelet (rotate and reverse) while the two are different for a necklace since rotation alone cannot make the two sequences the same. (mnemonic: Bracelets can be viewed Backwards, but Not Necklaces.) >>> B = [show('ABC', i) for i in bracelets(3, 3)] >>> N = [show('ABC', i) for i in necklaces(3, 3)] >>> set(N) - set(B) {'ACB'} >>> list(necklaces(4, 2)) [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1), (0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)] >>> [show('.o', i) for i in bracelets(4, 2)] ['....', '...o', '..oo', '.o.o', '.ooo', 'oooo'] References ========== .. [1] http://mathworld.wolfram.com/Necklace.html """ return uniq(minlex(i, directed=not free) for i in variations(list(range(k)), n, repetition=True)) def bracelets(n, k): """Wrapper to necklaces to return a free (unrestricted) necklace.""" return necklaces(n, k, free=True) def generate_oriented_forest(n): """ This algorithm generates oriented forests. An oriented graph is a directed graph having no symmetric pair of directed edges. A forest is an acyclic graph, i.e., it has no cycles. A forest can also be described as a disjoint union of trees, which are graphs in which any two vertices are connected by exactly one simple path. Examples ======== >>> from sympy.utilities.iterables import generate_oriented_forest >>> list(generate_oriented_forest(4)) [[0, 1, 2, 3], [0, 1, 2, 2], [0, 1, 2, 1], [0, 1, 2, 0], \ [0, 1, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]] References ========== .. [1] T. Beyer and S.M. Hedetniemi: constant time generation of rooted trees, SIAM J. Computing Vol. 9, No. 4, November 1980 .. [2] https://stackoverflow.com/questions/1633833/oriented-forest-taocp-algorithm-in-python """ P = list(range(-1, n)) while True: yield P[1:] if P[n] > 0: P[n] = P[P[n]] else: for p in range(n - 1, 0, -1): if P[p] != 0: target = P[p] - 1 for q in range(p - 1, 0, -1): if P[q] == target: break offset = p - q for i in range(p, n + 1): P[i] = P[i - offset] break else: break def minlex(seq, directed=True, key=None): r""" Return the rotation of the sequence in which the lexically smallest elements appear first, e.g. `cba \rightarrow acb`. The sequence returned is a tuple, unless the input sequence is a string in which case a string is returned. If ``directed`` is False then the smaller of the sequence and the reversed sequence is returned, e.g. `cba \rightarrow abc`. If ``key`` is not None then it is used to extract a comparison key from each element in iterable. Examples ======== >>> from sympy.combinatorics.polyhedron import minlex >>> minlex((1, 2, 0)) (0, 1, 2) >>> minlex((1, 0, 2)) (0, 2, 1) >>> minlex((1, 0, 2), directed=False) (0, 1, 2) >>> minlex('11010011000', directed=True) '00011010011' >>> minlex('11010011000', directed=False) '00011001011' >>> minlex(('bb', 'aaa', 'c', 'a')) ('a', 'bb', 'aaa', 'c') >>> minlex(('bb', 'aaa', 'c', 'a'), key=len) ('c', 'a', 'bb', 'aaa') """ from sympy.functions.elementary.miscellaneous import Id if key is None: key = Id best = rotate_left(seq, least_rotation(seq, key=key)) if not directed: rseq = seq[::-1] rbest = rotate_left(rseq, least_rotation(rseq, key=key)) best = min(best, rbest, key=key) # Convert to tuple, unless we started with a string. return tuple(best) if not isinstance(seq, str) else best def runs(seq, op=gt): """Group the sequence into lists in which successive elements all compare the same with the comparison operator, ``op``: op(seq[i + 1], seq[i]) is True from all elements in a run. Examples ======== >>> from sympy.utilities.iterables import runs >>> from operator import ge >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2]) [[0, 1, 2], [2], [1, 4], [3], [2], [2]] >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2], op=ge) [[0, 1, 2, 2], [1, 4], [3], [2, 2]] """ cycles = [] seq = iter(seq) try: run = [next(seq)] except StopIteration: return [] while True: try: ei = next(seq) except StopIteration: break if op(ei, run[-1]): run.append(ei) continue else: cycles.append(run) run = [ei] if run: cycles.append(run) return cycles def kbins(l, k, ordered=None): """ Return sequence ``l`` partitioned into ``k`` bins. Examples ======== The default is to give the items in the same order, but grouped into k partitions without any reordering: >>> from sympy.utilities.iterables import kbins >>> for p in kbins(list(range(5)), 2): ... print(p) ... [[0], [1, 2, 3, 4]] [[0, 1], [2, 3, 4]] [[0, 1, 2], [3, 4]] [[0, 1, 2, 3], [4]] The ``ordered`` flag is either None (to give the simple partition of the elements) or is a 2 digit integer indicating whether the order of the bins and the order of the items in the bins matters. Given:: A = [[0], [1, 2]] B = [[1, 2], [0]] C = [[2, 1], [0]] D = [[0], [2, 1]] the following values for ``ordered`` have the shown meanings:: 00 means A == B == C == D 01 means A == B 10 means A == D 11 means A == A >>> for ordered_flag in [None, 0, 1, 10, 11]: ... print('ordered = %s' % ordered_flag) ... for p in kbins(list(range(3)), 2, ordered=ordered_flag): ... print(' %s' % p) ... ordered = None [[0], [1, 2]] [[0, 1], [2]] ordered = 0 [[0, 1], [2]] [[0, 2], [1]] [[0], [1, 2]] ordered = 1 [[0], [1, 2]] [[0], [2, 1]] [[1], [0, 2]] [[1], [2, 0]] [[2], [0, 1]] [[2], [1, 0]] ordered = 10 [[0, 1], [2]] [[2], [0, 1]] [[0, 2], [1]] [[1], [0, 2]] [[0], [1, 2]] [[1, 2], [0]] ordered = 11 [[0], [1, 2]] [[0, 1], [2]] [[0], [2, 1]] [[0, 2], [1]] [[1], [0, 2]] [[1, 0], [2]] [[1], [2, 0]] [[1, 2], [0]] [[2], [0, 1]] [[2, 0], [1]] [[2], [1, 0]] [[2, 1], [0]] See Also ======== partitions, multiset_partitions """ def partition(lista, bins): # EnricoGiampieri's partition generator from # https://stackoverflow.com/questions/13131491/ # partition-n-items-into-k-bins-in-python-lazily if len(lista) == 1 or bins == 1: yield [lista] elif len(lista) > 1 and bins > 1: for i in range(1, len(lista)): for part in partition(lista[i:], bins - 1): if len([lista[:i]] + part) == bins: yield [lista[:i]] + part if ordered is None: yield from partition(l, k) elif ordered == 11: for pl in multiset_permutations(l): pl = list(pl) yield from partition(pl, k) elif ordered == 00: yield from multiset_partitions(l, k) elif ordered == 10: for p in multiset_partitions(l, k): for perm in permutations(p): yield list(perm) elif ordered == 1: for kgot, p in partitions(len(l), k, size=True): if kgot != k: continue for li in multiset_permutations(l): rv = [] i = j = 0 li = list(li) for size, multiplicity in sorted(p.items()): for m in range(multiplicity): j = i + size rv.append(li[i: j]) i = j yield rv else: raise ValueError( 'ordered must be one of 00, 01, 10 or 11, not %s' % ordered) def permute_signs(t): """Return iterator in which the signs of non-zero elements of t are permuted. Examples ======== >>> from sympy.utilities.iterables import permute_signs >>> list(permute_signs((0, 1, 2))) [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2)] """ for signs in product(*[(1, -1)]*(len(t) - t.count(0))): signs = list(signs) yield type(t)([i*signs.pop() if i else i for i in t]) def signed_permutations(t): """Return iterator in which the signs of non-zero elements of t and the order of the elements are permuted. Examples ======== >>> from sympy.utilities.iterables import signed_permutations >>> list(signed_permutations((0, 1, 2))) [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2), (0, 2, 1), (0, -2, 1), (0, 2, -1), (0, -2, -1), (1, 0, 2), (-1, 0, 2), (1, 0, -2), (-1, 0, -2), (1, 2, 0), (-1, 2, 0), (1, -2, 0), (-1, -2, 0), (2, 0, 1), (-2, 0, 1), (2, 0, -1), (-2, 0, -1), (2, 1, 0), (-2, 1, 0), (2, -1, 0), (-2, -1, 0)] """ return (type(t)(i) for j in permutations(t) for i in permute_signs(j)) def rotations(s, dir=1): """Return a generator giving the items in s as list where each subsequent list has the items rotated to the left (default) or right (``dir=-1``) relative to the previous list. Examples ======== >>> from sympy import rotations >>> list(rotations([1,2,3])) [[1, 2, 3], [2, 3, 1], [3, 1, 2]] >>> list(rotations([1,2,3], -1)) [[1, 2, 3], [3, 1, 2], [2, 3, 1]] """ seq = list(s) for i in range(len(seq)): yield seq seq = rotate_left(seq, dir) def roundrobin(*iterables): """roundrobin recipe taken from itertools documentation: https://docs.python.org/3/library/itertools.html#recipes roundrobin('ABC', 'D', 'EF') --> A D E B F C Recipe credited to George Sakkis """ nexts = cycle(iter(it).__next__ for it in iterables) pending = len(iterables) while pending: try: for nxt in nexts: yield nxt() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) class NotIterable: """ Use this as mixin when creating a class which is not supposed to return true when iterable() is called on its instances because calling list() on the instance, for example, would result in an infinite loop. """ pass def iterable(i, exclude=(str, dict, NotIterable)): """ Return a boolean indicating whether ``i`` is SymPy iterable. True also indicates that the iterator is finite, e.g. you can call list(...) on the instance. When SymPy is working with iterables, it is almost always assuming that the iterable is not a string or a mapping, so those are excluded by default. If you want a pure Python definition, make exclude=None. To exclude multiple items, pass them as a tuple. You can also set the _iterable attribute to True or False on your class, which will override the checks here, including the exclude test. As a rule of thumb, some SymPy functions use this to check if they should recursively map over an object. If an object is technically iterable in the Python sense but does not desire this behavior (e.g., because its iteration is not finite, or because iteration might induce an unwanted computation), it should disable it by setting the _iterable attribute to False. See also: is_sequence Examples ======== >>> from sympy.utilities.iterables import iterable >>> from sympy import Tuple >>> things = [[1], (1,), set([1]), Tuple(1), (j for j in [1, 2]), {1:2}, '1', 1] >>> for i in things: ... print('%s %s' % (iterable(i), type(i))) True <... 'list'> True <... 'tuple'> True <... 'set'> True <class 'sympy.core.containers.Tuple'> True <... 'generator'> False <... 'dict'> False <... 'str'> False <... 'int'> >>> iterable({}, exclude=None) True >>> iterable({}, exclude=str) True >>> iterable("no", exclude=str) False """ if hasattr(i, '_iterable'): return i._iterable try: iter(i) except TypeError: return False if exclude: return not isinstance(i, exclude) return True def is_sequence(i, include=None): """ Return a boolean indicating whether ``i`` is a sequence in the SymPy sense. If anything that fails the test below should be included as being a sequence for your application, set 'include' to that object's type; multiple types should be passed as a tuple of types. Note: although generators can generate a sequence, they often need special handling to make sure their elements are captured before the generator is exhausted, so these are not included by default in the definition of a sequence. See also: iterable Examples ======== >>> from sympy.utilities.iterables import is_sequence >>> from types import GeneratorType >>> is_sequence([]) True >>> is_sequence(set()) False >>> is_sequence('abc') False >>> is_sequence('abc', include=str) True >>> generator = (c for c in 'abc') >>> is_sequence(generator) False >>> is_sequence(generator, include=(str, GeneratorType)) True """ return (hasattr(i, '__getitem__') and iterable(i) or bool(include) and isinstance(i, include)) @deprecated( """ Using postorder_traversal from the sympy.utilities.iterables submodule is deprecated. Instead, use postorder_traversal from the top-level sympy namespace, like sympy.postorder_traversal """, deprecated_since_version="1.10", active_deprecations_target="deprecated-traversal-functions-moved") def postorder_traversal(node, keys=None): from sympy.core.traversal import postorder_traversal as _postorder_traversal return _postorder_traversal(node, keys=keys) @deprecated( """ Using interactive_traversal from the sympy.utilities.iterables submodule is deprecated. Instead, use interactive_traversal from the top-level sympy namespace, like sympy.interactive_traversal """, deprecated_since_version="1.10", active_deprecations_target="deprecated-traversal-functions-moved") def interactive_traversal(expr): from sympy.interactive.traversal import interactive_traversal as _interactive_traversal return _interactive_traversal(expr) @deprecated( """ Importing default_sort_key from sympy.utilities.iterables is deprecated. Use from sympy import default_sort_key instead. """, deprecated_since_version="1.10", active_deprecations_target="deprecated-sympy-core-compatibility", ) def default_sort_key(*args, **kwargs): from sympy import default_sort_key as _default_sort_key return _default_sort_key(*args, **kwargs) @deprecated( """ Importing default_sort_key from sympy.utilities.iterables is deprecated. Use from sympy import default_sort_key instead. """, deprecated_since_version="1.10", active_deprecations_target="deprecated-sympy-core-compatibility", ) def ordered(*args, **kwargs): from sympy import ordered as _ordered return _ordered(*args, **kwargs)
7b6dbe113d4ae14cf6e13b39d9262ab1981d037bf931ac5a85e63256b2572dd8
""" A Printer for generating readable representation of most SymPy classes. """ from typing import Any, Dict as tDict from sympy.core import S, Rational, Pow, Basic, Mul, Number from sympy.core.mul import _keep_coeff from sympy.core.relational import Relational from sympy.core.sorting import default_sort_key from sympy.core.sympify import SympifyError from sympy.utilities.iterables import sift from .precedence import precedence, PRECEDENCE from .printer import Printer, print_function from mpmath.libmp import prec_to_dps, to_str as mlib_to_str class StrPrinter(Printer): printmethod = "_sympystr" _default_settings = { "order": None, "full_prec": "auto", "sympy_integers": False, "abbrev": False, "perm_cyclic": True, "min": None, "max": None, } # type: tDict[str, Any] _relationals = {} # type: tDict[str, str] def parenthesize(self, item, level, strict=False): if (precedence(item) < level) or ((not strict) and precedence(item) <= level): return "(%s)" % self._print(item) else: return self._print(item) def stringify(self, args, sep, level=0): return sep.join([self.parenthesize(item, level) for item in args]) def emptyPrinter(self, expr): if isinstance(expr, str): return expr elif isinstance(expr, Basic): return repr(expr) else: return str(expr) def _print_Add(self, expr, order=None): terms = self._as_ordered_terms(expr, order=order) prec = precedence(expr) l = [] for term in terms: t = self._print(term) if t.startswith('-') and not term.is_Add: sign = "-" t = t[1:] else: sign = "+" if precedence(term) < prec or term.is_Add: l.extend([sign, "(%s)" % t]) else: l.extend([sign, t]) sign = l.pop(0) if sign == '+': sign = "" return sign + ' '.join(l) def _print_BooleanTrue(self, expr): return "True" def _print_BooleanFalse(self, expr): return "False" def _print_Not(self, expr): return '~%s' %(self.parenthesize(expr.args[0],PRECEDENCE["Not"])) def _print_And(self, expr): args = list(expr.args) for j, i in enumerate(args): if isinstance(i, Relational) and ( i.canonical.rhs is S.NegativeInfinity): args.insert(0, args.pop(j)) return self.stringify(args, " & ", PRECEDENCE["BitwiseAnd"]) def _print_Or(self, expr): return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"]) def _print_Xor(self, expr): return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"]) def _print_AppliedPredicate(self, expr): return '%s(%s)' % ( self._print(expr.function), self.stringify(expr.arguments, ", ")) def _print_Basic(self, expr): l = [self._print(o) for o in expr.args] return expr.__class__.__name__ + "(%s)" % ", ".join(l) def _print_BlockMatrix(self, B): if B.blocks.shape == (1, 1): self._print(B.blocks[0, 0]) return self._print(B.blocks) def _print_Catalan(self, expr): return 'Catalan' def _print_ComplexInfinity(self, expr): return 'zoo' def _print_ConditionSet(self, s): args = tuple([self._print(i) for i in (s.sym, s.condition)]) if s.base_set is S.UniversalSet: return 'ConditionSet(%s, %s)' % args args += (self._print(s.base_set),) return 'ConditionSet(%s, %s, %s)' % args def _print_Derivative(self, expr): dexpr = expr.expr dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count] return 'Derivative(%s)' % ", ".join(map(lambda arg: self._print(arg), [dexpr] + dvars)) def _print_dict(self, d): keys = sorted(d.keys(), key=default_sort_key) items = [] for key in keys: item = "%s: %s" % (self._print(key), self._print(d[key])) items.append(item) return "{%s}" % ", ".join(items) def _print_Dict(self, expr): return self._print_dict(expr) def _print_RandomDomain(self, d): if hasattr(d, 'as_boolean'): return 'Domain: ' + self._print(d.as_boolean()) elif hasattr(d, 'set'): return ('Domain: ' + self._print(d.symbols) + ' in ' + self._print(d.set)) else: return 'Domain on ' + self._print(d.symbols) def _print_Dummy(self, expr): return '_' + expr.name def _print_EulerGamma(self, expr): return 'EulerGamma' def _print_Exp1(self, expr): return 'E' def _print_ExprCondPair(self, expr): return '(%s, %s)' % (self._print(expr.expr), self._print(expr.cond)) def _print_Function(self, expr): return expr.func.__name__ + "(%s)" % self.stringify(expr.args, ", ") def _print_GoldenRatio(self, expr): return 'GoldenRatio' def _print_Heaviside(self, expr): # Same as _print_Function but uses pargs to suppress default 1/2 for # 2nd args return expr.func.__name__ + "(%s)" % self.stringify(expr.pargs, ", ") def _print_TribonacciConstant(self, expr): return 'TribonacciConstant' def _print_ImaginaryUnit(self, expr): return 'I' def _print_Infinity(self, expr): return 'oo' def _print_Integral(self, expr): def _xab_tostr(xab): if len(xab) == 1: return self._print(xab[0]) else: return self._print((xab[0],) + tuple(xab[1:])) L = ', '.join([_xab_tostr(l) for l in expr.limits]) return 'Integral(%s, %s)' % (self._print(expr.function), L) def _print_Interval(self, i): fin = 'Interval{m}({a}, {b})' a, b, l, r = i.args if a.is_infinite and b.is_infinite: m = '' elif a.is_infinite and not r: m = '' elif b.is_infinite and not l: m = '' elif not l and not r: m = '' elif l and r: m = '.open' elif l: m = '.Lopen' else: m = '.Ropen' return fin.format(**{'a': a, 'b': b, 'm': m}) def _print_AccumulationBounds(self, i): return "AccumBounds(%s, %s)" % (self._print(i.min), self._print(i.max)) def _print_Inverse(self, I): return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"]) def _print_Lambda(self, obj): expr = obj.expr sig = obj.signature if len(sig) == 1 and sig[0].is_symbol: sig = sig[0] return "Lambda(%s, %s)" % (self._print(sig), self._print(expr)) def _print_LatticeOp(self, expr): args = sorted(expr.args, key=default_sort_key) return expr.func.__name__ + "(%s)" % ", ".join(self._print(arg) for arg in args) def _print_Limit(self, expr): e, z, z0, dir = expr.args if str(dir) == "+": return "Limit(%s, %s, %s)" % tuple(map(self._print, (e, z, z0))) else: return "Limit(%s, %s, %s, dir='%s')" % tuple(map(self._print, (e, z, z0, dir))) def _print_list(self, expr): return "[%s]" % self.stringify(expr, ", ") def _print_List(self, expr): return self._print_list(expr) def _print_MatrixBase(self, expr): return expr._format_str(self) def _print_MatrixElement(self, expr): return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + '[%s, %s]' % (self._print(expr.i), self._print(expr.j)) def _print_MatrixSlice(self, expr): def strslice(x, dim): x = list(x) if x[2] == 1: del x[2] if x[0] == 0: x[0] = '' if x[1] == dim: x[1] = '' return ':'.join(map(lambda arg: self._print(arg), x)) return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' + strslice(expr.rowslice, expr.parent.rows) + ', ' + strslice(expr.colslice, expr.parent.cols) + ']') def _print_DeferredVector(self, expr): return expr.name def _print_Mul(self, expr): prec = precedence(expr) # Check for unevaluated Mul. In this case we need to make sure the # identities are visible, multiple Rational factors are not combined # etc so we display in a straight-forward form that fully preserves all # args and their order. args = expr.args if args[0] is S.One or any( isinstance(a, Number) or a.is_Pow and all(ai.is_Integer for ai in a.args) for a in args[1:]): d, n = sift(args, lambda x: isinstance(x, Pow) and bool(x.exp.as_coeff_Mul()[0] < 0), binary=True) for i, di in enumerate(d): if di.exp.is_Number: e = -di.exp else: dargs = list(di.exp.args) dargs[0] = -dargs[0] e = Mul._from_args(dargs) d[i] = Pow(di.base, e, evaluate=False) if e - 1 else di.base pre = [] # don't parenthesize first factor if negative if n and not n[0].is_Add and n[0].could_extract_minus_sign(): pre = [self._print(n.pop(0))] nfactors = pre + [self.parenthesize(a, prec, strict=False) for a in n] if not nfactors: nfactors = ['1'] # don't parenthesize first of denominator unless singleton if len(d) > 1 and d[0].could_extract_minus_sign(): pre = [self._print(d.pop(0))] else: pre = [] dfactors = pre + [self.parenthesize(a, prec, strict=False) for a in d] n = '*'.join(nfactors) d = '*'.join(dfactors) if len(dfactors) > 1: return '%s/(%s)' % (n, d) elif dfactors: return '%s/%s' % (n, d) return n c, e = expr.as_coeff_Mul() if c < 0: expr = _keep_coeff(-c, e) sign = "-" else: sign = "" a = [] # items in the numerator b = [] # items that are in the denominator (if any) pow_paren = [] # Will collect all pow with more than one base element and exp = -1 if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: # use make_args in case expr was something like -x -> x args = Mul.make_args(expr) # Gather args for numerator/denominator def apow(i): b, e = i.as_base_exp() eargs = list(Mul.make_args(e)) if eargs[0] is S.NegativeOne: eargs = eargs[1:] else: eargs[0] = -eargs[0] e = Mul._from_args(eargs) if isinstance(i, Pow): return i.func(b, e, evaluate=False) return i.func(e, evaluate=False) for item in args: if (item.is_commutative and isinstance(item, Pow) and bool(item.exp.as_coeff_Mul()[0] < 0)): if item.exp is not S.NegativeOne: b.append(apow(item)) else: if (len(item.args[0].args) != 1 and isinstance(item.base, (Mul, Pow))): # To avoid situations like #14160 pow_paren.append(item) b.append(item.base) elif item.is_Rational and item is not S.Infinity: if item.p != 1: a.append(Rational(item.p)) if item.q != 1: b.append(Rational(item.q)) else: a.append(item) a = a or [S.One] a_str = [self.parenthesize(x, prec, strict=False) for x in a] b_str = [self.parenthesize(x, prec, strict=False) for x in b] # To parenthesize Pow with exp = -1 and having more than one Symbol for item in pow_paren: if item.base in b: b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] if not b: return sign + '*'.join(a_str) elif len(b) == 1: return sign + '*'.join(a_str) + "/" + b_str[0] else: return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str) def _print_MatMul(self, expr): c, m = expr.as_coeff_mmul() sign = "" if c.is_number: re, im = c.as_real_imag() if im.is_zero and re.is_negative: expr = _keep_coeff(-c, m) sign = "-" elif re.is_zero and im.is_negative: expr = _keep_coeff(-c, m) sign = "-" return sign + '*'.join( [self.parenthesize(arg, precedence(expr)) for arg in expr.args] ) def _print_ElementwiseApplyFunction(self, expr): return "{}.({})".format( expr.function, self._print(expr.expr), ) def _print_NaN(self, expr): return 'nan' def _print_NegativeInfinity(self, expr): return '-oo' def _print_Order(self, expr): if not expr.variables or all(p is S.Zero for p in expr.point): if len(expr.variables) <= 1: return 'O(%s)' % self._print(expr.expr) else: return 'O(%s)' % self.stringify((expr.expr,) + expr.variables, ', ', 0) else: return 'O(%s)' % self.stringify(expr.args, ', ', 0) def _print_Ordinal(self, expr): return expr.__str__() def _print_Cycle(self, expr): return expr.__str__() def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation, Cycle from sympy.utilities.exceptions import sympy_deprecation_warning perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: sympy_deprecation_warning( f""" Setting Permutation.print_cyclic is deprecated. Instead use init_printing(perm_cyclic={perm_cyclic}). """, deprecated_since_version="1.6", active_deprecations_target="deprecated-permutation-print_cyclic", stacklevel=7, ) else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: if not expr.size: return '()' # before taking Cycle notation, see if the last element is # a singleton and move it to the head of the string s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):] last = s.rfind('(') if not last == 0 and ',' not in s[last:]: s = s[last:] + s[:last] s = s.replace(',', '') return s else: s = expr.support() if not s: if expr.size < 5: return 'Permutation(%s)' % self._print(expr.array_form) return 'Permutation([], size=%s)' % self._print(expr.size) trim = self._print(expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size) use = full = self._print(expr.array_form) if len(trim) < len(full): use = trim return 'Permutation(%s)' % use def _print_Subs(self, obj): expr, old, new = obj.args if len(obj.point) == 1: old = old[0] new = new[0] return "Subs(%s, %s, %s)" % ( self._print(expr), self._print(old), self._print(new)) def _print_TensorIndex(self, expr): return expr._print() def _print_TensorHead(self, expr): return expr._print() def _print_Tensor(self, expr): return expr._print() def _print_TensMul(self, expr): # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)" sign, args = expr._get_args_for_traditional_printer() return sign + "*".join( [self.parenthesize(arg, precedence(expr)) for arg in args] ) def _print_TensAdd(self, expr): return expr._print() def _print_ArraySymbol(self, expr): return self._print(expr.name) def _print_ArrayElement(self, expr): return "%s[%s]" % ( self.parenthesize(expr.name, PRECEDENCE["Func"], True), ", ".join([self._print(i) for i in expr.indices])) def _print_PermutationGroup(self, expr): p = [' %s' % self._print(a) for a in expr.args] return 'PermutationGroup([\n%s])' % ',\n'.join(p) def _print_Pi(self, expr): return 'pi' def _print_PolyRing(self, ring): return "Polynomial ring in %s over %s with %s order" % \ (", ".join(map(lambda rs: self._print(rs), ring.symbols)), self._print(ring.domain), self._print(ring.order)) def _print_FracField(self, field): return "Rational function field in %s over %s with %s order" % \ (", ".join(map(lambda fs: self._print(fs), field.symbols)), self._print(field.domain), self._print(field.order)) def _print_FreeGroupElement(self, elm): return elm.__str__() def _print_GaussianElement(self, poly): return "(%s + %s*I)" % (poly.x, poly.y) def _print_PolyElement(self, poly): return poly.str(self, PRECEDENCE, "%s**%s", "*") def _print_FracElement(self, frac): if frac.denom == 1: return self._print(frac.numer) else: numer = self.parenthesize(frac.numer, PRECEDENCE["Mul"], strict=True) denom = self.parenthesize(frac.denom, PRECEDENCE["Atom"], strict=True) return numer + "/" + denom def _print_Poly(self, expr): ATOM_PREC = PRECEDENCE["Atom"] - 1 terms, gens = [], [ self.parenthesize(s, ATOM_PREC) for s in expr.gens ] for monom, coeff in expr.terms(): s_monom = [] for i, e in enumerate(monom): if e > 0: if e == 1: s_monom.append(gens[i]) else: s_monom.append(gens[i] + "**%d" % e) s_monom = "*".join(s_monom) if coeff.is_Add: if s_monom: s_coeff = "(" + self._print(coeff) + ")" else: s_coeff = self._print(coeff) else: if s_monom: if coeff is S.One: terms.extend(['+', s_monom]) continue if coeff is S.NegativeOne: terms.extend(['-', s_monom]) continue s_coeff = self._print(coeff) if not s_monom: s_term = s_coeff else: s_term = s_coeff + "*" + s_monom if s_term.startswith('-'): terms.extend(['-', s_term[1:]]) else: terms.extend(['+', s_term]) if terms[0] in ('-', '+'): modifier = terms.pop(0) if modifier == '-': terms[0] = '-' + terms[0] format = expr.__class__.__name__ + "(%s, %s" from sympy.polys.polyerrors import PolynomialError try: format += ", modulus=%s" % expr.get_modulus() except PolynomialError: format += ", domain='%s'" % expr.get_domain() format += ")" for index, item in enumerate(gens): if len(item) > 2 and (item[:1] == "(" and item[len(item) - 1:] == ")"): gens[index] = item[1:len(item) - 1] return format % (' '.join(terms), ', '.join(gens)) def _print_UniversalSet(self, p): return 'UniversalSet' def _print_AlgebraicNumber(self, expr): if expr.is_aliased: return self._print(expr.as_poly().as_expr()) else: return self._print(expr.as_expr()) def _print_Pow(self, expr, rational=False): """Printing helper function for ``Pow`` Parameters ========== rational : bool, optional If ``True``, it will not attempt printing ``sqrt(x)`` or ``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)`` instead. See examples for additional details Examples ======== >>> from sympy import sqrt, StrPrinter >>> from sympy.abc import x How ``rational`` keyword works with ``sqrt``: >>> printer = StrPrinter() >>> printer._print_Pow(sqrt(x), rational=True) 'x**(1/2)' >>> printer._print_Pow(sqrt(x), rational=False) 'sqrt(x)' >>> printer._print_Pow(1/sqrt(x), rational=True) 'x**(-1/2)' >>> printer._print_Pow(1/sqrt(x), rational=False) '1/sqrt(x)' Notes ===== ``sqrt(x)`` is canonicalized as ``Pow(x, S.Half)`` in SymPy, so there is no need of defining a separate printer for ``sqrt``. Instead, it should be handled here as well. """ PREC = precedence(expr) if expr.exp is S.Half and not rational: return "sqrt(%s)" % self._print(expr.base) if expr.is_commutative: if -expr.exp is S.Half and not rational: # Note: Don't test "expr.exp == -S.Half" here, because that will # match -0.5, which we don't want. return "%s/sqrt(%s)" % tuple(map(lambda arg: self._print(arg), (S.One, expr.base))) if expr.exp is -S.One: # Similarly to the S.Half case, don't test with "==" here. return '%s/%s' % (self._print(S.One), self.parenthesize(expr.base, PREC, strict=False)) e = self.parenthesize(expr.exp, PREC, strict=False) if self.printmethod == '_sympyrepr' and expr.exp.is_Rational and expr.exp.q != 1: # the parenthesized exp should be '(Rational(a, b))' so strip parens, # but just check to be sure. if e.startswith('(Rational'): return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e[1:-1]) return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e) def _print_UnevaluatedExpr(self, expr): return self._print(expr.args[0]) def _print_MatPow(self, expr): PREC = precedence(expr) return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), self.parenthesize(expr.exp, PREC, strict=False)) def _print_Integer(self, expr): if self._settings.get("sympy_integers", False): return "S(%s)" % (expr) return str(expr.p) def _print_Integers(self, expr): return 'Integers' def _print_Naturals(self, expr): return 'Naturals' def _print_Naturals0(self, expr): return 'Naturals0' def _print_Rationals(self, expr): return 'Rationals' def _print_Reals(self, expr): return 'Reals' def _print_Complexes(self, expr): return 'Complexes' def _print_EmptySet(self, expr): return 'EmptySet' def _print_EmptySequence(self, expr): return 'EmptySequence' def _print_int(self, expr): return str(expr) def _print_mpz(self, expr): return str(expr) def _print_Rational(self, expr): if expr.q == 1: return str(expr.p) else: if self._settings.get("sympy_integers", False): return "S(%s)/%s" % (expr.p, expr.q) return "%s/%s" % (expr.p, expr.q) def _print_PythonRational(self, expr): if expr.q == 1: return str(expr.p) else: return "%d/%d" % (expr.p, expr.q) def _print_Fraction(self, expr): if expr.denominator == 1: return str(expr.numerator) else: return "%s/%s" % (expr.numerator, expr.denominator) def _print_mpq(self, expr): if expr.denominator == 1: return str(expr.numerator) else: return "%s/%s" % (expr.numerator, expr.denominator) def _print_Float(self, expr): prec = expr._prec if prec < 5: dps = 0 else: dps = prec_to_dps(expr._prec) if self._settings["full_prec"] is True: strip = False elif self._settings["full_prec"] is False: strip = True elif self._settings["full_prec"] == "auto": strip = self._print_level > 1 low = self._settings["min"] if "min" in self._settings else None high = self._settings["max"] if "max" in self._settings else None rv = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high) if rv.startswith('-.0'): rv = '-0.' + rv[3:] elif rv.startswith('.0'): rv = '0.' + rv[2:] if rv.startswith('+'): # e.g., +inf -> inf rv = rv[1:] return rv def _print_Relational(self, expr): charmap = { "==": "Eq", "!=": "Ne", ":=": "Assignment", '+=': "AddAugmentedAssignment", "-=": "SubAugmentedAssignment", "*=": "MulAugmentedAssignment", "/=": "DivAugmentedAssignment", "%=": "ModAugmentedAssignment", } if expr.rel_op in charmap: return '%s(%s, %s)' % (charmap[expr.rel_op], self._print(expr.lhs), self._print(expr.rhs)) return '%s %s %s' % (self.parenthesize(expr.lhs, precedence(expr)), self._relationals.get(expr.rel_op) or expr.rel_op, self.parenthesize(expr.rhs, precedence(expr))) def _print_ComplexRootOf(self, expr): return "CRootOf(%s, %d)" % (self._print_Add(expr.expr, order='lex'), expr.index) def _print_RootSum(self, expr): args = [self._print_Add(expr.expr, order='lex')] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) return "RootSum(%s)" % ", ".join(args) def _print_GroebnerBasis(self, basis): cls = basis.__class__.__name__ exprs = [self._print_Add(arg, order=basis.order) for arg in basis.exprs] exprs = "[%s]" % ", ".join(exprs) gens = [ self._print(gen) for gen in basis.gens ] domain = "domain='%s'" % self._print(basis.domain) order = "order='%s'" % self._print(basis.order) args = [exprs] + gens + [domain, order] return "%s(%s)" % (cls, ", ".join(args)) def _print_set(self, s): items = sorted(s, key=default_sort_key) args = ', '.join(self._print(item) for item in items) if not args: return "set()" return '{%s}' % args def _print_FiniteSet(self, s): from sympy.sets.sets import FiniteSet items = sorted(s, key=default_sort_key) args = ', '.join(self._print(item) for item in items) if any(item.has(FiniteSet) for item in items): return 'FiniteSet({})'.format(args) return '{{{}}}'.format(args) def _print_Partition(self, s): items = sorted(s, key=default_sort_key) args = ', '.join(self._print(arg) for arg in items) return 'Partition({})'.format(args) def _print_frozenset(self, s): if not s: return "frozenset()" return "frozenset(%s)" % self._print_set(s) def _print_Sum(self, expr): def _xab_tostr(xab): if len(xab) == 1: return self._print(xab[0]) else: return self._print((xab[0],) + tuple(xab[1:])) L = ', '.join([_xab_tostr(l) for l in expr.limits]) return 'Sum(%s, %s)' % (self._print(expr.function), L) def _print_Symbol(self, expr): return expr.name _print_MatrixSymbol = _print_Symbol _print_RandomSymbol = _print_Symbol def _print_Identity(self, expr): return "I" def _print_ZeroMatrix(self, expr): return "0" def _print_OneMatrix(self, expr): return "1" def _print_Predicate(self, expr): return "Q.%s" % expr.name def _print_str(self, expr): return str(expr) def _print_tuple(self, expr): if len(expr) == 1: return "(%s,)" % self._print(expr[0]) else: return "(%s)" % self.stringify(expr, ", ") def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_Transpose(self, T): return "%s.T" % self.parenthesize(T.arg, PRECEDENCE["Pow"]) def _print_Uniform(self, expr): return "Uniform(%s, %s)" % (self._print(expr.a), self._print(expr.b)) def _print_Quantity(self, expr): if self._settings.get("abbrev", False): return "%s" % expr.abbrev return "%s" % expr.name def _print_Quaternion(self, expr): s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args] a = [s[0]] + [i+"*"+j for i, j in zip(s[1:], "ijk")] return " + ".join(a) def _print_Dimension(self, expr): return str(expr) def _print_Wild(self, expr): return expr.name + '_' def _print_WildFunction(self, expr): return expr.name + '_' def _print_WildDot(self, expr): return expr.name def _print_WildPlus(self, expr): return expr.name def _print_WildStar(self, expr): return expr.name def _print_Zero(self, expr): if self._settings.get("sympy_integers", False): return "S(0)" return "0" def _print_DMP(self, p): try: if p.ring is not None: # TODO incorporate order return self._print(p.ring.to_sympy(p)) except SympifyError: pass cls = p.__class__.__name__ rep = self._print(p.rep) dom = self._print(p.dom) ring = self._print(p.ring) return "%s(%s, %s, %s)" % (cls, rep, dom, ring) def _print_DMF(self, expr): return self._print_DMP(expr) def _print_Object(self, obj): return 'Object("%s")' % obj.name def _print_IdentityMorphism(self, morphism): return 'IdentityMorphism(%s)' % morphism.domain def _print_NamedMorphism(self, morphism): return 'NamedMorphism(%s, %s, "%s")' % \ (morphism.domain, morphism.codomain, morphism.name) def _print_Category(self, category): return 'Category("%s")' % category.name def _print_Manifold(self, manifold): return manifold.name.name def _print_Patch(self, patch): return patch.name.name def _print_CoordSystem(self, coords): return coords.name.name def _print_BaseScalarField(self, field): return field._coord_sys.symbols[field._index].name def _print_BaseVectorField(self, field): return 'e_%s' % field._coord_sys.symbols[field._index].name def _print_Differential(self, diff): field = diff._form_field if hasattr(field, '_coord_sys'): return 'd%s' % field._coord_sys.symbols[field._index].name else: return 'd(%s)' % self._print(field) def _print_Tr(self, expr): #TODO : Handle indices return "%s(%s)" % ("Tr", self._print(expr.args[0])) def _print_Str(self, s): return self._print(s.name) def _print_AppliedBinaryRelation(self, expr): rel = expr.function return '%s(%s, %s)' % (self._print(rel), self._print(expr.lhs), self._print(expr.rhs)) @print_function(StrPrinter) def sstr(expr, **settings): """Returns the expression as a string. For large expressions where speed is a concern, use the setting order='none'. If abbrev=True setting is used then units are printed in abbreviated form. Examples ======== >>> from sympy import symbols, Eq, sstr >>> a, b = symbols('a b') >>> sstr(Eq(a + b, 0)) 'Eq(a + b, 0)' """ p = StrPrinter(settings) s = p.doprint(expr) return s class StrReprPrinter(StrPrinter): """(internal) -- see sstrrepr""" def _print_str(self, s): return repr(s) def _print_Str(self, s): # Str does not to be printed same as str here return "%s(%s)" % (s.__class__.__name__, self._print(s.name)) @print_function(StrReprPrinter) def sstrrepr(expr, **settings): """return expr in mixed str/repr form i.e. strings are returned in repr form with quotes, and everything else is returned in str form. This function could be useful for hooking into sys.displayhook """ p = StrReprPrinter(settings) s = p.doprint(expr) return s
202c50f1fd9b9a9a5ea6514e25e687cc63a95226f351510cb6866e46067888f8
""" A Printer which converts an expression into its LaTeX equivalent. """ from __future__ import annotations from typing import Any, Callable, TYPE_CHECKING import itertools from sympy.core import Add, Float, Mod, Mul, Number, S, Symbol, Expr from sympy.core.alphabets import greeks from sympy.core.containers import Tuple from sympy.core.function import Function, AppliedUndef, Derivative from sympy.core.operations import AssocOp from sympy.core.power import Pow from sympy.core.sorting import default_sort_key from sympy.core.sympify import SympifyError from sympy.logic.boolalg import true, BooleanTrue, BooleanFalse from sympy.tensor.array import NDimArray # sympy.printing imports from sympy.printing.precedence import precedence_traditional from sympy.printing.printer import Printer, print_function from sympy.printing.conventions import split_super_sub, requires_partial from sympy.printing.precedence import precedence, PRECEDENCE from mpmath.libmp.libmpf import prec_to_dps, to_str as mlib_to_str from sympy.utilities.iterables import has_variety, sift import re if TYPE_CHECKING: from sympy.vector.basisdependent import BasisDependent # Hand-picked functions which can be used directly in both LaTeX and MathJax # Complete list at # https://docs.mathjax.org/en/latest/tex.html#supported-latex-commands # This variable only contains those functions which SymPy uses. accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec', 'csc', 'cot', 'coth', 're', 'im', 'frac', 'root', 'arg', ] tex_greek_dictionary = { 'Alpha': r'\mathrm{A}', 'Beta': r'\mathrm{B}', 'Gamma': r'\Gamma', 'Delta': r'\Delta', 'Epsilon': r'\mathrm{E}', 'Zeta': r'\mathrm{Z}', 'Eta': r'\mathrm{H}', 'Theta': r'\Theta', 'Iota': r'\mathrm{I}', 'Kappa': r'\mathrm{K}', 'Lambda': r'\Lambda', 'Mu': r'\mathrm{M}', 'Nu': r'\mathrm{N}', 'Xi': r'\Xi', 'omicron': 'o', 'Omicron': r'\mathrm{O}', 'Pi': r'\Pi', 'Rho': r'\mathrm{P}', 'Sigma': r'\Sigma', 'Tau': r'\mathrm{T}', 'Upsilon': r'\Upsilon', 'Phi': r'\Phi', 'Chi': r'\mathrm{X}', 'Psi': r'\Psi', 'Omega': r'\Omega', 'lamda': r'\lambda', 'Lamda': r'\Lambda', 'khi': r'\chi', 'Khi': r'\mathrm{X}', 'varepsilon': r'\varepsilon', 'varkappa': r'\varkappa', 'varphi': r'\varphi', 'varpi': r'\varpi', 'varrho': r'\varrho', 'varsigma': r'\varsigma', 'vartheta': r'\vartheta', } other_symbols = {'aleph', 'beth', 'daleth', 'gimel', 'ell', 'eth', 'hbar', 'hslash', 'mho', 'wp'} # Variable name modifiers modifier_dict: dict[str, Callable[[str], str]] = { # Accents 'mathring': lambda s: r'\mathring{'+s+r'}', 'ddddot': lambda s: r'\ddddot{'+s+r'}', 'dddot': lambda s: r'\dddot{'+s+r'}', 'ddot': lambda s: r'\ddot{'+s+r'}', 'dot': lambda s: r'\dot{'+s+r'}', 'check': lambda s: r'\check{'+s+r'}', 'breve': lambda s: r'\breve{'+s+r'}', 'acute': lambda s: r'\acute{'+s+r'}', 'grave': lambda s: r'\grave{'+s+r'}', 'tilde': lambda s: r'\tilde{'+s+r'}', 'hat': lambda s: r'\hat{'+s+r'}', 'bar': lambda s: r'\bar{'+s+r'}', 'vec': lambda s: r'\vec{'+s+r'}', 'prime': lambda s: "{"+s+"}'", 'prm': lambda s: "{"+s+"}'", # Faces 'bold': lambda s: r'\boldsymbol{'+s+r'}', 'bm': lambda s: r'\boldsymbol{'+s+r'}', 'cal': lambda s: r'\mathcal{'+s+r'}', 'scr': lambda s: r'\mathscr{'+s+r'}', 'frak': lambda s: r'\mathfrak{'+s+r'}', # Brackets 'norm': lambda s: r'\left\|{'+s+r'}\right\|', 'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle', 'abs': lambda s: r'\left|{'+s+r'}\right|', 'mag': lambda s: r'\left|{'+s+r'}\right|', } greek_letters_set = frozenset(greeks) _between_two_numbers_p = ( re.compile(r'[0-9][} ]*$'), # search re.compile(r'[0-9]'), # match ) def latex_escape(s: str) -> str: """ Escape a string such that latex interprets it as plaintext. We cannot use verbatim easily with mathjax, so escaping is easier. Rules from https://tex.stackexchange.com/a/34586/41112. """ s = s.replace('\\', r'\textbackslash') for c in '&%$#_{}': s = s.replace(c, '\\' + c) s = s.replace('~', r'\textasciitilde') s = s.replace('^', r'\textasciicircum') return s class LatexPrinter(Printer): printmethod = "_latex" _default_settings: dict[str, Any] = { "full_prec": False, "fold_frac_powers": False, "fold_func_brackets": False, "fold_short_frac": None, "inv_trig_style": "abbreviated", "itex": False, "ln_notation": False, "long_frac_ratio": None, "mat_delim": "[", "mat_str": None, "mode": "plain", "mul_symbol": None, "order": None, "symbol_names": {}, "root_notation": True, "mat_symbol_style": "plain", "imaginary_unit": "i", "gothic_re_im": False, "decimal_separator": "period", "perm_cyclic": True, "parenthesize_super": True, "min": None, "max": None, "diff_operator": "d", } def __init__(self, settings=None): Printer.__init__(self, settings) if 'mode' in self._settings: valid_modes = ['inline', 'plain', 'equation', 'equation*'] if self._settings['mode'] not in valid_modes: raise ValueError("'mode' must be one of 'inline', 'plain', " "'equation' or 'equation*'") if self._settings['fold_short_frac'] is None and \ self._settings['mode'] == 'inline': self._settings['fold_short_frac'] = True mul_symbol_table = { None: r" ", "ldot": r" \,.\, ", "dot": r" \cdot ", "times": r" \times " } try: self._settings['mul_symbol_latex'] = \ mul_symbol_table[self._settings['mul_symbol']] except KeyError: self._settings['mul_symbol_latex'] = \ self._settings['mul_symbol'] try: self._settings['mul_symbol_latex_numbers'] = \ mul_symbol_table[self._settings['mul_symbol'] or 'dot'] except KeyError: if (self._settings['mul_symbol'].strip() in ['', ' ', '\\', '\\,', '\\:', '\\;', '\\quad']): self._settings['mul_symbol_latex_numbers'] = \ mul_symbol_table['dot'] else: self._settings['mul_symbol_latex_numbers'] = \ self._settings['mul_symbol'] self._delim_dict = {'(': ')', '[': ']'} imaginary_unit_table = { None: r"i", "i": r"i", "ri": r"\mathrm{i}", "ti": r"\text{i}", "j": r"j", "rj": r"\mathrm{j}", "tj": r"\text{j}", } imag_unit = self._settings['imaginary_unit'] self._settings['imaginary_unit_latex'] = imaginary_unit_table.get(imag_unit, imag_unit) diff_operator_table = { None: r"d", "d": r"d", "rd": r"\mathrm{d}", "td": r"\text{d}", } diff_operator = self._settings['diff_operator'] self._settings["diff_operator_latex"] = diff_operator_table.get(diff_operator, diff_operator) def _add_parens(self, s) -> str: return r"\left({}\right)".format(s) # TODO: merge this with the above, which requires a lot of test changes def _add_parens_lspace(self, s) -> str: return r"\left( {}\right)".format(s) def parenthesize(self, item, level, is_neg=False, strict=False) -> str: prec_val = precedence_traditional(item) if is_neg and strict: return self._add_parens(self._print(item)) if (prec_val < level) or ((not strict) and prec_val <= level): return self._add_parens(self._print(item)) else: return self._print(item) def parenthesize_super(self, s): """ Protect superscripts in s If the parenthesize_super option is set, protect with parentheses, else wrap in braces. """ if "^" in s: if self._settings['parenthesize_super']: return self._add_parens(s) else: return "{{{}}}".format(s) return s def doprint(self, expr) -> str: tex = Printer.doprint(self, expr) if self._settings['mode'] == 'plain': return tex elif self._settings['mode'] == 'inline': return r"$%s$" % tex elif self._settings['itex']: return r"$$%s$$" % tex else: env_str = self._settings['mode'] return r"\begin{%s}%s\end{%s}" % (env_str, tex, env_str) def _needs_brackets(self, expr) -> bool: """ Returns True if the expression needs to be wrapped in brackets when printed, False otherwise. For example: a + b => True; a => False; 10 => False; -10 => True. """ return not ((expr.is_Integer and expr.is_nonnegative) or (expr.is_Atom and (expr is not S.NegativeOne and expr.is_Rational is False))) def _needs_function_brackets(self, expr) -> bool: """ Returns True if the expression needs to be wrapped in brackets when passed as an argument to a function, False otherwise. This is a more liberal version of _needs_brackets, in that many expressions which need to be wrapped in brackets when added/subtracted/raised to a power do not need them when passed to a function. Such an example is a*b. """ if not self._needs_brackets(expr): return False else: # Muls of the form a*b*c... can be folded if expr.is_Mul and not self._mul_is_clean(expr): return True # Pows which don't need brackets can be folded elif expr.is_Pow and not self._pow_is_clean(expr): return True # Add and Function always need brackets elif expr.is_Add or expr.is_Function: return True else: return False def _needs_mul_brackets(self, expr, first=False, last=False) -> bool: """ Returns True if the expression needs to be wrapped in brackets when printed as part of a Mul, False otherwise. This is True for Add, but also for some container objects that would not need brackets when appearing last in a Mul, e.g. an Integral. ``last=True`` specifies that this expr is the last to appear in a Mul. ``first=True`` specifies that this expr is the first to appear in a Mul. """ from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.integrals.integrals import Integral if expr.is_Mul: if not first and expr.could_extract_minus_sign(): return True elif precedence_traditional(expr) < PRECEDENCE["Mul"]: return True elif expr.is_Relational: return True if expr.is_Piecewise: return True if any(expr.has(x) for x in (Mod,)): return True if (not last and any(expr.has(x) for x in (Integral, Product, Sum))): return True return False def _needs_add_brackets(self, expr) -> bool: """ Returns True if the expression needs to be wrapped in brackets when printed as part of an Add, False otherwise. This is False for most things. """ if expr.is_Relational: return True if any(expr.has(x) for x in (Mod,)): return True if expr.is_Add: return True return False def _mul_is_clean(self, expr) -> bool: for arg in expr.args: if arg.is_Function: return False return True def _pow_is_clean(self, expr) -> bool: return not self._needs_brackets(expr.base) def _do_exponent(self, expr: str, exp): if exp is not None: return r"\left(%s\right)^{%s}" % (expr, exp) else: return expr def _print_Basic(self, expr): name = self._deal_with_super_sub(expr.__class__.__name__) if expr.args: ls = [self._print(o) for o in expr.args] s = r"\operatorname{{{}}}\left({}\right)" return s.format(name, ", ".join(ls)) else: return r"\text{{{}}}".format(name) def _print_bool(self, e: bool | BooleanTrue | BooleanFalse): return r"\text{%s}" % e _print_BooleanTrue = _print_bool _print_BooleanFalse = _print_bool def _print_NoneType(self, e): return r"\text{%s}" % e def _print_Add(self, expr, order=None): terms = self._as_ordered_terms(expr, order=order) tex = "" for i, term in enumerate(terms): if i == 0: pass elif term.could_extract_minus_sign(): tex += " - " term = -term else: tex += " + " term_tex = self._print(term) if self._needs_add_brackets(term): term_tex = r"\left(%s\right)" % term_tex tex += term_tex return tex def _print_Cycle(self, expr): from sympy.combinatorics.permutations import Permutation if expr.size == 0: return r"\left( \right)" expr = Permutation(expr) expr_perm = expr.cyclic_form siz = expr.size if expr.array_form[-1] == siz - 1: expr_perm = expr_perm + [[siz - 1]] term_tex = '' for i in expr_perm: term_tex += str(i).replace(',', r"\;") term_tex = term_tex.replace('[', r"\left( ") term_tex = term_tex.replace(']', r"\right)") return term_tex def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation from sympy.utilities.exceptions import sympy_deprecation_warning perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: sympy_deprecation_warning( f""" Setting Permutation.print_cyclic is deprecated. Instead use init_printing(perm_cyclic={perm_cyclic}). """, deprecated_since_version="1.6", active_deprecations_target="deprecated-permutation-print_cyclic", stacklevel=8, ) else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: return self._print_Cycle(expr) if expr.size == 0: return r"\left( \right)" lower = [self._print(arg) for arg in expr.array_form] upper = [self._print(arg) for arg in range(len(lower))] row1 = " & ".join(upper) row2 = " & ".join(lower) mat = r" \\ ".join((row1, row2)) return r"\begin{pmatrix} %s \end{pmatrix}" % mat def _print_AppliedPermutation(self, expr): perm, var = expr.args return r"\sigma_{%s}(%s)" % (self._print(perm), self._print(var)) def _print_Float(self, expr): # Based off of that in StrPrinter dps = prec_to_dps(expr._prec) strip = False if self._settings['full_prec'] else True low = self._settings["min"] if "min" in self._settings else None high = self._settings["max"] if "max" in self._settings else None str_real = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high) # Must always have a mul symbol (as 2.5 10^{20} just looks odd) # thus we use the number separator separator = self._settings['mul_symbol_latex_numbers'] if 'e' in str_real: (mant, exp) = str_real.split('e') if exp[0] == '+': exp = exp[1:] if self._settings['decimal_separator'] == 'comma': mant = mant.replace('.','{,}') return r"%s%s10^{%s}" % (mant, separator, exp) elif str_real == "+inf": return r"\infty" elif str_real == "-inf": return r"- \infty" else: if self._settings['decimal_separator'] == 'comma': str_real = str_real.replace('.','{,}') return str_real def _print_Cross(self, expr): vec1 = expr._expr1 vec2 = expr._expr2 return r"%s \times %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']), self.parenthesize(vec2, PRECEDENCE['Mul'])) def _print_Curl(self, expr): vec = expr._expr return r"\nabla\times %s" % self.parenthesize(vec, PRECEDENCE['Mul']) def _print_Divergence(self, expr): vec = expr._expr return r"\nabla\cdot %s" % self.parenthesize(vec, PRECEDENCE['Mul']) def _print_Dot(self, expr): vec1 = expr._expr1 vec2 = expr._expr2 return r"%s \cdot %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']), self.parenthesize(vec2, PRECEDENCE['Mul'])) def _print_Gradient(self, expr): func = expr._expr return r"\nabla %s" % self.parenthesize(func, PRECEDENCE['Mul']) def _print_Laplacian(self, expr): func = expr._expr return r"\Delta %s" % self.parenthesize(func, PRECEDENCE['Mul']) def _print_Mul(self, expr: Expr): from sympy.simplify import fraction separator: str = self._settings['mul_symbol_latex'] numbersep: str = self._settings['mul_symbol_latex_numbers'] def convert(expr) -> str: if not expr.is_Mul: return str(self._print(expr)) else: if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: args = list(expr.args) # If there are quantities or prefixes, append them at the back. units, nonunits = sift(args, lambda x: (hasattr(x, "_scale_factor") or hasattr(x, "is_physical_constant")) or (isinstance(x, Pow) and hasattr(x.base, "is_physical_constant")), binary=True) prefixes, units = sift(units, lambda x: hasattr(x, "_scale_factor"), binary=True) return convert_args(nonunits + prefixes + units) def convert_args(args) -> str: _tex = last_term_tex = "" for i, term in enumerate(args): term_tex = self._print(term) if not (hasattr(term, "_scale_factor") or hasattr(term, "is_physical_constant")): if self._needs_mul_brackets(term, first=(i == 0), last=(i == len(args) - 1)): term_tex = r"\left(%s\right)" % term_tex if _between_two_numbers_p[0].search(last_term_tex) and \ _between_two_numbers_p[1].match(str(term)): # between two numbers _tex += numbersep elif _tex: _tex += separator elif _tex: _tex += separator _tex += term_tex last_term_tex = term_tex return _tex # Check for unevaluated Mul. In this case we need to make sure the # identities are visible, multiple Rational factors are not combined # etc so we display in a straight-forward form that fully preserves all # args and their order. # XXX: _print_Pow calls this routine with instances of Pow... if isinstance(expr, Mul): args = expr.args if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]): return convert_args(args) include_parens = False if expr.could_extract_minus_sign(): expr = -expr tex = "- " if expr.is_Add: tex += "(" include_parens = True else: tex = "" numer, denom = fraction(expr, exact=True) if denom is S.One and Pow(1, -1, evaluate=False) not in expr.args: # use the original expression here, since fraction() may have # altered it when producing numer and denom tex += convert(expr) else: snumer = convert(numer) sdenom = convert(denom) ldenom = len(sdenom.split()) ratio = self._settings['long_frac_ratio'] if self._settings['fold_short_frac'] and ldenom <= 2 and \ "^" not in sdenom: # handle short fractions if self._needs_mul_brackets(numer, last=False): tex += r"\left(%s\right) / %s" % (snumer, sdenom) else: tex += r"%s / %s" % (snumer, sdenom) elif ratio is not None and \ len(snumer.split()) > ratio*ldenom: # handle long fractions if self._needs_mul_brackets(numer, last=True): tex += r"\frac{1}{%s}%s\left(%s\right)" \ % (sdenom, separator, snumer) elif numer.is_Mul: # split a long numerator a = S.One b = S.One for x in numer.args: if self._needs_mul_brackets(x, last=False) or \ len(convert(a*x).split()) > ratio*ldenom or \ (b.is_commutative is x.is_commutative is False): b *= x else: a *= x if self._needs_mul_brackets(b, last=True): tex += r"\frac{%s}{%s}%s\left(%s\right)" \ % (convert(a), sdenom, separator, convert(b)) else: tex += r"\frac{%s}{%s}%s%s" \ % (convert(a), sdenom, separator, convert(b)) else: tex += r"\frac{1}{%s}%s%s" % (sdenom, separator, snumer) else: tex += r"\frac{%s}{%s}" % (snumer, sdenom) if include_parens: tex += ")" return tex def _print_AlgebraicNumber(self, expr): if expr.is_aliased: return self._print(expr.as_poly().as_expr()) else: return self._print(expr.as_expr()) def _print_PrimeIdeal(self, expr): p = self._print(expr.p) if expr.is_inert: return rf'\left({p}\right)' alpha = self._print(expr.alpha.as_expr()) return rf'\left({p}, {alpha}\right)' def _print_Pow(self, expr: Pow): # Treat x**Rational(1,n) as special case if expr.exp.is_Rational: p: int = expr.exp.p # type: ignore q: int = expr.exp.q # type: ignore if abs(p) == 1 and q != 1 and self._settings['root_notation']: base = self._print(expr.base) if q == 2: tex = r"\sqrt{%s}" % base elif self._settings['itex']: tex = r"\root{%d}{%s}" % (q, base) else: tex = r"\sqrt[%d]{%s}" % (q, base) if expr.exp.is_negative: return r"\frac{1}{%s}" % tex else: return tex elif self._settings['fold_frac_powers'] and q != 1: base = self.parenthesize(expr.base, PRECEDENCE['Pow']) # issue #12886: add parentheses for superscripts raised to powers if expr.base.is_Symbol: base = self.parenthesize_super(base) if expr.base.is_Function: return self._print(expr.base, exp="%s/%s" % (p, q)) return r"%s^{%s/%s}" % (base, p, q) elif expr.exp.is_negative and expr.base.is_commutative: # special case for 1^(-x), issue 9216 if expr.base == 1: return r"%s^{%s}" % (expr.base, expr.exp) # special case for (1/x)^(-y) and (-1/-x)^(-y), issue 20252 if expr.base.is_Rational: base_p: int = expr.base.p # type: ignore base_q: int = expr.base.q # type: ignore if base_p * base_q == abs(base_q): if expr.exp == -1: return r"\frac{1}{\frac{%s}{%s}}" % (base_p, base_q) else: return r"\frac{1}{(\frac{%s}{%s})^{%s}}" % (base_p, base_q, abs(expr.exp)) # things like 1/x return self._print_Mul(expr) if expr.base.is_Function: return self._print(expr.base, exp=self._print(expr.exp)) tex = r"%s^{%s}" return self._helper_print_standard_power(expr, tex) def _helper_print_standard_power(self, expr, template: str) -> str: exp = self._print(expr.exp) # issue #12886: add parentheses around superscripts raised # to powers base = self.parenthesize(expr.base, PRECEDENCE['Pow']) if expr.base.is_Symbol: base = self.parenthesize_super(base) elif (isinstance(expr.base, Derivative) and base.startswith(r'\left(') and re.match(r'\\left\(\\d?d?dot', base) and base.endswith(r'\right)')): # don't use parentheses around dotted derivative base = base[6: -7] # remove outermost added parens return template % (base, exp) def _print_UnevaluatedExpr(self, expr): return self._print(expr.args[0]) def _print_Sum(self, expr): if len(expr.limits) == 1: tex = r"\sum_{%s=%s}^{%s} " % \ tuple([self._print(i) for i in expr.limits[0]]) else: def _format_ineq(l): return r"%s \leq %s \leq %s" % \ tuple([self._print(s) for s in (l[1], l[0], l[2])]) tex = r"\sum_{\substack{%s}} " % \ str.join('\\\\', [_format_ineq(l) for l in expr.limits]) if isinstance(expr.function, Add): tex += r"\left(%s\right)" % self._print(expr.function) else: tex += self._print(expr.function) return tex def _print_Product(self, expr): if len(expr.limits) == 1: tex = r"\prod_{%s=%s}^{%s} " % \ tuple([self._print(i) for i in expr.limits[0]]) else: def _format_ineq(l): return r"%s \leq %s \leq %s" % \ tuple([self._print(s) for s in (l[1], l[0], l[2])]) tex = r"\prod_{\substack{%s}} " % \ str.join('\\\\', [_format_ineq(l) for l in expr.limits]) if isinstance(expr.function, Add): tex += r"\left(%s\right)" % self._print(expr.function) else: tex += self._print(expr.function) return tex def _print_BasisDependent(self, expr: 'BasisDependent'): from sympy.vector import Vector o1: list[str] = [] if expr == expr.zero: return expr.zero._latex_form if isinstance(expr, Vector): items = expr.separate().items() else: items = [(0, expr)] for system, vect in items: inneritems = list(vect.components.items()) inneritems.sort(key=lambda x: x[0].__str__()) for k, v in inneritems: if v == 1: o1.append(' + ' + k._latex_form) elif v == -1: o1.append(' - ' + k._latex_form) else: arg_str = r'\left(' + self._print(v) + r'\right)' o1.append(' + ' + arg_str + k._latex_form) outstr = (''.join(o1)) if outstr[1] != '-': outstr = outstr[3:] else: outstr = outstr[1:] return outstr def _print_Indexed(self, expr): tex_base = self._print(expr.base) tex = '{'+tex_base+'}'+'_{%s}' % ','.join( map(self._print, expr.indices)) return tex def _print_IndexedBase(self, expr): return self._print(expr.label) def _print_Idx(self, expr): label = self._print(expr.label) if expr.upper is not None: upper = self._print(expr.upper) if expr.lower is not None: lower = self._print(expr.lower) else: lower = self._print(S.Zero) interval = '{lower}\\mathrel{{..}}\\nobreak {upper}'.format( lower = lower, upper = upper) return '{{{label}}}_{{{interval}}}'.format( label = label, interval = interval) #if no bounds are defined this just prints the label return label def _print_Derivative(self, expr): if requires_partial(expr.expr): diff_symbol = r'\partial' else: diff_symbol = self._settings["diff_operator_latex"] tex = "" dim = 0 for x, num in reversed(expr.variable_count): dim += num if num == 1: tex += r"%s %s" % (diff_symbol, self._print(x)) else: tex += r"%s %s^{%s}" % (diff_symbol, self.parenthesize_super(self._print(x)), self._print(num)) if dim == 1: tex = r"\frac{%s}{%s}" % (diff_symbol, tex) else: tex = r"\frac{%s^{%s}}{%s}" % (diff_symbol, self._print(dim), tex) if any(i.could_extract_minus_sign() for i in expr.args): return r"%s %s" % (tex, self.parenthesize(expr.expr, PRECEDENCE["Mul"], is_neg=True, strict=True)) return r"%s %s" % (tex, self.parenthesize(expr.expr, PRECEDENCE["Mul"], is_neg=False, strict=True)) def _print_Subs(self, subs): expr, old, new = subs.args latex_expr = self._print(expr) latex_old = (self._print(e) for e in old) latex_new = (self._print(e) for e in new) latex_subs = r'\\ '.join( e[0] + '=' + e[1] for e in zip(latex_old, latex_new)) return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr, latex_subs) def _print_Integral(self, expr): tex, symbols = "", [] diff_symbol = self._settings["diff_operator_latex"] # Only up to \iiiint exists if len(expr.limits) <= 4 and all(len(lim) == 1 for lim in expr.limits): # Use len(expr.limits)-1 so that syntax highlighters don't think # \" is an escaped quote tex = r"\i" + "i"*(len(expr.limits) - 1) + "nt" symbols = [r"\, %s%s" % (diff_symbol, self._print(symbol[0])) for symbol in expr.limits] else: for lim in reversed(expr.limits): symbol = lim[0] tex += r"\int" if len(lim) > 1: if self._settings['mode'] != 'inline' \ and not self._settings['itex']: tex += r"\limits" if len(lim) == 3: tex += "_{%s}^{%s}" % (self._print(lim[1]), self._print(lim[2])) if len(lim) == 2: tex += "^{%s}" % (self._print(lim[1])) symbols.insert(0, r"\, %s%s" % (diff_symbol, self._print(symbol))) return r"%s %s%s" % (tex, self.parenthesize(expr.function, PRECEDENCE["Mul"], is_neg=any(i.could_extract_minus_sign() for i in expr.args), strict=True), "".join(symbols)) def _print_Limit(self, expr): e, z, z0, dir = expr.args tex = r"\lim_{%s \to " % self._print(z) if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity): tex += r"%s}" % self._print(z0) else: tex += r"%s^%s}" % (self._print(z0), self._print(dir)) if isinstance(e, AssocOp): return r"%s\left(%s\right)" % (tex, self._print(e)) else: return r"%s %s" % (tex, self._print(e)) def _hprint_Function(self, func: str) -> str: r''' Logic to decide how to render a function to latex - if it is a recognized latex name, use the appropriate latex command - if it is a single letter, excluding sub- and superscripts, just use that letter - if it is a longer name, then put \operatorname{} around it and be mindful of undercores in the name ''' func = self._deal_with_super_sub(func) superscriptidx = func.find("^") subscriptidx = func.find("_") if func in accepted_latex_functions: name = r"\%s" % func elif len(func) == 1 or func.startswith('\\') or subscriptidx == 1 or superscriptidx == 1: name = func else: if superscriptidx > 0 and subscriptidx > 0: name = r"\operatorname{%s}%s" %( func[:min(subscriptidx,superscriptidx)], func[min(subscriptidx,superscriptidx):]) elif superscriptidx > 0: name = r"\operatorname{%s}%s" %( func[:superscriptidx], func[superscriptidx:]) elif subscriptidx > 0: name = r"\operatorname{%s}%s" %( func[:subscriptidx], func[subscriptidx:]) else: name = r"\operatorname{%s}" % func return name def _print_Function(self, expr: Function, exp=None) -> str: r''' Render functions to LaTeX, handling functions that LaTeX knows about e.g., sin, cos, ... by using the proper LaTeX command (\sin, \cos, ...). For single-letter function names, render them as regular LaTeX math symbols. For multi-letter function names that LaTeX does not know about, (e.g., Li, sech) use \operatorname{} so that the function name is rendered in Roman font and LaTeX handles spacing properly. expr is the expression involving the function exp is an exponent ''' func = expr.func.__name__ if hasattr(self, '_print_' + func) and \ not isinstance(expr, AppliedUndef): return getattr(self, '_print_' + func)(expr, exp) else: args = [str(self._print(arg)) for arg in expr.args] # How inverse trig functions should be displayed, formats are: # abbreviated: asin, full: arcsin, power: sin^-1 inv_trig_style = self._settings['inv_trig_style'] # If we are dealing with a power-style inverse trig function inv_trig_power_case = False # If it is applicable to fold the argument brackets can_fold_brackets = self._settings['fold_func_brackets'] and \ len(args) == 1 and \ not self._needs_function_brackets(expr.args[0]) inv_trig_table = [ "asin", "acos", "atan", "acsc", "asec", "acot", "asinh", "acosh", "atanh", "acsch", "asech", "acoth", ] # If the function is an inverse trig function, handle the style if func in inv_trig_table: if inv_trig_style == "abbreviated": pass elif inv_trig_style == "full": func = ("ar" if func[-1] == "h" else "arc") + func[1:] elif inv_trig_style == "power": func = func[1:] inv_trig_power_case = True # Can never fold brackets if we're raised to a power if exp is not None: can_fold_brackets = False if inv_trig_power_case: if func in accepted_latex_functions: name = r"\%s^{-1}" % func else: name = r"\operatorname{%s}^{-1}" % func elif exp is not None: func_tex = self._hprint_Function(func) func_tex = self.parenthesize_super(func_tex) name = r'%s^{%s}' % (func_tex, exp) else: name = self._hprint_Function(func) if can_fold_brackets: if func in accepted_latex_functions: # Wrap argument safely to avoid parse-time conflicts # with the function name itself name += r" {%s}" else: name += r"%s" else: name += r"{\left(%s \right)}" if inv_trig_power_case and exp is not None: name += r"^{%s}" % exp return name % ",".join(args) def _print_UndefinedFunction(self, expr): return self._hprint_Function(str(expr)) def _print_ElementwiseApplyFunction(self, expr): return r"{%s}_{\circ}\left({%s}\right)" % ( self._print(expr.function), self._print(expr.expr), ) @property def _special_function_classes(self): from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.gamma_functions import gamma, lowergamma from sympy.functions.special.beta_functions import beta from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.error_functions import Chi return {KroneckerDelta: r'\delta', gamma: r'\Gamma', lowergamma: r'\gamma', beta: r'\operatorname{B}', DiracDelta: r'\delta', Chi: r'\operatorname{Chi}'} def _print_FunctionClass(self, expr): for cls in self._special_function_classes: if issubclass(expr, cls) and expr.__name__ == cls.__name__: return self._special_function_classes[cls] return self._hprint_Function(str(expr)) def _print_Lambda(self, expr): symbols, expr = expr.args if len(symbols) == 1: symbols = self._print(symbols[0]) else: symbols = self._print(tuple(symbols)) tex = r"\left( %s \mapsto %s \right)" % (symbols, self._print(expr)) return tex def _print_IdentityFunction(self, expr): return r"\left( x \mapsto x \right)" def _hprint_variadic_function(self, expr, exp=None) -> str: args = sorted(expr.args, key=default_sort_key) texargs = [r"%s" % self._print(symbol) for symbol in args] tex = r"\%s\left(%s\right)" % (str(expr.func).lower(), ", ".join(texargs)) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex _print_Min = _print_Max = _hprint_variadic_function def _print_floor(self, expr, exp=None): tex = r"\left\lfloor{%s}\right\rfloor" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_ceiling(self, expr, exp=None): tex = r"\left\lceil{%s}\right\rceil" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_log(self, expr, exp=None): if not self._settings["ln_notation"]: tex = r"\log{\left(%s \right)}" % self._print(expr.args[0]) else: tex = r"\ln{\left(%s \right)}" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_Abs(self, expr, exp=None): tex = r"\left|{%s}\right|" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_re(self, expr, exp=None): if self._settings['gothic_re_im']: tex = r"\Re{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom']) else: tex = r"\operatorname{{re}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom'])) return self._do_exponent(tex, exp) def _print_im(self, expr, exp=None): if self._settings['gothic_re_im']: tex = r"\Im{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom']) else: tex = r"\operatorname{{im}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom'])) return self._do_exponent(tex, exp) def _print_Not(self, e): from sympy.logic.boolalg import (Equivalent, Implies) if isinstance(e.args[0], Equivalent): return self._print_Equivalent(e.args[0], r"\not\Leftrightarrow") if isinstance(e.args[0], Implies): return self._print_Implies(e.args[0], r"\not\Rightarrow") if (e.args[0].is_Boolean): return r"\neg \left(%s\right)" % self._print(e.args[0]) else: return r"\neg %s" % self._print(e.args[0]) def _print_LogOp(self, args, char): arg = args[0] if arg.is_Boolean and not arg.is_Not: tex = r"\left(%s\right)" % self._print(arg) else: tex = r"%s" % self._print(arg) for arg in args[1:]: if arg.is_Boolean and not arg.is_Not: tex += r" %s \left(%s\right)" % (char, self._print(arg)) else: tex += r" %s %s" % (char, self._print(arg)) return tex def _print_And(self, e): args = sorted(e.args, key=default_sort_key) return self._print_LogOp(args, r"\wedge") def _print_Or(self, e): args = sorted(e.args, key=default_sort_key) return self._print_LogOp(args, r"\vee") def _print_Xor(self, e): args = sorted(e.args, key=default_sort_key) return self._print_LogOp(args, r"\veebar") def _print_Implies(self, e, altchar=None): return self._print_LogOp(e.args, altchar or r"\Rightarrow") def _print_Equivalent(self, e, altchar=None): args = sorted(e.args, key=default_sort_key) return self._print_LogOp(args, altchar or r"\Leftrightarrow") def _print_conjugate(self, expr, exp=None): tex = r"\overline{%s}" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_polar_lift(self, expr, exp=None): func = r"\operatorname{polar\_lift}" arg = r"{\left(%s \right)}" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}%s" % (func, exp, arg) else: return r"%s%s" % (func, arg) def _print_ExpBase(self, expr, exp=None): # TODO should exp_polar be printed differently? # what about exp_polar(0), exp_polar(1)? tex = r"e^{%s}" % self._print(expr.args[0]) return self._do_exponent(tex, exp) def _print_Exp1(self, expr, exp=None): return "e" def _print_elliptic_k(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"K^{%s}%s" % (exp, tex) else: return r"K%s" % tex def _print_elliptic_f(self, expr, exp=None): tex = r"\left(%s\middle| %s\right)" % \ (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"F^{%s}%s" % (exp, tex) else: return r"F%s" % tex def _print_elliptic_e(self, expr, exp=None): if len(expr.args) == 2: tex = r"\left(%s\middle| %s\right)" % \ (self._print(expr.args[0]), self._print(expr.args[1])) else: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"E^{%s}%s" % (exp, tex) else: return r"E%s" % tex def _print_elliptic_pi(self, expr, exp=None): if len(expr.args) == 3: tex = r"\left(%s; %s\middle| %s\right)" % \ (self._print(expr.args[0]), self._print(expr.args[1]), self._print(expr.args[2])) else: tex = r"\left(%s\middle| %s\right)" % \ (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"\Pi^{%s}%s" % (exp, tex) else: return r"\Pi%s" % tex def _print_beta(self, expr, exp=None): x = expr.args[0] # Deal with unevaluated single argument beta y = expr.args[0] if len(expr.args) == 1 else expr.args[1] tex = rf"\left({x}, {y}\right)" if exp is not None: return r"\operatorname{B}^{%s}%s" % (exp, tex) else: return r"\operatorname{B}%s" % tex def _print_betainc(self, expr, exp=None, operator='B'): largs = [self._print(arg) for arg in expr.args] tex = r"\left(%s, %s\right)" % (largs[0], largs[1]) if exp is not None: return r"\operatorname{%s}_{(%s, %s)}^{%s}%s" % (operator, largs[2], largs[3], exp, tex) else: return r"\operatorname{%s}_{(%s, %s)}%s" % (operator, largs[2], largs[3], tex) def _print_betainc_regularized(self, expr, exp=None): return self._print_betainc(expr, exp, operator='I') def _print_uppergamma(self, expr, exp=None): tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"\Gamma^{%s}%s" % (exp, tex) else: return r"\Gamma%s" % tex def _print_lowergamma(self, expr, exp=None): tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"\gamma^{%s}%s" % (exp, tex) else: return r"\gamma%s" % tex def _hprint_one_arg_func(self, expr, exp=None) -> str: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}%s" % (self._print(expr.func), exp, tex) else: return r"%s%s" % (self._print(expr.func), tex) _print_gamma = _hprint_one_arg_func def _print_Chi(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\operatorname{Chi}^{%s}%s" % (exp, tex) else: return r"\operatorname{Chi}%s" % tex def _print_expint(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[1]) nu = self._print(expr.args[0]) if exp is not None: return r"\operatorname{E}_{%s}^{%s}%s" % (nu, exp, tex) else: return r"\operatorname{E}_{%s}%s" % (nu, tex) def _print_fresnels(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"S^{%s}%s" % (exp, tex) else: return r"S%s" % tex def _print_fresnelc(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"C^{%s}%s" % (exp, tex) else: return r"C%s" % tex def _print_subfactorial(self, expr, exp=None): tex = r"!%s" % self.parenthesize(expr.args[0], PRECEDENCE["Func"]) if exp is not None: return r"\left(%s\right)^{%s}" % (tex, exp) else: return tex def _print_factorial(self, expr, exp=None): tex = r"%s!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_factorial2(self, expr, exp=None): tex = r"%s!!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_binomial(self, expr, exp=None): tex = r"{\binom{%s}{%s}}" % (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_RisingFactorial(self, expr, exp=None): n, k = expr.args base = r"%s" % self.parenthesize(n, PRECEDENCE['Func']) tex = r"{%s}^{\left(%s\right)}" % (base, self._print(k)) return self._do_exponent(tex, exp) def _print_FallingFactorial(self, expr, exp=None): n, k = expr.args sub = r"%s" % self.parenthesize(k, PRECEDENCE['Func']) tex = r"{\left(%s\right)}_{%s}" % (self._print(n), sub) return self._do_exponent(tex, exp) def _hprint_BesselBase(self, expr, exp, sym: str) -> str: tex = r"%s" % (sym) need_exp = False if exp is not None: if tex.find('^') == -1: tex = r"%s^{%s}" % (tex, exp) else: need_exp = True tex = r"%s_{%s}\left(%s\right)" % (tex, self._print(expr.order), self._print(expr.argument)) if need_exp: tex = self._do_exponent(tex, exp) return tex def _hprint_vec(self, vec) -> str: if not vec: return "" s = "" for i in vec[:-1]: s += "%s, " % self._print(i) s += self._print(vec[-1]) return s def _print_besselj(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'J') def _print_besseli(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'I') def _print_besselk(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'K') def _print_bessely(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'Y') def _print_yn(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'y') def _print_jn(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'j') def _print_hankel1(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'H^{(1)}') def _print_hankel2(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'H^{(2)}') def _print_hn1(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'h^{(1)}') def _print_hn2(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'h^{(2)}') def _hprint_airy(self, expr, exp=None, notation="") -> str: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}%s" % (notation, exp, tex) else: return r"%s%s" % (notation, tex) def _hprint_airy_prime(self, expr, exp=None, notation="") -> str: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"{%s^\prime}^{%s}%s" % (notation, exp, tex) else: return r"%s^\prime%s" % (notation, tex) def _print_airyai(self, expr, exp=None): return self._hprint_airy(expr, exp, 'Ai') def _print_airybi(self, expr, exp=None): return self._hprint_airy(expr, exp, 'Bi') def _print_airyaiprime(self, expr, exp=None): return self._hprint_airy_prime(expr, exp, 'Ai') def _print_airybiprime(self, expr, exp=None): return self._hprint_airy_prime(expr, exp, 'Bi') def _print_hyper(self, expr, exp=None): tex = r"{{}_{%s}F_{%s}\left(\begin{matrix} %s \\ %s \end{matrix}" \ r"\middle| {%s} \right)}" % \ (self._print(len(expr.ap)), self._print(len(expr.bq)), self._hprint_vec(expr.ap), self._hprint_vec(expr.bq), self._print(expr.argument)) if exp is not None: tex = r"{%s}^{%s}" % (tex, exp) return tex def _print_meijerg(self, expr, exp=None): tex = r"{G_{%s, %s}^{%s, %s}\left(\begin{matrix} %s & %s \\" \ r"%s & %s \end{matrix} \middle| {%s} \right)}" % \ (self._print(len(expr.ap)), self._print(len(expr.bq)), self._print(len(expr.bm)), self._print(len(expr.an)), self._hprint_vec(expr.an), self._hprint_vec(expr.aother), self._hprint_vec(expr.bm), self._hprint_vec(expr.bother), self._print(expr.argument)) if exp is not None: tex = r"{%s}^{%s}" % (tex, exp) return tex def _print_dirichlet_eta(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\eta^{%s}%s" % (exp, tex) return r"\eta%s" % tex def _print_zeta(self, expr, exp=None): if len(expr.args) == 2: tex = r"\left(%s, %s\right)" % tuple(map(self._print, expr.args)) else: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\zeta^{%s}%s" % (exp, tex) return r"\zeta%s" % tex def _print_stieltjes(self, expr, exp=None): if len(expr.args) == 2: tex = r"_{%s}\left(%s\right)" % tuple(map(self._print, expr.args)) else: tex = r"_{%s}" % self._print(expr.args[0]) if exp is not None: return r"\gamma%s^{%s}" % (tex, exp) return r"\gamma%s" % tex def _print_lerchphi(self, expr, exp=None): tex = r"\left(%s, %s, %s\right)" % tuple(map(self._print, expr.args)) if exp is None: return r"\Phi%s" % tex return r"\Phi^{%s}%s" % (exp, tex) def _print_polylog(self, expr, exp=None): s, z = map(self._print, expr.args) tex = r"\left(%s\right)" % z if exp is None: return r"\operatorname{Li}_{%s}%s" % (s, tex) return r"\operatorname{Li}_{%s}^{%s}%s" % (s, exp, tex) def _print_jacobi(self, expr, exp=None): n, a, b, x = map(self._print, expr.args) tex = r"P_{%s}^{\left(%s,%s\right)}\left(%s\right)" % (n, a, b, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_gegenbauer(self, expr, exp=None): n, a, x = map(self._print, expr.args) tex = r"C_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_chebyshevt(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"T_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_chebyshevu(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"U_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_legendre(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"P_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_assoc_legendre(self, expr, exp=None): n, a, x = map(self._print, expr.args) tex = r"P_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_hermite(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"H_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_laguerre(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"L_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_assoc_laguerre(self, expr, exp=None): n, a, x = map(self._print, expr.args) tex = r"L_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_Ynm(self, expr, exp=None): n, m, theta, phi = map(self._print, expr.args) tex = r"Y_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_Znm(self, expr, exp=None): n, m, theta, phi = map(self._print, expr.args) tex = r"Z_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def __print_mathieu_functions(self, character, args, prime=False, exp=None): a, q, z = map(self._print, args) sup = r"^{\prime}" if prime else "" exp = "" if not exp else "^{%s}" % exp return r"%s%s\left(%s, %s, %s\right)%s" % (character, sup, a, q, z, exp) def _print_mathieuc(self, expr, exp=None): return self.__print_mathieu_functions("C", expr.args, exp=exp) def _print_mathieus(self, expr, exp=None): return self.__print_mathieu_functions("S", expr.args, exp=exp) def _print_mathieucprime(self, expr, exp=None): return self.__print_mathieu_functions("C", expr.args, prime=True, exp=exp) def _print_mathieusprime(self, expr, exp=None): return self.__print_mathieu_functions("S", expr.args, prime=True, exp=exp) def _print_Rational(self, expr): if expr.q != 1: sign = "" p = expr.p if expr.p < 0: sign = "- " p = -p if self._settings['fold_short_frac']: return r"%s%d / %d" % (sign, p, expr.q) return r"%s\frac{%d}{%d}" % (sign, p, expr.q) else: return self._print(expr.p) def _print_Order(self, expr): s = self._print(expr.expr) if expr.point and any(p != S.Zero for p in expr.point) or \ len(expr.variables) > 1: s += '; ' if len(expr.variables) > 1: s += self._print(expr.variables) elif expr.variables: s += self._print(expr.variables[0]) s += r'\rightarrow ' if len(expr.point) > 1: s += self._print(expr.point) else: s += self._print(expr.point[0]) return r"O\left(%s\right)" % s def _print_Symbol(self, expr: Symbol, style='plain'): name: str = self._settings['symbol_names'].get(expr) if name is not None: return name return self._deal_with_super_sub(expr.name, style=style) _print_RandomSymbol = _print_Symbol def _deal_with_super_sub(self, string: str, style='plain') -> str: if '{' in string: name, supers, subs = string, [], [] else: name, supers, subs = split_super_sub(string) name = translate(name) supers = [translate(sup) for sup in supers] subs = [translate(sub) for sub in subs] # apply the style only to the name if style == 'bold': name = "\\mathbf{{{}}}".format(name) # glue all items together: if supers: name += "^{%s}" % " ".join(supers) if subs: name += "_{%s}" % " ".join(subs) return name def _print_Relational(self, expr): if self._settings['itex']: gt = r"\gt" lt = r"\lt" else: gt = ">" lt = "<" charmap = { "==": "=", ">": gt, "<": lt, ">=": r"\geq", "<=": r"\leq", "!=": r"\neq", } return "%s %s %s" % (self._print(expr.lhs), charmap[expr.rel_op], self._print(expr.rhs)) def _print_Piecewise(self, expr): ecpairs = [r"%s & \text{for}\: %s" % (self._print(e), self._print(c)) for e, c in expr.args[:-1]] if expr.args[-1].cond == true: ecpairs.append(r"%s & \text{otherwise}" % self._print(expr.args[-1].expr)) else: ecpairs.append(r"%s & \text{for}\: %s" % (self._print(expr.args[-1].expr), self._print(expr.args[-1].cond))) tex = r"\begin{cases} %s \end{cases}" return tex % r" \\".join(ecpairs) def _print_matrix_contents(self, expr): lines = [] for line in range(expr.rows): # horrible, should be 'rows' lines.append(" & ".join([self._print(i) for i in expr[line, :]])) mat_str = self._settings['mat_str'] if mat_str is None: if self._settings['mode'] == 'inline': mat_str = 'smallmatrix' else: if (expr.cols <= 10) is True: mat_str = 'matrix' else: mat_str = 'array' out_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}' out_str = out_str.replace('%MATSTR%', mat_str) if mat_str == 'array': out_str = out_str.replace('%s', '{' + 'c'*expr.cols + '}%s') return out_str % r"\\".join(lines) def _print_MatrixBase(self, expr): out_str = self._print_matrix_contents(expr) if self._settings['mat_delim']: left_delim: str = self._settings['mat_delim'] right_delim = self._delim_dict[left_delim] out_str = r'\left' + left_delim + out_str + \ r'\right' + right_delim return out_str def _print_MatrixElement(self, expr): return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True)\ + '_{%s, %s}' % (self._print(expr.i), self._print(expr.j)) def _print_MatrixSlice(self, expr): def latexslice(x, dim): x = list(x) if x[2] == 1: del x[2] if x[0] == 0: x[0] = None if x[1] == dim: x[1] = None return ':'.join(self._print(xi) if xi is not None else '' for xi in x) return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + r'\left[' + latexslice(expr.rowslice, expr.parent.rows) + ', ' + latexslice(expr.colslice, expr.parent.cols) + r'\right]') def _print_BlockMatrix(self, expr): return self._print(expr.blocks) def _print_Transpose(self, expr): mat = expr.arg from sympy.matrices import MatrixSymbol, BlockMatrix if (not isinstance(mat, MatrixSymbol) and not isinstance(mat, BlockMatrix) and mat.is_MatrixExpr): return r"\left(%s\right)^{T}" % self._print(mat) else: s = self.parenthesize(mat, precedence_traditional(expr), True) if '^' in s: return r"\left(%s\right)^{T}" % s else: return "%s^{T}" % s def _print_Trace(self, expr): mat = expr.arg return r"\operatorname{tr}\left(%s \right)" % self._print(mat) def _print_Adjoint(self, expr): mat = expr.arg from sympy.matrices import MatrixSymbol, BlockMatrix if (not isinstance(mat, MatrixSymbol) and not isinstance(mat, BlockMatrix) and mat.is_MatrixExpr): return r"\left(%s\right)^{\dagger}" % self._print(mat) else: s = self.parenthesize(mat, precedence_traditional(expr), True) if '^' in s: return r"\left(%s\right)^{\dagger}" % s else: return r"%s^{\dagger}" % s def _print_MatMul(self, expr): from sympy import MatMul # Parenthesize nested MatMul but not other types of Mul objects: parens = lambda x: self._print(x) if isinstance(x, Mul) and not isinstance(x, MatMul) else \ self.parenthesize(x, precedence_traditional(expr), False) args = list(expr.args) if expr.could_extract_minus_sign(): if args[0] == -1: args = args[1:] else: args[0] = -args[0] return '- ' + ' '.join(map(parens, args)) else: return ' '.join(map(parens, args)) def _print_Determinant(self, expr): mat = expr.arg if mat.is_MatrixExpr: from sympy.matrices.expressions.blockmatrix import BlockMatrix if isinstance(mat, BlockMatrix): return r"\left|{%s}\right|" % self._print_matrix_contents(mat.blocks) return r"\left|{%s}\right|" % self._print(mat) return r"\left|{%s}\right|" % self._print_matrix_contents(mat) def _print_Mod(self, expr, exp=None): if exp is not None: return r'\left(%s \bmod %s\right)^{%s}' % \ (self.parenthesize(expr.args[0], PRECEDENCE['Mul'], strict=True), self.parenthesize(expr.args[1], PRECEDENCE['Mul'], strict=True), exp) return r'%s \bmod %s' % (self.parenthesize(expr.args[0], PRECEDENCE['Mul'], strict=True), self.parenthesize(expr.args[1], PRECEDENCE['Mul'], strict=True)) def _print_HadamardProduct(self, expr): args = expr.args prec = PRECEDENCE['Pow'] parens = self.parenthesize return r' \circ '.join( map(lambda arg: parens(arg, prec, strict=True), args)) def _print_HadamardPower(self, expr): if precedence_traditional(expr.exp) < PRECEDENCE["Mul"]: template = r"%s^{\circ \left({%s}\right)}" else: template = r"%s^{\circ {%s}}" return self._helper_print_standard_power(expr, template) def _print_KroneckerProduct(self, expr): args = expr.args prec = PRECEDENCE['Pow'] parens = self.parenthesize return r' \otimes '.join( map(lambda arg: parens(arg, prec, strict=True), args)) def _print_MatPow(self, expr): base, exp = expr.base, expr.exp from sympy.matrices import MatrixSymbol if not isinstance(base, MatrixSymbol) and base.is_MatrixExpr: return "\\left(%s\\right)^{%s}" % (self._print(base), self._print(exp)) else: base_str = self._print(base) if '^' in base_str: return r"\left(%s\right)^{%s}" % (base_str, self._print(exp)) else: return "%s^{%s}" % (base_str, self._print(exp)) def _print_MatrixSymbol(self, expr): return self._print_Symbol(expr, style=self._settings[ 'mat_symbol_style']) def _print_ZeroMatrix(self, Z): return "0" if self._settings[ 'mat_symbol_style'] == 'plain' else r"\mathbf{0}" def _print_OneMatrix(self, O): return "1" if self._settings[ 'mat_symbol_style'] == 'plain' else r"\mathbf{1}" def _print_Identity(self, I): return r"\mathbb{I}" if self._settings[ 'mat_symbol_style'] == 'plain' else r"\mathbf{I}" def _print_PermutationMatrix(self, P): perm_str = self._print(P.args[0]) return "P_{%s}" % perm_str def _print_NDimArray(self, expr: NDimArray): if expr.rank() == 0: return self._print(expr[()]) mat_str = self._settings['mat_str'] if mat_str is None: if self._settings['mode'] == 'inline': mat_str = 'smallmatrix' else: if (expr.rank() == 0) or (expr.shape[-1] <= 10): mat_str = 'matrix' else: mat_str = 'array' block_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}' block_str = block_str.replace('%MATSTR%', mat_str) if mat_str == 'array': block_str= block_str.replace('%s','{}%s') if self._settings['mat_delim']: left_delim: str = self._settings['mat_delim'] right_delim = self._delim_dict[left_delim] block_str = r'\left' + left_delim + block_str + \ r'\right' + right_delim if expr.rank() == 0: return block_str % "" level_str: list[list[str]] = [[] for i in range(expr.rank() + 1)] shape_ranges = [list(range(i)) for i in expr.shape] for outer_i in itertools.product(*shape_ranges): level_str[-1].append(self._print(expr[outer_i])) even = True for back_outer_i in range(expr.rank()-1, -1, -1): if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]: break if even: level_str[back_outer_i].append( r" & ".join(level_str[back_outer_i+1])) else: level_str[back_outer_i].append( block_str % (r"\\".join(level_str[back_outer_i+1]))) if len(level_str[back_outer_i+1]) == 1: level_str[back_outer_i][-1] = r"\left[" + \ level_str[back_outer_i][-1] + r"\right]" even = not even level_str[back_outer_i+1] = [] out_str = level_str[0][0] if expr.rank() % 2 == 1: out_str = block_str % out_str return out_str def _printer_tensor_indices(self, name, indices, index_map: dict): out_str = self._print(name) last_valence = None prev_map = None for index in indices: new_valence = index.is_up if ((index in index_map) or prev_map) and \ last_valence == new_valence: out_str += "," if last_valence != new_valence: if last_valence is not None: out_str += "}" if index.is_up: out_str += "{}^{" else: out_str += "{}_{" out_str += self._print(index.args[0]) if index in index_map: out_str += "=" out_str += self._print(index_map[index]) prev_map = True else: prev_map = False last_valence = new_valence if last_valence is not None: out_str += "}" return out_str def _print_Tensor(self, expr): name = expr.args[0].args[0] indices = expr.get_indices() return self._printer_tensor_indices(name, indices, {}) def _print_TensorElement(self, expr): name = expr.expr.args[0].args[0] indices = expr.expr.get_indices() index_map = expr.index_map return self._printer_tensor_indices(name, indices, index_map) def _print_TensMul(self, expr): # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)" sign, args = expr._get_args_for_traditional_printer() return sign + "".join( [self.parenthesize(arg, precedence(expr)) for arg in args] ) def _print_TensAdd(self, expr): a = [] args = expr.args for x in args: a.append(self.parenthesize(x, precedence(expr))) a.sort() s = ' + '.join(a) s = s.replace('+ -', '- ') return s def _print_TensorIndex(self, expr): return "{}%s{%s}" % ( "^" if expr.is_up else "_", self._print(expr.args[0]) ) def _print_PartialDerivative(self, expr): if len(expr.variables) == 1: return r"\frac{\partial}{\partial {%s}}{%s}" % ( self._print(expr.variables[0]), self.parenthesize(expr.expr, PRECEDENCE["Mul"], False) ) else: return r"\frac{\partial^{%s}}{%s}{%s}" % ( len(expr.variables), " ".join([r"\partial {%s}" % self._print(i) for i in expr.variables]), self.parenthesize(expr.expr, PRECEDENCE["Mul"], False) ) def _print_ArraySymbol(self, expr): return self._print(expr.name) def _print_ArrayElement(self, expr): return "{{%s}_{%s}}" % ( self.parenthesize(expr.name, PRECEDENCE["Func"], True), ", ".join([f"{self._print(i)}" for i in expr.indices])) def _print_UniversalSet(self, expr): return r"\mathbb{U}" def _print_frac(self, expr, exp=None): if exp is None: return r"\operatorname{frac}{\left(%s\right)}" % self._print(expr.args[0]) else: return r"\operatorname{frac}{\left(%s\right)}^{%s}" % ( self._print(expr.args[0]), exp) def _print_tuple(self, expr): if self._settings['decimal_separator'] == 'comma': sep = ";" elif self._settings['decimal_separator'] == 'period': sep = "," else: raise ValueError('Unknown Decimal Separator') if len(expr) == 1: # 1-tuple needs a trailing separator return self._add_parens_lspace(self._print(expr[0]) + sep) else: return self._add_parens_lspace( (sep + r" \ ").join([self._print(i) for i in expr])) def _print_TensorProduct(self, expr): elements = [self._print(a) for a in expr.args] return r' \otimes '.join(elements) def _print_WedgeProduct(self, expr): elements = [self._print(a) for a in expr.args] return r' \wedge '.join(elements) def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_list(self, expr): if self._settings['decimal_separator'] == 'comma': return r"\left[ %s\right]" % \ r"; \ ".join([self._print(i) for i in expr]) elif self._settings['decimal_separator'] == 'period': return r"\left[ %s\right]" % \ r", \ ".join([self._print(i) for i in expr]) else: raise ValueError('Unknown Decimal Separator') def _print_dict(self, d): keys = sorted(d.keys(), key=default_sort_key) items = [] for key in keys: val = d[key] items.append("%s : %s" % (self._print(key), self._print(val))) return r"\left\{ %s\right\}" % r", \ ".join(items) def _print_Dict(self, expr): return self._print_dict(expr) def _print_DiracDelta(self, expr, exp=None): if len(expr.args) == 1 or expr.args[1] == 0: tex = r"\delta\left(%s\right)" % self._print(expr.args[0]) else: tex = r"\delta^{\left( %s \right)}\left( %s \right)" % ( self._print(expr.args[1]), self._print(expr.args[0])) if exp: tex = r"\left(%s\right)^{%s}" % (tex, exp) return tex def _print_SingularityFunction(self, expr, exp=None): shift = self._print(expr.args[0] - expr.args[1]) power = self._print(expr.args[2]) tex = r"{\left\langle %s \right\rangle}^{%s}" % (shift, power) if exp is not None: tex = r"{\left({\langle %s \rangle}^{%s}\right)}^{%s}" % (shift, power, exp) return tex def _print_Heaviside(self, expr, exp=None): pargs = ', '.join(self._print(arg) for arg in expr.pargs) tex = r"\theta\left(%s\right)" % pargs if exp: tex = r"\left(%s\right)^{%s}" % (tex, exp) return tex def _print_KroneckerDelta(self, expr, exp=None): i = self._print(expr.args[0]) j = self._print(expr.args[1]) if expr.args[0].is_Atom and expr.args[1].is_Atom: tex = r'\delta_{%s %s}' % (i, j) else: tex = r'\delta_{%s, %s}' % (i, j) if exp is not None: tex = r'\left(%s\right)^{%s}' % (tex, exp) return tex def _print_LeviCivita(self, expr, exp=None): indices = map(self._print, expr.args) if all(x.is_Atom for x in expr.args): tex = r'\varepsilon_{%s}' % " ".join(indices) else: tex = r'\varepsilon_{%s}' % ", ".join(indices) if exp: tex = r'\left(%s\right)^{%s}' % (tex, exp) return tex def _print_RandomDomain(self, d): if hasattr(d, 'as_boolean'): return '\\text{Domain: }' + self._print(d.as_boolean()) elif hasattr(d, 'set'): return ('\\text{Domain: }' + self._print(d.symbols) + ' \\in ' + self._print(d.set)) elif hasattr(d, 'symbols'): return '\\text{Domain on }' + self._print(d.symbols) else: return self._print(None) def _print_FiniteSet(self, s): items = sorted(s.args, key=default_sort_key) return self._print_set(items) def _print_set(self, s): items = sorted(s, key=default_sort_key) if self._settings['decimal_separator'] == 'comma': items = "; ".join(map(self._print, items)) elif self._settings['decimal_separator'] == 'period': items = ", ".join(map(self._print, items)) else: raise ValueError('Unknown Decimal Separator') return r"\left\{%s\right\}" % items _print_frozenset = _print_set def _print_Range(self, s): def _print_symbolic_range(): # Symbolic Range that cannot be resolved if s.args[0] == 0: if s.args[2] == 1: cont = self._print(s.args[1]) else: cont = ", ".join(self._print(arg) for arg in s.args) else: if s.args[2] == 1: cont = ", ".join(self._print(arg) for arg in s.args[:2]) else: cont = ", ".join(self._print(arg) for arg in s.args) return(f"\\text{{Range}}\\left({cont}\\right)") dots = object() if s.start.is_infinite and s.stop.is_infinite: if s.step.is_positive: printset = dots, -1, 0, 1, dots else: printset = dots, 1, 0, -1, dots elif s.start.is_infinite: printset = dots, s[-1] - s.step, s[-1] elif s.stop.is_infinite: it = iter(s) printset = next(it), next(it), dots elif s.is_empty is not None: if (s.size < 4) == True: printset = tuple(s) elif s.is_iterable: it = iter(s) printset = next(it), next(it), dots, s[-1] else: return _print_symbolic_range() else: return _print_symbolic_range() return (r"\left\{" + r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) + r"\right\}") def __print_number_polynomial(self, expr, letter, exp=None): if len(expr.args) == 2: if exp is not None: return r"%s_{%s}^{%s}\left(%s\right)" % (letter, self._print(expr.args[0]), exp, self._print(expr.args[1])) return r"%s_{%s}\left(%s\right)" % (letter, self._print(expr.args[0]), self._print(expr.args[1])) tex = r"%s_{%s}" % (letter, self._print(expr.args[0])) if exp is not None: tex = r"%s^{%s}" % (tex, exp) return tex def _print_bernoulli(self, expr, exp=None): return self.__print_number_polynomial(expr, "B", exp) def _print_genocchi(self, expr, exp=None): return self.__print_number_polynomial(expr, "G", exp) def _print_bell(self, expr, exp=None): if len(expr.args) == 3: tex1 = r"B_{%s, %s}" % (self._print(expr.args[0]), self._print(expr.args[1])) tex2 = r"\left(%s\right)" % r", ".join(self._print(el) for el in expr.args[2]) if exp is not None: tex = r"%s^{%s}%s" % (tex1, exp, tex2) else: tex = tex1 + tex2 return tex return self.__print_number_polynomial(expr, "B", exp) def _print_fibonacci(self, expr, exp=None): return self.__print_number_polynomial(expr, "F", exp) def _print_lucas(self, expr, exp=None): tex = r"L_{%s}" % self._print(expr.args[0]) if exp is not None: tex = r"%s^{%s}" % (tex, exp) return tex def _print_tribonacci(self, expr, exp=None): return self.__print_number_polynomial(expr, "T", exp) def _print_SeqFormula(self, s): dots = object() if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0: return r"\left\{%s\right\}_{%s=%s}^{%s}" % ( self._print(s.formula), self._print(s.variables[0]), self._print(s.start), self._print(s.stop) ) if s.start is S.NegativeInfinity: stop = s.stop printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2), s.coeff(stop - 1), s.coeff(stop)) elif s.stop is S.Infinity or s.length > 4: printset = s[:4] printset.append(dots) else: printset = tuple(s) return (r"\left[" + r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) + r"\right]") _print_SeqPer = _print_SeqFormula _print_SeqAdd = _print_SeqFormula _print_SeqMul = _print_SeqFormula def _print_Interval(self, i): if i.start == i.end: return r"\left\{%s\right\}" % self._print(i.start) else: if i.left_open: left = '(' else: left = '[' if i.right_open: right = ')' else: right = ']' return r"\left%s%s, %s\right%s" % \ (left, self._print(i.start), self._print(i.end), right) def _print_AccumulationBounds(self, i): return r"\left\langle %s, %s\right\rangle" % \ (self._print(i.min), self._print(i.max)) def _print_Union(self, u): prec = precedence_traditional(u) args_str = [self.parenthesize(i, prec) for i in u.args] return r" \cup ".join(args_str) def _print_Complement(self, u): prec = precedence_traditional(u) args_str = [self.parenthesize(i, prec) for i in u.args] return r" \setminus ".join(args_str) def _print_Intersection(self, u): prec = precedence_traditional(u) args_str = [self.parenthesize(i, prec) for i in u.args] return r" \cap ".join(args_str) def _print_SymmetricDifference(self, u): prec = precedence_traditional(u) args_str = [self.parenthesize(i, prec) for i in u.args] return r" \triangle ".join(args_str) def _print_ProductSet(self, p): prec = precedence_traditional(p) if len(p.sets) >= 1 and not has_variety(p.sets): return self.parenthesize(p.sets[0], prec) + "^{%d}" % len(p.sets) return r" \times ".join( self.parenthesize(set, prec) for set in p.sets) def _print_EmptySet(self, e): return r"\emptyset" def _print_Naturals(self, n): return r"\mathbb{N}" def _print_Naturals0(self, n): return r"\mathbb{N}_0" def _print_Integers(self, i): return r"\mathbb{Z}" def _print_Rationals(self, i): return r"\mathbb{Q}" def _print_Reals(self, i): return r"\mathbb{R}" def _print_Complexes(self, i): return r"\mathbb{C}" def _print_ImageSet(self, s): expr = s.lamda.expr sig = s.lamda.signature xys = ((self._print(x), self._print(y)) for x, y in zip(sig, s.base_sets)) xinys = r", ".join(r"%s \in %s" % xy for xy in xys) return r"\left\{%s\; \middle|\; %s\right\}" % (self._print(expr), xinys) def _print_ConditionSet(self, s): vars_print = ', '.join([self._print(var) for var in Tuple(s.sym)]) if s.base_set is S.UniversalSet: return r"\left\{%s\; \middle|\; %s \right\}" % \ (vars_print, self._print(s.condition)) return r"\left\{%s\; \middle|\; %s \in %s \wedge %s \right\}" % ( vars_print, vars_print, self._print(s.base_set), self._print(s.condition)) def _print_PowerSet(self, expr): arg_print = self._print(expr.args[0]) return r"\mathcal{{P}}\left({}\right)".format(arg_print) def _print_ComplexRegion(self, s): vars_print = ', '.join([self._print(var) for var in s.variables]) return r"\left\{%s\; \middle|\; %s \in %s \right\}" % ( self._print(s.expr), vars_print, self._print(s.sets)) def _print_Contains(self, e): return r"%s \in %s" % tuple(self._print(a) for a in e.args) def _print_FourierSeries(self, s): if s.an.formula is S.Zero and s.bn.formula is S.Zero: return self._print(s.a0) return self._print_Add(s.truncate()) + r' + \ldots' def _print_FormalPowerSeries(self, s): return self._print_Add(s.infinite) def _print_FiniteField(self, expr): return r"\mathbb{F}_{%s}" % expr.mod def _print_IntegerRing(self, expr): return r"\mathbb{Z}" def _print_RationalField(self, expr): return r"\mathbb{Q}" def _print_RealField(self, expr): return r"\mathbb{R}" def _print_ComplexField(self, expr): return r"\mathbb{C}" def _print_PolynomialRing(self, expr): domain = self._print(expr.domain) symbols = ", ".join(map(self._print, expr.symbols)) return r"%s\left[%s\right]" % (domain, symbols) def _print_FractionField(self, expr): domain = self._print(expr.domain) symbols = ", ".join(map(self._print, expr.symbols)) return r"%s\left(%s\right)" % (domain, symbols) def _print_PolynomialRingBase(self, expr): domain = self._print(expr.domain) symbols = ", ".join(map(self._print, expr.symbols)) inv = "" if not expr.is_Poly: inv = r"S_<^{-1}" return r"%s%s\left[%s\right]" % (inv, domain, symbols) def _print_Poly(self, poly): cls = poly.__class__.__name__ terms = [] for monom, coeff in poly.terms(): s_monom = '' for i, exp in enumerate(monom): if exp > 0: if exp == 1: s_monom += self._print(poly.gens[i]) else: s_monom += self._print(pow(poly.gens[i], exp)) if coeff.is_Add: if s_monom: s_coeff = r"\left(%s\right)" % self._print(coeff) else: s_coeff = self._print(coeff) else: if s_monom: if coeff is S.One: terms.extend(['+', s_monom]) continue if coeff is S.NegativeOne: terms.extend(['-', s_monom]) continue s_coeff = self._print(coeff) if not s_monom: s_term = s_coeff else: s_term = s_coeff + " " + s_monom if s_term.startswith('-'): terms.extend(['-', s_term[1:]]) else: terms.extend(['+', s_term]) if terms[0] in ('-', '+'): modifier = terms.pop(0) if modifier == '-': terms[0] = '-' + terms[0] expr = ' '.join(terms) gens = list(map(self._print, poly.gens)) domain = "domain=%s" % self._print(poly.get_domain()) args = ", ".join([expr] + gens + [domain]) if cls in accepted_latex_functions: tex = r"\%s {\left(%s \right)}" % (cls, args) else: tex = r"\operatorname{%s}{\left( %s \right)}" % (cls, args) return tex def _print_ComplexRootOf(self, root): cls = root.__class__.__name__ if cls == "ComplexRootOf": cls = "CRootOf" expr = self._print(root.expr) index = root.index if cls in accepted_latex_functions: return r"\%s {\left(%s, %d\right)}" % (cls, expr, index) else: return r"\operatorname{%s} {\left(%s, %d\right)}" % (cls, expr, index) def _print_RootSum(self, expr): cls = expr.__class__.__name__ args = [self._print(expr.expr)] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) if cls in accepted_latex_functions: return r"\%s {\left(%s\right)}" % (cls, ", ".join(args)) else: return r"\operatorname{%s} {\left(%s\right)}" % (cls, ", ".join(args)) def _print_OrdinalOmega(self, expr): return r"\omega" def _print_OmegaPower(self, expr): exp, mul = expr.args if mul != 1: if exp != 1: return r"{} \omega^{{{}}}".format(mul, exp) else: return r"{} \omega".format(mul) else: if exp != 1: return r"\omega^{{{}}}".format(exp) else: return r"\omega" def _print_Ordinal(self, expr): return " + ".join([self._print(arg) for arg in expr.args]) def _print_PolyElement(self, poly): mul_symbol = self._settings['mul_symbol_latex'] return poly.str(self, PRECEDENCE, "{%s}^{%d}", mul_symbol) def _print_FracElement(self, frac): if frac.denom == 1: return self._print(frac.numer) else: numer = self._print(frac.numer) denom = self._print(frac.denom) return r"\frac{%s}{%s}" % (numer, denom) def _print_euler(self, expr, exp=None): m, x = (expr.args[0], None) if len(expr.args) == 1 else expr.args tex = r"E_{%s}" % self._print(m) if exp is not None: tex = r"%s^{%s}" % (tex, exp) if x is not None: tex = r"%s\left(%s\right)" % (tex, self._print(x)) return tex def _print_catalan(self, expr, exp=None): tex = r"C_{%s}" % self._print(expr.args[0]) if exp is not None: tex = r"%s^{%s}" % (tex, exp) return tex def _print_UnifiedTransform(self, expr, s, inverse=False): return r"\mathcal{{{}}}{}_{{{}}}\left[{}\right]\left({}\right)".format(s, '^{-1}' if inverse else '', self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2])) def _print_MellinTransform(self, expr): return self._print_UnifiedTransform(expr, 'M') def _print_InverseMellinTransform(self, expr): return self._print_UnifiedTransform(expr, 'M', True) def _print_LaplaceTransform(self, expr): return self._print_UnifiedTransform(expr, 'L') def _print_InverseLaplaceTransform(self, expr): return self._print_UnifiedTransform(expr, 'L', True) def _print_FourierTransform(self, expr): return self._print_UnifiedTransform(expr, 'F') def _print_InverseFourierTransform(self, expr): return self._print_UnifiedTransform(expr, 'F', True) def _print_SineTransform(self, expr): return self._print_UnifiedTransform(expr, 'SIN') def _print_InverseSineTransform(self, expr): return self._print_UnifiedTransform(expr, 'SIN', True) def _print_CosineTransform(self, expr): return self._print_UnifiedTransform(expr, 'COS') def _print_InverseCosineTransform(self, expr): return self._print_UnifiedTransform(expr, 'COS', True) def _print_DMP(self, p): try: if p.ring is not None: # TODO incorporate order return self._print(p.ring.to_sympy(p)) except SympifyError: pass return self._print(repr(p)) def _print_DMF(self, p): return self._print_DMP(p) def _print_Object(self, object): return self._print(Symbol(object.name)) def _print_LambertW(self, expr, exp=None): arg0 = self._print(expr.args[0]) exp = r"^{%s}" % (exp,) if exp is not None else "" if len(expr.args) == 1: result = r"W%s\left(%s\right)" % (exp, arg0) else: arg1 = self._print(expr.args[1]) result = "W{0}_{{{1}}}\\left({2}\\right)".format(exp, arg1, arg0) return result def _print_Expectation(self, expr): return r"\operatorname{{E}}\left[{}\right]".format(self._print(expr.args[0])) def _print_Variance(self, expr): return r"\operatorname{{Var}}\left({}\right)".format(self._print(expr.args[0])) def _print_Covariance(self, expr): return r"\operatorname{{Cov}}\left({}\right)".format(", ".join(self._print(arg) for arg in expr.args)) def _print_Probability(self, expr): return r"\operatorname{{P}}\left({}\right)".format(self._print(expr.args[0])) def _print_Morphism(self, morphism): domain = self._print(morphism.domain) codomain = self._print(morphism.codomain) return "%s\\rightarrow %s" % (domain, codomain) def _print_TransferFunction(self, expr): num, den = self._print(expr.num), self._print(expr.den) return r"\frac{%s}{%s}" % (num, den) def _print_Series(self, expr): args = list(expr.args) parens = lambda x: self.parenthesize(x, precedence_traditional(expr), False) return ' '.join(map(parens, args)) def _print_MIMOSeries(self, expr): from sympy.physics.control.lti import MIMOParallel args = list(expr.args)[::-1] parens = lambda x: self.parenthesize(x, precedence_traditional(expr), False) if isinstance(x, MIMOParallel) else self._print(x) return r"\cdot".join(map(parens, args)) def _print_Parallel(self, expr): return ' + '.join(map(self._print, expr.args)) def _print_MIMOParallel(self, expr): return ' + '.join(map(self._print, expr.args)) def _print_Feedback(self, expr): from sympy.physics.control import TransferFunction, Series num, tf = expr.sys1, TransferFunction(1, 1, expr.var) num_arg_list = list(num.args) if isinstance(num, Series) else [num] den_arg_list = list(expr.sys2.args) if \ isinstance(expr.sys2, Series) else [expr.sys2] den_term_1 = tf if isinstance(num, Series) and isinstance(expr.sys2, Series): den_term_2 = Series(*num_arg_list, *den_arg_list) elif isinstance(num, Series) and isinstance(expr.sys2, TransferFunction): if expr.sys2 == tf: den_term_2 = Series(*num_arg_list) else: den_term_2 = tf, Series(*num_arg_list, expr.sys2) elif isinstance(num, TransferFunction) and isinstance(expr.sys2, Series): if num == tf: den_term_2 = Series(*den_arg_list) else: den_term_2 = Series(num, *den_arg_list) else: if num == tf: den_term_2 = Series(*den_arg_list) elif expr.sys2 == tf: den_term_2 = Series(*num_arg_list) else: den_term_2 = Series(*num_arg_list, *den_arg_list) numer = self._print(num) denom_1 = self._print(den_term_1) denom_2 = self._print(den_term_2) _sign = "+" if expr.sign == -1 else "-" return r"\frac{%s}{%s %s %s}" % (numer, denom_1, _sign, denom_2) def _print_MIMOFeedback(self, expr): from sympy.physics.control import MIMOSeries inv_mat = self._print(MIMOSeries(expr.sys2, expr.sys1)) sys1 = self._print(expr.sys1) _sign = "+" if expr.sign == -1 else "-" return r"\left(I_{\tau} %s %s\right)^{-1} \cdot %s" % (_sign, inv_mat, sys1) def _print_TransferFunctionMatrix(self, expr): mat = self._print(expr._expr_mat) return r"%s_\tau" % mat def _print_DFT(self, expr): return r"\text{{{}}}_{{{}}}".format(expr.__class__.__name__, expr.n) _print_IDFT = _print_DFT def _print_NamedMorphism(self, morphism): pretty_name = self._print(Symbol(morphism.name)) pretty_morphism = self._print_Morphism(morphism) return "%s:%s" % (pretty_name, pretty_morphism) def _print_IdentityMorphism(self, morphism): from sympy.categories import NamedMorphism return self._print_NamedMorphism(NamedMorphism( morphism.domain, morphism.codomain, "id")) def _print_CompositeMorphism(self, morphism): # All components of the morphism have names and it is thus # possible to build the name of the composite. component_names_list = [self._print(Symbol(component.name)) for component in morphism.components] component_names_list.reverse() component_names = "\\circ ".join(component_names_list) + ":" pretty_morphism = self._print_Morphism(morphism) return component_names + pretty_morphism def _print_Category(self, morphism): return r"\mathbf{{{}}}".format(self._print(Symbol(morphism.name))) def _print_Diagram(self, diagram): if not diagram.premises: # This is an empty diagram. return self._print(S.EmptySet) latex_result = self._print(diagram.premises) if diagram.conclusions: latex_result += "\\Longrightarrow %s" % \ self._print(diagram.conclusions) return latex_result def _print_DiagramGrid(self, grid): latex_result = "\\begin{array}{%s}\n" % ("c" * grid.width) for i in range(grid.height): for j in range(grid.width): if grid[i, j]: latex_result += latex(grid[i, j]) latex_result += " " if j != grid.width - 1: latex_result += "& " if i != grid.height - 1: latex_result += "\\\\" latex_result += "\n" latex_result += "\\end{array}\n" return latex_result def _print_FreeModule(self, M): return '{{{}}}^{{{}}}'.format(self._print(M.ring), self._print(M.rank)) def _print_FreeModuleElement(self, m): # Print as row vector for convenience, for now. return r"\left[ {} \right]".format(",".join( '{' + self._print(x) + '}' for x in m)) def _print_SubModule(self, m): return r"\left\langle {} \right\rangle".format(",".join( '{' + self._print(x) + '}' for x in m.gens)) def _print_ModuleImplementedIdeal(self, m): return r"\left\langle {} \right\rangle".format(",".join( '{' + self._print(x) + '}' for [x] in m._module.gens)) def _print_Quaternion(self, expr): # TODO: This expression is potentially confusing, # shall we print it as `Quaternion( ... )`? s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args] a = [s[0]] + [i+" "+j for i, j in zip(s[1:], "ijk")] return " + ".join(a) def _print_QuotientRing(self, R): # TODO nicer fractions for few generators... return r"\frac{{{}}}{{{}}}".format(self._print(R.ring), self._print(R.base_ideal)) def _print_QuotientRingElement(self, x): return r"{{{}}} + {{{}}}".format(self._print(x.data), self._print(x.ring.base_ideal)) def _print_QuotientModuleElement(self, m): return r"{{{}}} + {{{}}}".format(self._print(m.data), self._print(m.module.killed_module)) def _print_QuotientModule(self, M): # TODO nicer fractions for few generators... return r"\frac{{{}}}{{{}}}".format(self._print(M.base), self._print(M.killed_module)) def _print_MatrixHomomorphism(self, h): return r"{{{}}} : {{{}}} \to {{{}}}".format(self._print(h._sympy_matrix()), self._print(h.domain), self._print(h.codomain)) def _print_Manifold(self, manifold): string = manifold.name.name if '{' in string: name, supers, subs = string, [], [] else: name, supers, subs = split_super_sub(string) name = translate(name) supers = [translate(sup) for sup in supers] subs = [translate(sub) for sub in subs] name = r'\text{%s}' % name if supers: name += "^{%s}" % " ".join(supers) if subs: name += "_{%s}" % " ".join(subs) return name def _print_Patch(self, patch): return r'\text{%s}_{%s}' % (self._print(patch.name), self._print(patch.manifold)) def _print_CoordSystem(self, coordsys): return r'\text{%s}^{\text{%s}}_{%s}' % ( self._print(coordsys.name), self._print(coordsys.patch.name), self._print(coordsys.manifold) ) def _print_CovarDerivativeOp(self, cvd): return r'\mathbb{\nabla}_{%s}' % self._print(cvd._wrt) def _print_BaseScalarField(self, field): string = field._coord_sys.symbols[field._index].name return r'\mathbf{{{}}}'.format(self._print(Symbol(string))) def _print_BaseVectorField(self, field): string = field._coord_sys.symbols[field._index].name return r'\partial_{{{}}}'.format(self._print(Symbol(string))) def _print_Differential(self, diff): field = diff._form_field if hasattr(field, '_coord_sys'): string = field._coord_sys.symbols[field._index].name return r'\operatorname{{d}}{}'.format(self._print(Symbol(string))) else: string = self._print(field) return r'\operatorname{{d}}\left({}\right)'.format(string) def _print_Tr(self, p): # TODO: Handle indices contents = self._print(p.args[0]) return r'\operatorname{{tr}}\left({}\right)'.format(contents) def _print_totient(self, expr, exp=None): if exp is not None: return r'\left(\phi\left(%s\right)\right)^{%s}' % \ (self._print(expr.args[0]), exp) return r'\phi\left(%s\right)' % self._print(expr.args[0]) def _print_reduced_totient(self, expr, exp=None): if exp is not None: return r'\left(\lambda\left(%s\right)\right)^{%s}' % \ (self._print(expr.args[0]), exp) return r'\lambda\left(%s\right)' % self._print(expr.args[0]) def _print_divisor_sigma(self, expr, exp=None): if len(expr.args) == 2: tex = r"_%s\left(%s\right)" % tuple(map(self._print, (expr.args[1], expr.args[0]))) else: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\sigma^{%s}%s" % (exp, tex) return r"\sigma%s" % tex def _print_udivisor_sigma(self, expr, exp=None): if len(expr.args) == 2: tex = r"_%s\left(%s\right)" % tuple(map(self._print, (expr.args[1], expr.args[0]))) else: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\sigma^*^{%s}%s" % (exp, tex) return r"\sigma^*%s" % tex def _print_primenu(self, expr, exp=None): if exp is not None: return r'\left(\nu\left(%s\right)\right)^{%s}' % \ (self._print(expr.args[0]), exp) return r'\nu\left(%s\right)' % self._print(expr.args[0]) def _print_primeomega(self, expr, exp=None): if exp is not None: return r'\left(\Omega\left(%s\right)\right)^{%s}' % \ (self._print(expr.args[0]), exp) return r'\Omega\left(%s\right)' % self._print(expr.args[0]) def _print_Str(self, s): return str(s.name) def _print_float(self, expr): return self._print(Float(expr)) def _print_int(self, expr): return str(expr) def _print_mpz(self, expr): return str(expr) def _print_mpq(self, expr): return str(expr) def _print_Predicate(self, expr): return r"\operatorname{{Q}}_{{\text{{{}}}}}".format(latex_escape(str(expr.name))) def _print_AppliedPredicate(self, expr): pred = expr.function args = expr.arguments pred_latex = self._print(pred) args_latex = ', '.join([self._print(a) for a in args]) return '%s(%s)' % (pred_latex, args_latex) def emptyPrinter(self, expr): # default to just printing as monospace, like would normally be shown s = super().emptyPrinter(expr) return r"\mathtt{\text{%s}}" % latex_escape(s) def translate(s: str) -> str: r''' Check for a modifier ending the string. If present, convert the modifier to latex and translate the rest recursively. Given a description of a Greek letter or other special character, return the appropriate latex. Let everything else pass as given. >>> from sympy.printing.latex import translate >>> translate('alphahatdotprime') "{\\dot{\\hat{\\alpha}}}'" ''' # Process the rest tex = tex_greek_dictionary.get(s) if tex: return tex elif s.lower() in greek_letters_set: return "\\" + s.lower() elif s in other_symbols: return "\\" + s else: # Process modifiers, if any, and recurse for key in sorted(modifier_dict.keys(), key=len, reverse=True): if s.lower().endswith(key) and len(s) > len(key): return modifier_dict[key](translate(s[:-len(key)])) return s @print_function(LatexPrinter) def latex(expr, **settings): r"""Convert the given expression to LaTeX string representation. Parameters ========== full_prec: boolean, optional If set to True, a floating point number is printed with full precision. fold_frac_powers : boolean, optional Emit ``^{p/q}`` instead of ``^{\frac{p}{q}}`` for fractional powers. fold_func_brackets : boolean, optional Fold function brackets where applicable. fold_short_frac : boolean, optional Emit ``p / q`` instead of ``\frac{p}{q}`` when the denominator is simple enough (at most two terms and no powers). The default value is ``True`` for inline mode, ``False`` otherwise. inv_trig_style : string, optional How inverse trig functions should be displayed. Can be one of ``'abbreviated'``, ``'full'``, or ``'power'``. Defaults to ``'abbreviated'``. itex : boolean, optional Specifies if itex-specific syntax is used, including emitting ``$$...$$``. ln_notation : boolean, optional If set to ``True``, ``\ln`` is used instead of default ``\log``. long_frac_ratio : float or None, optional The allowed ratio of the width of the numerator to the width of the denominator before the printer breaks off long fractions. If ``None`` (the default value), long fractions are not broken up. mat_delim : string, optional The delimiter to wrap around matrices. Can be one of ``'['``, ``'('``, or the empty string ``''``. Defaults to ``'['``. mat_str : string, optional Which matrix environment string to emit. ``'smallmatrix'``, ``'matrix'``, ``'array'``, etc. Defaults to ``'smallmatrix'`` for inline mode, ``'matrix'`` for matrices of no more than 10 columns, and ``'array'`` otherwise. mode: string, optional Specifies how the generated code will be delimited. ``mode`` can be one of ``'plain'``, ``'inline'``, ``'equation'`` or ``'equation*'``. If ``mode`` is set to ``'plain'``, then the resulting code will not be delimited at all (this is the default). If ``mode`` is set to ``'inline'`` then inline LaTeX ``$...$`` will be used. If ``mode`` is set to ``'equation'`` or ``'equation*'``, the resulting code will be enclosed in the ``equation`` or ``equation*`` environment (remember to import ``amsmath`` for ``equation*``), unless the ``itex`` option is set. In the latter case, the ``$$...$$`` syntax is used. mul_symbol : string or None, optional The symbol to use for multiplication. Can be one of ``None``, ``'ldot'``, ``'dot'``, or ``'times'``. order: string, optional Any of the supported monomial orderings (currently ``'lex'``, ``'grlex'``, or ``'grevlex'``), ``'old'``, and ``'none'``. This parameter does nothing for `~.Mul` objects. Setting order to ``'old'`` uses the compatibility ordering for ``~.Add`` defined in Printer. For very large expressions, set the ``order`` keyword to ``'none'`` if speed is a concern. symbol_names : dictionary of strings mapped to symbols, optional Dictionary of symbols and the custom strings they should be emitted as. root_notation : boolean, optional If set to ``False``, exponents of the form 1/n are printed in fractonal form. Default is ``True``, to print exponent in root form. mat_symbol_style : string, optional Can be either ``'plain'`` (default) or ``'bold'``. If set to ``'bold'``, a `~.MatrixSymbol` A will be printed as ``\mathbf{A}``, otherwise as ``A``. imaginary_unit : string, optional String to use for the imaginary unit. Defined options are ``'i'`` (default) and ``'j'``. Adding ``r`` or ``t`` in front gives ``\mathrm`` or ``\text``, so ``'ri'`` leads to ``\mathrm{i}`` which gives `\mathrm{i}`. gothic_re_im : boolean, optional If set to ``True``, `\Re` and `\Im` is used for ``re`` and ``im``, respectively. The default is ``False`` leading to `\operatorname{re}` and `\operatorname{im}`. decimal_separator : string, optional Specifies what separator to use to separate the whole and fractional parts of a floating point number as in `2.5` for the default, ``period`` or `2{,}5` when ``comma`` is specified. Lists, sets, and tuple are printed with semicolon separating the elements when ``comma`` is chosen. For example, [1; 2; 3] when ``comma`` is chosen and [1,2,3] for when ``period`` is chosen. parenthesize_super : boolean, optional If set to ``False``, superscripted expressions will not be parenthesized when powered. Default is ``True``, which parenthesizes the expression when powered. min: Integer or None, optional Sets the lower bound for the exponent to print floating point numbers in fixed-point format. max: Integer or None, optional Sets the upper bound for the exponent to print floating point numbers in fixed-point format. diff_operator: string, optional String to use for differential operator. Default is ``'d'``, to print in italic form. ``'rd'``, ``'td'`` are shortcuts for ``\mathrm{d}`` and ``\text{d}``. Notes ===== Not using a print statement for printing, results in double backslashes for latex commands since that's the way Python escapes backslashes in strings. >>> from sympy import latex, Rational >>> from sympy.abc import tau >>> latex((2*tau)**Rational(7,2)) '8 \\sqrt{2} \\tau^{\\frac{7}{2}}' >>> print(latex((2*tau)**Rational(7,2))) 8 \sqrt{2} \tau^{\frac{7}{2}} Examples ======== >>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log >>> from sympy.abc import x, y, mu, r, tau Basic usage: >>> print(latex((2*tau)**Rational(7,2))) 8 \sqrt{2} \tau^{\frac{7}{2}} ``mode`` and ``itex`` options: >>> print(latex((2*mu)**Rational(7,2), mode='plain')) 8 \sqrt{2} \mu^{\frac{7}{2}} >>> print(latex((2*tau)**Rational(7,2), mode='inline')) $8 \sqrt{2} \tau^{7 / 2}$ >>> print(latex((2*mu)**Rational(7,2), mode='equation*')) \begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*} >>> print(latex((2*mu)**Rational(7,2), mode='equation')) \begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation} >>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True)) $$8 \sqrt{2} \mu^{\frac{7}{2}}$$ >>> print(latex((2*mu)**Rational(7,2), mode='plain')) 8 \sqrt{2} \mu^{\frac{7}{2}} >>> print(latex((2*tau)**Rational(7,2), mode='inline')) $8 \sqrt{2} \tau^{7 / 2}$ >>> print(latex((2*mu)**Rational(7,2), mode='equation*')) \begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*} >>> print(latex((2*mu)**Rational(7,2), mode='equation')) \begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation} >>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True)) $$8 \sqrt{2} \mu^{\frac{7}{2}}$$ Fraction options: >>> print(latex((2*tau)**Rational(7,2), fold_frac_powers=True)) 8 \sqrt{2} \tau^{7/2} >>> print(latex((2*tau)**sin(Rational(7,2)))) \left(2 \tau\right)^{\sin{\left(\frac{7}{2} \right)}} >>> print(latex((2*tau)**sin(Rational(7,2)), fold_func_brackets=True)) \left(2 \tau\right)^{\sin {\frac{7}{2}}} >>> print(latex(3*x**2/y)) \frac{3 x^{2}}{y} >>> print(latex(3*x**2/y, fold_short_frac=True)) 3 x^{2} / y >>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=2)) \frac{\int r\, dr}{2 \pi} >>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=0)) \frac{1}{2 \pi} \int r\, dr Multiplication options: >>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol="times")) \left(2 \times \tau\right)^{\sin{\left(\frac{7}{2} \right)}} Trig options: >>> print(latex(asin(Rational(7,2)))) \operatorname{asin}{\left(\frac{7}{2} \right)} >>> print(latex(asin(Rational(7,2)), inv_trig_style="full")) \arcsin{\left(\frac{7}{2} \right)} >>> print(latex(asin(Rational(7,2)), inv_trig_style="power")) \sin^{-1}{\left(\frac{7}{2} \right)} Matrix options: >>> print(latex(Matrix(2, 1, [x, y]))) \left[\begin{matrix}x\\y\end{matrix}\right] >>> print(latex(Matrix(2, 1, [x, y]), mat_str = "array")) \left[\begin{array}{c}x\\y\end{array}\right] >>> print(latex(Matrix(2, 1, [x, y]), mat_delim="(")) \left(\begin{matrix}x\\y\end{matrix}\right) Custom printing of symbols: >>> print(latex(x**2, symbol_names={x: 'x_i'})) x_i^{2} Logarithms: >>> print(latex(log(10))) \log{\left(10 \right)} >>> print(latex(log(10), ln_notation=True)) \ln{\left(10 \right)} ``latex()`` also supports the builtin container types :class:`list`, :class:`tuple`, and :class:`dict`: >>> print(latex([2/x, y], mode='inline')) $\left[ 2 / x, \ y\right]$ Unsupported types are rendered as monospaced plaintext: >>> print(latex(int)) \mathtt{\text{<class 'int'>}} >>> print(latex("plain % text")) \mathtt{\text{plain \% text}} See :ref:`printer_method_example` for an example of how to override this behavior for your own types by implementing ``_latex``. .. versionchanged:: 1.7.0 Unsupported types no longer have their ``str`` representation treated as valid latex. """ return LatexPrinter(settings).doprint(expr) def print_latex(expr, **settings): """Prints LaTeX representation of the given expression. Takes the same settings as ``latex()``.""" print(latex(expr, **settings)) def multiline_latex(lhs, rhs, terms_per_line=1, environment="align*", use_dots=False, **settings): r""" This function generates a LaTeX equation with a multiline right-hand side in an ``align*``, ``eqnarray`` or ``IEEEeqnarray`` environment. Parameters ========== lhs : Expr Left-hand side of equation rhs : Expr Right-hand side of equation terms_per_line : integer, optional Number of terms per line to print. Default is 1. environment : "string", optional Which LaTeX wnvironment to use for the output. Options are "align*" (default), "eqnarray", and "IEEEeqnarray". use_dots : boolean, optional If ``True``, ``\\dots`` is added to the end of each line. Default is ``False``. Examples ======== >>> from sympy import multiline_latex, symbols, sin, cos, exp, log, I >>> x, y, alpha = symbols('x y alpha') >>> expr = sin(alpha*y) + exp(I*alpha) - cos(log(y)) >>> print(multiline_latex(x, expr)) \begin{align*} x = & e^{i \alpha} \\ & + \sin{\left(\alpha y \right)} \\ & - \cos{\left(\log{\left(y \right)} \right)} \end{align*} Using at most two terms per line: >>> print(multiline_latex(x, expr, 2)) \begin{align*} x = & e^{i \alpha} + \sin{\left(\alpha y \right)} \\ & - \cos{\left(\log{\left(y \right)} \right)} \end{align*} Using ``eqnarray`` and dots: >>> print(multiline_latex(x, expr, terms_per_line=2, environment="eqnarray", use_dots=True)) \begin{eqnarray} x & = & e^{i \alpha} + \sin{\left(\alpha y \right)} \dots\nonumber\\ & & - \cos{\left(\log{\left(y \right)} \right)} \end{eqnarray} Using ``IEEEeqnarray``: >>> print(multiline_latex(x, expr, environment="IEEEeqnarray")) \begin{IEEEeqnarray}{rCl} x & = & e^{i \alpha} \nonumber\\ & & + \sin{\left(\alpha y \right)} \nonumber\\ & & - \cos{\left(\log{\left(y \right)} \right)} \end{IEEEeqnarray} Notes ===== All optional parameters from ``latex`` can also be used. """ # Based on code from https://github.com/sympy/sympy/issues/3001 l = LatexPrinter(**settings) if environment == "eqnarray": result = r'\begin{eqnarray}' + '\n' first_term = '& = &' nonumber = r'\nonumber' end_term = '\n\\end{eqnarray}' doubleet = True elif environment == "IEEEeqnarray": result = r'\begin{IEEEeqnarray}{rCl}' + '\n' first_term = '& = &' nonumber = r'\nonumber' end_term = '\n\\end{IEEEeqnarray}' doubleet = True elif environment == "align*": result = r'\begin{align*}' + '\n' first_term = '= &' nonumber = '' end_term = '\n\\end{align*}' doubleet = False else: raise ValueError("Unknown environment: {}".format(environment)) dots = '' if use_dots: dots=r'\dots' terms = rhs.as_ordered_terms() n_terms = len(terms) term_count = 1 for i in range(n_terms): term = terms[i] term_start = '' term_end = '' sign = '+' if term_count > terms_per_line: if doubleet: term_start = '& & ' else: term_start = '& ' term_count = 1 if term_count == terms_per_line: # End of line if i < n_terms-1: # There are terms remaining term_end = dots + nonumber + r'\\' + '\n' else: term_end = '' if term.as_ordered_factors()[0] == -1: term = -1*term sign = r'-' if i == 0: # beginning if sign == '+': sign = '' result += r'{:s} {:s}{:s} {:s} {:s}'.format(l.doprint(lhs), first_term, sign, l.doprint(term), term_end) else: result += r'{:s}{:s} {:s} {:s}'.format(term_start, sign, l.doprint(term), term_end) term_count += 1 result += end_term return result
d6848f8c62d89b20e90ed17dfe5eefa31b3ffa682a1ce2e09a539f709a123de8
from __future__ import annotations import numbers import decimal import fractions import math import re as regex import sys from functools import lru_cache from .containers import Tuple from .sympify import (SympifyError, _sympy_converter, sympify, _convert_numpy_types, _sympify, _is_numpy_instance) from .singleton import S, Singleton from .basic import Basic from .expr import Expr, AtomicExpr from .evalf import pure_complex from .cache import cacheit, clear_cache from .decorators import _sympifyit from .logic import fuzzy_not from .kind import NumberKind from sympy.external.gmpy import SYMPY_INTS, HAS_GMPY, gmpy from sympy.multipledispatch import dispatch import mpmath import mpmath.libmp as mlib from mpmath.libmp import bitcount, round_nearest as rnd from mpmath.libmp.backend import MPZ from mpmath.libmp import mpf_pow, mpf_pi, mpf_e, phi_fixed from mpmath.ctx_mp import mpnumeric from mpmath.libmp.libmpf import ( finf as _mpf_inf, fninf as _mpf_ninf, fnan as _mpf_nan, fzero, _normalize as mpf_normalize, prec_to_dps, dps_to_prec) from sympy.utilities.misc import as_int, debug, filldedent from .parameters import global_parameters _LOG2 = math.log(2) def comp(z1, z2, tol=None): r"""Return a bool indicating whether the error between z1 and z2 is $\le$ ``tol``. Examples ======== If ``tol`` is ``None`` then ``True`` will be returned if :math:`|z1 - z2|\times 10^p \le 5` where $p$ is minimum value of the decimal precision of each value. >>> from sympy import comp, pi >>> pi4 = pi.n(4); pi4 3.142 >>> comp(_, 3.142) True >>> comp(pi4, 3.141) False >>> comp(pi4, 3.143) False A comparison of strings will be made if ``z1`` is a Number and ``z2`` is a string or ``tol`` is ''. >>> comp(pi4, 3.1415) True >>> comp(pi4, 3.1415, '') False When ``tol`` is provided and $z2$ is non-zero and :math:`|z1| > 1` the error is normalized by :math:`|z1|`: >>> abs(pi4 - 3.14)/pi4 0.000509791731426756 >>> comp(pi4, 3.14, .001) # difference less than 0.1% True >>> comp(pi4, 3.14, .0005) # difference less than 0.1% False When :math:`|z1| \le 1` the absolute error is used: >>> 1/pi4 0.3183 >>> abs(1/pi4 - 0.3183)/(1/pi4) 3.07371499106316e-5 >>> abs(1/pi4 - 0.3183) 9.78393554684764e-6 >>> comp(1/pi4, 0.3183, 1e-5) True To see if the absolute error between ``z1`` and ``z2`` is less than or equal to ``tol``, call this as ``comp(z1 - z2, 0, tol)`` or ``comp(z1 - z2, tol=tol)``: >>> abs(pi4 - 3.14) 0.00160156249999988 >>> comp(pi4 - 3.14, 0, .002) True >>> comp(pi4 - 3.14, 0, .001) False """ if isinstance(z2, str): if not pure_complex(z1, or_real=True): raise ValueError('when z2 is a str z1 must be a Number') return str(z1) == z2 if not z1: z1, z2 = z2, z1 if not z1: return True if not tol: a, b = z1, z2 if tol == '': return str(a) == str(b) if tol is None: a, b = sympify(a), sympify(b) if not all(i.is_number for i in (a, b)): raise ValueError('expecting 2 numbers') fa = a.atoms(Float) fb = b.atoms(Float) if not fa and not fb: # no floats -- compare exactly return a == b # get a to be pure_complex for _ in range(2): ca = pure_complex(a, or_real=True) if not ca: if fa: a = a.n(prec_to_dps(min([i._prec for i in fa]))) ca = pure_complex(a, or_real=True) break else: fa, fb = fb, fa a, b = b, a cb = pure_complex(b) if not cb and fb: b = b.n(prec_to_dps(min([i._prec for i in fb]))) cb = pure_complex(b, or_real=True) if ca and cb and (ca[1] or cb[1]): return all(comp(i, j) for i, j in zip(ca, cb)) tol = 10**prec_to_dps(min(a._prec, getattr(b, '_prec', a._prec))) return int(abs(a - b)*tol) <= 5 diff = abs(z1 - z2) az1 = abs(z1) if z2 and az1 > 1: return diff/az1 <= tol else: return diff <= tol def mpf_norm(mpf, prec): """Return the mpf tuple normalized appropriately for the indicated precision after doing a check to see if zero should be returned or not when the mantissa is 0. ``mpf_normlize`` always assumes that this is zero, but it may not be since the mantissa for mpf's values "+inf", "-inf" and "nan" have a mantissa of zero, too. Note: this is not intended to validate a given mpf tuple, so sending mpf tuples that were not created by mpmath may produce bad results. This is only a wrapper to ``mpf_normalize`` which provides the check for non- zero mpfs that have a 0 for the mantissa. """ sign, man, expt, bc = mpf if not man: # hack for mpf_normalize which does not do this; # it assumes that if man is zero the result is 0 # (see issue 6639) if not bc: return fzero else: # don't change anything; this should already # be a well formed mpf tuple return mpf # Necessary if mpmath is using the gmpy backend from mpmath.libmp.backend import MPZ rv = mpf_normalize(sign, MPZ(man), expt, bc, prec, rnd) return rv # TODO: we should use the warnings module _errdict = {"divide": False} def seterr(divide=False): """ Should SymPy raise an exception on 0/0 or return a nan? divide == True .... raise an exception divide == False ... return nan """ if _errdict["divide"] != divide: clear_cache() _errdict["divide"] = divide def _as_integer_ratio(p): neg_pow, man, expt, _ = getattr(p, '_mpf_', mpmath.mpf(p)._mpf_) p = [1, -1][neg_pow % 2]*man if expt < 0: q = 2**-expt else: q = 1 p *= 2**expt return int(p), int(q) def _decimal_to_Rational_prec(dec): """Convert an ordinary decimal instance to a Rational.""" if not dec.is_finite(): raise TypeError("dec must be finite, got %s." % dec) s, d, e = dec.as_tuple() prec = len(d) if e >= 0: # it's an integer rv = Integer(int(dec)) else: s = (-1)**s d = sum([di*10**i for i, di in enumerate(reversed(d))]) rv = Rational(s*d, 10**-e) return rv, prec _floatpat = regex.compile(r"[-+]?((\d*\.\d+)|(\d+\.?))") def _literal_float(f): """Return True if n starts like a floating point number.""" return bool(_floatpat.match(f)) # (a,b) -> gcd(a,b) # TODO caching with decorator, but not to degrade performance @lru_cache(1024) def igcd(*args): """Computes nonnegative integer greatest common divisor. Explanation =========== The algorithm is based on the well known Euclid's algorithm [1]_. To improve speed, ``igcd()`` has its own caching mechanism. Examples ======== >>> from sympy import igcd >>> igcd(2, 4) 2 >>> igcd(5, 10, 15) 5 References ========== .. [1] https://en.wikipedia.org/wiki/Euclidean_algorithm """ if len(args) < 2: raise TypeError( 'igcd() takes at least 2 arguments (%s given)' % len(args)) args_temp = [abs(as_int(i)) for i in args] if 1 in args_temp: return 1 a = args_temp.pop() if HAS_GMPY: # Using gmpy if present to speed up. for b in args_temp: a = gmpy.gcd(a, b) if b else a return as_int(a) for b in args_temp: a = math.gcd(a, b) return a igcd2 = math.gcd def igcd_lehmer(a, b): r"""Computes greatest common divisor of two integers. Explanation =========== Euclid's algorithm for the computation of the greatest common divisor ``gcd(a, b)`` of two (positive) integers $a$ and $b$ is based on the division identity $$ a = q \times b + r$$, where the quotient $q$ and the remainder $r$ are integers and $0 \le r < b$. Then each common divisor of $a$ and $b$ divides $r$, and it follows that ``gcd(a, b) == gcd(b, r)``. The algorithm works by constructing the sequence r0, r1, r2, ..., where r0 = a, r1 = b, and each rn is the remainder from the division of the two preceding elements. In Python, ``q = a // b`` and ``r = a % b`` are obtained by the floor division and the remainder operations, respectively. These are the most expensive arithmetic operations, especially for large a and b. Lehmer's algorithm [1]_ is based on the observation that the quotients ``qn = r(n-1) // rn`` are in general small integers even when a and b are very large. Hence the quotients can be usually determined from a relatively small number of most significant bits. The efficiency of the algorithm is further enhanced by not computing each long remainder in Euclid's sequence. The remainders are linear combinations of a and b with integer coefficients derived from the quotients. The coefficients can be computed as far as the quotients can be determined from the chosen most significant parts of a and b. Only then a new pair of consecutive remainders is computed and the algorithm starts anew with this pair. References ========== .. [1] https://en.wikipedia.org/wiki/Lehmer%27s_GCD_algorithm """ a, b = abs(as_int(a)), abs(as_int(b)) if a < b: a, b = b, a # The algorithm works by using one or two digit division # whenever possible. The outer loop will replace the # pair (a, b) with a pair of shorter consecutive elements # of the Euclidean gcd sequence until a and b # fit into two Python (long) int digits. nbits = 2*sys.int_info.bits_per_digit while a.bit_length() > nbits and b != 0: # Quotients are mostly small integers that can # be determined from most significant bits. n = a.bit_length() - nbits x, y = int(a >> n), int(b >> n) # most significant bits # Elements of the Euclidean gcd sequence are linear # combinations of a and b with integer coefficients. # Compute the coefficients of consecutive pairs # a' = A*a + B*b, b' = C*a + D*b # using small integer arithmetic as far as possible. A, B, C, D = 1, 0, 0, 1 # initial values while True: # The coefficients alternate in sign while looping. # The inner loop combines two steps to keep track # of the signs. # At this point we have # A > 0, B <= 0, C <= 0, D > 0, # x' = x + B <= x < x" = x + A, # y' = y + C <= y < y" = y + D, # and # x'*N <= a' < x"*N, y'*N <= b' < y"*N, # where N = 2**n. # Now, if y' > 0, and x"//y' and x'//y" agree, # then their common value is equal to q = a'//b'. # In addition, # x'%y" = x' - q*y" < x" - q*y' = x"%y', # and # (x'%y")*N < a'%b' < (x"%y')*N. # On the other hand, we also have x//y == q, # and therefore # x'%y" = x + B - q*(y + D) = x%y + B', # x"%y' = x + A - q*(y + C) = x%y + A', # where # B' = B - q*D < 0, A' = A - q*C > 0. if y + C <= 0: break q = (x + A) // (y + C) # Now x'//y" <= q, and equality holds if # x' - q*y" = (x - q*y) + (B - q*D) >= 0. # This is a minor optimization to avoid division. x_qy, B_qD = x - q*y, B - q*D if x_qy + B_qD < 0: break # Next step in the Euclidean sequence. x, y = y, x_qy A, B, C, D = C, D, A - q*C, B_qD # At this point the signs of the coefficients # change and their roles are interchanged. # A <= 0, B > 0, C > 0, D < 0, # x' = x + A <= x < x" = x + B, # y' = y + D < y < y" = y + C. if y + D <= 0: break q = (x + B) // (y + D) x_qy, A_qC = x - q*y, A - q*C if x_qy + A_qC < 0: break x, y = y, x_qy A, B, C, D = C, D, A_qC, B - q*D # Now the conditions on top of the loop # are again satisfied. # A > 0, B < 0, C < 0, D > 0. if B == 0: # This can only happen when y == 0 in the beginning # and the inner loop does nothing. # Long division is forced. a, b = b, a % b continue # Compute new long arguments using the coefficients. a, b = A*a + B*b, C*a + D*b # Small divisors. Finish with the standard algorithm. while b: a, b = b, a % b return a def ilcm(*args): """Computes integer least common multiple. Examples ======== >>> from sympy import ilcm >>> ilcm(5, 10) 10 >>> ilcm(7, 3) 21 >>> ilcm(5, 10, 15) 30 """ if len(args) < 2: raise TypeError( 'ilcm() takes at least 2 arguments (%s given)' % len(args)) if 0 in args: return 0 a = args[0] for b in args[1:]: a = a // igcd(a, b) * b # since gcd(a,b) | a return a def igcdex(a, b): """Returns x, y, g such that g = x*a + y*b = gcd(a, b). Examples ======== >>> from sympy.core.numbers import igcdex >>> igcdex(2, 3) (-1, 1, 1) >>> igcdex(10, 12) (-1, 1, 2) >>> x, y, g = igcdex(100, 2004) >>> x, y, g (-20, 1, 4) >>> x*100 + y*2004 4 """ if (not a) and (not b): return (0, 1, 0) if not a: return (0, b//abs(b), abs(b)) if not b: return (a//abs(a), 0, abs(a)) if a < 0: a, x_sign = -a, -1 else: x_sign = 1 if b < 0: b, y_sign = -b, -1 else: y_sign = 1 x, y, r, s = 1, 0, 0, 1 while b: (c, q) = (a % b, a // b) (a, b, r, s, x, y) = (b, c, x - q*r, y - q*s, r, s) return (x*x_sign, y*y_sign, a) def mod_inverse(a, m): r""" Return the number $c$ such that, $a \times c = 1 \pmod{m}$ where $c$ has the same sign as $m$. If no such value exists, a ValueError is raised. Examples ======== >>> from sympy import mod_inverse, S Suppose we wish to find multiplicative inverse $x$ of 3 modulo 11. This is the same as finding $x$ such that $3x = 1 \pmod{11}$. One value of x that satisfies this congruence is 4. Because $3 \times 4 = 12$ and $12 = 1 \pmod{11}$. This is the value returned by ``mod_inverse``: >>> mod_inverse(3, 11) 4 >>> mod_inverse(-3, 11) 7 When there is a common factor between the numerators of `a` and `m` the inverse does not exist: >>> mod_inverse(2, 4) Traceback (most recent call last): ... ValueError: inverse of 2 mod 4 does not exist >>> mod_inverse(S(2)/7, S(5)/2) 7/2 References ========== .. [1] https://en.wikipedia.org/wiki/Modular_multiplicative_inverse .. [2] https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm """ c = None try: a, m = as_int(a), as_int(m) if m != 1 and m != -1: x, _, g = igcdex(a, m) if g == 1: c = x % m except ValueError: a, m = sympify(a), sympify(m) if not (a.is_number and m.is_number): raise TypeError(filldedent(''' Expected numbers for arguments; symbolic `mod_inverse` is not implemented but symbolic expressions can be handled with the similar function, sympy.polys.polytools.invert''')) big = (m > 1) if big not in (S.true, S.false): raise ValueError('m > 1 did not evaluate; try to simplify %s' % m) elif big: c = 1/a if c is None: raise ValueError('inverse of %s (mod %s) does not exist' % (a, m)) return c class Number(AtomicExpr): """Represents atomic numbers in SymPy. Explanation =========== Floating point numbers are represented by the Float class. Rational numbers (of any size) are represented by the Rational class. Integer numbers (of any size) are represented by the Integer class. Float and Rational are subclasses of Number; Integer is a subclass of Rational. For example, ``2/3`` is represented as ``Rational(2, 3)`` which is a different object from the floating point number obtained with Python division ``2/3``. Even for numbers that are exactly represented in binary, there is a difference between how two forms, such as ``Rational(1, 2)`` and ``Float(0.5)``, are used in SymPy. The rational form is to be preferred in symbolic computations. Other kinds of numbers, such as algebraic numbers ``sqrt(2)`` or complex numbers ``3 + 4*I``, are not instances of Number class as they are not atomic. See Also ======== Float, Integer, Rational """ is_commutative = True is_number = True is_Number = True __slots__ = () # Used to make max(x._prec, y._prec) return x._prec when only x is a float _prec = -1 kind = NumberKind def __new__(cls, *obj): if len(obj) == 1: obj = obj[0] if isinstance(obj, Number): return obj if isinstance(obj, SYMPY_INTS): return Integer(obj) if isinstance(obj, tuple) and len(obj) == 2: return Rational(*obj) if isinstance(obj, (float, mpmath.mpf, decimal.Decimal)): return Float(obj) if isinstance(obj, str): _obj = obj.lower() # float('INF') == float('inf') if _obj == 'nan': return S.NaN elif _obj == 'inf': return S.Infinity elif _obj == '+inf': return S.Infinity elif _obj == '-inf': return S.NegativeInfinity val = sympify(obj) if isinstance(val, Number): return val else: raise ValueError('String "%s" does not denote a Number' % obj) msg = "expected str|int|long|float|Decimal|Number object but got %r" raise TypeError(msg % type(obj).__name__) def could_extract_minus_sign(self): return bool(self.is_extended_negative) def invert(self, other, *gens, **args): from sympy.polys.polytools import invert if getattr(other, 'is_number', True): return mod_inverse(self, other) return invert(self, other, *gens, **args) def __divmod__(self, other): from sympy.functions.elementary.complexes import sign try: other = Number(other) if self.is_infinite or S.NaN in (self, other): return (S.NaN, S.NaN) except TypeError: return NotImplemented if not other: raise ZeroDivisionError('modulo by zero') if self.is_Integer and other.is_Integer: return Tuple(*divmod(self.p, other.p)) elif isinstance(other, Float): rat = self/Rational(other) else: rat = self/other if other.is_finite: w = int(rat) if rat >= 0 else int(rat) - 1 r = self - other*w else: w = 0 if not self or (sign(self) == sign(other)) else -1 r = other if w else self return Tuple(w, r) def __rdivmod__(self, other): try: other = Number(other) except TypeError: return NotImplemented return divmod(other, self) def _as_mpf_val(self, prec): """Evaluation of mpf tuple accurate to at least prec bits.""" raise NotImplementedError('%s needs ._as_mpf_val() method' % (self.__class__.__name__)) def _eval_evalf(self, prec): return Float._new(self._as_mpf_val(prec), prec) def _as_mpf_op(self, prec): prec = max(prec, self._prec) return self._as_mpf_val(prec), prec def __float__(self): return mlib.to_float(self._as_mpf_val(53)) def floor(self): raise NotImplementedError('%s needs .floor() method' % (self.__class__.__name__)) def ceiling(self): raise NotImplementedError('%s needs .ceiling() method' % (self.__class__.__name__)) def __floor__(self): return self.floor() def __ceil__(self): return self.ceiling() def _eval_conjugate(self): return self def _eval_order(self, *symbols): from sympy.series.order import Order # Order(5, x, y) -> Order(1,x,y) return Order(S.One, *symbols) def _eval_subs(self, old, new): if old == -self: return -new return self # there is no other possibility @classmethod def class_key(cls): return 1, 0, 'Number' @cacheit def sort_key(self, order=None): return self.class_key(), (0, ()), (), self @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other is S.NaN: return S.NaN elif other is S.Infinity: return S.Infinity elif other is S.NegativeInfinity: return S.NegativeInfinity return AtomicExpr.__add__(self, other) @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other is S.NaN: return S.NaN elif other is S.Infinity: return S.NegativeInfinity elif other is S.NegativeInfinity: return S.Infinity return AtomicExpr.__sub__(self, other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other is S.NaN: return S.NaN elif other is S.Infinity: if self.is_zero: return S.NaN elif self.is_positive: return S.Infinity else: return S.NegativeInfinity elif other is S.NegativeInfinity: if self.is_zero: return S.NaN elif self.is_positive: return S.NegativeInfinity else: return S.Infinity elif isinstance(other, Tuple): return NotImplemented return AtomicExpr.__mul__(self, other) @_sympifyit('other', NotImplemented) def __truediv__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other is S.NaN: return S.NaN elif other in (S.Infinity, S.NegativeInfinity): return S.Zero return AtomicExpr.__truediv__(self, other) def __eq__(self, other): raise NotImplementedError('%s needs .__eq__() method' % (self.__class__.__name__)) def __ne__(self, other): raise NotImplementedError('%s needs .__ne__() method' % (self.__class__.__name__)) def __lt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s < %s" % (self, other)) raise NotImplementedError('%s needs .__lt__() method' % (self.__class__.__name__)) def __le__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s <= %s" % (self, other)) raise NotImplementedError('%s needs .__le__() method' % (self.__class__.__name__)) def __gt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s > %s" % (self, other)) return _sympify(other).__lt__(self) def __ge__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s >= %s" % (self, other)) return _sympify(other).__le__(self) def __hash__(self): return super().__hash__() def is_constant(self, *wrt, **flags): return True def as_coeff_mul(self, *deps, rational=True, **kwargs): # a -> c*t if self.is_Rational or not rational: return self, tuple() elif self.is_negative: return S.NegativeOne, (-self,) return S.One, (self,) def as_coeff_add(self, *deps): # a -> c + t if self.is_Rational: return self, tuple() return S.Zero, (self,) def as_coeff_Mul(self, rational=False): """Efficiently extract the coefficient of a product. """ if rational and not self.is_Rational: return S.One, self return (self, S.One) if self else (S.One, self) def as_coeff_Add(self, rational=False): """Efficiently extract the coefficient of a summation. """ if not rational: return self, S.Zero return S.Zero, self def gcd(self, other): """Compute GCD of `self` and `other`. """ from sympy.polys.polytools import gcd return gcd(self, other) def lcm(self, other): """Compute LCM of `self` and `other`. """ from sympy.polys.polytools import lcm return lcm(self, other) def cofactors(self, other): """Compute GCD and cofactors of `self` and `other`. """ from sympy.polys.polytools import cofactors return cofactors(self, other) class Float(Number): """Represent a floating-point number of arbitrary precision. Examples ======== >>> from sympy import Float >>> Float(3.5) 3.50000000000000 >>> Float(3) 3.00000000000000 Creating Floats from strings (and Python ``int`` and ``long`` types) will give a minimum precision of 15 digits, but the precision will automatically increase to capture all digits entered. >>> Float(1) 1.00000000000000 >>> Float(10**20) 100000000000000000000. >>> Float('1e20') 100000000000000000000. However, *floating-point* numbers (Python ``float`` types) retain only 15 digits of precision: >>> Float(1e20) 1.00000000000000e+20 >>> Float(1.23456789123456789) 1.23456789123457 It may be preferable to enter high-precision decimal numbers as strings: >>> Float('1.23456789123456789') 1.23456789123456789 The desired number of digits can also be specified: >>> Float('1e-3', 3) 0.00100 >>> Float(100, 4) 100.0 Float can automatically count significant figures if a null string is sent for the precision; spaces or underscores are also allowed. (Auto- counting is only allowed for strings, ints and longs). >>> Float('123 456 789.123_456', '') 123456789.123456 >>> Float('12e-3', '') 0.012 >>> Float(3, '') 3. If a number is written in scientific notation, only the digits before the exponent are considered significant if a decimal appears, otherwise the "e" signifies only how to move the decimal: >>> Float('60.e2', '') # 2 digits significant 6.0e+3 >>> Float('60e2', '') # 4 digits significant 6000. >>> Float('600e-2', '') # 3 digits significant 6.00 Notes ===== Floats are inexact by their nature unless their value is a binary-exact value. >>> approx, exact = Float(.1, 1), Float(.125, 1) For calculation purposes, evalf needs to be able to change the precision but this will not increase the accuracy of the inexact value. The following is the most accurate 5-digit approximation of a value of 0.1 that had only 1 digit of precision: >>> approx.evalf(5) 0.099609 By contrast, 0.125 is exact in binary (as it is in base 10) and so it can be passed to Float or evalf to obtain an arbitrary precision with matching accuracy: >>> Float(exact, 5) 0.12500 >>> exact.evalf(20) 0.12500000000000000000 Trying to make a high-precision Float from a float is not disallowed, but one must keep in mind that the *underlying float* (not the apparent decimal value) is being obtained with high precision. For example, 0.3 does not have a finite binary representation. The closest rational is the fraction 5404319552844595/2**54. So if you try to obtain a Float of 0.3 to 20 digits of precision you will not see the same thing as 0.3 followed by 19 zeros: >>> Float(0.3, 20) 0.29999999999999998890 If you want a 20-digit value of the decimal 0.3 (not the floating point approximation of 0.3) you should send the 0.3 as a string. The underlying representation is still binary but a higher precision than Python's float is used: >>> Float('0.3', 20) 0.30000000000000000000 Although you can increase the precision of an existing Float using Float it will not increase the accuracy -- the underlying value is not changed: >>> def show(f): # binary rep of Float ... from sympy import Mul, Pow ... s, m, e, b = f._mpf_ ... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False) ... print('%s at prec=%s' % (v, f._prec)) ... >>> t = Float('0.3', 3) >>> show(t) 4915/2**14 at prec=13 >>> show(Float(t, 20)) # higher prec, not higher accuracy 4915/2**14 at prec=70 >>> show(Float(t, 2)) # lower prec 307/2**10 at prec=10 The same thing happens when evalf is used on a Float: >>> show(t.evalf(20)) 4915/2**14 at prec=70 >>> show(t.evalf(2)) 307/2**10 at prec=10 Finally, Floats can be instantiated with an mpf tuple (n, c, p) to produce the number (-1)**n*c*2**p: >>> n, c, p = 1, 5, 0 >>> (-1)**n*c*2**p -5 >>> Float((1, 5, 0)) -5.00000000000000 An actual mpf tuple also contains the number of bits in c as the last element of the tuple: >>> _._mpf_ (1, 5, 0, 3) This is not needed for instantiation and is not the same thing as the precision. The mpf tuple and the precision are two separate quantities that Float tracks. In SymPy, a Float is a number that can be computed with arbitrary precision. Although floating point 'inf' and 'nan' are not such numbers, Float can create these numbers: >>> Float('-inf') -oo >>> _.is_Float False Zero in Float only has a single value. Values are not separate for positive and negative zeroes. """ __slots__ = ('_mpf_', '_prec') _mpf_: tuple[int, int, int, int] # A Float represents many real numbers, # both rational and irrational. is_rational = None is_irrational = None is_number = True is_real = True is_extended_real = True is_Float = True def __new__(cls, num, dps=None, precision=None): if dps is not None and precision is not None: raise ValueError('Both decimal and binary precision supplied. ' 'Supply only one. ') if isinstance(num, str): # Float accepts spaces as digit separators num = num.replace(' ', '').lower() if num.startswith('.') and len(num) > 1: num = '0' + num elif num.startswith('-.') and len(num) > 2: num = '-0.' + num[2:] elif num in ('inf', '+inf'): return S.Infinity elif num == '-inf': return S.NegativeInfinity elif isinstance(num, float) and num == 0: num = '0' elif isinstance(num, float) and num == float('inf'): return S.Infinity elif isinstance(num, float) and num == float('-inf'): return S.NegativeInfinity elif isinstance(num, float) and math.isnan(num): return S.NaN elif isinstance(num, (SYMPY_INTS, Integer)): num = str(num) elif num is S.Infinity: return num elif num is S.NegativeInfinity: return num elif num is S.NaN: return num elif _is_numpy_instance(num): # support for numpy datatypes num = _convert_numpy_types(num) elif isinstance(num, mpmath.mpf): if precision is None: if dps is None: precision = num.context.prec num = num._mpf_ if dps is None and precision is None: dps = 15 if isinstance(num, Float): return num if isinstance(num, str) and _literal_float(num): try: Num = decimal.Decimal(num) except decimal.InvalidOperation: pass else: isint = '.' not in num num, dps = _decimal_to_Rational_prec(Num) if num.is_Integer and isint: dps = max(dps, len(str(num).lstrip('-'))) dps = max(15, dps) precision = dps_to_prec(dps) elif precision == '' and dps is None or precision is None and dps == '': if not isinstance(num, str): raise ValueError('The null string can only be used when ' 'the number to Float is passed as a string or an integer.') ok = None if _literal_float(num): try: Num = decimal.Decimal(num) except decimal.InvalidOperation: pass else: isint = '.' not in num num, dps = _decimal_to_Rational_prec(Num) if num.is_Integer and isint: dps = max(dps, len(str(num).lstrip('-'))) precision = dps_to_prec(dps) ok = True if ok is None: raise ValueError('string-float not recognized: %s' % num) # decimal precision(dps) is set and maybe binary precision(precision) # as well.From here on binary precision is used to compute the Float. # Hence, if supplied use binary precision else translate from decimal # precision. if precision is None or precision == '': precision = dps_to_prec(dps) precision = int(precision) if isinstance(num, float): _mpf_ = mlib.from_float(num, precision, rnd) elif isinstance(num, str): _mpf_ = mlib.from_str(num, precision, rnd) elif isinstance(num, decimal.Decimal): if num.is_finite(): _mpf_ = mlib.from_str(str(num), precision, rnd) elif num.is_nan(): return S.NaN elif num.is_infinite(): if num > 0: return S.Infinity return S.NegativeInfinity else: raise ValueError("unexpected decimal value %s" % str(num)) elif isinstance(num, tuple) and len(num) in (3, 4): if isinstance(num[1], str): # it's a hexadecimal (coming from a pickled object) num = list(num) # If we're loading an object pickled in Python 2 into # Python 3, we may need to strip a tailing 'L' because # of a shim for int on Python 3, see issue #13470. if num[1].endswith('L'): num[1] = num[1][:-1] # Strip leading '0x' - gmpy2 only documents such inputs # with base prefix as valid when the 2nd argument (base) is 0. # When mpmath uses Sage as the backend, however, it # ends up including '0x' when preparing the picklable tuple. # See issue #19690. if num[1].startswith('0x'): num[1] = num[1][2:] # Now we can assume that it is in standard form num[1] = MPZ(num[1], 16) _mpf_ = tuple(num) else: if len(num) == 4: # handle normalization hack return Float._new(num, precision) else: if not all(( num[0] in (0, 1), num[1] >= 0, all(type(i) in (int, int) for i in num) )): raise ValueError('malformed mpf: %s' % (num,)) # don't compute number or else it may # over/underflow return Float._new( (num[0], num[1], num[2], bitcount(num[1])), precision) else: try: _mpf_ = num._as_mpf_val(precision) except (NotImplementedError, AttributeError): _mpf_ = mpmath.mpf(num, prec=precision)._mpf_ return cls._new(_mpf_, precision, zero=False) @classmethod def _new(cls, _mpf_, _prec, zero=True): # special cases if zero and _mpf_ == fzero: return S.Zero # Float(0) -> 0.0; Float._new((0,0,0,0)) -> 0 elif _mpf_ == _mpf_nan: return S.NaN elif _mpf_ == _mpf_inf: return S.Infinity elif _mpf_ == _mpf_ninf: return S.NegativeInfinity obj = Expr.__new__(cls) obj._mpf_ = mpf_norm(_mpf_, _prec) obj._prec = _prec return obj # mpz can't be pickled def __getnewargs_ex__(self): return ((mlib.to_pickable(self._mpf_),), {'precision': self._prec}) def _hashable_content(self): return (self._mpf_, self._prec) def floor(self): return Integer(int(mlib.to_int( mlib.mpf_floor(self._mpf_, self._prec)))) def ceiling(self): return Integer(int(mlib.to_int( mlib.mpf_ceil(self._mpf_, self._prec)))) def __floor__(self): return self.floor() def __ceil__(self): return self.ceiling() @property def num(self): return mpmath.mpf(self._mpf_) def _as_mpf_val(self, prec): rv = mpf_norm(self._mpf_, prec) if rv != self._mpf_ and self._prec == prec: debug(self._mpf_, rv) return rv def _as_mpf_op(self, prec): return self._mpf_, max(prec, self._prec) def _eval_is_finite(self): if self._mpf_ in (_mpf_inf, _mpf_ninf): return False return True def _eval_is_infinite(self): if self._mpf_ in (_mpf_inf, _mpf_ninf): return True return False def _eval_is_integer(self): return self._mpf_ == fzero def _eval_is_negative(self): if self._mpf_ in (_mpf_ninf, _mpf_inf): return False return self.num < 0 def _eval_is_positive(self): if self._mpf_ in (_mpf_ninf, _mpf_inf): return False return self.num > 0 def _eval_is_extended_negative(self): if self._mpf_ == _mpf_ninf: return True if self._mpf_ == _mpf_inf: return False return self.num < 0 def _eval_is_extended_positive(self): if self._mpf_ == _mpf_inf: return True if self._mpf_ == _mpf_ninf: return False return self.num > 0 def _eval_is_zero(self): return self._mpf_ == fzero def __bool__(self): return self._mpf_ != fzero def __neg__(self): if not self: return self return Float._new(mlib.mpf_neg(self._mpf_), self._prec) @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number) and global_parameters.evaluate: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_add(self._mpf_, rhs, prec, rnd), prec) return Number.__add__(self, other) @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number) and global_parameters.evaluate: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_sub(self._mpf_, rhs, prec, rnd), prec) return Number.__sub__(self, other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number) and global_parameters.evaluate: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_mul(self._mpf_, rhs, prec, rnd), prec) return Number.__mul__(self, other) @_sympifyit('other', NotImplemented) def __truediv__(self, other): if isinstance(other, Number) and other != 0 and global_parameters.evaluate: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_div(self._mpf_, rhs, prec, rnd), prec) return Number.__truediv__(self, other) @_sympifyit('other', NotImplemented) def __mod__(self, other): if isinstance(other, Rational) and other.q != 1 and global_parameters.evaluate: # calculate mod with Rationals, *then* round the result return Float(Rational.__mod__(Rational(self), other), precision=self._prec) if isinstance(other, Float) and global_parameters.evaluate: r = self/other if r == int(r): return Float(0, precision=max(self._prec, other._prec)) if isinstance(other, Number) and global_parameters.evaluate: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_mod(self._mpf_, rhs, prec, rnd), prec) return Number.__mod__(self, other) @_sympifyit('other', NotImplemented) def __rmod__(self, other): if isinstance(other, Float) and global_parameters.evaluate: return other.__mod__(self) if isinstance(other, Number) and global_parameters.evaluate: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_mod(rhs, self._mpf_, prec, rnd), prec) return Number.__rmod__(self, other) def _eval_power(self, expt): """ expt is symbolic object but not equal to 0, 1 (-p)**r -> exp(r*log(-p)) -> exp(r*(log(p) + I*Pi)) -> -> p**r*(sin(Pi*r) + cos(Pi*r)*I) """ if self == 0: if expt.is_extended_positive: return self if expt.is_extended_negative: return S.ComplexInfinity if isinstance(expt, Number): if isinstance(expt, Integer): prec = self._prec return Float._new( mlib.mpf_pow_int(self._mpf_, expt.p, prec, rnd), prec) elif isinstance(expt, Rational) and \ expt.p == 1 and expt.q % 2 and self.is_negative: return Pow(S.NegativeOne, expt, evaluate=False)*( -self)._eval_power(expt) expt, prec = expt._as_mpf_op(self._prec) mpfself = self._mpf_ try: y = mpf_pow(mpfself, expt, prec, rnd) return Float._new(y, prec) except mlib.ComplexResult: re, im = mlib.mpc_pow( (mpfself, fzero), (expt, fzero), prec, rnd) return Float._new(re, prec) + \ Float._new(im, prec)*S.ImaginaryUnit def __abs__(self): return Float._new(mlib.mpf_abs(self._mpf_), self._prec) def __int__(self): if self._mpf_ == fzero: return 0 return int(mlib.to_int(self._mpf_)) # uses round_fast = round_down def __eq__(self, other): from sympy.logic.boolalg import Boolean try: other = _sympify(other) except SympifyError: return NotImplemented if isinstance(other, Boolean): return False if other.is_NumberSymbol: if other.is_irrational: return False return other.__eq__(self) if other.is_Float: # comparison is exact # so Float(.1, 3) != Float(.1, 33) return self._mpf_ == other._mpf_ if other.is_Rational: return other.__eq__(self) if other.is_Number: # numbers should compare at the same precision; # all _as_mpf_val routines should be sure to abide # by the request to change the prec if necessary; if # they don't, the equality test will fail since it compares # the mpf tuples ompf = other._as_mpf_val(self._prec) return bool(mlib.mpf_eq(self._mpf_, ompf)) if not self: return not other return False # Float != non-Number def __ne__(self, other): return not self == other def _Frel(self, other, op): try: other = _sympify(other) except SympifyError: return NotImplemented if other.is_Rational: # test self*other.q <?> other.p without losing precision ''' >>> f = Float(.1,2) >>> i = 1234567890 >>> (f*i)._mpf_ (0, 471, 18, 9) >>> mlib.mpf_mul(f._mpf_, mlib.from_int(i)) (0, 505555550955, -12, 39) ''' smpf = mlib.mpf_mul(self._mpf_, mlib.from_int(other.q)) ompf = mlib.from_int(other.p) return _sympify(bool(op(smpf, ompf))) elif other.is_Float: return _sympify(bool( op(self._mpf_, other._mpf_))) elif other.is_comparable and other not in ( S.Infinity, S.NegativeInfinity): other = other.evalf(prec_to_dps(self._prec)) if other._prec > 1: if other.is_Number: return _sympify(bool( op(self._mpf_, other._as_mpf_val(self._prec)))) def __gt__(self, other): if isinstance(other, NumberSymbol): return other.__lt__(self) rv = self._Frel(other, mlib.mpf_gt) if rv is None: return Expr.__gt__(self, other) return rv def __ge__(self, other): if isinstance(other, NumberSymbol): return other.__le__(self) rv = self._Frel(other, mlib.mpf_ge) if rv is None: return Expr.__ge__(self, other) return rv def __lt__(self, other): if isinstance(other, NumberSymbol): return other.__gt__(self) rv = self._Frel(other, mlib.mpf_lt) if rv is None: return Expr.__lt__(self, other) return rv def __le__(self, other): if isinstance(other, NumberSymbol): return other.__ge__(self) rv = self._Frel(other, mlib.mpf_le) if rv is None: return Expr.__le__(self, other) return rv def __hash__(self): return super().__hash__() def epsilon_eq(self, other, epsilon="1e-15"): return abs(self - other) < Float(epsilon) def __format__(self, format_spec): return format(decimal.Decimal(str(self)), format_spec) # Add sympify converters _sympy_converter[float] = _sympy_converter[decimal.Decimal] = Float # this is here to work nicely in Sage RealNumber = Float class Rational(Number): """Represents rational numbers (p/q) of any size. Examples ======== >>> from sympy import Rational, nsimplify, S, pi >>> Rational(1, 2) 1/2 Rational is unprejudiced in accepting input. If a float is passed, the underlying value of the binary representation will be returned: >>> Rational(.5) 1/2 >>> Rational(.2) 3602879701896397/18014398509481984 If the simpler representation of the float is desired then consider limiting the denominator to the desired value or convert the float to a string (which is roughly equivalent to limiting the denominator to 10**12): >>> Rational(str(.2)) 1/5 >>> Rational(.2).limit_denominator(10**12) 1/5 An arbitrarily precise Rational is obtained when a string literal is passed: >>> Rational("1.23") 123/100 >>> Rational('1e-2') 1/100 >>> Rational(".1") 1/10 >>> Rational('1e-2/3.2') 1/320 The conversion of other types of strings can be handled by the sympify() function, and conversion of floats to expressions or simple fractions can be handled with nsimplify: >>> S('.[3]') # repeating digits in brackets 1/3 >>> S('3**2/10') # general expressions 9/10 >>> nsimplify(.3) # numbers that have a simple form 3/10 But if the input does not reduce to a literal Rational, an error will be raised: >>> Rational(pi) Traceback (most recent call last): ... TypeError: invalid input: pi Low-level --------- Access numerator and denominator as .p and .q: >>> r = Rational(3, 4) >>> r 3/4 >>> r.p 3 >>> r.q 4 Note that p and q return integers (not SymPy Integers) so some care is needed when using them in expressions: >>> r.p/r.q 0.75 If an unevaluated Rational is desired, ``gcd=1`` can be passed and this will keep common divisors of the numerator and denominator from being eliminated. It is not possible, however, to leave a negative value in the denominator. >>> Rational(2, 4, gcd=1) 2/4 >>> Rational(2, -4, gcd=1).q 4 See Also ======== sympy.core.sympify.sympify, sympy.simplify.simplify.nsimplify """ is_real = True is_integer = False is_rational = True is_number = True __slots__ = ('p', 'q') p: int q: int is_Rational = True @cacheit def __new__(cls, p, q=None, gcd=None): if q is None: if isinstance(p, Rational): return p if isinstance(p, SYMPY_INTS): pass else: if isinstance(p, (float, Float)): return Rational(*_as_integer_ratio(p)) if not isinstance(p, str): try: p = sympify(p) except (SympifyError, SyntaxError): pass # error will raise below else: if p.count('/') > 1: raise TypeError('invalid input: %s' % p) p = p.replace(' ', '') pq = p.rsplit('/', 1) if len(pq) == 2: p, q = pq fp = fractions.Fraction(p) fq = fractions.Fraction(q) p = fp/fq try: p = fractions.Fraction(p) except ValueError: pass # error will raise below else: return Rational(p.numerator, p.denominator, 1) if not isinstance(p, Rational): raise TypeError('invalid input: %s' % p) q = 1 gcd = 1 if not isinstance(p, SYMPY_INTS): p = Rational(p) q *= p.q p = p.p else: p = int(p) if not isinstance(q, SYMPY_INTS): q = Rational(q) p *= q.q q = q.p else: q = int(q) # p and q are now ints if q == 0: if p == 0: if _errdict["divide"]: raise ValueError("Indeterminate 0/0") else: return S.NaN return S.ComplexInfinity if q < 0: q = -q p = -p if not gcd: gcd = igcd(abs(p), q) if gcd > 1: p //= gcd q //= gcd if q == 1: return Integer(p) if p == 1 and q == 2: return S.Half obj = Expr.__new__(cls) obj.p = p obj.q = q return obj def limit_denominator(self, max_denominator=1000000): """Closest Rational to self with denominator at most max_denominator. Examples ======== >>> from sympy import Rational >>> Rational('3.141592653589793').limit_denominator(10) 22/7 >>> Rational('3.141592653589793').limit_denominator(100) 311/99 """ f = fractions.Fraction(self.p, self.q) return Rational(f.limit_denominator(fractions.Fraction(int(max_denominator)))) def __getnewargs__(self): return (self.p, self.q) def _hashable_content(self): return (self.p, self.q) def _eval_is_positive(self): return self.p > 0 def _eval_is_zero(self): return self.p == 0 def __neg__(self): return Rational(-self.p, self.q) @_sympifyit('other', NotImplemented) def __add__(self, other): if global_parameters.evaluate: if isinstance(other, Integer): return Rational(self.p + self.q*other.p, self.q, 1) elif isinstance(other, Rational): #TODO: this can probably be optimized more return Rational(self.p*other.q + self.q*other.p, self.q*other.q) elif isinstance(other, Float): return other + self else: return Number.__add__(self, other) return Number.__add__(self, other) __radd__ = __add__ @_sympifyit('other', NotImplemented) def __sub__(self, other): if global_parameters.evaluate: if isinstance(other, Integer): return Rational(self.p - self.q*other.p, self.q, 1) elif isinstance(other, Rational): return Rational(self.p*other.q - self.q*other.p, self.q*other.q) elif isinstance(other, Float): return -other + self else: return Number.__sub__(self, other) return Number.__sub__(self, other) @_sympifyit('other', NotImplemented) def __rsub__(self, other): if global_parameters.evaluate: if isinstance(other, Integer): return Rational(self.q*other.p - self.p, self.q, 1) elif isinstance(other, Rational): return Rational(self.q*other.p - self.p*other.q, self.q*other.q) elif isinstance(other, Float): return -self + other else: return Number.__rsub__(self, other) return Number.__rsub__(self, other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if global_parameters.evaluate: if isinstance(other, Integer): return Rational(self.p*other.p, self.q, igcd(other.p, self.q)) elif isinstance(other, Rational): return Rational(self.p*other.p, self.q*other.q, igcd(self.p, other.q)*igcd(self.q, other.p)) elif isinstance(other, Float): return other*self else: return Number.__mul__(self, other) return Number.__mul__(self, other) __rmul__ = __mul__ @_sympifyit('other', NotImplemented) def __truediv__(self, other): if global_parameters.evaluate: if isinstance(other, Integer): if self.p and other.p == S.Zero: return S.ComplexInfinity else: return Rational(self.p, self.q*other.p, igcd(self.p, other.p)) elif isinstance(other, Rational): return Rational(self.p*other.q, self.q*other.p, igcd(self.p, other.p)*igcd(self.q, other.q)) elif isinstance(other, Float): return self*(1/other) else: return Number.__truediv__(self, other) return Number.__truediv__(self, other) @_sympifyit('other', NotImplemented) def __rtruediv__(self, other): if global_parameters.evaluate: if isinstance(other, Integer): return Rational(other.p*self.q, self.p, igcd(self.p, other.p)) elif isinstance(other, Rational): return Rational(other.p*self.q, other.q*self.p, igcd(self.p, other.p)*igcd(self.q, other.q)) elif isinstance(other, Float): return other*(1/self) else: return Number.__rtruediv__(self, other) return Number.__rtruediv__(self, other) @_sympifyit('other', NotImplemented) def __mod__(self, other): if global_parameters.evaluate: if isinstance(other, Rational): n = (self.p*other.q) // (other.p*self.q) return Rational(self.p*other.q - n*other.p*self.q, self.q*other.q) if isinstance(other, Float): # calculate mod with Rationals, *then* round the answer return Float(self.__mod__(Rational(other)), precision=other._prec) return Number.__mod__(self, other) return Number.__mod__(self, other) @_sympifyit('other', NotImplemented) def __rmod__(self, other): if isinstance(other, Rational): return Rational.__mod__(other, self) return Number.__rmod__(self, other) def _eval_power(self, expt): if isinstance(expt, Number): if isinstance(expt, Float): return self._eval_evalf(expt._prec)**expt if expt.is_extended_negative: # (3/4)**-2 -> (4/3)**2 ne = -expt if (ne is S.One): return Rational(self.q, self.p) if self.is_negative: return S.NegativeOne**expt*Rational(self.q, -self.p)**ne else: return Rational(self.q, self.p)**ne if expt is S.Infinity: # -oo already caught by test for negative if self.p > self.q: # (3/2)**oo -> oo return S.Infinity if self.p < -self.q: # (-3/2)**oo -> oo + I*oo return S.Infinity + S.Infinity*S.ImaginaryUnit return S.Zero if isinstance(expt, Integer): # (4/3)**2 -> 4**2 / 3**2 return Rational(self.p**expt.p, self.q**expt.p, 1) if isinstance(expt, Rational): intpart = expt.p // expt.q if intpart: intpart += 1 remfracpart = intpart*expt.q - expt.p ratfracpart = Rational(remfracpart, expt.q) if self.p != 1: return Integer(self.p)**expt*Integer(self.q)**ratfracpart*Rational(1, self.q**intpart, 1) return Integer(self.q)**ratfracpart*Rational(1, self.q**intpart, 1) else: remfracpart = expt.q - expt.p ratfracpart = Rational(remfracpart, expt.q) if self.p != 1: return Integer(self.p)**expt*Integer(self.q)**ratfracpart*Rational(1, self.q, 1) return Integer(self.q)**ratfracpart*Rational(1, self.q, 1) if self.is_extended_negative and expt.is_even: return (-self)**expt return def _as_mpf_val(self, prec): return mlib.from_rational(self.p, self.q, prec, rnd) def _mpmath_(self, prec, rnd): return mpmath.make_mpf(mlib.from_rational(self.p, self.q, prec, rnd)) def __abs__(self): return Rational(abs(self.p), self.q) def __int__(self): p, q = self.p, self.q if p < 0: return -int(-p//q) return int(p//q) def floor(self): return Integer(self.p // self.q) def ceiling(self): return -Integer(-self.p // self.q) def __floor__(self): return self.floor() def __ceil__(self): return self.ceiling() def __eq__(self, other): try: other = _sympify(other) except SympifyError: return NotImplemented if not isinstance(other, Number): # S(0) == S.false is False # S(0) == False is True return False if not self: return not other if other.is_NumberSymbol: if other.is_irrational: return False return other.__eq__(self) if other.is_Rational: # a Rational is always in reduced form so will never be 2/4 # so we can just check equivalence of args return self.p == other.p and self.q == other.q if other.is_Float: # all Floats have a denominator that is a power of 2 # so if self doesn't, it can't be equal to other if self.q & (self.q - 1): return False s, m, t = other._mpf_[:3] if s: m = -m if not t: # other is an odd integer if not self.is_Integer or self.is_even: return False return m == self.p from .power import integer_log if t > 0: # other is an even integer if not self.is_Integer: return False # does m*2**t == self.p return self.p and not self.p % m and \ integer_log(self.p//m, 2) == (t, True) # does non-integer s*m/2**-t = p/q? if self.is_Integer: return False return m == self.p and integer_log(self.q, 2) == (-t, True) return False def __ne__(self, other): return not self == other def _Rrel(self, other, attr): # if you want self < other, pass self, other, __gt__ try: other = _sympify(other) except SympifyError: return NotImplemented if other.is_Number: op = None s, o = self, other if other.is_NumberSymbol: op = getattr(o, attr) elif other.is_Float: op = getattr(o, attr) elif other.is_Rational: s, o = Integer(s.p*o.q), Integer(s.q*o.p) op = getattr(o, attr) if op: return op(s) if o.is_number and o.is_extended_real: return Integer(s.p), s.q*o def __gt__(self, other): rv = self._Rrel(other, '__lt__') if rv is None: rv = self, other elif not isinstance(rv, tuple): return rv return Expr.__gt__(*rv) def __ge__(self, other): rv = self._Rrel(other, '__le__') if rv is None: rv = self, other elif not isinstance(rv, tuple): return rv return Expr.__ge__(*rv) def __lt__(self, other): rv = self._Rrel(other, '__gt__') if rv is None: rv = self, other elif not isinstance(rv, tuple): return rv return Expr.__lt__(*rv) def __le__(self, other): rv = self._Rrel(other, '__ge__') if rv is None: rv = self, other elif not isinstance(rv, tuple): return rv return Expr.__le__(*rv) def __hash__(self): return super().__hash__() def factors(self, limit=None, use_trial=True, use_rho=False, use_pm1=False, verbose=False, visual=False): """A wrapper to factorint which return factors of self that are smaller than limit (or cheap to compute). Special methods of factoring are disabled by default so that only trial division is used. """ from sympy.ntheory.factor_ import factorrat return factorrat(self, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose).copy() @property def numerator(self): return self.p @property def denominator(self): return self.q @_sympifyit('other', NotImplemented) def gcd(self, other): if isinstance(other, Rational): if other == S.Zero: return other return Rational( igcd(self.p, other.p), ilcm(self.q, other.q)) return Number.gcd(self, other) @_sympifyit('other', NotImplemented) def lcm(self, other): if isinstance(other, Rational): return Rational( self.p // igcd(self.p, other.p) * other.p, igcd(self.q, other.q)) return Number.lcm(self, other) def as_numer_denom(self): return Integer(self.p), Integer(self.q) def as_content_primitive(self, radical=False, clear=True): """Return the tuple (R, self/R) where R is the positive Rational extracted from self. Examples ======== >>> from sympy import S >>> (S(-3)/2).as_content_primitive() (3/2, -1) See docstring of Expr.as_content_primitive for more examples. """ if self: if self.is_positive: return self, S.One return -self, S.NegativeOne return S.One, self def as_coeff_Mul(self, rational=False): """Efficiently extract the coefficient of a product. """ return self, S.One def as_coeff_Add(self, rational=False): """Efficiently extract the coefficient of a summation. """ return self, S.Zero class Integer(Rational): """Represents integer numbers of any size. Examples ======== >>> from sympy import Integer >>> Integer(3) 3 If a float or a rational is passed to Integer, the fractional part will be discarded; the effect is of rounding toward zero. >>> Integer(3.8) 3 >>> Integer(-3.8) -3 A string is acceptable input if it can be parsed as an integer: >>> Integer("9" * 20) 99999999999999999999 It is rarely needed to explicitly instantiate an Integer, because Python integers are automatically converted to Integer when they are used in SymPy expressions. """ q = 1 is_integer = True is_number = True is_Integer = True __slots__ = () def _as_mpf_val(self, prec): return mlib.from_int(self.p, prec, rnd) def _mpmath_(self, prec, rnd): return mpmath.make_mpf(self._as_mpf_val(prec)) @cacheit def __new__(cls, i): if isinstance(i, str): i = i.replace(' ', '') # whereas we cannot, in general, make a Rational from an # arbitrary expression, we can make an Integer unambiguously # (except when a non-integer expression happens to round to # an integer). So we proceed by taking int() of the input and # let the int routines determine whether the expression can # be made into an int or whether an error should be raised. try: ival = int(i) except TypeError: raise TypeError( "Argument of Integer should be of numeric type, got %s." % i) # We only work with well-behaved integer types. This converts, for # example, numpy.int32 instances. if ival == 1: return S.One if ival == -1: return S.NegativeOne if ival == 0: return S.Zero obj = Expr.__new__(cls) obj.p = ival return obj def __getnewargs__(self): return (self.p,) # Arithmetic operations are here for efficiency def __int__(self): return self.p def floor(self): return Integer(self.p) def ceiling(self): return Integer(self.p) def __floor__(self): return self.floor() def __ceil__(self): return self.ceiling() def __neg__(self): return Integer(-self.p) def __abs__(self): if self.p >= 0: return self else: return Integer(-self.p) def __divmod__(self, other): if isinstance(other, Integer) and global_parameters.evaluate: return Tuple(*(divmod(self.p, other.p))) else: return Number.__divmod__(self, other) def __rdivmod__(self, other): if isinstance(other, int) and global_parameters.evaluate: return Tuple(*(divmod(other, self.p))) else: try: other = Number(other) except TypeError: msg = "unsupported operand type(s) for divmod(): '%s' and '%s'" oname = type(other).__name__ sname = type(self).__name__ raise TypeError(msg % (oname, sname)) return Number.__divmod__(other, self) # TODO make it decorator + bytecodehacks? def __add__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(self.p + other) elif isinstance(other, Integer): return Integer(self.p + other.p) elif isinstance(other, Rational): return Rational(self.p*other.q + other.p, other.q, 1) return Rational.__add__(self, other) else: return Add(self, other) def __radd__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(other + self.p) elif isinstance(other, Rational): return Rational(other.p + self.p*other.q, other.q, 1) return Rational.__radd__(self, other) return Rational.__radd__(self, other) def __sub__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(self.p - other) elif isinstance(other, Integer): return Integer(self.p - other.p) elif isinstance(other, Rational): return Rational(self.p*other.q - other.p, other.q, 1) return Rational.__sub__(self, other) return Rational.__sub__(self, other) def __rsub__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(other - self.p) elif isinstance(other, Rational): return Rational(other.p - self.p*other.q, other.q, 1) return Rational.__rsub__(self, other) return Rational.__rsub__(self, other) def __mul__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(self.p*other) elif isinstance(other, Integer): return Integer(self.p*other.p) elif isinstance(other, Rational): return Rational(self.p*other.p, other.q, igcd(self.p, other.q)) return Rational.__mul__(self, other) return Rational.__mul__(self, other) def __rmul__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(other*self.p) elif isinstance(other, Rational): return Rational(other.p*self.p, other.q, igcd(self.p, other.q)) return Rational.__rmul__(self, other) return Rational.__rmul__(self, other) def __mod__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(self.p % other) elif isinstance(other, Integer): return Integer(self.p % other.p) return Rational.__mod__(self, other) return Rational.__mod__(self, other) def __rmod__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(other % self.p) elif isinstance(other, Integer): return Integer(other.p % self.p) return Rational.__rmod__(self, other) return Rational.__rmod__(self, other) def __eq__(self, other): if isinstance(other, int): return (self.p == other) elif isinstance(other, Integer): return (self.p == other.p) return Rational.__eq__(self, other) def __ne__(self, other): return not self == other def __gt__(self, other): try: other = _sympify(other) except SympifyError: return NotImplemented if other.is_Integer: return _sympify(self.p > other.p) return Rational.__gt__(self, other) def __lt__(self, other): try: other = _sympify(other) except SympifyError: return NotImplemented if other.is_Integer: return _sympify(self.p < other.p) return Rational.__lt__(self, other) def __ge__(self, other): try: other = _sympify(other) except SympifyError: return NotImplemented if other.is_Integer: return _sympify(self.p >= other.p) return Rational.__ge__(self, other) def __le__(self, other): try: other = _sympify(other) except SympifyError: return NotImplemented if other.is_Integer: return _sympify(self.p <= other.p) return Rational.__le__(self, other) def __hash__(self): return hash(self.p) def __index__(self): return self.p ######################################## def _eval_is_odd(self): return bool(self.p % 2) def _eval_power(self, expt): """ Tries to do some simplifications on self**expt Returns None if no further simplifications can be done. Explanation =========== When exponent is a fraction (so we have for example a square root), we try to find a simpler representation by factoring the argument up to factors of 2**15, e.g. - sqrt(4) becomes 2 - sqrt(-4) becomes 2*I - (2**(3+7)*3**(6+7))**Rational(1,7) becomes 6*18**(3/7) Further simplification would require a special call to factorint on the argument which is not done here for sake of speed. """ from sympy.ntheory.factor_ import perfect_power if expt is S.Infinity: if self.p > S.One: return S.Infinity # cases -1, 0, 1 are done in their respective classes return S.Infinity + S.ImaginaryUnit*S.Infinity if expt is S.NegativeInfinity: return Rational(1, self, 1)**S.Infinity if not isinstance(expt, Number): # simplify when expt is even # (-2)**k --> 2**k if self.is_negative and expt.is_even: return (-self)**expt if isinstance(expt, Float): # Rational knows how to exponentiate by a Float return super()._eval_power(expt) if not isinstance(expt, Rational): return if expt is S.Half and self.is_negative: # we extract I for this special case since everyone is doing so return S.ImaginaryUnit*Pow(-self, expt) if expt.is_negative: # invert base and change sign on exponent ne = -expt if self.is_negative: return S.NegativeOne**expt*Rational(1, -self, 1)**ne else: return Rational(1, self.p, 1)**ne # see if base is a perfect root, sqrt(4) --> 2 x, xexact = integer_nthroot(abs(self.p), expt.q) if xexact: # if it's a perfect root we've finished result = Integer(x**abs(expt.p)) if self.is_negative: result *= S.NegativeOne**expt return result # The following is an algorithm where we collect perfect roots # from the factors of base. # if it's not an nth root, it still might be a perfect power b_pos = int(abs(self.p)) p = perfect_power(b_pos) if p is not False: dict = {p[0]: p[1]} else: dict = Integer(b_pos).factors(limit=2**15) # now process the dict of factors out_int = 1 # integer part out_rad = 1 # extracted radicals sqr_int = 1 sqr_gcd = 0 sqr_dict = {} for prime, exponent in dict.items(): exponent *= expt.p # remove multiples of expt.q: (2**12)**(1/10) -> 2*(2**2)**(1/10) div_e, div_m = divmod(exponent, expt.q) if div_e > 0: out_int *= prime**div_e if div_m > 0: # see if the reduced exponent shares a gcd with e.q # (2**2)**(1/10) -> 2**(1/5) g = igcd(div_m, expt.q) if g != 1: out_rad *= Pow(prime, Rational(div_m//g, expt.q//g, 1)) else: sqr_dict[prime] = div_m # identify gcd of remaining powers for p, ex in sqr_dict.items(): if sqr_gcd == 0: sqr_gcd = ex else: sqr_gcd = igcd(sqr_gcd, ex) if sqr_gcd == 1: break for k, v in sqr_dict.items(): sqr_int *= k**(v//sqr_gcd) if sqr_int == b_pos and out_int == 1 and out_rad == 1: result = None else: result = out_int*out_rad*Pow(sqr_int, Rational(sqr_gcd, expt.q)) if self.is_negative: result *= Pow(S.NegativeOne, expt) return result def _eval_is_prime(self): from sympy.ntheory.primetest import isprime return isprime(self) def _eval_is_composite(self): if self > 1: return fuzzy_not(self.is_prime) else: return False def as_numer_denom(self): return self, S.One @_sympifyit('other', NotImplemented) def __floordiv__(self, other): if not isinstance(other, Expr): return NotImplemented if isinstance(other, Integer): return Integer(self.p // other) return Integer(divmod(self, other)[0]) def __rfloordiv__(self, other): return Integer(Integer(other).p // self.p) # These bitwise operations (__lshift__, __rlshift__, ..., __invert__) are defined # for Integer only and not for general SymPy expressions. This is to achieve # compatibility with the numbers.Integral ABC which only defines these operations # among instances of numbers.Integral. Therefore, these methods check explicitly for # integer types rather than using sympify because they should not accept arbitrary # symbolic expressions and there is no symbolic analogue of numbers.Integral's # bitwise operations. def __lshift__(self, other): if isinstance(other, (int, Integer, numbers.Integral)): return Integer(self.p << int(other)) else: return NotImplemented def __rlshift__(self, other): if isinstance(other, (int, numbers.Integral)): return Integer(int(other) << self.p) else: return NotImplemented def __rshift__(self, other): if isinstance(other, (int, Integer, numbers.Integral)): return Integer(self.p >> int(other)) else: return NotImplemented def __rrshift__(self, other): if isinstance(other, (int, numbers.Integral)): return Integer(int(other) >> self.p) else: return NotImplemented def __and__(self, other): if isinstance(other, (int, Integer, numbers.Integral)): return Integer(self.p & int(other)) else: return NotImplemented def __rand__(self, other): if isinstance(other, (int, numbers.Integral)): return Integer(int(other) & self.p) else: return NotImplemented def __xor__(self, other): if isinstance(other, (int, Integer, numbers.Integral)): return Integer(self.p ^ int(other)) else: return NotImplemented def __rxor__(self, other): if isinstance(other, (int, numbers.Integral)): return Integer(int(other) ^ self.p) else: return NotImplemented def __or__(self, other): if isinstance(other, (int, Integer, numbers.Integral)): return Integer(self.p | int(other)) else: return NotImplemented def __ror__(self, other): if isinstance(other, (int, numbers.Integral)): return Integer(int(other) | self.p) else: return NotImplemented def __invert__(self): return Integer(~self.p) # Add sympify converters _sympy_converter[int] = Integer class AlgebraicNumber(Expr): r""" Class for representing algebraic numbers in SymPy. Symbolically, an instance of this class represents an element $\alpha \in \mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$. That is, the algebraic number $\alpha$ is represented as an element of a particular number field $\mathbb{Q}(\theta)$, with a particular embedding of this field into the complex numbers. Formally, the primitive element $\theta$ is given by two data points: (1) its minimal polynomial (which defines $\mathbb{Q}(\theta)$), and (2) a particular complex number that is a root of this polynomial (which defines the embedding $\mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$). Finally, the algebraic number $\alpha$ which we represent is then given by the coefficients of a polynomial in $\theta$. """ __slots__ = ('rep', 'root', 'alias', 'minpoly', '_own_minpoly') is_AlgebraicNumber = True is_algebraic = True is_number = True kind = NumberKind # Optional alias symbol is not free. # Actually, alias should be a Str, but some methods # expect that it be an instance of Expr. free_symbols: set[Basic] = set() def __new__(cls, expr, coeffs=None, alias=None, **args): r""" Construct a new algebraic number $\alpha$ belonging to a number field $k = \mathbb{Q}(\theta)$. There are four instance attributes to be determined: =========== ============================================================================ Attribute Type/Meaning =========== ============================================================================ ``root`` :py:class:`~.Expr` for $\theta$ as a complex number ``minpoly`` :py:class:`~.Poly`, the minimal polynomial of $\theta$ ``rep`` :py:class:`~sympy.polys.polyclasses.DMP` giving $\alpha$ as poly in $\theta$ ``alias`` :py:class:`~.Symbol` for $\theta$, or ``None`` =========== ============================================================================ See Parameters section for how they are determined. Parameters ========== expr : :py:class:`~.Expr`, or pair $(m, r)$ There are three distinct modes of construction, depending on what is passed as *expr*. **(1)** *expr* is an :py:class:`~.AlgebraicNumber`: In this case we begin by copying all four instance attributes from *expr*. If *coeffs* were also given, we compose the two coeff polynomials (see below). If an *alias* was given, it overrides. **(2)** *expr* is any other type of :py:class:`~.Expr`: Then ``root`` will equal *expr*. Therefore it must express an algebraic quantity, and we will compute its ``minpoly``. **(3)** *expr* is an ordered pair $(m, r)$ giving the ``minpoly`` $m$, and a ``root`` $r$ thereof, which together define $\theta$. In this case $m$ may be either a univariate :py:class:`~.Poly` or any :py:class:`~.Expr` which represents the same, while $r$ must be some :py:class:`~.Expr` representing a complex number that is a root of $m$, including both explicit expressions in radicals, and instances of :py:class:`~.ComplexRootOf` or :py:class:`~.AlgebraicNumber`. coeffs : list, :py:class:`~.ANP`, None, optional (default=None) This defines ``rep``, giving the algebraic number $\alpha$ as a polynomial in $\theta$. If a list, the elements should be integers or rational numbers. If an :py:class:`~.ANP`, we take its coefficients (using its :py:meth:`~.ANP.to_list()` method). If ``None``, then the list of coefficients defaults to ``[1, 0]``, meaning that $\alpha = \theta$ is the primitive element of the field. If *expr* was an :py:class:`~.AlgebraicNumber`, let $g(x)$ be its ``rep`` polynomial, and let $f(x)$ be the polynomial defined by *coeffs*. Then ``self.rep`` will represent the composition $(f \circ g)(x)$. alias : str, :py:class:`~.Symbol`, None, optional (default=None) This is a way to provide a name for the primitive element. We described several ways in which the *expr* argument can define the value of the primitive element, but none of these methods gave it a name. Here, for example, *alias* could be set as ``Symbol('theta')``, in order to make this symbol appear when $\alpha$ is printed, or rendered as a polynomial, using the :py:meth:`~.as_poly()` method. Examples ======== Recall that we are constructing an algebraic number as a field element $\alpha \in \mathbb{Q}(\theta)$. >>> from sympy import AlgebraicNumber, sqrt, CRootOf, S >>> from sympy.abc import x Example (1): $\alpha = \theta = \sqrt{2}$ >>> a1 = AlgebraicNumber(sqrt(2)) >>> a1.minpoly_of_element().as_expr(x) x**2 - 2 >>> a1.evalf(10) 1.414213562 Example (2): $\alpha = 3 \sqrt{2} - 5$, $\theta = \sqrt{2}$. We can either build on the last example: >>> a2 = AlgebraicNumber(a1, [3, -5]) >>> a2.as_expr() -5 + 3*sqrt(2) or start from scratch: >>> a2 = AlgebraicNumber(sqrt(2), [3, -5]) >>> a2.as_expr() -5 + 3*sqrt(2) Example (3): $\alpha = 6 \sqrt{2} - 11$, $\theta = \sqrt{2}$. Again we can build on the previous example, and we see that the coeff polys are composed: >>> a3 = AlgebraicNumber(a2, [2, -1]) >>> a3.as_expr() -11 + 6*sqrt(2) reflecting the fact that $(2x - 1) \circ (3x - 5) = 6x - 11$. Example (4): $\alpha = \sqrt{2}$, $\theta = \sqrt{2} + \sqrt{3}$. The easiest way is to use the :py:func:`~.to_number_field()` function: >>> from sympy import to_number_field >>> a4 = to_number_field(sqrt(2), sqrt(2) + sqrt(3)) >>> a4.minpoly_of_element().as_expr(x) x**2 - 2 >>> a4.to_root() sqrt(2) >>> a4.primitive_element() sqrt(2) + sqrt(3) >>> a4.coeffs() [1/2, 0, -9/2, 0] but if you already knew the right coefficients, you could construct it directly: >>> a4 = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1)/2, 0, S(-9)/2, 0]) >>> a4.to_root() sqrt(2) >>> a4.primitive_element() sqrt(2) + sqrt(3) Example (5): Construct the Golden Ratio as an element of the 5th cyclotomic field, supposing we already know its coefficients. This time we introduce the alias $\zeta$ for the primitive element of the field: >>> from sympy import cyclotomic_poly >>> from sympy.abc import zeta >>> a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1), ... [-1, -1, 0, 0], alias=zeta) >>> a5.as_poly().as_expr() -zeta**3 - zeta**2 >>> a5.evalf() 1.61803398874989 (The index ``-1`` to ``CRootOf`` selects the complex root with the largest real and imaginary parts, which in this case is $\mathrm{e}^{2i\pi/5}$. See :py:class:`~.ComplexRootOf`.) Example (6): Building on the last example, construct the number $2 \phi \in \mathbb{Q}(\phi)$, where $\phi$ is the Golden Ratio: >>> from sympy.abc import phi >>> a6 = AlgebraicNumber(a5.to_root(), coeffs=[2, 0], alias=phi) >>> a6.as_poly().as_expr() 2*phi >>> a6.primitive_element().evalf() 1.61803398874989 Note that we needed to use ``a5.to_root()``, since passing ``a5`` as the first argument would have constructed the number $2 \phi$ as an element of the field $\mathbb{Q}(\zeta)$: >>> a6_wrong = AlgebraicNumber(a5, coeffs=[2, 0]) >>> a6_wrong.as_poly().as_expr() -2*zeta**3 - 2*zeta**2 >>> a6_wrong.primitive_element().evalf() 0.309016994374947 + 0.951056516295154*I """ from sympy.polys.polyclasses import ANP, DMP from sympy.polys.numberfields import minimal_polynomial expr = sympify(expr) rep0 = None alias0 = None if isinstance(expr, (tuple, Tuple)): minpoly, root = expr if not minpoly.is_Poly: from sympy.polys.polytools import Poly minpoly = Poly(minpoly) elif expr.is_AlgebraicNumber: minpoly, root, rep0, alias0 = (expr.minpoly, expr.root, expr.rep, expr.alias) else: minpoly, root = minimal_polynomial( expr, args.get('gen'), polys=True), expr dom = minpoly.get_domain() if coeffs is not None: if not isinstance(coeffs, ANP): rep = DMP.from_sympy_list(sympify(coeffs), 0, dom) scoeffs = Tuple(*coeffs) else: rep = DMP.from_list(coeffs.to_list(), 0, dom) scoeffs = Tuple(*coeffs.to_list()) else: rep = DMP.from_list([1, 0], 0, dom) scoeffs = Tuple(1, 0) if rep0 is not None: from sympy.polys.densetools import dup_compose c = dup_compose(rep.rep, rep0.rep, dom) rep = DMP.from_list(c, 0, dom) scoeffs = Tuple(*c) if rep.degree() >= minpoly.degree(): rep = rep.rem(minpoly.rep) sargs = (root, scoeffs) alias = alias or alias0 if alias is not None: from .symbol import Symbol if not isinstance(alias, Symbol): alias = Symbol(alias) sargs = sargs + (alias,) obj = Expr.__new__(cls, *sargs) obj.rep = rep obj.root = root obj.alias = alias obj.minpoly = minpoly obj._own_minpoly = None return obj def __hash__(self): return super().__hash__() def _eval_evalf(self, prec): return self.as_expr()._evalf(prec) @property def is_aliased(self): """Returns ``True`` if ``alias`` was set. """ return self.alias is not None def as_poly(self, x=None): """Create a Poly instance from ``self``. """ from sympy.polys.polytools import Poly, PurePoly if x is not None: return Poly.new(self.rep, x) else: if self.alias is not None: return Poly.new(self.rep, self.alias) else: from .symbol import Dummy return PurePoly.new(self.rep, Dummy('x')) def as_expr(self, x=None): """Create a Basic expression from ``self``. """ return self.as_poly(x or self.root).as_expr().expand() def coeffs(self): """Returns all SymPy coefficients of an algebraic number. """ return [ self.rep.dom.to_sympy(c) for c in self.rep.all_coeffs() ] def native_coeffs(self): """Returns all native coefficients of an algebraic number. """ return self.rep.all_coeffs() def to_algebraic_integer(self): """Convert ``self`` to an algebraic integer. """ from sympy.polys.polytools import Poly f = self.minpoly if f.LC() == 1: return self coeff = f.LC()**(f.degree() - 1) poly = f.compose(Poly(f.gen/f.LC())) minpoly = poly*coeff root = f.LC()*self.root return AlgebraicNumber((minpoly, root), self.coeffs()) def _eval_simplify(self, **kwargs): from sympy.polys.rootoftools import CRootOf from sympy.polys import minpoly measure, ratio = kwargs['measure'], kwargs['ratio'] for r in [r for r in self.minpoly.all_roots() if r.func != CRootOf]: if minpoly(self.root - r).is_Symbol: # use the matching root if it's simpler if measure(r) < ratio*measure(self.root): return AlgebraicNumber(r) return self def field_element(self, coeffs): r""" Form another element of the same number field. Explanation =========== If we represent $\alpha \in \mathbb{Q}(\theta)$, form another element $\beta \in \mathbb{Q}(\theta)$ of the same number field. Parameters ========== coeffs : list, :py:class:`~.ANP` Like the *coeffs* arg to the class :py:meth:`constructor<.AlgebraicNumber.__new__>`, defines the new element as a polynomial in the primitive element. If a list, the elements should be integers or rational numbers. If an :py:class:`~.ANP`, we take its coefficients (using its :py:meth:`~.ANP.to_list()` method). Examples ======== >>> from sympy import AlgebraicNumber, sqrt >>> a = AlgebraicNumber(sqrt(5), [-1, 1]) >>> b = a.field_element([3, 2]) >>> print(a) 1 - sqrt(5) >>> print(b) 2 + 3*sqrt(5) >>> print(b.primitive_element() == a.primitive_element()) True See Also ======== .AlgebraicNumber.__new__() """ return AlgebraicNumber( (self.minpoly, self.root), coeffs=coeffs, alias=self.alias) @property def is_primitive_element(self): r""" Say whether this algebraic number $\alpha \in \mathbb{Q}(\theta)$ is equal to the primitive element $\theta$ for its field. """ c = self.coeffs() # Second case occurs if self.minpoly is linear: return c == [1, 0] or c == [self.root] def primitive_element(self): r""" Get the primitive element $\theta$ for the number field $\mathbb{Q}(\theta)$ to which this algebraic number $\alpha$ belongs. Returns ======= AlgebraicNumber """ if self.is_primitive_element: return self return self.field_element([1, 0]) def to_primitive_element(self, radicals=True): r""" Convert ``self`` to an :py:class:`~.AlgebraicNumber` instance that is equal to its own primitive element. Explanation =========== If we represent $\alpha \in \mathbb{Q}(\theta)$, $\alpha \neq \theta$, construct a new :py:class:`~.AlgebraicNumber` that represents $\alpha \in \mathbb{Q}(\alpha)$. Examples ======== >>> from sympy import sqrt, to_number_field >>> from sympy.abc import x >>> a = to_number_field(sqrt(2), sqrt(2) + sqrt(3)) The :py:class:`~.AlgebraicNumber` ``a`` represents the number $\sqrt{2}$ in the field $\mathbb{Q}(\sqrt{2} + \sqrt{3})$. Rendering ``a`` as a polynomial, >>> a.as_poly().as_expr(x) x**3/2 - 9*x/2 reflects the fact that $\sqrt{2} = \theta^3/2 - 9 \theta/2$, where $\theta = \sqrt{2} + \sqrt{3}$. ``a`` is not equal to its own primitive element. Its minpoly >>> a.minpoly.as_poly().as_expr(x) x**4 - 10*x**2 + 1 is that of $\theta$. Converting to a primitive element, >>> a_prim = a.to_primitive_element() >>> a_prim.minpoly.as_poly().as_expr(x) x**2 - 2 we obtain an :py:class:`~.AlgebraicNumber` whose ``minpoly`` is that of the number itself. Parameters ========== radicals : boolean, optional (default=True) If ``True``, then we will try to return an :py:class:`~.AlgebraicNumber` whose ``root`` is an expression in radicals. If that is not possible (or if *radicals* is ``False``), ``root`` will be a :py:class:`~.ComplexRootOf`. Returns ======= AlgebraicNumber See Also ======== is_primitive_element """ if self.is_primitive_element: return self m = self.minpoly_of_element() r = self.to_root(radicals=radicals) return AlgebraicNumber((m, r)) def minpoly_of_element(self): r""" Compute the minimal polynomial for this algebraic number. Explanation =========== Recall that we represent an element $\alpha \in \mathbb{Q}(\theta)$. Our instance attribute ``self.minpoly`` is the minimal polynomial for our primitive element $\theta$. This method computes the minimal polynomial for $\alpha$. """ if self._own_minpoly is None: if self.is_primitive_element: self._own_minpoly = self.minpoly else: from sympy.polys.numberfields.minpoly import minpoly theta = self.primitive_element() self._own_minpoly = minpoly(self.as_expr(theta), polys=True) return self._own_minpoly def to_root(self, radicals=True, minpoly=None): """ Convert to an :py:class:`~.Expr` that is not an :py:class:`~.AlgebraicNumber`, specifically, either a :py:class:`~.ComplexRootOf`, or, optionally and where possible, an expression in radicals. Parameters ========== radicals : boolean, optional (default=True) If ``True``, then we will try to return the root as an expression in radicals. If that is not possible, we will return a :py:class:`~.ComplexRootOf`. minpoly : :py:class:`~.Poly` If the minimal polynomial for `self` has been pre-computed, it can be passed in order to save time. """ if self.is_primitive_element and not isinstance(self.root, AlgebraicNumber): return self.root m = minpoly or self.minpoly_of_element() roots = m.all_roots(radicals=radicals) if len(roots) == 1: return roots[0] ex = self.as_expr() for b in roots: if m.same_root(b, ex): return b class RationalConstant(Rational): """ Abstract base class for rationals with specific behaviors Derived classes must define class attributes p and q and should probably all be singletons. """ __slots__ = () def __new__(cls): return AtomicExpr.__new__(cls) class IntegerConstant(Integer): __slots__ = () def __new__(cls): return AtomicExpr.__new__(cls) class Zero(IntegerConstant, metaclass=Singleton): """The number zero. Zero is a singleton, and can be accessed by ``S.Zero`` Examples ======== >>> from sympy import S, Integer >>> Integer(0) is S.Zero True >>> 1/S.Zero zoo References ========== .. [1] https://en.wikipedia.org/wiki/Zero """ p = 0 q = 1 is_positive = False is_negative = False is_zero = True is_number = True is_comparable = True __slots__ = () def __getnewargs__(self): return () @staticmethod def __abs__(): return S.Zero @staticmethod def __neg__(): return S.Zero def _eval_power(self, expt): if expt.is_extended_positive: return self if expt.is_extended_negative: return S.ComplexInfinity if expt.is_extended_real is False: return S.NaN if expt.is_zero: return S.One # infinities are already handled with pos and neg # tests above; now throw away leading numbers on Mul # exponent since 0**-x = zoo**x even when x == 0 coeff, terms = expt.as_coeff_Mul() if coeff.is_negative: return S.ComplexInfinity**terms if coeff is not S.One: # there is a Number to discard return self**terms def _eval_order(self, *symbols): # Order(0,x) -> 0 return self def __bool__(self): return False class One(IntegerConstant, metaclass=Singleton): """The number one. One is a singleton, and can be accessed by ``S.One``. Examples ======== >>> from sympy import S, Integer >>> Integer(1) is S.One True References ========== .. [1] https://en.wikipedia.org/wiki/1_%28number%29 """ is_number = True is_positive = True p = 1 q = 1 __slots__ = () def __getnewargs__(self): return () @staticmethod def __abs__(): return S.One @staticmethod def __neg__(): return S.NegativeOne def _eval_power(self, expt): return self def _eval_order(self, *symbols): return @staticmethod def factors(limit=None, use_trial=True, use_rho=False, use_pm1=False, verbose=False, visual=False): if visual: return S.One else: return {} class NegativeOne(IntegerConstant, metaclass=Singleton): """The number negative one. NegativeOne is a singleton, and can be accessed by ``S.NegativeOne``. Examples ======== >>> from sympy import S, Integer >>> Integer(-1) is S.NegativeOne True See Also ======== One References ========== .. [1] https://en.wikipedia.org/wiki/%E2%88%921_%28number%29 """ is_number = True p = -1 q = 1 __slots__ = () def __getnewargs__(self): return () @staticmethod def __abs__(): return S.One @staticmethod def __neg__(): return S.One def _eval_power(self, expt): if expt.is_odd: return S.NegativeOne if expt.is_even: return S.One if isinstance(expt, Number): if isinstance(expt, Float): return Float(-1.0)**expt if expt is S.NaN: return S.NaN if expt in (S.Infinity, S.NegativeInfinity): return S.NaN if expt is S.Half: return S.ImaginaryUnit if isinstance(expt, Rational): if expt.q == 2: return S.ImaginaryUnit**Integer(expt.p) i, r = divmod(expt.p, expt.q) if i: return self**i*self**Rational(r, expt.q) return class Half(RationalConstant, metaclass=Singleton): """The rational number 1/2. Half is a singleton, and can be accessed by ``S.Half``. Examples ======== >>> from sympy import S, Rational >>> Rational(1, 2) is S.Half True References ========== .. [1] https://en.wikipedia.org/wiki/One_half """ is_number = True p = 1 q = 2 __slots__ = () def __getnewargs__(self): return () @staticmethod def __abs__(): return S.Half class Infinity(Number, metaclass=Singleton): r"""Positive infinite quantity. Explanation =========== In real analysis the symbol `\infty` denotes an unbounded limit: `x\to\infty` means that `x` grows without bound. Infinity is often used not only to define a limit but as a value in the affinely extended real number system. Points labeled `+\infty` and `-\infty` can be added to the topological space of the real numbers, producing the two-point compactification of the real numbers. Adding algebraic properties to this gives us the extended real numbers. Infinity is a singleton, and can be accessed by ``S.Infinity``, or can be imported as ``oo``. Examples ======== >>> from sympy import oo, exp, limit, Symbol >>> 1 + oo oo >>> 42/oo 0 >>> x = Symbol('x') >>> limit(exp(x), x, oo) oo See Also ======== NegativeInfinity, NaN References ========== .. [1] https://en.wikipedia.org/wiki/Infinity """ is_commutative = True is_number = True is_complex = False is_extended_real = True is_infinite = True is_comparable = True is_extended_positive = True is_prime = False __slots__ = () def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"\infty" def _eval_subs(self, old, new): if self == old: return new def _eval_evalf(self, prec=None): return Float('inf') def evalf(self, prec=None, **options): return self._eval_evalf(prec) @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other in (S.NegativeInfinity, S.NaN): return S.NaN return self return Number.__add__(self, other) __radd__ = __add__ @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other in (S.Infinity, S.NaN): return S.NaN return self return Number.__sub__(self, other) @_sympifyit('other', NotImplemented) def __rsub__(self, other): return (-self).__add__(other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other.is_zero or other is S.NaN: return S.NaN if other.is_extended_positive: return self return S.NegativeInfinity return Number.__mul__(self, other) __rmul__ = __mul__ @_sympifyit('other', NotImplemented) def __truediv__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other is S.Infinity or \ other is S.NegativeInfinity or \ other is S.NaN: return S.NaN if other.is_extended_nonnegative: return self return S.NegativeInfinity return Number.__truediv__(self, other) def __abs__(self): return S.Infinity def __neg__(self): return S.NegativeInfinity def _eval_power(self, expt): """ ``expt`` is symbolic object but not equal to 0 or 1. ================ ======= ============================== Expression Result Notes ================ ======= ============================== ``oo ** nan`` ``nan`` ``oo ** -p`` ``0`` ``p`` is number, ``oo`` ================ ======= ============================== See Also ======== Pow NaN NegativeInfinity """ if expt.is_extended_positive: return S.Infinity if expt.is_extended_negative: return S.Zero if expt is S.NaN: return S.NaN if expt is S.ComplexInfinity: return S.NaN if expt.is_extended_real is False and expt.is_number: from sympy.functions.elementary.complexes import re expt_real = re(expt) if expt_real.is_positive: return S.ComplexInfinity if expt_real.is_negative: return S.Zero if expt_real.is_zero: return S.NaN return self**expt.evalf() def _as_mpf_val(self, prec): return mlib.finf def __hash__(self): return super().__hash__() def __eq__(self, other): return other is S.Infinity or other == float('inf') def __ne__(self, other): return other is not S.Infinity and other != float('inf') __gt__ = Expr.__gt__ __ge__ = Expr.__ge__ __lt__ = Expr.__lt__ __le__ = Expr.__le__ @_sympifyit('other', NotImplemented) def __mod__(self, other): if not isinstance(other, Expr): return NotImplemented return S.NaN __rmod__ = __mod__ def floor(self): return self def ceiling(self): return self oo = S.Infinity class NegativeInfinity(Number, metaclass=Singleton): """Negative infinite quantity. NegativeInfinity is a singleton, and can be accessed by ``S.NegativeInfinity``. See Also ======== Infinity """ is_extended_real = True is_complex = False is_commutative = True is_infinite = True is_comparable = True is_extended_negative = True is_number = True is_prime = False __slots__ = () def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"-\infty" def _eval_subs(self, old, new): if self == old: return new def _eval_evalf(self, prec=None): return Float('-inf') def evalf(self, prec=None, **options): return self._eval_evalf(prec) @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other in (S.Infinity, S.NaN): return S.NaN return self return Number.__add__(self, other) __radd__ = __add__ @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other in (S.NegativeInfinity, S.NaN): return S.NaN return self return Number.__sub__(self, other) @_sympifyit('other', NotImplemented) def __rsub__(self, other): return (-self).__add__(other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other.is_zero or other is S.NaN: return S.NaN if other.is_extended_positive: return self return S.Infinity return Number.__mul__(self, other) __rmul__ = __mul__ @_sympifyit('other', NotImplemented) def __truediv__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other is S.Infinity or \ other is S.NegativeInfinity or \ other is S.NaN: return S.NaN if other.is_extended_nonnegative: return self return S.Infinity return Number.__truediv__(self, other) def __abs__(self): return S.Infinity def __neg__(self): return S.Infinity def _eval_power(self, expt): """ ``expt`` is symbolic object but not equal to 0 or 1. ================ ======= ============================== Expression Result Notes ================ ======= ============================== ``(-oo) ** nan`` ``nan`` ``(-oo) ** oo`` ``nan`` ``(-oo) ** -oo`` ``nan`` ``(-oo) ** e`` ``oo`` ``e`` is positive even integer ``(-oo) ** o`` ``-oo`` ``o`` is positive odd integer ================ ======= ============================== See Also ======== Infinity Pow NaN """ if expt.is_number: if expt is S.NaN or \ expt is S.Infinity or \ expt is S.NegativeInfinity: return S.NaN if isinstance(expt, Integer) and expt.is_extended_positive: if expt.is_odd: return S.NegativeInfinity else: return S.Infinity inf_part = S.Infinity**expt s_part = S.NegativeOne**expt if inf_part == 0 and s_part.is_finite: return inf_part if (inf_part is S.ComplexInfinity and s_part.is_finite and not s_part.is_zero): return S.ComplexInfinity return s_part*inf_part def _as_mpf_val(self, prec): return mlib.fninf def __hash__(self): return super().__hash__() def __eq__(self, other): return other is S.NegativeInfinity or other == float('-inf') def __ne__(self, other): return other is not S.NegativeInfinity and other != float('-inf') __gt__ = Expr.__gt__ __ge__ = Expr.__ge__ __lt__ = Expr.__lt__ __le__ = Expr.__le__ @_sympifyit('other', NotImplemented) def __mod__(self, other): if not isinstance(other, Expr): return NotImplemented return S.NaN __rmod__ = __mod__ def floor(self): return self def ceiling(self): return self def as_powers_dict(self): return {S.NegativeOne: 1, S.Infinity: 1} class NaN(Number, metaclass=Singleton): """ Not a Number. Explanation =========== This serves as a place holder for numeric values that are indeterminate. Most operations on NaN, produce another NaN. Most indeterminate forms, such as ``0/0`` or ``oo - oo` produce NaN. Two exceptions are ``0**0`` and ``oo**0``, which all produce ``1`` (this is consistent with Python's float). NaN is loosely related to floating point nan, which is defined in the IEEE 754 floating point standard, and corresponds to the Python ``float('nan')``. Differences are noted below. NaN is mathematically not equal to anything else, even NaN itself. This explains the initially counter-intuitive results with ``Eq`` and ``==`` in the examples below. NaN is not comparable so inequalities raise a TypeError. This is in contrast with floating point nan where all inequalities are false. NaN is a singleton, and can be accessed by ``S.NaN``, or can be imported as ``nan``. Examples ======== >>> from sympy import nan, S, oo, Eq >>> nan is S.NaN True >>> oo - oo nan >>> nan + 1 nan >>> Eq(nan, nan) # mathematical equality False >>> nan == nan # structural equality True References ========== .. [1] https://en.wikipedia.org/wiki/NaN """ is_commutative = True is_extended_real = None is_real = None is_rational = None is_algebraic = None is_transcendental = None is_integer = None is_comparable = False is_finite = None is_zero = None is_prime = None is_positive = None is_negative = None is_number = True __slots__ = () def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"\text{NaN}" def __neg__(self): return self @_sympifyit('other', NotImplemented) def __add__(self, other): return self @_sympifyit('other', NotImplemented) def __sub__(self, other): return self @_sympifyit('other', NotImplemented) def __mul__(self, other): return self @_sympifyit('other', NotImplemented) def __truediv__(self, other): return self def floor(self): return self def ceiling(self): return self def _as_mpf_val(self, prec): return _mpf_nan def __hash__(self): return super().__hash__() def __eq__(self, other): # NaN is structurally equal to another NaN return other is S.NaN def __ne__(self, other): return other is not S.NaN # Expr will _sympify and raise TypeError __gt__ = Expr.__gt__ __ge__ = Expr.__ge__ __lt__ = Expr.__lt__ __le__ = Expr.__le__ nan = S.NaN @dispatch(NaN, Expr) # type:ignore def _eval_is_eq(a, b): # noqa:F811 return False class ComplexInfinity(AtomicExpr, metaclass=Singleton): r"""Complex infinity. Explanation =========== In complex analysis the symbol `\tilde\infty`, called "complex infinity", represents a quantity with infinite magnitude, but undetermined complex phase. ComplexInfinity is a singleton, and can be accessed by ``S.ComplexInfinity``, or can be imported as ``zoo``. Examples ======== >>> from sympy import zoo >>> zoo + 42 zoo >>> 42/zoo 0 >>> zoo + zoo nan >>> zoo*zoo zoo See Also ======== Infinity """ is_commutative = True is_infinite = True is_number = True is_prime = False is_complex = False is_extended_real = False kind = NumberKind __slots__ = () def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"\tilde{\infty}" @staticmethod def __abs__(): return S.Infinity def floor(self): return self def ceiling(self): return self @staticmethod def __neg__(): return S.ComplexInfinity def _eval_power(self, expt): if expt is S.ComplexInfinity: return S.NaN if isinstance(expt, Number): if expt.is_zero: return S.NaN else: if expt.is_positive: return S.ComplexInfinity else: return S.Zero zoo = S.ComplexInfinity class NumberSymbol(AtomicExpr): is_commutative = True is_finite = True is_number = True __slots__ = () is_NumberSymbol = True kind = NumberKind def __new__(cls): return AtomicExpr.__new__(cls) def approximation(self, number_cls): """ Return an interval with number_cls endpoints that contains the value of NumberSymbol. If not implemented, then return None. """ def _eval_evalf(self, prec): return Float._new(self._as_mpf_val(prec), prec) def __eq__(self, other): try: other = _sympify(other) except SympifyError: return NotImplemented if self is other: return True if other.is_Number and self.is_irrational: return False return False # NumberSymbol != non-(Number|self) def __ne__(self, other): return not self == other def __le__(self, other): if self is other: return S.true return Expr.__le__(self, other) def __ge__(self, other): if self is other: return S.true return Expr.__ge__(self, other) def __int__(self): # subclass with appropriate return value raise NotImplementedError def __hash__(self): return super().__hash__() class Exp1(NumberSymbol, metaclass=Singleton): r"""The `e` constant. Explanation =========== The transcendental number `e = 2.718281828\ldots` is the base of the natural logarithm and of the exponential function, `e = \exp(1)`. Sometimes called Euler's number or Napier's constant. Exp1 is a singleton, and can be accessed by ``S.Exp1``, or can be imported as ``E``. Examples ======== >>> from sympy import exp, log, E >>> E is exp(1) True >>> log(E) 1 References ========== .. [1] https://en.wikipedia.org/wiki/E_%28mathematical_constant%29 """ is_real = True is_positive = True is_negative = False # XXX Forces is_negative/is_nonnegative is_irrational = True is_number = True is_algebraic = False is_transcendental = True __slots__ = () def _latex(self, printer): return r"e" @staticmethod def __abs__(): return S.Exp1 def __int__(self): return 2 def _as_mpf_val(self, prec): return mpf_e(prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (Integer(2), Integer(3)) elif issubclass(number_cls, Rational): pass def _eval_power(self, expt): if global_parameters.exp_is_pow: return self._eval_power_exp_is_pow(expt) else: from sympy.functions.elementary.exponential import exp return exp(expt) def _eval_power_exp_is_pow(self, arg): if arg.is_Number: if arg is oo: return oo elif arg == -oo: return S.Zero from sympy.functions.elementary.exponential import log if isinstance(arg, log): return arg.args[0] # don't autoexpand Pow or Mul (see the issue 3351): elif not arg.is_Add: Ioo = I*oo if arg in [Ioo, -Ioo]: return nan coeff = arg.coeff(pi*I) if coeff: if (2*coeff).is_integer: if coeff.is_even: return S.One elif coeff.is_odd: return S.NegativeOne elif (coeff + S.Half).is_even: return -I elif (coeff + S.Half).is_odd: return I elif coeff.is_Rational: ncoeff = coeff % 2 # restrict to [0, 2pi) if ncoeff > 1: # restrict to (-pi, pi] ncoeff -= 2 if ncoeff != coeff: return S.Exp1**(ncoeff*S.Pi*S.ImaginaryUnit) # Warning: code in risch.py will be very sensitive to changes # in this (see DifferentialExtension). # look for a single log factor coeff, terms = arg.as_coeff_Mul() # but it can't be multiplied by oo if coeff in (oo, -oo): return coeffs, log_term = [coeff], None for term in Mul.make_args(terms): if isinstance(term, log): if log_term is None: log_term = term.args[0] else: return elif term.is_comparable: coeffs.append(term) else: return return log_term**Mul(*coeffs) if log_term else None elif arg.is_Add: out = [] add = [] argchanged = False for a in arg.args: if a is S.One: add.append(a) continue newa = self**a if isinstance(newa, Pow) and newa.base is self: if newa.exp != a: add.append(newa.exp) argchanged = True else: add.append(a) else: out.append(newa) if out or argchanged: return Mul(*out)*Pow(self, Add(*add), evaluate=False) elif arg.is_Matrix: return arg.exp() def _eval_rewrite_as_sin(self, **kwargs): from sympy.functions.elementary.trigonometric import sin return sin(I + S.Pi/2) - I*sin(I) def _eval_rewrite_as_cos(self, **kwargs): from sympy.functions.elementary.trigonometric import cos return cos(I) + I*cos(I + S.Pi/2) E = S.Exp1 class Pi(NumberSymbol, metaclass=Singleton): r"""The `\pi` constant. Explanation =========== The transcendental number `\pi = 3.141592654\ldots` represents the ratio of a circle's circumference to its diameter, the area of the unit circle, the half-period of trigonometric functions, and many other things in mathematics. Pi is a singleton, and can be accessed by ``S.Pi``, or can be imported as ``pi``. Examples ======== >>> from sympy import S, pi, oo, sin, exp, integrate, Symbol >>> S.Pi pi >>> pi > 3 True >>> pi.is_irrational True >>> x = Symbol('x') >>> sin(x + 2*pi) sin(x) >>> integrate(exp(-x**2), (x, -oo, oo)) sqrt(pi) References ========== .. [1] https://en.wikipedia.org/wiki/Pi """ is_real = True is_positive = True is_negative = False is_irrational = True is_number = True is_algebraic = False is_transcendental = True __slots__ = () def _latex(self, printer): return r"\pi" @staticmethod def __abs__(): return S.Pi def __int__(self): return 3 def _as_mpf_val(self, prec): return mpf_pi(prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (Integer(3), Integer(4)) elif issubclass(number_cls, Rational): return (Rational(223, 71, 1), Rational(22, 7, 1)) pi = S.Pi class GoldenRatio(NumberSymbol, metaclass=Singleton): r"""The golden ratio, `\phi`. Explanation =========== `\phi = \frac{1 + \sqrt{5}}{2}` is an algebraic number. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities, i.e. their maximum. GoldenRatio is a singleton, and can be accessed by ``S.GoldenRatio``. Examples ======== >>> from sympy import S >>> S.GoldenRatio > 1 True >>> S.GoldenRatio.expand(func=True) 1/2 + sqrt(5)/2 >>> S.GoldenRatio.is_irrational True References ========== .. [1] https://en.wikipedia.org/wiki/Golden_ratio """ is_real = True is_positive = True is_negative = False is_irrational = True is_number = True is_algebraic = True is_transcendental = False __slots__ = () def _latex(self, printer): return r"\phi" def __int__(self): return 1 def _as_mpf_val(self, prec): # XXX track down why this has to be increased rv = mlib.from_man_exp(phi_fixed(prec + 10), -prec - 10) return mpf_norm(rv, prec) def _eval_expand_func(self, **hints): from sympy.functions.elementary.miscellaneous import sqrt return S.Half + S.Half*sqrt(5) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.One, Rational(2)) elif issubclass(number_cls, Rational): pass _eval_rewrite_as_sqrt = _eval_expand_func class TribonacciConstant(NumberSymbol, metaclass=Singleton): r"""The tribonacci constant. Explanation =========== The tribonacci numbers are like the Fibonacci numbers, but instead of starting with two predetermined terms, the sequence starts with three predetermined terms and each term afterwards is the sum of the preceding three terms. The tribonacci constant is the ratio toward which adjacent tribonacci numbers tend. It is a root of the polynomial `x^3 - x^2 - x - 1 = 0`, and also satisfies the equation `x + x^{-3} = 2`. TribonacciConstant is a singleton, and can be accessed by ``S.TribonacciConstant``. Examples ======== >>> from sympy import S >>> S.TribonacciConstant > 1 True >>> S.TribonacciConstant.expand(func=True) 1/3 + (19 - 3*sqrt(33))**(1/3)/3 + (3*sqrt(33) + 19)**(1/3)/3 >>> S.TribonacciConstant.is_irrational True >>> S.TribonacciConstant.n(20) 1.8392867552141611326 References ========== .. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers """ is_real = True is_positive = True is_negative = False is_irrational = True is_number = True is_algebraic = True is_transcendental = False __slots__ = () def _latex(self, printer): return r"\text{TribonacciConstant}" def __int__(self): return 1 def _eval_evalf(self, prec): rv = self._eval_expand_func(function=True)._eval_evalf(prec + 4) return Float(rv, precision=prec) def _eval_expand_func(self, **hints): from sympy.functions.elementary.miscellaneous import cbrt, sqrt return (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3 def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.One, Rational(2)) elif issubclass(number_cls, Rational): pass _eval_rewrite_as_sqrt = _eval_expand_func class EulerGamma(NumberSymbol, metaclass=Singleton): r"""The Euler-Mascheroni constant. Explanation =========== `\gamma = 0.5772157\ldots` (also called Euler's constant) is a mathematical constant recurring in analysis and number theory. It is defined as the limiting difference between the harmonic series and the natural logarithm: .. math:: \gamma = \lim\limits_{n\to\infty} \left(\sum\limits_{k=1}^n\frac{1}{k} - \ln n\right) EulerGamma is a singleton, and can be accessed by ``S.EulerGamma``. Examples ======== >>> from sympy import S >>> S.EulerGamma.is_irrational >>> S.EulerGamma > 0 True >>> S.EulerGamma > 1 False References ========== .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant """ is_real = True is_positive = True is_negative = False is_irrational = None is_number = True __slots__ = () def _latex(self, printer): return r"\gamma" def __int__(self): return 0 def _as_mpf_val(self, prec): # XXX track down why this has to be increased v = mlib.libhyper.euler_fixed(prec + 10) rv = mlib.from_man_exp(v, -prec - 10) return mpf_norm(rv, prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.Zero, S.One) elif issubclass(number_cls, Rational): return (S.Half, Rational(3, 5, 1)) class Catalan(NumberSymbol, metaclass=Singleton): r"""Catalan's constant. Explanation =========== $G = 0.91596559\ldots$ is given by the infinite series .. math:: G = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2} Catalan is a singleton, and can be accessed by ``S.Catalan``. Examples ======== >>> from sympy import S >>> S.Catalan.is_irrational >>> S.Catalan > 0 True >>> S.Catalan > 1 False References ========== .. [1] https://en.wikipedia.org/wiki/Catalan%27s_constant """ is_real = True is_positive = True is_negative = False is_irrational = None is_number = True __slots__ = () def __int__(self): return 0 def _as_mpf_val(self, prec): # XXX track down why this has to be increased v = mlib.catalan_fixed(prec + 10) rv = mlib.from_man_exp(v, -prec - 10) return mpf_norm(rv, prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.Zero, S.One) elif issubclass(number_cls, Rational): return (Rational(9, 10, 1), S.One) def _eval_rewrite_as_Sum(self, k_sym=None, symbols=None): if (k_sym is not None) or (symbols is not None): return self from .symbol import Dummy from sympy.concrete.summations import Sum k = Dummy('k', integer=True, nonnegative=True) return Sum(S.NegativeOne**k / (2*k+1)**2, (k, 0, S.Infinity)) def _latex(self, printer): return "G" class ImaginaryUnit(AtomicExpr, metaclass=Singleton): r"""The imaginary unit, `i = \sqrt{-1}`. I is a singleton, and can be accessed by ``S.I``, or can be imported as ``I``. Examples ======== >>> from sympy import I, sqrt >>> sqrt(-1) I >>> I*I -1 >>> 1/I -I References ========== .. [1] https://en.wikipedia.org/wiki/Imaginary_unit """ is_commutative = True is_imaginary = True is_finite = True is_number = True is_algebraic = True is_transcendental = False kind = NumberKind __slots__ = () def _latex(self, printer): return printer._settings['imaginary_unit_latex'] @staticmethod def __abs__(): return S.One def _eval_evalf(self, prec): return self def _eval_conjugate(self): return -S.ImaginaryUnit def _eval_power(self, expt): """ b is I = sqrt(-1) e is symbolic object but not equal to 0, 1 I**r -> (-1)**(r/2) -> exp(r/2*Pi*I) -> sin(Pi*r/2) + cos(Pi*r/2)*I, r is decimal I**0 mod 4 -> 1 I**1 mod 4 -> I I**2 mod 4 -> -1 I**3 mod 4 -> -I """ if isinstance(expt, Integer): expt = expt % 4 if expt == 0: return S.One elif expt == 1: return S.ImaginaryUnit elif expt == 2: return S.NegativeOne elif expt == 3: return -S.ImaginaryUnit if isinstance(expt, Rational): i, r = divmod(expt, 2) rv = Pow(S.ImaginaryUnit, r, evaluate=False) if i % 2: return Mul(S.NegativeOne, rv, evaluate=False) return rv def as_base_exp(self): return S.NegativeOne, S.Half @property def _mpc_(self): return (Float(0)._mpf_, Float(1)._mpf_) I = S.ImaginaryUnit @dispatch(Tuple, Number) # type:ignore def _eval_is_eq(self, other): # noqa: F811 return False def sympify_fractions(f): return Rational(f.numerator, f.denominator, 1) _sympy_converter[fractions.Fraction] = sympify_fractions if HAS_GMPY: def sympify_mpz(x): return Integer(int(x)) # XXX: The sympify_mpq function here was never used because it is # overridden by the other sympify_mpq function below. Maybe it should just # be removed or maybe it should be used for something... def sympify_mpq(x): return Rational(int(x.numerator), int(x.denominator)) _sympy_converter[type(gmpy.mpz(1))] = sympify_mpz _sympy_converter[type(gmpy.mpq(1, 2))] = sympify_mpq def sympify_mpmath_mpq(x): p, q = x._mpq_ return Rational(p, q, 1) _sympy_converter[type(mpmath.rational.mpq(1, 2))] = sympify_mpmath_mpq def sympify_mpmath(x): return Expr._from_mpmath(x, x.context.prec) _sympy_converter[mpnumeric] = sympify_mpmath def sympify_complex(a): real, imag = list(map(sympify, (a.real, a.imag))) return real + S.ImaginaryUnit*imag _sympy_converter[complex] = sympify_complex from .power import Pow, integer_nthroot from .mul import Mul Mul.identity = One() from .add import Add Add.identity = Zero() def _register_classes(): numbers.Number.register(Number) numbers.Real.register(Float) numbers.Rational.register(Rational) numbers.Integral.register(Integer) _register_classes() _illegal = (S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity)
77c3f6ac3162570a78250e22b6de3d5a7907983b753cc0bfd79057f8c9326087
"""Algorithms for computing symbolic roots of polynomials. """ import math from functools import reduce from sympy.core import S, I, pi from sympy.core.exprtools import factor_terms from sympy.core.function import _mexpand from sympy.core.logic import fuzzy_not from sympy.core.mul import expand_2arg, Mul from sympy.core.numbers import Rational, igcd, comp from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.core.sorting import ordered from sympy.core.symbol import Dummy, Symbol, symbols from sympy.core.sympify import sympify from sympy.functions import exp, im, cos, acos, Piecewise from sympy.functions.elementary.miscellaneous import root, sqrt from sympy.ntheory import divisors, isprime, nextprime from sympy.polys.domains import EX from sympy.polys.polyerrors import (PolynomialError, GeneratorsNeeded, DomainError, UnsolvableFactorError) from sympy.polys.polyquinticconst import PolyQuintic from sympy.polys.polytools import Poly, cancel, factor, gcd_list, discriminant from sympy.polys.rationaltools import together from sympy.polys.specialpolys import cyclotomic_poly from sympy.utilities import public from sympy.utilities.misc import filldedent z = Symbol('z') # importing from abc cause O to be lost as clashing symbol def roots_linear(f): """Returns a list of roots of a linear polynomial.""" r = -f.nth(0)/f.nth(1) dom = f.get_domain() if not dom.is_Numerical: if dom.is_Composite: r = factor(r) else: from sympy.simplify.simplify import simplify r = simplify(r) return [r] def roots_quadratic(f): """Returns a list of roots of a quadratic polynomial. If the domain is ZZ then the roots will be sorted with negatives coming before positives. The ordering will be the same for any numerical coefficients as long as the assumptions tested are correct, otherwise the ordering will not be sorted (but will be canonical). """ a, b, c = f.all_coeffs() dom = f.get_domain() def _sqrt(d): # remove squares from square root since both will be represented # in the results; a similar thing is happening in roots() but # must be duplicated here because not all quadratics are binomials co = [] other = [] for di in Mul.make_args(d): if di.is_Pow and di.exp.is_Integer and di.exp % 2 == 0: co.append(Pow(di.base, di.exp//2)) else: other.append(di) if co: d = Mul(*other) co = Mul(*co) return co*sqrt(d) return sqrt(d) def _simplify(expr): if dom.is_Composite: return factor(expr) else: from sympy.simplify.simplify import simplify return simplify(expr) if c is S.Zero: r0, r1 = S.Zero, -b/a if not dom.is_Numerical: r1 = _simplify(r1) elif r1.is_negative: r0, r1 = r1, r0 elif b is S.Zero: r = -c/a if not dom.is_Numerical: r = _simplify(r) R = _sqrt(r) r0 = -R r1 = R else: d = b**2 - 4*a*c A = 2*a B = -b/A if not dom.is_Numerical: d = _simplify(d) B = _simplify(B) D = factor_terms(_sqrt(d)/A) r0 = B - D r1 = B + D if a.is_negative: r0, r1 = r1, r0 elif not dom.is_Numerical: r0, r1 = [expand_2arg(i) for i in (r0, r1)] return [r0, r1] def roots_cubic(f, trig=False): """Returns a list of roots of a cubic polynomial. References ========== [1] https://en.wikipedia.org/wiki/Cubic_function, General formula for roots, (accessed November 17, 2014). """ if trig: a, b, c, d = f.all_coeffs() p = (3*a*c - b**2)/(3*a**2) q = (2*b**3 - 9*a*b*c + 27*a**2*d)/(27*a**3) D = 18*a*b*c*d - 4*b**3*d + b**2*c**2 - 4*a*c**3 - 27*a**2*d**2 if (D > 0) == True: rv = [] for k in range(3): rv.append(2*sqrt(-p/3)*cos(acos(q/p*sqrt(-3/p)*Rational(3, 2))/3 - k*pi*Rational(2, 3))) return [i - b/3/a for i in rv] # a*x**3 + b*x**2 + c*x + d -> x**3 + a*x**2 + b*x + c _, a, b, c = f.monic().all_coeffs() if c is S.Zero: x1, x2 = roots([1, a, b], multiple=True) return [x1, S.Zero, x2] # x**3 + a*x**2 + b*x + c -> u**3 + p*u + q p = b - a**2/3 q = c - a*b/3 + 2*a**3/27 pon3 = p/3 aon3 = a/3 u1 = None if p is S.Zero: if q is S.Zero: return [-aon3]*3 u1 = -root(q, 3) if q.is_positive else root(-q, 3) elif q is S.Zero: y1, y2 = roots([1, 0, p], multiple=True) return [tmp - aon3 for tmp in [y1, S.Zero, y2]] elif q.is_real and q.is_negative: u1 = -root(-q/2 + sqrt(q**2/4 + pon3**3), 3) coeff = I*sqrt(3)/2 if u1 is None: u1 = S.One u2 = Rational(-1, 2) + coeff u3 = Rational(-1, 2) - coeff b, c, d = a, b, c # a, b, c, d = S.One, a, b, c D0 = b**2 - 3*c # b**2 - 3*a*c D1 = 2*b**3 - 9*b*c + 27*d # 2*b**3 - 9*a*b*c + 27*a**2*d C = root((D1 + sqrt(D1**2 - 4*D0**3))/2, 3) return [-(b + uk*C + D0/C/uk)/3 for uk in [u1, u2, u3]] # -(b + uk*C + D0/C/uk)/3/a u2 = u1*(Rational(-1, 2) + coeff) u3 = u1*(Rational(-1, 2) - coeff) if p is S.Zero: return [u1 - aon3, u2 - aon3, u3 - aon3] soln = [ -u1 + pon3/u1 - aon3, -u2 + pon3/u2 - aon3, -u3 + pon3/u3 - aon3 ] return soln def _roots_quartic_euler(p, q, r, a): """ Descartes-Euler solution of the quartic equation Parameters ========== p, q, r: coefficients of ``x**4 + p*x**2 + q*x + r`` a: shift of the roots Notes ===== This is a helper function for ``roots_quartic``. Look for solutions of the form :: ``x1 = sqrt(R) - sqrt(A + B*sqrt(R))`` ``x2 = -sqrt(R) - sqrt(A - B*sqrt(R))`` ``x3 = -sqrt(R) + sqrt(A - B*sqrt(R))`` ``x4 = sqrt(R) + sqrt(A + B*sqrt(R))`` To satisfy the quartic equation one must have ``p = -2*(R + A); q = -4*B*R; r = (R - A)**2 - B**2*R`` so that ``R`` must satisfy the Descartes-Euler resolvent equation ``64*R**3 + 32*p*R**2 + (4*p**2 - 16*r)*R - q**2 = 0`` If the resolvent does not have a rational solution, return None; in that case it is likely that the Ferrari method gives a simpler solution. Examples ======== >>> from sympy import S >>> from sympy.polys.polyroots import _roots_quartic_euler >>> p, q, r = -S(64)/5, -S(512)/125, -S(1024)/3125 >>> _roots_quartic_euler(p, q, r, S(0))[0] -sqrt(32*sqrt(5)/125 + 16/5) + 4*sqrt(5)/5 """ # solve the resolvent equation x = Dummy('x') eq = 64*x**3 + 32*p*x**2 + (4*p**2 - 16*r)*x - q**2 xsols = list(roots(Poly(eq, x), cubics=False).keys()) xsols = [sol for sol in xsols if sol.is_rational and sol.is_nonzero] if not xsols: return None R = max(xsols) c1 = sqrt(R) B = -q*c1/(4*R) A = -R - p/2 c2 = sqrt(A + B) c3 = sqrt(A - B) return [c1 - c2 - a, -c1 - c3 - a, -c1 + c3 - a, c1 + c2 - a] def roots_quartic(f): r""" Returns a list of roots of a quartic polynomial. There are many references for solving quartic expressions available [1-5]. This reviewer has found that many of them require one to select from among 2 or more possible sets of solutions and that some solutions work when one is searching for real roots but do not work when searching for complex roots (though this is not always stated clearly). The following routine has been tested and found to be correct for 0, 2 or 4 complex roots. The quasisymmetric case solution [6] looks for quartics that have the form `x**4 + A*x**3 + B*x**2 + C*x + D = 0` where `(C/A)**2 = D`. Although no general solution that is always applicable for all coefficients is known to this reviewer, certain conditions are tested to determine the simplest 4 expressions that can be returned: 1) `f = c + a*(a**2/8 - b/2) == 0` 2) `g = d - a*(a*(3*a**2/256 - b/16) + c/4) = 0` 3) if `f != 0` and `g != 0` and `p = -d + a*c/4 - b**2/12` then a) `p == 0` b) `p != 0` Examples ======== >>> from sympy import Poly >>> from sympy.polys.polyroots import roots_quartic >>> r = roots_quartic(Poly('x**4-6*x**3+17*x**2-26*x+20')) >>> # 4 complex roots: 1+-I*sqrt(3), 2+-I >>> sorted(str(tmp.evalf(n=2)) for tmp in r) ['1.0 + 1.7*I', '1.0 - 1.7*I', '2.0 + 1.0*I', '2.0 - 1.0*I'] References ========== 1. http://mathforum.org/dr.math/faq/faq.cubic.equations.html 2. https://en.wikipedia.org/wiki/Quartic_function#Summary_of_Ferrari.27s_method 3. http://planetmath.org/encyclopedia/GaloisTheoreticDerivationOfTheQuarticFormula.html 4. http://staff.bath.ac.uk/masjhd/JHD-CA.pdf 5. http://www.albmath.org/files/Math_5713.pdf 6. http://www.statemaster.com/encyclopedia/Quartic-equation 7. eqworld.ipmnet.ru/en/solutions/ae/ae0108.pdf """ _, a, b, c, d = f.monic().all_coeffs() if not d: return [S.Zero] + roots([1, a, b, c], multiple=True) elif (c/a)**2 == d: x, m = f.gen, c/a g = Poly(x**2 + a*x + b - 2*m, x) z1, z2 = roots_quadratic(g) h1 = Poly(x**2 - z1*x + m, x) h2 = Poly(x**2 - z2*x + m, x) r1 = roots_quadratic(h1) r2 = roots_quadratic(h2) return r1 + r2 else: a2 = a**2 e = b - 3*a2/8 f = _mexpand(c + a*(a2/8 - b/2)) aon4 = a/4 g = _mexpand(d - aon4*(a*(3*a2/64 - b/4) + c)) if f.is_zero: y1, y2 = [sqrt(tmp) for tmp in roots([1, e, g], multiple=True)] return [tmp - aon4 for tmp in [-y1, -y2, y1, y2]] if g.is_zero: y = [S.Zero] + roots([1, 0, e, f], multiple=True) return [tmp - aon4 for tmp in y] else: # Descartes-Euler method, see [7] sols = _roots_quartic_euler(e, f, g, aon4) if sols: return sols # Ferrari method, see [1, 2] p = -e**2/12 - g q = -e**3/108 + e*g/3 - f**2/8 TH = Rational(1, 3) def _ans(y): w = sqrt(e + 2*y) arg1 = 3*e + 2*y arg2 = 2*f/w ans = [] for s in [-1, 1]: root = sqrt(-(arg1 + s*arg2)) for t in [-1, 1]: ans.append((s*w - t*root)/2 - aon4) return ans # whether a Piecewise is returned or not # depends on knowing p, so try to put # in a simple form p = _mexpand(p) # p == 0 case y1 = e*Rational(-5, 6) - q**TH if p.is_zero: return _ans(y1) # if p != 0 then u below is not 0 root = sqrt(q**2/4 + p**3/27) r = -q/2 + root # or -q/2 - root u = r**TH # primary root of solve(x**3 - r, x) y2 = e*Rational(-5, 6) + u - p/u/3 if fuzzy_not(p.is_zero): return _ans(y2) # sort it out once they know the values of the coefficients return [Piecewise((a1, Eq(p, 0)), (a2, True)) for a1, a2 in zip(_ans(y1), _ans(y2))] def roots_binomial(f): """Returns a list of roots of a binomial polynomial. If the domain is ZZ then the roots will be sorted with negatives coming before positives. The ordering will be the same for any numerical coefficients as long as the assumptions tested are correct, otherwise the ordering will not be sorted (but will be canonical). """ n = f.degree() a, b = f.nth(n), f.nth(0) base = -cancel(b/a) alpha = root(base, n) if alpha.is_number: alpha = alpha.expand(complex=True) # define some parameters that will allow us to order the roots. # If the domain is ZZ this is guaranteed to return roots sorted # with reals before non-real roots and non-real sorted according # to real part and imaginary part, e.g. -1, 1, -1 + I, 2 - I neg = base.is_negative even = n % 2 == 0 if neg: if even == True and (base + 1).is_positive: big = True else: big = False # get the indices in the right order so the computed # roots will be sorted when the domain is ZZ ks = [] imax = n//2 if even: ks.append(imax) imax -= 1 if not neg: ks.append(0) for i in range(imax, 0, -1): if neg: ks.extend([i, -i]) else: ks.extend([-i, i]) if neg: ks.append(0) if big: for i in range(0, len(ks), 2): pair = ks[i: i + 2] pair = list(reversed(pair)) # compute the roots roots, d = [], 2*I*pi/n for k in ks: zeta = exp(k*d).expand(complex=True) roots.append((alpha*zeta).expand(power_base=False)) return roots def _inv_totient_estimate(m): """ Find ``(L, U)`` such that ``L <= phi^-1(m) <= U``. Examples ======== >>> from sympy.polys.polyroots import _inv_totient_estimate >>> _inv_totient_estimate(192) (192, 840) >>> _inv_totient_estimate(400) (400, 1750) """ primes = [ d + 1 for d in divisors(m) if isprime(d + 1) ] a, b = 1, 1 for p in primes: a *= p b *= p - 1 L = m U = int(math.ceil(m*(float(a)/b))) P = p = 2 primes = [] while P <= U: p = nextprime(p) primes.append(p) P *= p P //= p b = 1 for p in primes[:-1]: b *= p - 1 U = int(math.ceil(m*(float(P)/b))) return L, U def roots_cyclotomic(f, factor=False): """Compute roots of cyclotomic polynomials. """ L, U = _inv_totient_estimate(f.degree()) for n in range(L, U + 1): g = cyclotomic_poly(n, f.gen, polys=True) if f.expr == g.expr: break else: # pragma: no cover raise RuntimeError("failed to find index of a cyclotomic polynomial") roots = [] if not factor: # get the indices in the right order so the computed # roots will be sorted h = n//2 ks = [i for i in range(1, n + 1) if igcd(i, n) == 1] ks.sort(key=lambda x: (x, -1) if x <= h else (abs(x - n), 1)) d = 2*I*pi/n for k in reversed(ks): roots.append(exp(k*d).expand(complex=True)) else: g = Poly(f, extension=root(-1, n)) for h, _ in ordered(g.factor_list()[1]): roots.append(-h.TC()) return roots def roots_quintic(f): """ Calculate exact roots of a solvable irreducible quintic with rational coefficients. Return an empty list if the quintic is reducible or not solvable. """ result = [] coeff_5, coeff_4, p_, q_, r_, s_ = f.all_coeffs() if not all(coeff.is_Rational for coeff in (coeff_5, coeff_4, p_, q_, r_, s_)): return result if coeff_5 != 1: f = Poly(f / coeff_5) _, coeff_4, p_, q_, r_, s_ = f.all_coeffs() # Cancel coeff_4 to form x^5 + px^3 + qx^2 + rx + s if coeff_4: p = p_ - 2*coeff_4*coeff_4/5 q = q_ - 3*coeff_4*p_/5 + 4*coeff_4**3/25 r = r_ - 2*coeff_4*q_/5 + 3*coeff_4**2*p_/25 - 3*coeff_4**4/125 s = s_ - coeff_4*r_/5 + coeff_4**2*q_/25 - coeff_4**3*p_/125 + 4*coeff_4**5/3125 x = f.gen f = Poly(x**5 + p*x**3 + q*x**2 + r*x + s) else: p, q, r, s = p_, q_, r_, s_ quintic = PolyQuintic(f) # Eqn standardized. Algo for solving starts here if not f.is_irreducible: return result f20 = quintic.f20 # Check if f20 has linear factors over domain Z if f20.is_irreducible: return result # Now, we know that f is solvable for _factor in f20.factor_list()[1]: if _factor[0].is_linear: theta = _factor[0].root(0) break d = discriminant(f) delta = sqrt(d) # zeta = a fifth root of unity zeta1, zeta2, zeta3, zeta4 = quintic.zeta T = quintic.T(theta, d) tol = S(1e-10) alpha = T[1] + T[2]*delta alpha_bar = T[1] - T[2]*delta beta = T[3] + T[4]*delta beta_bar = T[3] - T[4]*delta disc = alpha**2 - 4*beta disc_bar = alpha_bar**2 - 4*beta_bar l0 = quintic.l0(theta) Stwo = S(2) l1 = _quintic_simplify((-alpha + sqrt(disc)) / Stwo) l4 = _quintic_simplify((-alpha - sqrt(disc)) / Stwo) l2 = _quintic_simplify((-alpha_bar + sqrt(disc_bar)) / Stwo) l3 = _quintic_simplify((-alpha_bar - sqrt(disc_bar)) / Stwo) order = quintic.order(theta, d) test = (order*delta.n()) - ( (l1.n() - l4.n())*(l2.n() - l3.n()) ) # Comparing floats if not comp(test, 0, tol): l2, l3 = l3, l2 # Now we have correct order of l's R1 = l0 + l1*zeta1 + l2*zeta2 + l3*zeta3 + l4*zeta4 R2 = l0 + l3*zeta1 + l1*zeta2 + l4*zeta3 + l2*zeta4 R3 = l0 + l2*zeta1 + l4*zeta2 + l1*zeta3 + l3*zeta4 R4 = l0 + l4*zeta1 + l3*zeta2 + l2*zeta3 + l1*zeta4 Res = [None, [None]*5, [None]*5, [None]*5, [None]*5] Res_n = [None, [None]*5, [None]*5, [None]*5, [None]*5] # Simplifying improves performance a lot for exact expressions R1 = _quintic_simplify(R1) R2 = _quintic_simplify(R2) R3 = _quintic_simplify(R3) R4 = _quintic_simplify(R4) # hard-coded results for [factor(i) for i in _vsolve(x**5 - a - I*b, x)] x0 = z**(S(1)/5) x1 = sqrt(2) x2 = sqrt(5) x3 = sqrt(5 - x2) x4 = I*x2 x5 = x4 + I x6 = I*x0/4 x7 = x1*sqrt(x2 + 5) sol = [x0, -x6*(x1*x3 - x5), x6*(x1*x3 + x5), -x6*(x4 + x7 - I), x6*(-x4 + x7 + I)] R1 = R1.as_real_imag() R2 = R2.as_real_imag() R3 = R3.as_real_imag() R4 = R4.as_real_imag() for i, s in enumerate(sol): Res[1][i] = _quintic_simplify(s.xreplace({z: R1[0] + I*R1[1]})) Res[2][i] = _quintic_simplify(s.xreplace({z: R2[0] + I*R2[1]})) Res[3][i] = _quintic_simplify(s.xreplace({z: R3[0] + I*R3[1]})) Res[4][i] = _quintic_simplify(s.xreplace({z: R4[0] + I*R4[1]})) for i in range(1, 5): for j in range(5): Res_n[i][j] = Res[i][j].n() Res[i][j] = _quintic_simplify(Res[i][j]) r1 = Res[1][0] r1_n = Res_n[1][0] for i in range(5): if comp(im(r1_n*Res_n[4][i]), 0, tol): r4 = Res[4][i] break # Now we have various Res values. Each will be a list of five # values. We have to pick one r value from those five for each Res u, v = quintic.uv(theta, d) testplus = (u + v*delta*sqrt(5)).n() testminus = (u - v*delta*sqrt(5)).n() # Evaluated numbers suffixed with _n # We will use evaluated numbers for calculation. Much faster. r4_n = r4.n() r2 = r3 = None for i in range(5): r2temp_n = Res_n[2][i] for j in range(5): # Again storing away the exact number and using # evaluated numbers in computations r3temp_n = Res_n[3][j] if (comp((r1_n*r2temp_n**2 + r4_n*r3temp_n**2 - testplus).n(), 0, tol) and comp((r3temp_n*r1_n**2 + r2temp_n*r4_n**2 - testminus).n(), 0, tol)): r2 = Res[2][i] r3 = Res[3][j] break if r2 is not None: break else: return [] # fall back to normal solve # Now, we have r's so we can get roots x1 = (r1 + r2 + r3 + r4)/5 x2 = (r1*zeta4 + r2*zeta3 + r3*zeta2 + r4*zeta1)/5 x3 = (r1*zeta3 + r2*zeta1 + r3*zeta4 + r4*zeta2)/5 x4 = (r1*zeta2 + r2*zeta4 + r3*zeta1 + r4*zeta3)/5 x5 = (r1*zeta1 + r2*zeta2 + r3*zeta3 + r4*zeta4)/5 result = [x1, x2, x3, x4, x5] # Now check if solutions are distinct saw = set() for r in result: r = r.n(2) if r in saw: # Roots were identical. Abort, return [] # and fall back to usual solve return [] saw.add(r) # Restore to original equation where coeff_4 is nonzero if coeff_4: result = [x - coeff_4 / 5 for x in result] return result def _quintic_simplify(expr): from sympy.simplify.simplify import powsimp expr = powsimp(expr) expr = cancel(expr) return together(expr) def _integer_basis(poly): """Compute coefficient basis for a polynomial over integers. Returns the integer ``div`` such that substituting ``x = div*y`` ``p(x) = m*q(y)`` where the coefficients of ``q`` are smaller than those of ``p``. For example ``x**5 + 512*x + 1024 = 0`` with ``div = 4`` becomes ``y**5 + 2*y + 1 = 0`` Returns the integer ``div`` or ``None`` if there is no possible scaling. Examples ======== >>> from sympy.polys import Poly >>> from sympy.abc import x >>> from sympy.polys.polyroots import _integer_basis >>> p = Poly(x**5 + 512*x + 1024, x, domain='ZZ') >>> _integer_basis(p) 4 """ monoms, coeffs = list(zip(*poly.terms())) monoms, = list(zip(*monoms)) coeffs = list(map(abs, coeffs)) if coeffs[0] < coeffs[-1]: coeffs = list(reversed(coeffs)) n = monoms[0] monoms = [n - i for i in reversed(monoms)] else: return None monoms = monoms[:-1] coeffs = coeffs[:-1] # Special case for two-term polynominals if len(monoms) == 1: r = Pow(coeffs[0], S.One/monoms[0]) if r.is_Integer: return int(r) else: return None divs = reversed(divisors(gcd_list(coeffs))[1:]) try: div = next(divs) except StopIteration: return None while True: for monom, coeff in zip(monoms, coeffs): if coeff % div**monom != 0: try: div = next(divs) except StopIteration: return None else: break else: return div def preprocess_roots(poly): """Try to get rid of symbolic coefficients from ``poly``. """ coeff = S.One poly_func = poly.func try: _, poly = poly.clear_denoms(convert=True) except DomainError: return coeff, poly poly = poly.primitive()[1] poly = poly.retract() # TODO: This is fragile. Figure out how to make this independent of construct_domain(). if poly.get_domain().is_Poly and all(c.is_term for c in poly.rep.coeffs()): poly = poly.inject() strips = list(zip(*poly.monoms())) gens = list(poly.gens[1:]) base, strips = strips[0], strips[1:] for gen, strip in zip(list(gens), strips): reverse = False if strip[0] < strip[-1]: strip = reversed(strip) reverse = True ratio = None for a, b in zip(base, strip): if not a and not b: continue elif not a or not b: break elif b % a != 0: break else: _ratio = b // a if ratio is None: ratio = _ratio elif ratio != _ratio: break else: if reverse: ratio = -ratio poly = poly.eval(gen, 1) coeff *= gen**(-ratio) gens.remove(gen) if gens: poly = poly.eject(*gens) if poly.is_univariate and poly.get_domain().is_ZZ: basis = _integer_basis(poly) if basis is not None: n = poly.degree() def func(k, coeff): return coeff//basis**(n - k[0]) poly = poly.termwise(func) coeff *= basis if not isinstance(poly, poly_func): poly = poly_func(poly) return coeff, poly @public def roots(f, *gens, auto=True, cubics=True, trig=False, quartics=True, quintics=False, multiple=False, filter=None, predicate=None, strict=False, **flags): """ Computes symbolic roots of a univariate polynomial. Given a univariate polynomial f with symbolic coefficients (or a list of the polynomial's coefficients), returns a dictionary with its roots and their multiplicities. Only roots expressible via radicals will be returned. To get a complete set of roots use RootOf class or numerical methods instead. By default cubic and quartic formulas are used in the algorithm. To disable them because of unreadable output set ``cubics=False`` or ``quartics=False`` respectively. If cubic roots are real but are expressed in terms of complex numbers (casus irreducibilis [1]) the ``trig`` flag can be set to True to have the solutions returned in terms of cosine and inverse cosine functions. To get roots from a specific domain set the ``filter`` flag with one of the following specifiers: Z, Q, R, I, C. By default all roots are returned (this is equivalent to setting ``filter='C'``). By default a dictionary is returned giving a compact result in case of multiple roots. However to get a list containing all those roots set the ``multiple`` flag to True; the list will have identical roots appearing next to each other in the result. (For a given Poly, the all_roots method will give the roots in sorted numerical order.) If the ``strict`` flag is True, ``UnsolvableFactorError`` will be raised if the roots found are known to be incomplete (because some roots are not expressible in radicals). Examples ======== >>> from sympy import Poly, roots, degree >>> from sympy.abc import x, y >>> roots(x**2 - 1, x) {-1: 1, 1: 1} >>> p = Poly(x**2-1, x) >>> roots(p) {-1: 1, 1: 1} >>> p = Poly(x**2-y, x, y) >>> roots(Poly(p, x)) {-sqrt(y): 1, sqrt(y): 1} >>> roots(x**2 - y, x) {-sqrt(y): 1, sqrt(y): 1} >>> roots([1, 0, -1]) {-1: 1, 1: 1} ``roots`` will only return roots expressible in radicals. If the given polynomial has some or all of its roots inexpressible in radicals, the result of ``roots`` will be incomplete or empty respectively. Example where result is incomplete: >>> roots((x-1)*(x**5-x+1), x) {1: 1} In this case, the polynomial has an unsolvable quintic factor whose roots cannot be expressed by radicals. The polynomial has a rational root (due to the factor `(x-1)`), which is returned since ``roots`` always finds all rational roots. Example where result is empty: >>> roots(x**7-3*x**2+1, x) {} Here, the polynomial has no roots expressible in radicals, so ``roots`` returns an empty dictionary. The result produced by ``roots`` is complete if and only if the sum of the multiplicity of each root is equal to the degree of the polynomial. If strict=True, UnsolvableFactorError will be raised if the result is incomplete. The result can be be checked for completeness as follows: >>> f = x**3-2*x**2+1 >>> sum(roots(f, x).values()) == degree(f, x) True >>> f = (x-1)*(x**5-x+1) >>> sum(roots(f, x).values()) == degree(f, x) False References ========== .. [1] https://en.wikipedia.org/wiki/Cubic_function#Trigonometric_.28and_hyperbolic.29_method """ from sympy.polys.polytools import to_rational_coeffs flags = dict(flags) if isinstance(f, list): if gens: raise ValueError('redundant generators given') x = Dummy('x') poly, i = {}, len(f) - 1 for coeff in f: poly[i], i = sympify(coeff), i - 1 f = Poly(poly, x, field=True) else: try: F = Poly(f, *gens, **flags) if not isinstance(f, Poly) and not F.gen.is_Symbol: raise PolynomialError("generator must be a Symbol") f = F except GeneratorsNeeded: if multiple: return [] else: return {} else: n = f.degree() if f.length() == 2 and n > 2: # check for foo**n in constant if dep is c*gen**m con, dep = f.as_expr().as_independent(*f.gens) fcon = -(-con).factor() if fcon != con: con = fcon bases = [] for i in Mul.make_args(con): if i.is_Pow: b, e = i.as_base_exp() if e.is_Integer and b.is_Add: bases.append((b, Dummy(positive=True))) if bases: rv = roots(Poly((dep + con).xreplace(dict(bases)), *f.gens), *F.gens, auto=auto, cubics=cubics, trig=trig, quartics=quartics, quintics=quintics, multiple=multiple, filter=filter, predicate=predicate, **flags) return {factor_terms(k.xreplace( {v: k for k, v in bases}) ): v for k, v in rv.items()} if f.is_multivariate: raise PolynomialError('multivariate polynomials are not supported') def _update_dict(result, zeros, currentroot, k): if currentroot == S.Zero: if S.Zero in zeros: zeros[S.Zero] += k else: zeros[S.Zero] = k if currentroot in result: result[currentroot] += k else: result[currentroot] = k def _try_decompose(f): """Find roots using functional decomposition. """ factors, roots = f.decompose(), [] for currentroot in _try_heuristics(factors[0]): roots.append(currentroot) for currentfactor in factors[1:]: previous, roots = list(roots), [] for currentroot in previous: g = currentfactor - Poly(currentroot, f.gen) for currentroot in _try_heuristics(g): roots.append(currentroot) return roots def _try_heuristics(f): """Find roots using formulas and some tricks. """ if f.is_ground: return [] if f.is_monomial: return [S.Zero]*f.degree() if f.length() == 2: if f.degree() == 1: return list(map(cancel, roots_linear(f))) else: return roots_binomial(f) result = [] for i in [-1, 1]: if not f.eval(i): f = f.quo(Poly(f.gen - i, f.gen)) result.append(i) break n = f.degree() if n == 1: result += list(map(cancel, roots_linear(f))) elif n == 2: result += list(map(cancel, roots_quadratic(f))) elif f.is_cyclotomic: result += roots_cyclotomic(f) elif n == 3 and cubics: result += roots_cubic(f, trig=trig) elif n == 4 and quartics: result += roots_quartic(f) elif n == 5 and quintics: result += roots_quintic(f) return result # Convert the generators to symbols dumgens = symbols('x:%d' % len(f.gens), cls=Dummy) f = f.per(f.rep, dumgens) (k,), f = f.terms_gcd() if not k: zeros = {} else: zeros = {S.Zero: k} coeff, f = preprocess_roots(f) if auto and f.get_domain().is_Ring: f = f.to_field() # Use EX instead of ZZ_I or QQ_I if f.get_domain().is_QQ_I: f = f.per(f.rep.convert(EX)) rescale_x = None translate_x = None result = {} if not f.is_ground: dom = f.get_domain() if not dom.is_Exact and dom.is_Numerical: for r in f.nroots(): _update_dict(result, zeros, r, 1) elif f.degree() == 1: _update_dict(result, zeros, roots_linear(f)[0], 1) elif f.length() == 2: roots_fun = roots_quadratic if f.degree() == 2 else roots_binomial for r in roots_fun(f): _update_dict(result, zeros, r, 1) else: _, factors = Poly(f.as_expr()).factor_list() if len(factors) == 1 and f.degree() == 2: for r in roots_quadratic(f): _update_dict(result, zeros, r, 1) else: if len(factors) == 1 and factors[0][1] == 1: if f.get_domain().is_EX: res = to_rational_coeffs(f) if res: if res[0] is None: translate_x, f = res[2:] else: rescale_x, f = res[1], res[-1] result = roots(f) if not result: for currentroot in _try_decompose(f): _update_dict(result, zeros, currentroot, 1) else: for r in _try_heuristics(f): _update_dict(result, zeros, r, 1) else: for currentroot in _try_decompose(f): _update_dict(result, zeros, currentroot, 1) else: for currentfactor, k in factors: for r in _try_heuristics(Poly(currentfactor, f.gen, field=True)): _update_dict(result, zeros, r, k) if coeff is not S.One: _result, result, = result, {} for currentroot, k in _result.items(): result[coeff*currentroot] = k if filter not in [None, 'C']: handlers = { 'Z': lambda r: r.is_Integer, 'Q': lambda r: r.is_Rational, 'R': lambda r: all(a.is_real for a in r.as_numer_denom()), 'I': lambda r: r.is_imaginary, } try: query = handlers[filter] except KeyError: raise ValueError("Invalid filter: %s" % filter) for zero in dict(result).keys(): if not query(zero): del result[zero] if predicate is not None: for zero in dict(result).keys(): if not predicate(zero): del result[zero] if rescale_x: result1 = {} for k, v in result.items(): result1[k*rescale_x] = v result = result1 if translate_x: result1 = {} for k, v in result.items(): result1[k + translate_x] = v result = result1 # adding zero roots after non-trivial roots have been translated result.update(zeros) if strict and sum(result.values()) < f.degree(): raise UnsolvableFactorError(filldedent(''' Strict mode: some factors cannot be solved in radicals, so a complete list of solutions cannot be returned. Call roots with strict=False to get solutions expressible in radicals (if there are any). ''')) if not multiple: return result else: zeros = [] for zero in ordered(result): zeros.extend([zero]*result[zero]) return zeros def root_factors(f, *gens, filter=None, **args): """ Returns all factors of a univariate polynomial. Examples ======== >>> from sympy.abc import x, y >>> from sympy.polys.polyroots import root_factors >>> root_factors(x**2 - y, x) [x - sqrt(y), x + sqrt(y)] """ args = dict(args) F = Poly(f, *gens, **args) if not F.is_Poly: return [f] if F.is_multivariate: raise ValueError('multivariate polynomials are not supported') x = F.gens[0] zeros = roots(F, filter=filter) if not zeros: factors = [F] else: factors, N = [], 0 for r, n in ordered(zeros.items()): factors, N = factors + [Poly(x - r, x)]*n, N + n if N < F.degree(): G = reduce(lambda p, q: p*q, factors) factors.append(F.quo(G)) if not isinstance(f, Poly): factors = [ f.as_expr() for f in factors ] return factors
f219e58233f55d8708c9b8276d9b5e25d6e9df48438187eb8574bb7107dffda7
"""Sparse polynomial rings. """ from typing import Any, Dict as tDict from operator import add, mul, lt, le, gt, ge from functools import reduce from types import GeneratorType from sympy.core.expr import Expr from sympy.core.numbers import igcd, oo from sympy.core.symbol import Symbol, symbols as _symbols from sympy.core.sympify import CantSympify, sympify from sympy.ntheory.multinomial import multinomial_coefficients from sympy.polys.compatibility import IPolys from sympy.polys.constructor import construct_domain from sympy.polys.densebasic import dmp_to_dict, dmp_from_dict from sympy.polys.domains.domainelement import DomainElement from sympy.polys.domains.polynomialring import PolynomialRing from sympy.polys.heuristicgcd import heugcd from sympy.polys.monomials import MonomialOps from sympy.polys.orderings import lex from sympy.polys.polyerrors import ( CoercionFailed, GeneratorsError, ExactQuotientFailed, MultivariatePolynomialError) from sympy.polys.polyoptions import (Domain as DomainOpt, Order as OrderOpt, build_options) from sympy.polys.polyutils import (expr_from_dict, _dict_reorder, _parallel_dict_from_expr) from sympy.printing.defaults import DefaultPrinting from sympy.utilities import public from sympy.utilities.iterables import is_sequence from sympy.utilities.magic import pollute @public def ring(symbols, domain, order=lex): """Construct a polynomial ring returning ``(ring, x_1, ..., x_n)``. Parameters ========== symbols : str Symbol/Expr or sequence of str, Symbol/Expr (non-empty) domain : :class:`~.Domain` or coercible order : :class:`~.MonomialOrder` or coercible, optional, defaults to ``lex`` Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> from sympy.polys.orderings import lex >>> R, x, y, z = ring("x,y,z", ZZ, lex) >>> R Polynomial ring in x, y, z over ZZ with lex order >>> x + y + z x + y + z >>> type(_) <class 'sympy.polys.rings.PolyElement'> """ _ring = PolyRing(symbols, domain, order) return (_ring,) + _ring.gens @public def xring(symbols, domain, order=lex): """Construct a polynomial ring returning ``(ring, (x_1, ..., x_n))``. Parameters ========== symbols : str Symbol/Expr or sequence of str, Symbol/Expr (non-empty) domain : :class:`~.Domain` or coercible order : :class:`~.MonomialOrder` or coercible, optional, defaults to ``lex`` Examples ======== >>> from sympy.polys.rings import xring >>> from sympy.polys.domains import ZZ >>> from sympy.polys.orderings import lex >>> R, (x, y, z) = xring("x,y,z", ZZ, lex) >>> R Polynomial ring in x, y, z over ZZ with lex order >>> x + y + z x + y + z >>> type(_) <class 'sympy.polys.rings.PolyElement'> """ _ring = PolyRing(symbols, domain, order) return (_ring, _ring.gens) @public def vring(symbols, domain, order=lex): """Construct a polynomial ring and inject ``x_1, ..., x_n`` into the global namespace. Parameters ========== symbols : str Symbol/Expr or sequence of str, Symbol/Expr (non-empty) domain : :class:`~.Domain` or coercible order : :class:`~.MonomialOrder` or coercible, optional, defaults to ``lex`` Examples ======== >>> from sympy.polys.rings import vring >>> from sympy.polys.domains import ZZ >>> from sympy.polys.orderings import lex >>> vring("x,y,z", ZZ, lex) Polynomial ring in x, y, z over ZZ with lex order >>> x + y + z # noqa: x + y + z >>> type(_) <class 'sympy.polys.rings.PolyElement'> """ _ring = PolyRing(symbols, domain, order) pollute([ sym.name for sym in _ring.symbols ], _ring.gens) return _ring @public def sring(exprs, *symbols, **options): """Construct a ring deriving generators and domain from options and input expressions. Parameters ========== exprs : :class:`~.Expr` or sequence of :class:`~.Expr` (sympifiable) symbols : sequence of :class:`~.Symbol`/:class:`~.Expr` options : keyword arguments understood by :class:`~.Options` Examples ======== >>> from sympy import sring, symbols >>> x, y, z = symbols("x,y,z") >>> R, f = sring(x + 2*y + 3*z) >>> R Polynomial ring in x, y, z over ZZ with lex order >>> f x + 2*y + 3*z >>> type(_) <class 'sympy.polys.rings.PolyElement'> """ single = False if not is_sequence(exprs): exprs, single = [exprs], True exprs = list(map(sympify, exprs)) opt = build_options(symbols, options) # TODO: rewrite this so that it doesn't use expand() (see poly()). reps, opt = _parallel_dict_from_expr(exprs, opt) if opt.domain is None: coeffs = sum([ list(rep.values()) for rep in reps ], []) opt.domain, coeffs_dom = construct_domain(coeffs, opt=opt) coeff_map = dict(zip(coeffs, coeffs_dom)) reps = [{m: coeff_map[c] for m, c in rep.items()} for rep in reps] _ring = PolyRing(opt.gens, opt.domain, opt.order) polys = list(map(_ring.from_dict, reps)) if single: return (_ring, polys[0]) else: return (_ring, polys) def _parse_symbols(symbols): if isinstance(symbols, str): return _symbols(symbols, seq=True) if symbols else () elif isinstance(symbols, Expr): return (symbols,) elif is_sequence(symbols): if all(isinstance(s, str) for s in symbols): return _symbols(symbols) elif all(isinstance(s, Expr) for s in symbols): return symbols raise GeneratorsError("expected a string, Symbol or expression or a non-empty sequence of strings, Symbols or expressions") _ring_cache = {} # type: tDict[Any, Any] class PolyRing(DefaultPrinting, IPolys): """Multivariate distributed polynomial ring. """ def __new__(cls, symbols, domain, order=lex): symbols = tuple(_parse_symbols(symbols)) ngens = len(symbols) domain = DomainOpt.preprocess(domain) order = OrderOpt.preprocess(order) _hash_tuple = (cls.__name__, symbols, ngens, domain, order) obj = _ring_cache.get(_hash_tuple) if obj is None: if domain.is_Composite and set(symbols) & set(domain.symbols): raise GeneratorsError("polynomial ring and it's ground domain share generators") obj = object.__new__(cls) obj._hash_tuple = _hash_tuple obj._hash = hash(_hash_tuple) obj.dtype = type("PolyElement", (PolyElement,), {"ring": obj}) obj.symbols = symbols obj.ngens = ngens obj.domain = domain obj.order = order obj.zero_monom = (0,)*ngens obj.gens = obj._gens() obj._gens_set = set(obj.gens) obj._one = [(obj.zero_monom, domain.one)] if ngens: # These expect monomials in at least one variable codegen = MonomialOps(ngens) obj.monomial_mul = codegen.mul() obj.monomial_pow = codegen.pow() obj.monomial_mulpow = codegen.mulpow() obj.monomial_ldiv = codegen.ldiv() obj.monomial_div = codegen.div() obj.monomial_lcm = codegen.lcm() obj.monomial_gcd = codegen.gcd() else: monunit = lambda a, b: () obj.monomial_mul = monunit obj.monomial_pow = monunit obj.monomial_mulpow = lambda a, b, c: () obj.monomial_ldiv = monunit obj.monomial_div = monunit obj.monomial_lcm = monunit obj.monomial_gcd = monunit if order is lex: obj.leading_expv = max else: obj.leading_expv = lambda f: max(f, key=order) for symbol, generator in zip(obj.symbols, obj.gens): if isinstance(symbol, Symbol): name = symbol.name if not hasattr(obj, name): setattr(obj, name, generator) _ring_cache[_hash_tuple] = obj return obj def _gens(self): """Return a list of polynomial generators. """ one = self.domain.one _gens = [] for i in range(self.ngens): expv = self.monomial_basis(i) poly = self.zero poly[expv] = one _gens.append(poly) return tuple(_gens) def __getnewargs__(self): return (self.symbols, self.domain, self.order) def __getstate__(self): state = self.__dict__.copy() del state["leading_expv"] for key, value in state.items(): if key.startswith("monomial_"): del state[key] return state def __hash__(self): return self._hash def __eq__(self, other): return isinstance(other, PolyRing) and \ (self.symbols, self.domain, self.ngens, self.order) == \ (other.symbols, other.domain, other.ngens, other.order) def __ne__(self, other): return not self == other def clone(self, symbols=None, domain=None, order=None): return self.__class__(symbols or self.symbols, domain or self.domain, order or self.order) def monomial_basis(self, i): """Return the ith-basis element. """ basis = [0]*self.ngens basis[i] = 1 return tuple(basis) @property def zero(self): return self.dtype() @property def one(self): return self.dtype(self._one) def domain_new(self, element, orig_domain=None): return self.domain.convert(element, orig_domain) def ground_new(self, coeff): return self.term_new(self.zero_monom, coeff) def term_new(self, monom, coeff): coeff = self.domain_new(coeff) poly = self.zero if coeff: poly[monom] = coeff return poly def ring_new(self, element): if isinstance(element, PolyElement): if self == element.ring: return element elif isinstance(self.domain, PolynomialRing) and self.domain.ring == element.ring: return self.ground_new(element) else: raise NotImplementedError("conversion") elif isinstance(element, str): raise NotImplementedError("parsing") elif isinstance(element, dict): return self.from_dict(element) elif isinstance(element, list): try: return self.from_terms(element) except ValueError: return self.from_list(element) elif isinstance(element, Expr): return self.from_expr(element) else: return self.ground_new(element) __call__ = ring_new def from_dict(self, element, orig_domain=None): domain_new = self.domain_new poly = self.zero for monom, coeff in element.items(): coeff = domain_new(coeff, orig_domain) if coeff: poly[monom] = coeff return poly def from_terms(self, element, orig_domain=None): return self.from_dict(dict(element), orig_domain) def from_list(self, element): return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain)) def _rebuild_expr(self, expr, mapping): domain = self.domain def _rebuild(expr): generator = mapping.get(expr) if generator is not None: return generator elif expr.is_Add: return reduce(add, list(map(_rebuild, expr.args))) elif expr.is_Mul: return reduce(mul, list(map(_rebuild, expr.args))) else: # XXX: Use as_base_exp() to handle Pow(x, n) and also exp(n) # XXX: E can be a generator e.g. sring([exp(2)]) -> ZZ[E] base, exp = expr.as_base_exp() if exp.is_Integer and exp > 1: return _rebuild(base)**int(exp) else: return self.ground_new(domain.convert(expr)) return _rebuild(sympify(expr)) def from_expr(self, expr): mapping = dict(list(zip(self.symbols, self.gens))) try: poly = self._rebuild_expr(expr, mapping) except CoercionFailed: raise ValueError("expected an expression convertible to a polynomial in %s, got %s" % (self, expr)) else: return self.ring_new(poly) def index(self, gen): """Compute index of ``gen`` in ``self.gens``. """ if gen is None: if self.ngens: i = 0 else: i = -1 # indicate impossible choice elif isinstance(gen, int): i = gen if 0 <= i and i < self.ngens: pass elif -self.ngens <= i and i <= -1: i = -i - 1 else: raise ValueError("invalid generator index: %s" % gen) elif isinstance(gen, self.dtype): try: i = self.gens.index(gen) except ValueError: raise ValueError("invalid generator: %s" % gen) elif isinstance(gen, str): try: i = self.symbols.index(gen) except ValueError: raise ValueError("invalid generator: %s" % gen) else: raise ValueError("expected a polynomial generator, an integer, a string or None, got %s" % gen) return i def drop(self, *gens): """Remove specified generators from this ring. """ indices = set(map(self.index, gens)) symbols = [ s for i, s in enumerate(self.symbols) if i not in indices ] if not symbols: return self.domain else: return self.clone(symbols=symbols) def __getitem__(self, key): symbols = self.symbols[key] if not symbols: return self.domain else: return self.clone(symbols=symbols) def to_ground(self): # TODO: should AlgebraicField be a Composite domain? if self.domain.is_Composite or hasattr(self.domain, 'domain'): return self.clone(domain=self.domain.domain) else: raise ValueError("%s is not a composite domain" % self.domain) def to_domain(self): return PolynomialRing(self) def to_field(self): from sympy.polys.fields import FracField return FracField(self.symbols, self.domain, self.order) @property def is_univariate(self): return len(self.gens) == 1 @property def is_multivariate(self): return len(self.gens) > 1 def add(self, *objs): """ Add a sequence of polynomials or containers of polynomials. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> R, x = ring("x", ZZ) >>> R.add([ x**2 + 2*i + 3 for i in range(4) ]) 4*x**2 + 24 >>> _.factor_list() (4, [(x**2 + 6, 1)]) """ p = self.zero for obj in objs: if is_sequence(obj, include=GeneratorType): p += self.add(*obj) else: p += obj return p def mul(self, *objs): """ Multiply a sequence of polynomials or containers of polynomials. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> R, x = ring("x", ZZ) >>> R.mul([ x**2 + 2*i + 3 for i in range(4) ]) x**8 + 24*x**6 + 206*x**4 + 744*x**2 + 945 >>> _.factor_list() (1, [(x**2 + 3, 1), (x**2 + 5, 1), (x**2 + 7, 1), (x**2 + 9, 1)]) """ p = self.one for obj in objs: if is_sequence(obj, include=GeneratorType): p *= self.mul(*obj) else: p *= obj return p def drop_to_ground(self, *gens): r""" Remove specified generators from the ring and inject them into its domain. """ indices = set(map(self.index, gens)) symbols = [s for i, s in enumerate(self.symbols) if i not in indices] gens = [gen for i, gen in enumerate(self.gens) if i not in indices] if not symbols: return self else: return self.clone(symbols=symbols, domain=self.drop(*gens)) def compose(self, other): """Add the generators of ``other`` to ``self``""" if self != other: syms = set(self.symbols).union(set(other.symbols)) return self.clone(symbols=list(syms)) else: return self def add_gens(self, symbols): """Add the elements of ``symbols`` as generators to ``self``""" syms = set(self.symbols).union(set(symbols)) return self.clone(symbols=list(syms)) class PolyElement(DomainElement, DefaultPrinting, CantSympify, dict): """Element of multivariate distributed polynomial ring. """ def new(self, init): return self.__class__(init) def parent(self): return self.ring.to_domain() def __getnewargs__(self): return (self.ring, list(self.iterterms())) _hash = None def __hash__(self): # XXX: This computes a hash of a dictionary, but currently we don't # protect dictionary from being changed so any use site modifications # will make hashing go wrong. Use this feature with caution until we # figure out how to make a safe API without compromising speed of this # low-level class. _hash = self._hash if _hash is None: self._hash = _hash = hash((self.ring, frozenset(self.items()))) return _hash def copy(self): """Return a copy of polynomial self. Polynomials are mutable; if one is interested in preserving a polynomial, and one plans to use inplace operations, one can copy the polynomial. This method makes a shallow copy. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> R, x, y = ring('x, y', ZZ) >>> p = (x + y)**2 >>> p1 = p.copy() >>> p2 = p >>> p[R.zero_monom] = 3 >>> p x**2 + 2*x*y + y**2 + 3 >>> p1 x**2 + 2*x*y + y**2 >>> p2 x**2 + 2*x*y + y**2 + 3 """ return self.new(self) def set_ring(self, new_ring): if self.ring == new_ring: return self elif self.ring.symbols != new_ring.symbols: terms = list(zip(*_dict_reorder(self, self.ring.symbols, new_ring.symbols))) return new_ring.from_terms(terms, self.ring.domain) else: return new_ring.from_dict(self, self.ring.domain) def as_expr(self, *symbols): if symbols and len(symbols) != self.ring.ngens: raise ValueError("not enough symbols, expected %s got %s" % (self.ring.ngens, len(symbols))) else: symbols = self.ring.symbols return expr_from_dict(self.as_expr_dict(), *symbols) def as_expr_dict(self): to_sympy = self.ring.domain.to_sympy return {monom: to_sympy(coeff) for monom, coeff in self.iterterms()} def clear_denoms(self): domain = self.ring.domain if not domain.is_Field or not domain.has_assoc_Ring: return domain.one, self ground_ring = domain.get_ring() common = ground_ring.one lcm = ground_ring.lcm denom = domain.denom for coeff in self.values(): common = lcm(common, denom(coeff)) poly = self.new([ (k, v*common) for k, v in self.items() ]) return common, poly def strip_zero(self): """Eliminate monomials with zero coefficient. """ for k, v in list(self.items()): if not v: del self[k] def __eq__(p1, p2): """Equality test for polynomials. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', ZZ) >>> p1 = (x + y)**2 + (x - y)**2 >>> p1 == 4*x*y False >>> p1 == 2*(x**2 + y**2) True """ if not p2: return not p1 elif isinstance(p2, PolyElement) and p2.ring == p1.ring: return dict.__eq__(p1, p2) elif len(p1) > 1: return False else: return p1.get(p1.ring.zero_monom) == p2 def __ne__(p1, p2): return not p1 == p2 def almosteq(p1, p2, tolerance=None): """Approximate equality test for polynomials. """ ring = p1.ring if isinstance(p2, ring.dtype): if set(p1.keys()) != set(p2.keys()): return False almosteq = ring.domain.almosteq for k in p1.keys(): if not almosteq(p1[k], p2[k], tolerance): return False return True elif len(p1) > 1: return False else: try: p2 = ring.domain.convert(p2) except CoercionFailed: return False else: return ring.domain.almosteq(p1.const(), p2, tolerance) def sort_key(self): return (len(self), self.terms()) def _cmp(p1, p2, op): if isinstance(p2, p1.ring.dtype): return op(p1.sort_key(), p2.sort_key()) else: return NotImplemented def __lt__(p1, p2): return p1._cmp(p2, lt) def __le__(p1, p2): return p1._cmp(p2, le) def __gt__(p1, p2): return p1._cmp(p2, gt) def __ge__(p1, p2): return p1._cmp(p2, ge) def _drop(self, gen): ring = self.ring i = ring.index(gen) if ring.ngens == 1: return i, ring.domain else: symbols = list(ring.symbols) del symbols[i] return i, ring.clone(symbols=symbols) def drop(self, gen): i, ring = self._drop(gen) if self.ring.ngens == 1: if self.is_ground: return self.coeff(1) else: raise ValueError("Cannot drop %s" % gen) else: poly = ring.zero for k, v in self.items(): if k[i] == 0: K = list(k) del K[i] poly[tuple(K)] = v else: raise ValueError("Cannot drop %s" % gen) return poly def _drop_to_ground(self, gen): ring = self.ring i = ring.index(gen) symbols = list(ring.symbols) del symbols[i] return i, ring.clone(symbols=symbols, domain=ring[i]) def drop_to_ground(self, gen): if self.ring.ngens == 1: raise ValueError("Cannot drop only generator to ground") i, ring = self._drop_to_ground(gen) poly = ring.zero gen = ring.domain.gens[0] for monom, coeff in self.iterterms(): mon = monom[:i] + monom[i+1:] if mon not in poly: poly[mon] = (gen**monom[i]).mul_ground(coeff) else: poly[mon] += (gen**monom[i]).mul_ground(coeff) return poly def to_dense(self): return dmp_from_dict(self, self.ring.ngens-1, self.ring.domain) def to_dict(self): return dict(self) def str(self, printer, precedence, exp_pattern, mul_symbol): if not self: return printer._print(self.ring.domain.zero) prec_mul = precedence["Mul"] prec_atom = precedence["Atom"] ring = self.ring symbols = ring.symbols ngens = ring.ngens zm = ring.zero_monom sexpvs = [] for expv, coeff in self.terms(): negative = ring.domain.is_negative(coeff) sign = " - " if negative else " + " sexpvs.append(sign) if expv == zm: scoeff = printer._print(coeff) if negative and scoeff.startswith("-"): scoeff = scoeff[1:] else: if negative: coeff = -coeff if coeff != self.ring.one: scoeff = printer.parenthesize(coeff, prec_mul, strict=True) else: scoeff = '' sexpv = [] for i in range(ngens): exp = expv[i] if not exp: continue symbol = printer.parenthesize(symbols[i], prec_atom, strict=True) if exp != 1: if exp != int(exp) or exp < 0: sexp = printer.parenthesize(exp, prec_atom, strict=False) else: sexp = exp sexpv.append(exp_pattern % (symbol, sexp)) else: sexpv.append('%s' % symbol) if scoeff: sexpv = [scoeff] + sexpv sexpvs.append(mul_symbol.join(sexpv)) if sexpvs[0] in [" + ", " - "]: head = sexpvs.pop(0) if head == " - ": sexpvs.insert(0, "-") return "".join(sexpvs) @property def is_generator(self): return self in self.ring._gens_set @property def is_ground(self): return not self or (len(self) == 1 and self.ring.zero_monom in self) @property def is_monomial(self): return not self or (len(self) == 1 and self.LC == 1) @property def is_term(self): return len(self) <= 1 @property def is_negative(self): return self.ring.domain.is_negative(self.LC) @property def is_positive(self): return self.ring.domain.is_positive(self.LC) @property def is_nonnegative(self): return self.ring.domain.is_nonnegative(self.LC) @property def is_nonpositive(self): return self.ring.domain.is_nonpositive(self.LC) @property def is_zero(f): return not f @property def is_one(f): return f == f.ring.one @property def is_monic(f): return f.ring.domain.is_one(f.LC) @property def is_primitive(f): return f.ring.domain.is_one(f.content()) @property def is_linear(f): return all(sum(monom) <= 1 for monom in f.itermonoms()) @property def is_quadratic(f): return all(sum(monom) <= 2 for monom in f.itermonoms()) @property def is_squarefree(f): if not f.ring.ngens: return True return f.ring.dmp_sqf_p(f) @property def is_irreducible(f): if not f.ring.ngens: return True return f.ring.dmp_irreducible_p(f) @property def is_cyclotomic(f): if f.ring.is_univariate: return f.ring.dup_cyclotomic_p(f) else: raise MultivariatePolynomialError("cyclotomic polynomial") def __neg__(self): return self.new([ (monom, -coeff) for monom, coeff in self.iterterms() ]) def __pos__(self): return self def __add__(p1, p2): """Add two polynomials. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', ZZ) >>> (x + y)**2 + (x - y)**2 2*x**2 + 2*y**2 """ if not p2: return p1.copy() ring = p1.ring if isinstance(p2, ring.dtype): p = p1.copy() get = p.get zero = ring.domain.zero for k, v in p2.items(): v = get(k, zero) + v if v: p[k] = v else: del p[k] return p elif isinstance(p2, PolyElement): if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: pass elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: return p2.__radd__(p1) else: return NotImplemented try: cp2 = ring.domain_new(p2) except CoercionFailed: return NotImplemented else: p = p1.copy() if not cp2: return p zm = ring.zero_monom if zm not in p1.keys(): p[zm] = cp2 else: if p2 == -p[zm]: del p[zm] else: p[zm] += cp2 return p def __radd__(p1, n): p = p1.copy() if not n: return p ring = p1.ring try: n = ring.domain_new(n) except CoercionFailed: return NotImplemented else: zm = ring.zero_monom if zm not in p1.keys(): p[zm] = n else: if n == -p[zm]: del p[zm] else: p[zm] += n return p def __sub__(p1, p2): """Subtract polynomial p2 from p1. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', ZZ) >>> p1 = x + y**2 >>> p2 = x*y + y**2 >>> p1 - p2 -x*y + x """ if not p2: return p1.copy() ring = p1.ring if isinstance(p2, ring.dtype): p = p1.copy() get = p.get zero = ring.domain.zero for k, v in p2.items(): v = get(k, zero) - v if v: p[k] = v else: del p[k] return p elif isinstance(p2, PolyElement): if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: pass elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: return p2.__rsub__(p1) else: return NotImplemented try: p2 = ring.domain_new(p2) except CoercionFailed: return NotImplemented else: p = p1.copy() zm = ring.zero_monom if zm not in p1.keys(): p[zm] = -p2 else: if p2 == p[zm]: del p[zm] else: p[zm] -= p2 return p def __rsub__(p1, n): """n - p1 with n convertible to the coefficient domain. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', ZZ) >>> p = x + y >>> 4 - p -x - y + 4 """ ring = p1.ring try: n = ring.domain_new(n) except CoercionFailed: return NotImplemented else: p = ring.zero for expv in p1: p[expv] = -p1[expv] p += n return p def __mul__(p1, p2): """Multiply two polynomials. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', QQ) >>> p1 = x + y >>> p2 = x - y >>> p1*p2 x**2 - y**2 """ ring = p1.ring p = ring.zero if not p1 or not p2: return p elif isinstance(p2, ring.dtype): get = p.get zero = ring.domain.zero monomial_mul = ring.monomial_mul p2it = list(p2.items()) for exp1, v1 in p1.items(): for exp2, v2 in p2it: exp = monomial_mul(exp1, exp2) p[exp] = get(exp, zero) + v1*v2 p.strip_zero() return p elif isinstance(p2, PolyElement): if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: pass elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: return p2.__rmul__(p1) else: return NotImplemented try: p2 = ring.domain_new(p2) except CoercionFailed: return NotImplemented else: for exp1, v1 in p1.items(): v = v1*p2 if v: p[exp1] = v return p def __rmul__(p1, p2): """p2 * p1 with p2 in the coefficient domain of p1. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', ZZ) >>> p = x + y >>> 4 * p 4*x + 4*y """ p = p1.ring.zero if not p2: return p try: p2 = p.ring.domain_new(p2) except CoercionFailed: return NotImplemented else: for exp1, v1 in p1.items(): v = p2*v1 if v: p[exp1] = v return p def __pow__(self, n): """raise polynomial to power `n` Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', ZZ) >>> p = x + y**2 >>> p**3 x**3 + 3*x**2*y**2 + 3*x*y**4 + y**6 """ ring = self.ring if not n: if self: return ring.one else: raise ValueError("0**0") elif len(self) == 1: monom, coeff = list(self.items())[0] p = ring.zero if coeff == 1: p[ring.monomial_pow(monom, n)] = coeff else: p[ring.monomial_pow(monom, n)] = coeff**n return p # For ring series, we need negative and rational exponent support only # with monomials. n = int(n) if n < 0: raise ValueError("Negative exponent") elif n == 1: return self.copy() elif n == 2: return self.square() elif n == 3: return self*self.square() elif len(self) <= 5: # TODO: use an actual density measure return self._pow_multinomial(n) else: return self._pow_generic(n) def _pow_generic(self, n): p = self.ring.one c = self while True: if n & 1: p = p*c n -= 1 if not n: break c = c.square() n = n // 2 return p def _pow_multinomial(self, n): multinomials = multinomial_coefficients(len(self), n).items() monomial_mulpow = self.ring.monomial_mulpow zero_monom = self.ring.zero_monom terms = self.items() zero = self.ring.domain.zero poly = self.ring.zero for multinomial, multinomial_coeff in multinomials: product_monom = zero_monom product_coeff = multinomial_coeff for exp, (monom, coeff) in zip(multinomial, terms): if exp: product_monom = monomial_mulpow(product_monom, monom, exp) product_coeff *= coeff**exp monom = tuple(product_monom) coeff = product_coeff coeff = poly.get(monom, zero) + coeff if coeff: poly[monom] = coeff elif monom in poly: del poly[monom] return poly def square(self): """square of a polynomial Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring('x, y', ZZ) >>> p = x + y**2 >>> p.square() x**2 + 2*x*y**2 + y**4 """ ring = self.ring p = ring.zero get = p.get keys = list(self.keys()) zero = ring.domain.zero monomial_mul = ring.monomial_mul for i in range(len(keys)): k1 = keys[i] pk = self[k1] for j in range(i): k2 = keys[j] exp = monomial_mul(k1, k2) p[exp] = get(exp, zero) + pk*self[k2] p = p.imul_num(2) get = p.get for k, v in self.items(): k2 = monomial_mul(k, k) p[k2] = get(k2, zero) + v**2 p.strip_zero() return p def __divmod__(p1, p2): ring = p1.ring if not p2: raise ZeroDivisionError("polynomial division") elif isinstance(p2, ring.dtype): return p1.div(p2) elif isinstance(p2, PolyElement): if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: pass elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: return p2.__rdivmod__(p1) else: return NotImplemented try: p2 = ring.domain_new(p2) except CoercionFailed: return NotImplemented else: return (p1.quo_ground(p2), p1.rem_ground(p2)) def __rdivmod__(p1, p2): return NotImplemented def __mod__(p1, p2): ring = p1.ring if not p2: raise ZeroDivisionError("polynomial division") elif isinstance(p2, ring.dtype): return p1.rem(p2) elif isinstance(p2, PolyElement): if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: pass elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: return p2.__rmod__(p1) else: return NotImplemented try: p2 = ring.domain_new(p2) except CoercionFailed: return NotImplemented else: return p1.rem_ground(p2) def __rmod__(p1, p2): return NotImplemented def __truediv__(p1, p2): ring = p1.ring if not p2: raise ZeroDivisionError("polynomial division") elif isinstance(p2, ring.dtype): if p2.is_monomial: return p1*(p2**(-1)) else: return p1.quo(p2) elif isinstance(p2, PolyElement): if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: pass elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: return p2.__rtruediv__(p1) else: return NotImplemented try: p2 = ring.domain_new(p2) except CoercionFailed: return NotImplemented else: return p1.quo_ground(p2) def __rtruediv__(p1, p2): return NotImplemented __floordiv__ = __truediv__ __rfloordiv__ = __rtruediv__ # TODO: use // (__floordiv__) for exquo()? def _term_div(self): zm = self.ring.zero_monom domain = self.ring.domain domain_quo = domain.quo monomial_div = self.ring.monomial_div if domain.is_Field: def term_div(a_lm_a_lc, b_lm_b_lc): a_lm, a_lc = a_lm_a_lc b_lm, b_lc = b_lm_b_lc if b_lm == zm: # apparently this is a very common case monom = a_lm else: monom = monomial_div(a_lm, b_lm) if monom is not None: return monom, domain_quo(a_lc, b_lc) else: return None else: def term_div(a_lm_a_lc, b_lm_b_lc): a_lm, a_lc = a_lm_a_lc b_lm, b_lc = b_lm_b_lc if b_lm == zm: # apparently this is a very common case monom = a_lm else: monom = monomial_div(a_lm, b_lm) if not (monom is None or a_lc % b_lc): return monom, domain_quo(a_lc, b_lc) else: return None return term_div def div(self, fv): """Division algorithm, see [CLO] p64. fv array of polynomials return qv, r such that self = sum(fv[i]*qv[i]) + r All polynomials are required not to be Laurent polynomials. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring('x, y', ZZ) >>> f = x**3 >>> f0 = x - y**2 >>> f1 = x - y >>> qv, r = f.div((f0, f1)) >>> qv[0] x**2 + x*y**2 + y**4 >>> qv[1] 0 >>> r y**6 """ ring = self.ring ret_single = False if isinstance(fv, PolyElement): ret_single = True fv = [fv] if not all(fv): raise ZeroDivisionError("polynomial division") if not self: if ret_single: return ring.zero, ring.zero else: return [], ring.zero for f in fv: if f.ring != ring: raise ValueError('self and f must have the same ring') s = len(fv) qv = [ring.zero for i in range(s)] p = self.copy() r = ring.zero term_div = self._term_div() expvs = [fx.leading_expv() for fx in fv] while p: i = 0 divoccurred = 0 while i < s and divoccurred == 0: expv = p.leading_expv() term = term_div((expv, p[expv]), (expvs[i], fv[i][expvs[i]])) if term is not None: expv1, c = term qv[i] = qv[i]._iadd_monom((expv1, c)) p = p._iadd_poly_monom(fv[i], (expv1, -c)) divoccurred = 1 else: i += 1 if not divoccurred: expv = p.leading_expv() r = r._iadd_monom((expv, p[expv])) del p[expv] if expv == ring.zero_monom: r += p if ret_single: if not qv: return ring.zero, r else: return qv[0], r else: return qv, r def rem(self, G): f = self if isinstance(G, PolyElement): G = [G] if not all(G): raise ZeroDivisionError("polynomial division") ring = f.ring domain = ring.domain zero = domain.zero monomial_mul = ring.monomial_mul r = ring.zero term_div = f._term_div() ltf = f.LT f = f.copy() get = f.get while f: for g in G: tq = term_div(ltf, g.LT) if tq is not None: m, c = tq for mg, cg in g.iterterms(): m1 = monomial_mul(mg, m) c1 = get(m1, zero) - c*cg if not c1: del f[m1] else: f[m1] = c1 ltm = f.leading_expv() if ltm is not None: ltf = ltm, f[ltm] break else: ltm, ltc = ltf if ltm in r: r[ltm] += ltc else: r[ltm] = ltc del f[ltm] ltm = f.leading_expv() if ltm is not None: ltf = ltm, f[ltm] return r def quo(f, G): return f.div(G)[0] def exquo(f, G): q, r = f.div(G) if not r: return q else: raise ExactQuotientFailed(f, G) def _iadd_monom(self, mc): """add to self the monomial coeff*x0**i0*x1**i1*... unless self is a generator -- then just return the sum of the two. mc is a tuple, (monom, coeff), where monomial is (i0, i1, ...) Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring('x, y', ZZ) >>> p = x**4 + 2*y >>> m = (1, 2) >>> p1 = p._iadd_monom((m, 5)) >>> p1 x**4 + 5*x*y**2 + 2*y >>> p1 is p True >>> p = x >>> p1 = p._iadd_monom((m, 5)) >>> p1 5*x*y**2 + x >>> p1 is p False """ if self in self.ring._gens_set: cpself = self.copy() else: cpself = self expv, coeff = mc c = cpself.get(expv) if c is None: cpself[expv] = coeff else: c += coeff if c: cpself[expv] = c else: del cpself[expv] return cpself def _iadd_poly_monom(self, p2, mc): """add to self the product of (p)*(coeff*x0**i0*x1**i1*...) unless self is a generator -- then just return the sum of the two. mc is a tuple, (monom, coeff), where monomial is (i0, i1, ...) Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y, z = ring('x, y, z', ZZ) >>> p1 = x**4 + 2*y >>> p2 = y + z >>> m = (1, 2, 3) >>> p1 = p1._iadd_poly_monom(p2, (m, 3)) >>> p1 x**4 + 3*x*y**3*z**3 + 3*x*y**2*z**4 + 2*y """ p1 = self if p1 in p1.ring._gens_set: p1 = p1.copy() (m, c) = mc get = p1.get zero = p1.ring.domain.zero monomial_mul = p1.ring.monomial_mul for k, v in p2.items(): ka = monomial_mul(k, m) coeff = get(ka, zero) + v*c if coeff: p1[ka] = coeff else: del p1[ka] return p1 def degree(f, x=None): """ The leading degree in ``x`` or the main variable. Note that the degree of 0 is negative infinity (the SymPy object -oo). """ i = f.ring.index(x) if not f: return -oo elif i < 0: return 0 else: return max([ monom[i] for monom in f.itermonoms() ]) def degrees(f): """ A tuple containing leading degrees in all variables. Note that the degree of 0 is negative infinity (the SymPy object -oo) """ if not f: return (-oo,)*f.ring.ngens else: return tuple(map(max, list(zip(*f.itermonoms())))) def tail_degree(f, x=None): """ The tail degree in ``x`` or the main variable. Note that the degree of 0 is negative infinity (the SymPy object -oo) """ i = f.ring.index(x) if not f: return -oo elif i < 0: return 0 else: return min([ monom[i] for monom in f.itermonoms() ]) def tail_degrees(f): """ A tuple containing tail degrees in all variables. Note that the degree of 0 is negative infinity (the SymPy object -oo) """ if not f: return (-oo,)*f.ring.ngens else: return tuple(map(min, list(zip(*f.itermonoms())))) def leading_expv(self): """Leading monomial tuple according to the monomial ordering. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y, z = ring('x, y, z', ZZ) >>> p = x**4 + x**3*y + x**2*z**2 + z**7 >>> p.leading_expv() (4, 0, 0) """ if self: return self.ring.leading_expv(self) else: return None def _get_coeff(self, expv): return self.get(expv, self.ring.domain.zero) def coeff(self, element): """ Returns the coefficient that stands next to the given monomial. Parameters ========== element : PolyElement (with ``is_monomial = True``) or 1 Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y, z = ring("x,y,z", ZZ) >>> f = 3*x**2*y - x*y*z + 7*z**3 + 23 >>> f.coeff(x**2*y) 3 >>> f.coeff(x*y) 0 >>> f.coeff(1) 23 """ if element == 1: return self._get_coeff(self.ring.zero_monom) elif isinstance(element, self.ring.dtype): terms = list(element.iterterms()) if len(terms) == 1: monom, coeff = terms[0] if coeff == self.ring.domain.one: return self._get_coeff(monom) raise ValueError("expected a monomial, got %s" % element) def const(self): """Returns the constant coeffcient. """ return self._get_coeff(self.ring.zero_monom) @property def LC(self): return self._get_coeff(self.leading_expv()) @property def LM(self): expv = self.leading_expv() if expv is None: return self.ring.zero_monom else: return expv def leading_monom(self): """ Leading monomial as a polynomial element. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring('x, y', ZZ) >>> (3*x*y + y**2).leading_monom() x*y """ p = self.ring.zero expv = self.leading_expv() if expv: p[expv] = self.ring.domain.one return p @property def LT(self): expv = self.leading_expv() if expv is None: return (self.ring.zero_monom, self.ring.domain.zero) else: return (expv, self._get_coeff(expv)) def leading_term(self): """Leading term as a polynomial element. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring('x, y', ZZ) >>> (3*x*y + y**2).leading_term() 3*x*y """ p = self.ring.zero expv = self.leading_expv() if expv is not None: p[expv] = self[expv] return p def _sorted(self, seq, order): if order is None: order = self.ring.order else: order = OrderOpt.preprocess(order) if order is lex: return sorted(seq, key=lambda monom: monom[0], reverse=True) else: return sorted(seq, key=lambda monom: order(monom[0]), reverse=True) def coeffs(self, order=None): """Ordered list of polynomial coefficients. Parameters ========== order : :class:`~.MonomialOrder` or coercible, optional Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> from sympy.polys.orderings import lex, grlex >>> _, x, y = ring("x, y", ZZ, lex) >>> f = x*y**7 + 2*x**2*y**3 >>> f.coeffs() [2, 1] >>> f.coeffs(grlex) [1, 2] """ return [ coeff for _, coeff in self.terms(order) ] def monoms(self, order=None): """Ordered list of polynomial monomials. Parameters ========== order : :class:`~.MonomialOrder` or coercible, optional Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> from sympy.polys.orderings import lex, grlex >>> _, x, y = ring("x, y", ZZ, lex) >>> f = x*y**7 + 2*x**2*y**3 >>> f.monoms() [(2, 3), (1, 7)] >>> f.monoms(grlex) [(1, 7), (2, 3)] """ return [ monom for monom, _ in self.terms(order) ] def terms(self, order=None): """Ordered list of polynomial terms. Parameters ========== order : :class:`~.MonomialOrder` or coercible, optional Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> from sympy.polys.orderings import lex, grlex >>> _, x, y = ring("x, y", ZZ, lex) >>> f = x*y**7 + 2*x**2*y**3 >>> f.terms() [((2, 3), 2), ((1, 7), 1)] >>> f.terms(grlex) [((1, 7), 1), ((2, 3), 2)] """ return self._sorted(list(self.items()), order) def itercoeffs(self): """Iterator over coefficients of a polynomial. """ return iter(self.values()) def itermonoms(self): """Iterator over monomials of a polynomial. """ return iter(self.keys()) def iterterms(self): """Iterator over terms of a polynomial. """ return iter(self.items()) def listcoeffs(self): """Unordered list of polynomial coefficients. """ return list(self.values()) def listmonoms(self): """Unordered list of polynomial monomials. """ return list(self.keys()) def listterms(self): """Unordered list of polynomial terms. """ return list(self.items()) def imul_num(p, c): """multiply inplace the polynomial p by an element in the coefficient ring, provided p is not one of the generators; else multiply not inplace Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring('x, y', ZZ) >>> p = x + y**2 >>> p1 = p.imul_num(3) >>> p1 3*x + 3*y**2 >>> p1 is p True >>> p = x >>> p1 = p.imul_num(3) >>> p1 3*x >>> p1 is p False """ if p in p.ring._gens_set: return p*c if not c: p.clear() return for exp in p: p[exp] *= c return p def content(f): """Returns GCD of polynomial's coefficients. """ domain = f.ring.domain cont = domain.zero gcd = domain.gcd for coeff in f.itercoeffs(): cont = gcd(cont, coeff) return cont def primitive(f): """Returns content and a primitive polynomial. """ cont = f.content() return cont, f.quo_ground(cont) def monic(f): """Divides all coefficients by the leading coefficient. """ if not f: return f else: return f.quo_ground(f.LC) def mul_ground(f, x): if not x: return f.ring.zero terms = [ (monom, coeff*x) for monom, coeff in f.iterterms() ] return f.new(terms) def mul_monom(f, monom): monomial_mul = f.ring.monomial_mul terms = [ (monomial_mul(f_monom, monom), f_coeff) for f_monom, f_coeff in f.items() ] return f.new(terms) def mul_term(f, term): monom, coeff = term if not f or not coeff: return f.ring.zero elif monom == f.ring.zero_monom: return f.mul_ground(coeff) monomial_mul = f.ring.monomial_mul terms = [ (monomial_mul(f_monom, monom), f_coeff*coeff) for f_monom, f_coeff in f.items() ] return f.new(terms) def quo_ground(f, x): domain = f.ring.domain if not x: raise ZeroDivisionError('polynomial division') if not f or x == domain.one: return f if domain.is_Field: quo = domain.quo terms = [ (monom, quo(coeff, x)) for monom, coeff in f.iterterms() ] else: terms = [ (monom, coeff // x) for monom, coeff in f.iterterms() if not (coeff % x) ] return f.new(terms) def quo_term(f, term): monom, coeff = term if not coeff: raise ZeroDivisionError("polynomial division") elif not f: return f.ring.zero elif monom == f.ring.zero_monom: return f.quo_ground(coeff) term_div = f._term_div() terms = [ term_div(t, term) for t in f.iterterms() ] return f.new([ t for t in terms if t is not None ]) def trunc_ground(f, p): if f.ring.domain.is_ZZ: terms = [] for monom, coeff in f.iterterms(): coeff = coeff % p if coeff > p // 2: coeff = coeff - p terms.append((monom, coeff)) else: terms = [ (monom, coeff % p) for monom, coeff in f.iterterms() ] poly = f.new(terms) poly.strip_zero() return poly rem_ground = trunc_ground def extract_ground(self, g): f = self fc = f.content() gc = g.content() gcd = f.ring.domain.gcd(fc, gc) f = f.quo_ground(gcd) g = g.quo_ground(gcd) return gcd, f, g def _norm(f, norm_func): if not f: return f.ring.domain.zero else: ground_abs = f.ring.domain.abs return norm_func([ ground_abs(coeff) for coeff in f.itercoeffs() ]) def max_norm(f): return f._norm(max) def l1_norm(f): return f._norm(sum) def deflate(f, *G): ring = f.ring polys = [f] + list(G) J = [0]*ring.ngens for p in polys: for monom in p.itermonoms(): for i, m in enumerate(monom): J[i] = igcd(J[i], m) for i, b in enumerate(J): if not b: J[i] = 1 J = tuple(J) if all(b == 1 for b in J): return J, polys H = [] for p in polys: h = ring.zero for I, coeff in p.iterterms(): N = [ i // j for i, j in zip(I, J) ] h[tuple(N)] = coeff H.append(h) return J, H def inflate(f, J): poly = f.ring.zero for I, coeff in f.iterterms(): N = [ i*j for i, j in zip(I, J) ] poly[tuple(N)] = coeff return poly def lcm(self, g): f = self domain = f.ring.domain if not domain.is_Field: fc, f = f.primitive() gc, g = g.primitive() c = domain.lcm(fc, gc) h = (f*g).quo(f.gcd(g)) if not domain.is_Field: return h.mul_ground(c) else: return h.monic() def gcd(f, g): return f.cofactors(g)[0] def cofactors(f, g): if not f and not g: zero = f.ring.zero return zero, zero, zero elif not f: h, cff, cfg = f._gcd_zero(g) return h, cff, cfg elif not g: h, cfg, cff = g._gcd_zero(f) return h, cff, cfg elif len(f) == 1: h, cff, cfg = f._gcd_monom(g) return h, cff, cfg elif len(g) == 1: h, cfg, cff = g._gcd_monom(f) return h, cff, cfg J, (f, g) = f.deflate(g) h, cff, cfg = f._gcd(g) return (h.inflate(J), cff.inflate(J), cfg.inflate(J)) def _gcd_zero(f, g): one, zero = f.ring.one, f.ring.zero if g.is_nonnegative: return g, zero, one else: return -g, zero, -one def _gcd_monom(f, g): ring = f.ring ground_gcd = ring.domain.gcd ground_quo = ring.domain.quo monomial_gcd = ring.monomial_gcd monomial_ldiv = ring.monomial_ldiv mf, cf = list(f.iterterms())[0] _mgcd, _cgcd = mf, cf for mg, cg in g.iterterms(): _mgcd = monomial_gcd(_mgcd, mg) _cgcd = ground_gcd(_cgcd, cg) h = f.new([(_mgcd, _cgcd)]) cff = f.new([(monomial_ldiv(mf, _mgcd), ground_quo(cf, _cgcd))]) cfg = f.new([(monomial_ldiv(mg, _mgcd), ground_quo(cg, _cgcd)) for mg, cg in g.iterterms()]) return h, cff, cfg def _gcd(f, g): ring = f.ring if ring.domain.is_QQ: return f._gcd_QQ(g) elif ring.domain.is_ZZ: return f._gcd_ZZ(g) else: # TODO: don't use dense representation (port PRS algorithms) return ring.dmp_inner_gcd(f, g) def _gcd_ZZ(f, g): return heugcd(f, g) def _gcd_QQ(self, g): f = self ring = f.ring new_ring = ring.clone(domain=ring.domain.get_ring()) cf, f = f.clear_denoms() cg, g = g.clear_denoms() f = f.set_ring(new_ring) g = g.set_ring(new_ring) h, cff, cfg = f._gcd_ZZ(g) h = h.set_ring(ring) c, h = h.LC, h.monic() cff = cff.set_ring(ring).mul_ground(ring.domain.quo(c, cf)) cfg = cfg.set_ring(ring).mul_ground(ring.domain.quo(c, cg)) return h, cff, cfg def cancel(self, g): """ Cancel common factors in a rational function ``f/g``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> (2*x**2 - 2).cancel(x**2 - 2*x + 1) (2*x + 2, x - 1) """ f = self ring = f.ring if not f: return f, ring.one domain = ring.domain if not (domain.is_Field and domain.has_assoc_Ring): _, p, q = f.cofactors(g) else: new_ring = ring.clone(domain=domain.get_ring()) cq, f = f.clear_denoms() cp, g = g.clear_denoms() f = f.set_ring(new_ring) g = g.set_ring(new_ring) _, p, q = f.cofactors(g) _, cp, cq = new_ring.domain.cofactors(cp, cq) p = p.set_ring(ring) q = q.set_ring(ring) p = p.mul_ground(cp) q = q.mul_ground(cq) # Make canonical with respect to sign or quadrant in the case of ZZ_I # or QQ_I. This ensures that the LC of the denominator is canonical by # multiplying top and bottom by a unit of the ring. u = q.canonical_unit() if u == domain.one: p, q = p, q elif u == -domain.one: p, q = -p, -q else: p = p.mul_ground(u) q = q.mul_ground(u) return p, q def canonical_unit(f): domain = f.ring.domain return domain.canonical_unit(f.LC) def diff(f, x): """Computes partial derivative in ``x``. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring("x,y", ZZ) >>> p = x + x**2*y**3 >>> p.diff(x) 2*x*y**3 + 1 """ ring = f.ring i = ring.index(x) m = ring.monomial_basis(i) g = ring.zero for expv, coeff in f.iterterms(): if expv[i]: e = ring.monomial_ldiv(expv, m) g[e] = ring.domain_new(coeff*expv[i]) return g def __call__(f, *values): if 0 < len(values) <= f.ring.ngens: return f.evaluate(list(zip(f.ring.gens, values))) else: raise ValueError("expected at least 1 and at most %s values, got %s" % (f.ring.ngens, len(values))) def evaluate(self, x, a=None): f = self if isinstance(x, list) and a is None: (X, a), x = x[0], x[1:] f = f.evaluate(X, a) if not x: return f else: x = [ (Y.drop(X), a) for (Y, a) in x ] return f.evaluate(x) ring = f.ring i = ring.index(x) a = ring.domain.convert(a) if ring.ngens == 1: result = ring.domain.zero for (n,), coeff in f.iterterms(): result += coeff*a**n return result else: poly = ring.drop(x).zero for monom, coeff in f.iterterms(): n, monom = monom[i], monom[:i] + monom[i+1:] coeff = coeff*a**n if monom in poly: coeff = coeff + poly[monom] if coeff: poly[monom] = coeff else: del poly[monom] else: if coeff: poly[monom] = coeff return poly def subs(self, x, a=None): f = self if isinstance(x, list) and a is None: for X, a in x: f = f.subs(X, a) return f ring = f.ring i = ring.index(x) a = ring.domain.convert(a) if ring.ngens == 1: result = ring.domain.zero for (n,), coeff in f.iterterms(): result += coeff*a**n return ring.ground_new(result) else: poly = ring.zero for monom, coeff in f.iterterms(): n, monom = monom[i], monom[:i] + (0,) + monom[i+1:] coeff = coeff*a**n if monom in poly: coeff = coeff + poly[monom] if coeff: poly[monom] = coeff else: del poly[monom] else: if coeff: poly[monom] = coeff return poly def compose(f, x, a=None): ring = f.ring poly = ring.zero gens_map = dict(zip(ring.gens, range(ring.ngens))) if a is not None: replacements = [(x, a)] else: if isinstance(x, list): replacements = list(x) elif isinstance(x, dict): replacements = sorted(list(x.items()), key=lambda k: gens_map[k[0]]) else: raise ValueError("expected a generator, value pair a sequence of such pairs") for k, (x, g) in enumerate(replacements): replacements[k] = (gens_map[x], ring.ring_new(g)) for monom, coeff in f.iterterms(): monom = list(monom) subpoly = ring.one for i, g in replacements: n, monom[i] = monom[i], 0 if n: subpoly *= g**n subpoly = subpoly.mul_term((tuple(monom), coeff)) poly += subpoly return poly # TODO: following methods should point to polynomial # representation independent algorithm implementations. def pdiv(f, g): return f.ring.dmp_pdiv(f, g) def prem(f, g): return f.ring.dmp_prem(f, g) def pquo(f, g): return f.ring.dmp_quo(f, g) def pexquo(f, g): return f.ring.dmp_exquo(f, g) def half_gcdex(f, g): return f.ring.dmp_half_gcdex(f, g) def gcdex(f, g): return f.ring.dmp_gcdex(f, g) def subresultants(f, g): return f.ring.dmp_subresultants(f, g) def resultant(f, g): return f.ring.dmp_resultant(f, g) def discriminant(f): return f.ring.dmp_discriminant(f) def decompose(f): if f.ring.is_univariate: return f.ring.dup_decompose(f) else: raise MultivariatePolynomialError("polynomial decomposition") def shift(f, a): if f.ring.is_univariate: return f.ring.dup_shift(f, a) else: raise MultivariatePolynomialError("polynomial shift") def sturm(f): if f.ring.is_univariate: return f.ring.dup_sturm(f) else: raise MultivariatePolynomialError("sturm sequence") def gff_list(f): return f.ring.dmp_gff_list(f) def sqf_norm(f): return f.ring.dmp_sqf_norm(f) def sqf_part(f): return f.ring.dmp_sqf_part(f) def sqf_list(f, all=False): return f.ring.dmp_sqf_list(f, all=all) def factor_list(f): return f.ring.dmp_factor_list(f)
b935356e97d0a9dc2e7794d17d1093c1b3c525cb8b9ae6497e82d01ce3e3fa62
import re import fnmatch message_unicode_B = \ "File contains a unicode character : %s, line %s. " \ "But not in the whitelist. " \ "Add the file to the whitelist in " + __file__ message_unicode_D = \ "File does not contain a unicode character : %s." \ "but is in the whitelist. " \ "Remove the file from the whitelist in " + __file__ encoding_header_re = re.compile( r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)') # Whitelist pattern for files which can have unicode. unicode_whitelist = [ # Author names can include non-ASCII characters r'*/bin/authors_update.py', r'*/bin/mailmap_check.py', # These files have functions and test functions for unicode input and # output. r'*/sympy/testing/tests/test_code_quality.py', r'*/sympy/physics/vector/tests/test_printing.py', r'*/physics/quantum/tests/test_printing.py', r'*/sympy/vector/tests/test_printing.py', r'*/sympy/parsing/tests/test_sympy_parser.py', r'*/sympy/printing/pretty/tests/test_pretty.py', r'*/sympy/printing/tests/test_conventions.py', r'*/sympy/printing/tests/test_preview.py', r'*/liealgebras/type_g.py', r'*/liealgebras/weyl_group.py', r'*/liealgebras/tests/test_type_G.py', # wigner.py and polarization.py have unicode doctests. These probably # don't need to be there but some of the examples that are there are # pretty ugly without use_unicode (matrices need to be wrapped across # multiple lines etc) r'*/sympy/physics/wigner.py', r'*/sympy/physics/optics/polarization.py', # joint.py uses some unicode for variable names in the docstrings r'*/sympy/physics/mechanics/joint.py', ] unicode_strict_whitelist = [ r'*/sympy/parsing/latex/_antlr/__init__.py', # test_mathematica.py uses some unicode for testing Greek characters are working #24055 r'*/sympy/parsing/tests/test_mathematica.py', ] def _test_this_file_encoding( fname, test_file, unicode_whitelist=unicode_whitelist, unicode_strict_whitelist=unicode_strict_whitelist): """Test helper function for unicode test The test may have to operate on filewise manner, so it had moved to a separate process. """ has_unicode = False is_in_whitelist = False is_in_strict_whitelist = False for patt in unicode_whitelist: if fnmatch.fnmatch(fname, patt): is_in_whitelist = True break for patt in unicode_strict_whitelist: if fnmatch.fnmatch(fname, patt): is_in_strict_whitelist = True is_in_whitelist = True break if is_in_whitelist: for idx, line in enumerate(test_file): try: line.encode(encoding='ascii') except (UnicodeEncodeError, UnicodeDecodeError): has_unicode = True if not has_unicode and not is_in_strict_whitelist: assert False, message_unicode_D % fname else: for idx, line in enumerate(test_file): try: line.encode(encoding='ascii') except (UnicodeEncodeError, UnicodeDecodeError): assert False, message_unicode_B % (fname, idx + 1)
463b29ca91818602588d2447cce30e66f08ee1563a9df66b95541237e6d48b9f
""" This is our testing framework. Goals: * it should be compatible with py.test and operate very similarly (or identically) * does not require any external dependencies * preferably all the functionality should be in this file only * no magic, just import the test file and execute the test functions, that's it * portable """ import os import sys import platform import inspect import traceback import pdb import re import linecache import time from fnmatch import fnmatch from timeit import default_timer as clock import doctest as pdoctest # avoid clashing with our doctest() function from doctest import DocTestFinder, DocTestRunner import random import subprocess import shutil import signal import stat import tempfile import warnings from contextlib import contextmanager from inspect import unwrap from sympy.core.cache import clear_cache from sympy.external import import_module from sympy.external.gmpy import GROUND_TYPES, HAS_GMPY IS_WINDOWS = (os.name == 'nt') ON_TRAVIS = os.getenv('TRAVIS_BUILD_NUMBER', None) # emperically generated list of the proportion of time spent running # an even split of tests. This should periodically be regenerated. # A list of [.6, .1, .3] would mean that if the tests are evenly split # into '1/3', '2/3', '3/3', the first split would take 60% of the time, # the second 10% and the third 30%. These lists are normalized to sum # to 1, so [60, 10, 30] has the same behavior as [6, 1, 3] or [.6, .1, .3]. # # This list can be generated with the code: # from time import time # import sympy # import os # os.environ["TRAVIS_BUILD_NUMBER"] = '2' # Mock travis to get more correct densities # delays, num_splits = [], 30 # for i in range(1, num_splits + 1): # tic = time() # sympy.test(split='{}/{}'.format(i, num_splits), time_balance=False) # Add slow=True for slow tests # delays.append(time() - tic) # tot = sum(delays) # print([round(x / tot, 4) for x in delays]) SPLIT_DENSITY = [ 0.0059, 0.0027, 0.0068, 0.0011, 0.0006, 0.0058, 0.0047, 0.0046, 0.004, 0.0257, 0.0017, 0.0026, 0.004, 0.0032, 0.0016, 0.0015, 0.0004, 0.0011, 0.0016, 0.0014, 0.0077, 0.0137, 0.0217, 0.0074, 0.0043, 0.0067, 0.0236, 0.0004, 0.1189, 0.0142, 0.0234, 0.0003, 0.0003, 0.0047, 0.0006, 0.0013, 0.0004, 0.0008, 0.0007, 0.0006, 0.0139, 0.0013, 0.0007, 0.0051, 0.002, 0.0004, 0.0005, 0.0213, 0.0048, 0.0016, 0.0012, 0.0014, 0.0024, 0.0015, 0.0004, 0.0005, 0.0007, 0.011, 0.0062, 0.0015, 0.0021, 0.0049, 0.0006, 0.0006, 0.0011, 0.0006, 0.0019, 0.003, 0.0044, 0.0054, 0.0057, 0.0049, 0.0016, 0.0006, 0.0009, 0.0006, 0.0012, 0.0006, 0.0149, 0.0532, 0.0076, 0.0041, 0.0024, 0.0135, 0.0081, 0.2209, 0.0459, 0.0438, 0.0488, 0.0137, 0.002, 0.0003, 0.0008, 0.0039, 0.0024, 0.0005, 0.0004, 0.003, 0.056, 0.0026] SPLIT_DENSITY_SLOW = [0.0086, 0.0004, 0.0568, 0.0003, 0.0032, 0.0005, 0.0004, 0.0013, 0.0016, 0.0648, 0.0198, 0.1285, 0.098, 0.0005, 0.0064, 0.0003, 0.0004, 0.0026, 0.0007, 0.0051, 0.0089, 0.0024, 0.0033, 0.0057, 0.0005, 0.0003, 0.001, 0.0045, 0.0091, 0.0006, 0.0005, 0.0321, 0.0059, 0.1105, 0.216, 0.1489, 0.0004, 0.0003, 0.0006, 0.0483] class Skipped(Exception): pass class TimeOutError(Exception): pass class DependencyError(Exception): pass def _indent(s, indent=4): """ Add the given number of space characters to the beginning of every non-blank line in ``s``, and return the result. If the string ``s`` is Unicode, it is encoded using the stdout encoding and the ``backslashreplace`` error handler. """ # This regexp matches the start of non-blank lines: return re.sub('(?m)^(?!$)', indent*' ', s) pdoctest._indent = _indent # type: ignore # override reporter to maintain windows and python3 def _report_failure(self, out, test, example, got): """ Report that the given example failed. """ s = self._checker.output_difference(example, got, self.optionflags) s = s.encode('raw_unicode_escape').decode('utf8', 'ignore') out(self._failure_header(test, example) + s) if IS_WINDOWS: DocTestRunner.report_failure = _report_failure # type: ignore def convert_to_native_paths(lst): """ Converts a list of '/' separated paths into a list of native (os.sep separated) paths and converts to lowercase if the system is case insensitive. """ newlst = [] for i, rv in enumerate(lst): rv = os.path.join(*rv.split("/")) # on windows the slash after the colon is dropped if sys.platform == "win32": pos = rv.find(':') if pos != -1: if rv[pos + 1] != '\\': rv = rv[:pos + 1] + '\\' + rv[pos + 1:] newlst.append(os.path.normcase(rv)) return newlst def get_sympy_dir(): """ Returns the root SymPy directory and set the global value indicating whether the system is case sensitive or not. """ this_file = os.path.abspath(__file__) sympy_dir = os.path.join(os.path.dirname(this_file), "..", "..") sympy_dir = os.path.normpath(sympy_dir) return os.path.normcase(sympy_dir) def setup_pprint(): from sympy.interactive.printing import init_printing from sympy.printing.pretty.pretty import pprint_use_unicode import sympy.interactive.printing as interactive_printing # force pprint to be in ascii mode in doctests use_unicode_prev = pprint_use_unicode(False) # hook our nice, hash-stable strprinter init_printing(pretty_print=False) # Prevent init_printing() in doctests from affecting other doctests interactive_printing.NO_GLOBAL = True return use_unicode_prev @contextmanager def raise_on_deprecated(): """Context manager to make DeprecationWarning raise an error This is to catch SymPyDeprecationWarning from library code while running tests and doctests. It is important to use this context manager around each individual test/doctest in case some tests modify the warning filters. """ with warnings.catch_warnings(): warnings.filterwarnings('error', '.*', DeprecationWarning, module='sympy.*') yield def run_in_subprocess_with_hash_randomization( function, function_args=(), function_kwargs=None, command=sys.executable, module='sympy.testing.runtests', force=False): """ Run a function in a Python subprocess with hash randomization enabled. If hash randomization is not supported by the version of Python given, it returns False. Otherwise, it returns the exit value of the command. The function is passed to sys.exit(), so the return value of the function will be the return value. The environment variable PYTHONHASHSEED is used to seed Python's hash randomization. If it is set, this function will return False, because starting a new subprocess is unnecessary in that case. If it is not set, one is set at random, and the tests are run. Note that if this environment variable is set when Python starts, hash randomization is automatically enabled. To force a subprocess to be created even if PYTHONHASHSEED is set, pass ``force=True``. This flag will not force a subprocess in Python versions that do not support hash randomization (see below), because those versions of Python do not support the ``-R`` flag. ``function`` should be a string name of a function that is importable from the module ``module``, like "_test". The default for ``module`` is "sympy.testing.runtests". ``function_args`` and ``function_kwargs`` should be a repr-able tuple and dict, respectively. The default Python command is sys.executable, which is the currently running Python command. This function is necessary because the seed for hash randomization must be set by the environment variable before Python starts. Hence, in order to use a predetermined seed for tests, we must start Python in a separate subprocess. Hash randomization was added in the minor Python versions 2.6.8, 2.7.3, 3.1.5, and 3.2.3, and is enabled by default in all Python versions after and including 3.3.0. Examples ======== >>> from sympy.testing.runtests import ( ... run_in_subprocess_with_hash_randomization) >>> # run the core tests in verbose mode >>> run_in_subprocess_with_hash_randomization("_test", ... function_args=("core",), ... function_kwargs={'verbose': True}) # doctest: +SKIP # Will return 0 if sys.executable supports hash randomization and tests # pass, 1 if they fail, and False if it does not support hash # randomization. """ cwd = get_sympy_dir() # Note, we must return False everywhere, not None, as subprocess.call will # sometimes return None. # First check if the Python version supports hash randomization # If it does not have this support, it won't recognize the -R flag p = subprocess.Popen([command, "-RV"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd) p.communicate() if p.returncode != 0: return False hash_seed = os.getenv("PYTHONHASHSEED") if not hash_seed: os.environ["PYTHONHASHSEED"] = str(random.randrange(2**32)) else: if not force: return False function_kwargs = function_kwargs or {} # Now run the command commandstring = ("import sys; from %s import %s;sys.exit(%s(*%s, **%s))" % (module, function, function, repr(function_args), repr(function_kwargs))) try: p = subprocess.Popen([command, "-R", "-c", commandstring], cwd=cwd) p.communicate() except KeyboardInterrupt: p.wait() finally: # Put the environment variable back, so that it reads correctly for # the current Python process. if hash_seed is None: del os.environ["PYTHONHASHSEED"] else: os.environ["PYTHONHASHSEED"] = hash_seed return p.returncode def run_all_tests(test_args=(), test_kwargs=None, doctest_args=(), doctest_kwargs=None, examples_args=(), examples_kwargs=None): """ Run all tests. Right now, this runs the regular tests (bin/test), the doctests (bin/doctest), and the examples (examples/all.py). This is what ``setup.py test`` uses. You can pass arguments and keyword arguments to the test functions that support them (for now, test, doctest, and the examples). See the docstrings of those functions for a description of the available options. For example, to run the solvers tests with colors turned off: >>> from sympy.testing.runtests import run_all_tests >>> run_all_tests(test_args=("solvers",), ... test_kwargs={"colors:False"}) # doctest: +SKIP """ tests_successful = True test_kwargs = test_kwargs or {} doctest_kwargs = doctest_kwargs or {} examples_kwargs = examples_kwargs or {'quiet': True} try: # Regular tests if not test(*test_args, **test_kwargs): # some regular test fails, so set the tests_successful # flag to false and continue running the doctests tests_successful = False # Doctests print() if not doctest(*doctest_args, **doctest_kwargs): tests_successful = False # Examples print() sys.path.append("examples") # examples/all.py from all import run_examples # type: ignore if not run_examples(*examples_args, **examples_kwargs): tests_successful = False if tests_successful: return else: # Return nonzero exit code sys.exit(1) except KeyboardInterrupt: print() print("DO *NOT* COMMIT!") sys.exit(1) def test(*paths, subprocess=True, rerun=0, **kwargs): """ Run tests in the specified test_*.py files. Tests in a particular test_*.py file are run if any of the given strings in ``paths`` matches a part of the test file's path. If ``paths=[]``, tests in all test_*.py files are run. Notes: - If sort=False, tests are run in random order (not default). - Paths can be entered in native system format or in unix, forward-slash format. - Files that are on the blacklist can be tested by providing their path; they are only excluded if no paths are given. **Explanation of test results** ====== =============================================================== Output Meaning ====== =============================================================== . passed F failed X XPassed (expected to fail but passed) f XFAILed (expected to fail and indeed failed) s skipped w slow T timeout (e.g., when ``--timeout`` is used) K KeyboardInterrupt (when running the slow tests with ``--slow``, you can interrupt one of them without killing the test runner) ====== =============================================================== Colors have no additional meaning and are used just to facilitate interpreting the output. Examples ======== >>> import sympy Run all tests: >>> sympy.test() # doctest: +SKIP Run one file: >>> sympy.test("sympy/core/tests/test_basic.py") # doctest: +SKIP >>> sympy.test("_basic") # doctest: +SKIP Run all tests in sympy/functions/ and some particular file: >>> sympy.test("sympy/core/tests/test_basic.py", ... "sympy/functions") # doctest: +SKIP Run all tests in sympy/core and sympy/utilities: >>> sympy.test("/core", "/util") # doctest: +SKIP Run specific test from a file: >>> sympy.test("sympy/core/tests/test_basic.py", ... kw="test_equality") # doctest: +SKIP Run specific test from any file: >>> sympy.test(kw="subs") # doctest: +SKIP Run the tests with verbose mode on: >>> sympy.test(verbose=True) # doctest: +SKIP Do not sort the test output: >>> sympy.test(sort=False) # doctest: +SKIP Turn on post-mortem pdb: >>> sympy.test(pdb=True) # doctest: +SKIP Turn off colors: >>> sympy.test(colors=False) # doctest: +SKIP Force colors, even when the output is not to a terminal (this is useful, e.g., if you are piping to ``less -r`` and you still want colors) >>> sympy.test(force_colors=False) # doctest: +SKIP The traceback verboseness can be set to "short" or "no" (default is "short") >>> sympy.test(tb='no') # doctest: +SKIP The ``split`` option can be passed to split the test run into parts. The split currently only splits the test files, though this may change in the future. ``split`` should be a string of the form 'a/b', which will run part ``a`` of ``b``. For instance, to run the first half of the test suite: >>> sympy.test(split='1/2') # doctest: +SKIP The ``time_balance`` option can be passed in conjunction with ``split``. If ``time_balance=True`` (the default for ``sympy.test``), SymPy will attempt to split the tests such that each split takes equal time. This heuristic for balancing is based on pre-recorded test data. >>> sympy.test(split='1/2', time_balance=True) # doctest: +SKIP You can disable running the tests in a separate subprocess using ``subprocess=False``. This is done to support seeding hash randomization, which is enabled by default in the Python versions where it is supported. If subprocess=False, hash randomization is enabled/disabled according to whether it has been enabled or not in the calling Python process. However, even if it is enabled, the seed cannot be printed unless it is called from a new Python process. Hash randomization was added in the minor Python versions 2.6.8, 2.7.3, 3.1.5, and 3.2.3, and is enabled by default in all Python versions after and including 3.3.0. If hash randomization is not supported ``subprocess=False`` is used automatically. >>> sympy.test(subprocess=False) # doctest: +SKIP To set the hash randomization seed, set the environment variable ``PYTHONHASHSEED`` before running the tests. This can be done from within Python using >>> import os >>> os.environ['PYTHONHASHSEED'] = '42' # doctest: +SKIP Or from the command line using $ PYTHONHASHSEED=42 ./bin/test If the seed is not set, a random seed will be chosen. Note that to reproduce the same hash values, you must use both the same seed as well as the same architecture (32-bit vs. 64-bit). """ # count up from 0, do not print 0 print_counter = lambda i : (print("rerun %d" % (rerun-i)) if rerun-i else None) if subprocess: # loop backwards so last i is 0 for i in range(rerun, -1, -1): print_counter(i) ret = run_in_subprocess_with_hash_randomization("_test", function_args=paths, function_kwargs=kwargs) if ret is False: break val = not bool(ret) # exit on the first failure or if done if not val or i == 0: return val # rerun even if hash randomization is not supported for i in range(rerun, -1, -1): print_counter(i) val = not bool(_test(*paths, **kwargs)) if not val or i == 0: return val def _test(*paths, verbose=False, tb="short", kw=None, pdb=False, colors=True, force_colors=False, sort=True, seed=None, timeout=False, fail_on_timeout=False, slow=False, enhance_asserts=False, split=None, time_balance=True, blacklist=('sympy/integrals/rubi/rubi_tests/tests',), fast_threshold=None, slow_threshold=None): """ Internal function that actually runs the tests. All keyword arguments from ``test()`` are passed to this function except for ``subprocess``. Returns 0 if tests passed and 1 if they failed. See the docstring of ``test()`` for more information. """ kw = kw or () # ensure that kw is a tuple if isinstance(kw, str): kw = (kw,) post_mortem = pdb if seed is None: seed = random.randrange(100000000) if ON_TRAVIS and timeout is False: # Travis times out if no activity is seen for 10 minutes. timeout = 595 fail_on_timeout = True if ON_TRAVIS: # pyglet does not work on Travis blacklist = list(blacklist) + ['sympy/plotting/pygletplot/tests'] blacklist = convert_to_native_paths(blacklist) r = PyTestReporter(verbose=verbose, tb=tb, colors=colors, force_colors=force_colors, split=split) t = SymPyTests(r, kw, post_mortem, seed, fast_threshold=fast_threshold, slow_threshold=slow_threshold) test_files = t.get_test_files('sympy') not_blacklisted = [f for f in test_files if not any(b in f for b in blacklist)] if len(paths) == 0: matched = not_blacklisted else: paths = convert_to_native_paths(paths) matched = [] for f in not_blacklisted: basename = os.path.basename(f) for p in paths: if p in f or fnmatch(basename, p): matched.append(f) break density = None if time_balance: if slow: density = SPLIT_DENSITY_SLOW else: density = SPLIT_DENSITY if split: matched = split_list(matched, split, density=density) t._testfiles.extend(matched) return int(not t.test(sort=sort, timeout=timeout, slow=slow, enhance_asserts=enhance_asserts, fail_on_timeout=fail_on_timeout)) def doctest(*paths, subprocess=True, rerun=0, **kwargs): r""" Runs doctests in all \*.py files in the SymPy directory which match any of the given strings in ``paths`` or all tests if paths=[]. Notes: - Paths can be entered in native system format or in unix, forward-slash format. - Files that are on the blacklist can be tested by providing their path; they are only excluded if no paths are given. Examples ======== >>> import sympy Run all tests: >>> sympy.doctest() # doctest: +SKIP Run one file: >>> sympy.doctest("sympy/core/basic.py") # doctest: +SKIP >>> sympy.doctest("polynomial.rst") # doctest: +SKIP Run all tests in sympy/functions/ and some particular file: >>> sympy.doctest("/functions", "basic.py") # doctest: +SKIP Run any file having polynomial in its name, doc/src/modules/polynomial.rst, sympy/functions/special/polynomials.py, and sympy/polys/polynomial.py: >>> sympy.doctest("polynomial") # doctest: +SKIP The ``split`` option can be passed to split the test run into parts. The split currently only splits the test files, though this may change in the future. ``split`` should be a string of the form 'a/b', which will run part ``a`` of ``b``. Note that the regular doctests and the Sphinx doctests are split independently. For instance, to run the first half of the test suite: >>> sympy.doctest(split='1/2') # doctest: +SKIP The ``subprocess`` and ``verbose`` options are the same as with the function ``test()`` (see the docstring of that function for more information) except that ``verbose`` may also be set equal to ``2`` in order to print individual doctest lines, as they are being tested. """ # count up from 0, do not print 0 print_counter = lambda i : (print("rerun %d" % (rerun-i)) if rerun-i else None) if subprocess: # loop backwards so last i is 0 for i in range(rerun, -1, -1): print_counter(i) ret = run_in_subprocess_with_hash_randomization("_doctest", function_args=paths, function_kwargs=kwargs) if ret is False: break val = not bool(ret) # exit on the first failure or if done if not val or i == 0: return val # rerun even if hash randomization is not supported for i in range(rerun, -1, -1): print_counter(i) val = not bool(_doctest(*paths, **kwargs)) if not val or i == 0: return val def _get_doctest_blacklist(): '''Get the default blacklist for the doctests''' blacklist = [] blacklist.extend([ "doc/src/modules/plotting.rst", # generates live plots "doc/src/modules/physics/mechanics/autolev_parser.rst", "sympy/codegen/array_utils.py", # raises deprecation warning "sympy/core/compatibility.py", # backwards compatibility shim, importing it triggers a deprecation warning "sympy/core/trace.py", # backwards compatibility shim, importing it triggers a deprecation warning "sympy/galgebra.py", # no longer part of SymPy "sympy/integrals/rubi/rubi.py", "sympy/parsing/autolev/_antlr/autolevlexer.py", # generated code "sympy/parsing/autolev/_antlr/autolevlistener.py", # generated code "sympy/parsing/autolev/_antlr/autolevparser.py", # generated code "sympy/parsing/latex/_antlr/latexlexer.py", # generated code "sympy/parsing/latex/_antlr/latexparser.py", # generated code "sympy/plotting/pygletplot/__init__.py", # crashes on some systems "sympy/plotting/pygletplot/plot.py", # crashes on some systems "sympy/printing/ccode.py", # backwards compatibility shim, importing it breaks the codegen doctests "sympy/printing/cxxcode.py", # backwards compatibility shim, importing it breaks the codegen doctests "sympy/printing/fcode.py", # backwards compatibility shim, importing it breaks the codegen doctests "sympy/testing/randtest.py", # backwards compatibility shim, importing it triggers a deprecation warning "sympy/this.py", # prints text ]) # autolev parser tests num = 12 for i in range (1, num+1): blacklist.append("sympy/parsing/autolev/test-examples/ruletest" + str(i) + ".py") blacklist.extend(["sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py", "sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py", "sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py", "sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py"]) if import_module('numpy') is None: blacklist.extend([ "sympy/plotting/experimental_lambdify.py", "sympy/plotting/plot_implicit.py", "examples/advanced/autowrap_integrators.py", "examples/advanced/autowrap_ufuncify.py", "examples/intermediate/sample.py", "examples/intermediate/mplot2d.py", "examples/intermediate/mplot3d.py", "doc/src/modules/numeric-computation.rst" ]) else: if import_module('matplotlib') is None: blacklist.extend([ "examples/intermediate/mplot2d.py", "examples/intermediate/mplot3d.py" ]) else: # Use a non-windowed backend, so that the tests work on Travis import matplotlib matplotlib.use('Agg') if ON_TRAVIS or import_module('pyglet') is None: blacklist.extend(["sympy/plotting/pygletplot"]) if import_module('aesara') is None: blacklist.extend([ "sympy/printing/aesaracode.py", "doc/src/modules/numeric-computation.rst", ]) if import_module('cupy') is None: blacklist.extend([ "doc/src/modules/numeric-computation.rst", ]) if import_module('jax') is None: blacklist.extend([ "doc/src/modules/numeric-computation.rst", ]) if import_module('antlr4') is None: blacklist.extend([ "sympy/parsing/autolev/__init__.py", "sympy/parsing/latex/_parse_latex_antlr.py", ]) if import_module('lfortran') is None: #throws ImportError when lfortran not installed blacklist.extend([ "sympy/parsing/sym_expr.py", ]) if import_module("scipy") is None: # throws ModuleNotFoundError when scipy not installed blacklist.extend( ["doc/src/guides/solving/solve-numerically.md",] ) # disabled because of doctest failures in asmeurer's bot blacklist.extend([ "sympy/utilities/autowrap.py", "examples/advanced/autowrap_integrators.py", "examples/advanced/autowrap_ufuncify.py" ]) # blacklist these modules until issue 4840 is resolved blacklist.extend([ "sympy/conftest.py", # Depends on pytest "sympy/testing/benchmarking.py", ]) # These are deprecated stubs to be removed: blacklist.extend([ "sympy/utilities/benchmarking.py", "sympy/utilities/tmpfiles.py", "sympy/utilities/pytest.py", "sympy/utilities/runtests.py", "sympy/utilities/quality_unicode.py", "sympy/utilities/randtest.py", ]) blacklist = convert_to_native_paths(blacklist) return blacklist def _doctest(*paths, **kwargs): """ Internal function that actually runs the doctests. All keyword arguments from ``doctest()`` are passed to this function except for ``subprocess``. Returns 0 if tests passed and 1 if they failed. See the docstrings of ``doctest()`` and ``test()`` for more information. """ from sympy.printing.pretty.pretty import pprint_use_unicode normal = kwargs.get("normal", False) verbose = kwargs.get("verbose", False) colors = kwargs.get("colors", True) force_colors = kwargs.get("force_colors", False) blacklist = kwargs.get("blacklist", []) split = kwargs.get('split', None) blacklist.extend(_get_doctest_blacklist()) # Use a non-windowed backend, so that the tests work on Travis if import_module('matplotlib') is not None: import matplotlib matplotlib.use('Agg') # Disable warnings for external modules import sympy.external sympy.external.importtools.WARN_OLD_VERSION = False sympy.external.importtools.WARN_NOT_INSTALLED = False # Disable showing up of plots from sympy.plotting.plot import unset_show unset_show() r = PyTestReporter(verbose, split=split, colors=colors,\ force_colors=force_colors) t = SymPyDocTests(r, normal) test_files = t.get_test_files('sympy') test_files.extend(t.get_test_files('examples', init_only=False)) not_blacklisted = [f for f in test_files if not any(b in f for b in blacklist)] if len(paths) == 0: matched = not_blacklisted else: # take only what was requested...but not blacklisted items # and allow for partial match anywhere or fnmatch of name paths = convert_to_native_paths(paths) matched = [] for f in not_blacklisted: basename = os.path.basename(f) for p in paths: if p in f or fnmatch(basename, p): matched.append(f) break matched.sort() if split: matched = split_list(matched, split) t._testfiles.extend(matched) # run the tests and record the result for this *py portion of the tests if t._testfiles: failed = not t.test() else: failed = False # N.B. # -------------------------------------------------------------------- # Here we test *.rst and *.md files at or below doc/src. Code from these # must be self supporting in terms of imports since there is no importing # of necessary modules by doctest.testfile. If you try to pass *.py files # through this they might fail because they will lack the needed imports # and smarter parsing that can be done with source code. # test_files_rst = t.get_test_files('doc/src', '*.rst', init_only=False) test_files_md = t.get_test_files('doc/src', '*.md', init_only=False) test_files = test_files_rst + test_files_md test_files.sort() not_blacklisted = [f for f in test_files if not any(b in f for b in blacklist)] if len(paths) == 0: matched = not_blacklisted else: # Take only what was requested as long as it's not on the blacklist. # Paths were already made native in *py tests so don't repeat here. # There's no chance of having a *py file slip through since we # only have *rst files in test_files. matched = [] for f in not_blacklisted: basename = os.path.basename(f) for p in paths: if p in f or fnmatch(basename, p): matched.append(f) break if split: matched = split_list(matched, split) first_report = True for rst_file in matched: if not os.path.isfile(rst_file): continue old_displayhook = sys.displayhook try: use_unicode_prev = setup_pprint() out = sympytestfile( rst_file, module_relative=False, encoding='utf-8', optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE | pdoctest.IGNORE_EXCEPTION_DETAIL) finally: # make sure we return to the original displayhook in case some # doctest has changed that sys.displayhook = old_displayhook # The NO_GLOBAL flag overrides the no_global flag to init_printing # if True import sympy.interactive.printing as interactive_printing interactive_printing.NO_GLOBAL = False pprint_use_unicode(use_unicode_prev) rstfailed, tested = out if tested: failed = rstfailed or failed if first_report: first_report = False msg = 'rst/md doctests start' if not t._testfiles: r.start(msg=msg) else: r.write_center(msg) print() # use as the id, everything past the first 'sympy' file_id = rst_file[rst_file.find('sympy') + len('sympy') + 1:] print(file_id, end=" ") # get at least the name out so it is know who is being tested wid = r.terminal_width - len(file_id) - 1 # update width test_file = '[%s]' % (tested) report = '[%s]' % (rstfailed or 'OK') print(''.join( [test_file, ' '*(wid - len(test_file) - len(report)), report]) ) # the doctests for *py will have printed this message already if there was # a failure, so now only print it if there was intervening reporting by # testing the *rst as evidenced by first_report no longer being True. if not first_report and failed: print() print("DO *NOT* COMMIT!") return int(failed) sp = re.compile(r'([0-9]+)/([1-9][0-9]*)') def split_list(l, split, density=None): """ Splits a list into part a of b split should be a string of the form 'a/b'. For instance, '1/3' would give the split one of three. If the length of the list is not divisible by the number of splits, the last split will have more items. `density` may be specified as a list. If specified, tests will be balanced so that each split has as equal-as-possible amount of mass according to `density`. >>> from sympy.testing.runtests import split_list >>> a = list(range(10)) >>> split_list(a, '1/3') [0, 1, 2] >>> split_list(a, '2/3') [3, 4, 5] >>> split_list(a, '3/3') [6, 7, 8, 9] """ m = sp.match(split) if not m: raise ValueError("split must be a string of the form a/b where a and b are ints") i, t = map(int, m.groups()) if not density: return l[(i - 1)*len(l)//t : i*len(l)//t] # normalize density tot = sum(density) density = [x / tot for x in density] def density_inv(x): """Interpolate the inverse to the cumulative distribution function given by density""" if x <= 0: return 0 if x >= sum(density): return 1 # find the first time the cumulative sum surpasses x # and linearly interpolate cumm = 0 for i, d in enumerate(density): cumm += d if cumm >= x: break frac = (d - (cumm - x)) / d return (i + frac) / len(density) lower_frac = density_inv((i - 1) / t) higher_frac = density_inv(i / t) return l[int(lower_frac*len(l)) : int(higher_frac*len(l))] from collections import namedtuple SymPyTestResults = namedtuple('SymPyTestResults', 'failed attempted') def sympytestfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=pdoctest.DocTestParser(), encoding=None): """ Test examples in the given file. Return (#failures, #tests). Optional keyword arg ``module_relative`` specifies how filenames should be interpreted: - If ``module_relative`` is True (the default), then ``filename`` specifies a module-relative path. By default, this path is relative to the calling module's directory; but if the ``package`` argument is specified, then it is relative to that package. To ensure os-independence, ``filename`` should use "/" characters to separate path segments, and should not be an absolute path (i.e., it may not begin with "/"). - If ``module_relative`` is False, then ``filename`` specifies an os-specific path. The path may be absolute or relative (to the current working directory). Optional keyword arg ``name`` gives the name of the test; by default use the file's basename. Optional keyword argument ``package`` is a Python package or the name of a Python package whose directory should be used as the base directory for a module relative filename. If no package is specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify ``package`` if ``module_relative`` is False. Optional keyword arg ``globs`` gives a dict to be used as the globals when executing examples; by default, use {}. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg ``extraglobs`` gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. Optional keyword arg ``verbose`` prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg ``report`` prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg ``optionflags`` or's together module constants, and defaults to 0. Possible values (see the docs for details): - DONT_ACCEPT_TRUE_FOR_1 - DONT_ACCEPT_BLANKLINE - NORMALIZE_WHITESPACE - ELLIPSIS - SKIP - IGNORE_EXCEPTION_DETAIL - REPORT_UDIFF - REPORT_CDIFF - REPORT_NDIFF - REPORT_ONLY_FIRST_FAILURE Optional keyword arg ``raise_on_error`` raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Optional keyword arg ``parser`` specifies a DocTestParser (or subclass) that should be used to extract tests from the files. Optional keyword arg ``encoding`` specifies an encoding that should be used to convert the file to unicode. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path text, filename = pdoctest._load_testfile( filename, package, module_relative, encoding) # If no name was given, then use the file's name. if name is None: name = os.path.basename(filename) # Assemble the globals. if globs is None: globs = {} else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) if '__name__' not in globs: globs['__name__'] = '__main__' if raise_on_error: runner = pdoctest.DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = SymPyDocTestRunner(verbose=verbose, optionflags=optionflags) runner._checker = SymPyOutputChecker() # Read the file, convert it to a test, and run it. test = parser.get_doctest(text, globs, name, filename, 0) runner.run(test) if report: runner.summarize() if pdoctest.master is None: pdoctest.master = runner else: pdoctest.master.merge(runner) return SymPyTestResults(runner.failures, runner.tries) class SymPyTests: def __init__(self, reporter, kw="", post_mortem=False, seed=None, fast_threshold=None, slow_threshold=None): self._post_mortem = post_mortem self._kw = kw self._count = 0 self._root_dir = get_sympy_dir() self._reporter = reporter self._reporter.root_dir(self._root_dir) self._testfiles = [] self._seed = seed if seed is not None else random.random() # Defaults in seconds, from human / UX design limits # http://www.nngroup.com/articles/response-times-3-important-limits/ # # These defaults are *NOT* set in stone as we are measuring different # things, so others feel free to come up with a better yardstick :) if fast_threshold: self._fast_threshold = float(fast_threshold) else: self._fast_threshold = 8 if slow_threshold: self._slow_threshold = float(slow_threshold) else: self._slow_threshold = 10 def test(self, sort=False, timeout=False, slow=False, enhance_asserts=False, fail_on_timeout=False): """ Runs the tests returning True if all tests pass, otherwise False. If sort=False run tests in random order. """ if sort: self._testfiles.sort() elif slow: pass else: random.seed(self._seed) random.shuffle(self._testfiles) self._reporter.start(self._seed) for f in self._testfiles: try: self.test_file(f, sort, timeout, slow, enhance_asserts, fail_on_timeout) except KeyboardInterrupt: print(" interrupted by user") self._reporter.finish() raise return self._reporter.finish() def _enhance_asserts(self, source): from ast import (NodeTransformer, Compare, Name, Store, Load, Tuple, Assign, BinOp, Str, Mod, Assert, parse, fix_missing_locations) ops = {"Eq": '==', "NotEq": '!=', "Lt": '<', "LtE": '<=', "Gt": '>', "GtE": '>=', "Is": 'is', "IsNot": 'is not', "In": 'in', "NotIn": 'not in'} class Transform(NodeTransformer): def visit_Assert(self, stmt): if isinstance(stmt.test, Compare): compare = stmt.test values = [compare.left] + compare.comparators names = [ "_%s" % i for i, _ in enumerate(values) ] names_store = [ Name(n, Store()) for n in names ] names_load = [ Name(n, Load()) for n in names ] target = Tuple(names_store, Store()) value = Tuple(values, Load()) assign = Assign([target], value) new_compare = Compare(names_load[0], compare.ops, names_load[1:]) msg_format = "\n%s " + "\n%s ".join([ ops[op.__class__.__name__] for op in compare.ops ]) + "\n%s" msg = BinOp(Str(msg_format), Mod(), Tuple(names_load, Load())) test = Assert(new_compare, msg, lineno=stmt.lineno, col_offset=stmt.col_offset) return [assign, test] else: return stmt tree = parse(source) new_tree = Transform().visit(tree) return fix_missing_locations(new_tree) def test_file(self, filename, sort=True, timeout=False, slow=False, enhance_asserts=False, fail_on_timeout=False): reporter = self._reporter funcs = [] try: gl = {'__file__': filename} try: open_file = lambda: open(filename, encoding="utf8") with open_file() as f: source = f.read() if self._kw: for l in source.splitlines(): if l.lstrip().startswith('def '): if any(l.lower().find(k.lower()) != -1 for k in self._kw): break else: return if enhance_asserts: try: source = self._enhance_asserts(source) except ImportError: pass code = compile(source, filename, "exec", flags=0, dont_inherit=True) exec(code, gl) except (SystemExit, KeyboardInterrupt): raise except ImportError: reporter.import_error(filename, sys.exc_info()) return except Exception: reporter.test_exception(sys.exc_info()) clear_cache() self._count += 1 random.seed(self._seed) disabled = gl.get("disabled", False) if not disabled: # we need to filter only those functions that begin with 'test_' # We have to be careful about decorated functions. As long as # the decorator uses functools.wraps, we can detect it. funcs = [] for f in gl: if (f.startswith("test_") and (inspect.isfunction(gl[f]) or inspect.ismethod(gl[f]))): func = gl[f] # Handle multiple decorators while hasattr(func, '__wrapped__'): func = func.__wrapped__ if inspect.getsourcefile(func) == filename: funcs.append(gl[f]) if slow: funcs = [f for f in funcs if getattr(f, '_slow', False)] # Sorting of XFAILed functions isn't fixed yet :-( funcs.sort(key=lambda x: inspect.getsourcelines(x)[1]) i = 0 while i < len(funcs): if inspect.isgeneratorfunction(funcs[i]): # some tests can be generators, that return the actual # test functions. We unpack it below: f = funcs.pop(i) for fg in f(): func = fg[0] args = fg[1:] fgw = lambda: func(*args) funcs.insert(i, fgw) i += 1 else: i += 1 # drop functions that are not selected with the keyword expression: funcs = [x for x in funcs if self.matches(x)] if not funcs: return except Exception: reporter.entering_filename(filename, len(funcs)) raise reporter.entering_filename(filename, len(funcs)) if not sort: random.shuffle(funcs) for f in funcs: start = time.time() reporter.entering_test(f) try: if getattr(f, '_slow', False) and not slow: raise Skipped("Slow") with raise_on_deprecated(): if timeout: self._timeout(f, timeout, fail_on_timeout) else: random.seed(self._seed) f() except KeyboardInterrupt: if getattr(f, '_slow', False): reporter.test_skip("KeyboardInterrupt") else: raise except Exception: if timeout: signal.alarm(0) # Disable the alarm. It could not be handled before. t, v, tr = sys.exc_info() if t is AssertionError: reporter.test_fail((t, v, tr)) if self._post_mortem: pdb.post_mortem(tr) elif t.__name__ == "Skipped": reporter.test_skip(v) elif t.__name__ == "XFail": reporter.test_xfail() elif t.__name__ == "XPass": reporter.test_xpass(v) else: reporter.test_exception((t, v, tr)) if self._post_mortem: pdb.post_mortem(tr) else: reporter.test_pass() taken = time.time() - start if taken > self._slow_threshold: filename = os.path.relpath(filename, reporter._root_dir) reporter.slow_test_functions.append( (filename + "::" + f.__name__, taken)) if getattr(f, '_slow', False) and slow: if taken < self._fast_threshold: filename = os.path.relpath(filename, reporter._root_dir) reporter.fast_test_functions.append( (filename + "::" + f.__name__, taken)) reporter.leaving_filename() def _timeout(self, function, timeout, fail_on_timeout): def callback(x, y): signal.alarm(0) if fail_on_timeout: raise TimeOutError("Timed out after %d seconds" % timeout) else: raise Skipped("Timeout") signal.signal(signal.SIGALRM, callback) signal.alarm(timeout) # Set an alarm with a given timeout function() signal.alarm(0) # Disable the alarm def matches(self, x): """ Does the keyword expression self._kw match "x"? Returns True/False. Always returns True if self._kw is "". """ if not self._kw: return True for kw in self._kw: if x.__name__.lower().find(kw.lower()) != -1: return True return False def get_test_files(self, dir, pat='test_*.py'): """ Returns the list of test_*.py (default) files at or below directory ``dir`` relative to the SymPy home directory. """ dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0]) g = [] for path, folders, files in os.walk(dir): g.extend([os.path.join(path, f) for f in files if fnmatch(f, pat)]) return sorted([os.path.normcase(gi) for gi in g]) class SymPyDocTests: def __init__(self, reporter, normal): self._count = 0 self._root_dir = get_sympy_dir() self._reporter = reporter self._reporter.root_dir(self._root_dir) self._normal = normal self._testfiles = [] def test(self): """ Runs the tests and returns True if all tests pass, otherwise False. """ self._reporter.start() for f in self._testfiles: try: self.test_file(f) except KeyboardInterrupt: print(" interrupted by user") self._reporter.finish() raise return self._reporter.finish() def test_file(self, filename): clear_cache() from io import StringIO import sympy.interactive.printing as interactive_printing from sympy.printing.pretty.pretty import pprint_use_unicode rel_name = filename[len(self._root_dir) + 1:] dirname, file = os.path.split(filename) module = rel_name.replace(os.sep, '.')[:-3] if rel_name.startswith("examples"): # Examples files do not have __init__.py files, # So we have to temporarily extend sys.path to import them sys.path.insert(0, dirname) module = file[:-3] # remove ".py" try: module = pdoctest._normalize_module(module) tests = SymPyDocTestFinder().find(module) except (SystemExit, KeyboardInterrupt): raise except ImportError: self._reporter.import_error(filename, sys.exc_info()) return finally: if rel_name.startswith("examples"): del sys.path[0] tests = [test for test in tests if len(test.examples) > 0] # By default tests are sorted by alphabetical order by function name. # We sort by line number so one can edit the file sequentially from # bottom to top. However, if there are decorated functions, their line # numbers will be too large and for now one must just search for these # by text and function name. tests.sort(key=lambda x: -x.lineno) if not tests: return self._reporter.entering_filename(filename, len(tests)) for test in tests: assert len(test.examples) != 0 if self._reporter._verbose: self._reporter.write("\n{} ".format(test.name)) # check if there are external dependencies which need to be met if '_doctest_depends_on' in test.globs: try: self._check_dependencies(**test.globs['_doctest_depends_on']) except DependencyError as e: self._reporter.test_skip(v=str(e)) continue runner = SymPyDocTestRunner(verbose=self._reporter._verbose==2, optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE | pdoctest.IGNORE_EXCEPTION_DETAIL) runner._checker = SymPyOutputChecker() old = sys.stdout new = old if self._reporter._verbose==2 else StringIO() sys.stdout = new # If the testing is normal, the doctests get importing magic to # provide the global namespace. If not normal (the default) then # then must run on their own; all imports must be explicit within # a function's docstring. Once imported that import will be # available to the rest of the tests in a given function's # docstring (unless clear_globs=True below). if not self._normal: test.globs = {} # if this is uncommented then all the test would get is what # comes by default with a "from sympy import *" #exec('from sympy import *') in test.globs old_displayhook = sys.displayhook use_unicode_prev = setup_pprint() try: f, t = runner.run(test, out=new.write, clear_globs=False) except KeyboardInterrupt: raise finally: sys.stdout = old if f > 0: self._reporter.doctest_fail(test.name, new.getvalue()) else: self._reporter.test_pass() sys.displayhook = old_displayhook interactive_printing.NO_GLOBAL = False pprint_use_unicode(use_unicode_prev) self._reporter.leaving_filename() def get_test_files(self, dir, pat='*.py', init_only=True): r""" Returns the list of \*.py files (default) from which docstrings will be tested which are at or below directory ``dir``. By default, only those that have an __init__.py in their parent directory and do not start with ``test_`` will be included. """ def importable(x): """ Checks if given pathname x is an importable module by checking for __init__.py file. Returns True/False. Currently we only test if the __init__.py file exists in the directory with the file "x" (in theory we should also test all the parent dirs). """ init_py = os.path.join(os.path.dirname(x), "__init__.py") return os.path.exists(init_py) dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0]) g = [] for path, folders, files in os.walk(dir): g.extend([os.path.join(path, f) for f in files if not f.startswith('test_') and fnmatch(f, pat)]) if init_only: # skip files that are not importable (i.e. missing __init__.py) g = [x for x in g if importable(x)] return [os.path.normcase(gi) for gi in g] def _check_dependencies(self, executables=(), modules=(), disable_viewers=(), python_version=(3, 5)): """ Checks if the dependencies for the test are installed. Raises ``DependencyError`` it at least one dependency is not installed. """ for executable in executables: if not shutil.which(executable): raise DependencyError("Could not find %s" % executable) for module in modules: if module == 'matplotlib': matplotlib = import_module( 'matplotlib', import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']}, min_module_version='1.0.0', catch=(RuntimeError,)) if matplotlib is None: raise DependencyError("Could not import matplotlib") else: if not import_module(module): raise DependencyError("Could not import %s" % module) if disable_viewers: tempdir = tempfile.mkdtemp() os.environ['PATH'] = '%s:%s' % (tempdir, os.environ['PATH']) vw = ('#!/usr/bin/env python3\n' 'import sys\n' 'if len(sys.argv) <= 1:\n' ' exit("wrong number of args")\n') for viewer in disable_viewers: with open(os.path.join(tempdir, viewer), 'w') as fh: fh.write(vw) # make the file executable os.chmod(os.path.join(tempdir, viewer), stat.S_IREAD | stat.S_IWRITE | stat.S_IXUSR) if python_version: if sys.version_info < python_version: raise DependencyError("Requires Python >= " + '.'.join(map(str, python_version))) if 'pyglet' in modules: # monkey-patch pyglet s.t. it does not open a window during # doctesting import pyglet class DummyWindow: def __init__(self, *args, **kwargs): self.has_exit = True self.width = 600 self.height = 400 def set_vsync(self, x): pass def switch_to(self): pass def push_handlers(self, x): pass def close(self): pass pyglet.window.Window = DummyWindow class SymPyDocTestFinder(DocTestFinder): """ A class used to extract the DocTests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following object types: modules, functions, classes, methods, staticmethods, classmethods, and properties. Modified from doctest's version to look harder for code that appears comes from a different module. For example, the @vectorize decorator makes it look like functions come from multidimensional.py even though their code exists elsewhere. """ def _find(self, tests, obj, name, module, source_lines, globs, seen): """ Find tests for the given object and any contained objects, and add them to ``tests``. """ if self._verbose: print('Finding tests in %s' % name) # If we've already processed this object, then ignore it. if id(obj) in seen: return seen[id(obj)] = 1 # Make sure we don't run doctests for classes outside of sympy, such # as in numpy or scipy. if inspect.isclass(obj): if obj.__module__.split('.')[0] != 'sympy': return # Find a test for this object, and add it to the list of tests. test = self._get_test(obj, name, module, globs, source_lines) if test is not None: tests.append(test) if not self._recurse: return # Look for tests in a module's contained objects. if inspect.ismodule(obj): for rawname, val in obj.__dict__.items(): # Recurse to functions & classes. if inspect.isfunction(val) or inspect.isclass(val): # Make sure we don't run doctests functions or classes # from different modules if val.__module__ != module.__name__: continue assert self._from_module(module, val), \ "%s is not in module %s (rawname %s)" % (val, module, rawname) try: valname = '%s.%s' % (name, rawname) self._find(tests, val, valname, module, source_lines, globs, seen) except KeyboardInterrupt: raise # Look for tests in a module's __test__ dictionary. for valname, val in getattr(obj, '__test__', {}).items(): if not isinstance(valname, str): raise ValueError("SymPyDocTestFinder.find: __test__ keys " "must be strings: %r" % (type(valname),)) if not (inspect.isfunction(val) or inspect.isclass(val) or inspect.ismethod(val) or inspect.ismodule(val) or isinstance(val, str)): raise ValueError("SymPyDocTestFinder.find: __test__ values " "must be strings, functions, methods, " "classes, or modules: %r" % (type(val),)) valname = '%s.__test__.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) # Look for tests in a class's contained objects. if inspect.isclass(obj): for valname, val in obj.__dict__.items(): # Special handling for staticmethod/classmethod. if isinstance(val, staticmethod): val = getattr(obj, valname) if isinstance(val, classmethod): val = getattr(obj, valname).__func__ # Recurse to methods, properties, and nested classes. if ((inspect.isfunction(unwrap(val)) or inspect.isclass(val) or isinstance(val, property)) and self._from_module(module, val)): # Make sure we don't run doctests functions or classes # from different modules if isinstance(val, property): if hasattr(val.fget, '__module__'): if val.fget.__module__ != module.__name__: continue else: if val.__module__ != module.__name__: continue assert self._from_module(module, val), \ "%s is not in module %s (valname %s)" % ( val, module, valname) valname = '%s.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) def _get_test(self, obj, name, module, globs, source_lines): """ Return a DocTest for the given object, if it defines a docstring; otherwise, return None. """ lineno = None # Extract the object's docstring. If it does not have one, # then return None (no test for this object). if isinstance(obj, str): # obj is a string in the case for objects in the polys package. # Note that source_lines is a binary string (compiled polys # modules), which can't be handled by _find_lineno so determine # the line number here. docstring = obj matches = re.findall(r"line \d+", name) assert len(matches) == 1, \ "string '%s' does not contain lineno " % name # NOTE: this is not the exact linenumber but its better than no # lineno ;) lineno = int(matches[0][5:]) else: try: if obj.__doc__ is None: docstring = '' else: docstring = obj.__doc__ if not isinstance(docstring, str): docstring = str(docstring) except (TypeError, AttributeError): docstring = '' # Don't bother if the docstring is empty. if self._exclude_empty and not docstring: return None # check that properties have a docstring because _find_lineno # assumes it if isinstance(obj, property): if obj.fget.__doc__ is None: return None # Find the docstring's location in the file. if lineno is None: obj = unwrap(obj) # handling of properties is not implemented in _find_lineno so do # it here if hasattr(obj, 'func_closure') and obj.func_closure is not None: tobj = obj.func_closure[0].cell_contents elif isinstance(obj, property): tobj = obj.fget else: tobj = obj lineno = self._find_lineno(tobj, source_lines) if lineno is None: return None # Return a DocTest for this object. if module is None: filename = None else: filename = getattr(module, '__file__', module.__name__) if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] globs['_doctest_depends_on'] = getattr(obj, '_doctest_depends_on', {}) return self._parser.get_doctest(docstring, globs, name, filename, lineno) class SymPyDocTestRunner(DocTestRunner): """ A class used to run DocTest test cases, and accumulate statistics. The ``run`` method is used to process a single DocTest case. It returns a tuple ``(f, t)``, where ``t`` is the number of test cases tried, and ``f`` is the number of test cases that failed. Modified from the doctest version to not reset the sys.displayhook (see issue 5140). See the docstring of the original DocTestRunner for more information. """ def run(self, test, compileflags=None, out=None, clear_globs=True): """ Run the examples in ``test``, and display the results using the writer function ``out``. The examples are run in the namespace ``test.globs``. If ``clear_globs`` is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after the test completes, then use ``clear_globs=False``. ``compileflags`` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to ``globs``. The output of each example is checked using ``SymPyDocTestRunner.check_output``, and the results are formatted by the ``SymPyDocTestRunner.report_*`` methods. """ self.test = test # Remove ``` from the end of example, which may appear in Markdown # files for example in test.examples: example.want = example.want.replace('```\n', '') example.exc_msg = example.exc_msg and example.exc_msg.replace('```\n', '') if compileflags is None: compileflags = pdoctest._extract_future_flags(test.globs) save_stdout = sys.stdout if out is None: out = save_stdout.write sys.stdout = self._fakeout # Patch pdb.set_trace to restore sys.stdout during interactive # debugging (so it's not still redirected to self._fakeout). # Note that the interactive output will go to *our* # save_stdout, even if that's not the real sys.stdout; this # allows us to write test cases for the set_trace behavior. save_set_trace = pdb.set_trace self.debugger = pdoctest._OutputRedirectingPdb(save_stdout) self.debugger.reset() pdb.set_trace = self.debugger.set_trace # Patch linecache.getlines, so we can see the example's source # when we're inside the debugger. self.save_linecache_getlines = pdoctest.linecache.getlines linecache.getlines = self.__patched_linecache_getlines # Fail for deprecation warnings with raise_on_deprecated(): try: return self.__run(test, compileflags, out) finally: sys.stdout = save_stdout pdb.set_trace = save_set_trace linecache.getlines = self.save_linecache_getlines if clear_globs: test.globs.clear() # We have to override the name mangled methods. monkeypatched_methods = [ 'patched_linecache_getlines', 'run', 'record_outcome' ] for method in monkeypatched_methods: oldname = '_DocTestRunner__' + method newname = '_SymPyDocTestRunner__' + method setattr(SymPyDocTestRunner, newname, getattr(DocTestRunner, oldname)) class SymPyOutputChecker(pdoctest.OutputChecker): """ Compared to the OutputChecker from the stdlib our OutputChecker class supports numerical comparison of floats occurring in the output of the doctest examples """ def __init__(self): # NOTE OutputChecker is an old-style class with no __init__ method, # so we can't call the base class version of __init__ here got_floats = r'(\d+\.\d*|\.\d+)' # floats in the 'want' string may contain ellipses want_floats = got_floats + r'(\.{3})?' front_sep = r'\s|\+|\-|\*|,' back_sep = front_sep + r'|j|e' fbeg = r'^%s(?=%s|$)' % (got_floats, back_sep) fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, got_floats, back_sep) self.num_got_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend)) fbeg = r'^%s(?=%s|$)' % (want_floats, back_sep) fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, want_floats, back_sep) self.num_want_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend)) def check_output(self, want, got, optionflags): """ Return True iff the actual output from an example (`got`) matches the expected output (`want`). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See the documentation for `TestRunner` for more information about option flags. """ # Handle the common case first, for efficiency: # if they're string-identical, always return true. if got == want: return True # TODO parse integers as well ? # Parse floats and compare them. If some of the parsed floats contain # ellipses, skip the comparison. matches = self.num_got_rgx.finditer(got) numbers_got = [match.group(1) for match in matches] # list of strs matches = self.num_want_rgx.finditer(want) numbers_want = [match.group(1) for match in matches] # list of strs if len(numbers_got) != len(numbers_want): return False if len(numbers_got) > 0: nw_ = [] for ng, nw in zip(numbers_got, numbers_want): if '...' in nw: nw_.append(ng) continue else: nw_.append(nw) if abs(float(ng)-float(nw)) > 1e-5: return False got = self.num_got_rgx.sub(r'%s', got) got = got % tuple(nw_) # <BLANKLINE> can be used as a special sequence to signify a # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used. if not (optionflags & pdoctest.DONT_ACCEPT_BLANKLINE): # Replace <BLANKLINE> in want with a blank line. want = re.sub(r'(?m)^%s\s*?$' % re.escape(pdoctest.BLANKLINE_MARKER), '', want) # If a line in got contains only spaces, then remove the # spaces. got = re.sub(r'(?m)^\s*?$', '', got) if got == want: return True # This flag causes doctest to ignore any differences in the # contents of whitespace strings. Note that this can be used # in conjunction with the ELLIPSIS flag. if optionflags & pdoctest.NORMALIZE_WHITESPACE: got = ' '.join(got.split()) want = ' '.join(want.split()) if got == want: return True # The ELLIPSIS flag says to let the sequence "..." in `want` # match any substring in `got`. if optionflags & pdoctest.ELLIPSIS: if pdoctest._ellipsis_match(want, got): return True # We didn't find any match; return false. return False class Reporter: """ Parent class for all reporters. """ pass class PyTestReporter(Reporter): """ Py.test like reporter. Should produce output identical to py.test. """ def __init__(self, verbose=False, tb="short", colors=True, force_colors=False, split=None): self._verbose = verbose self._tb_style = tb self._colors = colors self._force_colors = force_colors self._xfailed = 0 self._xpassed = [] self._failed = [] self._failed_doctest = [] self._passed = 0 self._skipped = 0 self._exceptions = [] self._terminal_width = None self._default_width = 80 self._split = split self._active_file = '' self._active_f = None # TODO: Should these be protected? self.slow_test_functions = [] self.fast_test_functions = [] # this tracks the x-position of the cursor (useful for positioning # things on the screen), without the need for any readline library: self._write_pos = 0 self._line_wrap = False def root_dir(self, dir): self._root_dir = dir @property def terminal_width(self): if self._terminal_width is not None: return self._terminal_width def findout_terminal_width(): if sys.platform == "win32": # Windows support is based on: # # http://code.activestate.com/recipes/ # 440694-determine-size-of-console-window-on-windows/ from ctypes import windll, create_string_buffer h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if res: import struct (_, _, _, _, _, left, _, right, _, _, _) = \ struct.unpack("hhhhHhhhhhh", csbi.raw) return right - left else: return self._default_width if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty(): return self._default_width # leave PIPEs alone try: process = subprocess.Popen(['stty', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() stdout = stdout.decode("utf-8") except OSError: pass else: # We support the following output formats from stty: # # 1) Linux -> columns 80 # 2) OS X -> 80 columns # 3) Solaris -> columns = 80 re_linux = r"columns\s+(?P<columns>\d+);" re_osx = r"(?P<columns>\d+)\s*columns;" re_solaris = r"columns\s+=\s+(?P<columns>\d+);" for regex in (re_linux, re_osx, re_solaris): match = re.search(regex, stdout) if match is not None: columns = match.group('columns') try: width = int(columns) except ValueError: pass if width != 0: return width return self._default_width width = findout_terminal_width() self._terminal_width = width return width def write(self, text, color="", align="left", width=None, force_colors=False): """ Prints a text on the screen. It uses sys.stdout.write(), so no readline library is necessary. Parameters ========== color : choose from the colors below, "" means default color align : "left"/"right", "left" is a normal print, "right" is aligned on the right-hand side of the screen, filled with spaces if necessary width : the screen width """ color_templates = ( ("Black", "0;30"), ("Red", "0;31"), ("Green", "0;32"), ("Brown", "0;33"), ("Blue", "0;34"), ("Purple", "0;35"), ("Cyan", "0;36"), ("LightGray", "0;37"), ("DarkGray", "1;30"), ("LightRed", "1;31"), ("LightGreen", "1;32"), ("Yellow", "1;33"), ("LightBlue", "1;34"), ("LightPurple", "1;35"), ("LightCyan", "1;36"), ("White", "1;37"), ) colors = {} for name, value in color_templates: colors[name] = value c_normal = '\033[0m' c_color = '\033[%sm' if width is None: width = self.terminal_width if align == "right": if self._write_pos + len(text) > width: # we don't fit on the current line, create a new line self.write("\n") self.write(" "*(width - self._write_pos - len(text))) if not self._force_colors and hasattr(sys.stdout, 'isatty') and not \ sys.stdout.isatty(): # the stdout is not a terminal, this for example happens if the # output is piped to less, e.g. "bin/test | less". In this case, # the terminal control sequences would be printed verbatim, so # don't use any colors. color = "" elif sys.platform == "win32": # Windows consoles don't support ANSI escape sequences color = "" elif not self._colors: color = "" if self._line_wrap: if text[0] != "\n": sys.stdout.write("\n") # Avoid UnicodeEncodeError when printing out test failures if IS_WINDOWS: text = text.encode('raw_unicode_escape').decode('utf8', 'ignore') elif not sys.stdout.encoding.lower().startswith('utf'): text = text.encode(sys.stdout.encoding, 'backslashreplace' ).decode(sys.stdout.encoding) if color == "": sys.stdout.write(text) else: sys.stdout.write("%s%s%s" % (c_color % colors[color], text, c_normal)) sys.stdout.flush() l = text.rfind("\n") if l == -1: self._write_pos += len(text) else: self._write_pos = len(text) - l - 1 self._line_wrap = self._write_pos >= width self._write_pos %= width def write_center(self, text, delim="="): width = self.terminal_width if text != "": text = " %s " % text idx = (width - len(text)) // 2 t = delim*idx + text + delim*(width - idx - len(text)) self.write(t + "\n") def write_exception(self, e, val, tb): # remove the first item, as that is always runtests.py tb = tb.tb_next t = traceback.format_exception(e, val, tb) self.write("".join(t)) def start(self, seed=None, msg="test process starts"): self.write_center(msg) executable = sys.executable v = tuple(sys.version_info) python_version = "%s.%s.%s-%s-%s" % v implementation = platform.python_implementation() if implementation == 'PyPy': implementation += " %s.%s.%s-%s-%s" % sys.pypy_version_info self.write("executable: %s (%s) [%s]\n" % (executable, python_version, implementation)) from sympy.utilities.misc import ARCH self.write("architecture: %s\n" % ARCH) from sympy.core.cache import USE_CACHE self.write("cache: %s\n" % USE_CACHE) version = '' if GROUND_TYPES =='gmpy': if HAS_GMPY == 1: import gmpy elif HAS_GMPY == 2: import gmpy2 as gmpy version = gmpy.version() self.write("ground types: %s %s\n" % (GROUND_TYPES, version)) numpy = import_module('numpy') self.write("numpy: %s\n" % (None if not numpy else numpy.__version__)) if seed is not None: self.write("random seed: %d\n" % seed) from sympy.utilities.misc import HASH_RANDOMIZATION self.write("hash randomization: ") hash_seed = os.getenv("PYTHONHASHSEED") or '0' if HASH_RANDOMIZATION and (hash_seed == "random" or int(hash_seed)): self.write("on (PYTHONHASHSEED=%s)\n" % hash_seed) else: self.write("off\n") if self._split: self.write("split: %s\n" % self._split) self.write('\n') self._t_start = clock() def finish(self): self._t_end = clock() self.write("\n") global text, linelen text = "tests finished: %d passed, " % self._passed linelen = len(text) def add_text(mytext): global text, linelen """Break new text if too long.""" if linelen + len(mytext) > self.terminal_width: text += '\n' linelen = 0 text += mytext linelen += len(mytext) if len(self._failed) > 0: add_text("%d failed, " % len(self._failed)) if len(self._failed_doctest) > 0: add_text("%d failed, " % len(self._failed_doctest)) if self._skipped > 0: add_text("%d skipped, " % self._skipped) if self._xfailed > 0: add_text("%d expected to fail, " % self._xfailed) if len(self._xpassed) > 0: add_text("%d expected to fail but passed, " % len(self._xpassed)) if len(self._exceptions) > 0: add_text("%d exceptions, " % len(self._exceptions)) add_text("in %.2f seconds" % (self._t_end - self._t_start)) if self.slow_test_functions: self.write_center('slowest tests', '_') sorted_slow = sorted(self.slow_test_functions, key=lambda r: r[1]) for slow_func_name, taken in sorted_slow: print('%s - Took %.3f seconds' % (slow_func_name, taken)) if self.fast_test_functions: self.write_center('unexpectedly fast tests', '_') sorted_fast = sorted(self.fast_test_functions, key=lambda r: r[1]) for fast_func_name, taken in sorted_fast: print('%s - Took %.3f seconds' % (fast_func_name, taken)) if len(self._xpassed) > 0: self.write_center("xpassed tests", "_") for e in self._xpassed: self.write("%s: %s\n" % (e[0], e[1])) self.write("\n") if self._tb_style != "no" and len(self._exceptions) > 0: for e in self._exceptions: filename, f, (t, val, tb) = e self.write_center("", "_") if f is None: s = "%s" % filename else: s = "%s:%s" % (filename, f.__name__) self.write_center(s, "_") self.write_exception(t, val, tb) self.write("\n") if self._tb_style != "no" and len(self._failed) > 0: for e in self._failed: filename, f, (t, val, tb) = e self.write_center("", "_") self.write_center("%s:%s" % (filename, f.__name__), "_") self.write_exception(t, val, tb) self.write("\n") if self._tb_style != "no" and len(self._failed_doctest) > 0: for e in self._failed_doctest: filename, msg = e self.write_center("", "_") self.write_center("%s" % filename, "_") self.write(msg) self.write("\n") self.write_center(text) ok = len(self._failed) == 0 and len(self._exceptions) == 0 and \ len(self._failed_doctest) == 0 if not ok: self.write("DO *NOT* COMMIT!\n") return ok def entering_filename(self, filename, n): rel_name = filename[len(self._root_dir) + 1:] self._active_file = rel_name self._active_file_error = False self.write(rel_name) self.write("[%d] " % n) def leaving_filename(self): self.write(" ") if self._active_file_error: self.write("[FAIL]", "Red", align="right") else: self.write("[OK]", "Green", align="right") self.write("\n") if self._verbose: self.write("\n") def entering_test(self, f): self._active_f = f if self._verbose: self.write("\n" + f.__name__ + " ") def test_xfail(self): self._xfailed += 1 self.write("f", "Green") def test_xpass(self, v): message = str(v) self._xpassed.append((self._active_file, message)) self.write("X", "Green") def test_fail(self, exc_info): self._failed.append((self._active_file, self._active_f, exc_info)) self.write("F", "Red") self._active_file_error = True def doctest_fail(self, name, error_msg): # the first line contains "******", remove it: error_msg = "\n".join(error_msg.split("\n")[1:]) self._failed_doctest.append((name, error_msg)) self.write("F", "Red") self._active_file_error = True def test_pass(self, char="."): self._passed += 1 if self._verbose: self.write("ok", "Green") else: self.write(char, "Green") def test_skip(self, v=None): char = "s" self._skipped += 1 if v is not None: message = str(v) if message == "KeyboardInterrupt": char = "K" elif message == "Timeout": char = "T" elif message == "Slow": char = "w" if self._verbose: if v is not None: self.write(message + ' ', "Blue") else: self.write(" - ", "Blue") self.write(char, "Blue") def test_exception(self, exc_info): self._exceptions.append((self._active_file, self._active_f, exc_info)) if exc_info[0] is TimeOutError: self.write("T", "Red") else: self.write("E", "Red") self._active_file_error = True def import_error(self, filename, exc_info): self._exceptions.append((filename, None, exc_info)) rel_name = filename[len(self._root_dir) + 1:] self.write(rel_name) self.write("[?] Failed to import", "Red") self.write(" ") self.write("[FAIL]", "Red", align="right") self.write("\n")
c037494c2f67aa63ac763c5ee58216f7b13774a960ffead739ec0e7fc0321b7f
import re import typing from itertools import product from typing import Any, Dict as tDict, Tuple as tTuple, List, Optional, Union as tUnion, Callable import sympy from sympy import Mul, Add, Pow, log, exp, sqrt, cos, sin, tan, asin, acos, acot, asec, acsc, sinh, cosh, tanh, asinh, \ acosh, atanh, acoth, asech, acsch, expand, im, flatten, polylog, cancel, expand_trig, sign, simplify, \ UnevaluatedExpr, S, atan, atan2, Mod, Max, Min, rf, Ei, Si, Ci, airyai, airyaiprime, airybi, primepi, prime, \ isprime, cot, sec, csc, csch, sech, coth, Function, I, pi, Tuple, GreaterThan, StrictGreaterThan, StrictLessThan, \ LessThan, Equality, Or, And, Lambda, Integer, Dummy, symbols from sympy.core.sympify import sympify, _sympify from sympy.functions.special.bessel import airybiprime from sympy.functions.special.error_functions import li from sympy.utilities.exceptions import sympy_deprecation_warning def mathematica(s, additional_translations=None): sympy_deprecation_warning( """The ``mathematica`` function for the Mathematica parser is now deprecated. Use ``parse_mathematica`` instead. The parameter ``additional_translation`` can be replaced by SymPy's .replace( ) or .subs( ) methods on the output expression instead.""", deprecated_since_version="1.11", active_deprecations_target="mathematica-parser-new", ) parser = MathematicaParser(additional_translations) return sympify(parser._parse_old(s)) def parse_mathematica(s): """ Translate a string containing a Wolfram Mathematica expression to a SymPy expression. If the translator is unable to find a suitable SymPy expression, the ``FullForm`` of the Mathematica expression will be output, using SymPy ``Function`` objects as nodes of the syntax tree. Examples ======== >>> from sympy.parsing.mathematica import parse_mathematica >>> parse_mathematica("Sin[x]^2 Tan[y]") sin(x)**2*tan(y) >>> e = parse_mathematica("F[7,5,3]") >>> e F(7, 5, 3) >>> from sympy import Function, Max, Min >>> e.replace(Function("F"), lambda *x: Max(*x)*Min(*x)) 21 Both standard input form and Mathematica full form are supported: >>> parse_mathematica("x*(a + b)") x*(a + b) >>> parse_mathematica("Times[x, Plus[a, b]]") x*(a + b) To get a matrix from Wolfram's code: >>> m = parse_mathematica("{{a, b}, {c, d}}") >>> m ((a, b), (c, d)) >>> from sympy import Matrix >>> Matrix(m) Matrix([ [a, b], [c, d]]) If the translation into equivalent SymPy expressions fails, an SymPy expression equivalent to Wolfram Mathematica's "FullForm" will be created: >>> parse_mathematica("x_.") Optional(Pattern(x, Blank())) >>> parse_mathematica("Plus @@ {x, y, z}") Apply(Plus, (x, y, z)) >>> parse_mathematica("f[x_, 3] := x^3 /; x > 0") SetDelayed(f(Pattern(x, Blank()), 3), Condition(x**3, x > 0)) """ parser = MathematicaParser() return parser.parse(s) def _parse_Function(*args): if len(args) == 1: arg = args[0] Slot = Function("Slot") slots = arg.atoms(Slot) numbers = [a.args[0] for a in slots] number_of_arguments = max(numbers) if isinstance(number_of_arguments, Integer): variables = symbols(f"dummy0:{number_of_arguments}", cls=Dummy) return Lambda(variables, arg.xreplace({Slot(i+1): v for i, v in enumerate(variables)})) return Lambda((), arg) elif len(args) == 2: variables = args[0] body = args[1] return Lambda(variables, body) else: raise SyntaxError("Function node expects 1 or 2 arguments") def _deco(cls): cls._initialize_class() return cls @_deco class MathematicaParser: """ An instance of this class converts a string of a Wolfram Mathematica expression to a SymPy expression. The main parser acts internally in three stages: 1. tokenizer: tokenizes the Mathematica expression and adds the missing * operators. Handled by ``_from_mathematica_to_tokens(...)`` 2. full form list: sort the list of strings output by the tokenizer into a syntax tree of nested lists and strings, equivalent to Mathematica's ``FullForm`` expression output. This is handled by the function ``_from_tokens_to_fullformlist(...)``. 3. SymPy expression: the syntax tree expressed as full form list is visited and the nodes with equivalent classes in SymPy are replaced. Unknown syntax tree nodes are cast to SymPy ``Function`` objects. This is handled by ``_from_fullformlist_to_sympy(...)``. """ # left: Mathematica, right: SymPy CORRESPONDENCES = { 'Sqrt[x]': 'sqrt(x)', 'Exp[x]': 'exp(x)', 'Log[x]': 'log(x)', 'Log[x,y]': 'log(y,x)', 'Log2[x]': 'log(x,2)', 'Log10[x]': 'log(x,10)', 'Mod[x,y]': 'Mod(x,y)', 'Max[*x]': 'Max(*x)', 'Min[*x]': 'Min(*x)', 'Pochhammer[x,y]':'rf(x,y)', 'ArcTan[x,y]':'atan2(y,x)', 'ExpIntegralEi[x]': 'Ei(x)', 'SinIntegral[x]': 'Si(x)', 'CosIntegral[x]': 'Ci(x)', 'AiryAi[x]': 'airyai(x)', 'AiryAiPrime[x]': 'airyaiprime(x)', 'AiryBi[x]' :'airybi(x)', 'AiryBiPrime[x]' :'airybiprime(x)', 'LogIntegral[x]':' li(x)', 'PrimePi[x]': 'primepi(x)', 'Prime[x]': 'prime(x)', 'PrimeQ[x]': 'isprime(x)' } # trigonometric, e.t.c. for arc, tri, h in product(('', 'Arc'), ( 'Sin', 'Cos', 'Tan', 'Cot', 'Sec', 'Csc'), ('', 'h')): fm = arc + tri + h + '[x]' if arc: # arc func fs = 'a' + tri.lower() + h + '(x)' else: # non-arc func fs = tri.lower() + h + '(x)' CORRESPONDENCES.update({fm: fs}) REPLACEMENTS = { ' ': '', '^': '**', '{': '[', '}': ']', } RULES = { # a single whitespace to '*' 'whitespace': ( re.compile(r''' (?:(?<=[a-zA-Z\d])|(?<=\d\.)) # a letter or a number \s+ # any number of whitespaces (?:(?=[a-zA-Z\d])|(?=\.\d)) # a letter or a number ''', re.VERBOSE), '*'), # add omitted '*' character 'add*_1': ( re.compile(r''' (?:(?<=[])\d])|(?<=\d\.)) # ], ) or a number # '' (?=[(a-zA-Z]) # ( or a single letter ''', re.VERBOSE), '*'), # add omitted '*' character (variable letter preceding) 'add*_2': ( re.compile(r''' (?<=[a-zA-Z]) # a letter \( # ( as a character (?=.) # any characters ''', re.VERBOSE), '*('), # convert 'Pi' to 'pi' 'Pi': ( re.compile(r''' (?: \A|(?<=[^a-zA-Z]) ) Pi # 'Pi' is 3.14159... in Mathematica (?=[^a-zA-Z]) ''', re.VERBOSE), 'pi'), } # Mathematica function name pattern FM_PATTERN = re.compile(r''' (?: \A|(?<=[^a-zA-Z]) # at the top or a non-letter ) [A-Z][a-zA-Z\d]* # Function (?=\[) # [ as a character ''', re.VERBOSE) # list or matrix pattern (for future usage) ARG_MTRX_PATTERN = re.compile(r''' \{.*\} ''', re.VERBOSE) # regex string for function argument pattern ARGS_PATTERN_TEMPLATE = r''' (?: \A|(?<=[^a-zA-Z]) ) {arguments} # model argument like x, y,... (?=[^a-zA-Z]) ''' # will contain transformed CORRESPONDENCES dictionary TRANSLATIONS = {} # type: tDict[tTuple[str, int], tDict[str, Any]] # cache for a raw users' translation dictionary cache_original = {} # type: tDict[tTuple[str, int], tDict[str, Any]] # cache for a compiled users' translation dictionary cache_compiled = {} # type: tDict[tTuple[str, int], tDict[str, Any]] @classmethod def _initialize_class(cls): # get a transformed CORRESPONDENCES dictionary d = cls._compile_dictionary(cls.CORRESPONDENCES) cls.TRANSLATIONS.update(d) def __init__(self, additional_translations=None): self.translations = {} # update with TRANSLATIONS (class constant) self.translations.update(self.TRANSLATIONS) if additional_translations is None: additional_translations = {} # check the latest added translations if self.__class__.cache_original != additional_translations: if not isinstance(additional_translations, dict): raise ValueError('The argument must be dict type') # get a transformed additional_translations dictionary d = self._compile_dictionary(additional_translations) # update cache self.__class__.cache_original = additional_translations self.__class__.cache_compiled = d # merge user's own translations self.translations.update(self.__class__.cache_compiled) @classmethod def _compile_dictionary(cls, dic): # for return d = {} for fm, fs in dic.items(): # check function form cls._check_input(fm) cls._check_input(fs) # uncover '*' hiding behind a whitespace fm = cls._apply_rules(fm, 'whitespace') fs = cls._apply_rules(fs, 'whitespace') # remove whitespace(s) fm = cls._replace(fm, ' ') fs = cls._replace(fs, ' ') # search Mathematica function name m = cls.FM_PATTERN.search(fm) # if no-hit if m is None: err = "'{f}' function form is invalid.".format(f=fm) raise ValueError(err) # get Mathematica function name like 'Log' fm_name = m.group() # get arguments of Mathematica function args, end = cls._get_args(m) # function side check. (e.g.) '2*Func[x]' is invalid. if m.start() != 0 or end != len(fm): err = "'{f}' function form is invalid.".format(f=fm) raise ValueError(err) # check the last argument's 1st character if args[-1][0] == '*': key_arg = '*' else: key_arg = len(args) key = (fm_name, key_arg) # convert '*x' to '\\*x' for regex re_args = [x if x[0] != '*' else '\\' + x for x in args] # for regex. Example: (?:(x|y|z)) xyz = '(?:(' + '|'.join(re_args) + '))' # string for regex compile patStr = cls.ARGS_PATTERN_TEMPLATE.format(arguments=xyz) pat = re.compile(patStr, re.VERBOSE) # update dictionary d[key] = {} d[key]['fs'] = fs # SymPy function template d[key]['args'] = args # args are ['x', 'y'] for example d[key]['pat'] = pat return d def _convert_function(self, s): '''Parse Mathematica function to SymPy one''' # compiled regex object pat = self.FM_PATTERN scanned = '' # converted string cur = 0 # position cursor while True: m = pat.search(s) if m is None: # append the rest of string scanned += s break # get Mathematica function name fm = m.group() # get arguments, and the end position of fm function args, end = self._get_args(m) # the start position of fm function bgn = m.start() # convert Mathematica function to SymPy one s = self._convert_one_function(s, fm, args, bgn, end) # update cursor cur = bgn # append converted part scanned += s[:cur] # shrink s s = s[cur:] return scanned def _convert_one_function(self, s, fm, args, bgn, end): # no variable-length argument if (fm, len(args)) in self.translations: key = (fm, len(args)) # x, y,... model arguments x_args = self.translations[key]['args'] # make CORRESPONDENCES between model arguments and actual ones d = {k: v for k, v in zip(x_args, args)} # with variable-length argument elif (fm, '*') in self.translations: key = (fm, '*') # x, y,..*args (model arguments) x_args = self.translations[key]['args'] # make CORRESPONDENCES between model arguments and actual ones d = {} for i, x in enumerate(x_args): if x[0] == '*': d[x] = ','.join(args[i:]) break d[x] = args[i] # out of self.translations else: err = "'{f}' is out of the whitelist.".format(f=fm) raise ValueError(err) # template string of converted function template = self.translations[key]['fs'] # regex pattern for x_args pat = self.translations[key]['pat'] scanned = '' cur = 0 while True: m = pat.search(template) if m is None: scanned += template break # get model argument x = m.group() # get a start position of the model argument xbgn = m.start() # add the corresponding actual argument scanned += template[:xbgn] + d[x] # update cursor to the end of the model argument cur = m.end() # shrink template template = template[cur:] # update to swapped string s = s[:bgn] + scanned + s[end:] return s @classmethod def _get_args(cls, m): '''Get arguments of a Mathematica function''' s = m.string # whole string anc = m.end() + 1 # pointing the first letter of arguments square, curly = [], [] # stack for brakets args = [] # current cursor cur = anc for i, c in enumerate(s[anc:], anc): # extract one argument if c == ',' and (not square) and (not curly): args.append(s[cur:i]) # add an argument cur = i + 1 # move cursor # handle list or matrix (for future usage) if c == '{': curly.append(c) elif c == '}': curly.pop() # seek corresponding ']' with skipping irrevant ones if c == '[': square.append(c) elif c == ']': if square: square.pop() else: # empty stack args.append(s[cur:i]) break # the next position to ']' bracket (the function end) func_end = i + 1 return args, func_end @classmethod def _replace(cls, s, bef): aft = cls.REPLACEMENTS[bef] s = s.replace(bef, aft) return s @classmethod def _apply_rules(cls, s, bef): pat, aft = cls.RULES[bef] return pat.sub(aft, s) @classmethod def _check_input(cls, s): for bracket in (('[', ']'), ('{', '}'), ('(', ')')): if s.count(bracket[0]) != s.count(bracket[1]): err = "'{f}' function form is invalid.".format(f=s) raise ValueError(err) if '{' in s: err = "Currently list is not supported." raise ValueError(err) def _parse_old(self, s): # input check self._check_input(s) # uncover '*' hiding behind a whitespace s = self._apply_rules(s, 'whitespace') # remove whitespace(s) s = self._replace(s, ' ') # add omitted '*' character s = self._apply_rules(s, 'add*_1') s = self._apply_rules(s, 'add*_2') # translate function s = self._convert_function(s) # '^' to '**' s = self._replace(s, '^') # 'Pi' to 'pi' s = self._apply_rules(s, 'Pi') # '{', '}' to '[', ']', respectively # s = cls._replace(s, '{') # currently list is not taken into account # s = cls._replace(s, '}') return s def parse(self, s): s2 = self._from_mathematica_to_tokens(s) s3 = self._from_tokens_to_fullformlist(s2) s4 = self._from_fullformlist_to_sympy(s3) return s4 INFIX = "Infix" PREFIX = "Prefix" POSTFIX = "Postfix" FLAT = "Flat" RIGHT = "Right" LEFT = "Left" _mathematica_op_precedence: List[tTuple[str, Optional[str], tDict[str, tUnion[str, Callable]]]] = [ (POSTFIX, None, {";": lambda x: x + ["Null"] if isinstance(x, list) and x and x[0] == "CompoundExpression" else ["CompoundExpression", x, "Null"]}), (INFIX, FLAT, {";": "CompoundExpression"}), (INFIX, RIGHT, {"=": "Set", ":=": "SetDelayed", "+=": "AddTo", "-=": "SubtractFrom", "*=": "TimesBy", "/=": "DivideBy"}), (INFIX, LEFT, {"//": lambda x, y: [x, y]}), (POSTFIX, None, {"&": "Function"}), (INFIX, LEFT, {"/.": "ReplaceAll"}), (INFIX, RIGHT, {"->": "Rule", ":>": "RuleDelayed"}), (INFIX, LEFT, {"/;": "Condition"}), (INFIX, FLAT, {"|": "Alternatives"}), (POSTFIX, None, {"..": "Repeated", "...": "RepeatedNull"}), (INFIX, FLAT, {"||": "Or"}), (INFIX, FLAT, {"&&": "And"}), (PREFIX, None, {"!": "Not"}), (INFIX, FLAT, {"===": "SameQ", "=!=": "UnsameQ"}), (INFIX, FLAT, {"==": "Equal", "!=": "Unequal", "<=": "LessEqual", "<": "Less", ">=": "GreaterEqual", ">": "Greater"}), (INFIX, None, {";;": "Span"}), (INFIX, FLAT, {"+": "Plus", "-": "Plus"}), (INFIX, FLAT, {"*": "Times", "/": "Times"}), (INFIX, FLAT, {".": "Dot"}), (PREFIX, None, {"-": lambda x: MathematicaParser._get_neg(x), "+": lambda x: x}), (INFIX, RIGHT, {"^": "Power"}), (INFIX, RIGHT, {"@@": "Apply", "/@": "Map", "//@": "MapAll", "@@@": lambda x, y: ["Apply", x, y, ["List", "1"]]}), (POSTFIX, None, {"'": "Derivative", "!": "Factorial", "!!": "Factorial2", "--": "Decrement"}), (INFIX, None, {"[": lambda x, y: [x, *y], "[[": lambda x, y: ["Part", x, *y]}), (PREFIX, None, {"{": lambda x: ["List", *x], "(": lambda x: x[0]}), (INFIX, None, {"?": "PatternTest"}), (POSTFIX, None, { "_": lambda x: ["Pattern", x, ["Blank"]], "_.": lambda x: ["Optional", ["Pattern", x, ["Blank"]]], "__": lambda x: ["Pattern", x, ["BlankSequence"]], "___": lambda x: ["Pattern", x, ["BlankNullSequence"]], }), (INFIX, None, {"_": lambda x, y: ["Pattern", x, ["Blank", y]]}), (PREFIX, None, {"#": "Slot", "##": "SlotSequence"}), ] _missing_arguments_default = { "#": lambda: ["Slot", "1"], "##": lambda: ["SlotSequence", "1"], } _literal = r"[A-Za-z][A-Za-z0-9]*" _number = r"(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)" _enclosure_open = ["(", "[", "[[", "{"] _enclosure_close = [")", "]", "]]", "}"] @classmethod def _get_neg(cls, x): return f"-{x}" if isinstance(x, str) and re.match(MathematicaParser._number, x) else ["Times", "-1", x] @classmethod def _get_inv(cls, x): return ["Power", x, "-1"] _regex_tokenizer = None def _get_tokenizer(self): if self._regex_tokenizer is not None: # Check if the regular expression has already been compiled: return self._regex_tokenizer tokens = [self._literal, self._number] tokens_escape = self._enclosure_open[:] + self._enclosure_close[:] for typ, strat, symdict in self._mathematica_op_precedence: for k in symdict: tokens_escape.append(k) tokens_escape.sort(key=lambda x: -len(x)) tokens.extend(map(re.escape, tokens_escape)) tokens.append(",") tokens.append("\n") tokenizer = re.compile("(" + "|".join(tokens) + ")") self._regex_tokenizer = tokenizer return self._regex_tokenizer def _from_mathematica_to_tokens(self, code: str): tokenizer = self._get_tokenizer() # Find strings: code_splits: List[typing.Union[str, list]] = [] while True: string_start = code.find("\"") if string_start == -1: if len(code) > 0: code_splits.append(code) break match_end = re.search(r'(?<!\\)"', code[string_start+1:]) if match_end is None: raise SyntaxError('mismatch in string " " expression') string_end = string_start + match_end.start() + 1 if string_start > 0: code_splits.append(code[:string_start]) code_splits.append(["_Str", code[string_start+1:string_end].replace('\\"', '"')]) code = code[string_end+1:] # Remove comments: for i, code_split in enumerate(code_splits): if isinstance(code_split, list): continue while True: pos_comment_start = code_split.find("(*") if pos_comment_start == -1: break pos_comment_end = code_split.find("*)") if pos_comment_end == -1 or pos_comment_end < pos_comment_start: raise SyntaxError("mismatch in comment (* *) code") code_split = code_split[:pos_comment_start] + code_split[pos_comment_end+2:] code_splits[i] = code_split # Tokenize the input strings with a regular expression: token_lists = [tokenizer.findall(i) if isinstance(i, str) and i.isascii() else [i] for i in code_splits] tokens = [j for i in token_lists for j in i] # Remove newlines at the beginning while tokens and tokens[0] == "\n": tokens.pop(0) # Remove newlines at the end while tokens and tokens[-1] == "\n": tokens.pop(-1) return tokens def _is_op(self, token: tUnion[str, list]) -> bool: if isinstance(token, list): return False if re.match(self._literal, token): return False if re.match("-?" + self._number, token): return False return True def _is_valid_star1(self, token: tUnion[str, list]) -> bool: if token in (")", "}"): return True return not self._is_op(token) def _is_valid_star2(self, token: tUnion[str, list]) -> bool: if token in ("(", "{"): return True return not self._is_op(token) def _from_tokens_to_fullformlist(self, tokens: list): stack: List[list] = [[]] open_seq = [] pointer: int = 0 while pointer < len(tokens): token = tokens[pointer] if token in self._enclosure_open: stack[-1].append(token) open_seq.append(token) stack.append([]) elif token == ",": if len(stack[-1]) == 0 and stack[-2][-1] == open_seq[-1]: raise SyntaxError("%s cannot be followed by comma ," % open_seq[-1]) stack[-1] = self._parse_after_braces(stack[-1]) stack.append([]) elif token in self._enclosure_close: ind = self._enclosure_close.index(token) if self._enclosure_open[ind] != open_seq[-1]: unmatched_enclosure = SyntaxError("unmatched enclosure") if token == "]]" and open_seq[-1] == "[": if open_seq[-2] == "[": # These two lines would be logically correct, but are # unnecessary: # token = "]" # tokens[pointer] = "]" tokens.insert(pointer+1, "]") elif open_seq[-2] == "[[": if tokens[pointer+1] == "]": tokens[pointer+1] = "]]" elif tokens[pointer+1] == "]]": tokens[pointer+1] = "]]" tokens.insert(pointer+2, "]") else: raise unmatched_enclosure else: raise unmatched_enclosure if len(stack[-1]) == 0 and stack[-2][-1] == "(": raise SyntaxError("( ) not valid syntax") last_stack = self._parse_after_braces(stack[-1], True) stack[-1] = last_stack new_stack_element = [] while stack[-1][-1] != open_seq[-1]: new_stack_element.append(stack.pop()) new_stack_element.reverse() if open_seq[-1] == "(" and len(new_stack_element) != 1: raise SyntaxError("( must be followed by one expression, %i detected" % len(new_stack_element)) stack[-1].append(new_stack_element) open_seq.pop(-1) else: stack[-1].append(token) pointer += 1 assert len(stack) == 1 return self._parse_after_braces(stack[0]) def _util_remove_newlines(self, lines: list, tokens: list, inside_enclosure: bool): pointer = 0 size = len(tokens) while pointer < size: token = tokens[pointer] if token == "\n": if inside_enclosure: # Ignore newlines inside enclosures tokens.pop(pointer) size -= 1 continue if pointer == 0: tokens.pop(0) size -= 1 continue if pointer > 1: try: prev_expr = self._parse_after_braces(tokens[:pointer], inside_enclosure) except SyntaxError: tokens.pop(pointer) size -= 1 continue else: prev_expr = tokens[0] if len(prev_expr) > 0 and prev_expr[0] == "CompoundExpression": lines.extend(prev_expr[1:]) else: lines.append(prev_expr) for i in range(pointer): tokens.pop(0) size -= pointer pointer = 0 continue pointer += 1 def _util_add_missing_asterisks(self, tokens: list): size: int = len(tokens) pointer: int = 0 while pointer < size: if (pointer > 0 and self._is_valid_star1(tokens[pointer - 1]) and self._is_valid_star2(tokens[pointer])): # This is a trick to add missing * operators in the expression, # `"*" in op_dict` makes sure the precedence level is the same as "*", # while `not self._is_op( ... )` makes sure this and the previous # expression are not operators. if tokens[pointer] == "(": # ( has already been processed by now, replace: tokens[pointer] = "*" tokens[pointer + 1] = tokens[pointer + 1][0] else: tokens.insert(pointer, "*") pointer += 1 size += 1 pointer += 1 def _parse_after_braces(self, tokens: list, inside_enclosure: bool = False): op_dict: dict changed: bool = False lines: list = [] self._util_remove_newlines(lines, tokens, inside_enclosure) for op_type, grouping_strat, op_dict in reversed(self._mathematica_op_precedence): if "*" in op_dict: self._util_add_missing_asterisks(tokens) size: int = len(tokens) pointer: int = 0 while pointer < size: token = tokens[pointer] if isinstance(token, str) and token in op_dict: op_name: tUnion[str, Callable] = op_dict[token] node: list first_index: int if isinstance(op_name, str): node = [op_name] first_index = 1 else: node = [] first_index = 0 if token in ("+", "-") and op_type == self.PREFIX and pointer > 0 and not self._is_op(tokens[pointer - 1]): # Make sure that PREFIX + - don't match expressions like a + b or a - b, # the INFIX + - are supposed to match that expression: pointer += 1 continue if op_type == self.INFIX: if pointer == 0 or pointer == size - 1 or self._is_op(tokens[pointer - 1]) or self._is_op(tokens[pointer + 1]): pointer += 1 continue changed = True tokens[pointer] = node if op_type == self.INFIX: arg1 = tokens.pop(pointer-1) arg2 = tokens.pop(pointer) if token == "/": arg2 = self._get_inv(arg2) elif token == "-": arg2 = self._get_neg(arg2) pointer -= 1 size -= 2 node.append(arg1) node_p = node if grouping_strat == self.FLAT: while pointer + 2 < size and self._check_op_compatible(tokens[pointer+1], token): node_p.append(arg2) other_op = tokens.pop(pointer+1) arg2 = tokens.pop(pointer+1) if other_op == "/": arg2 = self._get_inv(arg2) elif other_op == "-": arg2 = self._get_neg(arg2) size -= 2 node_p.append(arg2) elif grouping_strat == self.RIGHT: while pointer + 2 < size and tokens[pointer+1] == token: node_p.append([op_name, arg2]) node_p = node_p[-1] tokens.pop(pointer+1) arg2 = tokens.pop(pointer+1) size -= 2 node_p.append(arg2) elif grouping_strat == self.LEFT: while pointer + 1 < size and tokens[pointer+1] == token: if isinstance(op_name, str): node_p[first_index] = [op_name, node_p[first_index], arg2] else: node_p[first_index] = op_name(node_p[first_index], arg2) tokens.pop(pointer+1) arg2 = tokens.pop(pointer+1) size -= 2 node_p.append(arg2) else: node.append(arg2) elif op_type == self.PREFIX: assert grouping_strat is None if pointer == size - 1 or self._is_op(tokens[pointer + 1]): tokens[pointer] = self._missing_arguments_default[token]() else: node.append(tokens.pop(pointer+1)) size -= 1 elif op_type == self.POSTFIX: assert grouping_strat is None if pointer == 0 or self._is_op(tokens[pointer - 1]): tokens[pointer] = self._missing_arguments_default[token]() else: node.append(tokens.pop(pointer-1)) pointer -= 1 size -= 1 if isinstance(op_name, Callable): # type: ignore op_call: Callable = typing.cast(Callable, op_name) new_node = op_call(*node) node.clear() if isinstance(new_node, list): node.extend(new_node) else: tokens[pointer] = new_node pointer += 1 if len(tokens) > 1 or (len(lines) == 0 and len(tokens) == 0): if changed: # Trick to deal with cases in which an operator with lower # precedence should be transformed before an operator of higher # precedence. Such as in the case of `#&[x]` (that is # equivalent to `Lambda(d_, d_)(x)` in SymPy). In this case the # operator `&` has lower precedence than `[`, but needs to be # evaluated first because otherwise `# (&[x])` is not a valid # expression: return self._parse_after_braces(tokens, inside_enclosure) raise SyntaxError("unable to create a single AST for the expression") if len(lines) > 0: if tokens[0] and tokens[0][0] == "CompoundExpression": tokens = tokens[0][1:] compound_expression = ["CompoundExpression", *lines, *tokens] return compound_expression return tokens[0] def _check_op_compatible(self, op1: str, op2: str): if op1 == op2: return True muldiv = {"*", "/"} addsub = {"+", "-"} if op1 in muldiv and op2 in muldiv: return True if op1 in addsub and op2 in addsub: return True return False def _from_fullform_to_fullformlist(self, wmexpr: str): """ Parses FullForm[Downvalues[]] generated by Mathematica """ out: list = [] stack = [out] generator = re.finditer(r'[\[\],]', wmexpr) last_pos = 0 for match in generator: if match is None: break position = match.start() last_expr = wmexpr[last_pos:position].replace(',', '').replace(']', '').replace('[', '').strip() if match.group() == ',': if last_expr != '': stack[-1].append(last_expr) elif match.group() == ']': if last_expr != '': stack[-1].append(last_expr) stack.pop() elif match.group() == '[': stack[-1].append([last_expr]) stack.append(stack[-1][-1]) last_pos = match.end() return out[0] def _from_fullformlist_to_fullformsympy(self, pylist: list): from sympy import Function, Symbol def converter(expr): if isinstance(expr, list): if len(expr) > 0: head = expr[0] args = [converter(arg) for arg in expr[1:]] return Function(head)(*args) else: raise ValueError("Empty list of expressions") elif isinstance(expr, str): return Symbol(expr) else: return _sympify(expr) return converter(pylist) _node_conversions = dict( Times=Mul, Plus=Add, Power=Pow, Log=lambda *a: log(*reversed(a)), Log2=lambda x: log(x, 2), Log10=lambda x: log(x, 10), Exp=exp, Sqrt=sqrt, Sin=sin, Cos=cos, Tan=tan, Cot=cot, Sec=sec, Csc=csc, ArcSin=asin, ArcCos=acos, ArcTan=lambda *a: atan2(*reversed(a)) if len(a) == 2 else atan(*a), ArcCot=acot, ArcSec=asec, ArcCsc=acsc, Sinh=sinh, Cosh=cosh, Tanh=tanh, Coth=coth, Sech=sech, Csch=csch, ArcSinh=asinh, ArcCosh=acosh, ArcTanh=atanh, ArcCoth=acoth, ArcSech=asech, ArcCsch=acsch, Expand=expand, Im=im, Re=sympy.re, Flatten=flatten, Polylog=polylog, Cancel=cancel, # Gamma=gamma, TrigExpand=expand_trig, Sign=sign, Simplify=simplify, Defer=UnevaluatedExpr, Identity=S, # Sum=Sum_doit, # Module=With, # Block=With, Null=lambda *a: S.Zero, Mod=Mod, Max=Max, Min=Min, Pochhammer=rf, ExpIntegralEi=Ei, SinIntegral=Si, CosIntegral=Ci, AiryAi=airyai, AiryAiPrime=airyaiprime, AiryBi=airybi, AiryBiPrime=airybiprime, LogIntegral=li, PrimePi=primepi, Prime=prime, PrimeQ=isprime, List=Tuple, Greater=StrictGreaterThan, GreaterEqual=GreaterThan, Less=StrictLessThan, LessEqual=LessThan, Equal=Equality, Or=Or, And=And, Function=_parse_Function, ) _atom_conversions = { "I": I, "Pi": pi, } def _from_fullformlist_to_sympy(self, full_form_list): def recurse(expr): if isinstance(expr, list): if isinstance(expr[0], list): head = recurse(expr[0]) else: head = self._node_conversions.get(expr[0], Function(expr[0])) return head(*list(recurse(arg) for arg in expr[1:])) else: return self._atom_conversions.get(expr, sympify(expr)) return recurse(full_form_list) def _from_fullformsympy_to_sympy(self, mform): expr = mform for mma_form, sympy_node in self._node_conversions.items(): expr = expr.replace(Function(mma_form), sympy_node) return expr
2ff37db81b07660d2087f85d8ea8adc80856b2b9b2790d954296a14e7156131a
"""Transform a string with Python-like source code into SymPy expression. """ from tokenize import (generate_tokens, untokenize, TokenError, NUMBER, STRING, NAME, OP, ENDMARKER, ERRORTOKEN, NEWLINE) from keyword import iskeyword import ast import unicodedata from io import StringIO import builtins import types from typing import Tuple as tTuple, Dict as tDict, Any, Callable, \ List, Optional, Union as tUnion from sympy.assumptions.ask import AssumptionKeys from sympy.core.basic import Basic from sympy.core import Symbol from sympy.core.function import Function from sympy.utilities.misc import func_name from sympy.functions.elementary.miscellaneous import Max, Min null = '' TOKEN = tTuple[int, str] DICT = tDict[str, Any] TRANS = Callable[[List[TOKEN], DICT, DICT], List[TOKEN]] def _token_splittable(token_name: str) -> bool: """ Predicate for whether a token name can be split into multiple tokens. A token is splittable if it does not contain an underscore character and it is not the name of a Greek letter. This is used to implicitly convert expressions like 'xyz' into 'x*y*z'. """ if '_' in token_name: return False try: return not unicodedata.lookup('GREEK SMALL LETTER ' + token_name) except KeyError: return len(token_name) > 1 def _token_callable(token: TOKEN, local_dict: DICT, global_dict: DICT, nextToken=None): """ Predicate for whether a token name represents a callable function. Essentially wraps ``callable``, but looks up the token name in the locals and globals. """ func = local_dict.get(token[1]) if not func: func = global_dict.get(token[1]) return callable(func) and not isinstance(func, Symbol) def _add_factorial_tokens(name: str, result: List[TOKEN]) -> List[TOKEN]: if result == [] or result[-1][1] == '(': raise TokenError() beginning = [(NAME, name), (OP, '(')] end = [(OP, ')')] diff = 0 length = len(result) for index, token in enumerate(result[::-1]): toknum, tokval = token i = length - index - 1 if tokval == ')': diff += 1 elif tokval == '(': diff -= 1 if diff == 0: if i - 1 >= 0 and result[i - 1][0] == NAME: return result[:i - 1] + beginning + result[i - 1:] + end else: return result[:i] + beginning + result[i:] + end return result class ParenthesisGroup(List[TOKEN]): """List of tokens representing an expression in parentheses.""" pass class AppliedFunction: """ A group of tokens representing a function and its arguments. `exponent` is for handling the shorthand sin^2, ln^2, etc. """ def __init__(self, function: TOKEN, args: ParenthesisGroup, exponent=None): if exponent is None: exponent = [] self.function = function self.args = args self.exponent = exponent self.items = ['function', 'args', 'exponent'] def expand(self) -> List[TOKEN]: """Return a list of tokens representing the function""" return [self.function, *self.args] def __getitem__(self, index): return getattr(self, self.items[index]) def __repr__(self): return "AppliedFunction(%s, %s, %s)" % (self.function, self.args, self.exponent) def _flatten(result: List[tUnion[TOKEN, AppliedFunction]]): result2: List[TOKEN] = [] for tok in result: if isinstance(tok, AppliedFunction): result2.extend(tok.expand()) else: result2.append(tok) return result2 def _group_parentheses(recursor: TRANS): def _inner(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Group tokens between parentheses with ParenthesisGroup. Also processes those tokens recursively. """ result: List[tUnion[TOKEN, ParenthesisGroup]] = [] stacks: List[ParenthesisGroup] = [] stacklevel = 0 for token in tokens: if token[0] == OP: if token[1] == '(': stacks.append(ParenthesisGroup([])) stacklevel += 1 elif token[1] == ')': stacks[-1].append(token) stack = stacks.pop() if len(stacks) > 0: # We don't recurse here since the upper-level stack # would reprocess these tokens stacks[-1].extend(stack) else: # Recurse here to handle nested parentheses # Strip off the outer parentheses to avoid an infinite loop inner = stack[1:-1] inner = recursor(inner, local_dict, global_dict) parenGroup = [stack[0]] + inner + [stack[-1]] result.append(ParenthesisGroup(parenGroup)) stacklevel -= 1 continue if stacklevel: stacks[-1].append(token) else: result.append(token) if stacklevel: raise TokenError("Mismatched parentheses") return result return _inner def _apply_functions(tokens: List[tUnion[TOKEN, ParenthesisGroup]], local_dict: DICT, global_dict: DICT): """Convert a NAME token + ParenthesisGroup into an AppliedFunction. Note that ParenthesisGroups, if not applied to any function, are converted back into lists of tokens. """ result: List[tUnion[TOKEN, AppliedFunction]] = [] symbol = None for tok in tokens: if isinstance(tok, ParenthesisGroup): if symbol and _token_callable(symbol, local_dict, global_dict): result[-1] = AppliedFunction(symbol, tok) symbol = None else: result.extend(tok) elif tok[0] == NAME: symbol = tok result.append(tok) else: symbol = None result.append(tok) return result def _implicit_multiplication(tokens: List[tUnion[TOKEN, AppliedFunction]], local_dict: DICT, global_dict: DICT): """Implicitly adds '*' tokens. Cases: - Two AppliedFunctions next to each other ("sin(x)cos(x)") - AppliedFunction next to an open parenthesis ("sin x (cos x + 1)") - A close parenthesis next to an AppliedFunction ("(x+2)sin x")\ - A close parenthesis next to an open parenthesis ("(x+2)(x+3)") - AppliedFunction next to an implicitly applied function ("sin(x)cos x") """ result: List[tUnion[TOKEN, AppliedFunction]] = [] skip = False for tok, nextTok in zip(tokens, tokens[1:]): result.append(tok) if skip: skip = False continue if tok[0] == OP and tok[1] == '.' and nextTok[0] == NAME: # Dotted name. Do not do implicit multiplication skip = True continue if isinstance(tok, AppliedFunction): if isinstance(nextTok, AppliedFunction): result.append((OP, '*')) elif nextTok == (OP, '('): # Applied function followed by an open parenthesis if tok.function[1] == "Function": tok.function = (tok.function[0], 'Symbol') result.append((OP, '*')) elif nextTok[0] == NAME: # Applied function followed by implicitly applied function result.append((OP, '*')) else: if tok == (OP, ')'): if isinstance(nextTok, AppliedFunction): # Close parenthesis followed by an applied function result.append((OP, '*')) elif nextTok[0] == NAME: # Close parenthesis followed by an implicitly applied function result.append((OP, '*')) elif nextTok == (OP, '('): # Close parenthesis followed by an open parenthesis result.append((OP, '*')) elif tok[0] == NAME and not _token_callable(tok, local_dict, global_dict): if isinstance(nextTok, AppliedFunction) or \ (nextTok[0] == NAME and _token_callable(nextTok, local_dict, global_dict)): # Constant followed by (implicitly applied) function result.append((OP, '*')) elif nextTok == (OP, '('): # Constant followed by parenthesis result.append((OP, '*')) elif nextTok[0] == NAME: # Constant followed by constant result.append((OP, '*')) if tokens: result.append(tokens[-1]) return result def _implicit_application(tokens: List[tUnion[TOKEN, AppliedFunction]], local_dict: DICT, global_dict: DICT): """Adds parentheses as needed after functions.""" result: List[tUnion[TOKEN, AppliedFunction]] = [] appendParen = 0 # number of closing parentheses to add skip = 0 # number of tokens to delay before adding a ')' (to # capture **, ^, etc.) exponentSkip = False # skipping tokens before inserting parentheses to # work with function exponentiation for tok, nextTok in zip(tokens, tokens[1:]): result.append(tok) if (tok[0] == NAME and nextTok[0] not in [OP, ENDMARKER, NEWLINE]): if _token_callable(tok, local_dict, global_dict, nextTok): # type: ignore result.append((OP, '(')) appendParen += 1 # name followed by exponent - function exponentiation elif (tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**'): if _token_callable(tok, local_dict, global_dict): # type: ignore exponentSkip = True elif exponentSkip: # if the last token added was an applied function (i.e. the # power of the function exponent) OR a multiplication (as # implicit multiplication would have added an extraneous # multiplication) if (isinstance(tok, AppliedFunction) or (tok[0] == OP and tok[1] == '*')): # don't add anything if the next token is a multiplication # or if there's already a parenthesis (if parenthesis, still # stop skipping tokens) if not (nextTok[0] == OP and nextTok[1] == '*'): if not(nextTok[0] == OP and nextTok[1] == '('): result.append((OP, '(')) appendParen += 1 exponentSkip = False elif appendParen: if nextTok[0] == OP and nextTok[1] in ('^', '**', '*'): skip = 1 continue if skip: skip -= 1 continue result.append((OP, ')')) appendParen -= 1 if tokens: result.append(tokens[-1]) if appendParen: result.extend([(OP, ')')] * appendParen) return result def function_exponentiation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Allows functions to be exponentiated, e.g. ``cos**2(x)``. Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, function_exponentiation) >>> transformations = standard_transformations + (function_exponentiation,) >>> parse_expr('sin**4(x)', transformations=transformations) sin(x)**4 """ result: List[TOKEN] = [] exponent: List[TOKEN] = [] consuming_exponent = False level = 0 for tok, nextTok in zip(tokens, tokens[1:]): if tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**': if _token_callable(tok, local_dict, global_dict): consuming_exponent = True elif consuming_exponent: if tok[0] == NAME and tok[1] == 'Function': tok = (NAME, 'Symbol') exponent.append(tok) # only want to stop after hitting ) if tok[0] == nextTok[0] == OP and tok[1] == ')' and nextTok[1] == '(': consuming_exponent = False # if implicit multiplication was used, we may have )*( instead if tok[0] == nextTok[0] == OP and tok[1] == '*' and nextTok[1] == '(': consuming_exponent = False del exponent[-1] continue elif exponent and not consuming_exponent: if tok[0] == OP: if tok[1] == '(': level += 1 elif tok[1] == ')': level -= 1 if level == 0: result.append(tok) result.extend(exponent) exponent = [] continue result.append(tok) if tokens: result.append(tokens[-1]) if exponent: result.extend(exponent) return result def split_symbols_custom(predicate: Callable[[str], bool]): """Creates a transformation that splits symbol names. ``predicate`` should return True if the symbol name is to be split. For instance, to retain the default behavior but avoid splitting certain symbol names, a predicate like this would work: >>> from sympy.parsing.sympy_parser import (parse_expr, _token_splittable, ... standard_transformations, implicit_multiplication, ... split_symbols_custom) >>> def can_split(symbol): ... if symbol not in ('list', 'of', 'unsplittable', 'names'): ... return _token_splittable(symbol) ... return False ... >>> transformation = split_symbols_custom(can_split) >>> parse_expr('unsplittable', transformations=standard_transformations + ... (transformation, implicit_multiplication)) unsplittable """ def _split_symbols(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): result: List[TOKEN] = [] split = False split_previous=False for tok in tokens: if split_previous: # throw out closing parenthesis of Symbol that was split split_previous=False continue split_previous=False if tok[0] == NAME and tok[1] in ['Symbol', 'Function']: split = True elif split and tok[0] == NAME: symbol = tok[1][1:-1] if predicate(symbol): tok_type = result[-2][1] # Symbol or Function del result[-2:] # Get rid of the call to Symbol i = 0 while i < len(symbol): char = symbol[i] if char in local_dict or char in global_dict: result.append((NAME, "%s" % char)) elif char.isdigit(): chars = [char] for i in range(i + 1, len(symbol)): if not symbol[i].isdigit(): i -= 1 break chars.append(symbol[i]) char = ''.join(chars) result.extend([(NAME, 'Number'), (OP, '('), (NAME, "'%s'" % char), (OP, ')')]) else: use = tok_type if i == len(symbol) else 'Symbol' result.extend([(NAME, use), (OP, '('), (NAME, "'%s'" % char), (OP, ')')]) i += 1 # Set split_previous=True so will skip # the closing parenthesis of the original Symbol split = False split_previous = True continue else: split = False result.append(tok) return result return _split_symbols #: Splits symbol names for implicit multiplication. #: #: Intended to let expressions like ``xyz`` be parsed as ``x*y*z``. Does not #: split Greek character names, so ``theta`` will *not* become #: ``t*h*e*t*a``. Generally this should be used with #: ``implicit_multiplication``. split_symbols = split_symbols_custom(_token_splittable) def implicit_multiplication(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT) -> List[TOKEN]: """Makes the multiplication operator optional in most cases. Use this before :func:`implicit_application`, otherwise expressions like ``sin 2x`` will be parsed as ``x * sin(2)`` rather than ``sin(2*x)``. Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, implicit_multiplication) >>> transformations = standard_transformations + (implicit_multiplication,) >>> parse_expr('3 x y', transformations=transformations) 3*x*y """ # These are interdependent steps, so we don't expose them separately res1 = _group_parentheses(implicit_multiplication)(tokens, local_dict, global_dict) res2 = _apply_functions(res1, local_dict, global_dict) res3 = _implicit_multiplication(res2, local_dict, global_dict) result = _flatten(res3) return result def implicit_application(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT) -> List[TOKEN]: """Makes parentheses optional in some cases for function calls. Use this after :func:`implicit_multiplication`, otherwise expressions like ``sin 2x`` will be parsed as ``x * sin(2)`` rather than ``sin(2*x)``. Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, implicit_application) >>> transformations = standard_transformations + (implicit_application,) >>> parse_expr('cot z + csc z', transformations=transformations) cot(z) + csc(z) """ res1 = _group_parentheses(implicit_application)(tokens, local_dict, global_dict) res2 = _apply_functions(res1, local_dict, global_dict) res3 = _implicit_application(res2, local_dict, global_dict) result = _flatten(res3) return result def implicit_multiplication_application(result: List[TOKEN], local_dict: DICT, global_dict: DICT) -> List[TOKEN]: """Allows a slightly relaxed syntax. - Parentheses for single-argument method calls are optional. - Multiplication is implicit. - Symbol names can be split (i.e. spaces are not needed between symbols). - Functions can be exponentiated. Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, implicit_multiplication_application) >>> parse_expr("10sin**2 x**2 + 3xyz + tan theta", ... transformations=(standard_transformations + ... (implicit_multiplication_application,))) 3*x*y*z + 10*sin(x**2)**2 + tan(theta) """ for step in (split_symbols, implicit_multiplication, implicit_application, function_exponentiation): result = step(result, local_dict, global_dict) return result def auto_symbol(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Inserts calls to ``Symbol``/``Function`` for undefined variables.""" result: List[TOKEN] = [] prevTok = (-1, '') tokens.append((-1, '')) # so zip traverses all tokens for tok, nextTok in zip(tokens, tokens[1:]): tokNum, tokVal = tok nextTokNum, nextTokVal = nextTok if tokNum == NAME: name = tokVal if (name in ['True', 'False', 'None'] or iskeyword(name) # Don't convert attribute access or (prevTok[0] == OP and prevTok[1] == '.') # Don't convert keyword arguments or (prevTok[0] == OP and prevTok[1] in ('(', ',') and nextTokNum == OP and nextTokVal == '=') # the name has already been defined or name in local_dict and local_dict[name] is not null): result.append((NAME, name)) continue elif name in local_dict: local_dict.setdefault(null, set()).add(name) if nextTokVal == '(': local_dict[name] = Function(name) else: local_dict[name] = Symbol(name) result.append((NAME, name)) continue elif name in global_dict: obj = global_dict[name] if isinstance(obj, (AssumptionKeys, Basic, type)) or callable(obj): result.append((NAME, name)) continue result.extend([ (NAME, 'Symbol' if nextTokVal != '(' else 'Function'), (OP, '('), (NAME, repr(str(name))), (OP, ')'), ]) else: result.append((tokNum, tokVal)) prevTok = (tokNum, tokVal) return result def lambda_notation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Substitutes "lambda" with its SymPy equivalent Lambda(). However, the conversion does not take place if only "lambda" is passed because that is a syntax error. """ result: List[TOKEN] = [] flag = False toknum, tokval = tokens[0] tokLen = len(tokens) if toknum == NAME and tokval == 'lambda': if tokLen == 2 or tokLen == 3 and tokens[1][0] == NEWLINE: # In Python 3.6.7+, inputs without a newline get NEWLINE added to # the tokens result.extend(tokens) elif tokLen > 2: result.extend([ (NAME, 'Lambda'), (OP, '('), (OP, '('), (OP, ')'), (OP, ')'), ]) for tokNum, tokVal in tokens[1:]: if tokNum == OP and tokVal == ':': tokVal = ',' flag = True if not flag and tokNum == OP and tokVal in ('*', '**'): raise TokenError("Starred arguments in lambda not supported") if flag: result.insert(-1, (tokNum, tokVal)) else: result.insert(-2, (tokNum, tokVal)) else: result.extend(tokens) return result def factorial_notation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Allows standard notation for factorial.""" result: List[TOKEN] = [] nfactorial = 0 for toknum, tokval in tokens: if toknum == ERRORTOKEN: op = tokval if op == '!': nfactorial += 1 else: nfactorial = 0 result.append((OP, op)) else: if nfactorial == 1: result = _add_factorial_tokens('factorial', result) elif nfactorial == 2: result = _add_factorial_tokens('factorial2', result) elif nfactorial > 2: raise TokenError nfactorial = 0 result.append((toknum, tokval)) return result def convert_xor(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Treats XOR, ``^``, as exponentiation, ``**``.""" result: List[TOKEN] = [] for toknum, tokval in tokens: if toknum == OP: if tokval == '^': result.append((OP, '**')) else: result.append((toknum, tokval)) else: result.append((toknum, tokval)) return result def repeated_decimals(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """ Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90) Run this before auto_number. """ result: List[TOKEN] = [] def is_digit(s): return all(i in '0123456789_' for i in s) # num will running match any DECIMAL [ INTEGER ] num: List[TOKEN] = [] for toknum, tokval in tokens: if toknum == NUMBER: if (not num and '.' in tokval and 'e' not in tokval.lower() and 'j' not in tokval.lower()): num.append((toknum, tokval)) elif is_digit(tokval)and len(num) == 2: num.append((toknum, tokval)) elif is_digit(tokval) and len(num) == 3 and is_digit(num[-1][1]): # Python 2 tokenizes 00123 as '00', '123' # Python 3 tokenizes 01289 as '012', '89' num.append((toknum, tokval)) else: num = [] elif toknum == OP: if tokval == '[' and len(num) == 1: num.append((OP, tokval)) elif tokval == ']' and len(num) >= 3: num.append((OP, tokval)) elif tokval == '.' and not num: # handle .[1] num.append((NUMBER, '0.')) else: num = [] else: num = [] result.append((toknum, tokval)) if num and num[-1][1] == ']': # pre.post[repetend] = a + b/c + d/e where a = pre, b/c = post, # and d/e = repetend result = result[:-len(num)] pre, post = num[0][1].split('.') repetend = num[2][1] if len(num) == 5: repetend += num[3][1] pre = pre.replace('_', '') post = post.replace('_', '') repetend = repetend.replace('_', '') zeros = '0'*len(post) post, repetends = [w.lstrip('0') for w in [post, repetend]] # or else interpreted as octal a = pre or '0' b, c = post or '0', '1' + zeros d, e = repetends, ('9'*len(repetend)) + zeros seq = [ (OP, '('), (NAME, 'Integer'), (OP, '('), (NUMBER, a), (OP, ')'), (OP, '+'), (NAME, 'Rational'), (OP, '('), (NUMBER, b), (OP, ','), (NUMBER, c), (OP, ')'), (OP, '+'), (NAME, 'Rational'), (OP, '('), (NUMBER, d), (OP, ','), (NUMBER, e), (OP, ')'), (OP, ')'), ] result.extend(seq) num = [] return result def auto_number(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """ Converts numeric literals to use SymPy equivalents. Complex numbers use ``I``, integer literals use ``Integer``, and float literals use ``Float``. """ result: List[TOKEN] = [] for toknum, tokval in tokens: if toknum == NUMBER: number = tokval postfix = [] if number.endswith('j') or number.endswith('J'): number = number[:-1] postfix = [(OP, '*'), (NAME, 'I')] if '.' in number or (('e' in number or 'E' in number) and not (number.startswith('0x') or number.startswith('0X'))): seq = [(NAME, 'Float'), (OP, '('), (NUMBER, repr(str(number))), (OP, ')')] else: seq = [(NAME, 'Integer'), (OP, '('), ( NUMBER, number), (OP, ')')] result.extend(seq + postfix) else: result.append((toknum, tokval)) return result def rationalize(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Converts floats into ``Rational``. Run AFTER ``auto_number``.""" result: List[TOKEN] = [] passed_float = False for toknum, tokval in tokens: if toknum == NAME: if tokval == 'Float': passed_float = True tokval = 'Rational' result.append((toknum, tokval)) elif passed_float == True and toknum == NUMBER: passed_float = False result.append((STRING, tokval)) else: result.append((toknum, tokval)) return result def _transform_equals_sign(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Transforms the equals sign ``=`` to instances of Eq. This is a helper function for ``convert_equals_signs``. Works with expressions containing one equals sign and no nesting. Expressions like ``(1=2)=False`` will not work with this and should be used with ``convert_equals_signs``. Examples: 1=2 to Eq(1,2) 1*2=x to Eq(1*2, x) This does not deal with function arguments yet. """ result: List[TOKEN] = [] if (OP, "=") in tokens: result.append((NAME, "Eq")) result.append((OP, "(")) for token in tokens: if token == (OP, "="): result.append((OP, ",")) continue result.append(token) result.append((OP, ")")) else: result = tokens return result def convert_equals_signs(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT) -> List[TOKEN]: """ Transforms all the equals signs ``=`` to instances of Eq. Parses the equals signs in the expression and replaces them with appropriate Eq instances. Also works with nested equals signs. Does not yet play well with function arguments. For example, the expression ``(x=y)`` is ambiguous and can be interpreted as x being an argument to a function and ``convert_equals_signs`` will not work for this. See also ======== convert_equality_operators Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, convert_equals_signs) >>> parse_expr("1*2=x", transformations=( ... standard_transformations + (convert_equals_signs,))) Eq(2, x) >>> parse_expr("(1*2=x)=False", transformations=( ... standard_transformations + (convert_equals_signs,))) Eq(Eq(2, x), False) """ res1 = _group_parentheses(convert_equals_signs)(tokens, local_dict, global_dict) res2 = _apply_functions(res1, local_dict, global_dict) res3 = _transform_equals_sign(res2, local_dict, global_dict) result = _flatten(res3) return result #: Standard transformations for :func:`parse_expr`. #: Inserts calls to :class:`~.Symbol`, :class:`~.Integer`, and other SymPy #: datatypes and allows the use of standard factorial notation (e.g. ``x!``). standard_transformations: tTuple[TRANS, ...] \ = (lambda_notation, auto_symbol, repeated_decimals, auto_number, factorial_notation) def stringify_expr(s: str, local_dict: DICT, global_dict: DICT, transformations: tTuple[TRANS, ...]) -> str: """ Converts the string ``s`` to Python code, in ``local_dict`` Generally, ``parse_expr`` should be used. """ tokens = [] input_code = StringIO(s.strip()) for toknum, tokval, _, _, _ in generate_tokens(input_code.readline): tokens.append((toknum, tokval)) for transform in transformations: tokens = transform(tokens, local_dict, global_dict) return untokenize(tokens) def eval_expr(code, local_dict: DICT, global_dict: DICT): """ Evaluate Python code generated by ``stringify_expr``. Generally, ``parse_expr`` should be used. """ expr = eval( code, global_dict, local_dict) # take local objects in preference return expr def parse_expr(s: str, local_dict: Optional[DICT] = None, transformations: tUnion[tTuple[TRANS, ...], str] \ = standard_transformations, global_dict: Optional[DICT] = None, evaluate=True): """Converts the string ``s`` to a SymPy expression, in ``local_dict`` Parameters ========== s : str The string to parse. local_dict : dict, optional A dictionary of local variables to use when parsing. global_dict : dict, optional A dictionary of global variables. By default, this is initialized with ``from sympy import *``; provide this parameter to override this behavior (for instance, to parse ``"Q & S"``). transformations : tuple or str A tuple of transformation functions used to modify the tokens of the parsed expression before evaluation. The default transformations convert numeric literals into their SymPy equivalents, convert undefined variables into SymPy symbols, and allow the use of standard mathematical factorial notation (e.g. ``x!``). Selection via string is available (see below). evaluate : bool, optional When False, the order of the arguments will remain as they were in the string and automatic simplification that would normally occur is suppressed. (see examples) Examples ======== >>> from sympy.parsing.sympy_parser import parse_expr >>> parse_expr("1/2") 1/2 >>> type(_) <class 'sympy.core.numbers.Half'> >>> from sympy.parsing.sympy_parser import standard_transformations,\\ ... implicit_multiplication_application >>> transformations = (standard_transformations + ... (implicit_multiplication_application,)) >>> parse_expr("2x", transformations=transformations) 2*x When evaluate=False, some automatic simplifications will not occur: >>> parse_expr("2**3"), parse_expr("2**3", evaluate=False) (8, 2**3) In addition the order of the arguments will not be made canonical. This feature allows one to tell exactly how the expression was entered: >>> a = parse_expr('1 + x', evaluate=False) >>> b = parse_expr('x + 1', evaluate=0) >>> a == b False >>> a.args (1, x) >>> b.args (x, 1) Note, however, that when these expressions are printed they will appear the same: >>> assert str(a) == str(b) As a convenience, transformations can be seen by printing ``transformations``: >>> from sympy.parsing.sympy_parser import transformations >>> print(transformations) 0: lambda_notation 1: auto_symbol 2: repeated_decimals 3: auto_number 4: factorial_notation 5: implicit_multiplication_application 6: convert_xor 7: implicit_application 8: implicit_multiplication 9: convert_equals_signs 10: function_exponentiation 11: rationalize The ``T`` object provides a way to select these transformations: >>> from sympy.parsing.sympy_parser import T If you print it, you will see the same list as shown above. >>> str(T) == str(transformations) True Standard slicing will return a tuple of transformations: >>> T[:5] == standard_transformations True So ``T`` can be used to specify the parsing transformations: >>> parse_expr("2x", transformations=T[:5]) Traceback (most recent call last): ... SyntaxError: invalid syntax >>> parse_expr("2x", transformations=T[:6]) 2*x >>> parse_expr('.3', transformations=T[3, 11]) 3/10 >>> parse_expr('.3x', transformations=T[:]) 3*x/10 As a further convenience, strings 'implicit' and 'all' can be used to select 0-5 and all the transformations, respectively. >>> parse_expr('.3x', transformations='all') 3*x/10 See Also ======== stringify_expr, eval_expr, standard_transformations, implicit_multiplication_application """ if local_dict is None: local_dict = {} elif not isinstance(local_dict, dict): raise TypeError('expecting local_dict to be a dict') elif null in local_dict: raise ValueError('cannot use "" in local_dict') if global_dict is None: global_dict = {} exec('from sympy import *', global_dict) builtins_dict = vars(builtins) for name, obj in builtins_dict.items(): if isinstance(obj, types.BuiltinFunctionType): global_dict[name] = obj global_dict['max'] = Max global_dict['min'] = Min elif not isinstance(global_dict, dict): raise TypeError('expecting global_dict to be a dict') transformations = transformations or () if isinstance(transformations, str): if transformations == 'all': _transformations = T[:] elif transformations == 'implicit': _transformations = T[:6] else: raise ValueError('unknown transformation group name') else: _transformations = transformations code = stringify_expr(s, local_dict, global_dict, _transformations) if not evaluate: code = compile(evaluateFalse(code), '<string>', 'eval') try: rv = eval_expr(code, local_dict, global_dict) # restore neutral definitions for names for i in local_dict.pop(null, ()): local_dict[i] = null return rv except Exception as e: # restore neutral definitions for names for i in local_dict.pop(null, ()): local_dict[i] = null raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}") def evaluateFalse(s: str): """ Replaces operators with the SymPy equivalent and sets evaluate=False. """ node = ast.parse(s) transformed_node = EvaluateFalseTransformer().visit(node) # node is a Module, we want an Expression transformed_node = ast.Expression(transformed_node.body[0].value) return ast.fix_missing_locations(transformed_node) class EvaluateFalseTransformer(ast.NodeTransformer): operators = { ast.Add: 'Add', ast.Mult: 'Mul', ast.Pow: 'Pow', ast.Sub: 'Add', ast.Div: 'Mul', ast.BitOr: 'Or', ast.BitAnd: 'And', ast.BitXor: 'Not', } functions = ( 'Abs', 'im', 're', 'sign', 'arg', 'conjugate', 'acos', 'acot', 'acsc', 'asec', 'asin', 'atan', 'acosh', 'acoth', 'acsch', 'asech', 'asinh', 'atanh', 'cos', 'cot', 'csc', 'sec', 'sin', 'tan', 'cosh', 'coth', 'csch', 'sech', 'sinh', 'tanh', 'exp', 'ln', 'log', 'sqrt', 'cbrt', ) def flatten(self, args, func): result = [] for arg in args: if isinstance(arg, ast.Call): arg_func = arg.func if isinstance(arg_func, ast.Call): arg_func = arg_func.func if arg_func.id == func: result.extend(self.flatten(arg.args, func)) else: result.append(arg) else: result.append(arg) return result def visit_BinOp(self, node): if node.op.__class__ in self.operators: sympy_class = self.operators[node.op.__class__] right = self.visit(node.right) left = self.visit(node.left) rev = False if isinstance(node.op, ast.Sub): right = ast.Call( func=ast.Name(id='Mul', ctx=ast.Load()), args=[ast.UnaryOp(op=ast.USub(), operand=ast.Num(1)), right], keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))], starargs=None, kwargs=None ) elif isinstance(node.op, ast.Div): if isinstance(node.left, ast.UnaryOp): left, right = right, left rev = True left = ast.Call( func=ast.Name(id='Pow', ctx=ast.Load()), args=[left, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))], keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))], starargs=None, kwargs=None ) else: right = ast.Call( func=ast.Name(id='Pow', ctx=ast.Load()), args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))], keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))], starargs=None, kwargs=None ) if rev: # undo reversal left, right = right, left new_node = ast.Call( func=ast.Name(id=sympy_class, ctx=ast.Load()), args=[left, right], keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))], starargs=None, kwargs=None ) if sympy_class in ('Add', 'Mul'): # Denest Add or Mul as appropriate new_node.args = self.flatten(new_node.args, sympy_class) return new_node return node def visit_Call(self, node): new_node = self.generic_visit(node) if isinstance(node.func, ast.Name) and node.func.id in self.functions: new_node.keywords.append(ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))) return new_node _transformation = { # items can be added but never re-ordered 0: lambda_notation, 1: auto_symbol, 2: repeated_decimals, 3: auto_number, 4: factorial_notation, 5: implicit_multiplication_application, 6: convert_xor, 7: implicit_application, 8: implicit_multiplication, 9: convert_equals_signs, 10: function_exponentiation, 11: rationalize} transformations = '\n'.join('%s: %s' % (i, func_name(f)) for i, f in _transformation.items()) class _T(): """class to retrieve transformations from a given slice EXAMPLES ======== >>> from sympy.parsing.sympy_parser import T, standard_transformations >>> assert T[:5] == standard_transformations """ def __init__(self): self.N = len(_transformation) def __str__(self): return transformations def __getitem__(self, t): if not type(t) is tuple: t = (t,) i = [] for ti in t: if type(ti) is int: i.append(range(self.N)[ti]) elif type(ti) is slice: i.extend(range(*ti.indices(self.N))) else: raise TypeError('unexpected slice arg') return tuple([_transformation[_] for _ in i]) T = _T()
2bc3fd140759afa51f40a6193bd4e584352a51ddd8b0c7a45c2b0acb61e1698d
from sympy.core import S, pi, Rational from sympy.functions import assoc_laguerre, sqrt, exp, factorial, factorial2 def R_nl(n, l, nu, r): """ Returns the radial wavefunction R_{nl} for a 3d isotropic harmonic oscillator. Parameters ========== n : The "nodal" quantum number. Corresponds to the number of nodes in the wavefunction. ``n >= 0`` l : The quantum number for orbital angular momentum. nu : mass-scaled frequency: nu = m*omega/(2*hbar) where `m` is the mass and `omega` the frequency of the oscillator. (in atomic units ``nu == omega/2``) r : Radial coordinate. Examples ======== >>> from sympy.physics.sho import R_nl >>> from sympy.abc import r, nu, l >>> R_nl(0, 0, 1, r) 2*2**(3/4)*exp(-r**2)/pi**(1/4) >>> R_nl(1, 0, 1, r) 4*2**(1/4)*sqrt(3)*(3/2 - 2*r**2)*exp(-r**2)/(3*pi**(1/4)) l, nu and r may be symbolic: >>> R_nl(0, 0, nu, r) 2*2**(3/4)*sqrt(nu**(3/2))*exp(-nu*r**2)/pi**(1/4) >>> R_nl(0, l, 1, r) r**l*sqrt(2**(l + 3/2)*2**(l + 2)/factorial2(2*l + 1))*exp(-r**2)/pi**(1/4) The normalization of the radial wavefunction is: >>> from sympy import Integral, oo >>> Integral(R_nl(0, 0, 1, r)**2*r**2, (r, 0, oo)).n() 1.00000000000000 >>> Integral(R_nl(1, 0, 1, r)**2*r**2, (r, 0, oo)).n() 1.00000000000000 >>> Integral(R_nl(1, 1, 1, r)**2*r**2, (r, 0, oo)).n() 1.00000000000000 """ n, l, nu, r = map(S, [n, l, nu, r]) # formula uses n >= 1 (instead of nodal n >= 0) n = n + 1 C = sqrt( ((2*nu)**(l + Rational(3, 2))*2**(n + l + 1)*factorial(n - 1))/ (sqrt(pi)*(factorial2(2*n + 2*l - 1))) ) return C*r**(l)*exp(-nu*r**2)*assoc_laguerre(n - 1, l + S.Half, 2*nu*r**2) def E_nl(n, l, hw): """ Returns the Energy of an isotropic harmonic oscillator. Parameters ========== n : The "nodal" quantum number. l : The orbital angular momentum. hw : The harmonic oscillator parameter. Notes ===== The unit of the returned value matches the unit of hw, since the energy is calculated as: E_nl = (2*n + l + 3/2)*hw Examples ======== >>> from sympy.physics.sho import E_nl >>> from sympy import symbols >>> x, y, z = symbols('x, y, z') >>> E_nl(x, y, z) z*(2*x + y + 3/2) """ return (2*n + l + Rational(3, 2))*hw
6577a652c6bf6f4acbb4f55352480091943511cbb67886716a23524975b43c39
from sympy.core import S, pi, Rational from sympy.functions import hermite, sqrt, exp, factorial, Abs from sympy.physics.quantum.constants import hbar def psi_n(n, x, m, omega): """ Returns the wavefunction psi_{n} for the One-dimensional harmonic oscillator. Parameters ========== n : the "nodal" quantum number. Corresponds to the number of nodes in the wavefunction. ``n >= 0`` x : x coordinate. m : Mass of the particle. omega : Angular frequency of the oscillator. Examples ======== >>> from sympy.physics.qho_1d import psi_n >>> from sympy.abc import m, x, omega >>> psi_n(0, x, m, omega) (m*omega)**(1/4)*exp(-m*omega*x**2/(2*hbar))/(hbar**(1/4)*pi**(1/4)) """ # sympify arguments n, x, m, omega = map(S, [n, x, m, omega]) nu = m * omega / hbar # normalization coefficient C = (nu/pi)**Rational(1, 4) * sqrt(1/(2**n*factorial(n))) return C * exp(-nu* x**2 /2) * hermite(n, sqrt(nu)*x) def E_n(n, omega): """ Returns the Energy of the One-dimensional harmonic oscillator. Parameters ========== n : The "nodal" quantum number. omega : The harmonic oscillator angular frequency. Notes ===== The unit of the returned value matches the unit of hw, since the energy is calculated as: E_n = hbar * omega*(n + 1/2) Examples ======== >>> from sympy.physics.qho_1d import E_n >>> from sympy.abc import x, omega >>> E_n(x, omega) hbar*omega*(x + 1/2) """ return hbar * omega * (n + S.Half) def coherent_state(n, alpha): """ Returns <n|alpha> for the coherent states of 1D harmonic oscillator. See https://en.wikipedia.org/wiki/Coherent_states Parameters ========== n : The "nodal" quantum number. alpha : The eigen value of annihilation operator. """ return exp(- Abs(alpha)**2/2)*(alpha**n)/sqrt(factorial(n))
8b71fa8a937087229e74f4f0e99a0c33289a3a82625a76078fb3b813b78ae94e
""" This module defines tensors with abstract index notation. The abstract index notation has been first formalized by Penrose. Tensor indices are formal objects, with a tensor type; there is no notion of index range, it is only possible to assign the dimension, used to trace the Kronecker delta; the dimension can be a Symbol. The Einstein summation convention is used. The covariant indices are indicated with a minus sign in front of the index. For instance the tensor ``t = p(a)*A(b,c)*q(-c)`` has the index ``c`` contracted. A tensor expression ``t`` can be called; called with its indices in sorted order it is equal to itself: in the above example ``t(a, b) == t``; one can call ``t`` with different indices; ``t(c, d) == p(c)*A(d,a)*q(-a)``. The contracted indices are dummy indices, internally they have no name, the indices being represented by a graph-like structure. Tensors are put in canonical form using ``canon_bp``, which uses the Butler-Portugal algorithm for canonicalization using the monoterm symmetries of the tensors. If there is a (anti)symmetric metric, the indices can be raised and lowered when the tensor is put in canonical form. """ from typing import Any, Dict as tDict, List, Set as tSet, Tuple as tTuple from functools import reduce from math import prod from abc import abstractmethod, ABCMeta from collections import defaultdict import operator import itertools from sympy.core.numbers import (Integer, Rational) from sympy.combinatorics import Permutation from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, \ bsgs_direct_product, canonicalize, riemann_bsgs from sympy.core import Basic, Expr, sympify, Add, Mul, S from sympy.core.assumptions import ManagedProperties from sympy.core.containers import Tuple, Dict from sympy.core.sorting import default_sort_key from sympy.core.symbol import Symbol, symbols from sympy.core.sympify import CantSympify, _sympify from sympy.core.operations import AssocOp from sympy.external.gmpy import SYMPY_INTS from sympy.matrices import eye from sympy.utilities.exceptions import (sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) from sympy.utilities.decorator import memoize_property, deprecated def deprecate_data(): sympy_deprecation_warning( """ The data attribute of TensorIndexType is deprecated. Use The replace_with_arrays() method instead. """, deprecated_since_version="1.4", active_deprecations_target="deprecated-tensorindextype-attrs", stacklevel=4, ) def deprecate_fun_eval(): sympy_deprecation_warning( """ The Tensor.fun_eval() method is deprecated. Use Tensor.substitute_indices() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensor-fun-eval", stacklevel=4, ) def deprecate_call(): sympy_deprecation_warning( """ Calling a tensor like Tensor(*indices) is deprecated. Use Tensor.substitute_indices() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensor-fun-eval", stacklevel=4, ) class _IndexStructure(CantSympify): """ This class handles the indices (free and dummy ones). It contains the algorithms to manage the dummy indices replacements and contractions of free indices under multiplications of tensor expressions, as well as stuff related to canonicalization sorting, getting the permutation of the expression and so on. It also includes tools to get the ``TensorIndex`` objects corresponding to the given index structure. """ def __init__(self, free, dum, index_types, indices, canon_bp=False): self.free = free self.dum = dum self.index_types = index_types self.indices = indices self._ext_rank = len(self.free) + 2*len(self.dum) self.dum.sort(key=lambda x: x[0]) @staticmethod def from_indices(*indices): """ Create a new ``_IndexStructure`` object from a list of ``indices``. Explanation =========== ``indices`` ``TensorIndex`` objects, the indices. Contractions are detected upon construction. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, _IndexStructure >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz) >>> _IndexStructure.from_indices(m0, m1, -m1, m3) _IndexStructure([(m0, 0), (m3, 3)], [(1, 2)], [Lorentz, Lorentz, Lorentz, Lorentz]) """ free, dum = _IndexStructure._free_dum_from_indices(*indices) index_types = [i.tensor_index_type for i in indices] indices = _IndexStructure._replace_dummy_names(indices, free, dum) return _IndexStructure(free, dum, index_types, indices) @staticmethod def from_components_free_dum(components, free, dum): index_types = [] for component in components: index_types.extend(component.index_types) indices = _IndexStructure.generate_indices_from_free_dum_index_types(free, dum, index_types) return _IndexStructure(free, dum, index_types, indices) @staticmethod def _free_dum_from_indices(*indices): """ Convert ``indices`` into ``free``, ``dum`` for single component tensor. Explanation =========== ``free`` list of tuples ``(index, pos, 0)``, where ``pos`` is the position of index in the list of indices formed by the component tensors ``dum`` list of tuples ``(pos_contr, pos_cov, 0, 0)`` Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, \ _IndexStructure >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz) >>> _IndexStructure._free_dum_from_indices(m0, m1, -m1, m3) ([(m0, 0), (m3, 3)], [(1, 2)]) """ n = len(indices) if n == 1: return [(indices[0], 0)], [] # find the positions of the free indices and of the dummy indices free = [True]*len(indices) index_dict = {} dum = [] for i, index in enumerate(indices): name = index.name typ = index.tensor_index_type contr = index.is_up if (name, typ) in index_dict: # found a pair of dummy indices is_contr, pos = index_dict[(name, typ)] # check consistency and update free if is_contr: if contr: raise ValueError('two equal contravariant indices in slots %d and %d' %(pos, i)) else: free[pos] = False free[i] = False else: if contr: free[pos] = False free[i] = False else: raise ValueError('two equal covariant indices in slots %d and %d' %(pos, i)) if contr: dum.append((i, pos)) else: dum.append((pos, i)) else: index_dict[(name, typ)] = index.is_up, i free = [(index, i) for i, index in enumerate(indices) if free[i]] free.sort() return free, dum def get_indices(self): """ Get a list of indices, creating new tensor indices to complete dummy indices. """ return self.indices[:] @staticmethod def generate_indices_from_free_dum_index_types(free, dum, index_types): indices = [None]*(len(free)+2*len(dum)) for idx, pos in free: indices[pos] = idx generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free) for pos1, pos2 in dum: typ1 = index_types[pos1] indname = generate_dummy_name(typ1) indices[pos1] = TensorIndex(indname, typ1, True) indices[pos2] = TensorIndex(indname, typ1, False) return _IndexStructure._replace_dummy_names(indices, free, dum) @staticmethod def _get_generator_for_dummy_indices(free): cdt = defaultdict(int) # if the free indices have names with dummy_name, start with an # index higher than those for the dummy indices # to avoid name collisions for indx, ipos in free: if indx.name.split('_')[0] == indx.tensor_index_type.dummy_name: cdt[indx.tensor_index_type] = max(cdt[indx.tensor_index_type], int(indx.name.split('_')[1]) + 1) def dummy_name_gen(tensor_index_type): nd = str(cdt[tensor_index_type]) cdt[tensor_index_type] += 1 return tensor_index_type.dummy_name + '_' + nd return dummy_name_gen @staticmethod def _replace_dummy_names(indices, free, dum): dum.sort(key=lambda x: x[0]) new_indices = [ind for ind in indices] assert len(indices) == len(free) + 2*len(dum) generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free) for ipos1, ipos2 in dum: typ1 = new_indices[ipos1].tensor_index_type indname = generate_dummy_name(typ1) new_indices[ipos1] = TensorIndex(indname, typ1, True) new_indices[ipos2] = TensorIndex(indname, typ1, False) return new_indices def get_free_indices(self): # type: () -> List[TensorIndex] """ Get a list of free indices. """ # get sorted indices according to their position: free = sorted(self.free, key=lambda x: x[1]) return [i[0] for i in free] def __str__(self): return "_IndexStructure({}, {}, {})".format(self.free, self.dum, self.index_types) def __repr__(self): return self.__str__() def _get_sorted_free_indices_for_canon(self): sorted_free = self.free[:] sorted_free.sort(key=lambda x: x[0]) return sorted_free def _get_sorted_dum_indices_for_canon(self): return sorted(self.dum, key=lambda x: x[0]) def _get_lexicographically_sorted_index_types(self): permutation = self.indices_canon_args()[0] index_types = [None]*self._ext_rank for i, it in enumerate(self.index_types): index_types[permutation(i)] = it return index_types def _get_lexicographically_sorted_indices(self): permutation = self.indices_canon_args()[0] indices = [None]*self._ext_rank for i, it in enumerate(self.indices): indices[permutation(i)] = it return indices def perm2tensor(self, g, is_canon_bp=False): """ Returns a ``_IndexStructure`` instance corresponding to the permutation ``g``. Explanation =========== ``g`` permutation corresponding to the tensor in the representation used in canonicalization ``is_canon_bp`` if True, then ``g`` is the permutation corresponding to the canonical form of the tensor """ sorted_free = [i[0] for i in self._get_sorted_free_indices_for_canon()] lex_index_types = self._get_lexicographically_sorted_index_types() lex_indices = self._get_lexicographically_sorted_indices() nfree = len(sorted_free) rank = self._ext_rank dum = [[None]*2 for i in range((rank - nfree)//2)] free = [] index_types = [None]*rank indices = [None]*rank for i in range(rank): gi = g[i] index_types[i] = lex_index_types[gi] indices[i] = lex_indices[gi] if gi < nfree: ind = sorted_free[gi] assert index_types[i] == sorted_free[gi].tensor_index_type free.append((ind, i)) else: j = gi - nfree idum, cov = divmod(j, 2) if cov: dum[idum][1] = i else: dum[idum][0] = i dum = [tuple(x) for x in dum] return _IndexStructure(free, dum, index_types, indices) def indices_canon_args(self): """ Returns ``(g, dummies, msym, v)``, the entries of ``canonicalize`` See ``canonicalize`` in ``tensor_can.py`` in combinatorics module. """ # to be called after sorted_components from sympy.combinatorics.permutations import _af_new n = self._ext_rank g = [None]*n + [n, n+1] # Converts the symmetry of the metric into msym from .canonicalize() # method in the combinatorics module def metric_symmetry_to_msym(metric): if metric is None: return None sym = metric.symmetry if sym == TensorSymmetry.fully_symmetric(2): return 0 if sym == TensorSymmetry.fully_symmetric(-2): return 1 return None # ordered indices: first the free indices, ordered by types # then the dummy indices, ordered by types and contravariant before # covariant # g[position in tensor] = position in ordered indices for i, (indx, ipos) in enumerate(self._get_sorted_free_indices_for_canon()): g[ipos] = i pos = len(self.free) j = len(self.free) dummies = [] prev = None a = [] msym = [] for ipos1, ipos2 in self._get_sorted_dum_indices_for_canon(): g[ipos1] = j g[ipos2] = j + 1 j += 2 typ = self.index_types[ipos1] if typ != prev: if a: dummies.append(a) a = [pos, pos + 1] prev = typ msym.append(metric_symmetry_to_msym(typ.metric)) else: a.extend([pos, pos + 1]) pos += 2 if a: dummies.append(a) return _af_new(g), dummies, msym def components_canon_args(components): numtyp = [] prev = None for t in components: if t == prev: numtyp[-1][1] += 1 else: prev = t numtyp.append([prev, 1]) v = [] for h, n in numtyp: if h.comm in (0, 1): comm = h.comm else: comm = TensorManager.get_comm(h.comm, h.comm) v.append((h.symmetry.base, h.symmetry.generators, n, comm)) return v class _TensorDataLazyEvaluator(CantSympify): """ EXPERIMENTAL: do not rely on this class, it may change without deprecation warnings in future versions of SymPy. Explanation =========== This object contains the logic to associate components data to a tensor expression. Components data are set via the ``.data`` property of tensor expressions, is stored inside this class as a mapping between the tensor expression and the ``ndarray``. Computations are executed lazily: whereas the tensor expressions can have contractions, tensor products, and additions, components data are not computed until they are accessed by reading the ``.data`` property associated to the tensor expression. """ _substitutions_dict = {} # type: tDict[Any, Any] _substitutions_dict_tensmul = {} # type: tDict[Any, Any] def __getitem__(self, key): dat = self._get(key) if dat is None: return None from .array import NDimArray if not isinstance(dat, NDimArray): return dat if dat.rank() == 0: return dat[()] elif dat.rank() == 1 and len(dat) == 1: return dat[0] return dat def _get(self, key): """ Retrieve ``data`` associated with ``key``. Explanation =========== This algorithm looks into ``self._substitutions_dict`` for all ``TensorHead`` in the ``TensExpr`` (or just ``TensorHead`` if key is a TensorHead instance). It reconstructs the components data that the tensor expression should have by performing on components data the operations that correspond to the abstract tensor operations applied. Metric tensor is handled in a different manner: it is pre-computed in ``self._substitutions_dict_tensmul``. """ if key in self._substitutions_dict: return self._substitutions_dict[key] if isinstance(key, TensorHead): return None if isinstance(key, Tensor): # special case to handle metrics. Metric tensors cannot be # constructed through contraction by the metric, their # components show if they are a matrix or its inverse. signature = tuple([i.is_up for i in key.get_indices()]) srch = (key.component,) + signature if srch in self._substitutions_dict_tensmul: return self._substitutions_dict_tensmul[srch] array_list = [self.data_from_tensor(key)] return self.data_contract_dum(array_list, key.dum, key.ext_rank) if isinstance(key, TensMul): tensmul_args = key.args if len(tensmul_args) == 1 and len(tensmul_args[0].components) == 1: # special case to handle metrics. Metric tensors cannot be # constructed through contraction by the metric, their # components show if they are a matrix or its inverse. signature = tuple([i.is_up for i in tensmul_args[0].get_indices()]) srch = (tensmul_args[0].components[0],) + signature if srch in self._substitutions_dict_tensmul: return self._substitutions_dict_tensmul[srch] #data_list = [self.data_from_tensor(i) for i in tensmul_args if isinstance(i, TensExpr)] data_list = [self.data_from_tensor(i) if isinstance(i, Tensor) else i.data for i in tensmul_args if isinstance(i, TensExpr)] coeff = prod([i for i in tensmul_args if not isinstance(i, TensExpr)]) if all(i is None for i in data_list): return None if any(i is None for i in data_list): raise ValueError("Mixing tensors with associated components "\ "data with tensors without components data") data_result = self.data_contract_dum(data_list, key.dum, key.ext_rank) return coeff*data_result if isinstance(key, TensAdd): data_list = [] free_args_list = [] for arg in key.args: if isinstance(arg, TensExpr): data_list.append(arg.data) free_args_list.append([x[0] for x in arg.free]) else: data_list.append(arg) free_args_list.append([]) if all(i is None for i in data_list): return None if any(i is None for i in data_list): raise ValueError("Mixing tensors with associated components "\ "data with tensors without components data") sum_list = [] from .array import permutedims for data, free_args in zip(data_list, free_args_list): if len(free_args) < 2: sum_list.append(data) else: free_args_pos = {y: x for x, y in enumerate(free_args)} axes = [free_args_pos[arg] for arg in key.free_args] sum_list.append(permutedims(data, axes)) return reduce(lambda x, y: x+y, sum_list) return None @staticmethod def data_contract_dum(ndarray_list, dum, ext_rank): from .array import tensorproduct, tensorcontraction, MutableDenseNDimArray arrays = list(map(MutableDenseNDimArray, ndarray_list)) prodarr = tensorproduct(*arrays) return tensorcontraction(prodarr, *dum) def data_tensorhead_from_tensmul(self, data, tensmul, tensorhead): """ This method is used when assigning components data to a ``TensMul`` object, it converts components data to a fully contravariant ndarray, which is then stored according to the ``TensorHead`` key. """ if data is None: return None return self._correct_signature_from_indices( data, tensmul.get_indices(), tensmul.free, tensmul.dum, True) def data_from_tensor(self, tensor): """ This method corrects the components data to the right signature (covariant/contravariant) using the metric associated with each ``TensorIndexType``. """ tensorhead = tensor.component if tensorhead.data is None: return None return self._correct_signature_from_indices( tensorhead.data, tensor.get_indices(), tensor.free, tensor.dum) def _assign_data_to_tensor_expr(self, key, data): if isinstance(key, TensAdd): raise ValueError('cannot assign data to TensAdd') # here it is assumed that `key` is a `TensMul` instance. if len(key.components) != 1: raise ValueError('cannot assign data to TensMul with multiple components') tensorhead = key.components[0] newdata = self.data_tensorhead_from_tensmul(data, key, tensorhead) return tensorhead, newdata def _check_permutations_on_data(self, tens, data): from .array import permutedims from .array.arrayop import Flatten if isinstance(tens, TensorHead): rank = tens.rank generators = tens.symmetry.generators elif isinstance(tens, Tensor): rank = tens.rank generators = tens.components[0].symmetry.generators elif isinstance(tens, TensorIndexType): rank = tens.metric.rank generators = tens.metric.symmetry.generators # Every generator is a permutation, check that by permuting the array # by that permutation, the array will be the same, except for a # possible sign change if the permutation admits it. for gener in generators: sign_change = +1 if (gener(rank) == rank) else -1 data_swapped = data last_data = data permute_axes = list(map(gener, range(rank))) # the order of a permutation is the number of times to get the # identity by applying that permutation. for i in range(gener.order()-1): data_swapped = permutedims(data_swapped, permute_axes) # if any value in the difference array is non-zero, raise an error: if any(Flatten(last_data - sign_change*data_swapped)): raise ValueError("Component data symmetry structure error") last_data = data_swapped def __setitem__(self, key, value): """ Set the components data of a tensor object/expression. Explanation =========== Components data are transformed to the all-contravariant form and stored with the corresponding ``TensorHead`` object. If a ``TensorHead`` object cannot be uniquely identified, it will raise an error. """ data = _TensorDataLazyEvaluator.parse_data(value) self._check_permutations_on_data(key, data) # TensorHead and TensorIndexType can be assigned data directly, while # TensMul must first convert data to a fully contravariant form, and # assign it to its corresponding TensorHead single component. if not isinstance(key, (TensorHead, TensorIndexType)): key, data = self._assign_data_to_tensor_expr(key, data) if isinstance(key, TensorHead): for dim, indextype in zip(data.shape, key.index_types): if indextype.data is None: raise ValueError("index type {} has no components data"\ " associated (needed to raise/lower index)".format(indextype)) if not indextype.dim.is_number: continue if dim != indextype.dim: raise ValueError("wrong dimension of ndarray") self._substitutions_dict[key] = data def __delitem__(self, key): del self._substitutions_dict[key] def __contains__(self, key): return key in self._substitutions_dict def add_metric_data(self, metric, data): """ Assign data to the ``metric`` tensor. The metric tensor behaves in an anomalous way when raising and lowering indices. Explanation =========== A fully covariant metric is the inverse transpose of the fully contravariant metric (it is meant matrix inverse). If the metric is symmetric, the transpose is not necessary and mixed covariant/contravariant metrics are Kronecker deltas. """ # hard assignment, data should not be added to `TensorHead` for metric: # the problem with `TensorHead` is that the metric is anomalous, i.e. # raising and lowering the index means considering the metric or its # inverse, this is not the case for other tensors. self._substitutions_dict_tensmul[metric, True, True] = data inverse_transpose = self.inverse_transpose_matrix(data) # in symmetric spaces, the transpose is the same as the original matrix, # the full covariant metric tensor is the inverse transpose, so this # code will be able to handle non-symmetric metrics. self._substitutions_dict_tensmul[metric, False, False] = inverse_transpose # now mixed cases, these are identical to the unit matrix if the metric # is symmetric. m = data.tomatrix() invt = inverse_transpose.tomatrix() self._substitutions_dict_tensmul[metric, True, False] = m * invt self._substitutions_dict_tensmul[metric, False, True] = invt * m @staticmethod def _flip_index_by_metric(data, metric, pos): from .array import tensorproduct, tensorcontraction mdim = metric.rank() ddim = data.rank() if pos == 0: data = tensorcontraction( tensorproduct( metric, data ), (1, mdim+pos) ) else: data = tensorcontraction( tensorproduct( data, metric ), (pos, ddim) ) return data @staticmethod def inverse_matrix(ndarray): m = ndarray.tomatrix().inv() return _TensorDataLazyEvaluator.parse_data(m) @staticmethod def inverse_transpose_matrix(ndarray): m = ndarray.tomatrix().inv().T return _TensorDataLazyEvaluator.parse_data(m) @staticmethod def _correct_signature_from_indices(data, indices, free, dum, inverse=False): """ Utility function to correct the values inside the components data ndarray according to whether indices are covariant or contravariant. It uses the metric matrix to lower values of covariant indices. """ # change the ndarray values according covariantness/contravariantness of the indices # use the metric for i, indx in enumerate(indices): if not indx.is_up and not inverse: data = _TensorDataLazyEvaluator._flip_index_by_metric(data, indx.tensor_index_type.data, i) elif not indx.is_up and inverse: data = _TensorDataLazyEvaluator._flip_index_by_metric( data, _TensorDataLazyEvaluator.inverse_matrix(indx.tensor_index_type.data), i ) return data @staticmethod def _sort_data_axes(old, new): from .array import permutedims new_data = old.data.copy() old_free = [i[0] for i in old.free] new_free = [i[0] for i in new.free] for i in range(len(new_free)): for j in range(i, len(old_free)): if old_free[j] == new_free[i]: old_free[i], old_free[j] = old_free[j], old_free[i] new_data = permutedims(new_data, (i, j)) break return new_data @staticmethod def add_rearrange_tensmul_parts(new_tensmul, old_tensmul): def sorted_compo(): return _TensorDataLazyEvaluator._sort_data_axes(old_tensmul, new_tensmul) _TensorDataLazyEvaluator._substitutions_dict[new_tensmul] = sorted_compo() @staticmethod def parse_data(data): """ Transform ``data`` to array. The parameter ``data`` may contain data in various formats, e.g. nested lists, SymPy ``Matrix``, and so on. Examples ======== >>> from sympy.tensor.tensor import _TensorDataLazyEvaluator >>> _TensorDataLazyEvaluator.parse_data([1, 3, -6, 12]) [1, 3, -6, 12] >>> _TensorDataLazyEvaluator.parse_data([[1, 2], [4, 7]]) [[1, 2], [4, 7]] """ from .array import MutableDenseNDimArray if not isinstance(data, MutableDenseNDimArray): if len(data) == 2 and hasattr(data[0], '__call__'): data = MutableDenseNDimArray(data[0], data[1]) else: data = MutableDenseNDimArray(data) return data _tensor_data_substitution_dict = _TensorDataLazyEvaluator() class _TensorManager: """ Class to manage tensor properties. Notes ===== Tensors belong to tensor commutation groups; each group has a label ``comm``; there are predefined labels: ``0`` tensors commuting with any other tensor ``1`` tensors anticommuting among themselves ``2`` tensors not commuting, apart with those with ``comm=0`` Other groups can be defined using ``set_comm``; tensors in those groups commute with those with ``comm=0``; by default they do not commute with any other group. """ def __init__(self): self._comm_init() def _comm_init(self): self._comm = [{} for i in range(3)] for i in range(3): self._comm[0][i] = 0 self._comm[i][0] = 0 self._comm[1][1] = 1 self._comm[2][1] = None self._comm[1][2] = None self._comm_symbols2i = {0:0, 1:1, 2:2} self._comm_i2symbol = {0:0, 1:1, 2:2} @property def comm(self): return self._comm def comm_symbols2i(self, i): """ Get the commutation group number corresponding to ``i``. ``i`` can be a symbol or a number or a string. If ``i`` is not already defined its commutation group number is set. """ if i not in self._comm_symbols2i: n = len(self._comm) self._comm.append({}) self._comm[n][0] = 0 self._comm[0][n] = 0 self._comm_symbols2i[i] = n self._comm_i2symbol[n] = i return n return self._comm_symbols2i[i] def comm_i2symbol(self, i): """ Returns the symbol corresponding to the commutation group number. """ return self._comm_i2symbol[i] def set_comm(self, i, j, c): """ Set the commutation parameter ``c`` for commutation groups ``i, j``. Parameters ========== i, j : symbols representing commutation groups c : group commutation number Notes ===== ``i, j`` can be symbols, strings or numbers, apart from ``0, 1`` and ``2`` which are reserved respectively for commuting, anticommuting tensors and tensors not commuting with any other group apart with the commuting tensors. For the remaining cases, use this method to set the commutation rules; by default ``c=None``. The group commutation number ``c`` is assigned in correspondence to the group commutation symbols; it can be 0 commuting 1 anticommuting None no commutation property Examples ======== ``G`` and ``GH`` do not commute with themselves and commute with each other; A is commuting. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorManager, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz') >>> i0,i1,i2,i3,i4 = tensor_indices('i0:5', Lorentz) >>> A = TensorHead('A', [Lorentz]) >>> G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm') >>> GH = TensorHead('GH', [Lorentz], TensorSymmetry.no_symmetry(1), 'GHcomm') >>> TensorManager.set_comm('Gcomm', 'GHcomm', 0) >>> (GH(i1)*G(i0)).canon_bp() G(i0)*GH(i1) >>> (G(i1)*G(i0)).canon_bp() G(i1)*G(i0) >>> (G(i1)*A(i0)).canon_bp() A(i0)*G(i1) """ if c not in (0, 1, None): raise ValueError('`c` can assume only the values 0, 1 or None') if i not in self._comm_symbols2i: n = len(self._comm) self._comm.append({}) self._comm[n][0] = 0 self._comm[0][n] = 0 self._comm_symbols2i[i] = n self._comm_i2symbol[n] = i if j not in self._comm_symbols2i: n = len(self._comm) self._comm.append({}) self._comm[0][n] = 0 self._comm[n][0] = 0 self._comm_symbols2i[j] = n self._comm_i2symbol[n] = j ni = self._comm_symbols2i[i] nj = self._comm_symbols2i[j] self._comm[ni][nj] = c self._comm[nj][ni] = c def set_comms(self, *args): """ Set the commutation group numbers ``c`` for symbols ``i, j``. Parameters ========== args : sequence of ``(i, j, c)`` """ for i, j, c in args: self.set_comm(i, j, c) def get_comm(self, i, j): """ Return the commutation parameter for commutation group numbers ``i, j`` see ``_TensorManager.set_comm`` """ return self._comm[i].get(j, 0 if i == 0 or j == 0 else None) def clear(self): """ Clear the TensorManager. """ self._comm_init() TensorManager = _TensorManager() class TensorIndexType(Basic): """ A TensorIndexType is characterized by its name and its metric. Parameters ========== name : name of the tensor type dummy_name : name of the head of dummy indices dim : dimension, it can be a symbol or an integer or ``None`` eps_dim : dimension of the epsilon tensor metric_symmetry : integer that denotes metric symmetry or ``None`` for no metric metric_name : string with the name of the metric tensor Attributes ========== ``metric`` : the metric tensor ``delta`` : ``Kronecker delta`` ``epsilon`` : the ``Levi-Civita epsilon`` tensor ``data`` : (deprecated) a property to add ``ndarray`` values, to work in a specified basis. Notes ===== The possible values of the ``metric_symmetry`` parameter are: ``1`` : metric tensor is fully symmetric ``0`` : metric tensor possesses no index symmetry ``-1`` : metric tensor is fully antisymmetric ``None``: there is no metric tensor (metric equals to ``None``) The metric is assumed to be symmetric by default. It can also be set to a custom tensor by the ``.set_metric()`` method. If there is a metric the metric is used to raise and lower indices. In the case of non-symmetric metric, the following raising and lowering conventions will be adopted: ``psi(a) = g(a, b)*psi(-b); chi(-a) = chi(b)*g(-b, -a)`` From these it is easy to find: ``g(-a, b) = delta(-a, b)`` where ``delta(-a, b) = delta(b, -a)`` is the ``Kronecker delta`` (see ``TensorIndex`` for the conventions on indices). For antisymmetric metrics there is also the following equality: ``g(a, -b) = -delta(a, -b)`` If there is no metric it is not possible to raise or lower indices; e.g. the index of the defining representation of ``SU(N)`` is 'covariant' and the conjugate representation is 'contravariant'; for ``N > 2`` they are linearly independent. ``eps_dim`` is by default equal to ``dim``, if the latter is an integer; else it can be assigned (for use in naive dimensional regularization); if ``eps_dim`` is not an integer ``epsilon`` is ``None``. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> Lorentz.metric metric(Lorentz,Lorentz) """ def __new__(cls, name, dummy_name=None, dim=None, eps_dim=None, metric_symmetry=1, metric_name='metric', **kwargs): if 'dummy_fmt' in kwargs: dummy_fmt = kwargs['dummy_fmt'] sympy_deprecation_warning( f""" The dummy_fmt keyword to TensorIndexType is deprecated. Use dummy_name={dummy_fmt} instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorindextype-dummy-fmt", ) dummy_name = dummy_fmt if isinstance(name, str): name = Symbol(name) if dummy_name is None: dummy_name = str(name)[0] if isinstance(dummy_name, str): dummy_name = Symbol(dummy_name) if dim is None: dim = Symbol("dim_" + dummy_name.name) else: dim = sympify(dim) if eps_dim is None: eps_dim = dim else: eps_dim = sympify(eps_dim) metric_symmetry = sympify(metric_symmetry) if isinstance(metric_name, str): metric_name = Symbol(metric_name) if 'metric' in kwargs: SymPyDeprecationWarning( """ The 'metric' keyword argument to TensorIndexType is deprecated. Use the 'metric_symmetry' keyword argument or the TensorIndexType.set_metric() method instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorindextype-metric", ) metric = kwargs.get('metric') if metric is not None: if metric in (True, False, 0, 1): metric_name = 'metric' #metric_antisym = metric else: metric_name = metric.name #metric_antisym = metric.antisym if metric: metric_symmetry = -1 else: metric_symmetry = 1 obj = Basic.__new__(cls, name, dummy_name, dim, eps_dim, metric_symmetry, metric_name) obj._autogenerated = [] return obj @property def name(self): return self.args[0].name @property def dummy_name(self): return self.args[1].name @property def dim(self): return self.args[2] @property def eps_dim(self): return self.args[3] @memoize_property def metric(self): metric_symmetry = self.args[4] metric_name = self.args[5] if metric_symmetry is None: return None if metric_symmetry == 0: symmetry = TensorSymmetry.no_symmetry(2) elif metric_symmetry == 1: symmetry = TensorSymmetry.fully_symmetric(2) elif metric_symmetry == -1: symmetry = TensorSymmetry.fully_symmetric(-2) return TensorHead(metric_name, [self]*2, symmetry) @memoize_property def delta(self): return TensorHead('KD', [self]*2, TensorSymmetry.fully_symmetric(2)) @memoize_property def epsilon(self): if not isinstance(self.eps_dim, (SYMPY_INTS, Integer)): return None symmetry = TensorSymmetry.fully_symmetric(-self.eps_dim) return TensorHead('Eps', [self]*self.eps_dim, symmetry) def set_metric(self, tensor): self._metric = tensor def __lt__(self, other): return self.name < other.name def __str__(self): return self.name __repr__ = __str__ # Everything below this line is deprecated @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self] @data.setter def data(self, data): deprecate_data() # This assignment is a bit controversial, should metric components be assigned # to the metric only or also to the TensorIndexType object? The advantage here # is the ability to assign a 1D array and transform it to a 2D diagonal array. from .array import MutableDenseNDimArray data = _TensorDataLazyEvaluator.parse_data(data) if data.rank() > 2: raise ValueError("data have to be of rank 1 (diagonal metric) or 2.") if data.rank() == 1: if self.dim.is_number: nda_dim = data.shape[0] if nda_dim != self.dim: raise ValueError("Dimension mismatch") dim = data.shape[0] newndarray = MutableDenseNDimArray.zeros(dim, dim) for i, val in enumerate(data): newndarray[i, i] = val data = newndarray dim1, dim2 = data.shape if dim1 != dim2: raise ValueError("Non-square matrix tensor.") if self.dim.is_number: if self.dim != dim1: raise ValueError("Dimension mismatch") _tensor_data_substitution_dict[self] = data _tensor_data_substitution_dict.add_metric_data(self.metric, data) with ignore_warnings(SymPyDeprecationWarning): delta = self.get_kronecker_delta() i1 = TensorIndex('i1', self) i2 = TensorIndex('i2', self) with ignore_warnings(SymPyDeprecationWarning): delta(i1, -i2).data = _TensorDataLazyEvaluator.parse_data(eye(dim1)) @data.deleter def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] if self.metric in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self.metric] @deprecated( """ The TensorIndexType.get_kronecker_delta() method is deprecated. Use the TensorIndexType.delta attribute instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorindextype-methods", ) def get_kronecker_delta(self): sym2 = TensorSymmetry(get_symmetric_group_sgs(2)) delta = TensorHead('KD', [self]*2, sym2) return delta @deprecated( """ The TensorIndexType.get_epsilon() method is deprecated. Use the TensorIndexType.epsilon attribute instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorindextype-methods", ) def get_epsilon(self): if not isinstance(self._eps_dim, (SYMPY_INTS, Integer)): return None sym = TensorSymmetry(get_symmetric_group_sgs(self._eps_dim, 1)) epsilon = TensorHead('Eps', [self]*self._eps_dim, sym) return epsilon def _components_data_full_destroy(self): """ EXPERIMENTAL: do not rely on this API method. This destroys components data associated to the ``TensorIndexType``, if any, specifically: * metric tensor data * Kronecker tensor data """ if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] def delete_tensmul_data(key): if key in _tensor_data_substitution_dict._substitutions_dict_tensmul: del _tensor_data_substitution_dict._substitutions_dict_tensmul[key] # delete metric data: delete_tensmul_data((self.metric, True, True)) delete_tensmul_data((self.metric, True, False)) delete_tensmul_data((self.metric, False, True)) delete_tensmul_data((self.metric, False, False)) # delete delta tensor data: delta = self.get_kronecker_delta() if delta in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[delta] class TensorIndex(Basic): """ Represents a tensor index Parameters ========== name : name of the index, or ``True`` if you want it to be automatically assigned tensor_index_type : ``TensorIndexType`` of the index is_up : flag for contravariant index (is_up=True by default) Attributes ========== ``name`` ``tensor_index_type`` ``is_up`` Notes ===== Tensor indices are contracted with the Einstein summation convention. An index can be in contravariant or in covariant form; in the latter case it is represented prepending a ``-`` to the index name. Adding ``-`` to a covariant (is_up=False) index makes it contravariant. Dummy indices have a name with head given by ``tensor_inde_type.dummy_name`` with underscore and a number. Similar to ``symbols`` multiple contravariant indices can be created at once using ``tensor_indices(s, typ)``, where ``s`` is a string of names. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, TensorIndex, TensorHead, tensor_indices >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> mu = TensorIndex('mu', Lorentz, is_up=False) >>> nu, rho = tensor_indices('nu, rho', Lorentz) >>> A = TensorHead('A', [Lorentz, Lorentz]) >>> A(mu, nu) A(-mu, nu) >>> A(-mu, -rho) A(mu, -rho) >>> A(mu, -mu) A(-L_0, L_0) """ def __new__(cls, name, tensor_index_type, is_up=True): if isinstance(name, str): name_symbol = Symbol(name) elif isinstance(name, Symbol): name_symbol = name elif name is True: name = "_i{}".format(len(tensor_index_type._autogenerated)) name_symbol = Symbol(name) tensor_index_type._autogenerated.append(name_symbol) else: raise ValueError("invalid name") is_up = sympify(is_up) return Basic.__new__(cls, name_symbol, tensor_index_type, is_up) @property def name(self): return self.args[0].name @property def tensor_index_type(self): return self.args[1] @property def is_up(self): return self.args[2] def _print(self): s = self.name if not self.is_up: s = '-%s' % s return s def __lt__(self, other): return ((self.tensor_index_type, self.name) < (other.tensor_index_type, other.name)) def __neg__(self): t1 = TensorIndex(self.name, self.tensor_index_type, (not self.is_up)) return t1 def tensor_indices(s, typ): """ Returns list of tensor indices given their names and their types. Parameters ========== s : string of comma separated names of indices typ : ``TensorIndexType`` of the indices Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz) """ if isinstance(s, str): a = [x.name for x in symbols(s, seq=True)] else: raise ValueError('expecting a string') tilist = [TensorIndex(i, typ) for i in a] if len(tilist) == 1: return tilist[0] return tilist class TensorSymmetry(Basic): """ Monoterm symmetry of a tensor (i.e. any symmetric or anti-symmetric index permutation). For the relevant terminology see ``tensor_can.py`` section of the combinatorics module. Parameters ========== bsgs : tuple ``(base, sgs)`` BSGS of the symmetry of the tensor Attributes ========== ``base`` : base of the BSGS ``generators`` : generators of the BSGS ``rank`` : rank of the tensor Notes ===== A tensor can have an arbitrary monoterm symmetry provided by its BSGS. Multiterm symmetries, like the cyclic symmetry of the Riemann tensor (i.e., Bianchi identity), are not covered. See combinatorics module for information on how to generate BSGS for a general index permutation group. Simple symmetries can be generated using built-in methods. See Also ======== sympy.combinatorics.tensor_can.get_symmetric_group_sgs Examples ======== Define a symmetric tensor of rank 2 >>> from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> sym = TensorSymmetry(get_symmetric_group_sgs(2)) >>> T = TensorHead('T', [Lorentz]*2, sym) Note, that the same can also be done using built-in TensorSymmetry methods >>> sym2 = TensorSymmetry.fully_symmetric(2) >>> sym == sym2 True """ def __new__(cls, *args, **kw_args): if len(args) == 1: base, generators = args[0] elif len(args) == 2: base, generators = args else: raise TypeError("bsgs required, either two separate parameters or one tuple") if not isinstance(base, Tuple): base = Tuple(*base) if not isinstance(generators, Tuple): generators = Tuple(*generators) return Basic.__new__(cls, base, generators, **kw_args) @property def base(self): return self.args[0] @property def generators(self): return self.args[1] @property def rank(self): return self.generators[0].size - 2 @classmethod def fully_symmetric(cls, rank): """ Returns a fully symmetric (antisymmetric if ``rank``<0) TensorSymmetry object for ``abs(rank)`` indices. """ if rank > 0: bsgs = get_symmetric_group_sgs(rank, False) elif rank < 0: bsgs = get_symmetric_group_sgs(-rank, True) elif rank == 0: bsgs = ([], [Permutation(1)]) return TensorSymmetry(bsgs) @classmethod def direct_product(cls, *args): """ Returns a TensorSymmetry object that is being a direct product of fully (anti-)symmetric index permutation groups. Notes ===== Some examples for different values of ``(*args)``: ``(1)`` vector, equivalent to ``TensorSymmetry.fully_symmetric(1)`` ``(2)`` tensor with 2 symmetric indices, equivalent to ``.fully_symmetric(2)`` ``(-2)`` tensor with 2 antisymmetric indices, equivalent to ``.fully_symmetric(-2)`` ``(2, -2)`` tensor with the first 2 indices commuting and the last 2 anticommuting ``(1, 1, 1)`` tensor with 3 indices without any symmetry """ base, sgs = [], [Permutation(1)] for arg in args: if arg > 0: bsgs2 = get_symmetric_group_sgs(arg, False) elif arg < 0: bsgs2 = get_symmetric_group_sgs(-arg, True) else: continue base, sgs = bsgs_direct_product(base, sgs, *bsgs2) return TensorSymmetry(base, sgs) @classmethod def riemann(cls): """ Returns a monotorem symmetry of the Riemann tensor """ return TensorSymmetry(riemann_bsgs) @classmethod def no_symmetry(cls, rank): """ TensorSymmetry object for ``rank`` indices with no symmetry """ return TensorSymmetry([], [Permutation(rank+1)]) @deprecated( """ The tensorsymmetry() function is deprecated. Use the TensorSymmetry constructor instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorsymmetry", ) def tensorsymmetry(*args): """ Returns a ``TensorSymmetry`` object. This method is deprecated, use ``TensorSymmetry.direct_product()`` or ``.riemann()`` instead. Explanation =========== One can represent a tensor with any monoterm slot symmetry group using a BSGS. ``args`` can be a BSGS ``args[0]`` base ``args[1]`` sgs Usually tensors are in (direct products of) representations of the symmetric group; ``args`` can be a list of lists representing the shapes of Young tableaux Notes ===== For instance: ``[[1]]`` vector ``[[1]*n]`` symmetric tensor of rank ``n`` ``[[n]]`` antisymmetric tensor of rank ``n`` ``[[2, 2]]`` monoterm slot symmetry of the Riemann tensor ``[[1],[1]]`` vector*vector ``[[2],[1],[1]`` (antisymmetric tensor)*vector*vector Notice that with the shape ``[2, 2]`` we associate only the monoterm symmetries of the Riemann tensor; this is an abuse of notation, since the shape ``[2, 2]`` corresponds usually to the irreducible representation characterized by the monoterm symmetries and by the cyclic symmetry. """ from sympy.combinatorics import Permutation def tableau2bsgs(a): if len(a) == 1: # antisymmetric vector n = a[0] bsgs = get_symmetric_group_sgs(n, 1) else: if all(x == 1 for x in a): # symmetric vector n = len(a) bsgs = get_symmetric_group_sgs(n) elif a == [2, 2]: bsgs = riemann_bsgs else: raise NotImplementedError return bsgs if not args: return TensorSymmetry(Tuple(), Tuple(Permutation(1))) if len(args) == 2 and isinstance(args[1][0], Permutation): return TensorSymmetry(args) base, sgs = tableau2bsgs(args[0]) for a in args[1:]: basex, sgsx = tableau2bsgs(a) base, sgs = bsgs_direct_product(base, sgs, basex, sgsx) return TensorSymmetry(Tuple(base, sgs)) @deprecated( "TensorType is deprecated. Use tensor_heads() instead.", deprecated_since_version="1.5", active_deprecations_target="deprecated-tensortype", ) class TensorType(Basic): """ Class of tensor types. Deprecated, use tensor_heads() instead. Parameters ========== index_types : list of ``TensorIndexType`` of the tensor indices symmetry : ``TensorSymmetry`` of the tensor Attributes ========== ``index_types`` ``symmetry`` ``types`` : list of ``TensorIndexType`` without repetitions """ is_commutative = False def __new__(cls, index_types, symmetry, **kw_args): assert symmetry.rank == len(index_types) obj = Basic.__new__(cls, Tuple(*index_types), symmetry, **kw_args) return obj @property def index_types(self): return self.args[0] @property def symmetry(self): return self.args[1] @property def types(self): return sorted(set(self.index_types), key=lambda x: x.name) def __str__(self): return 'TensorType(%s)' % ([str(x) for x in self.index_types]) def __call__(self, s, comm=0): """ Return a TensorHead object or a list of TensorHead objects. Parameters ========== s : name or string of names. comm : Commutation group. see ``_TensorManager.set_comm`` """ if isinstance(s, str): names = [x.name for x in symbols(s, seq=True)] else: raise ValueError('expecting a string') if len(names) == 1: return TensorHead(names[0], self.index_types, self.symmetry, comm) else: return [TensorHead(name, self.index_types, self.symmetry, comm) for name in names] @deprecated( """ The tensorhead() function is deprecated. Use tensor_heads() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorhead", ) def tensorhead(name, typ, sym=None, comm=0): """ Function generating tensorhead(s). This method is deprecated, use TensorHead constructor or tensor_heads() instead. Parameters ========== name : name or sequence of names (as in ``symbols``) typ : index types sym : same as ``*args`` in ``tensorsymmetry`` comm : commutation group number see ``_TensorManager.set_comm`` """ if sym is None: sym = [[1] for i in range(len(typ))] with ignore_warnings(SymPyDeprecationWarning): sym = tensorsymmetry(*sym) return TensorHead(name, typ, sym, comm) class TensorHead(Basic): """ Tensor head of the tensor. Parameters ========== name : name of the tensor index_types : list of TensorIndexType symmetry : TensorSymmetry of the tensor comm : commutation group number Attributes ========== ``name`` ``index_types`` ``rank`` : total number of indices ``symmetry`` ``comm`` : commutation group Notes ===== Similar to ``symbols`` multiple TensorHeads can be created using ``tensorhead(s, typ, sym=None, comm=0)`` function, where ``s`` is the string of names and ``sym`` is the monoterm tensor symmetry (see ``tensorsymmetry``). A ``TensorHead`` belongs to a commutation group, defined by a symbol on number ``comm`` (see ``_TensorManager.set_comm``); tensors in a commutation group have the same commutation properties; by default ``comm`` is ``0``, the group of the commuting tensors. Examples ======== Define a fully antisymmetric tensor of rank 2: >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> asym2 = TensorSymmetry.fully_symmetric(-2) >>> A = TensorHead('A', [Lorentz, Lorentz], asym2) Examples with ndarray values, the components data assigned to the ``TensorHead`` object are assumed to be in a fully-contravariant representation. In case it is necessary to assign components data which represents the values of a non-fully covariant tensor, see the other examples. >>> from sympy.tensor.tensor import tensor_indices >>> from sympy import diag >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> i0, i1 = tensor_indices('i0:2', Lorentz) Specify a replacement dictionary to keep track of the arrays to use for replacements in the tensorial expression. The ``TensorIndexType`` is associated to the metric used for contractions (in fully covariant form): >>> repl = {Lorentz: diag(1, -1, -1, -1)} Let's see some examples of working with components with the electromagnetic tensor: >>> from sympy import symbols >>> Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z') >>> c = symbols('c', positive=True) Let's define `F`, an antisymmetric tensor: >>> F = TensorHead('F', [Lorentz, Lorentz], asym2) Let's update the dictionary to contain the matrix to use in the replacements: >>> repl.update({F(-i0, -i1): [ ... [0, Ex/c, Ey/c, Ez/c], ... [-Ex/c, 0, -Bz, By], ... [-Ey/c, Bz, 0, -Bx], ... [-Ez/c, -By, Bx, 0]]}) Now it is possible to retrieve the contravariant form of the Electromagnetic tensor: >>> F(i0, i1).replace_with_arrays(repl, [i0, i1]) [[0, -E_x/c, -E_y/c, -E_z/c], [E_x/c, 0, -B_z, B_y], [E_y/c, B_z, 0, -B_x], [E_z/c, -B_y, B_x, 0]] and the mixed contravariant-covariant form: >>> F(i0, -i1).replace_with_arrays(repl, [i0, -i1]) [[0, E_x/c, E_y/c, E_z/c], [E_x/c, 0, B_z, -B_y], [E_y/c, -B_z, 0, B_x], [E_z/c, B_y, -B_x, 0]] Energy-momentum of a particle may be represented as: >>> from sympy import symbols >>> P = TensorHead('P', [Lorentz], TensorSymmetry.no_symmetry(1)) >>> E, px, py, pz = symbols('E p_x p_y p_z', positive=True) >>> repl.update({P(i0): [E, px, py, pz]}) The contravariant and covariant components are, respectively: >>> P(i0).replace_with_arrays(repl, [i0]) [E, p_x, p_y, p_z] >>> P(-i0).replace_with_arrays(repl, [-i0]) [E, -p_x, -p_y, -p_z] The contraction of a 1-index tensor by itself: >>> expr = P(i0)*P(-i0) >>> expr.replace_with_arrays(repl, []) E**2 - p_x**2 - p_y**2 - p_z**2 """ is_commutative = False def __new__(cls, name, index_types, symmetry=None, comm=0): if isinstance(name, str): name_symbol = Symbol(name) elif isinstance(name, Symbol): name_symbol = name else: raise ValueError("invalid name") if symmetry is None: symmetry = TensorSymmetry.no_symmetry(len(index_types)) else: assert symmetry.rank == len(index_types) obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), symmetry) obj.comm = TensorManager.comm_symbols2i(comm) return obj @property def name(self): return self.args[0].name @property def index_types(self): return list(self.args[1]) @property def symmetry(self): return self.args[2] @property def rank(self): return len(self.index_types) def __lt__(self, other): return (self.name, self.index_types) < (other.name, other.index_types) def commutes_with(self, other): """ Returns ``0`` if ``self`` and ``other`` commute, ``1`` if they anticommute. Returns ``None`` if ``self`` and ``other`` neither commute nor anticommute. """ r = TensorManager.get_comm(self.comm, other.comm) return r def _print(self): return '%s(%s)' %(self.name, ','.join([str(x) for x in self.index_types])) def __call__(self, *indices, **kw_args): """ Returns a tensor with indices. Explanation =========== There is a special behavior in case of indices denoted by ``True``, they are considered auto-matrix indices, their slots are automatically filled, and confer to the tensor the behavior of a matrix or vector upon multiplication with another tensor containing auto-matrix indices of the same ``TensorIndexType``. This means indices get summed over the same way as in matrix multiplication. For matrix behavior, define two auto-matrix indices, for vector behavior define just one. Indices can also be strings, in which case the attribute ``index_types`` is used to convert them to proper ``TensorIndex``. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, TensorHead >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> a, b = tensor_indices('a,b', Lorentz) >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2)) >>> t = A(a, -b) >>> t A(a, -b) """ updated_indices = [] for idx, typ in zip(indices, self.index_types): if isinstance(idx, str): idx = idx.strip().replace(" ", "") if idx.startswith('-'): updated_indices.append(TensorIndex(idx[1:], typ, is_up=False)) else: updated_indices.append(TensorIndex(idx, typ)) else: updated_indices.append(idx) updated_indices += indices[len(updated_indices):] tensor = Tensor(self, updated_indices, **kw_args) return tensor.doit() # Everything below this line is deprecated def __pow__(self, other): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self.data is None: raise ValueError("No power on abstract tensors.") from .array import tensorproduct, tensorcontraction metrics = [_.data for _ in self.index_types] marray = self.data marraydim = marray.rank() for metric in metrics: marray = tensorproduct(marray, metric, marray) marray = tensorcontraction(marray, (0, marraydim), (marraydim+1, marraydim+2)) return marray ** (other * S.Half) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self] @data.setter def data(self, data): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): _tensor_data_substitution_dict[self] = data @data.deleter def data(self): deprecate_data() if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] def __iter__(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data.__iter__() def _components_data_full_destroy(self): """ EXPERIMENTAL: do not rely on this API method. Destroy components data associated to the ``TensorHead`` object, this checks for attached components data, and destroys components data too. """ # do not garbage collect Kronecker tensor (it should be done by # ``TensorIndexType`` garbage collection) deprecate_data() if self.name == "KD": return # the data attached to a tensor must be deleted only by the TensorHead # destructor. If the TensorHead is deleted, it means that there are no # more instances of that tensor anywhere. if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] def tensor_heads(s, index_types, symmetry=None, comm=0): """ Returns a sequence of TensorHeads from a string `s` """ if isinstance(s, str): names = [x.name for x in symbols(s, seq=True)] else: raise ValueError('expecting a string') thlist = [TensorHead(name, index_types, symmetry, comm) for name in names] if len(thlist) == 1: return thlist[0] return thlist class _TensorMetaclass(ManagedProperties, ABCMeta): pass class TensExpr(Expr, metaclass=_TensorMetaclass): """ Abstract base class for tensor expressions Notes ===== A tensor expression is an expression formed by tensors; currently the sums of tensors are distributed. A ``TensExpr`` can be a ``TensAdd`` or a ``TensMul``. ``TensMul`` objects are formed by products of component tensors, and include a coefficient, which is a SymPy expression. In the internal representation contracted indices are represented by ``(ipos1, ipos2, icomp1, icomp2)``, where ``icomp1`` is the position of the component tensor with contravariant index, ``ipos1`` is the slot which the index occupies in that component tensor. Contracted indices are therefore nameless in the internal representation. """ _op_priority = 12.0 is_commutative = False def __neg__(self): return self*S.NegativeOne def __abs__(self): raise NotImplementedError def __add__(self, other): return TensAdd(self, other).doit() def __radd__(self, other): return TensAdd(other, self).doit() def __sub__(self, other): return TensAdd(self, -other).doit() def __rsub__(self, other): return TensAdd(other, -self).doit() def __mul__(self, other): """ Multiply two tensors using Einstein summation convention. Explanation =========== If the two tensors have an index in common, one contravariant and the other covariant, in their product the indices are summed Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> g = Lorentz.metric >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t1 = p(m0) >>> t2 = q(-m0) >>> t1*t2 p(L_0)*q(-L_0) """ return TensMul(self, other).doit() def __rmul__(self, other): return TensMul(other, self).doit() def __truediv__(self, other): other = _sympify(other) if isinstance(other, TensExpr): raise ValueError('cannot divide by a tensor') return TensMul(self, S.One/other).doit() def __rtruediv__(self, other): raise ValueError('cannot divide by a tensor') def __pow__(self, other): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self.data is None: raise ValueError("No power without ndarray data.") from .array import tensorproduct, tensorcontraction free = self.free marray = self.data mdim = marray.rank() for metric in free: marray = tensorcontraction( tensorproduct( marray, metric[0].tensor_index_type.data, marray), (0, mdim), (mdim+1, mdim+2) ) return marray ** (other * S.Half) def __rpow__(self, other): raise NotImplementedError @property @abstractmethod def nocoeff(self): raise NotImplementedError("abstract method") @property @abstractmethod def coeff(self): raise NotImplementedError("abstract method") @abstractmethod def get_indices(self): raise NotImplementedError("abstract method") @abstractmethod def get_free_indices(self): # type: () -> List[TensorIndex] raise NotImplementedError("abstract method") @abstractmethod def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> TensExpr raise NotImplementedError("abstract method") def fun_eval(self, *index_tuples): deprecate_fun_eval() return self.substitute_indices(*index_tuples) def get_matrix(self): """ DEPRECATED: do not use. Returns ndarray components data as a matrix, if components data are available and ndarray dimension does not exceed 2. """ from sympy.matrices.dense import Matrix deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if 0 < self.rank <= 2: rows = self.data.shape[0] columns = self.data.shape[1] if self.rank == 2 else 1 if self.rank == 2: mat_list = [] * rows for i in range(rows): mat_list.append([]) for j in range(columns): mat_list[i].append(self[i, j]) else: mat_list = [None] * rows for i in range(rows): mat_list[i] = self[i] return Matrix(mat_list) else: raise NotImplementedError( "missing multidimensional reduction to matrix.") @staticmethod def _get_indices_permutation(indices1, indices2): return [indices1.index(i) for i in indices2] def expand(self, **hints): return _expand(self, **hints).doit() def _expand(self, **kwargs): return self def _get_free_indices_set(self): indset = set() for arg in self.args: if isinstance(arg, TensExpr): indset.update(arg._get_free_indices_set()) return indset def _get_dummy_indices_set(self): indset = set() for arg in self.args: if isinstance(arg, TensExpr): indset.update(arg._get_dummy_indices_set()) return indset def _get_indices_set(self): indset = set() for arg in self.args: if isinstance(arg, TensExpr): indset.update(arg._get_indices_set()) return indset @property def _iterate_dummy_indices(self): dummy_set = self._get_dummy_indices_set() def recursor(expr, pos): if isinstance(expr, TensorIndex): if expr in dummy_set: yield (expr, pos) elif isinstance(expr, (Tuple, TensExpr)): for p, arg in enumerate(expr.args): yield from recursor(arg, pos+(p,)) return recursor(self, ()) @property def _iterate_free_indices(self): free_set = self._get_free_indices_set() def recursor(expr, pos): if isinstance(expr, TensorIndex): if expr in free_set: yield (expr, pos) elif isinstance(expr, (Tuple, TensExpr)): for p, arg in enumerate(expr.args): yield from recursor(arg, pos+(p,)) return recursor(self, ()) @property def _iterate_indices(self): def recursor(expr, pos): if isinstance(expr, TensorIndex): yield (expr, pos) elif isinstance(expr, (Tuple, TensExpr)): for p, arg in enumerate(expr.args): yield from recursor(arg, pos+(p,)) return recursor(self, ()) @staticmethod def _contract_and_permute_with_metric(metric, array, pos, dim): # TODO: add possibility of metric after (spinors) from .array import tensorcontraction, tensorproduct, permutedims array = tensorcontraction(tensorproduct(metric, array), (1, 2+pos)) permu = list(range(dim)) permu[0], permu[pos] = permu[pos], permu[0] return permutedims(array, permu) @staticmethod def _match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict): from .array import permutedims index_types1 = [i.tensor_index_type for i in free_ind1] # Check if variance of indices needs to be fixed: pos2up = [] pos2down = [] free2remaining = free_ind2[:] for pos1, index1 in enumerate(free_ind1): if index1 in free2remaining: pos2 = free2remaining.index(index1) free2remaining[pos2] = None continue if -index1 in free2remaining: pos2 = free2remaining.index(-index1) free2remaining[pos2] = None free_ind2[pos2] = index1 if index1.is_up: pos2up.append(pos2) else: pos2down.append(pos2) else: index2 = free2remaining[pos1] if index2 is None: raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2)) free2remaining[pos1] = None free_ind2[pos1] = index1 if index1.is_up ^ index2.is_up: if index1.is_up: pos2up.append(pos1) else: pos2down.append(pos1) if len(set(free_ind1) & set(free_ind2)) < len(free_ind1): raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2)) # Raise indices: for pos in pos2up: index_type_pos = index_types1[pos] # type: TensorIndexType if index_type_pos not in replacement_dict: raise ValueError("No metric provided to lower index") metric = replacement_dict[index_type_pos] metric_inverse = _TensorDataLazyEvaluator.inverse_matrix(metric) array = TensExpr._contract_and_permute_with_metric(metric_inverse, array, pos, len(free_ind1)) # Lower indices: for pos in pos2down: index_type_pos = index_types1[pos] # type: TensorIndexType if index_type_pos not in replacement_dict: raise ValueError("No metric provided to lower index") metric = replacement_dict[index_type_pos] array = TensExpr._contract_and_permute_with_metric(metric, array, pos, len(free_ind1)) if free_ind1: permutation = TensExpr._get_indices_permutation(free_ind2, free_ind1) array = permutedims(array, permutation) if hasattr(array, "rank") and array.rank() == 0: array = array[()] return free_ind2, array def replace_with_arrays(self, replacement_dict, indices=None): """ Replace the tensorial expressions with arrays. The final array will correspond to the N-dimensional array with indices arranged according to ``indices``. Parameters ========== replacement_dict dictionary containing the replacement rules for tensors. indices the index order with respect to which the array is read. The original index order will be used if no value is passed. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices >>> from sympy.tensor.tensor import TensorHead >>> from sympy import symbols, diag >>> L = TensorIndexType("L") >>> i, j = tensor_indices("i j", L) >>> A = TensorHead("A", [L]) >>> A(i).replace_with_arrays({A(i): [1, 2]}, [i]) [1, 2] Since 'indices' is optional, we can also call replace_with_arrays by this way if no specific index order is needed: >>> A(i).replace_with_arrays({A(i): [1, 2]}) [1, 2] >>> expr = A(i)*A(j) >>> expr.replace_with_arrays({A(i): [1, 2]}) [[1, 2], [2, 4]] For contractions, specify the metric of the ``TensorIndexType``, which in this case is ``L``, in its covariant form: >>> expr = A(i)*A(-i) >>> expr.replace_with_arrays({A(i): [1, 2], L: diag(1, -1)}) -3 Symmetrization of an array: >>> H = TensorHead("H", [L, L]) >>> a, b, c, d = symbols("a b c d") >>> expr = H(i, j)/2 + H(j, i)/2 >>> expr.replace_with_arrays({H(i, j): [[a, b], [c, d]]}) [[a, b/2 + c/2], [b/2 + c/2, d]] Anti-symmetrization of an array: >>> expr = H(i, j)/2 - H(j, i)/2 >>> repl = {H(i, j): [[a, b], [c, d]]} >>> expr.replace_with_arrays(repl) [[0, b/2 - c/2], [-b/2 + c/2, 0]] The same expression can be read as the transpose by inverting ``i`` and ``j``: >>> expr.replace_with_arrays(repl, [j, i]) [[0, -b/2 + c/2], [b/2 - c/2, 0]] """ from .array import Array indices = indices or [] remap = {k.args[0] if k.is_up else -k.args[0]: k for k in self.get_free_indices()} for i, index in enumerate(indices): if isinstance(index, (Symbol, Mul)): if index in remap: indices[i] = remap[index] else: indices[i] = -remap[-index] replacement_dict = {tensor: Array(array) for tensor, array in replacement_dict.items()} # Check dimensions of replaced arrays: for tensor, array in replacement_dict.items(): if isinstance(tensor, TensorIndexType): expected_shape = [tensor.dim for i in range(2)] else: expected_shape = [index_type.dim for index_type in tensor.index_types] if len(expected_shape) != array.rank() or (not all(dim1 == dim2 if dim1.is_number else True for dim1, dim2 in zip(expected_shape, array.shape))): raise ValueError("shapes for tensor %s expected to be %s, "\ "replacement array shape is %s" % (tensor, expected_shape, array.shape)) ret_indices, array = self._extract_data(replacement_dict) last_indices, array = self._match_indices_with_other_tensor(array, indices, ret_indices, replacement_dict) return array def _check_add_Sum(self, expr, index_symbols): from sympy.concrete.summations import Sum indices = self.get_indices() dum = self.dum sum_indices = [ (index_symbols[i], 0, indices[i].tensor_index_type.dim-1) for i, j in dum] if sum_indices: expr = Sum(expr, *sum_indices) return expr def _expand_partial_derivative(self): # simply delegate the _expand_partial_derivative() to # its arguments to expand a possibly found PartialDerivative return self.func(*[ a._expand_partial_derivative() if isinstance(a, TensExpr) else a for a in self.args]) class TensAdd(TensExpr, AssocOp): """ Sum of tensors. Parameters ========== free_args : list of the free indices Attributes ========== ``args`` : tuple of addends ``rank`` : rank of the tensor ``free_args`` : list of the free indices in sorted order Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_heads, tensor_indices >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> a, b = tensor_indices('a,b', Lorentz) >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t = p(a) + q(a); t p(a) + q(a) Examples with components data added to the tensor expression: >>> from sympy import symbols, diag >>> x, y, z, t = symbols("x y z t") >>> repl = {} >>> repl[Lorentz] = diag(1, -1, -1, -1) >>> repl[p(a)] = [1, 2, 3, 4] >>> repl[q(a)] = [x, y, z, t] The following are: 2**2 - 3**2 - 2**2 - 7**2 ==> -58 >>> expr = p(a) + q(a) >>> expr.replace_with_arrays(repl, [a]) [x + 1, y + 2, z + 3, t + 4] """ def __new__(cls, *args, **kw_args): args = [_sympify(x) for x in args if x] args = TensAdd._tensAdd_flatten(args) args.sort(key=default_sort_key) if not args: return S.Zero if len(args) == 1: return args[0] return Basic.__new__(cls, *args, **kw_args) @property def coeff(self): return S.One @property def nocoeff(self): return self def get_free_indices(self): # type: () -> List[TensorIndex] return self.free_indices def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> TensExpr newargs = [arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args] return self.func(*newargs) @memoize_property def rank(self): if isinstance(self.args[0], TensExpr): return self.args[0].rank else: return 0 @memoize_property def free_args(self): if isinstance(self.args[0], TensExpr): return self.args[0].free_args else: return [] @memoize_property def free_indices(self): if isinstance(self.args[0], TensExpr): return self.args[0].get_free_indices() else: return set() def doit(self, **hints): deep = hints.get('deep', True) if deep: args = [arg.doit(**hints) for arg in self.args] else: args = self.args if not args: return S.Zero if len(args) == 1 and not isinstance(args[0], TensExpr): return args[0] # now check that all addends have the same indices: TensAdd._tensAdd_check(args) # if TensAdd has only 1 element in its `args`: if len(args) == 1: # and isinstance(args[0], TensMul): return args[0] # Remove zeros: args = [x for x in args if x] # if there are no more args (i.e. have cancelled out), # just return zero: if not args: return S.Zero if len(args) == 1: return args[0] # Collect terms appearing more than once, differing by their coefficients: args = TensAdd._tensAdd_collect_terms(args) # collect canonicalized terms def sort_key(t): if not isinstance(t, TensExpr): return [], [], [] if hasattr(t, "_index_structure") and hasattr(t, "components"): x = get_index_structure(t) return t.components, x.free, x.dum return [], [], [] args.sort(key=sort_key) if not args: return S.Zero # it there is only a component tensor return it if len(args) == 1: return args[0] obj = self.func(*args) return obj @staticmethod def _tensAdd_flatten(args): # flatten TensAdd, coerce terms which are not tensors to tensors a = [] for x in args: if isinstance(x, (Add, TensAdd)): a.extend(list(x.args)) else: a.append(x) args = [x for x in a if x.coeff] return args @staticmethod def _tensAdd_check(args): # check that all addends have the same free indices def get_indices_set(x): # type: (Expr) -> tSet[TensorIndex] if isinstance(x, TensExpr): return set(x.get_free_indices()) return set() indices0 = get_indices_set(args[0]) # type: tSet[TensorIndex] list_indices = [get_indices_set(arg) for arg in args[1:]] # type: List[tSet[TensorIndex]] if not all(x == indices0 for x in list_indices): raise ValueError('all tensors must have the same indices') @staticmethod def _tensAdd_collect_terms(args): # collect TensMul terms differing at most by their coefficient terms_dict = defaultdict(list) scalars = S.Zero if isinstance(args[0], TensExpr): free_indices = set(args[0].get_free_indices()) else: free_indices = set() for arg in args: if not isinstance(arg, TensExpr): if free_indices != set(): raise ValueError("wrong valence") scalars += arg continue if free_indices != set(arg.get_free_indices()): raise ValueError("wrong valence") # TODO: what is the part which is not a coeff? # needs an implementation similar to .as_coeff_Mul() terms_dict[arg.nocoeff].append(arg.coeff) new_args = [TensMul(Add(*coeff), t).doit() for t, coeff in terms_dict.items() if Add(*coeff) != 0] if isinstance(scalars, Add): new_args = list(scalars.args) + new_args elif scalars != 0: new_args = [scalars] + new_args return new_args def get_indices(self): indices = [] for arg in self.args: indices.extend([i for i in get_indices(arg) if i not in indices]) return indices def _expand(self, **hints): return TensAdd(*[_expand(i, **hints) for i in self.args]) def __call__(self, *indices): deprecate_call() free_args = self.free_args indices = list(indices) if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: raise ValueError('incompatible types') if indices == free_args: return self index_tuples = list(zip(free_args, indices)) a = [x.func(*x.substitute_indices(*index_tuples).args) for x in self.args] res = TensAdd(*a).doit() return res def canon_bp(self): """ Canonicalize using the Butler-Portugal algorithm for canonicalization under monoterm symmetries. """ expr = self.expand() args = [canon_bp(x) for x in expr.args] res = TensAdd(*args).doit() return res def equals(self, other): other = _sympify(other) if isinstance(other, TensMul) and other.coeff == 0: return all(x.coeff == 0 for x in self.args) if isinstance(other, TensExpr): if self.rank != other.rank: return False if isinstance(other, TensAdd): if set(self.args) != set(other.args): return False else: return True t = self - other if not isinstance(t, TensExpr): return t == 0 else: if isinstance(t, TensMul): return t.coeff == 0 else: return all(x.coeff == 0 for x in t.args) def __getitem__(self, item): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data[item] def contract_delta(self, delta): args = [x.contract_delta(delta) for x in self.args] t = TensAdd(*args).doit() return canon_bp(t) def contract_metric(self, g): """ Raise or lower indices with the metric ``g``. Parameters ========== g : metric contract_all : if True, eliminate all ``g`` which are contracted Notes ===== see the ``TensorIndexType`` docstring for the contraction conventions """ args = [contract_metric(x, g) for x in self.args] t = TensAdd(*args).doit() return canon_bp(t) def substitute_indices(self, *index_tuples): new_args = [] for arg in self.args: if isinstance(arg, TensExpr): arg = arg.substitute_indices(*index_tuples) new_args.append(arg) return TensAdd(*new_args).doit() def _print(self): a = [] args = self.args for x in args: a.append(str(x)) s = ' + '.join(a) s = s.replace('+ -', '- ') return s def _extract_data(self, replacement_dict): from sympy.tensor.array import Array, permutedims args_indices, arrays = zip(*[ arg._extract_data(replacement_dict) if isinstance(arg, TensExpr) else ([], arg) for arg in self.args ]) arrays = [Array(i) for i in arrays] ref_indices = args_indices[0] for i in range(1, len(args_indices)): indices = args_indices[i] array = arrays[i] permutation = TensMul._get_indices_permutation(indices, ref_indices) arrays[i] = permutedims(array, permutation) return ref_indices, sum(arrays, Array.zeros(*array.shape)) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self.expand()] @data.setter def data(self, data): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): _tensor_data_substitution_dict[self] = data @data.deleter def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] def __iter__(self): deprecate_data() if not self.data: raise ValueError("No iteration on abstract tensors") return self.data.flatten().__iter__() def _eval_rewrite_as_Indexed(self, *args): return Add.fromiter(args) def _eval_partial_derivative(self, s): # Evaluation like Add list_addends = [] for a in self.args: if isinstance(a, TensExpr): list_addends.append(a._eval_partial_derivative(s)) # do not call diff if s is no symbol elif s._diff_wrt: list_addends.append(a._eval_derivative(s)) return self.func(*list_addends) class Tensor(TensExpr): """ Base tensor class, i.e. this represents a tensor, the single unit to be put into an expression. Explanation =========== This object is usually created from a ``TensorHead``, by attaching indices to it. Indices preceded by a minus sign are considered contravariant, otherwise covariant. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead >>> Lorentz = TensorIndexType("Lorentz", dummy_name="L") >>> mu, nu = tensor_indices('mu nu', Lorentz) >>> A = TensorHead("A", [Lorentz, Lorentz]) >>> A(mu, -nu) A(mu, -nu) >>> A(mu, -mu) A(L_0, -L_0) It is also possible to use symbols instead of inidices (appropriate indices are then generated automatically). >>> from sympy import Symbol >>> x = Symbol('x') >>> A(x, mu) A(x, mu) >>> A(x, -x) A(L_0, -L_0) """ is_commutative = False _index_structure = None # type: _IndexStructure args: tTuple[TensorHead, Tuple] def __new__(cls, tensor_head, indices, *, is_canon_bp=False, **kw_args): indices = cls._parse_indices(tensor_head, indices) obj = Basic.__new__(cls, tensor_head, Tuple(*indices), **kw_args) obj._index_structure = _IndexStructure.from_indices(*indices) obj._free = obj._index_structure.free[:] obj._dum = obj._index_structure.dum[:] obj._ext_rank = obj._index_structure._ext_rank obj._coeff = S.One obj._nocoeff = obj obj._component = tensor_head obj._components = [tensor_head] if tensor_head.rank != len(indices): raise ValueError("wrong number of indices") obj.is_canon_bp = is_canon_bp obj._index_map = Tensor._build_index_map(indices, obj._index_structure) return obj @property def free(self): return self._free @property def dum(self): return self._dum @property def ext_rank(self): return self._ext_rank @property def coeff(self): return self._coeff @property def nocoeff(self): return self._nocoeff @property def component(self): return self._component @property def components(self): return self._components @property def head(self): return self.args[0] @property def indices(self): return self.args[1] @property def free_indices(self): return set(self._index_structure.get_free_indices()) @property def index_types(self): return self.head.index_types @property def rank(self): return len(self.free_indices) @staticmethod def _build_index_map(indices, index_structure): index_map = {} for idx in indices: index_map[idx] = (indices.index(idx),) return index_map def doit(self, **hints): args, indices, free, dum = TensMul._tensMul_contract_indices([self]) return args[0] @staticmethod def _parse_indices(tensor_head, indices): if not isinstance(indices, (tuple, list, Tuple)): raise TypeError("indices should be an array, got %s" % type(indices)) indices = list(indices) for i, index in enumerate(indices): if isinstance(index, Symbol): indices[i] = TensorIndex(index, tensor_head.index_types[i], True) elif isinstance(index, Mul): c, e = index.as_coeff_Mul() if c == -1 and isinstance(e, Symbol): indices[i] = TensorIndex(e, tensor_head.index_types[i], False) else: raise ValueError("index not understood: %s" % index) elif not isinstance(index, TensorIndex): raise TypeError("wrong type for index: %s is %s" % (index, type(index))) return indices def _set_new_index_structure(self, im, is_canon_bp=False): indices = im.get_indices() return self._set_indices(*indices, is_canon_bp=is_canon_bp) def _set_indices(self, *indices, is_canon_bp=False, **kw_args): if len(indices) != self.ext_rank: raise ValueError("indices length mismatch") return self.func(self.args[0], indices, is_canon_bp=is_canon_bp).doit() def _get_free_indices_set(self): return {i[0] for i in self._index_structure.free} def _get_dummy_indices_set(self): dummy_pos = set(itertools.chain(*self._index_structure.dum)) return {idx for i, idx in enumerate(self.args[1]) if i in dummy_pos} def _get_indices_set(self): return set(self.args[1].args) @property def free_in_args(self): return [(ind, pos, 0) for ind, pos in self.free] @property def dum_in_args(self): return [(p1, p2, 0, 0) for p1, p2 in self.dum] @property def free_args(self): return sorted([x[0] for x in self.free]) def commutes_with(self, other): """ :param other: :return: 0 commute 1 anticommute None neither commute nor anticommute """ if not isinstance(other, TensExpr): return 0 elif isinstance(other, Tensor): return self.component.commutes_with(other.component) return NotImplementedError def perm2tensor(self, g, is_canon_bp=False): """ Returns the tensor corresponding to the permutation ``g``. For further details, see the method in ``TIDS`` with the same name. """ return perm2tensor(self, g, is_canon_bp) def canon_bp(self): if self.is_canon_bp: return self expr = self.expand() g, dummies, msym = expr._index_structure.indices_canon_args() v = components_canon_args([expr.component]) can = canonicalize(g, dummies, msym, *v) if can == 0: return S.Zero tensor = self.perm2tensor(can, True) return tensor def split(self): return [self] def _expand(self, **kwargs): return self def sorted_components(self): return self def get_indices(self): # type: () -> List[TensorIndex] """ Get a list of indices, corresponding to those of the tensor. """ return list(self.args[1]) def get_free_indices(self): # type: () -> List[TensorIndex] """ Get a list of free indices, corresponding to those of the tensor. """ return self._index_structure.get_free_indices() def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> Tensor # TODO: this could be optimized by only swapping the indices # instead of visiting the whole expression tree: return self.xreplace(repl) def as_base_exp(self): return self, S.One def substitute_indices(self, *index_tuples): """ Return a tensor with free indices substituted according to ``index_tuples``. ``index_types`` list of tuples ``(old_index, new_index)``. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz) >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) >>> t = A(i, k)*B(-k, -j); t A(i, L_0)*B(-L_0, -j) >>> t.substitute_indices((i, k),(-j, l)) A(k, L_0)*B(-L_0, l) """ indices = [] for index in self.indices: for ind_old, ind_new in index_tuples: if (index.name == ind_old.name and index.tensor_index_type == ind_old.tensor_index_type): if index.is_up == ind_old.is_up: indices.append(ind_new) else: indices.append(-ind_new) break else: indices.append(index) return self.head(*indices) def __call__(self, *indices): deprecate_call() free_args = self.free_args indices = list(indices) if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: raise ValueError('incompatible types') if indices == free_args: return self t = self.substitute_indices(*list(zip(free_args, indices))) # object is rebuilt in order to make sure that all contracted indices # get recognized as dummies, but only if there are contracted indices. if len({i if i.is_up else -i for i in indices}) != len(indices): return t.func(*t.args) return t # TODO: put this into TensExpr? def __iter__(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data.__iter__() # TODO: put this into TensExpr? def __getitem__(self, item): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data[item] def _extract_data(self, replacement_dict): from .array import Array for k, v in replacement_dict.items(): if isinstance(k, Tensor) and k.args[0] == self.args[0]: other = k array = v break else: raise ValueError("%s not found in %s" % (self, replacement_dict)) # TODO: inefficient, this should be done at root level only: replacement_dict = {k: Array(v) for k, v in replacement_dict.items()} array = Array(array) dum1 = self.dum dum2 = other.dum if len(dum2) > 0: for pair in dum2: # allow `dum2` if the contained values are also in `dum1`. if pair not in dum1: raise NotImplementedError("%s with contractions is not implemented" % other) # Remove elements in `dum2` from `dum1`: dum1 = [pair for pair in dum1 if pair not in dum2] if len(dum1) > 0: indices1 = self.get_indices() indices2 = other.get_indices() repl = {} for p1, p2 in dum1: repl[indices2[p2]] = -indices2[p1] for pos in (p1, p2): if indices1[pos].is_up ^ indices2[pos].is_up: metric = replacement_dict[indices1[pos].tensor_index_type] if indices1[pos].is_up: metric = _TensorDataLazyEvaluator.inverse_matrix(metric) array = self._contract_and_permute_with_metric(metric, array, pos, len(indices2)) other = other.xreplace(repl).doit() array = _TensorDataLazyEvaluator.data_contract_dum([array], dum1, len(indices2)) free_ind1 = self.get_free_indices() free_ind2 = other.get_free_indices() return self._match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self] @data.setter def data(self, data): deprecate_data() # TODO: check data compatibility with properties of tensor. with ignore_warnings(SymPyDeprecationWarning): _tensor_data_substitution_dict[self] = data @data.deleter def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] if self.metric in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self.metric] def _print(self): indices = [str(ind) for ind in self.indices] component = self.component if component.rank > 0: return ('%s(%s)' % (component.name, ', '.join(indices))) else: return ('%s' % component.name) def equals(self, other): if other == 0: return self.coeff == 0 other = _sympify(other) if not isinstance(other, TensExpr): assert not self.components return S.One == other def _get_compar_comp(self): t = self.canon_bp() r = (t.coeff, tuple(t.components), \ tuple(sorted(t.free)), tuple(sorted(t.dum))) return r return _get_compar_comp(self) == _get_compar_comp(other) def contract_metric(self, g): # if metric is not the same, ignore this step: if self.component != g: return self # in case there are free components, do not perform anything: if len(self.free) != 0: return self #antisym = g.index_types[0].metric_antisym if g.symmetry == TensorSymmetry.fully_symmetric(-2): antisym = 1 elif g.symmetry == TensorSymmetry.fully_symmetric(2): antisym = 0 elif g.symmetry == TensorSymmetry.no_symmetry(2): antisym = None else: raise NotImplementedError sign = S.One typ = g.index_types[0] if not antisym: # g(i, -i) sign = sign*typ.dim else: # g(i, -i) sign = sign*typ.dim dp0, dp1 = self.dum[0] if dp0 < dp1: # g(i, -i) = -D with antisymmetric metric sign = -sign return sign def contract_delta(self, metric): return self.contract_metric(metric) def _eval_rewrite_as_Indexed(self, tens, indices): from sympy.tensor.indexed import Indexed # TODO: replace .args[0] with .name: index_symbols = [i.args[0] for i in self.get_indices()] expr = Indexed(tens.args[0], *index_symbols) return self._check_add_Sum(expr, index_symbols) def _eval_partial_derivative(self, s): # type: (Tensor) -> Expr if not isinstance(s, Tensor): return S.Zero else: # @a_i/@a_k = delta_i^k # @a_i/@a^k = g_ij delta^j_k # @a^i/@a^k = delta^i_k # @a^i/@a_k = g^ij delta_j^k # TODO: if there is no metric present, the derivative should be zero? if self.head != s.head: return S.Zero # if heads are the same, provide delta and/or metric products # for every free index pair in the appropriate tensor # assumed that the free indices are in proper order # A contravariante index in the derivative becomes covariant # after performing the derivative and vice versa kronecker_delta_list = [1] # not guarantee a correct index order for (count, (iself, iother)) in enumerate(zip(self.get_free_indices(), s.get_free_indices())): if iself.tensor_index_type != iother.tensor_index_type: raise ValueError("index types not compatible") else: tensor_index_type = iself.tensor_index_type tensor_metric = tensor_index_type.metric dummy = TensorIndex("d_" + str(count), tensor_index_type, is_up=iself.is_up) if iself.is_up == iother.is_up: kroneckerdelta = tensor_index_type.delta(iself, -iother) else: kroneckerdelta = ( TensMul(tensor_metric(iself, dummy), tensor_index_type.delta(-dummy, -iother)) ) kronecker_delta_list.append(kroneckerdelta) return TensMul.fromiter(kronecker_delta_list).doit() # doit necessary to rename dummy indices accordingly class TensMul(TensExpr, AssocOp): """ Product of tensors. Parameters ========== coeff : SymPy coefficient of the tensor args Attributes ========== ``components`` : list of ``TensorHead`` of the component tensors ``types`` : list of nonrepeated ``TensorIndexType`` ``free`` : list of ``(ind, ipos, icomp)``, see Notes ``dum`` : list of ``(ipos1, ipos2, icomp1, icomp2)``, see Notes ``ext_rank`` : rank of the tensor counting the dummy indices ``rank`` : rank of the tensor ``coeff`` : SymPy coefficient of the tensor ``free_args`` : list of the free indices in sorted order ``is_canon_bp`` : ``True`` if the tensor in in canonical form Notes ===== ``args[0]`` list of ``TensorHead`` of the component tensors. ``args[1]`` list of ``(ind, ipos, icomp)`` where ``ind`` is a free index, ``ipos`` is the slot position of ``ind`` in the ``icomp``-th component tensor. ``args[2]`` list of tuples representing dummy indices. ``(ipos1, ipos2, icomp1, icomp2)`` indicates that the contravariant dummy index is the ``ipos1``-th slot position in the ``icomp1``-th component tensor; the corresponding covariant index is in the ``ipos2`` slot position in the ``icomp2``-th component tensor. """ identity = S.One _index_structure = None # type: _IndexStructure def __new__(cls, *args, **kw_args): is_canon_bp = kw_args.get('is_canon_bp', False) args = list(map(_sympify, args)) # Flatten: args = [i for arg in args for i in (arg.args if isinstance(arg, (TensMul, Mul)) else [arg])] args, indices, free, dum = TensMul._tensMul_contract_indices(args, replace_indices=False) # Data for indices: index_types = [i.tensor_index_type for i in indices] index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp) obj = TensExpr.__new__(cls, *args) obj._indices = indices obj._index_types = index_types[:] obj._index_structure = index_structure obj._free = index_structure.free[:] obj._dum = index_structure.dum[:] obj._free_indices = {x[0] for x in obj.free} obj._rank = len(obj.free) obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum) obj._coeff = S.One obj._is_canon_bp = is_canon_bp return obj index_types = property(lambda self: self._index_types) free = property(lambda self: self._free) dum = property(lambda self: self._dum) free_indices = property(lambda self: self._free_indices) rank = property(lambda self: self._rank) ext_rank = property(lambda self: self._ext_rank) @staticmethod def _indices_to_free_dum(args_indices): free2pos1 = {} free2pos2 = {} dummy_data = [] indices = [] # Notation for positions (to better understand the code): # `pos1`: position in the `args`. # `pos2`: position in the indices. # Example: # A(i, j)*B(k, m, n)*C(p) # `pos1` of `n` is 1 because it's in `B` (second `args` of TensMul). # `pos2` of `n` is 4 because it's the fifth overall index. # Counter for the index position wrt the whole expression: pos2 = 0 for pos1, arg_indices in enumerate(args_indices): for index_pos, index in enumerate(arg_indices): if not isinstance(index, TensorIndex): raise TypeError("expected TensorIndex") if -index in free2pos1: # Dummy index detected: other_pos1 = free2pos1.pop(-index) other_pos2 = free2pos2.pop(-index) if index.is_up: dummy_data.append((index, pos1, other_pos1, pos2, other_pos2)) else: dummy_data.append((-index, other_pos1, pos1, other_pos2, pos2)) indices.append(index) elif index in free2pos1: raise ValueError("Repeated index: %s" % index) else: free2pos1[index] = pos1 free2pos2[index] = pos2 indices.append(index) pos2 += 1 free = [(i, p) for (i, p) in free2pos2.items()] free_names = [i.name for i in free2pos2.keys()] dummy_data.sort(key=lambda x: x[3]) return indices, free, free_names, dummy_data @staticmethod def _dummy_data_to_dum(dummy_data): return [(p2a, p2b) for (i, p1a, p1b, p2a, p2b) in dummy_data] @staticmethod def _tensMul_contract_indices(args, replace_indices=True): replacements = [{} for _ in args] #_index_order = all(_has_index_order(arg) for arg in args) args_indices = [get_indices(arg) for arg in args] indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices) cdt = defaultdict(int) def dummy_name_gen(tensor_index_type): nd = str(cdt[tensor_index_type]) cdt[tensor_index_type] += 1 return tensor_index_type.dummy_name + '_' + nd if replace_indices: for old_index, pos1cov, pos1contra, pos2cov, pos2contra in dummy_data: index_type = old_index.tensor_index_type while True: dummy_name = dummy_name_gen(index_type) if dummy_name not in free_names: break dummy = TensorIndex(dummy_name, index_type, True) replacements[pos1cov][old_index] = dummy replacements[pos1contra][-old_index] = -dummy indices[pos2cov] = dummy indices[pos2contra] = -dummy args = [ arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg, repl in zip(args, replacements)] dum = TensMul._dummy_data_to_dum(dummy_data) return args, indices, free, dum @staticmethod def _get_components_from_args(args): """ Get a list of ``Tensor`` objects having the same ``TIDS`` if multiplied by one another. """ components = [] for arg in args: if not isinstance(arg, TensExpr): continue if isinstance(arg, TensAdd): continue components.extend(arg.components) return components @staticmethod def _rebuild_tensors_list(args, index_structure): indices = index_structure.get_indices() #tensors = [None for i in components] # pre-allocate list ind_pos = 0 for i, arg in enumerate(args): if not isinstance(arg, TensExpr): continue prev_pos = ind_pos ind_pos += arg.ext_rank args[i] = Tensor(arg.component, indices[prev_pos:ind_pos]) def doit(self, **hints): is_canon_bp = self._is_canon_bp deep = hints.get('deep', True) if deep: args = [arg.doit(**hints) for arg in self.args] else: args = self.args args = [arg for arg in args if arg != self.identity] # Extract non-tensor coefficients: coeff = reduce(lambda a, b: a*b, [arg for arg in args if not isinstance(arg, TensExpr)], S.One) args = [arg for arg in args if isinstance(arg, TensExpr)] if len(args) == 0: return coeff if coeff != self.identity: args = [coeff] + args if coeff == 0: return S.Zero if len(args) == 1: return args[0] args, indices, free, dum = TensMul._tensMul_contract_indices(args) # Data for indices: index_types = [i.tensor_index_type for i in indices] index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp) obj = self.func(*args) obj._index_types = index_types obj._index_structure = index_structure obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum) obj._coeff = coeff obj._is_canon_bp = is_canon_bp return obj # TODO: this method should be private # TODO: should this method be renamed _from_components_free_dum ? @staticmethod def from_data(coeff, components, free, dum, **kw_args): return TensMul(coeff, *TensMul._get_tensors_from_components_free_dum(components, free, dum), **kw_args).doit() @staticmethod def _get_tensors_from_components_free_dum(components, free, dum): """ Get a list of ``Tensor`` objects by distributing ``free`` and ``dum`` indices on the ``components``. """ index_structure = _IndexStructure.from_components_free_dum(components, free, dum) indices = index_structure.get_indices() tensors = [None for i in components] # pre-allocate list # distribute indices on components to build a list of tensors: ind_pos = 0 for i, component in enumerate(components): prev_pos = ind_pos ind_pos += component.rank tensors[i] = Tensor(component, indices[prev_pos:ind_pos]) return tensors def _get_free_indices_set(self): return {i[0] for i in self.free} def _get_dummy_indices_set(self): dummy_pos = set(itertools.chain(*self.dum)) return {idx for i, idx in enumerate(self._index_structure.get_indices()) if i in dummy_pos} def _get_position_offset_for_indices(self): arg_offset = [None for i in range(self.ext_rank)] counter = 0 for i, arg in enumerate(self.args): if not isinstance(arg, TensExpr): continue for j in range(arg.ext_rank): arg_offset[j + counter] = counter counter += arg.ext_rank return arg_offset @property def free_args(self): return sorted([x[0] for x in self.free]) @property def components(self): return self._get_components_from_args(self.args) @property def free_in_args(self): arg_offset = self._get_position_offset_for_indices() argpos = self._get_indices_to_args_pos() return [(ind, pos-arg_offset[pos], argpos[pos]) for (ind, pos) in self.free] @property def coeff(self): # return Mul.fromiter([c for c in self.args if not isinstance(c, TensExpr)]) return self._coeff @property def nocoeff(self): return self.func(*[t for t in self.args if isinstance(t, TensExpr)]).doit() @property def dum_in_args(self): arg_offset = self._get_position_offset_for_indices() argpos = self._get_indices_to_args_pos() return [(p1-arg_offset[p1], p2-arg_offset[p2], argpos[p1], argpos[p2]) for p1, p2 in self.dum] def equals(self, other): if other == 0: return self.coeff == 0 other = _sympify(other) if not isinstance(other, TensExpr): assert not self.components return self.coeff == other return self.canon_bp() == other.canon_bp() def get_indices(self): """ Returns the list of indices of the tensor. Explanation =========== The indices are listed in the order in which they appear in the component tensors. The dummy indices are given a name which does not collide with the names of the free indices. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> g = Lorentz.metric >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t = p(m1)*g(m0,m2) >>> t.get_indices() [m1, m0, m2] >>> t2 = p(m1)*g(-m1, m2) >>> t2.get_indices() [L_0, -L_0, m2] """ return self._indices def get_free_indices(self): # type: () -> List[TensorIndex] """ Returns the list of free indices of the tensor. Explanation =========== The indices are listed in the order in which they appear in the component tensors. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> g = Lorentz.metric >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t = p(m1)*g(m0,m2) >>> t.get_free_indices() [m1, m0, m2] >>> t2 = p(m1)*g(-m1, m2) >>> t2.get_free_indices() [m2] """ return self._index_structure.get_free_indices() def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> TensExpr return self.func(*[arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args]) def split(self): """ Returns a list of tensors, whose product is ``self``. Explanation =========== Dummy indices contracted among different tensor components become free indices with the same name as the one used to represent the dummy indices. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz) >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) >>> t = A(a,b)*B(-b,c) >>> t A(a, L_0)*B(-L_0, c) >>> t.split() [A(a, L_0), B(-L_0, c)] """ if self.args == (): return [self] splitp = [] res = 1 for arg in self.args: if isinstance(arg, Tensor): splitp.append(res*arg) res = 1 else: res *= arg return splitp def _expand(self, **hints): # TODO: temporary solution, in the future this should be linked to # `Expr.expand`. args = [_expand(arg, **hints) for arg in self.args] args1 = [arg.args if isinstance(arg, (Add, TensAdd)) else (arg,) for arg in args] return TensAdd(*[ TensMul(*i) for i in itertools.product(*args1)] ) def __neg__(self): return TensMul(S.NegativeOne, self, is_canon_bp=self._is_canon_bp).doit() def __getitem__(self, item): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data[item] def _get_args_for_traditional_printer(self): args = list(self.args) if (self.coeff < 0) == True: # expressions like "-A(a)" sign = "-" if self.coeff == S.NegativeOne: args = args[1:] else: args[0] = -args[0] else: sign = "" return sign, args def _sort_args_for_sorted_components(self): """ Returns the ``args`` sorted according to the components commutation properties. Explanation =========== The sorting is done taking into account the commutation group of the component tensors. """ cv = [arg for arg in self.args if isinstance(arg, TensExpr)] sign = 1 n = len(cv) - 1 for i in range(n): for j in range(n, i, -1): c = cv[j-1].commutes_with(cv[j]) # if `c` is `None`, it does neither commute nor anticommute, skip: if c not in (0, 1): continue typ1 = sorted(set(cv[j-1].component.index_types), key=lambda x: x.name) typ2 = sorted(set(cv[j].component.index_types), key=lambda x: x.name) if (typ1, cv[j-1].component.name) > (typ2, cv[j].component.name): cv[j-1], cv[j] = cv[j], cv[j-1] # if `c` is 1, the anticommute, so change sign: if c: sign = -sign coeff = sign * self.coeff if coeff != 1: return [coeff] + cv return cv def sorted_components(self): """ Returns a tensor product with sorted components. """ return TensMul(*self._sort_args_for_sorted_components()).doit() def perm2tensor(self, g, is_canon_bp=False): """ Returns the tensor corresponding to the permutation ``g`` For further details, see the method in ``TIDS`` with the same name. """ return perm2tensor(self, g, is_canon_bp=is_canon_bp) def canon_bp(self): """ Canonicalize using the Butler-Portugal algorithm for canonicalization under monoterm symmetries. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2)) >>> t = A(m0,-m1)*A(m1,-m0) >>> t.canon_bp() -A(L_0, L_1)*A(-L_0, -L_1) >>> t = A(m0,-m1)*A(m1,-m2)*A(m2,-m0) >>> t.canon_bp() 0 """ if self._is_canon_bp: return self expr = self.expand() if isinstance(expr, TensAdd): return expr.canon_bp() if not expr.components: return expr t = expr.sorted_components() g, dummies, msym = t._index_structure.indices_canon_args() v = components_canon_args(t.components) can = canonicalize(g, dummies, msym, *v) if can == 0: return S.Zero tmul = t.perm2tensor(can, True) return tmul def contract_delta(self, delta): t = self.contract_metric(delta) return t def _get_indices_to_args_pos(self): """ Get a dict mapping the index position to TensMul's argument number. """ pos_map = {} pos_counter = 0 for arg_i, arg in enumerate(self.args): if not isinstance(arg, TensExpr): continue assert isinstance(arg, Tensor) for i in range(arg.ext_rank): pos_map[pos_counter] = arg_i pos_counter += 1 return pos_map def contract_metric(self, g): """ Raise or lower indices with the metric ``g``. Parameters ========== g : metric Notes ===== See the ``TensorIndexType`` docstring for the contraction conventions. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> g = Lorentz.metric >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t = p(m0)*q(m1)*g(-m0, -m1) >>> t.canon_bp() metric(L_0, L_1)*p(-L_0)*q(-L_1) >>> t.contract_metric(g).canon_bp() p(L_0)*q(-L_0) """ expr = self.expand() if self != expr: expr = expr.canon_bp() return expr.contract_metric(g) pos_map = self._get_indices_to_args_pos() args = list(self.args) #antisym = g.index_types[0].metric_antisym if g.symmetry == TensorSymmetry.fully_symmetric(-2): antisym = 1 elif g.symmetry == TensorSymmetry.fully_symmetric(2): antisym = 0 elif g.symmetry == TensorSymmetry.no_symmetry(2): antisym = None else: raise NotImplementedError # list of positions of the metric ``g`` inside ``args`` gpos = [i for i, x in enumerate(self.args) if isinstance(x, Tensor) and x.component == g] if not gpos: return self # Sign is either 1 or -1, to correct the sign after metric contraction # (for spinor indices). sign = 1 dum = self.dum[:] free = self.free[:] elim = set() for gposx in gpos: if gposx in elim: continue free1 = [x for x in free if pos_map[x[1]] == gposx] dum1 = [x for x in dum if pos_map[x[0]] == gposx or pos_map[x[1]] == gposx] if not dum1: continue elim.add(gposx) # subs with the multiplication neutral element, that is, remove it: args[gposx] = 1 if len(dum1) == 2: if not antisym: dum10, dum11 = dum1 if pos_map[dum10[1]] == gposx: # the index with pos p0 contravariant p0 = dum10[0] else: # the index with pos p0 is covariant p0 = dum10[1] if pos_map[dum11[1]] == gposx: # the index with pos p1 is contravariant p1 = dum11[0] else: # the index with pos p1 is covariant p1 = dum11[1] dum.append((p0, p1)) else: dum10, dum11 = dum1 # change the sign to bring the indices of the metric to contravariant # form; change the sign if dum10 has the metric index in position 0 if pos_map[dum10[1]] == gposx: # the index with pos p0 is contravariant p0 = dum10[0] if dum10[1] == 1: sign = -sign else: # the index with pos p0 is covariant p0 = dum10[1] if dum10[0] == 0: sign = -sign if pos_map[dum11[1]] == gposx: # the index with pos p1 is contravariant p1 = dum11[0] sign = -sign else: # the index with pos p1 is covariant p1 = dum11[1] dum.append((p0, p1)) elif len(dum1) == 1: if not antisym: dp0, dp1 = dum1[0] if pos_map[dp0] == pos_map[dp1]: # g(i, -i) typ = g.index_types[0] sign = sign*typ.dim else: # g(i0, i1)*p(-i1) if pos_map[dp0] == gposx: p1 = dp1 else: p1 = dp0 ind, p = free1[0] free.append((ind, p1)) else: dp0, dp1 = dum1[0] if pos_map[dp0] == pos_map[dp1]: # g(i, -i) typ = g.index_types[0] sign = sign*typ.dim if dp0 < dp1: # g(i, -i) = -D with antisymmetric metric sign = -sign else: # g(i0, i1)*p(-i1) if pos_map[dp0] == gposx: p1 = dp1 if dp0 == 0: sign = -sign else: p1 = dp0 ind, p = free1[0] free.append((ind, p1)) dum = [x for x in dum if x not in dum1] free = [x for x in free if x not in free1] # shift positions: shift = 0 shifts = [0]*len(args) for i in range(len(args)): if i in elim: shift += 2 continue shifts[i] = shift free = [(ind, p - shifts[pos_map[p]]) for (ind, p) in free if pos_map[p] not in elim] dum = [(p0 - shifts[pos_map[p0]], p1 - shifts[pos_map[p1]]) for i, (p0, p1) in enumerate(dum) if pos_map[p0] not in elim and pos_map[p1] not in elim] res = sign*TensMul(*args).doit() if not isinstance(res, TensExpr): return res im = _IndexStructure.from_components_free_dum(res.components, free, dum) return res._set_new_index_structure(im) def _set_new_index_structure(self, im, is_canon_bp=False): indices = im.get_indices() return self._set_indices(*indices, is_canon_bp=is_canon_bp) def _set_indices(self, *indices, is_canon_bp=False, **kw_args): if len(indices) != self.ext_rank: raise ValueError("indices length mismatch") args = list(self.args)[:] pos = 0 for i, arg in enumerate(args): if not isinstance(arg, TensExpr): continue assert isinstance(arg, Tensor) ext_rank = arg.ext_rank args[i] = arg._set_indices(*indices[pos:pos+ext_rank]) pos += ext_rank return TensMul(*args, is_canon_bp=is_canon_bp).doit() @staticmethod def _index_replacement_for_contract_metric(args, free, dum): for arg in args: if not isinstance(arg, TensExpr): continue assert isinstance(arg, Tensor) def substitute_indices(self, *index_tuples): new_args = [] for arg in self.args: if isinstance(arg, TensExpr): arg = arg.substitute_indices(*index_tuples) new_args.append(arg) return TensMul(*new_args).doit() def __call__(self, *indices): deprecate_call() free_args = self.free_args indices = list(indices) if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: raise ValueError('incompatible types') if indices == free_args: return self t = self.substitute_indices(*list(zip(free_args, indices))) # object is rebuilt in order to make sure that all contracted indices # get recognized as dummies, but only if there are contracted indices. if len({i if i.is_up else -i for i in indices}) != len(indices): return t.func(*t.args) return t def _extract_data(self, replacement_dict): args_indices, arrays = zip(*[arg._extract_data(replacement_dict) for arg in self.args if isinstance(arg, TensExpr)]) coeff = reduce(operator.mul, [a for a in self.args if not isinstance(a, TensExpr)], S.One) indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices) dum = TensMul._dummy_data_to_dum(dummy_data) ext_rank = self.ext_rank free.sort(key=lambda x: x[1]) free_indices = [i[0] for i in free] return free_indices, coeff*_TensorDataLazyEvaluator.data_contract_dum(arrays, dum, ext_rank) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): dat = _tensor_data_substitution_dict[self.expand()] return dat @data.setter def data(self, data): deprecate_data() raise ValueError("Not possible to set component data to a tensor expression") @data.deleter def data(self): deprecate_data() raise ValueError("Not possible to delete component data to a tensor expression") def __iter__(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self.data is None: raise ValueError("No iteration on abstract tensors") return self.data.__iter__() def _eval_rewrite_as_Indexed(self, *args): from sympy.concrete.summations import Sum index_symbols = [i.args[0] for i in self.get_indices()] args = [arg.args[0] if isinstance(arg, Sum) else arg for arg in args] expr = Mul.fromiter(args) return self._check_add_Sum(expr, index_symbols) def _eval_partial_derivative(self, s): # Evaluation like Mul terms = [] for i, arg in enumerate(self.args): # checking whether some tensor instance is differentiated # or some other thing is necessary, but ugly if isinstance(arg, TensExpr): d = arg._eval_partial_derivative(s) else: # do not call diff is s is no symbol if s._diff_wrt: d = arg._eval_derivative(s) else: d = S.Zero if d: terms.append(TensMul.fromiter(self.args[:i] + (d,) + self.args[i + 1:])) return TensAdd.fromiter(terms) class TensorElement(TensExpr): """ Tensor with evaluated components. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry >>> from sympy import symbols >>> L = TensorIndexType("L") >>> i, j, k = symbols("i j k") >>> A = TensorHead("A", [L, L], TensorSymmetry.fully_symmetric(2)) >>> A(i, j).get_free_indices() [i, j] If we want to set component ``i`` to a specific value, use the ``TensorElement`` class: >>> from sympy.tensor.tensor import TensorElement >>> te = TensorElement(A(i, j), {i: 2}) As index ``i`` has been accessed (``{i: 2}`` is the evaluation of its 3rd element), the free indices will only contain ``j``: >>> te.get_free_indices() [j] """ def __new__(cls, expr, index_map): if not isinstance(expr, Tensor): # remap if not isinstance(expr, TensExpr): raise TypeError("%s is not a tensor expression" % expr) return expr.func(*[TensorElement(arg, index_map) for arg in expr.args]) expr_free_indices = expr.get_free_indices() name_translation = {i.args[0]: i for i in expr_free_indices} index_map = {name_translation.get(index, index): value for index, value in index_map.items()} index_map = {index: value for index, value in index_map.items() if index in expr_free_indices} if len(index_map) == 0: return expr free_indices = [i for i in expr_free_indices if i not in index_map.keys()] index_map = Dict(index_map) obj = TensExpr.__new__(cls, expr, index_map) obj._free_indices = free_indices return obj @property def free(self): return [(index, i) for i, index in enumerate(self.get_free_indices())] @property def dum(self): # TODO: inherit dummies from expr return [] @property def expr(self): return self._args[0] @property def index_map(self): return self._args[1] @property def coeff(self): return S.One @property def nocoeff(self): return self def get_free_indices(self): return self._free_indices def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> TensExpr # TODO: can be improved: return self.xreplace(repl) def get_indices(self): return self.get_free_indices() def _extract_data(self, replacement_dict): ret_indices, array = self.expr._extract_data(replacement_dict) index_map = self.index_map slice_tuple = tuple(index_map.get(i, slice(None)) for i in ret_indices) ret_indices = [i for i in ret_indices if i not in index_map] array = array.__getitem__(slice_tuple) return ret_indices, array def canon_bp(p): """ Butler-Portugal canonicalization. See ``tensor_can.py`` from the combinatorics module for the details. """ if isinstance(p, TensExpr): return p.canon_bp() return p def tensor_mul(*a): """ product of tensors """ if not a: return TensMul.from_data(S.One, [], [], []) t = a[0] for tx in a[1:]: t = t*tx return t def riemann_cyclic_replace(t_r): """ replace Riemann tensor with an equivalent expression ``R(m,n,p,q) -> 2/3*R(m,n,p,q) - 1/3*R(m,q,n,p) + 1/3*R(m,p,n,q)`` """ free = sorted(t_r.free, key=lambda x: x[1]) m, n, p, q = [x[0] for x in free] t0 = t_r*Rational(2, 3) t1 = -t_r.substitute_indices((m,m),(n,q),(p,n),(q,p))*Rational(1, 3) t2 = t_r.substitute_indices((m,m),(n,p),(p,n),(q,q))*Rational(1, 3) t3 = t0 + t1 + t2 return t3 def riemann_cyclic(t2): """ Replace each Riemann tensor with an equivalent expression satisfying the cyclic identity. This trick is discussed in the reference guide to Cadabra. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, riemann_cyclic, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz) >>> R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann()) >>> t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l)) >>> riemann_cyclic(t) 0 """ t2 = t2.expand() if isinstance(t2, (TensMul, Tensor)): args = [t2] else: args = t2.args a1 = [x.split() for x in args] a2 = [[riemann_cyclic_replace(tx) for tx in y] for y in a1] a3 = [tensor_mul(*v) for v in a2] t3 = TensAdd(*a3).doit() if not t3: return t3 else: return canon_bp(t3) def get_lines(ex, index_type): """ Returns ``(lines, traces, rest)`` for an index type, where ``lines`` is the list of list of positions of a matrix line, ``traces`` is the list of list of traced matrix lines, ``rest`` is the rest of the elements ot the tensor. """ def _join_lines(a): i = 0 while i < len(a): x = a[i] xend = x[-1] xstart = x[0] hit = True while hit: hit = False for j in range(i + 1, len(a)): if j >= len(a): break if a[j][0] == xend: hit = True x.extend(a[j][1:]) xend = x[-1] a.pop(j) continue if a[j][0] == xstart: hit = True a[i] = reversed(a[j][1:]) + x x = a[i] xstart = a[i][0] a.pop(j) continue if a[j][-1] == xend: hit = True x.extend(reversed(a[j][:-1])) xend = x[-1] a.pop(j) continue if a[j][-1] == xstart: hit = True a[i] = a[j][:-1] + x x = a[i] xstart = x[0] a.pop(j) continue i += 1 return a arguments = ex.args dt = {} for c in ex.args: if not isinstance(c, TensExpr): continue if c in dt: continue index_types = c.index_types a = [] for i in range(len(index_types)): if index_types[i] is index_type: a.append(i) if len(a) > 2: raise ValueError('at most two indices of type %s allowed' % index_type) if len(a) == 2: dt[c] = a #dum = ex.dum lines = [] traces = [] traces1 = [] #indices_to_args_pos = ex._get_indices_to_args_pos() # TODO: add a dum_to_components_map ? for p0, p1, c0, c1 in ex.dum_in_args: if arguments[c0] not in dt: continue if c0 == c1: traces.append([c0]) continue ta0 = dt[arguments[c0]] ta1 = dt[arguments[c1]] if p0 not in ta0: continue if ta0.index(p0) == ta1.index(p1): # case gamma(i,s0,-s1) in c0, gamma(j,-s0,s2) in c1; # to deal with this case one could add to the position # a flag for transposition; # one could write [(c0, False), (c1, True)] raise NotImplementedError # if p0 == ta0[1] then G in pos c0 is mult on the right by G in c1 # if p0 == ta0[0] then G in pos c1 is mult on the right by G in c0 ta0 = dt[arguments[c0]] b0, b1 = (c0, c1) if p0 == ta0[1] else (c1, c0) lines1 = lines[:] for line in lines: if line[-1] == b0: if line[0] == b1: n = line.index(min(line)) traces1.append(line) traces.append(line[n:] + line[:n]) else: line.append(b1) break elif line[0] == b1: line.insert(0, b0) break else: lines1.append([b0, b1]) lines = [x for x in lines1 if x not in traces1] lines = _join_lines(lines) rest = [] for line in lines: for y in line: rest.append(y) for line in traces: for y in line: rest.append(y) rest = [x for x in range(len(arguments)) if x not in rest] return lines, traces, rest def get_free_indices(t): if not isinstance(t, TensExpr): return () return t.get_free_indices() def get_indices(t): if not isinstance(t, TensExpr): return () return t.get_indices() def get_index_structure(t): if isinstance(t, TensExpr): return t._index_structure return _IndexStructure([], [], [], []) def get_coeff(t): if isinstance(t, Tensor): return S.One if isinstance(t, TensMul): return t.coeff if isinstance(t, TensExpr): raise ValueError("no coefficient associated to this tensor expression") return t def contract_metric(t, g): if isinstance(t, TensExpr): return t.contract_metric(g) return t def perm2tensor(t, g, is_canon_bp=False): """ Returns the tensor corresponding to the permutation ``g`` For further details, see the method in ``TIDS`` with the same name. """ if not isinstance(t, TensExpr): return t elif isinstance(t, (Tensor, TensMul)): nim = get_index_structure(t).perm2tensor(g, is_canon_bp=is_canon_bp) res = t._set_new_index_structure(nim, is_canon_bp=is_canon_bp) if g[-1] != len(g) - 1: return -res return res raise NotImplementedError() def substitute_indices(t, *index_tuples): if not isinstance(t, TensExpr): return t return t.substitute_indices(*index_tuples) def _expand(expr, **kwargs): if isinstance(expr, TensExpr): return expr._expand(**kwargs) else: return expr.expand(**kwargs)
74b89cfb608ca4f5c8b4bb090a3214ad10c48a8fa61f60dcbb71f4360468dc3a
r"""Module that defines indexed objects. The classes ``IndexedBase``, ``Indexed``, and ``Idx`` represent a matrix element ``M[i, j]`` as in the following diagram:: 1) The Indexed class represents the entire indexed object. | ___|___ ' ' M[i, j] / \__\______ | | | | | 2) The Idx class represents indices; each Idx can | optionally contain information about its range. | 3) IndexedBase represents the 'stem' of an indexed object, here `M`. The stem used by itself is usually taken to represent the entire array. There can be any number of indices on an Indexed object. No transformation properties are implemented in these Base objects, but implicit contraction of repeated indices is supported. Note that the support for complicated (i.e. non-atomic) integer expressions as indices is limited. (This should be improved in future releases.) Examples ======== To express the above matrix element example you would write: >>> from sympy import symbols, IndexedBase, Idx >>> M = IndexedBase('M') >>> i, j = symbols('i j', cls=Idx) >>> M[i, j] M[i, j] Repeated indices in a product implies a summation, so to express a matrix-vector product in terms of Indexed objects: >>> x = IndexedBase('x') >>> M[i, j]*x[j] M[i, j]*x[j] If the indexed objects will be converted to component based arrays, e.g. with the code printers or the autowrap framework, you also need to provide (symbolic or numerical) dimensions. This can be done by passing an optional shape parameter to IndexedBase upon construction: >>> dim1, dim2 = symbols('dim1 dim2', integer=True) >>> A = IndexedBase('A', shape=(dim1, 2*dim1, dim2)) >>> A.shape (dim1, 2*dim1, dim2) >>> A[i, j, 3].shape (dim1, 2*dim1, dim2) If an IndexedBase object has no shape information, it is assumed that the array is as large as the ranges of its indices: >>> n, m = symbols('n m', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', n) >>> M[i, j].shape (m, n) >>> M[i, j].ranges [(0, m - 1), (0, n - 1)] The above can be compared with the following: >>> A[i, 2, j].shape (dim1, 2*dim1, dim2) >>> A[i, 2, j].ranges [(0, m - 1), None, (0, n - 1)] To analyze the structure of indexed expressions, you can use the methods get_indices() and get_contraction_structure(): >>> from sympy.tensor import get_indices, get_contraction_structure >>> get_indices(A[i, j, j]) ({i}, {}) >>> get_contraction_structure(A[i, j, j]) {(j,): {A[i, j, j]}} See the appropriate docstrings for a detailed explanation of the output. """ # TODO: (some ideas for improvement) # # o test and guarantee numpy compatibility # - implement full support for broadcasting # - strided arrays # # o more functions to analyze indexed expressions # - identify standard constructs, e.g matrix-vector product in a subexpression # # o functions to generate component based arrays (numpy and sympy.Matrix) # - generate a single array directly from Indexed # - convert simple sub-expressions # # o sophisticated indexing (possibly in subclasses to preserve simplicity) # - Idx with range smaller than dimension of Indexed # - Idx with stepsize != 1 # - Idx with step determined by function call from collections.abc import Iterable from sympy.core.numbers import Number from sympy.core.assumptions import StdFactKB from sympy.core import Expr, Tuple, sympify, S from sympy.core.symbol import _filter_assumptions, Symbol from sympy.core.logic import fuzzy_bool, fuzzy_not from sympy.core.sympify import _sympify from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.multipledispatch import dispatch from sympy.utilities.iterables import is_sequence, NotIterable from sympy.utilities.misc import filldedent class IndexException(Exception): pass class Indexed(Expr): """Represents a mathematical object with indices. >>> from sympy import Indexed, IndexedBase, Idx, symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j) A[i, j] It is recommended that ``Indexed`` objects be created by indexing ``IndexedBase``: ``IndexedBase('A')[i, j]`` instead of ``Indexed(IndexedBase('A'), i, j)``. >>> A = IndexedBase('A') >>> a_ij = A[i, j] # Prefer this, >>> b_ij = Indexed(A, i, j) # over this. >>> a_ij == b_ij True """ is_commutative = True is_Indexed = True is_symbol = True is_Atom = True def __new__(cls, base, *args, **kw_args): from sympy.tensor.array.ndim_array import NDimArray from sympy.matrices.matrices import MatrixBase if not args: raise IndexException("Indexed needs at least one index.") if isinstance(base, (str, Symbol)): base = IndexedBase(base) elif not hasattr(base, '__getitem__') and not isinstance(base, IndexedBase): raise TypeError(filldedent(""" The base can only be replaced with a string, Symbol, IndexedBase or an object with a method for getting items (i.e. an object with a `__getitem__` method). """)) args = list(map(sympify, args)) if isinstance(base, (NDimArray, Iterable, Tuple, MatrixBase)) and all(i.is_number for i in args): if len(args) == 1: return base[args[0]] else: return base[args] base = _sympify(base) obj = Expr.__new__(cls, base, *args, **kw_args) try: IndexedBase._set_assumptions(obj, base.assumptions0) except AttributeError: IndexedBase._set_assumptions(obj, {}) return obj def _hashable_content(self): return super()._hashable_content() + tuple(sorted(self.assumptions0.items())) @property def name(self): return str(self) @property def _diff_wrt(self): """Allow derivatives with respect to an ``Indexed`` object.""" return True def _eval_derivative(self, wrt): from sympy.tensor.array.ndim_array import NDimArray if isinstance(wrt, Indexed) and wrt.base == self.base: if len(self.indices) != len(wrt.indices): msg = "Different # of indices: d({!s})/d({!s})".format(self, wrt) raise IndexException(msg) result = S.One for index1, index2 in zip(self.indices, wrt.indices): result *= KroneckerDelta(index1, index2) return result elif isinstance(self.base, NDimArray): from sympy.tensor.array import derive_by_array return Indexed(derive_by_array(self.base, wrt), *self.args[1:]) else: if Tuple(self.indices).has(wrt): return S.NaN return S.Zero @property def assumptions0(self): return {k: v for k, v in self._assumptions.items() if v is not None} @property def base(self): """Returns the ``IndexedBase`` of the ``Indexed`` object. Examples ======== >>> from sympy import Indexed, IndexedBase, Idx, symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j).base A >>> B = IndexedBase('B') >>> B == B[i, j].base True """ return self.args[0] @property def indices(self): """ Returns the indices of the ``Indexed`` object. Examples ======== >>> from sympy import Indexed, Idx, symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j).indices (i, j) """ return self.args[1:] @property def rank(self): """ Returns the rank of the ``Indexed`` object. Examples ======== >>> from sympy import Indexed, Idx, symbols >>> i, j, k, l, m = symbols('i:m', cls=Idx) >>> Indexed('A', i, j).rank 2 >>> q = Indexed('A', i, j, k, l, m) >>> q.rank 5 >>> q.rank == len(q.indices) True """ return len(self.args) - 1 @property def shape(self): """Returns a list with dimensions of each index. Dimensions is a property of the array, not of the indices. Still, if the ``IndexedBase`` does not define a shape attribute, it is assumed that the ranges of the indices correspond to the shape of the array. >>> from sympy import IndexedBase, Idx, symbols >>> n, m = symbols('n m', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', m) >>> A = IndexedBase('A', shape=(n, n)) >>> B = IndexedBase('B') >>> A[i, j].shape (n, n) >>> B[i, j].shape (m, m) """ if self.base.shape: return self.base.shape sizes = [] for i in self.indices: upper = getattr(i, 'upper', None) lower = getattr(i, 'lower', None) if None in (upper, lower): raise IndexException(filldedent(""" Range is not defined for all indices in: %s""" % self)) try: size = upper - lower + 1 except TypeError: raise IndexException(filldedent(""" Shape cannot be inferred from Idx with undefined range: %s""" % self)) sizes.append(size) return Tuple(*sizes) @property def ranges(self): """Returns a list of tuples with lower and upper range of each index. If an index does not define the data members upper and lower, the corresponding slot in the list contains ``None`` instead of a tuple. Examples ======== >>> from sympy import Indexed,Idx, symbols >>> Indexed('A', Idx('i', 2), Idx('j', 4), Idx('k', 8)).ranges [(0, 1), (0, 3), (0, 7)] >>> Indexed('A', Idx('i', 3), Idx('j', 3), Idx('k', 3)).ranges [(0, 2), (0, 2), (0, 2)] >>> x, y, z = symbols('x y z', integer=True) >>> Indexed('A', x, y, z).ranges [None, None, None] """ ranges = [] sentinel = object() for i in self.indices: upper = getattr(i, 'upper', sentinel) lower = getattr(i, 'lower', sentinel) if sentinel not in (upper, lower): ranges.append((lower, upper)) else: ranges.append(None) return ranges def _sympystr(self, p): indices = list(map(p.doprint, self.indices)) return "%s[%s]" % (p.doprint(self.base), ", ".join(indices)) @property def free_symbols(self): base_free_symbols = self.base.free_symbols indices_free_symbols = { fs for i in self.indices for fs in i.free_symbols} if base_free_symbols: return {self} | base_free_symbols | indices_free_symbols else: return indices_free_symbols @property def expr_free_symbols(self): from sympy.utilities.exceptions import sympy_deprecation_warning sympy_deprecation_warning(""" The expr_free_symbols property is deprecated. Use free_symbols to get the free symbols of an expression. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-expr-free-symbols") return {self} class IndexedBase(Expr, NotIterable): """Represent the base or stem of an indexed object The IndexedBase class represent an array that contains elements. The main purpose of this class is to allow the convenient creation of objects of the Indexed class. The __getitem__ method of IndexedBase returns an instance of Indexed. Alone, without indices, the IndexedBase class can be used as a notation for e.g. matrix equations, resembling what you could do with the Symbol class. But, the IndexedBase class adds functionality that is not available for Symbol instances: - An IndexedBase object can optionally store shape information. This can be used in to check array conformance and conditions for numpy broadcasting. (TODO) - An IndexedBase object implements syntactic sugar that allows easy symbolic representation of array operations, using implicit summation of repeated indices. - The IndexedBase object symbolizes a mathematical structure equivalent to arrays, and is recognized as such for code generation and automatic compilation and wrapping. >>> from sympy.tensor import IndexedBase, Idx >>> from sympy import symbols >>> A = IndexedBase('A'); A A >>> type(A) <class 'sympy.tensor.indexed.IndexedBase'> When an IndexedBase object receives indices, it returns an array with named axes, represented by an Indexed object: >>> i, j = symbols('i j', integer=True) >>> A[i, j, 2] A[i, j, 2] >>> type(A[i, j, 2]) <class 'sympy.tensor.indexed.Indexed'> The IndexedBase constructor takes an optional shape argument. If given, it overrides any shape information in the indices. (But not the index ranges!) >>> m, n, o, p = symbols('m n o p', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', n) >>> A[i, j].shape (m, n) >>> B = IndexedBase('B', shape=(o, p)) >>> B[i, j].shape (o, p) Assumptions can be specified with keyword arguments the same way as for Symbol: >>> A_real = IndexedBase('A', real=True) >>> A_real.is_real True >>> A != A_real True Assumptions can also be inherited if a Symbol is used to initialize the IndexedBase: >>> I = symbols('I', integer=True) >>> C_inherit = IndexedBase(I) >>> C_explicit = IndexedBase('I', integer=True) >>> C_inherit == C_explicit True """ is_commutative = True is_symbol = True is_Atom = True @staticmethod def _set_assumptions(obj, assumptions): """Set assumptions on obj, making sure to apply consistent values.""" tmp_asm_copy = assumptions.copy() is_commutative = fuzzy_bool(assumptions.get('commutative', True)) assumptions['commutative'] = is_commutative obj._assumptions = StdFactKB(assumptions) obj._assumptions._generator = tmp_asm_copy # Issue #8873 def __new__(cls, label, shape=None, *, offset=S.Zero, strides=None, **kw_args): from sympy.matrices.matrices import MatrixBase from sympy.tensor.array.ndim_array import NDimArray assumptions, kw_args = _filter_assumptions(kw_args) if isinstance(label, str): label = Symbol(label, **assumptions) elif isinstance(label, Symbol): assumptions = label._merge(assumptions) elif isinstance(label, (MatrixBase, NDimArray)): return label elif isinstance(label, Iterable): return _sympify(label) else: label = _sympify(label) if is_sequence(shape): shape = Tuple(*shape) elif shape is not None: shape = Tuple(shape) if shape is not None: obj = Expr.__new__(cls, label, shape) else: obj = Expr.__new__(cls, label) obj._shape = shape obj._offset = offset obj._strides = strides obj._name = str(label) IndexedBase._set_assumptions(obj, assumptions) return obj @property def name(self): return self._name def _hashable_content(self): return super()._hashable_content() + tuple(sorted(self.assumptions0.items())) @property def assumptions0(self): return {k: v for k, v in self._assumptions.items() if v is not None} def __getitem__(self, indices, **kw_args): if is_sequence(indices): # Special case needed because M[*my_tuple] is a syntax error. if self.shape and len(self.shape) != len(indices): raise IndexException("Rank mismatch.") return Indexed(self, *indices, **kw_args) else: if self.shape and len(self.shape) != 1: raise IndexException("Rank mismatch.") return Indexed(self, indices, **kw_args) @property def shape(self): """Returns the shape of the ``IndexedBase`` object. Examples ======== >>> from sympy import IndexedBase, Idx >>> from sympy.abc import x, y >>> IndexedBase('A', shape=(x, y)).shape (x, y) Note: If the shape of the ``IndexedBase`` is specified, it will override any shape information given by the indices. >>> A = IndexedBase('A', shape=(x, y)) >>> B = IndexedBase('B') >>> i = Idx('i', 2) >>> j = Idx('j', 1) >>> A[i, j].shape (x, y) >>> B[i, j].shape (2, 1) """ return self._shape @property def strides(self): """Returns the strided scheme for the ``IndexedBase`` object. Normally this is a tuple denoting the number of steps to take in the respective dimension when traversing an array. For code generation purposes strides='C' and strides='F' can also be used. strides='C' would mean that code printer would unroll in row-major order and 'F' means unroll in column major order. """ return self._strides @property def offset(self): """Returns the offset for the ``IndexedBase`` object. This is the value added to the resulting index when the 2D Indexed object is unrolled to a 1D form. Used in code generation. Examples ========== >>> from sympy.printing import ccode >>> from sympy.tensor import IndexedBase, Idx >>> from sympy import symbols >>> l, m, n, o = symbols('l m n o', integer=True) >>> A = IndexedBase('A', strides=(l, m, n), offset=o) >>> i, j, k = map(Idx, 'ijk') >>> ccode(A[i, j, k]) 'A[l*i + m*j + n*k + o]' """ return self._offset @property def label(self): """Returns the label of the ``IndexedBase`` object. Examples ======== >>> from sympy import IndexedBase >>> from sympy.abc import x, y >>> IndexedBase('A', shape=(x, y)).label A """ return self.args[0] def _sympystr(self, p): return p.doprint(self.label) class Idx(Expr): """Represents an integer index as an ``Integer`` or integer expression. There are a number of ways to create an ``Idx`` object. The constructor takes two arguments: ``label`` An integer or a symbol that labels the index. ``range`` Optionally you can specify a range as either * ``Symbol`` or integer: This is interpreted as a dimension. Lower and upper bounds are set to ``0`` and ``range - 1``, respectively. * ``tuple``: The two elements are interpreted as the lower and upper bounds of the range, respectively. Note: bounds of the range are assumed to be either integer or infinite (oo and -oo are allowed to specify an unbounded range). If ``n`` is given as a bound, then ``n.is_integer`` must not return false. For convenience, if the label is given as a string it is automatically converted to an integer symbol. (Note: this conversion is not done for range or dimension arguments.) Examples ======== >>> from sympy import Idx, symbols, oo >>> n, i, L, U = symbols('n i L U', integer=True) If a string is given for the label an integer ``Symbol`` is created and the bounds are both ``None``: >>> idx = Idx('qwerty'); idx qwerty >>> idx.lower, idx.upper (None, None) Both upper and lower bounds can be specified: >>> idx = Idx(i, (L, U)); idx i >>> idx.lower, idx.upper (L, U) When only a single bound is given it is interpreted as the dimension and the lower bound defaults to 0: >>> idx = Idx(i, n); idx.lower, idx.upper (0, n - 1) >>> idx = Idx(i, 4); idx.lower, idx.upper (0, 3) >>> idx = Idx(i, oo); idx.lower, idx.upper (0, oo) """ is_integer = True is_finite = True is_real = True is_symbol = True is_Atom = True _diff_wrt = True def __new__(cls, label, range=None, **kw_args): if isinstance(label, str): label = Symbol(label, integer=True) label, range = list(map(sympify, (label, range))) if label.is_Number: if not label.is_integer: raise TypeError("Index is not an integer number.") return label if not label.is_integer: raise TypeError("Idx object requires an integer label.") elif is_sequence(range): if len(range) != 2: raise ValueError(filldedent(""" Idx range tuple must have length 2, but got %s""" % len(range))) for bound in range: if (bound.is_integer is False and bound is not S.Infinity and bound is not S.NegativeInfinity): raise TypeError("Idx object requires integer bounds.") args = label, Tuple(*range) elif isinstance(range, Expr): if range is not S.Infinity and fuzzy_not(range.is_integer): raise TypeError("Idx object requires an integer dimension.") args = label, Tuple(0, range - 1) elif range: raise TypeError(filldedent(""" The range must be an ordered iterable or integer SymPy expression.""")) else: args = label, obj = Expr.__new__(cls, *args, **kw_args) obj._assumptions["finite"] = True obj._assumptions["real"] = True return obj @property def label(self): """Returns the label (Integer or integer expression) of the Idx object. Examples ======== >>> from sympy import Idx, Symbol >>> x = Symbol('x', integer=True) >>> Idx(x).label x >>> j = Symbol('j', integer=True) >>> Idx(j).label j >>> Idx(j + 1).label j + 1 """ return self.args[0] @property def lower(self): """Returns the lower bound of the ``Idx``. Examples ======== >>> from sympy import Idx >>> Idx('j', 2).lower 0 >>> Idx('j', 5).lower 0 >>> Idx('j').lower is None True """ try: return self.args[1][0] except IndexError: return @property def upper(self): """Returns the upper bound of the ``Idx``. Examples ======== >>> from sympy import Idx >>> Idx('j', 2).upper 1 >>> Idx('j', 5).upper 4 >>> Idx('j').upper is None True """ try: return self.args[1][1] except IndexError: return def _sympystr(self, p): return p.doprint(self.label) @property def name(self): return self.label.name if self.label.is_Symbol else str(self.label) @property def free_symbols(self): return {self} @dispatch(Idx, Idx) def _eval_is_ge(lhs, rhs): # noqa:F811 other_upper = rhs if rhs.upper is None else rhs.upper other_lower = rhs if rhs.lower is None else rhs.lower if lhs.lower is not None and (lhs.lower >= other_upper) == True: return True if lhs.upper is not None and (lhs.upper < other_lower) == True: return False return None @dispatch(Idx, Number) # type:ignore def _eval_is_ge(lhs, rhs): # noqa:F811 other_upper = rhs other_lower = rhs if lhs.lower is not None and (lhs.lower >= other_upper) == True: return True if lhs.upper is not None and (lhs.upper < other_lower) == True: return False return None @dispatch(Number, Idx) # type:ignore def _eval_is_ge(lhs, rhs): # noqa:F811 other_upper = lhs other_lower = lhs if rhs.upper is not None and (rhs.upper <= other_lower) == True: return True if rhs.lower is not None and (rhs.lower > other_upper) == True: return False return None
a032b914dd977da324e4e9304b28ab5767d5f41524b61378f288b5ae49b7a76b
""" Boolean algebra module for SymPy """ from collections import defaultdict from itertools import chain, combinations, product, permutations from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.cache import cacheit from sympy.core.containers import Tuple from sympy.core.decorators import sympify_method_args, sympify_return from sympy.core.function import Application, Derivative from sympy.core.kind import BooleanKind, NumberKind from sympy.core.numbers import Number from sympy.core.operations import LatticeOp from sympy.core.singleton import Singleton, S from sympy.core.sorting import ordered from sympy.core.sympify import _sympy_converter, _sympify, sympify from sympy.utilities.iterables import sift, ibin from sympy.utilities.misc import filldedent def as_Boolean(e): """Like ``bool``, return the Boolean value of an expression, e, which can be any instance of :py:class:`~.Boolean` or ``bool``. Examples ======== >>> from sympy import true, false, nan >>> from sympy.logic.boolalg import as_Boolean >>> from sympy.abc import x >>> as_Boolean(0) is false True >>> as_Boolean(1) is true True >>> as_Boolean(x) x >>> as_Boolean(2) Traceback (most recent call last): ... TypeError: expecting bool or Boolean, not `2`. >>> as_Boolean(nan) Traceback (most recent call last): ... TypeError: expecting bool or Boolean, not `nan`. """ from sympy.core.symbol import Symbol if e == True: return true if e == False: return false if isinstance(e, Symbol): z = e.is_zero if z is None: return e return false if z else true if isinstance(e, Boolean): return e raise TypeError('expecting bool or Boolean, not `%s`.' % e) @sympify_method_args class Boolean(Basic): """A Boolean object is an object for which logic operations make sense.""" __slots__ = () kind = BooleanKind @sympify_return([('other', 'Boolean')], NotImplemented) def __and__(self, other): return And(self, other) __rand__ = __and__ @sympify_return([('other', 'Boolean')], NotImplemented) def __or__(self, other): return Or(self, other) __ror__ = __or__ def __invert__(self): """Overloading for ~""" return Not(self) @sympify_return([('other', 'Boolean')], NotImplemented) def __rshift__(self, other): return Implies(self, other) @sympify_return([('other', 'Boolean')], NotImplemented) def __lshift__(self, other): return Implies(other, self) __rrshift__ = __lshift__ __rlshift__ = __rshift__ @sympify_return([('other', 'Boolean')], NotImplemented) def __xor__(self, other): return Xor(self, other) __rxor__ = __xor__ def equals(self, other): """ Returns ``True`` if the given formulas have the same truth table. For two formulas to be equal they must have the same literals. Examples ======== >>> from sympy.abc import A, B, C >>> from sympy import And, Or, Not >>> (A >> B).equals(~B >> ~A) True >>> Not(And(A, B, C)).equals(And(Not(A), Not(B), Not(C))) False >>> Not(And(A, Not(A))).equals(Or(B, Not(B))) False """ from sympy.logic.inference import satisfiable from sympy.core.relational import Relational if self.has(Relational) or other.has(Relational): raise NotImplementedError('handling of relationals') return self.atoms() == other.atoms() and \ not satisfiable(Not(Equivalent(self, other))) def to_nnf(self, simplify=True): # override where necessary return self def as_set(self): """ Rewrites Boolean expression in terms of real sets. Examples ======== >>> from sympy import Symbol, Eq, Or, And >>> x = Symbol('x', real=True) >>> Eq(x, 0).as_set() {0} >>> (x > 0).as_set() Interval.open(0, oo) >>> And(-2 < x, x < 2).as_set() Interval.open(-2, 2) >>> Or(x < -2, 2 < x).as_set() Union(Interval.open(-oo, -2), Interval.open(2, oo)) """ from sympy.calculus.util import periodicity from sympy.core.relational import Relational free = self.free_symbols if len(free) == 1: x = free.pop() if x.kind is NumberKind: reps = {} for r in self.atoms(Relational): if periodicity(r, x) not in (0, None): s = r._eval_as_set() if s in (S.EmptySet, S.UniversalSet, S.Reals): reps[r] = s.as_relational(x) continue raise NotImplementedError(filldedent(''' as_set is not implemented for relationals with periodic solutions ''')) new = self.subs(reps) if new.func != self.func: return new.as_set() # restart with new obj else: return new._eval_as_set() return self._eval_as_set() else: raise NotImplementedError("Sorry, as_set has not yet been" " implemented for multivariate" " expressions") @property def binary_symbols(self): from sympy.core.relational import Eq, Ne return set().union(*[i.binary_symbols for i in self.args if i.is_Boolean or i.is_Symbol or isinstance(i, (Eq, Ne))]) def _eval_refine(self, assumptions): from sympy.assumptions import ask ret = ask(self, assumptions) if ret is True: return true elif ret is False: return false return None class BooleanAtom(Boolean): """ Base class of :py:class:`~.BooleanTrue` and :py:class:`~.BooleanFalse`. """ is_Boolean = True is_Atom = True _op_priority = 11 # higher than Expr def simplify(self, *a, **kw): return self def expand(self, *a, **kw): return self @property def canonical(self): return self def _noop(self, other=None): raise TypeError('BooleanAtom not allowed in this context.') __add__ = _noop __radd__ = _noop __sub__ = _noop __rsub__ = _noop __mul__ = _noop __rmul__ = _noop __pow__ = _noop __rpow__ = _noop __truediv__ = _noop __rtruediv__ = _noop __mod__ = _noop __rmod__ = _noop _eval_power = _noop # /// drop when Py2 is no longer supported def __lt__(self, other): raise TypeError(filldedent(''' A Boolean argument can only be used in Eq and Ne; all other relationals expect real expressions. ''')) __le__ = __lt__ __gt__ = __lt__ __ge__ = __lt__ # \\\ def _eval_simplify(self, **kwargs): return self class BooleanTrue(BooleanAtom, metaclass=Singleton): """ SymPy version of ``True``, a singleton that can be accessed via ``S.true``. This is the SymPy version of ``True``, for use in the logic module. The primary advantage of using ``true`` instead of ``True`` is that shorthand Boolean operations like ``~`` and ``>>`` will work as expected on this class, whereas with True they act bitwise on 1. Functions in the logic module will return this class when they evaluate to true. Notes ===== There is liable to be some confusion as to when ``True`` should be used and when ``S.true`` should be used in various contexts throughout SymPy. An important thing to remember is that ``sympify(True)`` returns ``S.true``. This means that for the most part, you can just use ``True`` and it will automatically be converted to ``S.true`` when necessary, similar to how you can generally use 1 instead of ``S.One``. The rule of thumb is: "If the boolean in question can be replaced by an arbitrary symbolic ``Boolean``, like ``Or(x, y)`` or ``x > 1``, use ``S.true``. Otherwise, use ``True``" In other words, use ``S.true`` only on those contexts where the boolean is being used as a symbolic representation of truth. For example, if the object ends up in the ``.args`` of any expression, then it must necessarily be ``S.true`` instead of ``True``, as elements of ``.args`` must be ``Basic``. On the other hand, ``==`` is not a symbolic operation in SymPy, since it always returns ``True`` or ``False``, and does so in terms of structural equality rather than mathematical, so it should return ``True``. The assumptions system should use ``True`` and ``False``. Aside from not satisfying the above rule of thumb, the assumptions system uses a three-valued logic (``True``, ``False``, ``None``), whereas ``S.true`` and ``S.false`` represent a two-valued logic. When in doubt, use ``True``. "``S.true == True is True``." While "``S.true is True``" is ``False``, "``S.true == True``" is ``True``, so if there is any doubt over whether a function or expression will return ``S.true`` or ``True``, just use ``==`` instead of ``is`` to do the comparison, and it will work in either case. Finally, for boolean flags, it's better to just use ``if x`` instead of ``if x is True``. To quote PEP 8: Do not compare boolean values to ``True`` or ``False`` using ``==``. * Yes: ``if greeting:`` * No: ``if greeting == True:`` * Worse: ``if greeting is True:`` Examples ======== >>> from sympy import sympify, true, false, Or >>> sympify(True) True >>> _ is True, _ is true (False, True) >>> Or(true, false) True >>> _ is true True Python operators give a boolean result for true but a bitwise result for True >>> ~true, ~True (False, -2) >>> true >> true, True >> True (True, 0) Python operators give a boolean result for true but a bitwise result for True >>> ~true, ~True (False, -2) >>> true >> true, True >> True (True, 0) See Also ======== sympy.logic.boolalg.BooleanFalse """ def __bool__(self): return True def __hash__(self): return hash(True) def __eq__(self, other): if other is True: return True if other is False: return False return super().__eq__(other) @property def negated(self): return false def as_set(self): """ Rewrite logic operators and relationals in terms of real sets. Examples ======== >>> from sympy import true >>> true.as_set() UniversalSet """ return S.UniversalSet class BooleanFalse(BooleanAtom, metaclass=Singleton): """ SymPy version of ``False``, a singleton that can be accessed via ``S.false``. This is the SymPy version of ``False``, for use in the logic module. The primary advantage of using ``false`` instead of ``False`` is that shorthand Boolean operations like ``~`` and ``>>`` will work as expected on this class, whereas with ``False`` they act bitwise on 0. Functions in the logic module will return this class when they evaluate to false. Notes ====== See the notes section in :py:class:`sympy.logic.boolalg.BooleanTrue` Examples ======== >>> from sympy import sympify, true, false, Or >>> sympify(False) False >>> _ is False, _ is false (False, True) >>> Or(true, false) True >>> _ is true True Python operators give a boolean result for false but a bitwise result for False >>> ~false, ~False (True, -1) >>> false >> false, False >> False (True, 0) See Also ======== sympy.logic.boolalg.BooleanTrue """ def __bool__(self): return False def __hash__(self): return hash(False) def __eq__(self, other): if other is True: return False if other is False: return True return super().__eq__(other) @property def negated(self): return true def as_set(self): """ Rewrite logic operators and relationals in terms of real sets. Examples ======== >>> from sympy import false >>> false.as_set() EmptySet """ return S.EmptySet true = BooleanTrue() false = BooleanFalse() # We want S.true and S.false to work, rather than S.BooleanTrue and # S.BooleanFalse, but making the class and instance names the same causes some # major issues (like the inability to import the class directly from this # file). S.true = true S.false = false _sympy_converter[bool] = lambda x: true if x else false class BooleanFunction(Application, Boolean): """Boolean function is a function that lives in a boolean space It is used as base class for :py:class:`~.And`, :py:class:`~.Or`, :py:class:`~.Not`, etc. """ is_Boolean = True def _eval_simplify(self, **kwargs): rv = simplify_univariate(self) if not isinstance(rv, BooleanFunction): return rv.simplify(**kwargs) rv = rv.func(*[a.simplify(**kwargs) for a in rv.args]) return simplify_logic(rv) def simplify(self, **kwargs): from sympy.simplify.simplify import simplify return simplify(self, **kwargs) def __lt__(self, other): raise TypeError(filldedent(''' A Boolean argument can only be used in Eq and Ne; all other relationals expect real expressions. ''')) __le__ = __lt__ __ge__ = __lt__ __gt__ = __lt__ @classmethod def binary_check_and_simplify(self, *args): from sympy.core.relational import Relational, Eq, Ne args = [as_Boolean(i) for i in args] bin_syms = set().union(*[i.binary_symbols for i in args]) rel = set().union(*[i.atoms(Relational) for i in args]) reps = {} for x in bin_syms: for r in rel: if x in bin_syms and x in r.free_symbols: if isinstance(r, (Eq, Ne)): if not ( true in r.args or false in r.args): reps[r] = false else: raise TypeError(filldedent(''' Incompatible use of binary symbol `%s` as a real variable in `%s` ''' % (x, r))) return [i.subs(reps) for i in args] def to_nnf(self, simplify=True): return self._to_nnf(*self.args, simplify=simplify) def to_anf(self, deep=True): return self._to_anf(*self.args, deep=deep) @classmethod def _to_nnf(cls, *args, **kwargs): simplify = kwargs.get('simplify', True) argset = set() for arg in args: if not is_literal(arg): arg = arg.to_nnf(simplify) if simplify: if isinstance(arg, cls): arg = arg.args else: arg = (arg,) for a in arg: if Not(a) in argset: return cls.zero argset.add(a) else: argset.add(arg) return cls(*argset) @classmethod def _to_anf(cls, *args, **kwargs): deep = kwargs.get('deep', True) argset = set() for arg in args: if deep: if not is_literal(arg) or isinstance(arg, Not): arg = arg.to_anf(deep=deep) argset.add(arg) else: argset.add(arg) return cls(*argset, remove_true=False) # the diff method below is copied from Expr class def diff(self, *symbols, **assumptions): assumptions.setdefault("evaluate", True) return Derivative(self, *symbols, **assumptions) def _eval_derivative(self, x): if x in self.binary_symbols: from sympy.core.relational import Eq from sympy.functions.elementary.piecewise import Piecewise return Piecewise( (0, Eq(self.subs(x, 0), self.subs(x, 1))), (1, True)) elif x in self.free_symbols: # not implemented, see https://www.encyclopediaofmath.org/ # index.php/Boolean_differential_calculus pass else: return S.Zero class And(LatticeOp, BooleanFunction): """ Logical AND function. It evaluates its arguments in order, returning false immediately when an argument is false and true if they are all true. Examples ======== >>> from sympy.abc import x, y >>> from sympy import And >>> x & y x & y Notes ===== The ``&`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise and. Hence, ``And(a, b)`` and ``a & b`` will produce different results if ``a`` and ``b`` are integers. >>> And(x, y).subs(x, 1) y """ zero = false identity = true nargs = None @classmethod def _new_args_filter(cls, args): args = BooleanFunction.binary_check_and_simplify(*args) args = LatticeOp._new_args_filter(args, And) newargs = [] rel = set() for x in ordered(args): if x.is_Relational: c = x.canonical if c in rel: continue elif c.negated.canonical in rel: return [false] else: rel.add(c) newargs.append(x) return newargs def _eval_subs(self, old, new): args = [] bad = None for i in self.args: try: i = i.subs(old, new) except TypeError: # store TypeError if bad is None: bad = i continue if i == False: return false elif i != True: args.append(i) if bad is not None: # let it raise bad.subs(old, new) # If old is And, replace the parts of the arguments with new if all # are there if isinstance(old, And): old_set = set(old.args) if old_set.issubset(args): args = set(args) - old_set args.add(new) return self.func(*args) def _eval_simplify(self, **kwargs): from sympy.core.relational import Equality, Relational from sympy.solvers.solveset import linear_coeffs # standard simplify rv = super()._eval_simplify(**kwargs) if not isinstance(rv, And): return rv # simplify args that are equalities involving # symbols so x == 0 & x == y -> x==0 & y == 0 Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational), binary=True) if not Rel: return rv eqs, other = sift(Rel, lambda i: isinstance(i, Equality), binary=True) measure = kwargs['measure'] if eqs: ratio = kwargs['ratio'] reps = {} sifted = {} # group by length of free symbols sifted = sift(ordered([ (i.free_symbols, i) for i in eqs]), lambda x: len(x[0])) eqs = [] nonlineqs = [] while 1 in sifted: for free, e in sifted.pop(1): x = free.pop() if (e.lhs != x or x in e.rhs.free_symbols) and x not in reps: try: m, b = linear_coeffs( e.rewrite(Add, evaluate=False), x) enew = e.func(x, -b/m) if measure(enew) <= ratio*measure(e): e = enew else: eqs.append(e) continue except ValueError: pass if x in reps: eqs.append(e.subs(x, reps[x])) elif e.lhs == x and x not in e.rhs.free_symbols: reps[x] = e.rhs eqs.append(e) else: # x is not yet identified, but may be later nonlineqs.append(e) resifted = defaultdict(list) for k in sifted: for f, e in sifted[k]: e = e.xreplace(reps) f = e.free_symbols resifted[len(f)].append((f, e)) sifted = resifted for k in sifted: eqs.extend([e for f, e in sifted[k]]) nonlineqs = [ei.subs(reps) for ei in nonlineqs] other = [ei.subs(reps) for ei in other] rv = rv.func(*([i.canonical for i in (eqs + nonlineqs + other)] + nonRel)) patterns = _simplify_patterns_and() threeterm_patterns = _simplify_patterns_and3() return _apply_patternbased_simplification(rv, patterns, measure, false, threeterm_patterns=threeterm_patterns) def _eval_as_set(self): from sympy.sets.sets import Intersection return Intersection(*[arg.as_set() for arg in self.args]) def _eval_rewrite_as_Nor(self, *args, **kwargs): return Nor(*[Not(arg) for arg in self.args]) def to_anf(self, deep=True): if deep: result = And._to_anf(*self.args, deep=deep) return distribute_xor_over_and(result) return self class Or(LatticeOp, BooleanFunction): """ Logical OR function It evaluates its arguments in order, returning true immediately when an argument is true, and false if they are all false. Examples ======== >>> from sympy.abc import x, y >>> from sympy import Or >>> x | y x | y Notes ===== The ``|`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise or. Hence, ``Or(a, b)`` and ``a | b`` will return different things if ``a`` and ``b`` are integers. >>> Or(x, y).subs(x, 0) y """ zero = true identity = false @classmethod def _new_args_filter(cls, args): newargs = [] rel = [] args = BooleanFunction.binary_check_and_simplify(*args) for x in args: if x.is_Relational: c = x.canonical if c in rel: continue nc = c.negated.canonical if any(r == nc for r in rel): return [true] rel.append(c) newargs.append(x) return LatticeOp._new_args_filter(newargs, Or) def _eval_subs(self, old, new): args = [] bad = None for i in self.args: try: i = i.subs(old, new) except TypeError: # store TypeError if bad is None: bad = i continue if i == True: return true elif i != False: args.append(i) if bad is not None: # let it raise bad.subs(old, new) # If old is Or, replace the parts of the arguments with new if all # are there if isinstance(old, Or): old_set = set(old.args) if old_set.issubset(args): args = set(args) - old_set args.add(new) return self.func(*args) def _eval_as_set(self): from sympy.sets.sets import Union return Union(*[arg.as_set() for arg in self.args]) def _eval_rewrite_as_Nand(self, *args, **kwargs): return Nand(*[Not(arg) for arg in self.args]) def _eval_simplify(self, **kwargs): from sympy.core.relational import Le, Ge, Eq lege = self.atoms(Le, Ge) if lege: reps = {i: self.func( Eq(i.lhs, i.rhs), i.strict) for i in lege} return self.xreplace(reps)._eval_simplify(**kwargs) # standard simplify rv = super()._eval_simplify(**kwargs) if not isinstance(rv, Or): return rv patterns = _simplify_patterns_or() return _apply_patternbased_simplification(rv, patterns, kwargs['measure'], true) def to_anf(self, deep=True): args = range(1, len(self.args) + 1) args = (combinations(self.args, j) for j in args) args = chain.from_iterable(args) # powerset args = (And(*arg) for arg in args) args = map(lambda x: to_anf(x, deep=deep) if deep else x, args) return Xor(*list(args), remove_true=False) class Not(BooleanFunction): """ Logical Not function (negation) Returns ``true`` if the statement is ``false`` or ``False``. Returns ``false`` if the statement is ``true`` or ``True``. Examples ======== >>> from sympy import Not, And, Or >>> from sympy.abc import x, A, B >>> Not(True) False >>> Not(False) True >>> Not(And(True, False)) True >>> Not(Or(True, False)) False >>> Not(And(And(True, x), Or(x, False))) ~x >>> ~x ~x >>> Not(And(Or(A, B), Or(~A, ~B))) ~((A | B) & (~A | ~B)) Notes ===== - The ``~`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise not. In particular, ``~a`` and ``Not(a)`` will be different if ``a`` is an integer. Furthermore, since bools in Python subclass from ``int``, ``~True`` is the same as ``~1`` which is ``-2``, which has a boolean value of True. To avoid this issue, use the SymPy boolean types ``true`` and ``false``. >>> from sympy import true >>> ~True -2 >>> ~true False """ is_Not = True @classmethod def eval(cls, arg): if isinstance(arg, Number) or arg in (True, False): return false if arg else true if arg.is_Not: return arg.args[0] # Simplify Relational objects. if arg.is_Relational: return arg.negated def _eval_as_set(self): """ Rewrite logic operators and relationals in terms of real sets. Examples ======== >>> from sympy import Not, Symbol >>> x = Symbol('x') >>> Not(x > 0).as_set() Interval(-oo, 0) """ return self.args[0].as_set().complement(S.Reals) def to_nnf(self, simplify=True): if is_literal(self): return self expr = self.args[0] func, args = expr.func, expr.args if func == And: return Or._to_nnf(*[Not(arg) for arg in args], simplify=simplify) if func == Or: return And._to_nnf(*[Not(arg) for arg in args], simplify=simplify) if func == Implies: a, b = args return And._to_nnf(a, Not(b), simplify=simplify) if func == Equivalent: return And._to_nnf(Or(*args), Or(*[Not(arg) for arg in args]), simplify=simplify) if func == Xor: result = [] for i in range(1, len(args)+1, 2): for neg in combinations(args, i): clause = [Not(s) if s in neg else s for s in args] result.append(Or(*clause)) return And._to_nnf(*result, simplify=simplify) if func == ITE: a, b, c = args return And._to_nnf(Or(a, Not(c)), Or(Not(a), Not(b)), simplify=simplify) raise ValueError("Illegal operator %s in expression" % func) def to_anf(self, deep=True): return Xor._to_anf(true, self.args[0], deep=deep) class Xor(BooleanFunction): """ Logical XOR (exclusive OR) function. Returns True if an odd number of the arguments are True and the rest are False. Returns False if an even number of the arguments are True and the rest are False. Examples ======== >>> from sympy.logic.boolalg import Xor >>> from sympy import symbols >>> x, y = symbols('x y') >>> Xor(True, False) True >>> Xor(True, True) False >>> Xor(True, False, True, True, False) True >>> Xor(True, False, True, False) False >>> x ^ y x ^ y Notes ===== The ``^`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise xor. In particular, ``a ^ b`` and ``Xor(a, b)`` will be different if ``a`` and ``b`` are integers. >>> Xor(x, y).subs(y, 0) x """ def __new__(cls, *args, remove_true=True, **kwargs): argset = set() obj = super().__new__(cls, *args, **kwargs) for arg in obj._args: if isinstance(arg, Number) or arg in (True, False): if arg: arg = true else: continue if isinstance(arg, Xor): for a in arg.args: argset.remove(a) if a in argset else argset.add(a) elif arg in argset: argset.remove(arg) else: argset.add(arg) rel = [(r, r.canonical, r.negated.canonical) for r in argset if r.is_Relational] odd = False # is number of complimentary pairs odd? start 0 -> False remove = [] for i, (r, c, nc) in enumerate(rel): for j in range(i + 1, len(rel)): rj, cj = rel[j][:2] if cj == nc: odd = ~odd break elif cj == c: break else: continue remove.append((r, rj)) if odd: argset.remove(true) if true in argset else argset.add(true) for a, b in remove: argset.remove(a) argset.remove(b) if len(argset) == 0: return false elif len(argset) == 1: return argset.pop() elif True in argset and remove_true: argset.remove(True) return Not(Xor(*argset)) else: obj._args = tuple(ordered(argset)) obj._argset = frozenset(argset) return obj # XXX: This should be cached on the object rather than using cacheit # Maybe it can be computed in __new__? @property # type: ignore @cacheit def args(self): return tuple(ordered(self._argset)) def to_nnf(self, simplify=True): args = [] for i in range(0, len(self.args)+1, 2): for neg in combinations(self.args, i): clause = [Not(s) if s in neg else s for s in self.args] args.append(Or(*clause)) return And._to_nnf(*args, simplify=simplify) def _eval_rewrite_as_Or(self, *args, **kwargs): a = self.args return Or(*[_convert_to_varsSOP(x, self.args) for x in _get_odd_parity_terms(len(a))]) def _eval_rewrite_as_And(self, *args, **kwargs): a = self.args return And(*[_convert_to_varsPOS(x, self.args) for x in _get_even_parity_terms(len(a))]) def _eval_simplify(self, **kwargs): # as standard simplify uses simplify_logic which writes things as # And and Or, we only simplify the partial expressions before using # patterns rv = self.func(*[a.simplify(**kwargs) for a in self.args]) if not isinstance(rv, Xor): # This shouldn't really happen here return rv patterns = _simplify_patterns_xor() return _apply_patternbased_simplification(rv, patterns, kwargs['measure'], None) def _eval_subs(self, old, new): # If old is Xor, replace the parts of the arguments with new if all # are there if isinstance(old, Xor): old_set = set(old.args) if old_set.issubset(self.args): args = set(self.args) - old_set args.add(new) return self.func(*args) class Nand(BooleanFunction): """ Logical NAND function. It evaluates its arguments in order, giving True immediately if any of them are False, and False if they are all True. Returns True if any of the arguments are False Returns False if all arguments are True Examples ======== >>> from sympy.logic.boolalg import Nand >>> from sympy import symbols >>> x, y = symbols('x y') >>> Nand(False, True) True >>> Nand(True, True) False >>> Nand(x, y) ~(x & y) """ @classmethod def eval(cls, *args): return Not(And(*args)) class Nor(BooleanFunction): """ Logical NOR function. It evaluates its arguments in order, giving False immediately if any of them are True, and True if they are all False. Returns False if any argument is True Returns True if all arguments are False Examples ======== >>> from sympy.logic.boolalg import Nor >>> from sympy import symbols >>> x, y = symbols('x y') >>> Nor(True, False) False >>> Nor(True, True) False >>> Nor(False, True) False >>> Nor(False, False) True >>> Nor(x, y) ~(x | y) """ @classmethod def eval(cls, *args): return Not(Or(*args)) class Xnor(BooleanFunction): """ Logical XNOR function. Returns False if an odd number of the arguments are True and the rest are False. Returns True if an even number of the arguments are True and the rest are False. Examples ======== >>> from sympy.logic.boolalg import Xnor >>> from sympy import symbols >>> x, y = symbols('x y') >>> Xnor(True, False) False >>> Xnor(True, True) True >>> Xnor(True, False, True, True, False) False >>> Xnor(True, False, True, False) True """ @classmethod def eval(cls, *args): return Not(Xor(*args)) class Implies(BooleanFunction): r""" Logical implication. A implies B is equivalent to if A then B. Mathematically, it is written as `A \Rightarrow B` and is equivalent to `\neg A \vee B` or ``~A | B``. Accepts two Boolean arguments; A and B. Returns False if A is True and B is False Returns True otherwise. Examples ======== >>> from sympy.logic.boolalg import Implies >>> from sympy import symbols >>> x, y = symbols('x y') >>> Implies(True, False) False >>> Implies(False, False) True >>> Implies(True, True) True >>> Implies(False, True) True >>> x >> y Implies(x, y) >>> y << x Implies(x, y) Notes ===== The ``>>`` and ``<<`` operators are provided as a convenience, but note that their use here is different from their normal use in Python, which is bit shifts. Hence, ``Implies(a, b)`` and ``a >> b`` will return different things if ``a`` and ``b`` are integers. In particular, since Python considers ``True`` and ``False`` to be integers, ``True >> True`` will be the same as ``1 >> 1``, i.e., 0, which has a truth value of False. To avoid this issue, use the SymPy objects ``true`` and ``false``. >>> from sympy import true, false >>> True >> False 1 >>> true >> false False """ @classmethod def eval(cls, *args): try: newargs = [] for x in args: if isinstance(x, Number) or x in (0, 1): newargs.append(bool(x)) else: newargs.append(x) A, B = newargs except ValueError: raise ValueError( "%d operand(s) used for an Implies " "(pairs are required): %s" % (len(args), str(args))) if A in (True, False) or B in (True, False): return Or(Not(A), B) elif A == B: return true elif A.is_Relational and B.is_Relational: if A.canonical == B.canonical: return true if A.negated.canonical == B.canonical: return B else: return Basic.__new__(cls, *args) def to_nnf(self, simplify=True): a, b = self.args return Or._to_nnf(Not(a), b, simplify=simplify) def to_anf(self, deep=True): a, b = self.args return Xor._to_anf(true, a, And(a, b), deep=deep) class Equivalent(BooleanFunction): """ Equivalence relation. ``Equivalent(A, B)`` is True iff A and B are both True or both False. Returns True if all of the arguments are logically equivalent. Returns False otherwise. For two arguments, this is equivalent to :py:class:`~.Xnor`. Examples ======== >>> from sympy.logic.boolalg import Equivalent, And >>> from sympy.abc import x >>> Equivalent(False, False, False) True >>> Equivalent(True, False, False) False >>> Equivalent(x, And(x, True)) True """ def __new__(cls, *args, **options): from sympy.core.relational import Relational args = [_sympify(arg) for arg in args] argset = set(args) for x in args: if isinstance(x, Number) or x in [True, False]: # Includes 0, 1 argset.discard(x) argset.add(bool(x)) rel = [] for r in argset: if isinstance(r, Relational): rel.append((r, r.canonical, r.negated.canonical)) remove = [] for i, (r, c, nc) in enumerate(rel): for j in range(i + 1, len(rel)): rj, cj = rel[j][:2] if cj == nc: return false elif cj == c: remove.append((r, rj)) break for a, b in remove: argset.remove(a) argset.remove(b) argset.add(True) if len(argset) <= 1: return true if True in argset: argset.discard(True) return And(*argset) if False in argset: argset.discard(False) return And(*[Not(arg) for arg in argset]) _args = frozenset(argset) obj = super().__new__(cls, _args) obj._argset = _args return obj # XXX: This should be cached on the object rather than using cacheit # Maybe it can be computed in __new__? @property # type: ignore @cacheit def args(self): return tuple(ordered(self._argset)) def to_nnf(self, simplify=True): args = [] for a, b in zip(self.args, self.args[1:]): args.append(Or(Not(a), b)) args.append(Or(Not(self.args[-1]), self.args[0])) return And._to_nnf(*args, simplify=simplify) def to_anf(self, deep=True): a = And(*self.args) b = And(*[to_anf(Not(arg), deep=False) for arg in self.args]) b = distribute_xor_over_and(b) return Xor._to_anf(a, b, deep=deep) class ITE(BooleanFunction): """ If-then-else clause. ``ITE(A, B, C)`` evaluates and returns the result of B if A is true else it returns the result of C. All args must be Booleans. From a logic gate perspective, ITE corresponds to a 2-to-1 multiplexer, where A is the select signal. Examples ======== >>> from sympy.logic.boolalg import ITE, And, Xor, Or >>> from sympy.abc import x, y, z >>> ITE(True, False, True) False >>> ITE(Or(True, False), And(True, True), Xor(True, True)) True >>> ITE(x, y, z) ITE(x, y, z) >>> ITE(True, x, y) x >>> ITE(False, x, y) y >>> ITE(x, y, y) y Trying to use non-Boolean args will generate a TypeError: >>> ITE(True, [], ()) Traceback (most recent call last): ... TypeError: expecting bool, Boolean or ITE, not `[]` """ def __new__(cls, *args, **kwargs): from sympy.core.relational import Eq, Ne if len(args) != 3: raise ValueError('expecting exactly 3 args') a, b, c = args # check use of binary symbols if isinstance(a, (Eq, Ne)): # in this context, we can evaluate the Eq/Ne # if one arg is a binary symbol and the other # is true/false b, c = map(as_Boolean, (b, c)) bin_syms = set().union(*[i.binary_symbols for i in (b, c)]) if len(set(a.args) - bin_syms) == 1: # one arg is a binary_symbols _a = a if a.lhs is true: a = a.rhs elif a.rhs is true: a = a.lhs elif a.lhs is false: a = Not(a.rhs) elif a.rhs is false: a = Not(a.lhs) else: # binary can only equal True or False a = false if isinstance(_a, Ne): a = Not(a) else: a, b, c = BooleanFunction.binary_check_and_simplify( a, b, c) rv = None if kwargs.get('evaluate', True): rv = cls.eval(a, b, c) if rv is None: rv = BooleanFunction.__new__(cls, a, b, c, evaluate=False) return rv @classmethod def eval(cls, *args): from sympy.core.relational import Eq, Ne # do the args give a singular result? a, b, c = args if isinstance(a, (Ne, Eq)): _a = a if true in a.args: a = a.lhs if a.rhs is true else a.rhs elif false in a.args: a = Not(a.lhs) if a.rhs is false else Not(a.rhs) else: _a = None if _a is not None and isinstance(_a, Ne): a = Not(a) if a is true: return b if a is false: return c if b == c: return b else: # or maybe the results allow the answer to be expressed # in terms of the condition if b is true and c is false: return a if b is false and c is true: return Not(a) if [a, b, c] != args: return cls(a, b, c, evaluate=False) def to_nnf(self, simplify=True): a, b, c = self.args return And._to_nnf(Or(Not(a), b), Or(a, c), simplify=simplify) def _eval_as_set(self): return self.to_nnf().as_set() def _eval_rewrite_as_Piecewise(self, *args, **kwargs): from sympy.functions.elementary.piecewise import Piecewise return Piecewise((args[1], args[0]), (args[2], True)) class Exclusive(BooleanFunction): """ True if only one or no argument is true. ``Exclusive(A, B, C)`` is equivalent to ``~(A & B) & ~(A & C) & ~(B & C)``. For two arguments, this is equivalent to :py:class:`~.Xor`. Examples ======== >>> from sympy.logic.boolalg import Exclusive >>> Exclusive(False, False, False) True >>> Exclusive(False, True, False) True >>> Exclusive(False, True, True) False """ @classmethod def eval(cls, *args): and_args = [] for a, b in combinations(args, 2): and_args.append(Not(And(a, b))) return And(*and_args) # end class definitions. Some useful methods def conjuncts(expr): """Return a list of the conjuncts in ``expr``. Examples ======== >>> from sympy.logic.boolalg import conjuncts >>> from sympy.abc import A, B >>> conjuncts(A & B) frozenset({A, B}) >>> conjuncts(A | B) frozenset({A | B}) """ return And.make_args(expr) def disjuncts(expr): """Return a list of the disjuncts in ``expr``. Examples ======== >>> from sympy.logic.boolalg import disjuncts >>> from sympy.abc import A, B >>> disjuncts(A | B) frozenset({A, B}) >>> disjuncts(A & B) frozenset({A & B}) """ return Or.make_args(expr) def distribute_and_over_or(expr): """ Given a sentence ``expr`` consisting of conjunctions and disjunctions of literals, return an equivalent sentence in CNF. Examples ======== >>> from sympy.logic.boolalg import distribute_and_over_or, And, Or, Not >>> from sympy.abc import A, B, C >>> distribute_and_over_or(Or(A, And(Not(B), Not(C)))) (A | ~B) & (A | ~C) """ return _distribute((expr, And, Or)) def distribute_or_over_and(expr): """ Given a sentence ``expr`` consisting of conjunctions and disjunctions of literals, return an equivalent sentence in DNF. Note that the output is NOT simplified. Examples ======== >>> from sympy.logic.boolalg import distribute_or_over_and, And, Or, Not >>> from sympy.abc import A, B, C >>> distribute_or_over_and(And(Or(Not(A), B), C)) (B & C) | (C & ~A) """ return _distribute((expr, Or, And)) def distribute_xor_over_and(expr): """ Given a sentence ``expr`` consisting of conjunction and exclusive disjunctions of literals, return an equivalent exclusive disjunction. Note that the output is NOT simplified. Examples ======== >>> from sympy.logic.boolalg import distribute_xor_over_and, And, Xor, Not >>> from sympy.abc import A, B, C >>> distribute_xor_over_and(And(Xor(Not(A), B), C)) (B & C) ^ (C & ~A) """ return _distribute((expr, Xor, And)) def _distribute(info): """ Distributes ``info[1]`` over ``info[2]`` with respect to ``info[0]``. """ if isinstance(info[0], info[2]): for arg in info[0].args: if isinstance(arg, info[1]): conj = arg break else: return info[0] rest = info[2](*[a for a in info[0].args if a is not conj]) return info[1](*list(map(_distribute, [(info[2](c, rest), info[1], info[2]) for c in conj.args])), remove_true=False) elif isinstance(info[0], info[1]): return info[1](*list(map(_distribute, [(x, info[1], info[2]) for x in info[0].args])), remove_true=False) else: return info[0] def to_anf(expr, deep=True): r""" Converts expr to Algebraic Normal Form (ANF). ANF is a canonical normal form, which means that two equivalent formulas will convert to the same ANF. A logical expression is in ANF if it has the form .. math:: 1 \oplus a \oplus b \oplus ab \oplus abc i.e. it can be: - purely true, - purely false, - conjunction of variables, - exclusive disjunction. The exclusive disjunction can only contain true, variables or conjunction of variables. No negations are permitted. If ``deep`` is ``False``, arguments of the boolean expression are considered variables, i.e. only the top-level expression is converted to ANF. Examples ======== >>> from sympy.logic.boolalg import And, Or, Not, Implies, Equivalent >>> from sympy.logic.boolalg import to_anf >>> from sympy.abc import A, B, C >>> to_anf(Not(A)) A ^ True >>> to_anf(And(Or(A, B), Not(C))) A ^ B ^ (A & B) ^ (A & C) ^ (B & C) ^ (A & B & C) >>> to_anf(Implies(Not(A), Equivalent(B, C)), deep=False) True ^ ~A ^ (~A & (Equivalent(B, C))) """ expr = sympify(expr) if is_anf(expr): return expr return expr.to_anf(deep=deep) def to_nnf(expr, simplify=True): """ Converts ``expr`` to Negation Normal Form (NNF). A logical expression is in NNF if it contains only :py:class:`~.And`, :py:class:`~.Or` and :py:class:`~.Not`, and :py:class:`~.Not` is applied only to literals. If ``simplify`` is ``True``, the result contains no redundant clauses. Examples ======== >>> from sympy.abc import A, B, C, D >>> from sympy.logic.boolalg import Not, Equivalent, to_nnf >>> to_nnf(Not((~A & ~B) | (C & D))) (A | B) & (~C | ~D) >>> to_nnf(Equivalent(A >> B, B >> A)) (A | ~B | (A & ~B)) & (B | ~A | (B & ~A)) """ if is_nnf(expr, simplify): return expr return expr.to_nnf(simplify) def to_cnf(expr, simplify=False, force=False): """ Convert a propositional logical sentence ``expr`` to conjunctive normal form: ``((A | ~B | ...) & (B | C | ...) & ...)``. If ``simplify`` is ``True``, ``expr`` is evaluated to its simplest CNF form using the Quine-McCluskey algorithm; this may take a long time. If there are more than 8 variables the ``force`` flag must be set to ``True`` to simplify (default is ``False``). Examples ======== >>> from sympy.logic.boolalg import to_cnf >>> from sympy.abc import A, B, D >>> to_cnf(~(A | B) | D) (D | ~A) & (D | ~B) >>> to_cnf((A | B) & (A | ~A), True) A | B """ expr = sympify(expr) if not isinstance(expr, BooleanFunction): return expr if simplify: if not force and len(_find_predicates(expr)) > 8: raise ValueError(filldedent(''' To simplify a logical expression with more than 8 variables may take a long time and requires the use of `force=True`.''')) return simplify_logic(expr, 'cnf', True, force=force) # Don't convert unless we have to if is_cnf(expr): return expr expr = eliminate_implications(expr) res = distribute_and_over_or(expr) return res def to_dnf(expr, simplify=False, force=False): """ Convert a propositional logical sentence ``expr`` to disjunctive normal form: ``((A & ~B & ...) | (B & C & ...) | ...)``. If ``simplify`` is ``True``, ``expr`` is evaluated to its simplest DNF form using the Quine-McCluskey algorithm; this may take a long time. If there are more than 8 variables, the ``force`` flag must be set to ``True`` to simplify (default is ``False``). Examples ======== >>> from sympy.logic.boolalg import to_dnf >>> from sympy.abc import A, B, C >>> to_dnf(B & (A | C)) (A & B) | (B & C) >>> to_dnf((A & B) | (A & ~B) | (B & C) | (~B & C), True) A | C """ expr = sympify(expr) if not isinstance(expr, BooleanFunction): return expr if simplify: if not force and len(_find_predicates(expr)) > 8: raise ValueError(filldedent(''' To simplify a logical expression with more than 8 variables may take a long time and requires the use of `force=True`.''')) return simplify_logic(expr, 'dnf', True, force=force) # Don't convert unless we have to if is_dnf(expr): return expr expr = eliminate_implications(expr) return distribute_or_over_and(expr) def is_anf(expr): r""" Checks if ``expr`` is in Algebraic Normal Form (ANF). A logical expression is in ANF if it has the form .. math:: 1 \oplus a \oplus b \oplus ab \oplus abc i.e. it is purely true, purely false, conjunction of variables or exclusive disjunction. The exclusive disjunction can only contain true, variables or conjunction of variables. No negations are permitted. Examples ======== >>> from sympy.logic.boolalg import And, Not, Xor, true, is_anf >>> from sympy.abc import A, B, C >>> is_anf(true) True >>> is_anf(A) True >>> is_anf(And(A, B, C)) True >>> is_anf(Xor(A, Not(B))) False """ expr = sympify(expr) if is_literal(expr) and not isinstance(expr, Not): return True if isinstance(expr, And): for arg in expr.args: if not arg.is_Symbol: return False return True elif isinstance(expr, Xor): for arg in expr.args: if isinstance(arg, And): for a in arg.args: if not a.is_Symbol: return False elif is_literal(arg): if isinstance(arg, Not): return False else: return False return True else: return False def is_nnf(expr, simplified=True): """ Checks if ``expr`` is in Negation Normal Form (NNF). A logical expression is in NNF if it contains only :py:class:`~.And`, :py:class:`~.Or` and :py:class:`~.Not`, and :py:class:`~.Not` is applied only to literals. If ``simplified`` is ``True``, checks if result contains no redundant clauses. Examples ======== >>> from sympy.abc import A, B, C >>> from sympy.logic.boolalg import Not, is_nnf >>> is_nnf(A & B | ~C) True >>> is_nnf((A | ~A) & (B | C)) False >>> is_nnf((A | ~A) & (B | C), False) True >>> is_nnf(Not(A & B) | C) False >>> is_nnf((A >> B) & (B >> A)) False """ expr = sympify(expr) if is_literal(expr): return True stack = [expr] while stack: expr = stack.pop() if expr.func in (And, Or): if simplified: args = expr.args for arg in args: if Not(arg) in args: return False stack.extend(expr.args) elif not is_literal(expr): return False return True def is_cnf(expr): """ Test whether or not an expression is in conjunctive normal form. Examples ======== >>> from sympy.logic.boolalg import is_cnf >>> from sympy.abc import A, B, C >>> is_cnf(A | B | C) True >>> is_cnf(A & B & C) True >>> is_cnf((A & B) | C) False """ return _is_form(expr, And, Or) def is_dnf(expr): """ Test whether or not an expression is in disjunctive normal form. Examples ======== >>> from sympy.logic.boolalg import is_dnf >>> from sympy.abc import A, B, C >>> is_dnf(A | B | C) True >>> is_dnf(A & B & C) True >>> is_dnf((A & B) | C) True >>> is_dnf(A & (B | C)) False """ return _is_form(expr, Or, And) def _is_form(expr, function1, function2): """ Test whether or not an expression is of the required form. """ expr = sympify(expr) vals = function1.make_args(expr) if isinstance(expr, function1) else [expr] for lit in vals: if isinstance(lit, function2): vals2 = function2.make_args(lit) if isinstance(lit, function2) else [lit] for l in vals2: if is_literal(l) is False: return False elif is_literal(lit) is False: return False return True def eliminate_implications(expr): """ Change :py:class:`~.Implies` and :py:class:`~.Equivalent` into :py:class:`~.And`, :py:class:`~.Or`, and :py:class:`~.Not`. That is, return an expression that is equivalent to ``expr``, but has only ``&``, ``|``, and ``~`` as logical operators. Examples ======== >>> from sympy.logic.boolalg import Implies, Equivalent, \ eliminate_implications >>> from sympy.abc import A, B, C >>> eliminate_implications(Implies(A, B)) B | ~A >>> eliminate_implications(Equivalent(A, B)) (A | ~B) & (B | ~A) >>> eliminate_implications(Equivalent(A, B, C)) (A | ~C) & (B | ~A) & (C | ~B) """ return to_nnf(expr, simplify=False) def is_literal(expr): """ Returns True if expr is a literal, else False. Examples ======== >>> from sympy import Or, Q >>> from sympy.abc import A, B >>> from sympy.logic.boolalg import is_literal >>> is_literal(A) True >>> is_literal(~A) True >>> is_literal(Q.zero(A)) True >>> is_literal(A + B) True >>> is_literal(Or(A, B)) False """ from sympy.assumptions import AppliedPredicate if isinstance(expr, Not): return is_literal(expr.args[0]) elif expr in (True, False) or isinstance(expr, AppliedPredicate) or expr.is_Atom: return True elif not isinstance(expr, BooleanFunction) and all( (isinstance(expr, AppliedPredicate) or a.is_Atom) for a in expr.args): return True return False def to_int_repr(clauses, symbols): """ Takes clauses in CNF format and puts them into an integer representation. Examples ======== >>> from sympy.logic.boolalg import to_int_repr >>> from sympy.abc import x, y >>> to_int_repr([x | y, y], [x, y]) == [{1, 2}, {2}] True """ # Convert the symbol list into a dict symbols = dict(zip(symbols, range(1, len(symbols) + 1))) def append_symbol(arg, symbols): if isinstance(arg, Not): return -symbols[arg.args[0]] else: return symbols[arg] return [{append_symbol(arg, symbols) for arg in Or.make_args(c)} for c in clauses] def term_to_integer(term): """ Return an integer corresponding to the base-2 digits given by *term*. Parameters ========== term : a string or list of ones and zeros Examples ======== >>> from sympy.logic.boolalg import term_to_integer >>> term_to_integer([1, 0, 0]) 4 >>> term_to_integer('100') 4 """ return int(''.join(list(map(str, list(term)))), 2) integer_to_term = ibin # XXX could delete? def truth_table(expr, variables, input=True): """ Return a generator of all possible configurations of the input variables, and the result of the boolean expression for those values. Parameters ========== expr : Boolean expression variables : list of variables input : bool (default ``True``) Indicates whether to return the input combinations. Examples ======== >>> from sympy.logic.boolalg import truth_table >>> from sympy.abc import x,y >>> table = truth_table(x >> y, [x, y]) >>> for t in table: ... print('{0} -> {1}'.format(*t)) [0, 0] -> True [0, 1] -> True [1, 0] -> False [1, 1] -> True >>> table = truth_table(x | y, [x, y]) >>> list(table) [([0, 0], False), ([0, 1], True), ([1, 0], True), ([1, 1], True)] If ``input`` is ``False``, ``truth_table`` returns only a list of truth values. In this case, the corresponding input values of variables can be deduced from the index of a given output. >>> from sympy.utilities.iterables import ibin >>> vars = [y, x] >>> values = truth_table(x >> y, vars, input=False) >>> values = list(values) >>> values [True, False, True, True] >>> for i, value in enumerate(values): ... print('{0} -> {1}'.format(list(zip( ... vars, ibin(i, len(vars)))), value)) [(y, 0), (x, 0)] -> True [(y, 0), (x, 1)] -> False [(y, 1), (x, 0)] -> True [(y, 1), (x, 1)] -> True """ variables = [sympify(v) for v in variables] expr = sympify(expr) if not isinstance(expr, BooleanFunction) and not is_literal(expr): return table = product((0, 1), repeat=len(variables)) for term in table: value = expr.xreplace(dict(zip(variables, term))) if input: yield list(term), value else: yield value def _check_pair(minterm1, minterm2): """ Checks if a pair of minterms differs by only one bit. If yes, returns index, else returns `-1`. """ # Early termination seems to be faster than list comprehension, # at least for large examples. index = -1 for x, i in enumerate(minterm1): # zip(minterm1, minterm2) is slower if i != minterm2[x]: if index == -1: index = x else: return -1 return index def _convert_to_varsSOP(minterm, variables): """ Converts a term in the expansion of a function from binary to its variable form (for SOP). """ temp = [variables[n] if val == 1 else Not(variables[n]) for n, val in enumerate(minterm) if val != 3] return And(*temp) def _convert_to_varsPOS(maxterm, variables): """ Converts a term in the expansion of a function from binary to its variable form (for POS). """ temp = [variables[n] if val == 0 else Not(variables[n]) for n, val in enumerate(maxterm) if val != 3] return Or(*temp) def _convert_to_varsANF(term, variables): """ Converts a term in the expansion of a function from binary to its variable form (for ANF). Parameters ========== term : list of 1's and 0's (complementation patter) variables : list of variables """ temp = [variables[n] for n, t in enumerate(term) if t == 1] if not temp: return true return And(*temp) def _get_odd_parity_terms(n): """ Returns a list of lists, with all possible combinations of n zeros and ones with an odd number of ones. """ return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 1] def _get_even_parity_terms(n): """ Returns a list of lists, with all possible combinations of n zeros and ones with an even number of ones. """ return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 0] def _simplified_pairs(terms): """ Reduces a set of minterms, if possible, to a simplified set of minterms with one less variable in the terms using QM method. """ if not terms: return [] simplified_terms = [] todo = list(range(len(terms))) # Count number of ones as _check_pair can only potentially match if there # is at most a difference of a single one termdict = defaultdict(list) for n, term in enumerate(terms): ones = sum([1 for t in term if t == 1]) termdict[ones].append(n) variables = len(terms[0]) for k in range(variables): for i in termdict[k]: for j in termdict[k+1]: index = _check_pair(terms[i], terms[j]) if index != -1: # Mark terms handled todo[i] = todo[j] = None # Copy old term newterm = terms[i][:] # Set differing position to don't care newterm[index] = 3 # Add if not already there if newterm not in simplified_terms: simplified_terms.append(newterm) if simplified_terms: # Further simplifications only among the new terms simplified_terms = _simplified_pairs(simplified_terms) # Add remaining, non-simplified, terms simplified_terms.extend([terms[i] for i in todo if i is not None]) return simplified_terms def _rem_redundancy(l1, terms): """ After the truth table has been sufficiently simplified, use the prime implicant table method to recognize and eliminate redundant pairs, and return the essential arguments. """ if not terms: return [] nterms = len(terms) nl1 = len(l1) # Create dominating matrix dommatrix = [[0]*nl1 for n in range(nterms)] colcount = [0]*nl1 rowcount = [0]*nterms for primei, prime in enumerate(l1): for termi, term in enumerate(terms): # Check prime implicant covering term if all(t == 3 or t == mt for t, mt in zip(prime, term)): dommatrix[termi][primei] = 1 colcount[primei] += 1 rowcount[termi] += 1 # Keep track if anything changed anythingchanged = True # Then, go again while anythingchanged: anythingchanged = False for rowi in range(nterms): # Still non-dominated? if rowcount[rowi]: row = dommatrix[rowi] for row2i in range(nterms): # Still non-dominated? if rowi != row2i and rowcount[rowi] and (rowcount[rowi] <= rowcount[row2i]): row2 = dommatrix[row2i] if all(row2[n] >= row[n] for n in range(nl1)): # row2 dominating row, remove row2 rowcount[row2i] = 0 anythingchanged = True for primei, prime in enumerate(row2): if prime: # Make corresponding entry 0 dommatrix[row2i][primei] = 0 colcount[primei] -= 1 colcache = {} for coli in range(nl1): # Still non-dominated? if colcount[coli]: if coli in colcache: col = colcache[coli] else: col = [dommatrix[i][coli] for i in range(nterms)] colcache[coli] = col for col2i in range(nl1): # Still non-dominated? if coli != col2i and colcount[col2i] and (colcount[coli] >= colcount[col2i]): if col2i in colcache: col2 = colcache[col2i] else: col2 = [dommatrix[i][col2i] for i in range(nterms)] colcache[col2i] = col2 if all(col[n] >= col2[n] for n in range(nterms)): # col dominating col2, remove col2 colcount[col2i] = 0 anythingchanged = True for termi, term in enumerate(col2): if term and dommatrix[termi][col2i]: # Make corresponding entry 0 dommatrix[termi][col2i] = 0 rowcount[termi] -= 1 if not anythingchanged: # Heuristically select the prime implicant covering most terms maxterms = 0 bestcolidx = -1 for coli in range(nl1): s = colcount[coli] if s > maxterms: bestcolidx = coli maxterms = s # In case we found a prime implicant covering at least two terms if bestcolidx != -1 and maxterms > 1: for primei, prime in enumerate(l1): if primei != bestcolidx: for termi, term in enumerate(colcache[bestcolidx]): if term and dommatrix[termi][primei]: # Make corresponding entry 0 dommatrix[termi][primei] = 0 anythingchanged = True rowcount[termi] -= 1 colcount[primei] -= 1 return [l1[i] for i in range(nl1) if colcount[i]] def _input_to_binlist(inputlist, variables): binlist = [] bits = len(variables) for val in inputlist: if isinstance(val, int): binlist.append(ibin(val, bits)) elif isinstance(val, dict): nonspecvars = list(variables) for key in val.keys(): nonspecvars.remove(key) for t in product((0, 1), repeat=len(nonspecvars)): d = dict(zip(nonspecvars, t)) d.update(val) binlist.append([d[v] for v in variables]) elif isinstance(val, (list, tuple)): if len(val) != bits: raise ValueError("Each term must contain {bits} bits as there are" "\n{bits} variables (or be an integer)." "".format(bits=bits)) binlist.append(list(val)) else: raise TypeError("A term list can only contain lists," " ints or dicts.") return binlist def SOPform(variables, minterms, dontcares=None): """ The SOPform function uses simplified_pairs and a redundant group- eliminating algorithm to convert the list of all input combos that generate '1' (the minterms) into the smallest sum-of-products form. The variables must be given as the first argument. Return a logical :py:class:`~.Or` function (i.e., the "sum of products" or "SOP" form) that gives the desired outcome. If there are inputs that can be ignored, pass them as a list, too. The result will be one of the (perhaps many) functions that satisfy the conditions. Examples ======== >>> from sympy.logic import SOPform >>> from sympy import symbols >>> w, x, y, z = symbols('w x y z') >>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], ... [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]] >>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]] >>> SOPform([w, x, y, z], minterms, dontcares) (y & z) | (~w & ~x) The terms can also be represented as integers: >>> minterms = [1, 3, 7, 11, 15] >>> dontcares = [0, 2, 5] >>> SOPform([w, x, y, z], minterms, dontcares) (y & z) | (~w & ~x) They can also be specified using dicts, which does not have to be fully specified: >>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}] >>> SOPform([w, x, y, z], minterms) (x & ~w) | (y & z & ~x) Or a combination: >>> minterms = [4, 7, 11, [1, 1, 1, 1]] >>> dontcares = [{w : 0, x : 0, y: 0}, 5] >>> SOPform([w, x, y, z], minterms, dontcares) (w & y & z) | (~w & ~y) | (x & z & ~w) See also ======== POSform References ========== .. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm .. [2] https://en.wikipedia.org/wiki/Don%27t-care_term """ if not minterms: return false variables = tuple(map(sympify, variables)) minterms = _input_to_binlist(minterms, variables) dontcares = _input_to_binlist((dontcares or []), variables) for d in dontcares: if d in minterms: raise ValueError('%s in minterms is also in dontcares' % d) return _sop_form(variables, minterms, dontcares) def _sop_form(variables, minterms, dontcares): new = _simplified_pairs(minterms + dontcares) essential = _rem_redundancy(new, minterms) return Or(*[_convert_to_varsSOP(x, variables) for x in essential]) def POSform(variables, minterms, dontcares=None): """ The POSform function uses simplified_pairs and a redundant-group eliminating algorithm to convert the list of all input combinations that generate '1' (the minterms) into the smallest product-of-sums form. The variables must be given as the first argument. Return a logical :py:class:`~.And` function (i.e., the "product of sums" or "POS" form) that gives the desired outcome. If there are inputs that can be ignored, pass them as a list, too. The result will be one of the (perhaps many) functions that satisfy the conditions. Examples ======== >>> from sympy.logic import POSform >>> from sympy import symbols >>> w, x, y, z = symbols('w x y z') >>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], ... [1, 0, 1, 1], [1, 1, 1, 1]] >>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]] >>> POSform([w, x, y, z], minterms, dontcares) z & (y | ~w) The terms can also be represented as integers: >>> minterms = [1, 3, 7, 11, 15] >>> dontcares = [0, 2, 5] >>> POSform([w, x, y, z], minterms, dontcares) z & (y | ~w) They can also be specified using dicts, which does not have to be fully specified: >>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}] >>> POSform([w, x, y, z], minterms) (x | y) & (x | z) & (~w | ~x) Or a combination: >>> minterms = [4, 7, 11, [1, 1, 1, 1]] >>> dontcares = [{w : 0, x : 0, y: 0}, 5] >>> POSform([w, x, y, z], minterms, dontcares) (w | x) & (y | ~w) & (z | ~y) See also ======== SOPform References ========== .. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm .. [2] https://en.wikipedia.org/wiki/Don%27t-care_term """ if not minterms: return false variables = tuple(map(sympify, variables)) minterms = _input_to_binlist(minterms, variables) dontcares = _input_to_binlist((dontcares or []), variables) for d in dontcares: if d in minterms: raise ValueError('%s in minterms is also in dontcares' % d) maxterms = [] for t in product((0, 1), repeat=len(variables)): t = list(t) if (t not in minterms) and (t not in dontcares): maxterms.append(t) new = _simplified_pairs(maxterms + dontcares) essential = _rem_redundancy(new, maxterms) return And(*[_convert_to_varsPOS(x, variables) for x in essential]) def ANFform(variables, truthvalues): """ The ANFform function converts the list of truth values to Algebraic Normal Form (ANF). The variables must be given as the first argument. Return True, False, logical :py:class:`~.And` funciton (i.e., the "Zhegalkin monomial") or logical :py:class:`~.Xor` function (i.e., the "Zhegalkin polynomial"). When True and False are represented by 1 and 0, respectively, then :py:class:`~.And` is multiplication and :py:class:`~.Xor` is addition. Formally a "Zhegalkin monomial" is the product (logical And) of a finite set of distinct variables, including the empty set whose product is denoted 1 (True). A "Zhegalkin polynomial" is the sum (logical Xor) of a set of Zhegalkin monomials, with the empty set denoted by 0 (False). Parameters ========== variables : list of variables truthvalues : list of 1's and 0's (result column of truth table) Examples ======== >>> from sympy.logic.boolalg import ANFform >>> from sympy.abc import x, y >>> ANFform([x], [1, 0]) x ^ True >>> ANFform([x, y], [0, 1, 1, 1]) x ^ y ^ (x & y) References ========== .. [1] https://en.wikipedia.org/wiki/Zhegalkin_polynomial """ n_vars = len(variables) n_values = len(truthvalues) if n_values != 2 ** n_vars: raise ValueError("The number of truth values must be equal to 2^%d, " "got %d" % (n_vars, n_values)) variables = tuple(map(sympify, variables)) coeffs = anf_coeffs(truthvalues) terms = [] for i, t in enumerate(product((0, 1), repeat=n_vars)): if coeffs[i] == 1: terms.append(t) return Xor(*[_convert_to_varsANF(x, variables) for x in terms], remove_true=False) def anf_coeffs(truthvalues): """ Convert a list of truth values of some boolean expression to the list of coefficients of the polynomial mod 2 (exclusive disjunction) representing the boolean expression in ANF (i.e., the "Zhegalkin polynomial"). There are `2^n` possible Zhegalkin monomials in `n` variables, since each monomial is fully specified by the presence or absence of each variable. We can enumerate all the monomials. For example, boolean function with four variables ``(a, b, c, d)`` can contain up to `2^4 = 16` monomials. The 13-th monomial is the product ``a & b & d``, because 13 in binary is 1, 1, 0, 1. A given monomial's presence or absence in a polynomial corresponds to that monomial's coefficient being 1 or 0 respectively. Examples ======== >>> from sympy.logic.boolalg import anf_coeffs, bool_monomial, Xor >>> from sympy.abc import a, b, c >>> truthvalues = [0, 1, 1, 0, 0, 1, 0, 1] >>> coeffs = anf_coeffs(truthvalues) >>> coeffs [0, 1, 1, 0, 0, 0, 1, 0] >>> polynomial = Xor(*[ ... bool_monomial(k, [a, b, c]) ... for k, coeff in enumerate(coeffs) if coeff == 1 ... ]) >>> polynomial b ^ c ^ (a & b) """ s = '{:b}'.format(len(truthvalues)) n = len(s) - 1 if len(truthvalues) != 2**n: raise ValueError("The number of truth values must be a power of two, " "got %d" % len(truthvalues)) coeffs = [[v] for v in truthvalues] for i in range(n): tmp = [] for j in range(2 ** (n-i-1)): tmp.append(coeffs[2*j] + list(map(lambda x, y: x^y, coeffs[2*j], coeffs[2*j+1]))) coeffs = tmp return coeffs[0] def bool_minterm(k, variables): """ Return the k-th minterm. Minterms are numbered by a binary encoding of the complementation pattern of the variables. This convention assigns the value 1 to the direct form and 0 to the complemented form. Parameters ========== k : int or list of 1's and 0's (complementation patter) variables : list of variables Examples ======== >>> from sympy.logic.boolalg import bool_minterm >>> from sympy.abc import x, y, z >>> bool_minterm([1, 0, 1], [x, y, z]) x & z & ~y >>> bool_minterm(6, [x, y, z]) x & y & ~z References ========== .. [1] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_minterms """ if isinstance(k, int): k = ibin(k, len(variables)) variables = tuple(map(sympify, variables)) return _convert_to_varsSOP(k, variables) def bool_maxterm(k, variables): """ Return the k-th maxterm. Each maxterm is assigned an index based on the opposite conventional binary encoding used for minterms. The maxterm convention assigns the value 0 to the direct form and 1 to the complemented form. Parameters ========== k : int or list of 1's and 0's (complementation pattern) variables : list of variables Examples ======== >>> from sympy.logic.boolalg import bool_maxterm >>> from sympy.abc import x, y, z >>> bool_maxterm([1, 0, 1], [x, y, z]) y | ~x | ~z >>> bool_maxterm(6, [x, y, z]) z | ~x | ~y References ========== .. [1] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_maxterms """ if isinstance(k, int): k = ibin(k, len(variables)) variables = tuple(map(sympify, variables)) return _convert_to_varsPOS(k, variables) def bool_monomial(k, variables): """ Return the k-th monomial. Monomials are numbered by a binary encoding of the presence and absences of the variables. This convention assigns the value 1 to the presence of variable and 0 to the absence of variable. Each boolean function can be uniquely represented by a Zhegalkin Polynomial (Algebraic Normal Form). The Zhegalkin Polynomial of the boolean function with `n` variables can contain up to `2^n` monomials. We can enumarate all the monomials. Each monomial is fully specified by the presence or absence of each variable. For example, boolean function with four variables ``(a, b, c, d)`` can contain up to `2^4 = 16` monomials. The 13-th monomial is the product ``a & b & d``, because 13 in binary is 1, 1, 0, 1. Parameters ========== k : int or list of 1's and 0's variables : list of variables Examples ======== >>> from sympy.logic.boolalg import bool_monomial >>> from sympy.abc import x, y, z >>> bool_monomial([1, 0, 1], [x, y, z]) x & z >>> bool_monomial(6, [x, y, z]) x & y """ if isinstance(k, int): k = ibin(k, len(variables)) variables = tuple(map(sympify, variables)) return _convert_to_varsANF(k, variables) def _find_predicates(expr): """Helper to find logical predicates in BooleanFunctions. A logical predicate is defined here as anything within a BooleanFunction that is not a BooleanFunction itself. """ if not isinstance(expr, BooleanFunction): return {expr} return set().union(*(map(_find_predicates, expr.args))) def simplify_logic(expr, form=None, deep=True, force=False, dontcare=None): """ This function simplifies a boolean function to its simplified version in SOP or POS form. The return type is an :py:class:`~.Or` or :py:class:`~.And` object in SymPy. Parameters ========== expr : Boolean expression form : string (``'cnf'`` or ``'dnf'``) or ``None`` (default). If ``'cnf'`` or ``'dnf'``, the simplest expression in the corresponding normal form is returned; if ``None``, the answer is returned according to the form with fewest args (in CNF by default). deep : bool (default ``True``) Indicates whether to recursively simplify any non-boolean functions contained within the input. force : bool (default ``False``) As the simplifications require exponential time in the number of variables, there is by default a limit on expressions with 8 variables. When the expression has more than 8 variables only symbolical simplification (controlled by ``deep``) is made. By setting ``force`` to ``True``, this limit is removed. Be aware that this can lead to very long simplification times. dontcare : Boolean expression Optimize expression under the assumption that inputs where this expression is true are don't care. This is useful in e.g. Piecewise conditions, where later conditions do not need to consider inputs that are convered by previous conditions. For example, if a previous condition is ``And(A, B)``, the simplification of expr can be made with don't cares for ``And(A, B)``. Examples ======== >>> from sympy.logic import simplify_logic >>> from sympy.abc import x, y, z >>> b = (~x & ~y & ~z) | ( ~x & ~y & z) >>> simplify_logic(b) ~x & ~y >>> simplify_logic(x | y, dontcare=y) x References ========== .. [1] https://en.wikipedia.org/wiki/Don%27t-care_term """ if form not in (None, 'cnf', 'dnf'): raise ValueError("form can be cnf or dnf only") expr = sympify(expr) # check for quick exit if form is given: right form and all args are # literal and do not involve Not if form: form_ok = False if form == 'cnf': form_ok = is_cnf(expr) elif form == 'dnf': form_ok = is_dnf(expr) if form_ok and all(is_literal(a) for a in expr.args): return expr from sympy.core.relational import Relational if deep: variables = expr.atoms(Relational) from sympy.simplify.simplify import simplify s = tuple(map(simplify, variables)) expr = expr.xreplace(dict(zip(variables, s))) if not isinstance(expr, BooleanFunction): return expr # Replace Relationals with Dummys to possibly # reduce the number of variables repl = {} undo = {} from sympy.core.symbol import Dummy variables = expr.atoms(Relational) if dontcare is not None: dontcare = sympify(dontcare) variables.update(dontcare.atoms(Relational)) while variables: var = variables.pop() if var.is_Relational: d = Dummy() undo[d] = var repl[var] = d nvar = var.negated if nvar in variables: repl[nvar] = Not(d) variables.remove(nvar) expr = expr.xreplace(repl) if dontcare is not None: dontcare = dontcare.xreplace(repl) # Get new variables after replacing variables = _find_predicates(expr) if not force and len(variables) > 8: return expr.xreplace(undo) if dontcare is not None: # Add variables from dontcare dcvariables = _find_predicates(dontcare) variables.update(dcvariables) # if too many restore to variables only if not force and len(variables) > 8: variables = _find_predicates(expr) dontcare = None # group into constants and variable values c, v = sift(ordered(variables), lambda x: x in (True, False), binary=True) variables = c + v # standardize constants to be 1 or 0 in keeping with truthtable c = [1 if i == True else 0 for i in c] truthtable = _get_truthtable(v, expr, c) if dontcare is not None: dctruthtable = _get_truthtable(v, dontcare, c) truthtable = [t for t in truthtable if t not in dctruthtable] else: dctruthtable = [] big = len(truthtable) >= (2 ** (len(variables) - 1)) if form == 'dnf' or form is None and big: return _sop_form(variables, truthtable, dctruthtable).xreplace(undo) return POSform(variables, truthtable, dctruthtable).xreplace(undo) def _get_truthtable(variables, expr, const): """ Return a list of all combinations leading to a True result for ``expr``. """ _variables = variables.copy() def _get_tt(inputs): if _variables: v = _variables.pop() tab = [[i[0].xreplace({v: false}), [0] + i[1]] for i in inputs if i[0] is not false] tab.extend([[i[0].xreplace({v: true}), [1] + i[1]] for i in inputs if i[0] is not false]) return _get_tt(tab) return inputs res = [const + k[1] for k in _get_tt([[expr, []]]) if k[0]] if res == [[]]: return [] else: return res def _finger(eq): """ Assign a 5-item fingerprint to each symbol in the equation: [ # of times it appeared as a Symbol; # of times it appeared as a Not(symbol); # of times it appeared as a Symbol in an And or Or; # of times it appeared as a Not(Symbol) in an And or Or; a sorted tuple of tuples, (i, j, k), where i is the number of arguments in an And or Or with which it appeared as a Symbol, and j is the number of arguments that were Not(Symbol); k is the number of times that (i, j) was seen. ] Examples ======== >>> from sympy.logic.boolalg import _finger as finger >>> from sympy import And, Or, Not, Xor, to_cnf, symbols >>> from sympy.abc import a, b, x, y >>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y)) >>> dict(finger(eq)) {(0, 0, 1, 0, ((2, 0, 1),)): [x], (0, 0, 1, 0, ((2, 1, 1),)): [a, b], (0, 0, 1, 2, ((2, 0, 1),)): [y]} >>> dict(finger(x & ~y)) {(0, 1, 0, 0, ()): [y], (1, 0, 0, 0, ()): [x]} In the following, the (5, 2, 6) means that there were 6 Or functions in which a symbol appeared as itself amongst 5 arguments in which there were also 2 negated symbols, e.g. ``(a0 | a1 | a2 | ~a3 | ~a4)`` is counted once for a0, a1 and a2. >>> dict(finger(to_cnf(Xor(*symbols('a:5'))))) {(0, 0, 8, 8, ((5, 0, 1), (5, 2, 6), (5, 4, 1))): [a0, a1, a2, a3, a4]} The equation must not have more than one level of nesting: >>> dict(finger(And(Or(x, y), y))) {(0, 0, 1, 0, ((2, 0, 1),)): [x], (1, 0, 1, 0, ((2, 0, 1),)): [y]} >>> dict(finger(And(Or(x, And(a, x)), y))) Traceback (most recent call last): ... NotImplementedError: unexpected level of nesting So y and x have unique fingerprints, but a and b do not. """ f = eq.free_symbols d = dict(list(zip(f, [[0]*4 + [defaultdict(int)] for fi in f]))) for a in eq.args: if a.is_Symbol: d[a][0] += 1 elif a.is_Not: d[a.args[0]][1] += 1 else: o = len(a.args), sum(isinstance(ai, Not) for ai in a.args) for ai in a.args: if ai.is_Symbol: d[ai][2] += 1 d[ai][-1][o] += 1 elif ai.is_Not: d[ai.args[0]][3] += 1 else: raise NotImplementedError('unexpected level of nesting') inv = defaultdict(list) for k, v in ordered(iter(d.items())): v[-1] = tuple(sorted([i + (j,) for i, j in v[-1].items()])) inv[tuple(v)].append(k) return inv def bool_map(bool1, bool2): """ Return the simplified version of *bool1*, and the mapping of variables that makes the two expressions *bool1* and *bool2* represent the same logical behaviour for some correspondence between the variables of each. If more than one mappings of this sort exist, one of them is returned. For example, ``And(x, y)`` is logically equivalent to ``And(a, b)`` for the mapping ``{x: a, y: b}`` or ``{x: b, y: a}``. If no such mapping exists, return ``False``. Examples ======== >>> from sympy import SOPform, bool_map, Or, And, Not, Xor >>> from sympy.abc import w, x, y, z, a, b, c, d >>> function1 = SOPform([x, z, y],[[1, 0, 1], [0, 0, 1]]) >>> function2 = SOPform([a, b, c],[[1, 0, 1], [1, 0, 0]]) >>> bool_map(function1, function2) (y & ~z, {y: a, z: b}) The results are not necessarily unique, but they are canonical. Here, ``(w, z)`` could be ``(a, d)`` or ``(d, a)``: >>> eq = Or(And(Not(y), w), And(Not(y), z), And(x, y)) >>> eq2 = Or(And(Not(c), a), And(Not(c), d), And(b, c)) >>> bool_map(eq, eq2) ((x & y) | (w & ~y) | (z & ~y), {w: a, x: b, y: c, z: d}) >>> eq = And(Xor(a, b), c, And(c,d)) >>> bool_map(eq, eq.subs(c, x)) (c & d & (a | b) & (~a | ~b), {a: a, b: b, c: d, d: x}) """ def match(function1, function2): """Return the mapping that equates variables between two simplified boolean expressions if possible. By "simplified" we mean that a function has been denested and is either an And (or an Or) whose arguments are either symbols (x), negated symbols (Not(x)), or Or (or an And) whose arguments are only symbols or negated symbols. For example, ``And(x, Not(y), Or(w, Not(z)))``. Basic.match is not robust enough (see issue 4835) so this is a workaround that is valid for simplified boolean expressions """ # do some quick checks if function1.__class__ != function2.__class__: return None # maybe simplification makes them the same? if len(function1.args) != len(function2.args): return None # maybe simplification makes them the same? if function1.is_Symbol: return {function1: function2} # get the fingerprint dictionaries f1 = _finger(function1) f2 = _finger(function2) # more quick checks if len(f1) != len(f2): return False # assemble the match dictionary if possible matchdict = {} for k in f1.keys(): if k not in f2: return False if len(f1[k]) != len(f2[k]): return False for i, x in enumerate(f1[k]): matchdict[x] = f2[k][i] return matchdict a = simplify_logic(bool1) b = simplify_logic(bool2) m = match(a, b) if m: return a, m return m def _apply_patternbased_simplification(rv, patterns, measure, dominatingvalue, replacementvalue=None, threeterm_patterns=None): """ Replace patterns of Relational Parameters ========== rv : Expr Boolean expression patterns : tuple Tuple of tuples, with (pattern to simplify, simplified pattern) with two terms. measure : function Simplification measure. dominatingvalue : Boolean or ``None`` The dominating value for the function of consideration. For example, for :py:class:`~.And` ``S.false`` is dominating. As soon as one expression is ``S.false`` in :py:class:`~.And`, the whole expression is ``S.false``. replacementvalue : Boolean or ``None``, optional The resulting value for the whole expression if one argument evaluates to ``dominatingvalue``. For example, for :py:class:`~.Nand` ``S.false`` is dominating, but in this case the resulting value is ``S.true``. Default is ``None``. If ``replacementvalue`` is ``None`` and ``dominatingvalue`` is not ``None``, ``replacementvalue = dominatingvalue``. threeterm_patterns : tuple, optional Tuple of tuples, with (pattern to simplify, simplified pattern) with three terms. """ from sympy.core.relational import Relational, _canonical if replacementvalue is None and dominatingvalue is not None: replacementvalue = dominatingvalue # Use replacement patterns for Relationals Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational), binary=True) if len(Rel) <= 1: return rv Rel, nonRealRel = sift(Rel, lambda i: not any(s.is_real is False for s in i.free_symbols), binary=True) Rel = [i.canonical for i in Rel] if threeterm_patterns and len(Rel) >= 3: Rel = _apply_patternbased_threeterm_simplification(Rel, threeterm_patterns, rv.func, dominatingvalue, replacementvalue, measure) Rel = _apply_patternbased_twoterm_simplification(Rel, patterns, rv.func, dominatingvalue, replacementvalue, measure) rv = rv.func(*([_canonical(i) for i in ordered(Rel)] + nonRel + nonRealRel)) return rv def _apply_patternbased_twoterm_simplification(Rel, patterns, func, dominatingvalue, replacementvalue, measure): """ Apply pattern-based two-term simplification.""" from sympy.functions.elementary.miscellaneous import Min, Max from sympy.core.relational import Ge, Gt, _Inequality changed = True while changed and len(Rel) >= 2: changed = False # Use only < or <= Rel = [r.reversed if isinstance(r, (Ge, Gt)) else r for r in Rel] # Sort based on ordered Rel = list(ordered(Rel)) # Eq and Ne must be tested reversed as well rtmp = [(r, ) if isinstance(r, _Inequality) else (r, r.reversed) for r in Rel] # Create a list of possible replacements results = [] # Try all combinations of possibly reversed relational for ((i, pi), (j, pj)) in combinations(enumerate(rtmp), 2): for pattern, simp in patterns: res = [] for p1, p2 in product(pi, pj): # use SymPy matching oldexpr = Tuple(p1, p2) tmpres = oldexpr.match(pattern) if tmpres: res.append((tmpres, oldexpr)) if res: for tmpres, oldexpr in res: # we have a matching, compute replacement np = simp.xreplace(tmpres) if np == dominatingvalue: # if dominatingvalue, the whole expression # will be replacementvalue return [replacementvalue] # add replacement if not isinstance(np, ITE) and not np.has(Min, Max): # We only want to use ITE and Min/Max replacements if # they simplify to a relational costsaving = measure(func(*oldexpr.args)) - measure(np) if costsaving > 0: results.append((costsaving, ([i, j], np))) if results: # Sort results based on complexity results = list(reversed(sorted(results, key=lambda pair: pair[0]))) # Replace the one providing most simplification replacement = results[0][1] idx, newrel = replacement idx.sort() # Remove the old relationals for index in reversed(idx): del Rel[index] if dominatingvalue is None or newrel != Not(dominatingvalue): # Insert the new one (no need to insert a value that will # not affect the result) if newrel.func == func: for a in newrel.args: Rel.append(a) else: Rel.append(newrel) # We did change something so try again changed = True return Rel def _apply_patternbased_threeterm_simplification(Rel, patterns, func, dominatingvalue, replacementvalue, measure): """ Apply pattern-based three-term simplification.""" from sympy.functions.elementary.miscellaneous import Min, Max from sympy.core.relational import Le, Lt, _Inequality changed = True while changed and len(Rel) >= 3: changed = False # Use only > or >= Rel = [r.reversed if isinstance(r, (Le, Lt)) else r for r in Rel] # Sort based on ordered Rel = list(ordered(Rel)) # Create a list of possible replacements results = [] # Eq and Ne must be tested reversed as well rtmp = [(r, ) if isinstance(r, _Inequality) else (r, r.reversed) for r in Rel] # Try all combinations of possibly reversed relational for ((i, pi), (j, pj), (k, pk)) in permutations(enumerate(rtmp), 3): for pattern, simp in patterns: res = [] for p1, p2, p3 in product(pi, pj, pk): # use SymPy matching oldexpr = Tuple(p1, p2, p3) tmpres = oldexpr.match(pattern) if tmpres: res.append((tmpres, oldexpr)) if res: for tmpres, oldexpr in res: # we have a matching, compute replacement np = simp.xreplace(tmpres) if np == dominatingvalue: # if dominatingvalue, the whole expression # will be replacementvalue return [replacementvalue] # add replacement if not isinstance(np, ITE) and not np.has(Min, Max): # We only want to use ITE and Min/Max replacements if # they simplify to a relational costsaving = measure(func(*oldexpr.args)) - measure(np) if costsaving > 0: results.append((costsaving, ([i, j, k], np))) if results: # Sort results based on complexity results = list(reversed(sorted(results, key=lambda pair: pair[0]))) # Replace the one providing most simplification replacement = results[0][1] idx, newrel = replacement idx.sort() # Remove the old relationals for index in reversed(idx): del Rel[index] if dominatingvalue is None or newrel != Not(dominatingvalue): # Insert the new one (no need to insert a value that will # not affect the result) if newrel.func == func: for a in newrel.args: Rel.append(a) else: Rel.append(newrel) # We did change something so try again changed = True return Rel @cacheit def _simplify_patterns_and(): """ Two-term patterns for And.""" from sympy.core import Wild from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import Min, Max a = Wild('a') b = Wild('b') c = Wild('c') # Relationals patterns should be in alphabetical order # (pattern1, pattern2, simplified) # Do not use Ge, Gt _matchers_and = ((Tuple(Eq(a, b), Lt(a, b)), false), #(Tuple(Eq(a, b), Lt(b, a)), S.false), #(Tuple(Le(b, a), Lt(a, b)), S.false), #(Tuple(Lt(b, a), Le(a, b)), S.false), (Tuple(Lt(b, a), Lt(a, b)), false), (Tuple(Eq(a, b), Le(b, a)), Eq(a, b)), #(Tuple(Eq(a, b), Le(a, b)), Eq(a, b)), #(Tuple(Le(b, a), Lt(b, a)), Gt(a, b)), (Tuple(Le(b, a), Le(a, b)), Eq(a, b)), #(Tuple(Le(b, a), Ne(a, b)), Gt(a, b)), #(Tuple(Lt(b, a), Ne(a, b)), Gt(a, b)), (Tuple(Le(a, b), Lt(a, b)), Lt(a, b)), (Tuple(Le(a, b), Ne(a, b)), Lt(a, b)), (Tuple(Lt(a, b), Ne(a, b)), Lt(a, b)), # Sign (Tuple(Eq(a, b), Eq(a, -b)), And(Eq(a, S.Zero), Eq(b, S.Zero))), # Min/Max/ITE (Tuple(Le(b, a), Le(c, a)), Ge(a, Max(b, c))), (Tuple(Le(b, a), Lt(c, a)), ITE(b > c, Ge(a, b), Gt(a, c))), (Tuple(Lt(b, a), Lt(c, a)), Gt(a, Max(b, c))), (Tuple(Le(a, b), Le(a, c)), Le(a, Min(b, c))), (Tuple(Le(a, b), Lt(a, c)), ITE(b < c, Le(a, b), Lt(a, c))), (Tuple(Lt(a, b), Lt(a, c)), Lt(a, Min(b, c))), (Tuple(Le(a, b), Le(c, a)), ITE(Eq(b, c), Eq(a, b), ITE(b < c, false, And(Le(a, b), Ge(a, c))))), (Tuple(Le(c, a), Le(a, b)), ITE(Eq(b, c), Eq(a, b), ITE(b < c, false, And(Le(a, b), Ge(a, c))))), (Tuple(Lt(a, b), Lt(c, a)), ITE(b < c, false, And(Lt(a, b), Gt(a, c)))), (Tuple(Lt(c, a), Lt(a, b)), ITE(b < c, false, And(Lt(a, b), Gt(a, c)))), (Tuple(Le(a, b), Lt(c, a)), ITE(b <= c, false, And(Le(a, b), Gt(a, c)))), (Tuple(Le(c, a), Lt(a, b)), ITE(b <= c, false, And(Lt(a, b), Ge(a, c)))), (Tuple(Eq(a, b), Eq(a, c)), ITE(Eq(b, c), Eq(a, b), false)), (Tuple(Lt(a, b), Lt(-b, a)), ITE(b > 0, Lt(Abs(a), b), false)), (Tuple(Le(a, b), Le(-b, a)), ITE(b >= 0, Le(Abs(a), b), false)), ) return _matchers_and @cacheit def _simplify_patterns_and3(): """ Three-term patterns for And.""" from sympy.core import Wild from sympy.core.relational import Eq, Ge, Gt a = Wild('a') b = Wild('b') c = Wild('c') # Relationals patterns should be in alphabetical order # (pattern1, pattern2, pattern3, simplified) # Do not use Le, Lt _matchers_and = ((Tuple(Ge(a, b), Ge(b, c), Gt(c, a)), false), (Tuple(Ge(a, b), Gt(b, c), Gt(c, a)), false), (Tuple(Gt(a, b), Gt(b, c), Gt(c, a)), false), # (Tuple(Ge(c, a), Gt(a, b), Gt(b, c)), S.false), # Lower bound relations # Commented out combinations that does not simplify (Tuple(Ge(a, b), Ge(a, c), Ge(b, c)), And(Ge(a, b), Ge(b, c))), (Tuple(Ge(a, b), Ge(a, c), Gt(b, c)), And(Ge(a, b), Gt(b, c))), # (Tuple(Ge(a, b), Gt(a, c), Ge(b, c)), And(Ge(a, b), Ge(b, c))), (Tuple(Ge(a, b), Gt(a, c), Gt(b, c)), And(Ge(a, b), Gt(b, c))), # (Tuple(Gt(a, b), Ge(a, c), Ge(b, c)), And(Gt(a, b), Ge(b, c))), (Tuple(Ge(a, c), Gt(a, b), Gt(b, c)), And(Gt(a, b), Gt(b, c))), (Tuple(Ge(b, c), Gt(a, b), Gt(a, c)), And(Gt(a, b), Ge(b, c))), (Tuple(Gt(a, b), Gt(a, c), Gt(b, c)), And(Gt(a, b), Gt(b, c))), # Upper bound relations # Commented out combinations that does not simplify (Tuple(Ge(b, a), Ge(c, a), Ge(b, c)), And(Ge(c, a), Ge(b, c))), (Tuple(Ge(b, a), Ge(c, a), Gt(b, c)), And(Ge(c, a), Gt(b, c))), # (Tuple(Ge(b, a), Gt(c, a), Ge(b, c)), And(Gt(c, a), Ge(b, c))), (Tuple(Ge(b, a), Gt(c, a), Gt(b, c)), And(Gt(c, a), Gt(b, c))), # (Tuple(Gt(b, a), Ge(c, a), Ge(b, c)), And(Ge(c, a), Ge(b, c))), (Tuple(Ge(c, a), Gt(b, a), Gt(b, c)), And(Ge(c, a), Gt(b, c))), (Tuple(Ge(b, c), Gt(b, a), Gt(c, a)), And(Gt(c, a), Ge(b, c))), (Tuple(Gt(b, a), Gt(c, a), Gt(b, c)), And(Gt(c, a), Gt(b, c))), # Circular relation (Tuple(Ge(a, b), Ge(b, c), Ge(c, a)), And(Eq(a, b), Eq(b, c))), ) return _matchers_and @cacheit def _simplify_patterns_or(): """ Two-term patterns for Or.""" from sympy.core import Wild from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import Min, Max a = Wild('a') b = Wild('b') c = Wild('c') # Relationals patterns should be in alphabetical order # (pattern1, pattern2, simplified) # Do not use Ge, Gt _matchers_or = ((Tuple(Le(b, a), Le(a, b)), true), #(Tuple(Le(b, a), Lt(a, b)), true), (Tuple(Le(b, a), Ne(a, b)), true), #(Tuple(Le(a, b), Lt(b, a)), true), #(Tuple(Le(a, b), Ne(a, b)), true), #(Tuple(Eq(a, b), Le(b, a)), Ge(a, b)), #(Tuple(Eq(a, b), Lt(b, a)), Ge(a, b)), (Tuple(Eq(a, b), Le(a, b)), Le(a, b)), (Tuple(Eq(a, b), Lt(a, b)), Le(a, b)), #(Tuple(Le(b, a), Lt(b, a)), Ge(a, b)), (Tuple(Lt(b, a), Lt(a, b)), Ne(a, b)), (Tuple(Lt(b, a), Ne(a, b)), Ne(a, b)), (Tuple(Le(a, b), Lt(a, b)), Le(a, b)), #(Tuple(Lt(a, b), Ne(a, b)), Ne(a, b)), (Tuple(Eq(a, b), Ne(a, c)), ITE(Eq(b, c), true, Ne(a, c))), (Tuple(Ne(a, b), Ne(a, c)), ITE(Eq(b, c), Ne(a, b), true)), # Min/Max/ITE (Tuple(Le(b, a), Le(c, a)), Ge(a, Min(b, c))), #(Tuple(Ge(b, a), Ge(c, a)), Ge(Min(b, c), a)), (Tuple(Le(b, a), Lt(c, a)), ITE(b > c, Lt(c, a), Le(b, a))), (Tuple(Lt(b, a), Lt(c, a)), Gt(a, Min(b, c))), #(Tuple(Gt(b, a), Gt(c, a)), Gt(Min(b, c), a)), (Tuple(Le(a, b), Le(a, c)), Le(a, Max(b, c))), #(Tuple(Le(b, a), Le(c, a)), Le(Max(b, c), a)), (Tuple(Le(a, b), Lt(a, c)), ITE(b >= c, Le(a, b), Lt(a, c))), (Tuple(Lt(a, b), Lt(a, c)), Lt(a, Max(b, c))), #(Tuple(Lt(b, a), Lt(c, a)), Lt(Max(b, c), a)), (Tuple(Le(a, b), Le(c, a)), ITE(b >= c, true, Or(Le(a, b), Ge(a, c)))), (Tuple(Le(c, a), Le(a, b)), ITE(b >= c, true, Or(Le(a, b), Ge(a, c)))), (Tuple(Lt(a, b), Lt(c, a)), ITE(b > c, true, Or(Lt(a, b), Gt(a, c)))), (Tuple(Lt(c, a), Lt(a, b)), ITE(b > c, true, Or(Lt(a, b), Gt(a, c)))), (Tuple(Le(a, b), Lt(c, a)), ITE(b >= c, true, Or(Le(a, b), Gt(a, c)))), (Tuple(Le(c, a), Lt(a, b)), ITE(b >= c, true, Or(Lt(a, b), Ge(a, c)))), (Tuple(Lt(b, a), Lt(a, -b)), ITE(b >= 0, Gt(Abs(a), b), true)), (Tuple(Le(b, a), Le(a, -b)), ITE(b > 0, Ge(Abs(a), b), true)), ) return _matchers_or @cacheit def _simplify_patterns_xor(): """ Two-term patterns for Xor.""" from sympy.functions.elementary.miscellaneous import Min, Max from sympy.core import Wild from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt a = Wild('a') b = Wild('b') c = Wild('c') # Relationals patterns should be in alphabetical order # (pattern1, pattern2, simplified) # Do not use Ge, Gt _matchers_xor = (#(Tuple(Le(b, a), Lt(a, b)), true), #(Tuple(Lt(b, a), Le(a, b)), true), #(Tuple(Eq(a, b), Le(b, a)), Gt(a, b)), #(Tuple(Eq(a, b), Lt(b, a)), Ge(a, b)), (Tuple(Eq(a, b), Le(a, b)), Lt(a, b)), (Tuple(Eq(a, b), Lt(a, b)), Le(a, b)), (Tuple(Le(a, b), Lt(a, b)), Eq(a, b)), (Tuple(Le(a, b), Le(b, a)), Ne(a, b)), (Tuple(Le(b, a), Ne(a, b)), Le(a, b)), # (Tuple(Lt(b, a), Lt(a, b)), Ne(a, b)), (Tuple(Lt(b, a), Ne(a, b)), Lt(a, b)), # (Tuple(Le(a, b), Lt(a, b)), Eq(a, b)), # (Tuple(Le(a, b), Ne(a, b)), Ge(a, b)), # (Tuple(Lt(a, b), Ne(a, b)), Gt(a, b)), # Min/Max/ITE (Tuple(Le(b, a), Le(c, a)), And(Ge(a, Min(b, c)), Lt(a, Max(b, c)))), (Tuple(Le(b, a), Lt(c, a)), ITE(b > c, And(Gt(a, c), Lt(a, b)), And(Ge(a, b), Le(a, c)))), (Tuple(Lt(b, a), Lt(c, a)), And(Gt(a, Min(b, c)), Le(a, Max(b, c)))), (Tuple(Le(a, b), Le(a, c)), And(Le(a, Max(b, c)), Gt(a, Min(b, c)))), (Tuple(Le(a, b), Lt(a, c)), ITE(b < c, And(Lt(a, c), Gt(a, b)), And(Le(a, b), Ge(a, c)))), (Tuple(Lt(a, b), Lt(a, c)), And(Lt(a, Max(b, c)), Ge(a, Min(b, c)))), ) return _matchers_xor def simplify_univariate(expr): """return a simplified version of univariate boolean expression, else ``expr``""" from sympy.functions.elementary.piecewise import Piecewise from sympy.core.relational import Eq, Ne if not isinstance(expr, BooleanFunction): return expr if expr.atoms(Eq, Ne): return expr c = expr free = c.free_symbols if len(free) != 1: return c x = free.pop() ok, i = Piecewise((0, c), evaluate=False )._intervals(x, err_on_Eq=True) if not ok: return c if not i: return false args = [] for a, b, _, _ in i: if a is S.NegativeInfinity: if b is S.Infinity: c = true else: if c.subs(x, b) == True: c = (x <= b) else: c = (x < b) else: incl_a = (c.subs(x, a) == True) incl_b = (c.subs(x, b) == True) if incl_a and incl_b: if b.is_infinite: c = (x >= a) else: c = And(a <= x, x <= b) elif incl_a: c = And(a <= x, x < b) elif incl_b: if b.is_infinite: c = (x > a) else: c = And(a < x, x <= b) else: c = And(a < x, x < b) args.append(c) return Or(*args) # Classes corresponding to logic gates # Used in gateinputcount method BooleanGates = (And, Or, Xor, Nand, Nor, Not, Xnor, ITE) def gateinputcount(expr): """ Return the total number of inputs for the logic gates realizing the Boolean expression. Returns ======= int Number of gate inputs Note ==== Not all Boolean functions count as gate here, only those that are considered to be standard gates. These are: :py:class:`~.And`, :py:class:`~.Or`, :py:class:`~.Xor`, :py:class:`~.Not`, and :py:class:`~.ITE` (multiplexer). :py:class:`~.Nand`, :py:class:`~.Nor`, and :py:class:`~.Xnor` will be evaluated to ``Not(And())`` etc. Examples ======== >>> from sympy.logic import And, Or, Nand, Not, gateinputcount >>> from sympy.abc import x, y, z >>> expr = And(x, y) >>> gateinputcount(expr) 2 >>> gateinputcount(Or(expr, z)) 4 Note that ``Nand`` is automatically evaluated to ``Not(And())`` so >>> gateinputcount(Nand(x, y, z)) 4 >>> gateinputcount(Not(And(x, y, z))) 4 Although this can be avoided by using ``evaluate=False`` >>> gateinputcount(Nand(x, y, z, evaluate=False)) 3 Also note that a comparison will count as a Boolean variable: >>> gateinputcount(And(x > z, y >= 2)) 2 As will a symbol: >>> gateinputcount(x) 0 """ if not isinstance(expr, Boolean): raise TypeError("Expression must be Boolean") if isinstance(expr, BooleanGates): return len(expr.args) + sum(gateinputcount(x) for x in expr.args) return 0
4e1fb072b1b9b1fa2ebe58bfbc41f78050e081fac67a966639eed31549e87c0a
""" Basic methods common to all matrices to be used when creating more advanced matrices (e.g., matrices over rings, etc.). """ from collections import defaultdict from collections.abc import Iterable from inspect import isfunction from functools import reduce from sympy.assumptions.refine import refine from sympy.core import SympifyError, Add from sympy.core.basic import Atom from sympy.core.decorators import call_highest_priority from sympy.core.kind import Kind, NumberKind from sympy.core.logic import fuzzy_and, FuzzyBool from sympy.core.mod import Mod from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.functions.elementary.complexes import Abs, re, im from .utilities import _dotprodsimp, _simplify from sympy.polys.polytools import Poly from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import flatten, is_sequence from sympy.utilities.misc import as_int, filldedent from sympy.tensor.array import NDimArray from .utilities import _get_intermediate_simp_bool class MatrixError(Exception): pass class ShapeError(ValueError, MatrixError): """Wrong matrix shape""" pass class NonSquareMatrixError(ShapeError): pass class NonInvertibleMatrixError(ValueError, MatrixError): """The matrix in not invertible (division by multidimensional zero error).""" pass class NonPositiveDefiniteMatrixError(ValueError, MatrixError): """The matrix is not a positive-definite matrix.""" pass class MatrixRequired: """All subclasses of matrix objects must implement the required matrix properties listed here.""" rows = None # type: int cols = None # type: int _simplify = None @classmethod def _new(cls, *args, **kwargs): """`_new` must, at minimum, be callable as `_new(rows, cols, mat) where mat is a flat list of the elements of the matrix.""" raise NotImplementedError("Subclasses must implement this.") def __eq__(self, other): raise NotImplementedError("Subclasses must implement this.") def __getitem__(self, key): """Implementations of __getitem__ should accept ints, in which case the matrix is indexed as a flat list, tuples (i,j) in which case the (i,j) entry is returned, slices, or mixed tuples (a,b) where a and b are any combination of slices and integers.""" raise NotImplementedError("Subclasses must implement this.") def __len__(self): """The total number of entries in the matrix.""" raise NotImplementedError("Subclasses must implement this.") @property def shape(self): raise NotImplementedError("Subclasses must implement this.") class MatrixShaping(MatrixRequired): """Provides basic matrix shaping and extracting of submatrices""" def _eval_col_del(self, col): def entry(i, j): return self[i, j] if j < col else self[i, j + 1] return self._new(self.rows, self.cols - 1, entry) def _eval_col_insert(self, pos, other): def entry(i, j): if j < pos: return self[i, j] elif pos <= j < pos + other.cols: return other[i, j - pos] return self[i, j - other.cols] return self._new(self.rows, self.cols + other.cols, entry) def _eval_col_join(self, other): rows = self.rows def entry(i, j): if i < rows: return self[i, j] return other[i - rows, j] return classof(self, other)._new(self.rows + other.rows, self.cols, entry) def _eval_extract(self, rowsList, colsList): mat = list(self) cols = self.cols indices = (i * cols + j for i in rowsList for j in colsList) return self._new(len(rowsList), len(colsList), list(mat[i] for i in indices)) def _eval_get_diag_blocks(self): sub_blocks = [] def recurse_sub_blocks(M): i = 1 while i <= M.shape[0]: if i == 1: to_the_right = M[0, i:] to_the_bottom = M[i:, 0] else: to_the_right = M[:i, i:] to_the_bottom = M[i:, :i] if any(to_the_right) or any(to_the_bottom): i += 1 continue else: sub_blocks.append(M[:i, :i]) if M.shape == M[:i, :i].shape: return else: recurse_sub_blocks(M[i:, i:]) return recurse_sub_blocks(self) return sub_blocks def _eval_row_del(self, row): def entry(i, j): return self[i, j] if i < row else self[i + 1, j] return self._new(self.rows - 1, self.cols, entry) def _eval_row_insert(self, pos, other): entries = list(self) insert_pos = pos * self.cols entries[insert_pos:insert_pos] = list(other) return self._new(self.rows + other.rows, self.cols, entries) def _eval_row_join(self, other): cols = self.cols def entry(i, j): if j < cols: return self[i, j] return other[i, j - cols] return classof(self, other)._new(self.rows, self.cols + other.cols, entry) def _eval_tolist(self): return [list(self[i,:]) for i in range(self.rows)] def _eval_todok(self): dok = {} rows, cols = self.shape for i in range(rows): for j in range(cols): val = self[i, j] if val != self.zero: dok[i, j] = val return dok def _eval_vec(self): rows = self.rows def entry(n, _): # we want to read off the columns first j = n // rows i = n - j * rows return self[i, j] return self._new(len(self), 1, entry) def _eval_vech(self, diagonal): c = self.cols v = [] if diagonal: for j in range(c): for i in range(j, c): v.append(self[i, j]) else: for j in range(c): for i in range(j + 1, c): v.append(self[i, j]) return self._new(len(v), 1, v) def col_del(self, col): """Delete the specified column.""" if col < 0: col += self.cols if not 0 <= col < self.cols: raise IndexError("Column {} is out of range.".format(col)) return self._eval_col_del(col) def col_insert(self, pos, other): """Insert one or more columns at the given column position. Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(3, 1) >>> M.col_insert(1, V) Matrix([ [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]]) See Also ======== col row_insert """ # Allows you to build a matrix even if it is null matrix if not self: return type(self)(other) pos = as_int(pos) if pos < 0: pos = self.cols + pos if pos < 0: pos = 0 elif pos > self.cols: pos = self.cols if self.rows != other.rows: raise ShapeError( "The matrices have incompatible number of rows ({} and {})" .format(self.rows, other.rows)) return self._eval_col_insert(pos, other) def col_join(self, other): """Concatenates two matrices along self's last and other's first row. Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(1, 3) >>> M.col_join(V) Matrix([ [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 1, 1]]) See Also ======== col row_join """ # A null matrix can always be stacked (see #10770) if self.rows == 0 and self.cols != other.cols: return self._new(0, other.cols, []).col_join(other) if self.cols != other.cols: raise ShapeError( "The matrices have incompatible number of columns ({} and {})" .format(self.cols, other.cols)) return self._eval_col_join(other) def col(self, j): """Elementary column selector. Examples ======== >>> from sympy import eye >>> eye(2).col(0) Matrix([ [1], [0]]) See Also ======== row col_del col_join col_insert """ return self[:, j] def extract(self, rowsList, colsList): r"""Return a submatrix by specifying a list of rows and columns. Negative indices can be given. All indices must be in the range $-n \le i < n$ where $n$ is the number of rows or columns. Examples ======== >>> from sympy import Matrix >>> m = Matrix(4, 3, range(12)) >>> m Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]) >>> m.extract([0, 1, 3], [0, 1]) Matrix([ [0, 1], [3, 4], [9, 10]]) Rows or columns can be repeated: >>> m.extract([0, 0, 1], [-1]) Matrix([ [2], [2], [5]]) Every other row can be taken by using range to provide the indices: >>> m.extract(range(0, m.rows, 2), [-1]) Matrix([ [2], [8]]) RowsList or colsList can also be a list of booleans, in which case the rows or columns corresponding to the True values will be selected: >>> m.extract([0, 1, 2, 3], [True, False, True]) Matrix([ [0, 2], [3, 5], [6, 8], [9, 11]]) """ if not is_sequence(rowsList) or not is_sequence(colsList): raise TypeError("rowsList and colsList must be iterable") # ensure rowsList and colsList are lists of integers if rowsList and all(isinstance(i, bool) for i in rowsList): rowsList = [index for index, item in enumerate(rowsList) if item] if colsList and all(isinstance(i, bool) for i in colsList): colsList = [index for index, item in enumerate(colsList) if item] # ensure everything is in range rowsList = [a2idx(k, self.rows) for k in rowsList] colsList = [a2idx(k, self.cols) for k in colsList] return self._eval_extract(rowsList, colsList) def get_diag_blocks(self): """Obtains the square sub-matrices on the main diagonal of a square matrix. Useful for inverting symbolic matrices or solving systems of linear equations which may be decoupled by having a block diagonal structure. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y, z >>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]]) >>> a1, a2, a3 = A.get_diag_blocks() >>> a1 Matrix([ [1, 3], [y, z**2]]) >>> a2 Matrix([[x]]) >>> a3 Matrix([[0]]) """ return self._eval_get_diag_blocks() @classmethod def hstack(cls, *args): """Return a matrix formed by joining args horizontally (i.e. by repeated application of row_join). Examples ======== >>> from sympy import Matrix, eye >>> Matrix.hstack(eye(2), 2*eye(2)) Matrix([ [1, 0, 2, 0], [0, 1, 0, 2]]) """ if len(args) == 0: return cls._new() kls = type(args[0]) return reduce(kls.row_join, args) def reshape(self, rows, cols): """Reshape the matrix. Total number of elements must remain the same. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 3, lambda i, j: 1) >>> m Matrix([ [1, 1, 1], [1, 1, 1]]) >>> m.reshape(1, 6) Matrix([[1, 1, 1, 1, 1, 1]]) >>> m.reshape(3, 2) Matrix([ [1, 1], [1, 1], [1, 1]]) """ if self.rows * self.cols != rows * cols: raise ValueError("Invalid reshape parameters %d %d" % (rows, cols)) return self._new(rows, cols, lambda i, j: self[i * cols + j]) def row_del(self, row): """Delete the specified row.""" if row < 0: row += self.rows if not 0 <= row < self.rows: raise IndexError("Row {} is out of range.".format(row)) return self._eval_row_del(row) def row_insert(self, pos, other): """Insert one or more rows at the given row position. Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(1, 3) >>> M.row_insert(1, V) Matrix([ [0, 0, 0], [1, 1, 1], [0, 0, 0], [0, 0, 0]]) See Also ======== row col_insert """ # Allows you to build a matrix even if it is null matrix if not self: return self._new(other) pos = as_int(pos) if pos < 0: pos = self.rows + pos if pos < 0: pos = 0 elif pos > self.rows: pos = self.rows if self.cols != other.cols: raise ShapeError( "The matrices have incompatible number of columns ({} and {})" .format(self.cols, other.cols)) return self._eval_row_insert(pos, other) def row_join(self, other): """Concatenates two matrices along self's last and rhs's first column Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(3, 1) >>> M.row_join(V) Matrix([ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]]) See Also ======== row col_join """ # A null matrix can always be stacked (see #10770) if self.cols == 0 and self.rows != other.rows: return self._new(other.rows, 0, []).row_join(other) if self.rows != other.rows: raise ShapeError( "The matrices have incompatible number of rows ({} and {})" .format(self.rows, other.rows)) return self._eval_row_join(other) def diagonal(self, k=0): """Returns the kth diagonal of self. The main diagonal corresponds to `k=0`; diagonals above and below correspond to `k > 0` and `k < 0`, respectively. The values of `self[i, j]` for which `j - i = k`, are returned in order of increasing `i + j`, starting with `i + j = |k|`. Examples ======== >>> from sympy import Matrix >>> m = Matrix(3, 3, lambda i, j: j - i); m Matrix([ [ 0, 1, 2], [-1, 0, 1], [-2, -1, 0]]) >>> _.diagonal() Matrix([[0, 0, 0]]) >>> m.diagonal(1) Matrix([[1, 1]]) >>> m.diagonal(-2) Matrix([[-2]]) Even though the diagonal is returned as a Matrix, the element retrieval can be done with a single index: >>> Matrix.diag(1, 2, 3).diagonal()[1] # instead of [0, 1] 2 See Also ======== diag - to create a diagonal matrix """ rv = [] k = as_int(k) r = 0 if k > 0 else -k c = 0 if r else k while True: if r == self.rows or c == self.cols: break rv.append(self[r, c]) r += 1 c += 1 if not rv: raise ValueError(filldedent(''' The %s diagonal is out of range [%s, %s]''' % ( k, 1 - self.rows, self.cols - 1))) return self._new(1, len(rv), rv) def row(self, i): """Elementary row selector. Examples ======== >>> from sympy import eye >>> eye(2).row(0) Matrix([[1, 0]]) See Also ======== col row_del row_join row_insert """ return self[i, :] @property def shape(self): """The shape (dimensions) of the matrix as the 2-tuple (rows, cols). Examples ======== >>> from sympy import zeros >>> M = zeros(2, 3) >>> M.shape (2, 3) >>> M.rows 2 >>> M.cols 3 """ return (self.rows, self.cols) def todok(self): """Return the matrix as dictionary of keys. Examples ======== >>> from sympy import Matrix >>> M = Matrix.eye(3) >>> M.todok() {(0, 0): 1, (1, 1): 1, (2, 2): 1} """ return self._eval_todok() def tolist(self): """Return the Matrix as a nested Python list. Examples ======== >>> from sympy import Matrix, ones >>> m = Matrix(3, 3, range(9)) >>> m Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> m.tolist() [[0, 1, 2], [3, 4, 5], [6, 7, 8]] >>> ones(3, 0).tolist() [[], [], []] When there are no rows then it will not be possible to tell how many columns were in the original matrix: >>> ones(0, 3).tolist() [] """ if not self.rows: return [] if not self.cols: return [[] for i in range(self.rows)] return self._eval_tolist() def todod(M): """Returns matrix as dict of dicts containing non-zero elements of the Matrix Examples ======== >>> from sympy import Matrix >>> A = Matrix([[0, 1],[0, 3]]) >>> A Matrix([ [0, 1], [0, 3]]) >>> A.todod() {0: {1: 1}, 1: {1: 3}} """ rowsdict = {} Mlol = M.tolist() for i, Mi in enumerate(Mlol): row = {j: Mij for j, Mij in enumerate(Mi) if Mij} if row: rowsdict[i] = row return rowsdict def vec(self): """Return the Matrix converted into a one column matrix by stacking columns Examples ======== >>> from sympy import Matrix >>> m=Matrix([[1, 3], [2, 4]]) >>> m Matrix([ [1, 3], [2, 4]]) >>> m.vec() Matrix([ [1], [2], [3], [4]]) See Also ======== vech """ return self._eval_vec() def vech(self, diagonal=True, check_symmetry=True): """Reshapes the matrix into a column vector by stacking the elements in the lower triangle. Parameters ========== diagonal : bool, optional If ``True``, it includes the diagonal elements. check_symmetry : bool, optional If ``True``, it checks whether the matrix is symmetric. Examples ======== >>> from sympy import Matrix >>> m=Matrix([[1, 2], [2, 3]]) >>> m Matrix([ [1, 2], [2, 3]]) >>> m.vech() Matrix([ [1], [2], [3]]) >>> m.vech(diagonal=False) Matrix([[2]]) Notes ===== This should work for symmetric matrices and ``vech`` can represent symmetric matrices in vector form with less size than ``vec``. See Also ======== vec """ if not self.is_square: raise NonSquareMatrixError if check_symmetry and not self.is_symmetric(): raise ValueError("The matrix is not symmetric.") return self._eval_vech(diagonal) @classmethod def vstack(cls, *args): """Return a matrix formed by joining args vertically (i.e. by repeated application of col_join). Examples ======== >>> from sympy import Matrix, eye >>> Matrix.vstack(eye(2), 2*eye(2)) Matrix([ [1, 0], [0, 1], [2, 0], [0, 2]]) """ if len(args) == 0: return cls._new() kls = type(args[0]) return reduce(kls.col_join, args) class MatrixSpecial(MatrixRequired): """Construction of special matrices""" @classmethod def _eval_diag(cls, rows, cols, diag_dict): """diag_dict is a defaultdict containing all the entries of the diagonal matrix.""" def entry(i, j): return diag_dict[(i, j)] return cls._new(rows, cols, entry) @classmethod def _eval_eye(cls, rows, cols): vals = [cls.zero]*(rows*cols) vals[::cols+1] = [cls.one]*min(rows, cols) return cls._new(rows, cols, vals, copy=False) @classmethod def _eval_jordan_block(cls, rows, cols, eigenvalue, band='upper'): if band == 'lower': def entry(i, j): if i == j: return eigenvalue elif j + 1 == i: return cls.one return cls.zero else: def entry(i, j): if i == j: return eigenvalue elif i + 1 == j: return cls.one return cls.zero return cls._new(rows, cols, entry) @classmethod def _eval_ones(cls, rows, cols): def entry(i, j): return cls.one return cls._new(rows, cols, entry) @classmethod def _eval_zeros(cls, rows, cols): return cls._new(rows, cols, [cls.zero]*(rows*cols), copy=False) @classmethod def _eval_wilkinson(cls, n): def entry(i, j): return cls.one if i + 1 == j else cls.zero D = cls._new(2*n + 1, 2*n + 1, entry) wminus = cls.diag([i for i in range(-n, n + 1)], unpack=True) + D + D.T wplus = abs(cls.diag([i for i in range(-n, n + 1)], unpack=True)) + D + D.T return wminus, wplus @classmethod def diag(kls, *args, strict=False, unpack=True, rows=None, cols=None, **kwargs): """Returns a matrix with the specified diagonal. If matrices are passed, a block-diagonal matrix is created (i.e. the "direct sum" of the matrices). kwargs ====== rows : rows of the resulting matrix; computed if not given. cols : columns of the resulting matrix; computed if not given. cls : class for the resulting matrix unpack : bool which, when True (default), unpacks a single sequence rather than interpreting it as a Matrix. strict : bool which, when False (default), allows Matrices to have variable-length rows. Examples ======== >>> from sympy import Matrix >>> Matrix.diag(1, 2, 3) Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) The current default is to unpack a single sequence. If this is not desired, set `unpack=False` and it will be interpreted as a matrix. >>> Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3) True When more than one element is passed, each is interpreted as something to put on the diagonal. Lists are converted to matrices. Filling of the diagonal always continues from the bottom right hand corner of the previous item: this will create a block-diagonal matrix whether the matrices are square or not. >>> col = [1, 2, 3] >>> row = [[4, 5]] >>> Matrix.diag(col, row) Matrix([ [1, 0, 0], [2, 0, 0], [3, 0, 0], [0, 4, 5]]) When `unpack` is False, elements within a list need not all be of the same length. Setting `strict` to True would raise a ValueError for the following: >>> Matrix.diag([[1, 2, 3], [4, 5], [6]], unpack=False) Matrix([ [1, 2, 3], [4, 5, 0], [6, 0, 0]]) The type of the returned matrix can be set with the ``cls`` keyword. >>> from sympy import ImmutableMatrix >>> from sympy.utilities.misc import func_name >>> func_name(Matrix.diag(1, cls=ImmutableMatrix)) 'ImmutableDenseMatrix' A zero dimension matrix can be used to position the start of the filling at the start of an arbitrary row or column: >>> from sympy import ones >>> r2 = ones(0, 2) >>> Matrix.diag(r2, 1, 2) Matrix([ [0, 0, 1, 0], [0, 0, 0, 2]]) See Also ======== eye diagonal - to extract a diagonal .dense.diag .expressions.blockmatrix.BlockMatrix .sparsetools.banded - to create multi-diagonal matrices """ from sympy.matrices.matrices import MatrixBase from sympy.matrices.dense import Matrix from sympy.matrices import SparseMatrix klass = kwargs.get('cls', kls) if unpack and len(args) == 1 and is_sequence(args[0]) and \ not isinstance(args[0], MatrixBase): args = args[0] # fill a default dict with the diagonal entries diag_entries = defaultdict(int) rmax = cmax = 0 # keep track of the biggest index seen for m in args: if isinstance(m, list): if strict: # if malformed, Matrix will raise an error _ = Matrix(m) r, c = _.shape m = _.tolist() else: r, c, smat = SparseMatrix._handle_creation_inputs(m) for (i, j), _ in smat.items(): diag_entries[(i + rmax, j + cmax)] = _ m = [] # to skip process below elif hasattr(m, 'shape'): # a Matrix # convert to list of lists r, c = m.shape m = m.tolist() else: # in this case, we're a single value diag_entries[(rmax, cmax)] = m rmax += 1 cmax += 1 continue # process list of lists for i, mi in enumerate(m): for j, _ in enumerate(mi): diag_entries[(i + rmax, j + cmax)] = _ rmax += r cmax += c if rows is None: rows, cols = cols, rows if rows is None: rows, cols = rmax, cmax else: cols = rows if cols is None else cols if rows < rmax or cols < cmax: raise ValueError(filldedent(''' The constructed matrix is {} x {} but a size of {} x {} was specified.'''.format(rmax, cmax, rows, cols))) return klass._eval_diag(rows, cols, diag_entries) @classmethod def eye(kls, rows, cols=None, **kwargs): """Returns an identity matrix. Args ==== rows : rows of the matrix cols : cols of the matrix (if None, cols=rows) kwargs ====== cls : class of the returned matrix """ if cols is None: cols = rows if rows < 0 or cols < 0: raise ValueError("Cannot create a {} x {} matrix. " "Both dimensions must be positive".format(rows, cols)) klass = kwargs.get('cls', kls) rows, cols = as_int(rows), as_int(cols) return klass._eval_eye(rows, cols) @classmethod def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs): """Returns a Jordan block Parameters ========== size : Integer, optional Specifies the shape of the Jordan block matrix. eigenvalue : Number or Symbol Specifies the value for the main diagonal of the matrix. .. note:: The keyword ``eigenval`` is also specified as an alias of this keyword, but it is not recommended to use. We may deprecate the alias in later release. band : 'upper' or 'lower', optional Specifies the position of the off-diagonal to put `1` s on. cls : Matrix, optional Specifies the matrix class of the output form. If it is not specified, the class type where the method is being executed on will be returned. rows, cols : Integer, optional Specifies the shape of the Jordan block matrix. See Notes section for the details of how these key works. .. deprecated:: 1.4 The rows and cols parameters are deprecated and will be removed in a future version. Returns ======= Matrix A Jordan block matrix. Raises ====== ValueError If insufficient arguments are given for matrix size specification, or no eigenvalue is given. Examples ======== Creating a default Jordan block: >>> from sympy import Matrix >>> from sympy.abc import x >>> Matrix.jordan_block(4, x) Matrix([ [x, 1, 0, 0], [0, x, 1, 0], [0, 0, x, 1], [0, 0, 0, x]]) Creating an alternative Jordan block matrix where `1` is on lower off-diagonal: >>> Matrix.jordan_block(4, x, band='lower') Matrix([ [x, 0, 0, 0], [1, x, 0, 0], [0, 1, x, 0], [0, 0, 1, x]]) Creating a Jordan block with keyword arguments >>> Matrix.jordan_block(size=4, eigenvalue=x) Matrix([ [x, 1, 0, 0], [0, x, 1, 0], [0, 0, x, 1], [0, 0, 0, x]]) Notes ===== .. deprecated:: 1.4 This feature is deprecated and will be removed in a future version. The keyword arguments ``size``, ``rows``, ``cols`` relates to the Jordan block size specifications. If you want to create a square Jordan block, specify either one of the three arguments. If you want to create a rectangular Jordan block, specify ``rows`` and ``cols`` individually. +--------------------------------+---------------------+ | Arguments Given | Matrix Shape | +----------+----------+----------+----------+----------+ | size | rows | cols | rows | cols | +==========+==========+==========+==========+==========+ | size | Any | size | size | +----------+----------+----------+----------+----------+ | | None | ValueError | | +----------+----------+----------+----------+ | None | rows | None | rows | rows | | +----------+----------+----------+----------+ | | None | cols | cols | cols | + +----------+----------+----------+----------+ | | rows | cols | rows | cols | +----------+----------+----------+----------+----------+ References ========== .. [1] https://en.wikipedia.org/wiki/Jordan_matrix """ if 'rows' in kwargs or 'cols' in kwargs: msg = """ The 'rows' and 'cols' keywords to Matrix.jordan_block() are deprecated. Use the 'size' parameter instead. """ if 'rows' in kwargs and 'cols' in kwargs: msg += f"""\ To get a non-square Jordan block matrix use a more generic banded matrix constructor, like def entry(i, j): if i == j: return eigenvalue elif {"i + 1 == j" if band == 'upper' else "j + 1 == i"}: return 1 return 0 Matrix({kwargs['rows']}, {kwargs['cols']}, entry) """ sympy_deprecation_warning(msg, deprecated_since_version="1.4", active_deprecations_target="deprecated-matrix-jordan_block-rows-cols") klass = kwargs.pop('cls', kls) rows = kwargs.pop('rows', None) cols = kwargs.pop('cols', None) eigenval = kwargs.get('eigenval', None) if eigenvalue is None and eigenval is None: raise ValueError("Must supply an eigenvalue") elif eigenvalue != eigenval and None not in (eigenval, eigenvalue): raise ValueError( "Inconsistent values are given: 'eigenval'={}, " "'eigenvalue'={}".format(eigenval, eigenvalue)) else: if eigenval is not None: eigenvalue = eigenval if (size, rows, cols) == (None, None, None): raise ValueError("Must supply a matrix size") if size is not None: rows, cols = size, size elif rows is not None and cols is None: cols = rows elif cols is not None and rows is None: rows = cols rows, cols = as_int(rows), as_int(cols) return klass._eval_jordan_block(rows, cols, eigenvalue, band) @classmethod def ones(kls, rows, cols=None, **kwargs): """Returns a matrix of ones. Args ==== rows : rows of the matrix cols : cols of the matrix (if None, cols=rows) kwargs ====== cls : class of the returned matrix """ if cols is None: cols = rows klass = kwargs.get('cls', kls) rows, cols = as_int(rows), as_int(cols) return klass._eval_ones(rows, cols) @classmethod def zeros(kls, rows, cols=None, **kwargs): """Returns a matrix of zeros. Args ==== rows : rows of the matrix cols : cols of the matrix (if None, cols=rows) kwargs ====== cls : class of the returned matrix """ if cols is None: cols = rows if rows < 0 or cols < 0: raise ValueError("Cannot create a {} x {} matrix. " "Both dimensions must be positive".format(rows, cols)) klass = kwargs.get('cls', kls) rows, cols = as_int(rows), as_int(cols) return klass._eval_zeros(rows, cols) @classmethod def companion(kls, poly): """Returns a companion matrix of a polynomial. Examples ======== >>> from sympy import Matrix, Poly, Symbol, symbols >>> x = Symbol('x') >>> c0, c1, c2, c3, c4 = symbols('c0:5') >>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x) >>> Matrix.companion(p) Matrix([ [0, 0, 0, 0, -c0], [1, 0, 0, 0, -c1], [0, 1, 0, 0, -c2], [0, 0, 1, 0, -c3], [0, 0, 0, 1, -c4]]) """ poly = kls._sympify(poly) if not isinstance(poly, Poly): raise ValueError("{} must be a Poly instance.".format(poly)) if not poly.is_monic: raise ValueError("{} must be a monic polynomial.".format(poly)) if not poly.is_univariate: raise ValueError( "{} must be a univariate polynomial.".format(poly)) size = poly.degree() if not size >= 1: raise ValueError( "{} must have degree not less than 1.".format(poly)) coeffs = poly.all_coeffs() def entry(i, j): if j == size - 1: return -coeffs[-1 - i] elif i == j + 1: return kls.one return kls.zero return kls._new(size, size, entry) @classmethod def wilkinson(kls, n, **kwargs): """Returns two square Wilkinson Matrix of size 2*n + 1 $W_{2n + 1}^-, W_{2n + 1}^+ =$ Wilkinson(n) Examples ======== >>> from sympy import Matrix >>> wminus, wplus = Matrix.wilkinson(3) >>> wminus Matrix([ [-3, 1, 0, 0, 0, 0, 0], [ 1, -2, 1, 0, 0, 0, 0], [ 0, 1, -1, 1, 0, 0, 0], [ 0, 0, 1, 0, 1, 0, 0], [ 0, 0, 0, 1, 1, 1, 0], [ 0, 0, 0, 0, 1, 2, 1], [ 0, 0, 0, 0, 0, 1, 3]]) >>> wplus Matrix([ [3, 1, 0, 0, 0, 0, 0], [1, 2, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 1, 2, 1], [0, 0, 0, 0, 0, 1, 3]]) References ========== .. [1] https://blogs.mathworks.com/cleve/2013/04/15/wilkinsons-matrices-2/ .. [2] J. H. Wilkinson, The Algebraic Eigenvalue Problem, Claredon Press, Oxford, 1965, 662 pp. """ klass = kwargs.get('cls', kls) n = as_int(n) return klass._eval_wilkinson(n) class MatrixProperties(MatrixRequired): """Provides basic properties of a matrix.""" def _eval_atoms(self, *types): result = set() for i in self: result.update(i.atoms(*types)) return result def _eval_free_symbols(self): return set().union(*(i.free_symbols for i in self if i)) def _eval_has(self, *patterns): return any(a.has(*patterns) for a in self) def _eval_is_anti_symmetric(self, simpfunc): if not all(simpfunc(self[i, j] + self[j, i]).is_zero for i in range(self.rows) for j in range(self.cols)): return False return True def _eval_is_diagonal(self): for i in range(self.rows): for j in range(self.cols): if i != j and self[i, j]: return False return True # _eval_is_hermitian is called by some general SymPy # routines and has a different *args signature. Make # sure the names don't clash by adding `_matrix_` in name. def _eval_is_matrix_hermitian(self, simpfunc): mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i].conjugate())) return mat.is_zero_matrix def _eval_is_Identity(self) -> FuzzyBool: def dirac(i, j): if i == j: return 1 return 0 return all(self[i, j] == dirac(i, j) for i in range(self.rows) for j in range(self.cols)) def _eval_is_lower_hessenberg(self): return all(self[i, j].is_zero for i in range(self.rows) for j in range(i + 2, self.cols)) def _eval_is_lower(self): return all(self[i, j].is_zero for i in range(self.rows) for j in range(i + 1, self.cols)) def _eval_is_symbolic(self): return self.has(Symbol) def _eval_is_symmetric(self, simpfunc): mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i])) return mat.is_zero_matrix def _eval_is_zero_matrix(self): if any(i.is_zero == False for i in self): return False if any(i.is_zero is None for i in self): return None return True def _eval_is_upper_hessenberg(self): return all(self[i, j].is_zero for i in range(2, self.rows) for j in range(min(self.cols, (i - 1)))) def _eval_values(self): return [i for i in self if not i.is_zero] def _has_positive_diagonals(self): diagonal_entries = (self[i, i] for i in range(self.rows)) return fuzzy_and(x.is_positive for x in diagonal_entries) def _has_nonnegative_diagonals(self): diagonal_entries = (self[i, i] for i in range(self.rows)) return fuzzy_and(x.is_nonnegative for x in diagonal_entries) def atoms(self, *types): """Returns the atoms that form the current object. Examples ======== >>> from sympy.abc import x, y >>> from sympy import Matrix >>> Matrix([[x]]) Matrix([[x]]) >>> _.atoms() {x} >>> Matrix([[x, y], [y, x]]) Matrix([ [x, y], [y, x]]) >>> _.atoms() {x, y} """ types = tuple(t if isinstance(t, type) else type(t) for t in types) if not types: types = (Atom,) return self._eval_atoms(*types) @property def free_symbols(self): """Returns the free symbols within the matrix. Examples ======== >>> from sympy.abc import x >>> from sympy import Matrix >>> Matrix([[x], [1]]).free_symbols {x} """ return self._eval_free_symbols() def has(self, *patterns): """Test whether any subexpression matches any of the patterns. Examples ======== >>> from sympy import Matrix, SparseMatrix, Float >>> from sympy.abc import x, y >>> A = Matrix(((1, x), (0.2, 3))) >>> B = SparseMatrix(((1, x), (0.2, 3))) >>> A.has(x) True >>> A.has(y) False >>> A.has(Float) True >>> B.has(x) True >>> B.has(y) False >>> B.has(Float) True """ return self._eval_has(*patterns) def is_anti_symmetric(self, simplify=True): """Check if matrix M is an antisymmetric matrix, that is, M is a square matrix with all M[i, j] == -M[j, i]. When ``simplify=True`` (default), the sum M[i, j] + M[j, i] is simplified before testing to see if it is zero. By default, the SymPy simplify function is used. To use a custom function set simplify to a function that accepts a single argument which returns a simplified expression. To skip simplification, set simplify to False but note that although this will be faster, it may induce false negatives. Examples ======== >>> from sympy import Matrix, symbols >>> m = Matrix(2, 2, [0, 1, -1, 0]) >>> m Matrix([ [ 0, 1], [-1, 0]]) >>> m.is_anti_symmetric() True >>> x, y = symbols('x y') >>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0]) >>> m Matrix([ [ 0, 0, x], [-y, 0, 0]]) >>> m.is_anti_symmetric() False >>> from sympy.abc import x, y >>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, ... -(x + 1)**2, 0, x*y, ... -y, -x*y, 0]) Simplification of matrix elements is done by default so even though two elements which should be equal and opposite would not pass an equality test, the matrix is still reported as anti-symmetric: >>> m[0, 1] == -m[1, 0] False >>> m.is_anti_symmetric() True If ``simplify=False`` is used for the case when a Matrix is already simplified, this will speed things up. Here, we see that without simplification the matrix does not appear anti-symmetric: >>> m.is_anti_symmetric(simplify=False) False But if the matrix were already expanded, then it would appear anti-symmetric and simplification in the is_anti_symmetric routine is not needed: >>> m = m.expand() >>> m.is_anti_symmetric(simplify=False) True """ # accept custom simplification simpfunc = simplify if not isfunction(simplify): simpfunc = _simplify if simplify else lambda x: x if not self.is_square: return False return self._eval_is_anti_symmetric(simpfunc) def is_diagonal(self): """Check if matrix is diagonal, that is matrix in which the entries outside the main diagonal are all zero. Examples ======== >>> from sympy import Matrix, diag >>> m = Matrix(2, 2, [1, 0, 0, 2]) >>> m Matrix([ [1, 0], [0, 2]]) >>> m.is_diagonal() True >>> m = Matrix(2, 2, [1, 1, 0, 2]) >>> m Matrix([ [1, 1], [0, 2]]) >>> m.is_diagonal() False >>> m = diag(1, 2, 3) >>> m Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> m.is_diagonal() True See Also ======== is_lower is_upper sympy.matrices.matrices.MatrixEigen.is_diagonalizable diagonalize """ return self._eval_is_diagonal() @property def is_weakly_diagonally_dominant(self): r"""Tests if the matrix is row weakly diagonally dominant. Explanation =========== A $n, n$ matrix $A$ is row weakly diagonally dominant if .. math:: \left|A_{i, i}\right| \ge \sum_{j = 0, j \neq i}^{n-1} \left|A_{i, j}\right| \quad {\text{for all }} i \in \{ 0, ..., n-1 \} Examples ======== >>> from sympy import Matrix >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]]) >>> A.is_weakly_diagonally_dominant True >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]]) >>> A.is_weakly_diagonally_dominant False >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]]) >>> A.is_weakly_diagonally_dominant True Notes ===== If you want to test whether a matrix is column diagonally dominant, you can apply the test after transposing the matrix. """ if not self.is_square: return False rows, cols = self.shape def test_row(i): summation = self.zero for j in range(cols): if i != j: summation += Abs(self[i, j]) return (Abs(self[i, i]) - summation).is_nonnegative return fuzzy_and(test_row(i) for i in range(rows)) @property def is_strongly_diagonally_dominant(self): r"""Tests if the matrix is row strongly diagonally dominant. Explanation =========== A $n, n$ matrix $A$ is row strongly diagonally dominant if .. math:: \left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1} \left|A_{i, j}\right| \quad {\text{for all }} i \in \{ 0, ..., n-1 \} Examples ======== >>> from sympy import Matrix >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]]) >>> A.is_strongly_diagonally_dominant False >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]]) >>> A.is_strongly_diagonally_dominant False >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]]) >>> A.is_strongly_diagonally_dominant True Notes ===== If you want to test whether a matrix is column diagonally dominant, you can apply the test after transposing the matrix. """ if not self.is_square: return False rows, cols = self.shape def test_row(i): summation = self.zero for j in range(cols): if i != j: summation += Abs(self[i, j]) return (Abs(self[i, i]) - summation).is_positive return fuzzy_and(test_row(i) for i in range(rows)) @property def is_hermitian(self): """Checks if the matrix is Hermitian. In a Hermitian matrix element i,j is the complex conjugate of element j,i. Examples ======== >>> from sympy import Matrix >>> from sympy import I >>> from sympy.abc import x >>> a = Matrix([[1, I], [-I, 1]]) >>> a Matrix([ [ 1, I], [-I, 1]]) >>> a.is_hermitian True >>> a[0, 0] = 2*I >>> a.is_hermitian False >>> a[0, 0] = x >>> a.is_hermitian >>> a[0, 1] = a[1, 0]*I >>> a.is_hermitian False """ if not self.is_square: return False return self._eval_is_matrix_hermitian(_simplify) @property def is_Identity(self) -> FuzzyBool: if not self.is_square: return False return self._eval_is_Identity() @property def is_lower_hessenberg(self): r"""Checks if the matrix is in the lower-Hessenberg form. The lower hessenberg matrix has zero entries above the first superdiagonal. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]]) >>> a Matrix([ [1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]]) >>> a.is_lower_hessenberg True See Also ======== is_upper_hessenberg is_lower """ return self._eval_is_lower_hessenberg() @property def is_lower(self): """Check if matrix is a lower triangular matrix. True can be returned even if the matrix is not square. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [1, 0, 0, 1]) >>> m Matrix([ [1, 0], [0, 1]]) >>> m.is_lower True >>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4, 0, 6, 6, 5]) >>> m Matrix([ [0, 0, 0], [2, 0, 0], [1, 4, 0], [6, 6, 5]]) >>> m.is_lower True >>> from sympy.abc import x, y >>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y]) >>> m Matrix([ [x**2 + y, x + y**2], [ 0, x + y]]) >>> m.is_lower False See Also ======== is_upper is_diagonal is_lower_hessenberg """ return self._eval_is_lower() @property def is_square(self): """Checks if a matrix is square. A matrix is square if the number of rows equals the number of columns. The empty matrix is square by definition, since the number of rows and the number of columns are both zero. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[1, 2, 3], [4, 5, 6]]) >>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> c = Matrix([]) >>> a.is_square False >>> b.is_square True >>> c.is_square True """ return self.rows == self.cols def is_symbolic(self): """Checks if any elements contain Symbols. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y >>> M = Matrix([[x, y], [1, 0]]) >>> M.is_symbolic() True """ return self._eval_is_symbolic() def is_symmetric(self, simplify=True): """Check if matrix is symmetric matrix, that is square matrix and is equal to its transpose. By default, simplifications occur before testing symmetry. They can be skipped using 'simplify=False'; while speeding things a bit, this may however induce false negatives. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [0, 1, 1, 2]) >>> m Matrix([ [0, 1], [1, 2]]) >>> m.is_symmetric() True >>> m = Matrix(2, 2, [0, 1, 2, 0]) >>> m Matrix([ [0, 1], [2, 0]]) >>> m.is_symmetric() False >>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0]) >>> m Matrix([ [0, 0, 0], [0, 0, 0]]) >>> m.is_symmetric() False >>> from sympy.abc import x, y >>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3]) >>> m Matrix([ [ 1, x**2 + 2*x + 1, y], [(x + 1)**2, 2, 0], [ y, 0, 3]]) >>> m.is_symmetric() True If the matrix is already simplified, you may speed-up is_symmetric() test by using 'simplify=False'. >>> bool(m.is_symmetric(simplify=False)) False >>> m1 = m.expand() >>> m1.is_symmetric(simplify=False) True """ simpfunc = simplify if not isfunction(simplify): simpfunc = _simplify if simplify else lambda x: x if not self.is_square: return False return self._eval_is_symmetric(simpfunc) @property def is_upper_hessenberg(self): """Checks if the matrix is the upper-Hessenberg form. The upper hessenberg matrix has zero entries below the first subdiagonal. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]]) >>> a Matrix([ [1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]]) >>> a.is_upper_hessenberg True See Also ======== is_lower_hessenberg is_upper """ return self._eval_is_upper_hessenberg() @property def is_upper(self): """Check if matrix is an upper triangular matrix. True can be returned even if the matrix is not square. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [1, 0, 0, 1]) >>> m Matrix([ [1, 0], [0, 1]]) >>> m.is_upper True >>> m = Matrix(4, 3, [5, 1, 9, 0, 4, 6, 0, 0, 5, 0, 0, 0]) >>> m Matrix([ [5, 1, 9], [0, 4, 6], [0, 0, 5], [0, 0, 0]]) >>> m.is_upper True >>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1]) >>> m Matrix([ [4, 2, 5], [6, 1, 1]]) >>> m.is_upper False See Also ======== is_lower is_diagonal is_upper_hessenberg """ return all(self[i, j].is_zero for i in range(1, self.rows) for j in range(min(i, self.cols))) @property def is_zero_matrix(self): """Checks if a matrix is a zero matrix. A matrix is zero if every element is zero. A matrix need not be square to be considered zero. The empty matrix is zero by the principle of vacuous truth. For a matrix that may or may not be zero (e.g. contains a symbol), this will be None Examples ======== >>> from sympy import Matrix, zeros >>> from sympy.abc import x >>> a = Matrix([[0, 0], [0, 0]]) >>> b = zeros(3, 4) >>> c = Matrix([[0, 1], [0, 0]]) >>> d = Matrix([]) >>> e = Matrix([[x, 0], [0, 0]]) >>> a.is_zero_matrix True >>> b.is_zero_matrix True >>> c.is_zero_matrix False >>> d.is_zero_matrix True >>> e.is_zero_matrix """ return self._eval_is_zero_matrix() def values(self): """Return non-zero values of self.""" return self._eval_values() class MatrixOperations(MatrixRequired): """Provides basic matrix shape and elementwise operations. Should not be instantiated directly.""" def _eval_adjoint(self): return self.transpose().conjugate() def _eval_applyfunc(self, f): out = self._new(self.rows, self.cols, [f(x) for x in self]) return out def _eval_as_real_imag(self): # type: ignore return (self.applyfunc(re), self.applyfunc(im)) def _eval_conjugate(self): return self.applyfunc(lambda x: x.conjugate()) def _eval_permute_cols(self, perm): # apply the permutation to a list mapping = list(perm) def entry(i, j): return self[i, mapping[j]] return self._new(self.rows, self.cols, entry) def _eval_permute_rows(self, perm): # apply the permutation to a list mapping = list(perm) def entry(i, j): return self[mapping[i], j] return self._new(self.rows, self.cols, entry) def _eval_trace(self): return sum(self[i, i] for i in range(self.rows)) def _eval_transpose(self): return self._new(self.cols, self.rows, lambda i, j: self[j, i]) def adjoint(self): """Conjugate transpose or Hermitian conjugation.""" return self._eval_adjoint() def applyfunc(self, f): """Apply a function to each element of the matrix. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, lambda i, j: i*2+j) >>> m Matrix([ [0, 1], [2, 3]]) >>> m.applyfunc(lambda i: 2*i) Matrix([ [0, 2], [4, 6]]) """ if not callable(f): raise TypeError("`f` must be callable.") return self._eval_applyfunc(f) def as_real_imag(self, deep=True, **hints): """Returns a tuple containing the (real, imaginary) part of matrix.""" # XXX: Ignoring deep and hints... return self._eval_as_real_imag() def conjugate(self): """Return the by-element conjugation. Examples ======== >>> from sympy import SparseMatrix, I >>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I))) >>> a Matrix([ [1, 2 + I], [3, 4], [I, -I]]) >>> a.C Matrix([ [ 1, 2 - I], [ 3, 4], [-I, I]]) See Also ======== transpose: Matrix transposition H: Hermite conjugation sympy.matrices.matrices.MatrixBase.D: Dirac conjugation """ return self._eval_conjugate() def doit(self, **hints): return self.applyfunc(lambda x: x.doit(**hints)) def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False): """Apply evalf() to each element of self.""" options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict, 'quad':quad, 'verbose':verbose} return self.applyfunc(lambda i: i.evalf(n, **options)) def expand(self, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints): """Apply core.function.expand to each entry of the matrix. Examples ======== >>> from sympy.abc import x >>> from sympy import Matrix >>> Matrix(1, 1, [x*(x+1)]) Matrix([[x*(x + 1)]]) >>> _.expand() Matrix([[x**2 + x]]) """ return self.applyfunc(lambda x: x.expand( deep, modulus, power_base, power_exp, mul, log, multinomial, basic, **hints)) @property def H(self): """Return Hermite conjugate. Examples ======== >>> from sympy import Matrix, I >>> m = Matrix((0, 1 + I, 2, 3)) >>> m Matrix([ [ 0], [1 + I], [ 2], [ 3]]) >>> m.H Matrix([[0, 1 - I, 2, 3]]) See Also ======== conjugate: By-element conjugation sympy.matrices.matrices.MatrixBase.D: Dirac conjugation """ return self.T.C def permute(self, perm, orientation='rows', direction='forward'): r"""Permute the rows or columns of a matrix by the given list of swaps. Parameters ========== perm : Permutation, list, or list of lists A representation for the permutation. If it is ``Permutation``, it is used directly with some resizing with respect to the matrix size. If it is specified as list of lists, (e.g., ``[[0, 1], [0, 2]]``), then the permutation is formed from applying the product of cycles. The direction how the cyclic product is applied is described in below. If it is specified as a list, the list should represent an array form of a permutation. (e.g., ``[1, 2, 0]``) which would would form the swapping function `0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0`. orientation : 'rows', 'cols' A flag to control whether to permute the rows or the columns direction : 'forward', 'backward' A flag to control whether to apply the permutations from the start of the list first, or from the back of the list first. For example, if the permutation specification is ``[[0, 1], [0, 2]]``, If the flag is set to ``'forward'``, the cycle would be formed as `0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0`. If the flag is set to ``'backward'``, the cycle would be formed as `0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0`. If the argument ``perm`` is not in a form of list of lists, this flag takes no effect. Examples ======== >>> from sympy import eye >>> M = eye(3) >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward') Matrix([ [0, 0, 1], [1, 0, 0], [0, 1, 0]]) >>> from sympy import eye >>> M = eye(3) >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward') Matrix([ [0, 1, 0], [0, 0, 1], [1, 0, 0]]) Notes ===== If a bijective function `\sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0` denotes the permutation. If the matrix `A` is the matrix to permute, represented as a horizontal or a vertical stack of vectors: .. math:: A = \begin{bmatrix} a_0 \\ a_1 \\ \vdots \\ a_{n-1} \end{bmatrix} = \begin{bmatrix} \alpha_0 & \alpha_1 & \cdots & \alpha_{n-1} \end{bmatrix} If the matrix `B` is the result, the permutation of matrix rows is defined as: .. math:: B := \begin{bmatrix} a_{\sigma(0)} \\ a_{\sigma(1)} \\ \vdots \\ a_{\sigma(n-1)} \end{bmatrix} And the permutation of matrix columns is defined as: .. math:: B := \begin{bmatrix} \alpha_{\sigma(0)} & \alpha_{\sigma(1)} & \cdots & \alpha_{\sigma(n-1)} \end{bmatrix} """ from sympy.combinatorics import Permutation # allow british variants and `columns` if direction == 'forwards': direction = 'forward' if direction == 'backwards': direction = 'backward' if orientation == 'columns': orientation = 'cols' if direction not in ('forward', 'backward'): raise TypeError("direction='{}' is an invalid kwarg. " "Try 'forward' or 'backward'".format(direction)) if orientation not in ('rows', 'cols'): raise TypeError("orientation='{}' is an invalid kwarg. " "Try 'rows' or 'cols'".format(orientation)) if not isinstance(perm, (Permutation, Iterable)): raise ValueError( "{} must be a list, a list of lists, " "or a SymPy permutation object.".format(perm)) # ensure all swaps are in range max_index = self.rows if orientation == 'rows' else self.cols if not all(0 <= t <= max_index for t in flatten(list(perm))): raise IndexError("`swap` indices out of range.") if perm and not isinstance(perm, Permutation) and \ isinstance(perm[0], Iterable): if direction == 'forward': perm = list(reversed(perm)) perm = Permutation(perm, size=max_index+1) else: perm = Permutation(perm, size=max_index+1) if orientation == 'rows': return self._eval_permute_rows(perm) if orientation == 'cols': return self._eval_permute_cols(perm) def permute_cols(self, swaps, direction='forward'): """Alias for ``self.permute(swaps, orientation='cols', direction=direction)`` See Also ======== permute """ return self.permute(swaps, orientation='cols', direction=direction) def permute_rows(self, swaps, direction='forward'): """Alias for ``self.permute(swaps, orientation='rows', direction=direction)`` See Also ======== permute """ return self.permute(swaps, orientation='rows', direction=direction) def refine(self, assumptions=True): """Apply refine to each element of the matrix. Examples ======== >>> from sympy import Symbol, Matrix, Abs, sqrt, Q >>> x = Symbol('x') >>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]]) Matrix([ [ Abs(x)**2, sqrt(x**2)], [sqrt(x**2), Abs(x)**2]]) >>> _.refine(Q.real(x)) Matrix([ [ x**2, Abs(x)], [Abs(x), x**2]]) """ return self.applyfunc(lambda x: refine(x, assumptions)) def replace(self, F, G, map=False, simultaneous=True, exact=None): """Replaces Function F in Matrix entries with Function G. Examples ======== >>> from sympy import symbols, Function, Matrix >>> F, G = symbols('F, G', cls=Function) >>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M Matrix([ [F(0), F(1)], [F(1), F(2)]]) >>> N = M.replace(F,G) >>> N Matrix([ [G(0), G(1)], [G(1), G(2)]]) """ return self.applyfunc( lambda x: x.replace(F, G, map=map, simultaneous=simultaneous, exact=exact)) def rot90(self, k=1): """Rotates Matrix by 90 degrees Parameters ========== k : int Specifies how many times the matrix is rotated by 90 degrees (clockwise when positive, counter-clockwise when negative). Examples ======== >>> from sympy import Matrix, symbols >>> A = Matrix(2, 2, symbols('a:d')) >>> A Matrix([ [a, b], [c, d]]) Rotating the matrix clockwise one time: >>> A.rot90(1) Matrix([ [c, a], [d, b]]) Rotating the matrix anticlockwise two times: >>> A.rot90(-2) Matrix([ [d, c], [b, a]]) """ mod = k%4 if mod == 0: return self if mod == 1: return self[::-1, ::].T if mod == 2: return self[::-1, ::-1] if mod == 3: return self[::, ::-1].T def simplify(self, **kwargs): """Apply simplify to each element of the matrix. Examples ======== >>> from sympy.abc import x, y >>> from sympy import SparseMatrix, sin, cos >>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2]) Matrix([[x*sin(y)**2 + x*cos(y)**2]]) >>> _.simplify() Matrix([[x]]) """ return self.applyfunc(lambda x: x.simplify(**kwargs)) def subs(self, *args, **kwargs): # should mirror core.basic.subs """Return a new matrix with subs applied to each entry. Examples ======== >>> from sympy.abc import x, y >>> from sympy import SparseMatrix, Matrix >>> SparseMatrix(1, 1, [x]) Matrix([[x]]) >>> _.subs(x, y) Matrix([[y]]) >>> Matrix(_).subs(y, x) Matrix([[x]]) """ if len(args) == 1 and not isinstance(args[0], (dict, set)) and iter(args[0]) and not is_sequence(args[0]): args = (list(args[0]),) return self.applyfunc(lambda x: x.subs(*args, **kwargs)) def trace(self): """ Returns the trace of a square matrix i.e. the sum of the diagonal elements. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.trace() 5 """ if self.rows != self.cols: raise NonSquareMatrixError() return self._eval_trace() def transpose(self): """ Returns the transpose of the matrix. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.transpose() Matrix([ [1, 3], [2, 4]]) >>> from sympy import Matrix, I >>> m=Matrix(((1, 2+I), (3, 4))) >>> m Matrix([ [1, 2 + I], [3, 4]]) >>> m.transpose() Matrix([ [ 1, 3], [2 + I, 4]]) >>> m.T == m.transpose() True See Also ======== conjugate: By-element conjugation """ return self._eval_transpose() @property def T(self): '''Matrix transposition''' return self.transpose() @property def C(self): '''By-element conjugation''' return self.conjugate() def n(self, *args, **kwargs): """Apply evalf() to each element of self.""" return self.evalf(*args, **kwargs) def xreplace(self, rule): # should mirror core.basic.xreplace """Return a new matrix with xreplace applied to each entry. Examples ======== >>> from sympy.abc import x, y >>> from sympy import SparseMatrix, Matrix >>> SparseMatrix(1, 1, [x]) Matrix([[x]]) >>> _.xreplace({x: y}) Matrix([[y]]) >>> Matrix(_).xreplace({y: x}) Matrix([[x]]) """ return self.applyfunc(lambda x: x.xreplace(rule)) def _eval_simplify(self, **kwargs): # XXX: We can't use self.simplify here as mutable subclasses will # override simplify and have it return None return MatrixOperations.simplify(self, **kwargs) def _eval_trigsimp(self, **opts): from sympy.simplify.trigsimp import trigsimp return self.applyfunc(lambda x: trigsimp(x, **opts)) def upper_triangular(self, k=0): """returns the elements on and above the kth diagonal of a matrix. If k is not specified then simply returns upper-triangular portion of a matrix Examples ======== >>> from sympy import ones >>> A = ones(4) >>> A.upper_triangular() Matrix([ [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1]]) >>> A.upper_triangular(2) Matrix([ [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]]) >>> A.upper_triangular(-1) Matrix([ [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1]]) """ def entry(i, j): return self[i, j] if i + k <= j else self.zero return self._new(self.rows, self.cols, entry) def lower_triangular(self, k=0): """returns the elements on and below the kth diagonal of a matrix. If k is not specified then simply returns lower-triangular portion of a matrix Examples ======== >>> from sympy import ones >>> A = ones(4) >>> A.lower_triangular() Matrix([ [1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1]]) >>> A.lower_triangular(-2) Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [1, 1, 0, 0]]) >>> A.lower_triangular(1) Matrix([ [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1]]) """ def entry(i, j): return self[i, j] if i + k >= j else self.zero return self._new(self.rows, self.cols, entry) class MatrixArithmetic(MatrixRequired): """Provides basic matrix arithmetic operations. Should not be instantiated directly.""" _op_priority = 10.01 def _eval_Abs(self): return self._new(self.rows, self.cols, lambda i, j: Abs(self[i, j])) def _eval_add(self, other): return self._new(self.rows, self.cols, lambda i, j: self[i, j] + other[i, j]) def _eval_matrix_mul(self, other): def entry(i, j): vec = [self[i,k]*other[k,j] for k in range(self.cols)] try: return Add(*vec) except (TypeError, SympifyError): # Some matrices don't work with `sum` or `Add` # They don't work with `sum` because `sum` tries to add `0` # Fall back to a safe way to multiply if the `Add` fails. return reduce(lambda a, b: a + b, vec) return self._new(self.rows, other.cols, entry) def _eval_matrix_mul_elementwise(self, other): return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other[i,j]) def _eval_matrix_rmul(self, other): def entry(i, j): return sum(other[i,k]*self[k,j] for k in range(other.cols)) return self._new(other.rows, self.cols, entry) def _eval_pow_by_recursion(self, num): if num == 1: return self if num % 2 == 1: a, b = self, self._eval_pow_by_recursion(num - 1) else: a = b = self._eval_pow_by_recursion(num // 2) return a.multiply(b) def _eval_pow_by_cayley(self, exp): from sympy.discrete.recurrences import linrec_coeffs row = self.shape[0] p = self.charpoly() coeffs = (-p).all_coeffs()[1:] coeffs = linrec_coeffs(coeffs, exp) new_mat = self.eye(row) ans = self.zeros(row) for i in range(row): ans += coeffs[i]*new_mat new_mat *= self return ans def _eval_pow_by_recursion_dotprodsimp(self, num, prevsimp=None): if prevsimp is None: prevsimp = [True]*len(self) if num == 1: return self if num % 2 == 1: a, b = self, self._eval_pow_by_recursion_dotprodsimp(num - 1, prevsimp=prevsimp) else: a = b = self._eval_pow_by_recursion_dotprodsimp(num // 2, prevsimp=prevsimp) m = a.multiply(b, dotprodsimp=False) lenm = len(m) elems = [None]*lenm for i in range(lenm): if prevsimp[i]: elems[i], prevsimp[i] = _dotprodsimp(m[i], withsimp=True) else: elems[i] = m[i] return m._new(m.rows, m.cols, elems) def _eval_scalar_mul(self, other): return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other) def _eval_scalar_rmul(self, other): return self._new(self.rows, self.cols, lambda i, j: other*self[i,j]) def _eval_Mod(self, other): return self._new(self.rows, self.cols, lambda i, j: Mod(self[i, j], other)) # Python arithmetic functions def __abs__(self): """Returns a new matrix with entry-wise absolute values.""" return self._eval_Abs() @call_highest_priority('__radd__') def __add__(self, other): """Return self + other, raising ShapeError if shapes do not match.""" if isinstance(other, NDimArray): # Matrix and array addition is currently not implemented return NotImplemented other = _matrixify(other) # matrix-like objects can have shapes. This is # our first sanity check. if hasattr(other, 'shape'): if self.shape != other.shape: raise ShapeError("Matrix size mismatch: %s + %s" % ( self.shape, other.shape)) # honest SymPy matrices defer to their class's routine if getattr(other, 'is_Matrix', False): # call the highest-priority class's _eval_add a, b = self, other if a.__class__ != classof(a, b): b, a = a, b return a._eval_add(b) # Matrix-like objects can be passed to CommonMatrix routines directly. if getattr(other, 'is_MatrixLike', False): return MatrixArithmetic._eval_add(self, other) raise TypeError('cannot add %s and %s' % (type(self), type(other))) @call_highest_priority('__rtruediv__') def __truediv__(self, other): return self * (self.one / other) @call_highest_priority('__rmatmul__') def __matmul__(self, other): other = _matrixify(other) if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False): return NotImplemented return self.__mul__(other) def __mod__(self, other): return self.applyfunc(lambda x: x % other) @call_highest_priority('__rmul__') def __mul__(self, other): """Return self*other where other is either a scalar or a matrix of compatible dimensions. Examples ======== >>> from sympy import Matrix >>> A = Matrix([[1, 2, 3], [4, 5, 6]]) >>> 2*A == A*2 == Matrix([[2, 4, 6], [8, 10, 12]]) True >>> B = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> A*B Matrix([ [30, 36, 42], [66, 81, 96]]) >>> B*A Traceback (most recent call last): ... ShapeError: Matrices size mismatch. >>> See Also ======== matrix_multiply_elementwise """ return self.multiply(other) def multiply(self, other, dotprodsimp=None): """Same as __mul__() but with optional simplification. Parameters ========== dotprodsimp : bool, optional Specifies whether intermediate term algebraic simplification is used during matrix multiplications to control expression blowup and thus speed up calculation. Default is off. """ isimpbool = _get_intermediate_simp_bool(False, dotprodsimp) other = _matrixify(other) # matrix-like objects can have shapes. This is # our first sanity check. Double check other is not explicitly not a Matrix. if (hasattr(other, 'shape') and len(other.shape) == 2 and (getattr(other, 'is_Matrix', True) or getattr(other, 'is_MatrixLike', True))): if self.shape[1] != other.shape[0]: raise ShapeError("Matrix size mismatch: %s * %s." % ( self.shape, other.shape)) # honest SymPy matrices defer to their class's routine if getattr(other, 'is_Matrix', False): m = self._eval_matrix_mul(other) if isimpbool: return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m]) return m # Matrix-like objects can be passed to CommonMatrix routines directly. if getattr(other, 'is_MatrixLike', False): return MatrixArithmetic._eval_matrix_mul(self, other) # if 'other' is not iterable then scalar multiplication. if not isinstance(other, Iterable): try: return self._eval_scalar_mul(other) except TypeError: pass return NotImplemented def multiply_elementwise(self, other): """Return the Hadamard product (elementwise product) of A and B Examples ======== >>> from sympy import Matrix >>> A = Matrix([[0, 1, 2], [3, 4, 5]]) >>> B = Matrix([[1, 10, 100], [100, 10, 1]]) >>> A.multiply_elementwise(B) Matrix([ [ 0, 10, 200], [300, 40, 5]]) See Also ======== sympy.matrices.matrices.MatrixBase.cross sympy.matrices.matrices.MatrixBase.dot multiply """ if self.shape != other.shape: raise ShapeError("Matrix shapes must agree {} != {}".format(self.shape, other.shape)) return self._eval_matrix_mul_elementwise(other) def __neg__(self): return self._eval_scalar_mul(-1) @call_highest_priority('__rpow__') def __pow__(self, exp): """Return self**exp a scalar or symbol.""" return self.pow(exp) def pow(self, exp, method=None): r"""Return self**exp a scalar or symbol. Parameters ========== method : multiply, mulsimp, jordan, cayley If multiply then it returns exponentiation using recursion. If jordan then Jordan form exponentiation will be used. If cayley then the exponentiation is done using Cayley-Hamilton theorem. If mulsimp then the exponentiation is done using recursion with dotprodsimp. This specifies whether intermediate term algebraic simplification is used during naive matrix power to control expression blowup and thus speed up calculation. If None, then it heuristically decides which method to use. """ if method is not None and method not in ['multiply', 'mulsimp', 'jordan', 'cayley']: raise TypeError('No such method') if self.rows != self.cols: raise NonSquareMatrixError() a = self jordan_pow = getattr(a, '_matrix_pow_by_jordan_blocks', None) exp = sympify(exp) if exp.is_zero: return a._new(a.rows, a.cols, lambda i, j: int(i == j)) if exp == 1: return a diagonal = getattr(a, 'is_diagonal', None) if diagonal is not None and diagonal(): return a._new(a.rows, a.cols, lambda i, j: a[i,j]**exp if i == j else 0) if exp.is_Number and exp % 1 == 0: if a.rows == 1: return a._new([[a[0]**exp]]) if exp < 0: exp = -exp a = a.inv() # When certain conditions are met, # Jordan block algorithm is faster than # computation by recursion. if method == 'jordan': try: return jordan_pow(exp) except MatrixError: if method == 'jordan': raise elif method == 'cayley': if not exp.is_Number or exp % 1 != 0: raise ValueError("cayley method is only valid for integer powers") return a._eval_pow_by_cayley(exp) elif method == "mulsimp": if not exp.is_Number or exp % 1 != 0: raise ValueError("mulsimp method is only valid for integer powers") return a._eval_pow_by_recursion_dotprodsimp(exp) elif method == "multiply": if not exp.is_Number or exp % 1 != 0: raise ValueError("multiply method is only valid for integer powers") return a._eval_pow_by_recursion(exp) elif method is None and exp.is_Number and exp % 1 == 0: # Decide heuristically which method to apply if a.rows == 2 and exp > 100000: return jordan_pow(exp) elif _get_intermediate_simp_bool(True, None): return a._eval_pow_by_recursion_dotprodsimp(exp) elif exp > 10000: return a._eval_pow_by_cayley(exp) else: return a._eval_pow_by_recursion(exp) if jordan_pow: try: return jordan_pow(exp) except NonInvertibleMatrixError: # Raised by jordan_pow on zero determinant matrix unless exp is # definitely known to be a non-negative integer. # Here we raise if n is definitely not a non-negative integer # but otherwise we can leave this as an unevaluated MatPow. if exp.is_integer is False or exp.is_nonnegative is False: raise from sympy.matrices.expressions import MatPow return MatPow(a, exp) @call_highest_priority('__add__') def __radd__(self, other): return self + other @call_highest_priority('__matmul__') def __rmatmul__(self, other): other = _matrixify(other) if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False): return NotImplemented return self.__rmul__(other) @call_highest_priority('__mul__') def __rmul__(self, other): return self.rmultiply(other) def rmultiply(self, other, dotprodsimp=None): """Same as __rmul__() but with optional simplification. Parameters ========== dotprodsimp : bool, optional Specifies whether intermediate term algebraic simplification is used during matrix multiplications to control expression blowup and thus speed up calculation. Default is off. """ isimpbool = _get_intermediate_simp_bool(False, dotprodsimp) other = _matrixify(other) # matrix-like objects can have shapes. This is # our first sanity check. Double check other is not explicitly not a Matrix. if (hasattr(other, 'shape') and len(other.shape) == 2 and (getattr(other, 'is_Matrix', True) or getattr(other, 'is_MatrixLike', True))): if self.shape[0] != other.shape[1]: raise ShapeError("Matrix size mismatch.") # honest SymPy matrices defer to their class's routine if getattr(other, 'is_Matrix', False): m = self._eval_matrix_rmul(other) if isimpbool: return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m]) return m # Matrix-like objects can be passed to CommonMatrix routines directly. if getattr(other, 'is_MatrixLike', False): return MatrixArithmetic._eval_matrix_rmul(self, other) # if 'other' is not iterable then scalar multiplication. if not isinstance(other, Iterable): try: return self._eval_scalar_rmul(other) except TypeError: pass return NotImplemented @call_highest_priority('__sub__') def __rsub__(self, a): return (-self) + a @call_highest_priority('__rsub__') def __sub__(self, a): return self + (-a) class MatrixCommon(MatrixArithmetic, MatrixOperations, MatrixProperties, MatrixSpecial, MatrixShaping): """All common matrix operations including basic arithmetic, shaping, and special matrices like `zeros`, and `eye`.""" _diff_wrt = True # type: bool class _MinimalMatrix: """Class providing the minimum functionality for a matrix-like object and implementing every method required for a `MatrixRequired`. This class does not have everything needed to become a full-fledged SymPy object, but it will satisfy the requirements of anything inheriting from `MatrixRequired`. If you wish to make a specialized matrix type, make sure to implement these methods and properties with the exception of `__init__` and `__repr__` which are included for convenience.""" is_MatrixLike = True _sympify = staticmethod(sympify) _class_priority = 3 zero = S.Zero one = S.One is_Matrix = True is_MatrixExpr = False @classmethod def _new(cls, *args, **kwargs): return cls(*args, **kwargs) def __init__(self, rows, cols=None, mat=None, copy=False): if isfunction(mat): # if we passed in a function, use that to populate the indices mat = list(mat(i, j) for i in range(rows) for j in range(cols)) if cols is None and mat is None: mat = rows rows, cols = getattr(mat, 'shape', (rows, cols)) try: # if we passed in a list of lists, flatten it and set the size if cols is None and mat is None: mat = rows cols = len(mat[0]) rows = len(mat) mat = [x for l in mat for x in l] except (IndexError, TypeError): pass self.mat = tuple(self._sympify(x) for x in mat) self.rows, self.cols = rows, cols if self.rows is None or self.cols is None: raise NotImplementedError("Cannot initialize matrix with given parameters") def __getitem__(self, key): def _normalize_slices(row_slice, col_slice): """Ensure that row_slice and col_slice do not have `None` in their arguments. Any integers are converted to slices of length 1""" if not isinstance(row_slice, slice): row_slice = slice(row_slice, row_slice + 1, None) row_slice = slice(*row_slice.indices(self.rows)) if not isinstance(col_slice, slice): col_slice = slice(col_slice, col_slice + 1, None) col_slice = slice(*col_slice.indices(self.cols)) return (row_slice, col_slice) def _coord_to_index(i, j): """Return the index in _mat corresponding to the (i,j) position in the matrix. """ return i * self.cols + j if isinstance(key, tuple): i, j = key if isinstance(i, slice) or isinstance(j, slice): # if the coordinates are not slices, make them so # and expand the slices so they don't contain `None` i, j = _normalize_slices(i, j) rowsList, colsList = list(range(self.rows))[i], \ list(range(self.cols))[j] indices = (i * self.cols + j for i in rowsList for j in colsList) return self._new(len(rowsList), len(colsList), list(self.mat[i] for i in indices)) # if the key is a tuple of ints, change # it to an array index key = _coord_to_index(i, j) return self.mat[key] def __eq__(self, other): try: classof(self, other) except TypeError: return False return ( self.shape == other.shape and list(self) == list(other)) def __len__(self): return self.rows*self.cols def __repr__(self): return "_MinimalMatrix({}, {}, {})".format(self.rows, self.cols, self.mat) @property def shape(self): return (self.rows, self.cols) class _CastableMatrix: # this is needed here ONLY FOR TESTS. def as_mutable(self): return self def as_immutable(self): return self class _MatrixWrapper: """Wrapper class providing the minimum functionality for a matrix-like object: .rows, .cols, .shape, indexability, and iterability. CommonMatrix math operations should work on matrix-like objects. This one is intended for matrix-like objects which use the same indexing format as SymPy with respect to returning matrix elements instead of rows for non-tuple indexes. """ is_Matrix = False # needs to be here because of __getattr__ is_MatrixLike = True def __init__(self, mat, shape): self.mat = mat self.shape = shape self.rows, self.cols = shape def __getitem__(self, key): if isinstance(key, tuple): return sympify(self.mat.__getitem__(key)) return sympify(self.mat.__getitem__((key // self.rows, key % self.cols))) def __iter__(self): # supports numpy.matrix and numpy.array mat = self.mat cols = self.cols return iter(sympify(mat[r, c]) for r in range(self.rows) for c in range(cols)) class MatrixKind(Kind): """ Kind for all matrices in SymPy. Basic class for this kind is ``MatrixBase`` and ``MatrixExpr``, but any expression representing the matrix can have this. Parameters ========== element_kind : Kind Kind of the element. Default is :class:`sympy.core.kind.NumberKind`, which means that the matrix contains only numbers. Examples ======== Any instance of matrix class has ``MatrixKind``: >>> from sympy import MatrixSymbol >>> A = MatrixSymbol('A', 2,2) >>> A.kind MatrixKind(NumberKind) Although expression representing a matrix may be not instance of matrix class, it will have ``MatrixKind`` as well: >>> from sympy import MatrixExpr, Integral >>> from sympy.abc import x >>> intM = Integral(A, x) >>> isinstance(intM, MatrixExpr) False >>> intM.kind MatrixKind(NumberKind) Use ``isinstance()`` to check for ``MatrixKind`` without specifying the element kind. Use ``is`` with specifying the element kind: >>> from sympy import Matrix >>> from sympy.core import NumberKind >>> from sympy.matrices import MatrixKind >>> M = Matrix([1, 2]) >>> isinstance(M.kind, MatrixKind) True >>> M.kind is MatrixKind(NumberKind) True See Also ======== sympy.core.kind.NumberKind sympy.core.kind.UndefinedKind sympy.core.containers.TupleKind sympy.sets.sets.SetKind """ def __new__(cls, element_kind=NumberKind): obj = super().__new__(cls, element_kind) obj.element_kind = element_kind return obj def __repr__(self): return "MatrixKind(%s)" % self.element_kind def _matrixify(mat): """If `mat` is a Matrix or is matrix-like, return a Matrix or MatrixWrapper object. Otherwise `mat` is passed through without modification.""" if getattr(mat, 'is_Matrix', False) or getattr(mat, 'is_MatrixLike', False): return mat if not(getattr(mat, 'is_Matrix', True) or getattr(mat, 'is_MatrixLike', True)): return mat shape = None if hasattr(mat, 'shape'): # numpy, scipy.sparse if len(mat.shape) == 2: shape = mat.shape elif hasattr(mat, 'rows') and hasattr(mat, 'cols'): # mpmath shape = (mat.rows, mat.cols) if shape: return _MatrixWrapper(mat, shape) return mat def a2idx(j, n=None): """Return integer after making positive and validating against n.""" if not isinstance(j, int): jindex = getattr(j, '__index__', None) if jindex is not None: j = jindex() else: raise IndexError("Invalid index a[%r]" % (j,)) if n is not None: if j < 0: j += n if not (j >= 0 and j < n): raise IndexError("Index out of range: a[%s]" % (j,)) return int(j) def classof(A, B): """ Get the type of the result when combining matrices of different types. Currently the strategy is that immutability is contagious. Examples ======== >>> from sympy import Matrix, ImmutableMatrix >>> from sympy.matrices.common import classof >>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix >>> IM = ImmutableMatrix([[1, 2], [3, 4]]) >>> classof(M, IM) <class 'sympy.matrices.immutable.ImmutableDenseMatrix'> """ priority_A = getattr(A, '_class_priority', None) priority_B = getattr(B, '_class_priority', None) if None not in (priority_A, priority_B): if A._class_priority > B._class_priority: return A.__class__ else: return B.__class__ try: import numpy except ImportError: pass else: if isinstance(A, numpy.ndarray): return B.__class__ if isinstance(B, numpy.ndarray): return A.__class__ raise TypeError("Incompatible classes %s, %s" % (A.__class__, B.__class__))
d635f1005b25da2bd7953f52b0638ceecd6ebd2d94284b96ccd600fdb4ed4ba5
from sympy.core import S from sympy.core.relational import Eq, Ne from sympy.logic.boolalg import BooleanFunction from sympy.utilities.misc import func_name from .sets import Set class Contains(BooleanFunction): """ Asserts that x is an element of the set S. Examples ======== >>> from sympy import Symbol, Integer, S, Contains >>> Contains(Integer(2), S.Integers) True >>> Contains(Integer(-2), S.Naturals) False >>> i = Symbol('i', integer=True) >>> Contains(i, S.Naturals) Contains(i, Naturals) References ========== .. [1] https://en.wikipedia.org/wiki/Element_%28mathematics%29 """ @classmethod def eval(cls, x, s): if not isinstance(s, Set): raise TypeError('expecting Set, not %s' % func_name(s)) ret = s.contains(x) if not isinstance(ret, Contains) and ( ret in (S.true, S.false) or isinstance(ret, Set)): return ret @property def binary_symbols(self): return set().union(*[i.binary_symbols for i in self.args[1].args if i.is_Boolean or i.is_Symbol or isinstance(i, (Eq, Ne))]) def as_set(self): return self.args[1]
da4449d1846bb0329a77c437e145ddcb894e5462a1e8bbcbe8ba243d50d937c0
"""Implicit plotting module for SymPy. Explanation =========== The module implements a data series called ImplicitSeries which is used by ``Plot`` class to plot implicit plots for different backends. The module, by default, implements plotting using interval arithmetic. It switches to a fall back algorithm if the expression cannot be plotted using interval arithmetic. It is also possible to specify to use the fall back algorithm for all plots. Boolean combinations of expressions cannot be plotted by the fall back algorithm. See Also ======== sympy.plotting.plot References ========== .. [1] Jeffrey Allen Tupper. Reliable Two-Dimensional Graphing Methods for Mathematical Formulae with Two Free Variables. .. [2] Jeffrey Allen Tupper. Graphing Equations with Generalized Interval Arithmetic. Master's thesis. University of Toronto, 1996 """ from .plot import BaseSeries, Plot from .experimental_lambdify import experimental_lambdify, vectorized_lambdify from .intervalmath import interval from sympy.core.relational import (Equality, GreaterThan, LessThan, Relational, StrictLessThan, StrictGreaterThan) from sympy.core.containers import Tuple from sympy.core.relational import Eq from sympy.core.symbol import (Dummy, Symbol) from sympy.core.sympify import sympify from sympy.external import import_module from sympy.logic.boolalg import BooleanFunction from sympy.polys.polyutils import _sort_gens from sympy.utilities.decorator import doctest_depends_on from sympy.utilities.iterables import flatten import warnings class ImplicitSeries(BaseSeries): """ Representation for Implicit plot """ is_implicit = True def __init__(self, expr, var_start_end_x, var_start_end_y, has_equality, use_interval_math, depth, nb_of_points, line_color): super().__init__() self.expr = sympify(expr) self.label = self.expr self.var_x = sympify(var_start_end_x[0]) self.start_x = float(var_start_end_x[1]) self.end_x = float(var_start_end_x[2]) self.var_y = sympify(var_start_end_y[0]) self.start_y = float(var_start_end_y[1]) self.end_y = float(var_start_end_y[2]) self.get_points = self.get_raster self.has_equality = has_equality # If the expression has equality, i.e. #Eq, Greaterthan, LessThan. self.nb_of_points = nb_of_points self.use_interval_math = use_interval_math self.depth = 4 + depth self.line_color = line_color def __str__(self): return ('Implicit equation: %s for ' '%s over %s and %s over %s') % ( str(self.expr), str(self.var_x), str((self.start_x, self.end_x)), str(self.var_y), str((self.start_y, self.end_y))) def get_raster(self): func = experimental_lambdify((self.var_x, self.var_y), self.expr, use_interval=True) xinterval = interval(self.start_x, self.end_x) yinterval = interval(self.start_y, self.end_y) try: func(xinterval, yinterval) except AttributeError: # XXX: AttributeError("'list' object has no attribute 'is_real'") # That needs fixing somehow - we shouldn't be catching # AttributeError here. if self.use_interval_math: warnings.warn("Adaptive meshing could not be applied to the" " expression. Using uniform meshing.", stacklevel=7) self.use_interval_math = False if self.use_interval_math: return self._get_raster_interval(func) else: return self._get_meshes_grid() def _get_raster_interval(self, func): """ Uses interval math to adaptively mesh and obtain the plot""" k = self.depth interval_list = [] #Create initial 32 divisions np = import_module('numpy') xsample = np.linspace(self.start_x, self.end_x, 33) ysample = np.linspace(self.start_y, self.end_y, 33) #Add a small jitter so that there are no false positives for equality. # Ex: y==x becomes True for x interval(1, 2) and y interval(1, 2) #which will draw a rectangle. jitterx = (np.random.rand( len(xsample)) * 2 - 1) * (self.end_x - self.start_x) / 2**20 jittery = (np.random.rand( len(ysample)) * 2 - 1) * (self.end_y - self.start_y) / 2**20 xsample += jitterx ysample += jittery xinter = [interval(x1, x2) for x1, x2 in zip(xsample[:-1], xsample[1:])] yinter = [interval(y1, y2) for y1, y2 in zip(ysample[:-1], ysample[1:])] interval_list = [[x, y] for x in xinter for y in yinter] plot_list = [] #recursive call refinepixels which subdivides the intervals which are #neither True nor False according to the expression. def refine_pixels(interval_list): """ Evaluates the intervals and subdivides the interval if the expression is partially satisfied.""" temp_interval_list = [] plot_list = [] for intervals in interval_list: #Convert the array indices to x and y values intervalx = intervals[0] intervaly = intervals[1] func_eval = func(intervalx, intervaly) #The expression is valid in the interval. Change the contour #array values to 1. if func_eval[1] is False or func_eval[0] is False: pass elif func_eval == (True, True): plot_list.append([intervalx, intervaly]) elif func_eval[1] is None or func_eval[0] is None: #Subdivide avgx = intervalx.mid avgy = intervaly.mid a = interval(intervalx.start, avgx) b = interval(avgx, intervalx.end) c = interval(intervaly.start, avgy) d = interval(avgy, intervaly.end) temp_interval_list.append([a, c]) temp_interval_list.append([a, d]) temp_interval_list.append([b, c]) temp_interval_list.append([b, d]) return temp_interval_list, plot_list while k >= 0 and len(interval_list): interval_list, plot_list_temp = refine_pixels(interval_list) plot_list.extend(plot_list_temp) k = k - 1 #Check whether the expression represents an equality #If it represents an equality, then none of the intervals #would have satisfied the expression due to floating point #differences. Add all the undecided values to the plot. if self.has_equality: for intervals in interval_list: intervalx = intervals[0] intervaly = intervals[1] func_eval = func(intervalx, intervaly) if func_eval[1] and func_eval[0] is not False: plot_list.append([intervalx, intervaly]) return plot_list, 'fill' def _get_meshes_grid(self): """Generates the mesh for generating a contour. In the case of equality, ``contour`` function of matplotlib can be used. In other cases, matplotlib's ``contourf`` is used. """ equal = False if isinstance(self.expr, Equality): expr = self.expr.lhs - self.expr.rhs equal = True elif isinstance(self.expr, (GreaterThan, StrictGreaterThan)): expr = self.expr.lhs - self.expr.rhs elif isinstance(self.expr, (LessThan, StrictLessThan)): expr = self.expr.rhs - self.expr.lhs else: raise NotImplementedError("The expression is not supported for " "plotting in uniform meshed plot.") np = import_module('numpy') xarray = np.linspace(self.start_x, self.end_x, self.nb_of_points) yarray = np.linspace(self.start_y, self.end_y, self.nb_of_points) x_grid, y_grid = np.meshgrid(xarray, yarray) func = vectorized_lambdify((self.var_x, self.var_y), expr) z_grid = func(x_grid, y_grid) z_grid[np.ma.where(z_grid < 0)] = -1 z_grid[np.ma.where(z_grid > 0)] = 1 if equal: return xarray, yarray, z_grid, 'contour' else: return xarray, yarray, z_grid, 'contourf' @doctest_depends_on(modules=('matplotlib',)) def plot_implicit(expr, x_var=None, y_var=None, adaptive=True, depth=0, points=300, line_color="blue", show=True, **kwargs): """A plot function to plot implicit equations / inequalities. Arguments ========= - expr : The equation / inequality that is to be plotted. - x_var (optional) : symbol to plot on x-axis or tuple giving symbol and range as ``(symbol, xmin, xmax)`` - y_var (optional) : symbol to plot on y-axis or tuple giving symbol and range as ``(symbol, ymin, ymax)`` If neither ``x_var`` nor ``y_var`` are given then the free symbols in the expression will be assigned in the order they are sorted. The following keyword arguments can also be used: - ``adaptive`` Boolean. The default value is set to True. It has to be set to False if you want to use a mesh grid. - ``depth`` integer. The depth of recursion for adaptive mesh grid. Default value is 0. Takes value in the range (0, 4). - ``points`` integer. The number of points if adaptive mesh grid is not used. Default value is 300. - ``show`` Boolean. Default value is True. If set to False, the plot will not be shown. See ``Plot`` for further information. - ``title`` string. The title for the plot. - ``xlabel`` string. The label for the x-axis - ``ylabel`` string. The label for the y-axis Aesthetics options: - ``line_color``: float or string. Specifies the color for the plot. See ``Plot`` to see how to set color for the plots. Default value is "Blue" plot_implicit, by default, uses interval arithmetic to plot functions. If the expression cannot be plotted using interval arithmetic, it defaults to a generating a contour using a mesh grid of fixed number of points. By setting adaptive to False, you can force plot_implicit to use the mesh grid. The mesh grid method can be effective when adaptive plotting using interval arithmetic, fails to plot with small line width. Examples ======== Plot expressions: .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import plot_implicit, symbols, Eq, And >>> x, y = symbols('x y') Without any ranges for the symbols in the expression: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p1 = plot_implicit(Eq(x**2 + y**2, 5)) With the range for the symbols: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p2 = plot_implicit( ... Eq(x**2 + y**2, 3), (x, -3, 3), (y, -3, 3)) With depth of recursion as argument: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p3 = plot_implicit( ... Eq(x**2 + y**2, 5), (x, -4, 4), (y, -4, 4), depth = 2) Using mesh grid and not using adaptive meshing: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p4 = plot_implicit( ... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2), ... adaptive=False) Using mesh grid without using adaptive meshing with number of points specified: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p5 = plot_implicit( ... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2), ... adaptive=False, points=400) Plotting regions: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p6 = plot_implicit(y > x**2) Plotting Using boolean conjunctions: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p7 = plot_implicit(And(y > x, y > -x)) When plotting an expression with a single variable (y - 1, for example), specify the x or the y variable explicitly: .. plot:: :context: close-figs :format: doctest :include-source: True >>> p8 = plot_implicit(y - 1, y_var=y) >>> p9 = plot_implicit(x - 1, x_var=x) """ has_equality = False # Represents whether the expression contains an Equality, #GreaterThan or LessThan def arg_expand(bool_expr): """ Recursively expands the arguments of an Boolean Function """ for arg in bool_expr.args: if isinstance(arg, BooleanFunction): arg_expand(arg) elif isinstance(arg, Relational): arg_list.append(arg) arg_list = [] if isinstance(expr, BooleanFunction): arg_expand(expr) #Check whether there is an equality in the expression provided. if any(isinstance(e, (Equality, GreaterThan, LessThan)) for e in arg_list): has_equality = True elif not isinstance(expr, Relational): expr = Eq(expr, 0) has_equality = True elif isinstance(expr, (Equality, GreaterThan, LessThan)): has_equality = True xyvar = [i for i in (x_var, y_var) if i is not None] free_symbols = expr.free_symbols range_symbols = Tuple(*flatten(xyvar)).free_symbols undeclared = free_symbols - range_symbols if len(free_symbols & range_symbols) > 2: raise NotImplementedError("Implicit plotting is not implemented for " "more than 2 variables") #Create default ranges if the range is not provided. default_range = Tuple(-5, 5) def _range_tuple(s): if isinstance(s, Symbol): return Tuple(s) + default_range if len(s) == 3: return Tuple(*s) raise ValueError('symbol or `(symbol, min, max)` expected but got %s' % s) if len(xyvar) == 0: xyvar = list(_sort_gens(free_symbols)) var_start_end_x = _range_tuple(xyvar[0]) x = var_start_end_x[0] if len(xyvar) != 2: if x in undeclared or not undeclared: xyvar.append(Dummy('f(%s)' % x.name)) else: xyvar.append(undeclared.pop()) var_start_end_y = _range_tuple(xyvar[1]) #Check whether the depth is greater than 4 or less than 0. if depth > 4: depth = 4 elif depth < 0: depth = 0 series_argument = ImplicitSeries(expr, var_start_end_x, var_start_end_y, has_equality, adaptive, depth, points, line_color) #set the x and y limits kwargs['xlim'] = tuple(float(x) for x in var_start_end_x[1:]) kwargs['ylim'] = tuple(float(y) for y in var_start_end_y[1:]) # set the x and y labels kwargs.setdefault('xlabel', var_start_end_x[0]) kwargs.setdefault('ylabel', var_start_end_y[0]) p = Plot(series_argument, **kwargs) if show: p.show() return p
7058d497c225aa724841544b241c6191594b88b13317e3f9c5d3b8701bbcc743
from typing import Tuple as tTuple from sympy.core.add import Add from sympy.core.cache import cacheit from sympy.core.expr import Expr from sympy.core.function import Function, ArgumentIndexError, PoleError, expand_mul from sympy.core.logic import fuzzy_not, fuzzy_or, FuzzyBool, fuzzy_and from sympy.core.mod import Mod from sympy.core.numbers import igcdex, Rational, pi, Integer, Float from sympy.core.relational import Ne, Eq from sympy.core.singleton import S from sympy.core.symbol import Symbol, Dummy from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial, RisingFactorial from sympy.functions.combinatorial.numbers import bernoulli, euler from sympy.functions.elementary.complexes import arg as arg_f, im, re from sympy.functions.elementary.exponential import log, exp from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt, Min, Max from sympy.functions.elementary.piecewise import Piecewise from sympy.logic.boolalg import And from sympy.ntheory import factorint from sympy.polys.specialpolys import symmetric_poly from sympy.utilities.iterables import numbered_symbols ############################################################################### ########################## UTILITIES ########################################## ############################################################################### def _imaginary_unit_as_coefficient(arg): """ Helper to extract symbolic coefficient for imaginary unit """ if isinstance(arg, Float): return None else: return arg.as_coefficient(S.ImaginaryUnit) ############################################################################### ########################## TRIGONOMETRIC FUNCTIONS ############################ ############################################################################### class TrigonometricFunction(Function): """Base class for trigonometric functions. """ unbranched = True _singularities = (S.ComplexInfinity,) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational and fuzzy_not(s.args[0].is_zero): return False else: return s.is_rational def _eval_is_algebraic(self): s = self.func(*self.args) if s.func == self.func: if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic: return False pi_coeff = _pi_coeff(self.args[0]) if pi_coeff is not None and pi_coeff.is_rational: return True else: return s.is_algebraic def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=deep, **hints) return re_part + im_part*S.ImaginaryUnit def _as_real_imag(self, deep=True, **hints): if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.args[0].expand(deep, **hints), S.Zero) else: return (self.args[0], S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() return (re, im) def _period(self, general_period, symbol=None): f = expand_mul(self.args[0]) if symbol is None: symbol = tuple(f.free_symbols)[0] if not f.has(symbol): return S.Zero if f == symbol: return general_period if symbol in f.free_symbols: if f.is_Mul: g, h = f.as_independent(symbol) if h == symbol: return general_period/abs(g) if f.is_Add: a, h = f.as_independent(symbol) g, h = h.as_independent(symbol, as_Add=False) if h == symbol: return general_period/abs(g) raise NotImplementedError("Use the periodicity function instead.") @cacheit def _table2(): # If nested sqrt's are worse than un-evaluation # you can require q to be in (1, 2, 3, 4, 6, 12) # q <= 12, q=15, q=20, q=24, q=30, q=40, q=60, q=120 return # expressions with 2 or fewer sqrt nestings. return { 12: (3, 4), 20: (4, 5), 30: (5, 6), 15: (6, 10), 24: (6, 8), 40: (8, 10), 60: (20, 30), 120: (40, 60) } def _peeloff_pi(arg): r""" Split ARG into two parts, a "rest" and a multiple of $\pi$. This assumes ARG to be an Add. The multiple of $\pi$ returned in the second position is always a Rational. Examples ======== >>> from sympy.functions.elementary.trigonometric import _peeloff_pi >>> from sympy import pi >>> from sympy.abc import x, y >>> _peeloff_pi(x + pi/2) (x, 1/2) >>> _peeloff_pi(x + 2*pi/3 + pi*y) (x + pi*y + pi/6, 1/2) """ pi_coeff = S.Zero rest_terms = [] for a in Add.make_args(arg): K = a.coeff(pi) if K and K.is_rational: pi_coeff += K else: rest_terms.append(a) if pi_coeff is S.Zero: return arg, S.Zero m1 = (pi_coeff % S.Half) m2 = pi_coeff - m1 if m2.is_integer or ((2*m2).is_integer and m2.is_even is False): return Add(*(rest_terms + [m1*pi])), m2 return arg, S.Zero def _pi_coeff(arg, cycles=1): r""" When arg is a Number times $\pi$ (e.g. $3\pi/2$) then return the Number normalized to be in the range $[0, 2]$, else `None`. When an even multiple of $\pi$ is encountered, if it is multiplying something with known parity then the multiple is returned as 0 otherwise as 2. Examples ======== >>> from sympy.functions.elementary.trigonometric import _pi_coeff >>> from sympy import pi, Dummy >>> from sympy.abc import x >>> _pi_coeff(3*x*pi) 3*x >>> _pi_coeff(11*pi/7) 11/7 >>> _pi_coeff(-11*pi/7) 3/7 >>> _pi_coeff(4*pi) 0 >>> _pi_coeff(5*pi) 1 >>> _pi_coeff(5.0*pi) 1 >>> _pi_coeff(5.5*pi) 3/2 >>> _pi_coeff(2 + pi) >>> _pi_coeff(2*Dummy(integer=True)*pi) 2 >>> _pi_coeff(2*Dummy(even=True)*pi) 0 """ if arg is pi: return S.One elif not arg: return S.Zero elif arg.is_Mul: cx = arg.coeff(pi) if cx: c, x = cx.as_coeff_Mul() # pi is not included as coeff if c.is_Float: # recast exact binary fractions to Rationals f = abs(c) % 1 if f != 0: p = -int(round(log(f, 2).evalf())) m = 2**p cm = c*m i = int(cm) if i == cm: c = Rational(i, m) cx = c*x else: c = Rational(int(c)) cx = c*x if x.is_integer: c2 = c % 2 if c2 == 1: return x elif not c2: if x.is_even is not None: # known parity return S.Zero return Integer(2) else: return c2*x return cx elif arg.is_zero: return S.Zero @cacheit def _cospi257(): """ Express cos(pi/257) explicitly as a function of radicals Based upon the equations in http://math.stackexchange.com/questions/516142/how-does-cos2-pi-257-look-like-in-real-radicals See also https://r-knott.surrey.ac.uk/Fibonacci/simpleTrig.html """ def f1(a, b): return (a + sqrt(a**2 + b))/2, (a - sqrt(a**2 + b))/2 def f2(a, b): return (a - sqrt(a**2 + b))/2 t1, t2 = f1(-1, 256) z1, z3 = f1(t1, 64) z2, z4 = f1(t2, 64) y1, y5 = f1(z1, 4*(5 + t1 + 2*z1)) y6, y2 = f1(z2, 4*(5 + t2 + 2*z2)) y3, y7 = f1(z3, 4*(5 + t1 + 2*z3)) y8, y4 = f1(z4, 4*(5 + t2 + 2*z4)) x1, x9 = f1(y1, -4*(t1 + y1 + y3 + 2*y6)) x2, x10 = f1(y2, -4*(t2 + y2 + y4 + 2*y7)) x3, x11 = f1(y3, -4*(t1 + y3 + y5 + 2*y8)) x4, x12 = f1(y4, -4*(t2 + y4 + y6 + 2*y1)) x5, x13 = f1(y5, -4*(t1 + y5 + y7 + 2*y2)) x6, x14 = f1(y6, -4*(t2 + y6 + y8 + 2*y3)) x15, x7 = f1(y7, -4*(t1 + y7 + y1 + 2*y4)) x8, x16 = f1(y8, -4*(t2 + y8 + y2 + 2*y5)) v1 = f2(x1, -4*(x1 + x2 + x3 + x6)) v2 = f2(x2, -4*(x2 + x3 + x4 + x7)) v3 = f2(x8, -4*(x8 + x9 + x10 + x13)) v4 = f2(x9, -4*(x9 + x10 + x11 + x14)) v5 = f2(x10, -4*(x10 + x11 + x12 + x15)) v6 = f2(x16, -4*(x16 + x1 + x2 + x5)) u1 = -f2(-v1, -4*(v2 + v3)) u2 = -f2(-v4, -4*(v5 + v6)) w1 = -2*f2(-u1, -4*u2) return sqrt(sqrt(2)*sqrt(w1 + 4)/8 + S.Half) @cacheit def _cos_sqrt_cst_table_some(): return { 3: S.Half, 5: (sqrt(5) + 1) / 4, 17: sqrt((15 + sqrt(17)) / 32 + sqrt(2) * (sqrt(17 - sqrt(17)) + sqrt(sqrt(2) * (-8 * sqrt(17 + sqrt(17)) - (1 - sqrt(17)) * sqrt(17 - sqrt(17))) + 6 * sqrt(17) + 34)) / 32), 257: _cospi257() # 65537 is the only other known Fermat prime and the very # large expression is intentionally omitted from SymPy; see # https://r-knott.surrey.ac.uk/Fibonacci/simpleTrig.html } class sin(TrigonometricFunction): r""" The sine function. Returns the sine of x (measured in radians). Explanation =========== This function will evaluate automatically in the case $x/\pi$ is some rational number [4]_. For example, if $x$ is a multiple of $\pi$, $\pi/2$, $\pi/3$, $\pi/4$, and $\pi/6$. Examples ======== >>> from sympy import sin, pi >>> from sympy.abc import x >>> sin(x**2).diff(x) 2*x*cos(x**2) >>> sin(1).diff(x) 0 >>> sin(pi) 0 >>> sin(pi/2) 1 >>> sin(pi/6) 1/2 >>> sin(pi/12) -sqrt(2)/4 + sqrt(6)/4 See Also ======== csc, cos, sec, tan, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Sin .. [4] http://mathworld.wolfram.com/TrigonometryAngles.html """ def period(self, symbol=None): return self._period(2*pi, symbol) def fdiff(self, argindex=1): if argindex == 1: return cos(self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.calculus.accumulationbounds import AccumBounds from sympy.sets.setexpr import SetExpr if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.Zero elif arg in (S.Infinity, S.NegativeInfinity): return AccumBounds(-1, 1) if arg is S.ComplexInfinity: return S.NaN if isinstance(arg, AccumBounds): from sympy.sets.sets import FiniteSet min, max = arg.min, arg.max d = floor(min/(2*pi)) if min is not S.NegativeInfinity: min = min - d*2*pi if max is not S.Infinity: max = max - d*2*pi if AccumBounds(min, max).intersection(FiniteSet(pi/2, pi*Rational(5, 2))) \ is not S.EmptySet and \ AccumBounds(min, max).intersection(FiniteSet(pi*Rational(3, 2), pi*Rational(7, 2))) is not S.EmptySet: return AccumBounds(-1, 1) elif AccumBounds(min, max).intersection(FiniteSet(pi/2, pi*Rational(5, 2))) \ is not S.EmptySet: return AccumBounds(Min(sin(min), sin(max)), 1) elif AccumBounds(min, max).intersection(FiniteSet(pi*Rational(3, 2), pi*Rational(8, 2))) \ is not S.EmptySet: return AccumBounds(-1, Max(sin(min), sin(max))) else: return AccumBounds(Min(sin(min), sin(max)), Max(sin(min), sin(max))) elif isinstance(arg, SetExpr): return arg._eval_func(cls) if arg.could_extract_minus_sign(): return -cls(-arg) i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import sinh return S.ImaginaryUnit*sinh(i_coeff) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_integer: return S.Zero if (2*pi_coeff).is_integer: # is_even-case handled above as then pi_coeff.is_integer, # so check if known to be not even if pi_coeff.is_even is False: return S.NegativeOne**(pi_coeff - S.Half) if not pi_coeff.is_Rational: narg = pi_coeff*pi if narg != arg: return cls(narg) return None # https://github.com/sympy/sympy/issues/6048 # transform a sine to a cosine, to avoid redundant code if pi_coeff.is_Rational: x = pi_coeff % 2 if x > 1: return -cls((x % 1)*pi) if 2*x > 1: return cls((1 - x)*pi) narg = ((pi_coeff + Rational(3, 2)) % 2)*pi result = cos(narg) if not isinstance(result, cos): return result if pi_coeff*pi != arg: return cls(pi_coeff*pi) return None if arg.is_Add: x, m = _peeloff_pi(arg) if m: m = m*pi return sin(m)*cos(x) + cos(m)*sin(x) if arg.is_zero: return S.Zero if isinstance(arg, asin): return arg.args[0] if isinstance(arg, atan): x = arg.args[0] return x/sqrt(1 + x**2) if isinstance(arg, atan2): y, x = arg.args return y/sqrt(x**2 + y**2) if isinstance(arg, acos): x = arg.args[0] return sqrt(1 - x**2) if isinstance(arg, acot): x = arg.args[0] return 1/(sqrt(1 + 1/x**2)*x) if isinstance(arg, acsc): x = arg.args[0] return 1/x if isinstance(arg, asec): x = arg.args[0] return sqrt(1 - 1/x**2) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 2: p = previous_terms[-2] return -p*x**2/(n*(n - 1)) else: return S.NegativeOne**(n//2)*x**n/factorial(n) def _eval_nseries(self, x, n, logx, cdir=0): arg = self.args[0] if logx is not None: arg = arg.subs(log(x), logx) if arg.subs(x, 0).has(S.NaN, S.ComplexInfinity): raise PoleError("Cannot expand %s around 0" % (self)) return Function._eval_nseries(self, x, n=n, logx=logx, cdir=cdir) def _eval_rewrite_as_exp(self, arg, **kwargs): from sympy.functions.elementary.hyperbolic import HyperbolicFunction I = S.ImaginaryUnit if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) return (exp(arg*I) - exp(-arg*I))/(2*I) def _eval_rewrite_as_Pow(self, arg, **kwargs): if isinstance(arg, log): I = S.ImaginaryUnit x = arg.args[0] return I*x**-I/2 - I*x**I /2 def _eval_rewrite_as_cos(self, arg, **kwargs): return cos(arg - pi/2, evaluate=False) def _eval_rewrite_as_tan(self, arg, **kwargs): tan_half = tan(S.Half*arg) return 2*tan_half/(1 + tan_half**2) def _eval_rewrite_as_sincos(self, arg, **kwargs): return sin(arg)*cos(arg)/cos(arg) def _eval_rewrite_as_cot(self, arg, **kwargs): cot_half = cot(S.Half*arg) return Piecewise((0, And(Eq(im(arg), 0), Eq(Mod(arg, pi), 0))), (2*cot_half/(1 + cot_half**2), True)) def _eval_rewrite_as_pow(self, arg, **kwargs): return self.rewrite(cos).rewrite(pow) def _eval_rewrite_as_sqrt(self, arg, **kwargs): return self.rewrite(cos).rewrite(sqrt) def _eval_rewrite_as_csc(self, arg, **kwargs): return 1/csc(arg) def _eval_rewrite_as_sec(self, arg, **kwargs): return 1/sec(arg - pi/2, evaluate=False) def _eval_rewrite_as_sinc(self, arg, **kwargs): return arg*sinc(arg) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): from sympy.functions.elementary.hyperbolic import cosh, sinh re, im = self._as_real_imag(deep=deep, **hints) return (sin(re)*cosh(im), cos(re)*sinh(im)) def _eval_expand_trig(self, **hints): from sympy.functions.special.polynomials import chebyshevt, chebyshevu arg = self.args[0] x = None if arg.is_Add: # TODO, implement more if deep stuff here # TODO: Do this more efficiently for more than two terms x, y = arg.as_two_terms() sx = sin(x, evaluate=False)._eval_expand_trig() sy = sin(y, evaluate=False)._eval_expand_trig() cx = cos(x, evaluate=False)._eval_expand_trig() cy = cos(y, evaluate=False)._eval_expand_trig() return sx*cy + sy*cx elif arg.is_Mul: n, x = arg.as_coeff_Mul(rational=True) if n.is_Integer: # n will be positive because of .eval # canonicalization # See http://mathworld.wolfram.com/Multiple-AngleFormulas.html if n.is_odd: return S.NegativeOne**((n - 1)/2)*chebyshevt(n, sin(x)) else: return expand_mul(S.NegativeOne**(n/2 - 1)*cos(x)* chebyshevu(n - 1, sin(x)), deep=False) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_Rational: return self.rewrite(sqrt) return sin(arg) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.accumulationbounds import AccumBounds arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = x0/pi if n.is_integer: lt = (arg - n*pi).as_leading_term(x) return (S.NegativeOne**n)*lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in [S.Infinity, S.NegativeInfinity]: return AccumBounds(-1, 1) return self.func(x0) if x0.is_finite else self def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def _eval_is_finite(self): arg = self.args[0] if arg.is_extended_real: return True def _eval_is_zero(self): rest, pi_mult = _peeloff_pi(self.args[0]) if rest.is_zero: return pi_mult.is_integer def _eval_is_complex(self): if self.args[0].is_extended_real \ or self.args[0].is_complex: return True class cos(TrigonometricFunction): """ The cosine function. Returns the cosine of x (measured in radians). Explanation =========== See :func:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import cos, pi >>> from sympy.abc import x >>> cos(x**2).diff(x) -2*x*sin(x**2) >>> cos(1).diff(x) 0 >>> cos(pi) -1 >>> cos(pi/2) 0 >>> cos(2*pi/3) -1/2 >>> cos(pi/12) sqrt(2)/4 + sqrt(6)/4 See Also ======== sin, csc, sec, tan, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Cos """ def period(self, symbol=None): return self._period(2*pi, symbol) def fdiff(self, argindex=1): if argindex == 1: return -sin(self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.functions.special.polynomials import chebyshevt from sympy.calculus.accumulationbounds import AccumBounds from sympy.sets.setexpr import SetExpr if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.One elif arg in (S.Infinity, S.NegativeInfinity): # In this case it is better to return AccumBounds(-1, 1) # rather than returning S.NaN, since AccumBounds(-1, 1) # preserves the information that sin(oo) is between # -1 and 1, where S.NaN does not do that. return AccumBounds(-1, 1) if arg is S.ComplexInfinity: return S.NaN if isinstance(arg, AccumBounds): return sin(arg + pi/2) elif isinstance(arg, SetExpr): return arg._eval_func(cls) if arg.is_extended_real and arg.is_finite is False: return AccumBounds(-1, 1) if arg.could_extract_minus_sign(): return cls(-arg) i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import cosh return cosh(i_coeff) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_integer: return (S.NegativeOne)**pi_coeff if (2*pi_coeff).is_integer: # is_even-case handled above as then pi_coeff.is_integer, # so check if known to be not even if pi_coeff.is_even is False: return S.Zero if not pi_coeff.is_Rational: narg = pi_coeff*pi if narg != arg: return cls(narg) return None # cosine formula ##################### # https://github.com/sympy/sympy/issues/6048 # explicit calculations are performed for # cos(k pi/n) for n = 8,10,12,15,20,24,30,40,60,120 # Some other exact values like cos(k pi/240) can be # calculated using a partial-fraction decomposition # by calling cos( X ).rewrite(sqrt) if pi_coeff.is_Rational: q = pi_coeff.q p = pi_coeff.p % (2*q) if p > q: narg = (pi_coeff - 1)*pi return -cls(narg) if 2*p > q: narg = (1 - pi_coeff)*pi return -cls(narg) # If nested sqrt's are worse than un-evaluation # you can require q to be in (1, 2, 3, 4, 6, 12) # q <= 12, q=15, q=20, q=24, q=30, q=40, q=60, q=120 return # expressions with 2 or fewer sqrt nestings. table2 = _table2() if q in table2: a, b = table2[q] a, b = p*pi/a, p*pi/b nvala, nvalb = cls(a), cls(b) if None in (nvala, nvalb): return None return nvala*nvalb + cls(pi/2 - a)*cls(pi/2 - b) if q > 12: return None cst_table_some = { 3: S.Half, 5: (sqrt(5) + 1) / 4, } if q in cst_table_some: cts = cst_table_some[pi_coeff.q] return chebyshevt(pi_coeff.p, cts).expand() if 0 == q % 2: narg = (pi_coeff*2)*pi nval = cls(narg) if None == nval: return None x = (2*pi_coeff + 1)/2 sign_cos = (-1)**((-1 if x < 0 else 1)*int(abs(x))) return sign_cos*sqrt( (1 + nval)/2 ) return None if arg.is_Add: x, m = _peeloff_pi(arg) if m: m = m*pi return cos(m)*cos(x) - sin(m)*sin(x) if arg.is_zero: return S.One if isinstance(arg, acos): return arg.args[0] if isinstance(arg, atan): x = arg.args[0] return 1/sqrt(1 + x**2) if isinstance(arg, atan2): y, x = arg.args return x/sqrt(x**2 + y**2) if isinstance(arg, asin): x = arg.args[0] return sqrt(1 - x ** 2) if isinstance(arg, acot): x = arg.args[0] return 1/sqrt(1 + 1/x**2) if isinstance(arg, acsc): x = arg.args[0] return sqrt(1 - 1/x**2) if isinstance(arg, asec): x = arg.args[0] return 1/x @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2: p = previous_terms[-2] return -p*x**2/(n*(n - 1)) else: return S.NegativeOne**(n//2)*x**n/factorial(n) def _eval_nseries(self, x, n, logx, cdir=0): arg = self.args[0] if logx is not None: arg = arg.subs(log(x), logx) if arg.subs(x, 0).has(S.NaN, S.ComplexInfinity): raise PoleError("Cannot expand %s around 0" % (self)) return Function._eval_nseries(self, x, n=n, logx=logx, cdir=cdir) def _eval_rewrite_as_exp(self, arg, **kwargs): I = S.ImaginaryUnit from sympy.functions.elementary.hyperbolic import HyperbolicFunction if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) return (exp(arg*I) + exp(-arg*I))/2 def _eval_rewrite_as_Pow(self, arg, **kwargs): if isinstance(arg, log): I = S.ImaginaryUnit x = arg.args[0] return x**I/2 + x**-I/2 def _eval_rewrite_as_sin(self, arg, **kwargs): return sin(arg + pi/2, evaluate=False) def _eval_rewrite_as_tan(self, arg, **kwargs): tan_half = tan(S.Half*arg)**2 return (1 - tan_half)/(1 + tan_half) def _eval_rewrite_as_sincos(self, arg, **kwargs): return sin(arg)*cos(arg)/sin(arg) def _eval_rewrite_as_cot(self, arg, **kwargs): cot_half = cot(S.Half*arg)**2 return Piecewise((1, And(Eq(im(arg), 0), Eq(Mod(arg, 2*pi), 0))), ((cot_half - 1)/(cot_half + 1), True)) def _eval_rewrite_as_pow(self, arg, **kwargs): return self._eval_rewrite_as_sqrt(arg) def _eval_rewrite_as_sqrt(self, arg, **kwargs): from sympy.functions.special.polynomials import chebyshevt def migcdex(x): # recursive calcuation of gcd and linear combination # for a sequence of integers. # Given (x1, x2, x3) # Returns (y1, y1, y3, g) # such that g is the gcd and x1*y1+x2*y2+x3*y3 - g = 0 # Note, that this is only one such linear combination. if len(x) == 1: return (1, x[0]) if len(x) == 2: return igcdex(x[0], x[-1]) g = migcdex(x[1:]) u, v, h = igcdex(x[0], g[-1]) return tuple([u] + [v*i for i in g[0:-1] ] + [h]) def ipartfrac(r, factors=None): if isinstance(r, int): return r if not isinstance(r, Rational): raise TypeError("r is not rational") n = r.q if 2 > r.q*r.q: return r.q if None == factors: a = [n//x**y for x, y in factorint(r.q).items()] else: a = [n//x for x in factors] if len(a) == 1: return [ r ] h = migcdex(a) ans = [ r.p*Rational(i*j, r.q) for i, j in zip(h[:-1], a) ] assert r == sum(ans) return ans pi_coeff = _pi_coeff(arg) if pi_coeff is None: return None if pi_coeff.is_integer: # it was unevaluated return self.func(pi_coeff*pi) if not pi_coeff.is_Rational: return None cst_table_some = _cos_sqrt_cst_table_some() if pi_coeff.q in cst_table_some: rv = chebyshevt(pi_coeff.p, cst_table_some[pi_coeff.q]) if pi_coeff.q < 257: rv = rv.expand() return rv if not pi_coeff.q % 2: # recursively remove factors of 2 pico2 = pi_coeff*2 nval = cos(pico2*pi).rewrite(sqrt) x = (pico2 + 1)/2 sign_cos = -1 if int(x) % 2 else 1 return sign_cos*sqrt( (1 + nval)/2 ) def _fermatCoords(n): # if n can be factored in terms of Fermat primes with # multiplicity of each being 1, return those primes, else # False primes = [] for p_i in cst_table_some: quotient, remainder = divmod(n, p_i) if remainder == 0: n = quotient primes.append(p_i) if n == 1: return tuple(primes) return False FC = _fermatCoords(pi_coeff.q) if FC: decomp = ipartfrac(pi_coeff, FC) X = [(x[1], x[0]*pi) for x in zip(decomp, numbered_symbols('z'))] pcls = cos(sum([x[0] for x in X]))._eval_expand_trig().subs(X) return pcls.rewrite(sqrt) else: decomp = ipartfrac(pi_coeff) X = [(x[1], x[0]*pi) for x in zip(decomp, numbered_symbols('z'))] pcls = cos(sum([x[0] for x in X]))._eval_expand_trig().subs(X) return pcls def _eval_rewrite_as_sec(self, arg, **kwargs): return 1/sec(arg) def _eval_rewrite_as_csc(self, arg, **kwargs): return 1/sec(arg).rewrite(csc) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): from sympy.functions.elementary.hyperbolic import cosh, sinh re, im = self._as_real_imag(deep=deep, **hints) return (cos(re)*cosh(im), -sin(re)*sinh(im)) def _eval_expand_trig(self, **hints): from sympy.functions.special.polynomials import chebyshevt arg = self.args[0] x = None if arg.is_Add: # TODO: Do this more efficiently for more than two terms x, y = arg.as_two_terms() sx = sin(x, evaluate=False)._eval_expand_trig() sy = sin(y, evaluate=False)._eval_expand_trig() cx = cos(x, evaluate=False)._eval_expand_trig() cy = cos(y, evaluate=False)._eval_expand_trig() return cx*cy - sx*sy elif arg.is_Mul: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff.is_Integer: return chebyshevt(coeff, cos(terms)) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_Rational: return self.rewrite(sqrt) return cos(arg) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.accumulationbounds import AccumBounds arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = (x0 + pi/2)/pi if n.is_integer: lt = (arg - n*pi + pi/2).as_leading_term(x) return (S.NegativeOne**n)*lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in [S.Infinity, S.NegativeInfinity]: return AccumBounds(-1, 1) return self.func(x0) if x0.is_finite else self def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def _eval_is_finite(self): arg = self.args[0] if arg.is_extended_real: return True def _eval_is_complex(self): if self.args[0].is_extended_real \ or self.args[0].is_complex: return True def _eval_is_zero(self): rest, pi_mult = _peeloff_pi(self.args[0]) if pi_mult: return fuzzy_and([(pi_mult - S.Half).is_integer, rest.is_zero]) else: return rest.is_zero class tan(TrigonometricFunction): """ The tangent function. Returns the tangent of x (measured in radians). Explanation =========== See :class:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import tan, pi >>> from sympy.abc import x >>> tan(x**2).diff(x) 2*x*(tan(x**2)**2 + 1) >>> tan(1).diff(x) 0 >>> tan(pi/8).expand() -1 + sqrt(2) See Also ======== sin, csc, cos, sec, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Tan """ def period(self, symbol=None): return self._period(pi, symbol) def fdiff(self, argindex=1): if argindex == 1: return S.One + self**2 else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return atan @classmethod def eval(cls, arg): from sympy.calculus.accumulationbounds import AccumBounds if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.Zero elif arg in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) if arg is S.ComplexInfinity: return S.NaN if isinstance(arg, AccumBounds): min, max = arg.min, arg.max d = floor(min/pi) if min is not S.NegativeInfinity: min = min - d*pi if max is not S.Infinity: max = max - d*pi from sympy.sets.sets import FiniteSet if AccumBounds(min, max).intersection(FiniteSet(pi/2, pi*Rational(3, 2))): return AccumBounds(S.NegativeInfinity, S.Infinity) else: return AccumBounds(tan(min), tan(max)) if arg.could_extract_minus_sign(): return -cls(-arg) i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import tanh return S.ImaginaryUnit*tanh(i_coeff) pi_coeff = _pi_coeff(arg, 2) if pi_coeff is not None: if pi_coeff.is_integer: return S.Zero if not pi_coeff.is_Rational: narg = pi_coeff*pi if narg != arg: return cls(narg) return None if pi_coeff.is_Rational: q = pi_coeff.q p = pi_coeff.p % q # ensure simplified results are returned for n*pi/5, n*pi/10 table10 = { 1: sqrt(1 - 2*sqrt(5)/5), 2: sqrt(5 - 2*sqrt(5)), 3: sqrt(1 + 2*sqrt(5)/5), 4: sqrt(5 + 2*sqrt(5)) } if q in (5, 10): n = 10*p/q if n > 5: n = 10 - n return -table10[n] else: return table10[n] if not pi_coeff.q % 2: narg = pi_coeff*pi*2 cresult, sresult = cos(narg), cos(narg - pi/2) if not isinstance(cresult, cos) \ and not isinstance(sresult, cos): if sresult == 0: return S.ComplexInfinity return 1/sresult - cresult/sresult table2 = _table2() if q in table2: a, b = table2[q] nvala, nvalb = cls(p*pi/a), cls(p*pi/b) if None in (nvala, nvalb): return None return (nvala - nvalb)/(1 + nvala*nvalb) narg = ((pi_coeff + S.Half) % 1 - S.Half)*pi # see cos() to specify which expressions should be # expanded automatically in terms of radicals cresult, sresult = cos(narg), cos(narg - pi/2) if not isinstance(cresult, cos) \ and not isinstance(sresult, cos): if cresult == 0: return S.ComplexInfinity return (sresult/cresult) if narg != arg: return cls(narg) if arg.is_Add: x, m = _peeloff_pi(arg) if m: tanm = tan(m*pi) if tanm is S.ComplexInfinity: return -cot(x) else: # tanm == 0 return tan(x) if arg.is_zero: return S.Zero if isinstance(arg, atan): return arg.args[0] if isinstance(arg, atan2): y, x = arg.args return y/x if isinstance(arg, asin): x = arg.args[0] return x/sqrt(1 - x**2) if isinstance(arg, acos): x = arg.args[0] return sqrt(1 - x**2)/x if isinstance(arg, acot): x = arg.args[0] return 1/x if isinstance(arg, acsc): x = arg.args[0] return 1/(sqrt(1 - 1/x**2)*x) if isinstance(arg, asec): x = arg.args[0] return sqrt(1 - 1/x**2)*x @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) a, b = ((n - 1)//2), 2**(n + 1) B = bernoulli(n + 1) F = factorial(n + 1) return S.NegativeOne**a*b*(b - 1)*B/F*x**n def _eval_nseries(self, x, n, logx, cdir=0): i = self.args[0].limit(x, 0)*2/pi if i and i.is_Integer: return self.rewrite(cos)._eval_nseries(x, n=n, logx=logx) return Function._eval_nseries(self, x, n=n, logx=logx) def _eval_rewrite_as_Pow(self, arg, **kwargs): if isinstance(arg, log): I = S.ImaginaryUnit x = arg.args[0] return I*(x**-I - x**I)/(x**-I + x**I) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): re, im = self._as_real_imag(deep=deep, **hints) if im: from sympy.functions.elementary.hyperbolic import cosh, sinh denom = cos(2*re) + cosh(2*im) return (sin(2*re)/denom, sinh(2*im)/denom) else: return (self.func(re), S.Zero) def _eval_expand_trig(self, **hints): arg = self.args[0] x = None if arg.is_Add: n = len(arg.args) TX = [] for x in arg.args: tx = tan(x, evaluate=False)._eval_expand_trig() TX.append(tx) Yg = numbered_symbols('Y') Y = [ next(Yg) for i in range(n) ] p = [0, 0] for i in range(n + 1): p[1 - i % 2] += symmetric_poly(i, Y)*(-1)**((i % 4)//2) return (p[0]/p[1]).subs(list(zip(Y, TX))) elif arg.is_Mul: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff.is_Integer and coeff > 1: I = S.ImaginaryUnit z = Symbol('dummy', real=True) P = ((1 + I*z)**coeff).expand() return (im(P)/re(P)).subs([(z, tan(terms))]) return tan(arg) def _eval_rewrite_as_exp(self, arg, **kwargs): I = S.ImaginaryUnit from sympy.functions.elementary.hyperbolic import HyperbolicFunction if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) neg_exp, pos_exp = exp(-arg*I), exp(arg*I) return I*(neg_exp - pos_exp)/(neg_exp + pos_exp) def _eval_rewrite_as_sin(self, x, **kwargs): return 2*sin(x)**2/sin(2*x) def _eval_rewrite_as_cos(self, x, **kwargs): return cos(x - pi/2, evaluate=False)/cos(x) def _eval_rewrite_as_sincos(self, arg, **kwargs): return sin(arg)/cos(arg) def _eval_rewrite_as_cot(self, arg, **kwargs): return 1/cot(arg) def _eval_rewrite_as_sec(self, arg, **kwargs): sin_in_sec_form = sin(arg).rewrite(sec) cos_in_sec_form = cos(arg).rewrite(sec) return sin_in_sec_form/cos_in_sec_form def _eval_rewrite_as_csc(self, arg, **kwargs): sin_in_csc_form = sin(arg).rewrite(csc) cos_in_csc_form = cos(arg).rewrite(csc) return sin_in_csc_form/cos_in_csc_form def _eval_rewrite_as_pow(self, arg, **kwargs): y = self.rewrite(cos).rewrite(pow) if y.has(cos): return None return y def _eval_rewrite_as_sqrt(self, arg, **kwargs): y = self.rewrite(cos).rewrite(sqrt) if y.has(cos): return None return y def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.accumulationbounds import AccumBounds from sympy.functions.elementary.complexes import re arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = 2*x0/pi if n.is_integer: lt = (arg - n*pi/2).as_leading_term(x) return lt if n.is_even else -1/lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) return self.func(x0) if x0.is_finite else self def _eval_is_extended_real(self): # FIXME: currently tan(pi/2) return zoo return self.args[0].is_extended_real def _eval_is_real(self): arg = self.args[0] if arg.is_real and (arg/pi - S.Half).is_integer is False: return True def _eval_is_finite(self): arg = self.args[0] if arg.is_real and (arg/pi - S.Half).is_integer is False: return True if arg.is_imaginary: return True def _eval_is_zero(self): rest, pi_mult = _peeloff_pi(self.args[0]) if rest.is_zero: return pi_mult.is_integer def _eval_is_complex(self): arg = self.args[0] if arg.is_real and (arg/pi - S.Half).is_integer is False: return True class cot(TrigonometricFunction): """ The cotangent function. Returns the cotangent of x (measured in radians). Explanation =========== See :class:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import cot, pi >>> from sympy.abc import x >>> cot(x**2).diff(x) 2*x*(-cot(x**2)**2 - 1) >>> cot(1).diff(x) 0 >>> cot(pi/12) sqrt(3) + 2 See Also ======== sin, csc, cos, sec, tan asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Cot """ def period(self, symbol=None): return self._period(pi, symbol) def fdiff(self, argindex=1): if argindex == 1: return S.NegativeOne - self**2 else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return acot @classmethod def eval(cls, arg): from sympy.calculus.accumulationbounds import AccumBounds if arg.is_Number: if arg is S.NaN: return S.NaN if arg.is_zero: return S.ComplexInfinity elif arg in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) if arg is S.ComplexInfinity: return S.NaN if isinstance(arg, AccumBounds): return -tan(arg + pi/2) if arg.could_extract_minus_sign(): return -cls(-arg) i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import coth return -S.ImaginaryUnit*coth(i_coeff) pi_coeff = _pi_coeff(arg, 2) if pi_coeff is not None: if pi_coeff.is_integer: return S.ComplexInfinity if not pi_coeff.is_Rational: narg = pi_coeff*pi if narg != arg: return cls(narg) return None if pi_coeff.is_Rational: if pi_coeff.q in (5, 10): return tan(pi/2 - arg) if pi_coeff.q > 2 and not pi_coeff.q % 2: narg = pi_coeff*pi*2 cresult, sresult = cos(narg), cos(narg - pi/2) if not isinstance(cresult, cos) \ and not isinstance(sresult, cos): return 1/sresult + cresult/sresult q = pi_coeff.q p = pi_coeff.p % q table2 = _table2() if q in table2: a, b = table2[q] nvala, nvalb = cls(p*pi/a), cls(p*pi/b) if None in (nvala, nvalb): return None return (1 + nvala*nvalb)/(nvalb - nvala) narg = (((pi_coeff + S.Half) % 1) - S.Half)*pi # see cos() to specify which expressions should be # expanded automatically in terms of radicals cresult, sresult = cos(narg), cos(narg - pi/2) if not isinstance(cresult, cos) \ and not isinstance(sresult, cos): if sresult == 0: return S.ComplexInfinity return cresult/sresult if narg != arg: return cls(narg) if arg.is_Add: x, m = _peeloff_pi(arg) if m: cotm = cot(m*pi) if cotm is S.ComplexInfinity: return cot(x) else: # cotm == 0 return -tan(x) if arg.is_zero: return S.ComplexInfinity if isinstance(arg, acot): return arg.args[0] if isinstance(arg, atan): x = arg.args[0] return 1/x if isinstance(arg, atan2): y, x = arg.args return x/y if isinstance(arg, asin): x = arg.args[0] return sqrt(1 - x**2)/x if isinstance(arg, acos): x = arg.args[0] return x/sqrt(1 - x**2) if isinstance(arg, acsc): x = arg.args[0] return sqrt(1 - 1/x**2)*x if isinstance(arg, asec): x = arg.args[0] return 1/(sqrt(1 - 1/x**2)*x) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return 1/sympify(x) elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) B = bernoulli(n + 1) F = factorial(n + 1) return S.NegativeOne**((n + 1)//2)*2**(n + 1)*B/F*x**n def _eval_nseries(self, x, n, logx, cdir=0): i = self.args[0].limit(x, 0)/pi if i and i.is_Integer: return self.rewrite(cos)._eval_nseries(x, n=n, logx=logx) return self.rewrite(tan)._eval_nseries(x, n=n, logx=logx) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): re, im = self._as_real_imag(deep=deep, **hints) if im: from sympy.functions.elementary.hyperbolic import cosh, sinh denom = cos(2*re) - cosh(2*im) return (-sin(2*re)/denom, sinh(2*im)/denom) else: return (self.func(re), S.Zero) def _eval_rewrite_as_exp(self, arg, **kwargs): from sympy.functions.elementary.hyperbolic import HyperbolicFunction I = S.ImaginaryUnit if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) neg_exp, pos_exp = exp(-arg*I), exp(arg*I) return I*(pos_exp + neg_exp)/(pos_exp - neg_exp) def _eval_rewrite_as_Pow(self, arg, **kwargs): if isinstance(arg, log): I = S.ImaginaryUnit x = arg.args[0] return -I*(x**-I + x**I)/(x**-I - x**I) def _eval_rewrite_as_sin(self, x, **kwargs): return sin(2*x)/(2*(sin(x)**2)) def _eval_rewrite_as_cos(self, x, **kwargs): return cos(x)/cos(x - pi/2, evaluate=False) def _eval_rewrite_as_sincos(self, arg, **kwargs): return cos(arg)/sin(arg) def _eval_rewrite_as_tan(self, arg, **kwargs): return 1/tan(arg) def _eval_rewrite_as_sec(self, arg, **kwargs): cos_in_sec_form = cos(arg).rewrite(sec) sin_in_sec_form = sin(arg).rewrite(sec) return cos_in_sec_form/sin_in_sec_form def _eval_rewrite_as_csc(self, arg, **kwargs): cos_in_csc_form = cos(arg).rewrite(csc) sin_in_csc_form = sin(arg).rewrite(csc) return cos_in_csc_form/sin_in_csc_form def _eval_rewrite_as_pow(self, arg, **kwargs): y = self.rewrite(cos).rewrite(pow) if y.has(cos): return None return y def _eval_rewrite_as_sqrt(self, arg, **kwargs): y = self.rewrite(cos).rewrite(sqrt) if y.has(cos): return None return y def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.accumulationbounds import AccumBounds from sympy.functions.elementary.complexes import re arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = 2*x0/pi if n.is_integer: lt = (arg - n*pi/2).as_leading_term(x) return 1/lt if n.is_even else -lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) return self.func(x0) if x0.is_finite else self def _eval_is_extended_real(self): return self.args[0].is_extended_real def _eval_expand_trig(self, **hints): arg = self.args[0] x = None if arg.is_Add: n = len(arg.args) CX = [] for x in arg.args: cx = cot(x, evaluate=False)._eval_expand_trig() CX.append(cx) Yg = numbered_symbols('Y') Y = [ next(Yg) for i in range(n) ] p = [0, 0] for i in range(n, -1, -1): p[(n - i) % 2] += symmetric_poly(i, Y)*(-1)**(((n - i) % 4)//2) return (p[0]/p[1]).subs(list(zip(Y, CX))) elif arg.is_Mul: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff.is_Integer and coeff > 1: I = S.ImaginaryUnit z = Symbol('dummy', real=True) P = ((z + I)**coeff).expand() return (re(P)/im(P)).subs([(z, cot(terms))]) return cot(arg) # XXX sec and csc return 1/cos and 1/sin def _eval_is_finite(self): arg = self.args[0] if arg.is_real and (arg/pi).is_integer is False: return True if arg.is_imaginary: return True def _eval_is_real(self): arg = self.args[0] if arg.is_real and (arg/pi).is_integer is False: return True def _eval_is_complex(self): arg = self.args[0] if arg.is_real and (arg/pi).is_integer is False: return True def _eval_is_zero(self): rest, pimult = _peeloff_pi(self.args[0]) if pimult and rest.is_zero: return (pimult - S.Half).is_integer def _eval_subs(self, old, new): arg = self.args[0] argnew = arg.subs(old, new) if arg != argnew and (argnew/pi).is_integer: return S.ComplexInfinity return cot(argnew) class ReciprocalTrigonometricFunction(TrigonometricFunction): """Base class for reciprocal functions of trigonometric functions. """ _reciprocal_of = None # mandatory, to be defined in subclass _singularities = (S.ComplexInfinity,) # _is_even and _is_odd are used for correct evaluation of csc(-x), sec(-x) # TODO refactor into TrigonometricFunction common parts of # trigonometric functions eval() like even/odd, func(x+2*k*pi), etc. # optional, to be defined in subclasses: _is_even = None # type: FuzzyBool _is_odd = None # type: FuzzyBool @classmethod def eval(cls, arg): if arg.could_extract_minus_sign(): if cls._is_even: return cls(-arg) if cls._is_odd: return -cls(-arg) pi_coeff = _pi_coeff(arg) if (pi_coeff is not None and not (2*pi_coeff).is_integer and pi_coeff.is_Rational): q = pi_coeff.q p = pi_coeff.p % (2*q) if p > q: narg = (pi_coeff - 1)*pi return -cls(narg) if 2*p > q: narg = (1 - pi_coeff)*pi if cls._is_odd: return cls(narg) elif cls._is_even: return -cls(narg) if hasattr(arg, 'inverse') and arg.inverse() == cls: return arg.args[0] t = cls._reciprocal_of.eval(arg) if t is None: return t elif any(isinstance(i, cos) for i in (t, -t)): return (1/t).rewrite(sec) elif any(isinstance(i, sin) for i in (t, -t)): return (1/t).rewrite(csc) else: return 1/t def _call_reciprocal(self, method_name, *args, **kwargs): # Calls method_name on _reciprocal_of o = self._reciprocal_of(self.args[0]) return getattr(o, method_name)(*args, **kwargs) def _calculate_reciprocal(self, method_name, *args, **kwargs): # If calling method_name on _reciprocal_of returns a value != None # then return the reciprocal of that value t = self._call_reciprocal(method_name, *args, **kwargs) return 1/t if t is not None else t def _rewrite_reciprocal(self, method_name, arg): # Special handling for rewrite functions. If reciprocal rewrite returns # unmodified expression, then return None t = self._call_reciprocal(method_name, arg) if t is not None and t != self._reciprocal_of(arg): return 1/t def _period(self, symbol): f = expand_mul(self.args[0]) return self._reciprocal_of(f).period(symbol) def fdiff(self, argindex=1): return -self._calculate_reciprocal("fdiff", argindex)/self**2 def _eval_rewrite_as_exp(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_exp", arg) def _eval_rewrite_as_Pow(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_Pow", arg) def _eval_rewrite_as_sin(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_sin", arg) def _eval_rewrite_as_cos(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_cos", arg) def _eval_rewrite_as_tan(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_tan", arg) def _eval_rewrite_as_pow(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_pow", arg) def _eval_rewrite_as_sqrt(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_sqrt", arg) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): return (1/self._reciprocal_of(self.args[0])).as_real_imag(deep, **hints) def _eval_expand_trig(self, **hints): return self._calculate_reciprocal("_eval_expand_trig", **hints) def _eval_is_extended_real(self): return self._reciprocal_of(self.args[0])._eval_is_extended_real() def _eval_as_leading_term(self, x, logx=None, cdir=0): return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x) def _eval_is_finite(self): return (1/self._reciprocal_of(self.args[0])).is_finite def _eval_nseries(self, x, n, logx, cdir=0): return (1/self._reciprocal_of(self.args[0]))._eval_nseries(x, n, logx) class sec(ReciprocalTrigonometricFunction): """ The secant function. Returns the secant of x (measured in radians). Explanation =========== See :class:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import sec >>> from sympy.abc import x >>> sec(x**2).diff(x) 2*x*tan(x**2)*sec(x**2) >>> sec(1).diff(x) 0 See Also ======== sin, csc, cos, tan, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Sec """ _reciprocal_of = cos _is_even = True def period(self, symbol=None): return self._period(symbol) def _eval_rewrite_as_cot(self, arg, **kwargs): cot_half_sq = cot(arg/2)**2 return (cot_half_sq + 1)/(cot_half_sq - 1) def _eval_rewrite_as_cos(self, arg, **kwargs): return (1/cos(arg)) def _eval_rewrite_as_sincos(self, arg, **kwargs): return sin(arg)/(cos(arg)*sin(arg)) def _eval_rewrite_as_sin(self, arg, **kwargs): return (1/cos(arg).rewrite(sin)) def _eval_rewrite_as_tan(self, arg, **kwargs): return (1/cos(arg).rewrite(tan)) def _eval_rewrite_as_csc(self, arg, **kwargs): return csc(pi/2 - arg, evaluate=False) def fdiff(self, argindex=1): if argindex == 1: return tan(self.args[0])*sec(self.args[0]) else: raise ArgumentIndexError(self, argindex) def _eval_is_complex(self): arg = self.args[0] if arg.is_complex and (arg/pi - S.Half).is_integer is False: return True @staticmethod @cacheit def taylor_term(n, x, *previous_terms): # Reference Formula: # http://functions.wolfram.com/ElementaryFunctions/Sec/06/01/02/01/ if n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) k = n//2 return S.NegativeOne**k*euler(2*k)/factorial(2*k)*x**(2*k) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.accumulationbounds import AccumBounds from sympy.functions.elementary.complexes import re arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = (x0 + pi/2)/pi if n.is_integer: lt = (arg - n*pi + pi/2).as_leading_term(x) return (S.NegativeOne**n)/lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) return self.func(x0) if x0.is_finite else self class csc(ReciprocalTrigonometricFunction): """ The cosecant function. Returns the cosecant of x (measured in radians). Explanation =========== See :func:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import csc >>> from sympy.abc import x >>> csc(x**2).diff(x) -2*x*cot(x**2)*csc(x**2) >>> csc(1).diff(x) 0 See Also ======== sin, cos, sec, tan, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Csc """ _reciprocal_of = sin _is_odd = True def period(self, symbol=None): return self._period(symbol) def _eval_rewrite_as_sin(self, arg, **kwargs): return (1/sin(arg)) def _eval_rewrite_as_sincos(self, arg, **kwargs): return cos(arg)/(sin(arg)*cos(arg)) def _eval_rewrite_as_cot(self, arg, **kwargs): cot_half = cot(arg/2) return (1 + cot_half**2)/(2*cot_half) def _eval_rewrite_as_cos(self, arg, **kwargs): return 1/sin(arg).rewrite(cos) def _eval_rewrite_as_sec(self, arg, **kwargs): return sec(pi/2 - arg, evaluate=False) def _eval_rewrite_as_tan(self, arg, **kwargs): return (1/sin(arg).rewrite(tan)) def fdiff(self, argindex=1): if argindex == 1: return -cot(self.args[0])*csc(self.args[0]) else: raise ArgumentIndexError(self, argindex) def _eval_is_complex(self): arg = self.args[0] if arg.is_real and (arg/pi).is_integer is False: return True @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return 1/sympify(x) elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) k = n//2 + 1 return (S.NegativeOne**(k - 1)*2*(2**(2*k - 1) - 1)* bernoulli(2*k)*x**(2*k - 1)/factorial(2*k)) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.accumulationbounds import AccumBounds from sympy.functions.elementary.complexes import re arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = x0/pi if n.is_integer: lt = (arg - n*pi).as_leading_term(x) return (S.NegativeOne**n)/lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) return self.func(x0) if x0.is_finite else self class sinc(Function): r""" Represents an unnormalized sinc function: .. math:: \operatorname{sinc}(x) = \begin{cases} \frac{\sin x}{x} & \qquad x \neq 0 \\ 1 & \qquad x = 0 \end{cases} Examples ======== >>> from sympy import sinc, oo, jn >>> from sympy.abc import x >>> sinc(x) sinc(x) * Automated Evaluation >>> sinc(0) 1 >>> sinc(oo) 0 * Differentiation >>> sinc(x).diff() cos(x)/x - sin(x)/x**2 * Series Expansion >>> sinc(x).series() 1 - x**2/6 + x**4/120 + O(x**6) * As zero'th order spherical Bessel Function >>> sinc(x).rewrite(jn) jn(0, x) See also ======== sin References ========== .. [1] https://en.wikipedia.org/wiki/Sinc_function """ _singularities = (S.ComplexInfinity,) def fdiff(self, argindex=1): x = self.args[0] if argindex == 1: # We would like to return the Piecewise here, but Piecewise.diff # currently can't handle removable singularities, meaning things # like sinc(x).diff(x, 2) give the wrong answer at x = 0. See # https://github.com/sympy/sympy/issues/11402. # # return Piecewise(((x*cos(x) - sin(x))/x**2, Ne(x, S.Zero)), (S.Zero, S.true)) return cos(x)/x - sin(x)/x**2 else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_zero: return S.One if arg.is_Number: if arg in [S.Infinity, S.NegativeInfinity]: return S.Zero elif arg is S.NaN: return S.NaN if arg is S.ComplexInfinity: return S.NaN if arg.could_extract_minus_sign(): return cls(-arg) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_integer: if fuzzy_not(arg.is_zero): return S.Zero elif (2*pi_coeff).is_integer: return S.NegativeOne**(pi_coeff - S.Half)/arg def _eval_nseries(self, x, n, logx, cdir=0): x = self.args[0] return (sin(x)/x)._eval_nseries(x, n, logx) def _eval_rewrite_as_jn(self, arg, **kwargs): from sympy.functions.special.bessel import jn return jn(0, arg) def _eval_rewrite_as_sin(self, arg, **kwargs): return Piecewise((sin(arg)/arg, Ne(arg, S.Zero)), (S.One, S.true)) def _eval_is_zero(self): if self.args[0].is_infinite: return True rest, pi_mult = _peeloff_pi(self.args[0]) if rest.is_zero: return fuzzy_and([pi_mult.is_integer, pi_mult.is_nonzero]) if rest.is_Number and pi_mult.is_integer: return False def _eval_is_real(self): if self.args[0].is_extended_real or self.args[0].is_imaginary: return True _eval_is_finite = _eval_is_real ############################################################################### ########################### TRIGONOMETRIC INVERSES ############################ ############################################################################### class InverseTrigonometricFunction(Function): """Base class for inverse trigonometric functions.""" _singularities = (S.One, S.NegativeOne, S.Zero, S.ComplexInfinity) # type: tTuple[Expr, ...] @staticmethod @cacheit def _asin_table(): # Only keys with could_extract_minus_sign() == False # are actually needed. return { sqrt(3)/2: pi/3, sqrt(2)/2: pi/4, 1/sqrt(2): pi/4, sqrt((5 - sqrt(5))/8): pi/5, sqrt(2)*sqrt(5 - sqrt(5))/4: pi/5, sqrt((5 + sqrt(5))/8): pi*Rational(2, 5), sqrt(2)*sqrt(5 + sqrt(5))/4: pi*Rational(2, 5), S.Half: pi/6, sqrt(2 - sqrt(2))/2: pi/8, sqrt(S.Half - sqrt(2)/4): pi/8, sqrt(2 + sqrt(2))/2: pi*Rational(3, 8), sqrt(S.Half + sqrt(2)/4): pi*Rational(3, 8), (sqrt(5) - 1)/4: pi/10, (1 - sqrt(5))/4: -pi/10, (sqrt(5) + 1)/4: pi*Rational(3, 10), sqrt(6)/4 - sqrt(2)/4: pi/12, -sqrt(6)/4 + sqrt(2)/4: -pi/12, (sqrt(3) - 1)/sqrt(8): pi/12, (1 - sqrt(3))/sqrt(8): -pi/12, sqrt(6)/4 + sqrt(2)/4: pi*Rational(5, 12), (1 + sqrt(3))/sqrt(8): pi*Rational(5, 12) } @staticmethod @cacheit def _atan_table(): # Only keys with could_extract_minus_sign() == False # are actually needed. return { sqrt(3)/3: pi/6, 1/sqrt(3): pi/6, sqrt(3): pi/3, sqrt(2) - 1: pi/8, 1 - sqrt(2): -pi/8, 1 + sqrt(2): pi*Rational(3, 8), sqrt(5 - 2*sqrt(5)): pi/5, sqrt(5 + 2*sqrt(5)): pi*Rational(2, 5), sqrt(1 - 2*sqrt(5)/5): pi/10, sqrt(1 + 2*sqrt(5)/5): pi*Rational(3, 10), 2 - sqrt(3): pi/12, -2 + sqrt(3): -pi/12, 2 + sqrt(3): pi*Rational(5, 12) } @staticmethod @cacheit def _acsc_table(): # Keys for which could_extract_minus_sign() # will obviously return True are omitted. return { 2*sqrt(3)/3: pi/3, sqrt(2): pi/4, sqrt(2 + 2*sqrt(5)/5): pi/5, 1/sqrt(Rational(5, 8) - sqrt(5)/8): pi/5, sqrt(2 - 2*sqrt(5)/5): pi*Rational(2, 5), 1/sqrt(Rational(5, 8) + sqrt(5)/8): pi*Rational(2, 5), 2: pi/6, sqrt(4 + 2*sqrt(2)): pi/8, 2/sqrt(2 - sqrt(2)): pi/8, sqrt(4 - 2*sqrt(2)): pi*Rational(3, 8), 2/sqrt(2 + sqrt(2)): pi*Rational(3, 8), 1 + sqrt(5): pi/10, sqrt(5) - 1: pi*Rational(3, 10), -(sqrt(5) - 1): pi*Rational(-3, 10), sqrt(6) + sqrt(2): pi/12, sqrt(6) - sqrt(2): pi*Rational(5, 12), -(sqrt(6) - sqrt(2)): pi*Rational(-5, 12) } class asin(InverseTrigonometricFunction): r""" The inverse sine function. Returns the arcsine of x in radians. Explanation =========== ``asin(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when the result is a rational multiple of $\pi$ (see the ``eval`` class method). A purely imaginary argument will lead to an asinh expression. Examples ======== >>> from sympy import asin, oo >>> asin(1) pi/2 >>> asin(-1) -pi/2 >>> asin(-oo) oo*I >>> asin(oo) -oo*I See Also ======== sin, csc, cos, sec, tan, cot acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcSin """ def fdiff(self, argindex=1): if argindex == 1: return 1/sqrt(1 - self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational: return False else: return s.is_rational def _eval_is_positive(self): return self._eval_is_extended_real() and self.args[0].is_positive def _eval_is_negative(self): return self._eval_is_extended_real() and self.args[0].is_negative @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.NegativeInfinity*S.ImaginaryUnit elif arg is S.NegativeInfinity: return S.Infinity*S.ImaginaryUnit elif arg.is_zero: return S.Zero elif arg is S.One: return pi/2 elif arg is S.NegativeOne: return -pi/2 if arg is S.ComplexInfinity: return S.ComplexInfinity if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_number: asin_table = cls._asin_table() if arg in asin_table: return asin_table[arg] i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import asinh return S.ImaginaryUnit*asinh(i_coeff) if arg.is_zero: return S.Zero if isinstance(arg, sin): ang = arg.args[0] if ang.is_comparable: ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to (-pi,pi] ang = pi - ang # restrict to [-pi/2,pi/2] if ang > pi/2: ang = pi - ang if ang < -pi/2: ang = -pi - ang return ang if isinstance(arg, cos): # acos(x) + asin(x) = pi/2 ang = arg.args[0] if ang.is_comparable: return pi/2 - acos(arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) >= 2 and n > 2: p = previous_terms[-2] return p*(n - 2)**2/(n*(n - 1))*x**2 else: k = (n - 1) // 2 R = RisingFactorial(S.Half, k) F = factorial(k) return R/F*x**n/n def _eval_as_leading_term(self, x, logx=None, cdir=0): # asin arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0.is_zero: return arg.as_leading_term(x) # Handling branch points if x0 in (-S.One, S.One, S.ComplexInfinity): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand() # Handling points lying on branch cuts (-oo, -1) U (1, oo) if (1 - x0**2).is_negative: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_negative: if x0.is_negative: return -pi - self.func(x0) elif im(ndir).is_positive: if x0.is_positive: return pi - self.func(x0) else: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand() return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # asin from sympy.series.order import O arg0 = self.args[0].subs(x, 0) # Handling branch points if arg0 is S.One: t = Dummy('t', positive=True) ser = asin(S.One - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else pi/2 + O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = asin(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else -pi/2 + O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res # Handling points lying on branch cuts (-oo, -1) U (1, oo) if (1 - arg0**2).is_negative: ndir = self.args[0].dir(x, cdir if cdir else 1) if im(ndir).is_negative: if arg0.is_negative: return -pi - res elif im(ndir).is_positive: if arg0.is_positive: return pi - res else: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def _eval_rewrite_as_acos(self, x, **kwargs): return pi/2 - acos(x) def _eval_rewrite_as_atan(self, x, **kwargs): return 2*atan(x/(1 + sqrt(1 - x**2))) def _eval_rewrite_as_log(self, x, **kwargs): return -S.ImaginaryUnit*log(S.ImaginaryUnit*x + sqrt(1 - x**2)) _eval_rewrite_as_tractable = _eval_rewrite_as_log def _eval_rewrite_as_acot(self, arg, **kwargs): return 2*acot((1 + sqrt(1 - arg**2))/arg) def _eval_rewrite_as_asec(self, arg, **kwargs): return pi/2 - asec(1/arg) def _eval_rewrite_as_acsc(self, arg, **kwargs): return acsc(1/arg) def _eval_is_extended_real(self): x = self.args[0] return x.is_extended_real and (1 - abs(x)).is_nonnegative def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sin class acos(InverseTrigonometricFunction): r""" The inverse cosine function. Returns the arc cosine of x (measured in radians). Examples ======== ``acos(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when the result is a rational multiple of $\pi$ (see the eval class method). ``acos(zoo)`` evaluates to ``zoo`` (see note in :class:`sympy.functions.elementary.trigonometric.asec`) A purely imaginary argument will be rewritten to asinh. Examples ======== >>> from sympy import acos, oo >>> acos(1) 0 >>> acos(0) pi/2 >>> acos(oo) oo*I See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcCos """ def fdiff(self, argindex=1): if argindex == 1: return -1/sqrt(1 - self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational: return False else: return s.is_rational @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity*S.ImaginaryUnit elif arg is S.NegativeInfinity: return S.NegativeInfinity*S.ImaginaryUnit elif arg.is_zero: return pi/2 elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return pi if arg is S.ComplexInfinity: return S.ComplexInfinity if arg.is_number: asin_table = cls._asin_table() if arg in asin_table: return pi/2 - asin_table[arg] elif -arg in asin_table: return pi/2 + asin_table[-arg] i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: return pi/2 - asin(arg) if isinstance(arg, cos): ang = arg.args[0] if ang.is_comparable: ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to [0,pi] ang = 2*pi - ang return ang if isinstance(arg, sin): # acos(x) + asin(x) = pi/2 ang = arg.args[0] if ang.is_comparable: return pi/2 - asin(arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return pi/2 elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) >= 2 and n > 2: p = previous_terms[-2] return p*(n - 2)**2/(n*(n - 1))*x**2 else: k = (n - 1) // 2 R = RisingFactorial(S.Half, k) F = factorial(k) return -R/F*x**n/n def _eval_as_leading_term(self, x, logx=None, cdir=0): # acos arg = self.args[0] x0 = arg.subs(x, 0).cancel() # Handling branch points if x0 == 1: return sqrt(2)*sqrt((S.One - arg).as_leading_term(x)) if x0 in (-S.One, S.ComplexInfinity): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) # Handling points lying on branch cuts (-oo, -1) U (1, oo) if (1 - x0**2).is_negative: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_negative: if x0.is_negative: return 2*pi - self.func(x0) elif im(ndir).is_positive: if x0.is_positive: return -self.func(x0) else: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand() return self.func(x0) def _eval_is_extended_real(self): x = self.args[0] return x.is_extended_real and (1 - abs(x)).is_nonnegative def _eval_is_nonnegative(self): return self._eval_is_extended_real() def _eval_nseries(self, x, n, logx, cdir=0): # acos from sympy.series.order import O arg0 = self.args[0].subs(x, 0) # Handling branch points if arg0 is S.One: t = Dummy('t', positive=True) ser = acos(S.One - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = acos(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else pi + O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res # Handling points lying on branch cuts (-oo, -1) U (1, oo) if (1 - arg0**2).is_negative: ndir = self.args[0].dir(x, cdir if cdir else 1) if im(ndir).is_negative: if arg0.is_negative: return 2*pi - res elif im(ndir).is_positive: if arg0.is_positive: return -res else: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def _eval_rewrite_as_log(self, x, **kwargs): return pi/2 + S.ImaginaryUnit*\ log(S.ImaginaryUnit*x + sqrt(1 - x**2)) _eval_rewrite_as_tractable = _eval_rewrite_as_log def _eval_rewrite_as_asin(self, x, **kwargs): return pi/2 - asin(x) def _eval_rewrite_as_atan(self, x, **kwargs): return atan(sqrt(1 - x**2)/x) + (pi/2)*(1 - x*sqrt(1/x**2)) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return cos def _eval_rewrite_as_acot(self, arg, **kwargs): return pi/2 - 2*acot((1 + sqrt(1 - arg**2))/arg) def _eval_rewrite_as_asec(self, arg, **kwargs): return asec(1/arg) def _eval_rewrite_as_acsc(self, arg, **kwargs): return pi/2 - acsc(1/arg) def _eval_conjugate(self): z = self.args[0] r = self.func(self.args[0].conjugate()) if z.is_extended_real is False: return r elif z.is_extended_real and (z + 1).is_nonnegative and (z - 1).is_nonpositive: return r class atan(InverseTrigonometricFunction): r""" The inverse tangent function. Returns the arc tangent of x (measured in radians). Explanation =========== ``atan(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when the result is a rational multiple of $\pi$ (see the eval class method). Examples ======== >>> from sympy import atan, oo >>> atan(0) 0 >>> atan(1) pi/4 >>> atan(oo) pi/2 See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, acos, asec, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcTan """ args: tTuple[Expr] _singularities = (S.ImaginaryUnit, -S.ImaginaryUnit) def fdiff(self, argindex=1): if argindex == 1: return 1/(1 + self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational: return False else: return s.is_rational def _eval_is_positive(self): return self.args[0].is_extended_positive def _eval_is_nonnegative(self): return self.args[0].is_extended_nonnegative def _eval_is_zero(self): return self.args[0].is_zero def _eval_is_real(self): return self.args[0].is_extended_real @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return pi/2 elif arg is S.NegativeInfinity: return -pi/2 elif arg.is_zero: return S.Zero elif arg is S.One: return pi/4 elif arg is S.NegativeOne: return -pi/4 if arg is S.ComplexInfinity: from sympy.calculus.accumulationbounds import AccumBounds return AccumBounds(-pi/2, pi/2) if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_number: atan_table = cls._atan_table() if arg in atan_table: return atan_table[arg] i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import atanh return S.ImaginaryUnit*atanh(i_coeff) if arg.is_zero: return S.Zero if isinstance(arg, tan): ang = arg.args[0] if ang.is_comparable: ang %= pi # restrict to [0,pi) if ang > pi/2: # restrict to [-pi/2,pi/2] ang -= pi return ang if isinstance(arg, cot): # atan(x) + acot(x) = pi/2 ang = arg.args[0] if ang.is_comparable: ang = pi/2 - acot(arg) if ang > pi/2: # restrict to [-pi/2,pi/2] ang -= pi return ang @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) return S.NegativeOne**((n - 1)//2)*x**n/n def _eval_as_leading_term(self, x, logx=None, cdir=0): # atan arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0.is_zero: return arg.as_leading_term(x) # Handling branch points if x0 in (-S.ImaginaryUnit, S.ImaginaryUnit, S.ComplexInfinity): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand() # Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo) if (1 + x0**2).is_negative: ndir = arg.dir(x, cdir if cdir else 1) if re(ndir).is_negative: if im(x0).is_positive: return self.func(x0) - pi elif re(ndir).is_positive: if im(x0).is_negative: return self.func(x0) + pi else: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand() return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # atan arg0 = self.args[0].subs(x, 0) # Handling branch points if arg0 in (S.ImaginaryUnit, S.NegativeOne*S.ImaginaryUnit): return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) res = Function._eval_nseries(self, x, n=n, logx=logx) ndir = self.args[0].dir(x, cdir if cdir else 1) if arg0 is S.ComplexInfinity: if re(ndir) > 0: return res - pi return res # Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo) if (1 + arg0**2).is_negative: if re(ndir).is_negative: if im(arg0).is_positive: return res - pi elif re(ndir).is_positive: if im(arg0).is_negative: return res + pi else: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def _eval_rewrite_as_log(self, x, **kwargs): return S.ImaginaryUnit/2*(log(S.One - S.ImaginaryUnit*x) - log(S.One + S.ImaginaryUnit*x)) _eval_rewrite_as_tractable = _eval_rewrite_as_log def _eval_aseries(self, n, args0, x, logx): if args0[0] is S.Infinity: return (pi/2 - atan(1/self.args[0]))._eval_nseries(x, n, logx) elif args0[0] is S.NegativeInfinity: return (-pi/2 - atan(1/self.args[0]))._eval_nseries(x, n, logx) else: return super()._eval_aseries(n, args0, x, logx) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return tan def _eval_rewrite_as_asin(self, arg, **kwargs): return sqrt(arg**2)/arg*(pi/2 - asin(1/sqrt(1 + arg**2))) def _eval_rewrite_as_acos(self, arg, **kwargs): return sqrt(arg**2)/arg*acos(1/sqrt(1 + arg**2)) def _eval_rewrite_as_acot(self, arg, **kwargs): return acot(1/arg) def _eval_rewrite_as_asec(self, arg, **kwargs): return sqrt(arg**2)/arg*asec(sqrt(1 + arg**2)) def _eval_rewrite_as_acsc(self, arg, **kwargs): return sqrt(arg**2)/arg*(pi/2 - acsc(sqrt(1 + arg**2))) class acot(InverseTrigonometricFunction): r""" The inverse cotangent function. Returns the arc cotangent of x (measured in radians). Explanation =========== ``acot(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, \tilde{\infty}, 0, 1, -1\}$ and for some instances when the result is a rational multiple of $\pi$ (see the eval class method). A purely imaginary argument will lead to an ``acoth`` expression. ``acot(x)`` has a branch cut along $(-i, i)$, hence it is discontinuous at 0. Its range for real $x$ is $(-\frac{\pi}{2}, \frac{\pi}{2}]$. Examples ======== >>> from sympy import acot, sqrt >>> acot(0) pi/2 >>> acot(1) pi/4 >>> acot(sqrt(3) - 2) -5*pi/12 See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, acos, asec, atan, atan2 References ========== .. [1] http://dlmf.nist.gov/4.23 .. [2] http://functions.wolfram.com/ElementaryFunctions/ArcCot """ _singularities = (S.ImaginaryUnit, -S.ImaginaryUnit) def fdiff(self, argindex=1): if argindex == 1: return -1/(1 + self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational: return False else: return s.is_rational def _eval_is_positive(self): return self.args[0].is_nonnegative def _eval_is_negative(self): return self.args[0].is_negative def _eval_is_extended_real(self): return self.args[0].is_extended_real @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return pi/ 2 elif arg is S.One: return pi/4 elif arg is S.NegativeOne: return -pi/4 if arg is S.ComplexInfinity: return S.Zero if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_number: atan_table = cls._atan_table() if arg in atan_table: ang = pi/2 - atan_table[arg] if ang > pi/2: # restrict to (-pi/2,pi/2] ang -= pi return ang i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: from sympy.functions.elementary.hyperbolic import acoth return -S.ImaginaryUnit*acoth(i_coeff) if arg.is_zero: return pi*S.Half if isinstance(arg, cot): ang = arg.args[0] if ang.is_comparable: ang %= pi # restrict to [0,pi) if ang > pi/2: # restrict to (-pi/2,pi/2] ang -= pi; return ang if isinstance(arg, tan): # atan(x) + acot(x) = pi/2 ang = arg.args[0] if ang.is_comparable: ang = pi/2 - atan(arg) if ang > pi/2: # restrict to (-pi/2,pi/2] ang -= pi return ang @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return pi/2 # FIX THIS elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) return S.NegativeOne**((n + 1)//2)*x**n/n def _eval_as_leading_term(self, x, logx=None, cdir=0): # acot arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0 is S.ComplexInfinity: return (1/arg).as_leading_term(x) # Handling branch points if x0 in (-S.ImaginaryUnit, S.ImaginaryUnit, S.Zero): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand() # Handling points lying on branch cuts [-I, I] if x0.is_imaginary and (1 + x0**2).is_positive: ndir = arg.dir(x, cdir if cdir else 1) if re(ndir).is_positive: if im(x0).is_positive: return self.func(x0) + pi elif re(ndir).is_negative: if im(x0).is_negative: return self.func(x0) - pi else: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand() return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # acot arg0 = self.args[0].subs(x, 0) # Handling branch points if arg0 in (S.ImaginaryUnit, S.NegativeOne*S.ImaginaryUnit): return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res ndir = self.args[0].dir(x, cdir if cdir else 1) if arg0.is_zero: if re(ndir) < 0: return res - pi return res # Handling points lying on branch cuts [-I, I] if arg0.is_imaginary and (1 + arg0**2).is_positive: if re(ndir).is_positive: if im(arg0).is_positive: return res + pi elif re(ndir).is_negative: if im(arg0).is_negative: return res - pi else: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def _eval_aseries(self, n, args0, x, logx): if args0[0] is S.Infinity: return (pi/2 - acot(1/self.args[0]))._eval_nseries(x, n, logx) elif args0[0] is S.NegativeInfinity: return (pi*Rational(3, 2) - acot(1/self.args[0]))._eval_nseries(x, n, logx) else: return super(atan, self)._eval_aseries(n, args0, x, logx) def _eval_rewrite_as_log(self, x, **kwargs): return S.ImaginaryUnit/2*(log(1 - S.ImaginaryUnit/x) - log(1 + S.ImaginaryUnit/x)) _eval_rewrite_as_tractable = _eval_rewrite_as_log def inverse(self, argindex=1): """ Returns the inverse of this function. """ return cot def _eval_rewrite_as_asin(self, arg, **kwargs): return (arg*sqrt(1/arg**2)* (pi/2 - asin(sqrt(-arg**2)/sqrt(-arg**2 - 1)))) def _eval_rewrite_as_acos(self, arg, **kwargs): return arg*sqrt(1/arg**2)*acos(sqrt(-arg**2)/sqrt(-arg**2 - 1)) def _eval_rewrite_as_atan(self, arg, **kwargs): return atan(1/arg) def _eval_rewrite_as_asec(self, arg, **kwargs): return arg*sqrt(1/arg**2)*asec(sqrt((1 + arg**2)/arg**2)) def _eval_rewrite_as_acsc(self, arg, **kwargs): return arg*sqrt(1/arg**2)*(pi/2 - acsc(sqrt((1 + arg**2)/arg**2))) class asec(InverseTrigonometricFunction): r""" The inverse secant function. Returns the arc secant of x (measured in radians). Explanation =========== ``asec(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when the result is a rational multiple of $\pi$ (see the eval class method). ``asec(x)`` has branch cut in the interval $[-1, 1]$. For complex arguments, it can be defined [4]_ as .. math:: \operatorname{sec^{-1}}(z) = -i\frac{\log\left(\sqrt{1 - z^2} + 1\right)}{z} At ``x = 0``, for positive branch cut, the limit evaluates to ``zoo``. For negative branch cut, the limit .. math:: \lim_{z \to 0}-i\frac{\log\left(-\sqrt{1 - z^2} + 1\right)}{z} simplifies to :math:`-i\log\left(z/2 + O\left(z^3\right)\right)` which ultimately evaluates to ``zoo``. As ``acos(x) = asec(1/x)``, a similar argument can be given for ``acos(x)``. Examples ======== >>> from sympy import asec, oo >>> asec(1) 0 >>> asec(-1) pi >>> asec(0) zoo >>> asec(-oo) pi/2 See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, acos, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcSec .. [4] http://reference.wolfram.com/language/ref/ArcSec.html """ @classmethod def eval(cls, arg): if arg.is_zero: return S.ComplexInfinity if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return pi if arg in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]: return pi/2 if arg.is_number: acsc_table = cls._acsc_table() if arg in acsc_table: return pi/2 - acsc_table[arg] elif -arg in acsc_table: return pi/2 + acsc_table[-arg] if arg.is_infinite: return pi/2 if isinstance(arg, sec): ang = arg.args[0] if ang.is_comparable: ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to [0,pi] ang = 2*pi - ang return ang if isinstance(arg, csc): # asec(x) + acsc(x) = pi/2 ang = arg.args[0] if ang.is_comparable: return pi/2 - acsc(arg) def fdiff(self, argindex=1): if argindex == 1: return 1/(self.args[0]**2*sqrt(1 - 1/self.args[0]**2)) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sec @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.ImaginaryUnit*log(2 / x) elif n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2 and n > 2: p = previous_terms[-2] return p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2) else: k = n // 2 R = RisingFactorial(S.Half, k) * n F = factorial(k) * n // 2 * n // 2 return -S.ImaginaryUnit * R / F * x**n / 4 def _eval_as_leading_term(self, x, logx=None, cdir=0): # asec arg = self.args[0] x0 = arg.subs(x, 0).cancel() # Handling branch points if x0 == 1: return sqrt(2)*sqrt((arg - S.One).as_leading_term(x)) if x0 in (-S.One, S.Zero): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) # Handling points lying on branch cuts (-1, 1) if x0.is_real and (1 - x0**2).is_positive: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_negative: if x0.is_positive: return -self.func(x0) elif im(ndir).is_positive: if x0.is_negative: return 2*pi - self.func(x0) else: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand() return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # asec from sympy.series.order import O arg0 = self.args[0].subs(x, 0) # Handling branch points if arg0 is S.One: t = Dummy('t', positive=True) ser = asec(S.One + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = asec(S.NegativeOne - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res # Handling points lying on branch cuts (-1, 1) if arg0.is_real and (1 - arg0**2).is_positive: ndir = self.args[0].dir(x, cdir if cdir else 1) if im(ndir).is_negative: if arg0.is_positive: return -res elif im(ndir).is_positive: if arg0.is_negative: return 2*pi - res else: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def _eval_is_extended_real(self): x = self.args[0] if x.is_extended_real is False: return False return fuzzy_or(((x - 1).is_nonnegative, (-x - 1).is_nonnegative)) def _eval_rewrite_as_log(self, arg, **kwargs): return pi/2 + S.ImaginaryUnit*log(S.ImaginaryUnit/arg + sqrt(1 - 1/arg**2)) _eval_rewrite_as_tractable = _eval_rewrite_as_log def _eval_rewrite_as_asin(self, arg, **kwargs): return pi/2 - asin(1/arg) def _eval_rewrite_as_acos(self, arg, **kwargs): return acos(1/arg) def _eval_rewrite_as_atan(self, x, **kwargs): sx2x = sqrt(x**2)/x return pi/2*(1 - sx2x) + sx2x*atan(sqrt(x**2 - 1)) def _eval_rewrite_as_acot(self, x, **kwargs): sx2x = sqrt(x**2)/x return pi/2*(1 - sx2x) + sx2x*acot(1/sqrt(x**2 - 1)) def _eval_rewrite_as_acsc(self, arg, **kwargs): return pi/2 - acsc(arg) class acsc(InverseTrigonometricFunction): r""" The inverse cosecant function. Returns the arc cosecant of x (measured in radians). Explanation =========== ``acsc(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, 0, 1, -1\}$` and for some instances when the result is a rational multiple of $\pi$ (see the ``eval`` class method). Examples ======== >>> from sympy import acsc, oo >>> acsc(1) pi/2 >>> acsc(-1) -pi/2 >>> acsc(oo) 0 >>> acsc(-oo) == acsc(oo) True >>> acsc(0) zoo See Also ======== sin, csc, cos, sec, tan, cot asin, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcCsc """ @classmethod def eval(cls, arg): if arg.is_zero: return S.ComplexInfinity if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.One: return pi/2 elif arg is S.NegativeOne: return -pi/2 if arg in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]: return S.Zero if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_infinite: return S.Zero if arg.is_number: acsc_table = cls._acsc_table() if arg in acsc_table: return acsc_table[arg] if isinstance(arg, csc): ang = arg.args[0] if ang.is_comparable: ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to (-pi,pi] ang = pi - ang # restrict to [-pi/2,pi/2] if ang > pi/2: ang = pi - ang if ang < -pi/2: ang = -pi - ang return ang if isinstance(arg, sec): # asec(x) + acsc(x) = pi/2 ang = arg.args[0] if ang.is_comparable: return pi/2 - asec(arg) def fdiff(self, argindex=1): if argindex == 1: return -1/(self.args[0]**2*sqrt(1 - 1/self.args[0]**2)) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return csc @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return pi/2 - S.ImaginaryUnit*log(2) + S.ImaginaryUnit*log(x) elif n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2 and n > 2: p = previous_terms[-2] return p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2) else: k = n // 2 R = RisingFactorial(S.Half, k) * n F = factorial(k) * n // 2 * n // 2 return S.ImaginaryUnit * R / F * x**n / 4 def _eval_as_leading_term(self, x, logx=None, cdir=0): # acsc arg = self.args[0] x0 = arg.subs(x, 0).cancel() # Handling branch points if x0 in (-S.One, S.One, S.Zero): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand() if x0 is S.ComplexInfinity: return (1/arg).as_leading_term(x) # Handling points lying on branch cuts (-1, 1) if x0.is_real and (1 - x0**2).is_positive: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_negative: if x0.is_positive: return pi - self.func(x0) elif im(ndir).is_positive: if x0.is_negative: return -pi - self.func(x0) else: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand() return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # acsc from sympy.series.order import O arg0 = self.args[0].subs(x, 0) # Handling branch points if arg0 is S.One: t = Dummy('t', positive=True) ser = acsc(S.One + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = acsc(S.NegativeOne - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res # Handling points lying on branch cuts (-1, 1) if arg0.is_real and (1 - arg0**2).is_positive: ndir = self.args[0].dir(x, cdir if cdir else 1) if im(ndir).is_negative: if arg0.is_positive: return pi - res elif im(ndir).is_positive: if arg0.is_negative: return -pi - res else: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def _eval_rewrite_as_log(self, arg, **kwargs): return -S.ImaginaryUnit*log(S.ImaginaryUnit/arg + sqrt(1 - 1/arg**2)) _eval_rewrite_as_tractable = _eval_rewrite_as_log def _eval_rewrite_as_asin(self, arg, **kwargs): return asin(1/arg) def _eval_rewrite_as_acos(self, arg, **kwargs): return pi/2 - acos(1/arg) def _eval_rewrite_as_atan(self, x, **kwargs): return sqrt(x**2)/x*(pi/2 - atan(sqrt(x**2 - 1))) def _eval_rewrite_as_acot(self, arg, **kwargs): return sqrt(arg**2)/arg*(pi/2 - acot(1/sqrt(arg**2 - 1))) def _eval_rewrite_as_asec(self, arg, **kwargs): return pi/2 - asec(arg) class atan2(InverseTrigonometricFunction): r""" The function ``atan2(y, x)`` computes `\operatorname{atan}(y/x)` taking two arguments `y` and `x`. Signs of both `y` and `x` are considered to determine the appropriate quadrant of `\operatorname{atan}(y/x)`. The range is `(-\pi, \pi]`. The complete definition reads as follows: .. math:: \operatorname{atan2}(y, x) = \begin{cases} \arctan\left(\frac y x\right) & \qquad x > 0 \\ \arctan\left(\frac y x\right) + \pi& \qquad y \ge 0, x < 0 \\ \arctan\left(\frac y x\right) - \pi& \qquad y < 0, x < 0 \\ +\frac{\pi}{2} & \qquad y > 0, x = 0 \\ -\frac{\pi}{2} & \qquad y < 0, x = 0 \\ \text{undefined} & \qquad y = 0, x = 0 \end{cases} Attention: Note the role reversal of both arguments. The `y`-coordinate is the first argument and the `x`-coordinate the second. If either `x` or `y` is complex: .. math:: \operatorname{atan2}(y, x) = -i\log\left(\frac{x + iy}{\sqrt{x^2 + y^2}}\right) Examples ======== Going counter-clock wise around the origin we find the following angles: >>> from sympy import atan2 >>> atan2(0, 1) 0 >>> atan2(1, 1) pi/4 >>> atan2(1, 0) pi/2 >>> atan2(1, -1) 3*pi/4 >>> atan2(0, -1) pi >>> atan2(-1, -1) -3*pi/4 >>> atan2(-1, 0) -pi/2 >>> atan2(-1, 1) -pi/4 which are all correct. Compare this to the results of the ordinary `\operatorname{atan}` function for the point `(x, y) = (-1, 1)` >>> from sympy import atan, S >>> atan(S(1)/-1) -pi/4 >>> atan2(1, -1) 3*pi/4 where only the `\operatorname{atan2}` function reurns what we expect. We can differentiate the function with respect to both arguments: >>> from sympy import diff >>> from sympy.abc import x, y >>> diff(atan2(y, x), x) -y/(x**2 + y**2) >>> diff(atan2(y, x), y) x/(x**2 + y**2) We can express the `\operatorname{atan2}` function in terms of complex logarithms: >>> from sympy import log >>> atan2(y, x).rewrite(log) -I*log((x + I*y)/sqrt(x**2 + y**2)) and in terms of `\operatorname(atan)`: >>> from sympy import atan >>> atan2(y, x).rewrite(atan) Piecewise((2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)), (pi, re(x) < 0), (0, Ne(x, 0)), (nan, True)) but note that this form is undefined on the negative real axis. See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, acos, asec, atan, acot References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] https://en.wikipedia.org/wiki/Atan2 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcTan2 """ @classmethod def eval(cls, y, x): from sympy.functions.special.delta_functions import Heaviside if x is S.NegativeInfinity: if y.is_zero: # Special case y = 0 because we define Heaviside(0) = 1/2 return pi return 2*pi*(Heaviside(re(y))) - pi elif x is S.Infinity: return S.Zero elif x.is_imaginary and y.is_imaginary and x.is_number and y.is_number: x = im(x) y = im(y) if x.is_extended_real and y.is_extended_real: if x.is_positive: return atan(y/x) elif x.is_negative: if y.is_negative: return atan(y/x) - pi elif y.is_nonnegative: return atan(y/x) + pi elif x.is_zero: if y.is_positive: return pi/2 elif y.is_negative: return -pi/2 elif y.is_zero: return S.NaN if y.is_zero: if x.is_extended_nonzero: return pi*(S.One - Heaviside(x)) if x.is_number: return Piecewise((pi, re(x) < 0), (0, Ne(x, 0)), (S.NaN, True)) if x.is_number and y.is_number: return -S.ImaginaryUnit*log( (x + S.ImaginaryUnit*y)/sqrt(x**2 + y**2)) def _eval_rewrite_as_log(self, y, x, **kwargs): return -S.ImaginaryUnit*log((x + S.ImaginaryUnit*y)/sqrt(x**2 + y**2)) def _eval_rewrite_as_atan(self, y, x, **kwargs): return Piecewise((2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)), (pi, re(x) < 0), (0, Ne(x, 0)), (S.NaN, True)) def _eval_rewrite_as_arg(self, y, x, **kwargs): if x.is_extended_real and y.is_extended_real: return arg_f(x + y*S.ImaginaryUnit) n = x + S.ImaginaryUnit*y d = x**2 + y**2 return arg_f(n/sqrt(d)) - S.ImaginaryUnit*log(abs(n)/sqrt(abs(d))) def _eval_is_extended_real(self): return self.args[0].is_extended_real and self.args[1].is_extended_real def _eval_conjugate(self): return self.func(self.args[0].conjugate(), self.args[1].conjugate()) def fdiff(self, argindex): y, x = self.args if argindex == 1: # Diff wrt y return x/(x**2 + y**2) elif argindex == 2: # Diff wrt x return -y/(x**2 + y**2) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): y, x = self.args if x.is_extended_real and y.is_extended_real: return super()._eval_evalf(prec)
5b7f7c9ac1ec5a59780c8c31bd49c6b234ca2390f4fd90982d70b34a20bec9e5
from itertools import product from typing import Tuple as tTuple from sympy.core.add import Add from sympy.core.cache import cacheit from sympy.core.expr import Expr from sympy.core.function import (Function, ArgumentIndexError, expand_log, expand_mul, FunctionClass, PoleError, expand_multinomial, expand_complex) from sympy.core.logic import fuzzy_and, fuzzy_not, fuzzy_or from sympy.core.mul import Mul from sympy.core.numbers import Integer, Rational, pi, I, ImaginaryUnit from sympy.core.parameters import global_parameters from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Wild, Dummy from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import arg, unpolarify, im, re, Abs from sympy.functions.elementary.miscellaneous import sqrt from sympy.ntheory import multiplicity, perfect_power from sympy.ntheory.factor_ import factorint # NOTE IMPORTANT # The series expansion code in this file is an important part of the gruntz # algorithm for determining limits. _eval_nseries has to return a generalized # power series with coefficients in C(log(x), log). # In more detail, the result of _eval_nseries(self, x, n) must be # c_0*x**e_0 + ... (finitely many terms) # where e_i are numbers (not necessarily integers) and c_i involve only # numbers, the function log, and log(x). [This also means it must not contain # log(x(1+p)), this *has* to be expanded to log(x)+log(1+p) if x.is_positive and # p.is_positive.] class ExpBase(Function): unbranched = True _singularities = (S.ComplexInfinity,) @property def kind(self): return self.exp.kind def inverse(self, argindex=1): """ Returns the inverse function of ``exp(x)``. """ return log def as_numer_denom(self): """ Returns this with a positive exponent as a 2-tuple (a fraction). Examples ======== >>> from sympy import exp >>> from sympy.abc import x >>> exp(-x).as_numer_denom() (1, exp(x)) >>> exp(x).as_numer_denom() (exp(x), 1) """ # this should be the same as Pow.as_numer_denom wrt # exponent handling exp = self.exp neg_exp = exp.is_negative if not neg_exp and not (-exp).is_negative: neg_exp = exp.could_extract_minus_sign() if neg_exp: return S.One, self.func(-exp) return self, S.One @property def exp(self): """ Returns the exponent of the function. """ return self.args[0] def as_base_exp(self): """ Returns the 2-tuple (base, exponent). """ return self.func(1), Mul(*self.args) def _eval_adjoint(self): return self.func(self.exp.adjoint()) def _eval_conjugate(self): return self.func(self.exp.conjugate()) def _eval_transpose(self): return self.func(self.exp.transpose()) def _eval_is_finite(self): arg = self.exp if arg.is_infinite: if arg.is_extended_negative: return True if arg.is_extended_positive: return False if arg.is_finite: return True def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: z = s.exp.is_zero if z: return True elif s.exp.is_rational and fuzzy_not(z): return False else: return s.is_rational def _eval_is_zero(self): return self.exp is S.NegativeInfinity def _eval_power(self, other): """exp(arg)**e -> exp(arg*e) if assumptions allow it. """ b, e = self.as_base_exp() return Pow._eval_power(Pow(b, e, evaluate=False), other) def _eval_expand_power_exp(self, **hints): from sympy.concrete.products import Product from sympy.concrete.summations import Sum arg = self.args[0] if arg.is_Add and arg.is_commutative: return Mul.fromiter(self.func(x) for x in arg.args) elif isinstance(arg, Sum) and arg.is_commutative: return Product(self.func(arg.function), *arg.limits) return self.func(arg) class exp_polar(ExpBase): r""" Represent a *polar number* (see g-function Sphinx documentation). Explanation =========== ``exp_polar`` represents the function `Exp: \mathbb{C} \rightarrow \mathcal{S}`, sending the complex number `z = a + bi` to the polar number `r = exp(a), \theta = b`. It is one of the main functions to construct polar numbers. Examples ======== >>> from sympy import exp_polar, pi, I, exp The main difference is that polar numbers do not "wrap around" at `2 \pi`: >>> exp(2*pi*I) 1 >>> exp_polar(2*pi*I) exp_polar(2*I*pi) apart from that they behave mostly like classical complex numbers: >>> exp_polar(2)*exp_polar(3) exp_polar(5) See Also ======== sympy.simplify.powsimp.powsimp polar_lift periodic_argument principal_branch """ is_polar = True is_comparable = False # cannot be evalf'd def _eval_Abs(self): # Abs is never a polar number return exp(re(self.args[0])) def _eval_evalf(self, prec): """ Careful! any evalf of polar numbers is flaky """ i = im(self.args[0]) try: bad = (i <= -pi or i > pi) except TypeError: bad = True if bad: return self # cannot evalf for this argument res = exp(self.args[0])._eval_evalf(prec) if i > 0 and im(res) < 0: # i ~ pi, but exp(I*i) evaluated to argument slightly bigger than pi return re(res) return res def _eval_power(self, other): return self.func(self.args[0]*other) def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def as_base_exp(self): # XXX exp_polar(0) is special! if self.args[0] == 0: return self, S.One return ExpBase.as_base_exp(self) class ExpMeta(FunctionClass): def __instancecheck__(cls, instance): if exp in instance.__class__.__mro__: return True return isinstance(instance, Pow) and instance.base is S.Exp1 class exp(ExpBase, metaclass=ExpMeta): """ The exponential function, :math:`e^x`. Examples ======== >>> from sympy import exp, I, pi >>> from sympy.abc import x >>> exp(x) exp(x) >>> exp(x).diff(x) exp(x) >>> exp(I*pi) -1 Parameters ========== arg : Expr See Also ======== log """ def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return self else: raise ArgumentIndexError(self, argindex) def _eval_refine(self, assumptions): from sympy.assumptions import ask, Q arg = self.args[0] if arg.is_Mul: Ioo = I*S.Infinity if arg in [Ioo, -Ioo]: return S.NaN coeff = arg.as_coefficient(pi*I) if coeff: if ask(Q.integer(2*coeff)): if ask(Q.even(coeff)): return S.One elif ask(Q.odd(coeff)): return S.NegativeOne elif ask(Q.even(coeff + S.Half)): return -I elif ask(Q.odd(coeff + S.Half)): return I @classmethod def eval(cls, arg): from sympy.calculus import AccumBounds from sympy.matrices.matrices import MatrixBase from sympy.sets.setexpr import SetExpr from sympy.simplify.simplify import logcombine if isinstance(arg, MatrixBase): return arg.exp() elif global_parameters.exp_is_pow: return Pow(S.Exp1, arg) elif arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.One elif arg is S.One: return S.Exp1 elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Zero elif arg is S.ComplexInfinity: return S.NaN elif isinstance(arg, log): return arg.args[0] elif isinstance(arg, AccumBounds): return AccumBounds(exp(arg.min), exp(arg.max)) elif isinstance(arg, SetExpr): return arg._eval_func(cls) elif arg.is_Mul: coeff = arg.as_coefficient(pi*I) if coeff: if (2*coeff).is_integer: if coeff.is_even: return S.One elif coeff.is_odd: return S.NegativeOne elif (coeff + S.Half).is_even: return -I elif (coeff + S.Half).is_odd: return I elif coeff.is_Rational: ncoeff = coeff % 2 # restrict to [0, 2pi) if ncoeff > 1: # restrict to (-pi, pi] ncoeff -= 2 if ncoeff != coeff: return cls(ncoeff*pi*I) # Warning: code in risch.py will be very sensitive to changes # in this (see DifferentialExtension). # look for a single log factor coeff, terms = arg.as_coeff_Mul() # but it can't be multiplied by oo if coeff in [S.NegativeInfinity, S.Infinity]: if terms.is_number: if coeff is S.NegativeInfinity: terms = -terms if re(terms).is_zero and terms is not S.Zero: return S.NaN if re(terms).is_positive and im(terms) is not S.Zero: return S.ComplexInfinity if re(terms).is_negative: return S.Zero return None coeffs, log_term = [coeff], None for term in Mul.make_args(terms): term_ = logcombine(term) if isinstance(term_, log): if log_term is None: log_term = term_.args[0] else: return None elif term.is_comparable: coeffs.append(term) else: return None return log_term**Mul(*coeffs) if log_term else None elif arg.is_Add: out = [] add = [] argchanged = False for a in arg.args: if a is S.One: add.append(a) continue newa = cls(a) if isinstance(newa, cls): if newa.args[0] != a: add.append(newa.args[0]) argchanged = True else: add.append(a) else: out.append(newa) if out or argchanged: return Mul(*out)*cls(Add(*add), evaluate=False) if arg.is_zero: return S.One @property def base(self): """ Returns the base of the exponential function. """ return S.Exp1 @staticmethod @cacheit def taylor_term(n, x, *previous_terms): """ Calculates the next term in the Taylor series expansion. """ if n < 0: return S.Zero if n == 0: return S.One x = sympify(x) if previous_terms: p = previous_terms[-1] if p is not None: return p * x / n return x**n/factorial(n) def as_real_imag(self, deep=True, **hints): """ Returns this function as a 2-tuple representing a complex number. Examples ======== >>> from sympy import exp, I >>> from sympy.abc import x >>> exp(x).as_real_imag() (exp(re(x))*cos(im(x)), exp(re(x))*sin(im(x))) >>> exp(1).as_real_imag() (E, 0) >>> exp(I).as_real_imag() (cos(1), sin(1)) >>> exp(1+I).as_real_imag() (E*cos(1), E*sin(1)) See Also ======== sympy.functions.elementary.complexes.re sympy.functions.elementary.complexes.im """ from sympy.functions.elementary.trigonometric import cos, sin re, im = self.args[0].as_real_imag() if deep: re = re.expand(deep, **hints) im = im.expand(deep, **hints) cos, sin = cos(im), sin(im) return (exp(re)*cos, exp(re)*sin) def _eval_subs(self, old, new): # keep processing of power-like args centralized in Pow if old.is_Pow: # handle (exp(3*log(x))).subs(x**2, z) -> z**(3/2) old = exp(old.exp*log(old.base)) elif old is S.Exp1 and new.is_Function: old = exp if isinstance(old, exp) or old is S.Exp1: f = lambda a: Pow(*a.as_base_exp(), evaluate=False) if ( a.is_Pow or isinstance(a, exp)) else a return Pow._eval_subs(f(self), f(old), new) if old is exp and not new.is_Function: return new**self.exp._subs(old, new) return Function._eval_subs(self, old, new) def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True elif self.args[0].is_imaginary: arg2 = -S(2) * I * self.args[0] / pi return arg2.is_even def _eval_is_complex(self): def complex_extended_negative(arg): yield arg.is_complex yield arg.is_extended_negative return fuzzy_or(complex_extended_negative(self.args[0])) def _eval_is_algebraic(self): if (self.exp / pi / I).is_rational: return True if fuzzy_not(self.exp.is_zero): if self.exp.is_algebraic: return False elif (self.exp / pi).is_rational: return False def _eval_is_extended_positive(self): if self.exp.is_extended_real: return self.args[0] is not S.NegativeInfinity elif self.exp.is_imaginary: arg2 = -I * self.args[0] / pi return arg2.is_even def _eval_nseries(self, x, n, logx, cdir=0): # NOTE Please see the comment at the beginning of this file, labelled # IMPORTANT. from sympy.functions.elementary.complexes import sign from sympy.functions.elementary.integers import ceiling from sympy.series.limits import limit from sympy.series.order import Order from sympy.simplify.powsimp import powsimp arg = self.exp arg_series = arg._eval_nseries(x, n=n, logx=logx) if arg_series.is_Order: return 1 + arg_series arg0 = limit(arg_series.removeO(), x, 0) if arg0 is S.NegativeInfinity: return Order(x**n, x) if arg0 is S.Infinity: return self # checking for indecisiveness/ sign terms in arg0 if any(isinstance(arg, (sign, ImaginaryUnit)) for arg in arg0.args): return self t = Dummy("t") nterms = n try: cf = Order(arg.as_leading_term(x, logx=logx), x).getn() except (NotImplementedError, PoleError): cf = 0 if cf and cf > 0: nterms = ceiling(n/cf) exp_series = exp(t)._taylor(t, nterms) r = exp(arg0)*exp_series.subs(t, arg_series - arg0) rep = {logx: log(x)} if logx is not None else {} if r.subs(rep) == self: return r if cf and cf > 1: r += Order((arg_series - arg0)**n, x)/x**((cf-1)*n) else: r += Order((arg_series - arg0)**n, x) r = r.expand() r = powsimp(r, deep=True, combine='exp') # powsimp may introduce unexpanded (-1)**Rational; see PR #17201 simplerat = lambda x: x.is_Rational and x.q in [3, 4, 6] w = Wild('w', properties=[simplerat]) r = r.replace(S.NegativeOne**w, expand_complex(S.NegativeOne**w)) return r def _taylor(self, x, n): l = [] g = None for i in range(n): g = self.taylor_term(i, self.args[0], g) g = g.nseries(x, n=n) l.append(g.removeO()) return Add(*l) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.calculus.util import AccumBounds arg = self.args[0].cancel().as_leading_term(x, logx=logx) arg0 = arg.subs(x, 0) if arg is S.NaN: return S.NaN if isinstance(arg0, AccumBounds): # This check addresses a corner case involving AccumBounds. # if isinstance(arg, AccumBounds) is True, then arg0 can either be 0, # AccumBounds(-oo, 0) or AccumBounds(-oo, oo). # Check out function: test_issue_18473() in test_exponential.py and # test_limits.py for more information. if re(cdir) < S.Zero: return exp(-arg0) return exp(arg0) if arg0 is S.NaN: arg0 = arg.limit(x, 0) if arg0.is_infinite is False: return exp(arg0) raise PoleError("Cannot expand %s around 0" % (self)) def _eval_rewrite_as_sin(self, arg, **kwargs): from sympy.functions.elementary.trigonometric import sin return sin(I*arg + pi/2) - I*sin(I*arg) def _eval_rewrite_as_cos(self, arg, **kwargs): from sympy.functions.elementary.trigonometric import cos return cos(I*arg) + I*cos(I*arg + pi/2) def _eval_rewrite_as_tanh(self, arg, **kwargs): from sympy.functions.elementary.hyperbolic import tanh return (1 + tanh(arg/2))/(1 - tanh(arg/2)) def _eval_rewrite_as_sqrt(self, arg, **kwargs): from sympy.functions.elementary.trigonometric import sin, cos if arg.is_Mul: coeff = arg.coeff(pi*I) if coeff and coeff.is_number: cosine, sine = cos(pi*coeff), sin(pi*coeff) if not isinstance(cosine, cos) and not isinstance (sine, sin): return cosine + I*sine def _eval_rewrite_as_Pow(self, arg, **kwargs): if arg.is_Mul: logs = [a for a in arg.args if isinstance(a, log) and len(a.args) == 1] if logs: return Pow(logs[0].args[0], arg.coeff(logs[0])) def match_real_imag(expr): r""" Try to match expr with $a + Ib$ for real $a$ and $b$. ``match_real_imag`` returns a tuple containing the real and imaginary parts of expr or ``(None, None)`` if direct matching is not possible. Contrary to :func:`~.re()`, :func:`~.im()``, and ``as_real_imag()``, this helper will not force things by returning expressions themselves containing ``re()`` or ``im()`` and it does not expand its argument either. """ r_, i_ = expr.as_independent(I, as_Add=True) if i_ == 0 and r_.is_real: return (r_, i_) i_ = i_.as_coefficient(I) if i_ and i_.is_real and r_.is_real: return (r_, i_) else: return (None, None) # simpler to check for than None class log(Function): r""" The natural logarithm function `\ln(x)` or `\log(x)`. Explanation =========== Logarithms are taken with the natural base, `e`. To get a logarithm of a different base ``b``, use ``log(x, b)``, which is essentially short-hand for ``log(x)/log(b)``. ``log`` represents the principal branch of the natural logarithm. As such it has a branch cut along the negative real axis and returns values having a complex argument in `(-\pi, \pi]`. Examples ======== >>> from sympy import log, sqrt, S, I >>> log(8, 2) 3 >>> log(S(8)/3, 2) -log(3)/log(2) + 3 >>> log(-1 + I*sqrt(3)) log(2) + 2*I*pi/3 See Also ======== exp """ args: tTuple[Expr] _singularities = (S.Zero, S.ComplexInfinity) def fdiff(self, argindex=1): """ Returns the first derivative of the function. """ if argindex == 1: return 1/self.args[0] else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): r""" Returns `e^x`, the inverse function of `\log(x)`. """ return exp @classmethod def eval(cls, arg, base=None): from sympy.calculus import AccumBounds from sympy.sets.setexpr import SetExpr arg = sympify(arg) if base is not None: base = sympify(base) if base == 1: if arg == 1: return S.NaN else: return S.ComplexInfinity try: # handle extraction of powers of the base now # or else expand_log in Mul would have to handle this n = multiplicity(base, arg) if n: return n + log(arg / base**n) / log(base) else: return log(arg)/log(base) except ValueError: pass if base is not S.Exp1: return cls(arg)/cls(base) else: return cls(arg) if arg.is_Number: if arg.is_zero: return S.ComplexInfinity elif arg is S.One: return S.Zero elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Infinity elif arg is S.NaN: return S.NaN elif arg.is_Rational and arg.p == 1: return -cls(arg.q) if arg.is_Pow and arg.base is S.Exp1 and arg.exp.is_extended_real: return arg.exp if isinstance(arg, exp) and arg.exp.is_extended_real: return arg.exp elif isinstance(arg, exp) and arg.exp.is_number: r_, i_ = match_real_imag(arg.exp) if i_ and i_.is_comparable: i_ %= 2*pi if i_ > pi: i_ -= 2*pi return r_ + expand_mul(i_ * I, deep=False) elif isinstance(arg, exp_polar): return unpolarify(arg.exp) elif isinstance(arg, AccumBounds): if arg.min.is_positive: return AccumBounds(log(arg.min), log(arg.max)) elif arg.min.is_zero: return AccumBounds(S.NegativeInfinity, log(arg.max)) else: return S.NaN elif isinstance(arg, SetExpr): return arg._eval_func(cls) if arg.is_number: if arg.is_negative: return pi * I + cls(-arg) elif arg is S.ComplexInfinity: return S.ComplexInfinity elif arg is S.Exp1: return S.One if arg.is_zero: return S.ComplexInfinity # don't autoexpand Pow or Mul (see the issue 3351): if not arg.is_Add: coeff = arg.as_coefficient(I) if coeff is not None: if coeff is S.Infinity: return S.Infinity elif coeff is S.NegativeInfinity: return S.Infinity elif coeff.is_Rational: if coeff.is_nonnegative: return pi * I * S.Half + cls(coeff) else: return -pi * I * S.Half + cls(-coeff) if arg.is_number and arg.is_algebraic: # Match arg = coeff*(r_ + i_*I) with coeff>0, r_ and i_ real. coeff, arg_ = arg.as_independent(I, as_Add=False) if coeff.is_negative: coeff *= -1 arg_ *= -1 arg_ = expand_mul(arg_, deep=False) r_, i_ = arg_.as_independent(I, as_Add=True) i_ = i_.as_coefficient(I) if coeff.is_real and i_ and i_.is_real and r_.is_real: if r_.is_zero: if i_.is_positive: return pi * I * S.Half + cls(coeff * i_) elif i_.is_negative: return -pi * I * S.Half + cls(coeff * -i_) else: from sympy.simplify import ratsimp # Check for arguments involving rational multiples of pi t = (i_/r_).cancel() t1 = (-t).cancel() atan_table = _log_atan_table() if t in atan_table: modulus = ratsimp(coeff * Abs(arg_)) if r_.is_positive: return cls(modulus) + I * atan_table[t] else: return cls(modulus) + I * (atan_table[t] - pi) elif t1 in atan_table: modulus = ratsimp(coeff * Abs(arg_)) if r_.is_positive: return cls(modulus) + I * (-atan_table[t1]) else: return cls(modulus) + I * (pi - atan_table[t1]) def as_base_exp(self): """ Returns this function in the form (base, exponent). """ return self, S.One @staticmethod @cacheit def taylor_term(n, x, *previous_terms): # of log(1+x) r""" Returns the next term in the Taylor series expansion of `\log(1+x)`. """ from sympy.simplify.powsimp import powsimp if n < 0: return S.Zero x = sympify(x) if n == 0: return x if previous_terms: p = previous_terms[-1] if p is not None: return powsimp((-n) * p * x / (n + 1), deep=True, combine='exp') return (1 - 2*(n % 2)) * x**(n + 1)/(n + 1) def _eval_expand_log(self, deep=True, **hints): from sympy.concrete import Sum, Product force = hints.get('force', False) factor = hints.get('factor', False) if (len(self.args) == 2): return expand_log(self.func(*self.args), deep=deep, force=force) arg = self.args[0] if arg.is_Integer: # remove perfect powers p = perfect_power(arg) logarg = None coeff = 1 if p is not False: arg, coeff = p logarg = self.func(arg) # expand as product of its prime factors if factor=True if factor: p = factorint(arg) if arg not in p.keys(): logarg = sum(n*log(val) for val, n in p.items()) if logarg is not None: return coeff*logarg elif arg.is_Rational: return log(arg.p) - log(arg.q) elif arg.is_Mul: expr = [] nonpos = [] for x in arg.args: if force or x.is_positive or x.is_polar: a = self.func(x) if isinstance(a, log): expr.append(self.func(x)._eval_expand_log(**hints)) else: expr.append(a) elif x.is_negative: a = self.func(-x) expr.append(a) nonpos.append(S.NegativeOne) else: nonpos.append(x) return Add(*expr) + log(Mul(*nonpos)) elif arg.is_Pow or isinstance(arg, exp): if force or (arg.exp.is_extended_real and (arg.base.is_positive or ((arg.exp+1) .is_positive and (arg.exp-1).is_nonpositive))) or arg.base.is_polar: b = arg.base e = arg.exp a = self.func(b) if isinstance(a, log): return unpolarify(e) * a._eval_expand_log(**hints) else: return unpolarify(e) * a elif isinstance(arg, Product): if force or arg.function.is_positive: return Sum(log(arg.function), *arg.limits) return self.func(arg) def _eval_simplify(self, **kwargs): from sympy.simplify.simplify import expand_log, simplify, inversecombine if len(self.args) == 2: # it's unevaluated return simplify(self.func(*self.args), **kwargs) expr = self.func(simplify(self.args[0], **kwargs)) if kwargs['inverse']: expr = inversecombine(expr) expr = expand_log(expr, deep=True) return min([expr, self], key=kwargs['measure']) def as_real_imag(self, deep=True, **hints): """ Returns this function as a complex coordinate. Examples ======== >>> from sympy import I, log >>> from sympy.abc import x >>> log(x).as_real_imag() (log(Abs(x)), arg(x)) >>> log(I).as_real_imag() (0, pi/2) >>> log(1 + I).as_real_imag() (log(sqrt(2)), pi/4) >>> log(I*x).as_real_imag() (log(Abs(x)), arg(I*x)) """ sarg = self.args[0] if deep: sarg = self.args[0].expand(deep, **hints) sarg_abs = Abs(sarg) if sarg_abs == sarg: return self, S.Zero sarg_arg = arg(sarg) if hints.get('log', False): # Expand the log hints['complex'] = False return (log(sarg_abs).expand(deep, **hints), sarg_arg) else: return log(sarg_abs), sarg_arg def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if (self.args[0] - 1).is_zero: return True if s.args[0].is_rational and fuzzy_not((self.args[0] - 1).is_zero): return False else: return s.is_rational def _eval_is_algebraic(self): s = self.func(*self.args) if s.func == self.func: if (self.args[0] - 1).is_zero: return True elif fuzzy_not((self.args[0] - 1).is_zero): if self.args[0].is_algebraic: return False else: return s.is_algebraic def _eval_is_extended_real(self): return self.args[0].is_extended_positive def _eval_is_complex(self): z = self.args[0] return fuzzy_and([z.is_complex, fuzzy_not(z.is_zero)]) def _eval_is_finite(self): arg = self.args[0] if arg.is_zero: return False return arg.is_finite def _eval_is_extended_positive(self): return (self.args[0] - 1).is_extended_positive def _eval_is_zero(self): return (self.args[0] - 1).is_zero def _eval_is_extended_nonnegative(self): return (self.args[0] - 1).is_extended_nonnegative def _eval_nseries(self, x, n, logx, cdir=0): # NOTE Please see the comment at the beginning of this file, labelled # IMPORTANT. from sympy.series.order import Order from sympy.simplify.simplify import logcombine from sympy.core.symbol import Dummy if self.args[0] == x: return log(x) if logx is None else logx arg = self.args[0] t = Dummy('t', positive=True) if cdir == 0: cdir = 1 z = arg.subs(x, cdir*t) k, l = Wild("k"), Wild("l") r = z.match(k*t**l) if r is not None: k, l = r[k], r[l] if l != 0 and not l.has(t) and not k.has(t): r = l*log(x) if logx is None else l*logx r += log(k) - l*log(cdir) # XXX true regardless of assumptions? return r def coeff_exp(term, x): coeff, exp = S.One, S.Zero for factor in Mul.make_args(term): if factor.has(x): base, exp = factor.as_base_exp() if base != x: try: return term.leadterm(x) except ValueError: return term, S.Zero else: coeff *= factor return coeff, exp # TODO new and probably slow try: a, b = z.leadterm(t, logx=logx, cdir=1) except (ValueError, NotImplementedError, PoleError): s = z._eval_nseries(t, n=n, logx=logx, cdir=1) while s.is_Order: n += 1 s = z._eval_nseries(t, n=n, logx=logx, cdir=1) try: a, b = s.removeO().leadterm(t, cdir=1) except ValueError: a, b = s.removeO().as_leading_term(t, cdir=1), S.Zero p = (z/(a*t**b) - 1)._eval_nseries(t, n=n, logx=logx, cdir=1) if p.has(exp): p = logcombine(p) if isinstance(p, Order): n = p.getn() _, d = coeff_exp(p, t) logx = log(x) if logx is None else logx if not d.is_positive: res = log(a) - b*log(cdir) + b*logx _res = res logflags = dict(deep=True, log=True, mul=False, power_exp=False, power_base=False, multinomial=False, basic=False, force=True, factor=False) expr = self.expand(**logflags) if (not a.could_extract_minus_sign() and logx.could_extract_minus_sign()): _res = _res.subs(-logx, -log(x)).expand(**logflags) else: _res = _res.subs(logx, log(x)).expand(**logflags) if _res == expr: return res return res + Order(x**n, x) def mul(d1, d2): res = {} for e1, e2 in product(d1, d2): ex = e1 + e2 if ex < n: res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2] return res pterms = {} for term in Add.make_args(p.removeO()): co1, e1 = coeff_exp(term, t) pterms[e1] = pterms.get(e1, S.Zero) + co1 k = S.One terms = {} pk = pterms while k*d < n: coeff = -S.NegativeOne**k/k for ex in pk: _ = terms.get(ex, S.Zero) + coeff*pk[ex] terms[ex] = _.nsimplify() pk = mul(pk, pterms) k += S.One res = log(a) - b*log(cdir) + b*logx for ex in terms: res += terms[ex]*t**(ex) if a.is_negative and im(z) != 0: from sympy.functions.special.delta_functions import Heaviside for i, term in enumerate(z.lseries(t)): if not term.is_real or i == 5: break if i < 5: coeff, _ = term.as_coeff_exponent(t) res += -2*I*pi*Heaviside(-im(coeff), 0) res = res.subs(t, x/cdir) return res + Order(x**n, x) def _eval_as_leading_term(self, x, logx=None, cdir=0): # NOTE # Refer https://github.com/sympy/sympy/pull/23592 for more information # on each of the following steps involved in this method. arg0 = self.args[0].together() # STEP 1 t = Dummy('t', positive=True) if cdir == 0: cdir = 1 z = arg0.subs(x, cdir*t) # STEP 2 try: c, e = z.leadterm(t, logx=logx, cdir=1) except ValueError: arg = arg0.as_leading_term(x, logx=logx, cdir=cdir) return log(arg) if c.has(t): c = c.subs(t, x/cdir) if e != 0: raise PoleError("Cannot expand %s around 0" % (self)) return log(c) # STEP 3 if c == S.One and e == S.Zero: return (arg0 - S.One).as_leading_term(x, logx=logx) # STEP 4 res = log(c) - e*log(cdir) logx = log(x) if logx is None else logx res += e*logx # STEP 5 if c.is_negative and im(z) != 0: from sympy.functions.special.delta_functions import Heaviside for i, term in enumerate(z.lseries(t)): if not term.is_real or i == 5: break if i < 5: coeff, _ = term.as_coeff_exponent(t) res += -2*I*pi*Heaviside(-im(coeff), 0) return res class LambertW(Function): r""" The Lambert W function $W(z)$ is defined as the inverse function of $w \exp(w)$ [1]_. Explanation =========== In other words, the value of $W(z)$ is such that $z = W(z) \exp(W(z))$ for any complex number $z$. The Lambert W function is a multivalued function with infinitely many branches $W_k(z)$, indexed by $k \in \mathbb{Z}$. Each branch gives a different solution $w$ of the equation $z = w \exp(w)$. The Lambert W function has two partially real branches: the principal branch ($k = 0$) is real for real $z > -1/e$, and the $k = -1$ branch is real for $-1/e < z < 0$. All branches except $k = 0$ have a logarithmic singularity at $z = 0$. Examples ======== >>> from sympy import LambertW >>> LambertW(1.2) 0.635564016364870 >>> LambertW(1.2, -1).n() -1.34747534407696 - 4.41624341514535*I >>> LambertW(-1).is_real False References ========== .. [1] https://en.wikipedia.org/wiki/Lambert_W_function """ _singularities = (-Pow(S.Exp1, -1, evaluate=False), S.ComplexInfinity) @classmethod def eval(cls, x, k=None): if k == S.Zero: return cls(x) elif k is None: k = S.Zero if k.is_zero: if x.is_zero: return S.Zero if x is S.Exp1: return S.One if x == -1/S.Exp1: return S.NegativeOne if x == -log(2)/2: return -log(2) if x == 2*log(2): return log(2) if x == -pi/2: return I*pi/2 if x == exp(1 + S.Exp1): return S.Exp1 if x is S.Infinity: return S.Infinity if x.is_zero: return S.Zero if fuzzy_not(k.is_zero): if x.is_zero: return S.NegativeInfinity if k is S.NegativeOne: if x == -pi/2: return -I*pi/2 elif x == -1/S.Exp1: return S.NegativeOne elif x == -2*exp(-2): return -Integer(2) def fdiff(self, argindex=1): """ Return the first derivative of this function. """ x = self.args[0] if len(self.args) == 1: if argindex == 1: return LambertW(x)/(x*(1 + LambertW(x))) else: k = self.args[1] if argindex == 1: return LambertW(x, k)/(x*(1 + LambertW(x, k))) raise ArgumentIndexError(self, argindex) def _eval_is_extended_real(self): x = self.args[0] if len(self.args) == 1: k = S.Zero else: k = self.args[1] if k.is_zero: if (x + 1/S.Exp1).is_positive: return True elif (x + 1/S.Exp1).is_nonpositive: return False elif (k + 1).is_zero: if x.is_negative and (x + 1/S.Exp1).is_positive: return True elif x.is_nonpositive or (x + 1/S.Exp1).is_nonnegative: return False elif fuzzy_not(k.is_zero) and fuzzy_not((k + 1).is_zero): if x.is_extended_real: return False def _eval_is_finite(self): return self.args[0].is_finite def _eval_is_algebraic(self): s = self.func(*self.args) if s.func == self.func: if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic: return False else: return s.is_algebraic def _eval_as_leading_term(self, x, logx=None, cdir=0): if len(self.args) == 1: arg = self.args[0] arg0 = arg.subs(x, 0).cancel() if not arg0.is_zero: return self.func(arg0) return arg.as_leading_term(x) def _eval_nseries(self, x, n, logx, cdir=0): if len(self.args) == 1: from sympy.functions.elementary.integers import ceiling from sympy.series.order import Order arg = self.args[0].nseries(x, n=n, logx=logx) lt = arg.as_leading_term(x, logx=logx) lte = 1 if lt.is_Pow: lte = lt.exp if ceiling(n/lte) >= 1: s = Add(*[(-S.One)**(k - 1)*Integer(k)**(k - 2)/ factorial(k - 1)*arg**k for k in range(1, ceiling(n/lte))]) s = expand_multinomial(s) else: s = S.Zero return s + Order(x**n, x) return super()._eval_nseries(x, n, logx) def _eval_is_zero(self): x = self.args[0] if len(self.args) == 1: return x.is_zero else: return fuzzy_and([x.is_zero, self.args[1].is_zero]) @cacheit def _log_atan_table(): return { # first quadrant only sqrt(3): pi / 3, 1: pi / 4, sqrt(5 - 2 * sqrt(5)): pi / 5, sqrt(2) * sqrt(5 - sqrt(5)) / (1 + sqrt(5)): pi / 5, sqrt(5 + 2 * sqrt(5)): pi * Rational(2, 5), sqrt(2) * sqrt(sqrt(5) + 5) / (-1 + sqrt(5)): pi * Rational(2, 5), sqrt(3) / 3: pi / 6, sqrt(2) - 1: pi / 8, sqrt(2 - sqrt(2)) / sqrt(sqrt(2) + 2): pi / 8, sqrt(2) + 1: pi * Rational(3, 8), sqrt(sqrt(2) + 2) / sqrt(2 - sqrt(2)): pi * Rational(3, 8), sqrt(1 - 2 * sqrt(5) / 5): pi / 10, (-sqrt(2) + sqrt(10)) / (2 * sqrt(sqrt(5) + 5)): pi / 10, sqrt(1 + 2 * sqrt(5) / 5): pi * Rational(3, 10), (sqrt(2) + sqrt(10)) / (2 * sqrt(5 - sqrt(5))): pi * Rational(3, 10), 2 - sqrt(3): pi / 12, (-1 + sqrt(3)) / (1 + sqrt(3)): pi / 12, 2 + sqrt(3): pi * Rational(5, 12), (1 + sqrt(3)) / (-1 + sqrt(3)): pi * Rational(5, 12) }
e7335d8395bbd63b4ad99ec506a81da1aa58638236b4ebdf5661a279e10598ef
from sympy.core import S, sympify, cacheit from sympy.core.add import Add from sympy.core.function import Function, ArgumentIndexError from sympy.core.logic import fuzzy_or, fuzzy_and, FuzzyBool from sympy.core.numbers import I, pi, Rational from sympy.core.symbol import Dummy from sympy.functions.combinatorial.factorials import (binomial, factorial, RisingFactorial) from sympy.functions.combinatorial.numbers import bernoulli, euler, nC from sympy.functions.elementary.complexes import Abs, im, re from sympy.functions.elementary.exponential import exp, log, match_real_imag from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import ( acos, acot, asin, atan, cos, cot, csc, sec, sin, tan, _imaginary_unit_as_coefficient) from sympy.polys.specialpolys import symmetric_poly def _rewrite_hyperbolics_as_exp(expr): return expr.xreplace({h: h.rewrite(exp) for h in expr.atoms(HyperbolicFunction)}) @cacheit def _acosh_table(): return { I: log(I*(1 + sqrt(2))), -I: log(-I*(1 + sqrt(2))), S.Half: pi/3, Rational(-1, 2): pi*Rational(2, 3), sqrt(2)/2: pi/4, -sqrt(2)/2: pi*Rational(3, 4), 1/sqrt(2): pi/4, -1/sqrt(2): pi*Rational(3, 4), sqrt(3)/2: pi/6, -sqrt(3)/2: pi*Rational(5, 6), (sqrt(3) - 1)/sqrt(2**3): pi*Rational(5, 12), -(sqrt(3) - 1)/sqrt(2**3): pi*Rational(7, 12), sqrt(2 + sqrt(2))/2: pi/8, -sqrt(2 + sqrt(2))/2: pi*Rational(7, 8), sqrt(2 - sqrt(2))/2: pi*Rational(3, 8), -sqrt(2 - sqrt(2))/2: pi*Rational(5, 8), (1 + sqrt(3))/(2*sqrt(2)): pi/12, -(1 + sqrt(3))/(2*sqrt(2)): pi*Rational(11, 12), (sqrt(5) + 1)/4: pi/5, -(sqrt(5) + 1)/4: pi*Rational(4, 5) } @cacheit def _acsch_table(): return { I: -pi / 2, I*(sqrt(2) + sqrt(6)): -pi / 12, I*(1 + sqrt(5)): -pi / 10, I*2 / sqrt(2 - sqrt(2)): -pi / 8, I*2: -pi / 6, I*sqrt(2 + 2/sqrt(5)): -pi / 5, I*sqrt(2): -pi / 4, I*(sqrt(5)-1): -3*pi / 10, I*2 / sqrt(3): -pi / 3, I*2 / sqrt(2 + sqrt(2)): -3*pi / 8, I*sqrt(2 - 2/sqrt(5)): -2*pi / 5, I*(sqrt(6) - sqrt(2)): -5*pi / 12, S(2): -I*log((1+sqrt(5))/2), } @cacheit def _asech_table(): return { I: - (pi*I / 2) + log(1 + sqrt(2)), -I: (pi*I / 2) + log(1 + sqrt(2)), (sqrt(6) - sqrt(2)): pi / 12, (sqrt(2) - sqrt(6)): 11*pi / 12, sqrt(2 - 2/sqrt(5)): pi / 10, -sqrt(2 - 2/sqrt(5)): 9*pi / 10, 2 / sqrt(2 + sqrt(2)): pi / 8, -2 / sqrt(2 + sqrt(2)): 7*pi / 8, 2 / sqrt(3): pi / 6, -2 / sqrt(3): 5*pi / 6, (sqrt(5) - 1): pi / 5, (1 - sqrt(5)): 4*pi / 5, sqrt(2): pi / 4, -sqrt(2): 3*pi / 4, sqrt(2 + 2/sqrt(5)): 3*pi / 10, -sqrt(2 + 2/sqrt(5)): 7*pi / 10, S(2): pi / 3, -S(2): 2*pi / 3, sqrt(2*(2 + sqrt(2))): 3*pi / 8, -sqrt(2*(2 + sqrt(2))): 5*pi / 8, (1 + sqrt(5)): 2*pi / 5, (-1 - sqrt(5)): 3*pi / 5, (sqrt(6) + sqrt(2)): 5*pi / 12, (-sqrt(6) - sqrt(2)): 7*pi / 12, I*S.Infinity: -pi*I / 2, I*S.NegativeInfinity: pi*I / 2, } ############################################################################### ########################### HYPERBOLIC FUNCTIONS ############################## ############################################################################### class HyperbolicFunction(Function): """ Base class for hyperbolic functions. See Also ======== sinh, cosh, tanh, coth """ unbranched = True def _peeloff_ipi(arg): r""" Split ARG into two parts, a "rest" and a multiple of $I\pi$. This assumes ARG to be an ``Add``. The multiple of $I\pi$ returned in the second position is always a ``Rational``. Examples ======== >>> from sympy.functions.elementary.hyperbolic import _peeloff_ipi as peel >>> from sympy import pi, I >>> from sympy.abc import x, y >>> peel(x + I*pi/2) (x, 1/2) >>> peel(x + I*2*pi/3 + I*pi*y) (x + I*pi*y + I*pi/6, 1/2) """ ipi = pi*I for a in Add.make_args(arg): if a == ipi: K = S.One break elif a.is_Mul: K, p = a.as_two_terms() if p == ipi and K.is_Rational: break else: return arg, S.Zero m1 = (K % S.Half) m2 = K - m1 return arg - m2*ipi, m2 class sinh(HyperbolicFunction): r""" ``sinh(x)`` is the hyperbolic sine of ``x``. The hyperbolic sine function is $\frac{e^x - e^{-x}}{2}$. Examples ======== >>> from sympy import sinh >>> from sympy.abc import x >>> sinh(x) sinh(x) See Also ======== cosh, tanh, asinh """ def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return cosh(self.args[0]) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return asinh @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.NegativeInfinity elif arg.is_zero: return S.Zero elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.NaN i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: return I * sin(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_Add: x, m = _peeloff_ipi(arg) if m: m = m*pi*I return sinh(m)*cosh(x) + cosh(m)*sinh(x) if arg.is_zero: return S.Zero if arg.func == asinh: return arg.args[0] if arg.func == acosh: x = arg.args[0] return sqrt(x - 1) * sqrt(x + 1) if arg.func == atanh: x = arg.args[0] return x/sqrt(1 - x**2) if arg.func == acoth: x = arg.args[0] return 1/(sqrt(x - 1) * sqrt(x + 1)) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): """ Returns the next term in the Taylor series expansion. """ if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 2: p = previous_terms[-2] return p * x**2 / (n*(n - 1)) else: return x**(n) / factorial(n) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): """ Returns this function as a complex coordinate. """ if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() return (sinh(re)*cos(im), cosh(re)*sin(im)) def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=deep, **hints) return re_part + im_part*I def _eval_expand_trig(self, deep=True, **hints): if deep: arg = self.args[0].expand(deep, **hints) else: arg = self.args[0] x = None if arg.is_Add: # TODO, implement more if deep stuff here x, y = arg.as_two_terms() else: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One and coeff.is_Integer and terms is not S.One: x = terms y = (coeff - 1)*x if x is not None: return (sinh(x)*cosh(y) + sinh(y)*cosh(x)).expand(trig=True) return sinh(arg) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): return (exp(arg) - exp(-arg)) / 2 def _eval_rewrite_as_exp(self, arg, **kwargs): return (exp(arg) - exp(-arg)) / 2 def _eval_rewrite_as_sin(self, arg, **kwargs): return -I * sin(I * arg) def _eval_rewrite_as_csc(self, arg, **kwargs): return -I / csc(I * arg) def _eval_rewrite_as_cosh(self, arg, **kwargs): return -I*cosh(arg + pi*I/2) def _eval_rewrite_as_tanh(self, arg, **kwargs): tanh_half = tanh(S.Half*arg) return 2*tanh_half/(1 - tanh_half**2) def _eval_rewrite_as_coth(self, arg, **kwargs): coth_half = coth(S.Half*arg) return 2*coth_half/(coth_half**2 - 1) def _eval_rewrite_as_csch(self, arg, **kwargs): return 1 / csch(arg) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if cdir.is_negative else '+') if arg0.is_zero: return arg elif arg0.is_finite: return self.func(arg0) else: return self def _eval_is_real(self): arg = self.args[0] if arg.is_real: return True # if `im` is of the form n*pi # else, check if it is a number re, im = arg.as_real_imag() return (im%pi).is_zero def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def _eval_is_positive(self): if self.args[0].is_extended_real: return self.args[0].is_positive def _eval_is_negative(self): if self.args[0].is_extended_real: return self.args[0].is_negative def _eval_is_finite(self): arg = self.args[0] return arg.is_finite def _eval_is_zero(self): rest, ipi_mult = _peeloff_ipi(self.args[0]) if rest.is_zero: return ipi_mult.is_integer class cosh(HyperbolicFunction): r""" ``cosh(x)`` is the hyperbolic cosine of ``x``. The hyperbolic cosine function is $\frac{e^x + e^{-x}}{2}$. Examples ======== >>> from sympy import cosh >>> from sympy.abc import x >>> cosh(x) cosh(x) See Also ======== sinh, tanh, acosh """ def fdiff(self, argindex=1): if argindex == 1: return sinh(self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.functions.elementary.trigonometric import cos if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Infinity elif arg.is_zero: return S.One elif arg.is_negative: return cls(-arg) else: if arg is S.ComplexInfinity: return S.NaN i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: return cos(i_coeff) else: if arg.could_extract_minus_sign(): return cls(-arg) if arg.is_Add: x, m = _peeloff_ipi(arg) if m: m = m*pi*I return cosh(m)*cosh(x) + sinh(m)*sinh(x) if arg.is_zero: return S.One if arg.func == asinh: return sqrt(1 + arg.args[0]**2) if arg.func == acosh: return arg.args[0] if arg.func == atanh: return 1/sqrt(1 - arg.args[0]**2) if arg.func == acoth: x = arg.args[0] return x/(sqrt(x - 1) * sqrt(x + 1)) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2: p = previous_terms[-2] return p * x**2 / (n*(n - 1)) else: return x**(n)/factorial(n) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() return (cosh(re)*cos(im), sinh(re)*sin(im)) def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=deep, **hints) return re_part + im_part*I def _eval_expand_trig(self, deep=True, **hints): if deep: arg = self.args[0].expand(deep, **hints) else: arg = self.args[0] x = None if arg.is_Add: # TODO, implement more if deep stuff here x, y = arg.as_two_terms() else: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One and coeff.is_Integer and terms is not S.One: x = terms y = (coeff - 1)*x if x is not None: return (cosh(x)*cosh(y) + sinh(x)*sinh(y)).expand(trig=True) return cosh(arg) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): return (exp(arg) + exp(-arg)) / 2 def _eval_rewrite_as_exp(self, arg, **kwargs): return (exp(arg) + exp(-arg)) / 2 def _eval_rewrite_as_cos(self, arg, **kwargs): return cos(I * arg) def _eval_rewrite_as_sec(self, arg, **kwargs): return 1 / sec(I * arg) def _eval_rewrite_as_sinh(self, arg, **kwargs): return -I*sinh(arg + pi*I/2) def _eval_rewrite_as_tanh(self, arg, **kwargs): tanh_half = tanh(S.Half*arg)**2 return (1 + tanh_half)/(1 - tanh_half) def _eval_rewrite_as_coth(self, arg, **kwargs): coth_half = coth(S.Half*arg)**2 return (coth_half + 1)/(coth_half - 1) def _eval_rewrite_as_sech(self, arg, **kwargs): return 1 / sech(arg) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if cdir.is_negative else '+') if arg0.is_zero: return S.One elif arg0.is_finite: return self.func(arg0) else: return self def _eval_is_real(self): arg = self.args[0] # `cosh(x)` is real for real OR purely imaginary `x` if arg.is_real or arg.is_imaginary: return True # cosh(a+ib) = cos(b)*cosh(a) + i*sin(b)*sinh(a) # the imaginary part can be an expression like n*pi # if not, check if the imaginary part is a number re, im = arg.as_real_imag() return (im%pi).is_zero def _eval_is_positive(self): # cosh(x+I*y) = cos(y)*cosh(x) + I*sin(y)*sinh(x) # cosh(z) is positive iff it is real and the real part is positive. # So we need sin(y)*sinh(x) = 0 which gives x=0 or y=n*pi # Case 1 (y=n*pi): cosh(z) = (-1)**n * cosh(x) -> positive for n even # Case 2 (x=0): cosh(z) = cos(y) -> positive when cos(y) is positive z = self.args[0] x, y = z.as_real_imag() ymod = y % (2*pi) yzero = ymod.is_zero # shortcut if ymod is zero if yzero: return True xzero = x.is_zero # shortcut x is not zero if xzero is False: return yzero return fuzzy_or([ # Case 1: yzero, # Case 2: fuzzy_and([ xzero, fuzzy_or([ymod < pi/2, ymod > 3*pi/2]) ]) ]) def _eval_is_nonnegative(self): z = self.args[0] x, y = z.as_real_imag() ymod = y % (2*pi) yzero = ymod.is_zero # shortcut if ymod is zero if yzero: return True xzero = x.is_zero # shortcut x is not zero if xzero is False: return yzero return fuzzy_or([ # Case 1: yzero, # Case 2: fuzzy_and([ xzero, fuzzy_or([ymod <= pi/2, ymod >= 3*pi/2]) ]) ]) def _eval_is_finite(self): arg = self.args[0] return arg.is_finite def _eval_is_zero(self): rest, ipi_mult = _peeloff_ipi(self.args[0]) if ipi_mult and rest.is_zero: return (ipi_mult - S.Half).is_integer class tanh(HyperbolicFunction): r""" ``tanh(x)`` is the hyperbolic tangent of ``x``. The hyperbolic tangent function is $\frac{\sinh(x)}{\cosh(x)}$. Examples ======== >>> from sympy import tanh >>> from sympy.abc import x >>> tanh(x) tanh(x) See Also ======== sinh, cosh, atanh """ def fdiff(self, argindex=1): if argindex == 1: return S.One - tanh(self.args[0])**2 else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return atanh @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.One elif arg is S.NegativeInfinity: return S.NegativeOne elif arg.is_zero: return S.Zero elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.NaN i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: if i_coeff.could_extract_minus_sign(): return -I * tan(-i_coeff) return I * tan(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_Add: x, m = _peeloff_ipi(arg) if m: tanhm = tanh(m*pi*I) if tanhm is S.ComplexInfinity: return coth(x) else: # tanhm == 0 return tanh(x) if arg.is_zero: return S.Zero if arg.func == asinh: x = arg.args[0] return x/sqrt(1 + x**2) if arg.func == acosh: x = arg.args[0] return sqrt(x - 1) * sqrt(x + 1) / x if arg.func == atanh: return arg.args[0] if arg.func == acoth: return 1/arg.args[0] @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) a = 2**(n + 1) B = bernoulli(n + 1) F = factorial(n + 1) return a*(a - 1) * B/F * x**n def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() denom = sinh(re)**2 + cos(im)**2 return (sinh(re)*cosh(re)/denom, sin(im)*cos(im)/denom) def _eval_expand_trig(self, **hints): arg = self.args[0] if arg.is_Add: n = len(arg.args) TX = [tanh(x, evaluate=False)._eval_expand_trig() for x in arg.args] p = [0, 0] # [den, num] for i in range(n + 1): p[i % 2] += symmetric_poly(i, TX) return p[1]/p[0] elif arg.is_Mul: coeff, terms = arg.as_coeff_Mul() if coeff.is_Integer and coeff > 1: T = tanh(terms) n = [nC(range(coeff), k)*T**k for k in range(1, coeff + 1, 2)] d = [nC(range(coeff), k)*T**k for k in range(0, coeff + 1, 2)] return Add(*n)/Add(*d) return tanh(arg) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): neg_exp, pos_exp = exp(-arg), exp(arg) return (pos_exp - neg_exp)/(pos_exp + neg_exp) def _eval_rewrite_as_exp(self, arg, **kwargs): neg_exp, pos_exp = exp(-arg), exp(arg) return (pos_exp - neg_exp)/(pos_exp + neg_exp) def _eval_rewrite_as_tan(self, arg, **kwargs): return -I * tan(I * arg) def _eval_rewrite_as_cot(self, arg, **kwargs): return -I / cot(I * arg) def _eval_rewrite_as_sinh(self, arg, **kwargs): return I*sinh(arg)/sinh(pi*I/2 - arg) def _eval_rewrite_as_cosh(self, arg, **kwargs): return I*cosh(pi*I/2 - arg)/cosh(arg) def _eval_rewrite_as_coth(self, arg, **kwargs): return 1/coth(arg) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return arg else: return self.func(arg) def _eval_is_real(self): arg = self.args[0] if arg.is_real: return True re, im = arg.as_real_imag() # if denom = 0, tanh(arg) = zoo if re == 0 and im % pi == pi/2: return None # check if im is of the form n*pi/2 to make sin(2*im) = 0 # if not, im could be a number, return False in that case return (im % (pi/2)).is_zero def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def _eval_is_positive(self): if self.args[0].is_extended_real: return self.args[0].is_positive def _eval_is_negative(self): if self.args[0].is_extended_real: return self.args[0].is_negative def _eval_is_finite(self): arg = self.args[0] re, im = arg.as_real_imag() denom = cos(im)**2 + sinh(re)**2 if denom == 0: return False elif denom.is_number: return True if arg.is_extended_real: return True def _eval_is_zero(self): arg = self.args[0] if arg.is_zero: return True class coth(HyperbolicFunction): r""" ``coth(x)`` is the hyperbolic cotangent of ``x``. The hyperbolic cotangent function is $\frac{\cosh(x)}{\sinh(x)}$. Examples ======== >>> from sympy import coth >>> from sympy.abc import x >>> coth(x) coth(x) See Also ======== sinh, cosh, acoth """ def fdiff(self, argindex=1): if argindex == 1: return -1/sinh(self.args[0])**2 else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return acoth @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.One elif arg is S.NegativeInfinity: return S.NegativeOne elif arg.is_zero: return S.ComplexInfinity elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.NaN i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: if i_coeff.could_extract_minus_sign(): return I * cot(-i_coeff) return -I * cot(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_Add: x, m = _peeloff_ipi(arg) if m: cothm = coth(m*pi*I) if cothm is S.ComplexInfinity: return coth(x) else: # cothm == 0 return tanh(x) if arg.is_zero: return S.ComplexInfinity if arg.func == asinh: x = arg.args[0] return sqrt(1 + x**2)/x if arg.func == acosh: x = arg.args[0] return x/(sqrt(x - 1) * sqrt(x + 1)) if arg.func == atanh: return 1/arg.args[0] if arg.func == acoth: return arg.args[0] @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return 1 / sympify(x) elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) B = bernoulli(n + 1) F = factorial(n + 1) return 2**(n + 1) * B/F * x**n def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): from sympy.functions.elementary.trigonometric import (cos, sin) if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() denom = sinh(re)**2 + sin(im)**2 return (sinh(re)*cosh(re)/denom, -sin(im)*cos(im)/denom) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): neg_exp, pos_exp = exp(-arg), exp(arg) return (pos_exp + neg_exp)/(pos_exp - neg_exp) def _eval_rewrite_as_exp(self, arg, **kwargs): neg_exp, pos_exp = exp(-arg), exp(arg) return (pos_exp + neg_exp)/(pos_exp - neg_exp) def _eval_rewrite_as_sinh(self, arg, **kwargs): return -I*sinh(pi*I/2 - arg)/sinh(arg) def _eval_rewrite_as_cosh(self, arg, **kwargs): return -I*cosh(arg)/cosh(pi*I/2 - arg) def _eval_rewrite_as_tanh(self, arg, **kwargs): return 1/tanh(arg) def _eval_is_positive(self): if self.args[0].is_extended_real: return self.args[0].is_positive def _eval_is_negative(self): if self.args[0].is_extended_real: return self.args[0].is_negative def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return 1/arg else: return self.func(arg) def _eval_expand_trig(self, **hints): arg = self.args[0] if arg.is_Add: CX = [coth(x, evaluate=False)._eval_expand_trig() for x in arg.args] p = [[], []] n = len(arg.args) for i in range(n, -1, -1): p[(n - i) % 2].append(symmetric_poly(i, CX)) return Add(*p[0])/Add(*p[1]) elif arg.is_Mul: coeff, x = arg.as_coeff_Mul(rational=True) if coeff.is_Integer and coeff > 1: c = coth(x, evaluate=False) p = [[], []] for i in range(coeff, -1, -1): p[(coeff - i) % 2].append(binomial(coeff, i)*c**i) return Add(*p[0])/Add(*p[1]) return coth(arg) class ReciprocalHyperbolicFunction(HyperbolicFunction): """Base class for reciprocal functions of hyperbolic functions. """ #To be defined in class _reciprocal_of = None _is_even = None # type: FuzzyBool _is_odd = None # type: FuzzyBool @classmethod def eval(cls, arg): if arg.could_extract_minus_sign(): if cls._is_even: return cls(-arg) if cls._is_odd: return -cls(-arg) t = cls._reciprocal_of.eval(arg) if hasattr(arg, 'inverse') and arg.inverse() == cls: return arg.args[0] return 1/t if t is not None else t def _call_reciprocal(self, method_name, *args, **kwargs): # Calls method_name on _reciprocal_of o = self._reciprocal_of(self.args[0]) return getattr(o, method_name)(*args, **kwargs) def _calculate_reciprocal(self, method_name, *args, **kwargs): # If calling method_name on _reciprocal_of returns a value != None # then return the reciprocal of that value t = self._call_reciprocal(method_name, *args, **kwargs) return 1/t if t is not None else t def _rewrite_reciprocal(self, method_name, arg): # Special handling for rewrite functions. If reciprocal rewrite returns # unmodified expression, then return None t = self._call_reciprocal(method_name, arg) if t is not None and t != self._reciprocal_of(arg): return 1/t def _eval_rewrite_as_exp(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_exp", arg) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_tractable", arg) def _eval_rewrite_as_tanh(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_tanh", arg) def _eval_rewrite_as_coth(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_coth", arg) def as_real_imag(self, deep = True, **hints): return (1 / self._reciprocal_of(self.args[0])).as_real_imag(deep, **hints) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=True, **hints) return re_part + I*im_part def _eval_expand_trig(self, **hints): return self._calculate_reciprocal("_eval_expand_trig", **hints) def _eval_as_leading_term(self, x, logx=None, cdir=0): return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x) def _eval_is_extended_real(self): return self._reciprocal_of(self.args[0]).is_extended_real def _eval_is_finite(self): return (1/self._reciprocal_of(self.args[0])).is_finite class csch(ReciprocalHyperbolicFunction): r""" ``csch(x)`` is the hyperbolic cosecant of ``x``. The hyperbolic cosecant function is $\frac{2}{e^x - e^{-x}}$ Examples ======== >>> from sympy import csch >>> from sympy.abc import x >>> csch(x) csch(x) See Also ======== sinh, cosh, tanh, sech, asinh, acosh """ _reciprocal_of = sinh _is_odd = True def fdiff(self, argindex=1): """ Returns the first derivative of this function """ if argindex == 1: return -coth(self.args[0]) * csch(self.args[0]) else: raise ArgumentIndexError(self, argindex) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): """ Returns the next term in the Taylor series expansion """ if n == 0: return 1/sympify(x) elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) B = bernoulli(n + 1) F = factorial(n + 1) return 2 * (1 - 2**n) * B/F * x**n def _eval_rewrite_as_sin(self, arg, **kwargs): return I / sin(I * arg) def _eval_rewrite_as_csc(self, arg, **kwargs): return I * csc(I * arg) def _eval_rewrite_as_cosh(self, arg, **kwargs): return I / cosh(arg + I * pi / 2) def _eval_rewrite_as_sinh(self, arg, **kwargs): return 1 / sinh(arg) def _eval_is_positive(self): if self.args[0].is_extended_real: return self.args[0].is_positive def _eval_is_negative(self): if self.args[0].is_extended_real: return self.args[0].is_negative class sech(ReciprocalHyperbolicFunction): r""" ``sech(x)`` is the hyperbolic secant of ``x``. The hyperbolic secant function is $\frac{2}{e^x + e^{-x}}$ Examples ======== >>> from sympy import sech >>> from sympy.abc import x >>> sech(x) sech(x) See Also ======== sinh, cosh, tanh, coth, csch, asinh, acosh """ _reciprocal_of = cosh _is_even = True def fdiff(self, argindex=1): if argindex == 1: return - tanh(self.args[0])*sech(self.args[0]) else: raise ArgumentIndexError(self, argindex) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) return euler(n) / factorial(n) * x**(n) def _eval_rewrite_as_cos(self, arg, **kwargs): return 1 / cos(I * arg) def _eval_rewrite_as_sec(self, arg, **kwargs): return sec(I * arg) def _eval_rewrite_as_sinh(self, arg, **kwargs): return I / sinh(arg + I * pi /2) def _eval_rewrite_as_cosh(self, arg, **kwargs): return 1 / cosh(arg) def _eval_is_positive(self): if self.args[0].is_extended_real: return True ############################################################################### ############################# HYPERBOLIC INVERSES ############################# ############################################################################### class InverseHyperbolicFunction(Function): """Base class for inverse hyperbolic functions.""" pass class asinh(InverseHyperbolicFunction): """ ``asinh(x)`` is the inverse hyperbolic sine of ``x``. The inverse hyperbolic sine function. Examples ======== >>> from sympy import asinh >>> from sympy.abc import x >>> asinh(x).diff(x) 1/sqrt(x**2 + 1) >>> asinh(1) log(1 + sqrt(2)) See Also ======== acosh, atanh, sinh """ def fdiff(self, argindex=1): if argindex == 1: return 1/sqrt(self.args[0]**2 + 1) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.NegativeInfinity elif arg.is_zero: return S.Zero elif arg is S.One: return log(sqrt(2) + 1) elif arg is S.NegativeOne: return log(sqrt(2) - 1) elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.ComplexInfinity if arg.is_zero: return S.Zero i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: return I * asin(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if isinstance(arg, sinh) and arg.args[0].is_number: z = arg.args[0] if z.is_real: return z r, i = match_real_imag(z) if r is not None and i is not None: f = floor((i + pi/2)/pi) m = z - I*pi*f even = f.is_even if even is True: return m elif even is False: return -m @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) >= 2 and n > 2: p = previous_terms[-2] return -p * (n - 2)**2/(n*(n - 1)) * x**2 else: k = (n - 1) // 2 R = RisingFactorial(S.Half, k) F = factorial(k) return S.NegativeOne**k * R / F * x**n / n def _eval_as_leading_term(self, x, logx=None, cdir=0): # asinh arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0.is_zero: return arg.as_leading_term(x) # Handling branch points if x0 in (-I, I, S.ComplexInfinity): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) # Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo) if (1 + x0**2).is_negative: ndir = arg.dir(x, cdir if cdir else 1) if re(ndir).is_positive: if im(x0).is_negative: return -self.func(x0) - I*pi elif re(ndir).is_negative: if im(x0).is_positive: return -self.func(x0) + I*pi else: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # asinh arg = self.args[0] arg0 = arg.subs(x, 0) # Handling branch points if arg0 in (I, -I): return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res # Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo) if (1 + arg0**2).is_negative: ndir = arg.dir(x, cdir if cdir else 1) if re(ndir).is_positive: if im(arg0).is_negative: return -res - I*pi elif re(ndir).is_negative: if im(arg0).is_positive: return -res + I*pi else: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def _eval_rewrite_as_log(self, x, **kwargs): return log(x + sqrt(x**2 + 1)) _eval_rewrite_as_tractable = _eval_rewrite_as_log def _eval_rewrite_as_atanh(self, x, **kwargs): return atanh(x/sqrt(1 + x**2)) def _eval_rewrite_as_acosh(self, x, **kwargs): ix = I*x return I*(sqrt(1 - ix)/sqrt(ix - 1) * acosh(ix) - pi/2) def _eval_rewrite_as_asin(self, x, **kwargs): return -I * asin(I * x) def _eval_rewrite_as_acos(self, x, **kwargs): return I * acos(I * x) - I*pi/2 def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sinh def _eval_is_zero(self): return self.args[0].is_zero class acosh(InverseHyperbolicFunction): """ ``acosh(x)`` is the inverse hyperbolic cosine of ``x``. The inverse hyperbolic cosine function. Examples ======== >>> from sympy import acosh >>> from sympy.abc import x >>> acosh(x).diff(x) 1/(sqrt(x - 1)*sqrt(x + 1)) >>> acosh(1) 0 See Also ======== asinh, atanh, cosh """ def fdiff(self, argindex=1): if argindex == 1: arg = self.args[0] return 1/(sqrt(arg - 1)*sqrt(arg + 1)) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Infinity elif arg.is_zero: return pi*I / 2 elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return pi*I if arg.is_number: cst_table = _acosh_table() if arg in cst_table: if arg.is_extended_real: return cst_table[arg]*I return cst_table[arg] if arg is S.ComplexInfinity: return S.ComplexInfinity if arg == I*S.Infinity: return S.Infinity + I*pi/2 if arg == -I*S.Infinity: return S.Infinity - I*pi/2 if arg.is_zero: return pi*I*S.Half if isinstance(arg, cosh) and arg.args[0].is_number: z = arg.args[0] if z.is_real: return Abs(z) r, i = match_real_imag(z) if r is not None and i is not None: f = floor(i/pi) m = z - I*pi*f even = f.is_even if even is True: if r.is_nonnegative: return m elif r.is_negative: return -m elif even is False: m -= I*pi if r.is_nonpositive: return -m elif r.is_positive: return m @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return I*pi/2 elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) >= 2 and n > 2: p = previous_terms[-2] return p * (n - 2)**2/(n*(n - 1)) * x**2 else: k = (n - 1) // 2 R = RisingFactorial(S.Half, k) F = factorial(k) return -R / F * I * x**n / n def _eval_as_leading_term(self, x, logx=None, cdir=0): # acosh arg = self.args[0] x0 = arg.subs(x, 0).cancel() # Handling branch points if x0 in (-S.One, S.Zero, S.One, S.ComplexInfinity): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) # Handling points lying on branch cuts (-oo, 1) if (x0 - 1).is_negative: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_negative: if (x0 + 1).is_negative: return self.func(x0) - 2*I*pi return -self.func(x0) elif not im(ndir).is_positive: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # acosh arg = self.args[0] arg0 = arg.subs(x, 0) # Handling branch points if arg0 in (S.One, S.NegativeOne): return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res # Handling points lying on branch cuts (-oo, 1) if (arg0 - 1).is_negative: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_negative: if (arg0 + 1).is_negative: return res - 2*I*pi return -res elif not im(ndir).is_positive: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def _eval_rewrite_as_log(self, x, **kwargs): return log(x + sqrt(x + 1) * sqrt(x - 1)) _eval_rewrite_as_tractable = _eval_rewrite_as_log def _eval_rewrite_as_acos(self, x, **kwargs): return sqrt(x - 1)/sqrt(1 - x) * acos(x) def _eval_rewrite_as_asin(self, x, **kwargs): return sqrt(x - 1)/sqrt(1 - x) * (pi/2 - asin(x)) def _eval_rewrite_as_asinh(self, x, **kwargs): return sqrt(x - 1)/sqrt(1 - x) * (pi/2 + I*asinh(I*x)) def _eval_rewrite_as_atanh(self, x, **kwargs): sxm1 = sqrt(x - 1) s1mx = sqrt(1 - x) sx2m1 = sqrt(x**2 - 1) return (pi/2*sxm1/s1mx*(1 - x * sqrt(1/x**2)) + sxm1*sqrt(x + 1)/sx2m1 * atanh(sx2m1/x)) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return cosh def _eval_is_zero(self): if (self.args[0] - 1).is_zero: return True class atanh(InverseHyperbolicFunction): """ ``atanh(x)`` is the inverse hyperbolic tangent of ``x``. The inverse hyperbolic tangent function. Examples ======== >>> from sympy import atanh >>> from sympy.abc import x >>> atanh(x).diff(x) 1/(1 - x**2) See Also ======== asinh, acosh, tanh """ def fdiff(self, argindex=1): if argindex == 1: return 1/(1 - self.args[0]**2) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.Zero elif arg is S.One: return S.Infinity elif arg is S.NegativeOne: return S.NegativeInfinity elif arg is S.Infinity: return -I * atan(arg) elif arg is S.NegativeInfinity: return I * atan(-arg) elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: from sympy.calculus.accumulationbounds import AccumBounds return I*AccumBounds(-pi/2, pi/2) i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: return I * atan(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_zero: return S.Zero if isinstance(arg, tanh) and arg.args[0].is_number: z = arg.args[0] if z.is_real: return z r, i = match_real_imag(z) if r is not None and i is not None: f = floor(2*i/pi) even = f.is_even m = z - I*f*pi/2 if even is True: return m elif even is False: return m - I*pi/2 @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) return x**n / n def _eval_as_leading_term(self, x, logx=None, cdir=0): # atanh arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0.is_zero: return arg.as_leading_term(x) # Handling branch points if x0 in (-S.One, S.One, S.ComplexInfinity): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) # Handling points lying on branch cuts (-oo, -1] U [1, oo) if (1 - x0**2).is_negative: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_negative: if x0.is_negative: return self.func(x0) - I*pi elif im(ndir).is_positive: if x0.is_positive: return self.func(x0) + I*pi else: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # atanh arg = self.args[0] arg0 = arg.subs(x, 0) # Handling branch points if arg0 in (S.One, S.NegativeOne): return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res # Handling points lying on branch cuts (-oo, -1] U [1, oo) if (1 - arg0**2).is_negative: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_negative: if arg0.is_negative: return res - I*pi elif im(ndir).is_positive: if arg0.is_positive: return res + I*pi else: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def _eval_rewrite_as_log(self, x, **kwargs): return (log(1 + x) - log(1 - x)) / 2 _eval_rewrite_as_tractable = _eval_rewrite_as_log def _eval_rewrite_as_asinh(self, x, **kwargs): f = sqrt(1/(x**2 - 1)) return (pi*x/(2*sqrt(-x**2)) - sqrt(-x)*sqrt(1 - x**2)/sqrt(x)*f*asinh(f)) def _eval_is_zero(self): if self.args[0].is_zero: return True def _eval_is_imaginary(self): return self.args[0].is_imaginary def inverse(self, argindex=1): """ Returns the inverse of this function. """ return tanh class acoth(InverseHyperbolicFunction): """ ``acoth(x)`` is the inverse hyperbolic cotangent of ``x``. The inverse hyperbolic cotangent function. Examples ======== >>> from sympy import acoth >>> from sympy.abc import x >>> acoth(x).diff(x) 1/(1 - x**2) See Also ======== asinh, acosh, coth """ def fdiff(self, argindex=1): if argindex == 1: return 1/(1 - self.args[0]**2) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return pi*I / 2 elif arg is S.One: return S.Infinity elif arg is S.NegativeOne: return S.NegativeInfinity elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.Zero i_coeff = _imaginary_unit_as_coefficient(arg) if i_coeff is not None: return -I * acot(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_zero: return pi*I*S.Half @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return -I*pi/2 elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) return x**n / n def _eval_as_leading_term(self, x, logx=None, cdir=0): # acoth arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0 is S.ComplexInfinity: return (1/arg).as_leading_term(x) # Handling branch points if x0 in (-S.One, S.One, S.Zero): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) # Handling points lying on branch cuts [-1, 1] if x0.is_real and (1 - x0**2).is_positive: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_negative: if x0.is_positive: return self.func(x0) + I*pi elif im(ndir).is_positive: if x0.is_negative: return self.func(x0) - I*pi else: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # acoth arg = self.args[0] arg0 = arg.subs(x, 0) # Handling branch points if arg0 in (S.One, S.NegativeOne): return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res # Handling points lying on branch cuts [-1, 1] if arg0.is_real and (1 - arg0**2).is_positive: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_negative: if arg0.is_positive: return res + I*pi elif im(ndir).is_positive: if arg0.is_negative: return res - I*pi else: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def _eval_rewrite_as_log(self, x, **kwargs): return (log(1 + 1/x) - log(1 - 1/x)) / 2 _eval_rewrite_as_tractable = _eval_rewrite_as_log def _eval_rewrite_as_atanh(self, x, **kwargs): return atanh(1/x) def _eval_rewrite_as_asinh(self, x, **kwargs): return (pi*I/2*(sqrt((x - 1)/x)*sqrt(x/(x - 1)) - sqrt(1 + 1/x)*sqrt(x/(x + 1))) + x*sqrt(1/x**2)*asinh(sqrt(1/(x**2 - 1)))) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return coth class asech(InverseHyperbolicFunction): """ ``asech(x)`` is the inverse hyperbolic secant of ``x``. The inverse hyperbolic secant function. Examples ======== >>> from sympy import asech, sqrt, S >>> from sympy.abc import x >>> asech(x).diff(x) -1/(x*sqrt(1 - x**2)) >>> asech(1).diff(x) 0 >>> asech(1) 0 >>> asech(S(2)) I*pi/3 >>> asech(-sqrt(2)) 3*I*pi/4 >>> asech((sqrt(6) - sqrt(2))) I*pi/12 See Also ======== asinh, atanh, cosh, acoth References ========== .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function .. [2] http://dlmf.nist.gov/4.37 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcSech/ """ def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] return -1/(z*sqrt(1 - z**2)) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return pi*I / 2 elif arg is S.NegativeInfinity: return pi*I / 2 elif arg.is_zero: return S.Infinity elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return pi*I if arg.is_number: cst_table = _asech_table() if arg in cst_table: if arg.is_extended_real: return cst_table[arg]*I return cst_table[arg] if arg is S.ComplexInfinity: from sympy.calculus.accumulationbounds import AccumBounds return I*AccumBounds(-pi/2, pi/2) if arg.is_zero: return S.Infinity @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return log(2 / x) elif n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2 and n > 2: p = previous_terms[-2] return p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2) else: k = n // 2 R = RisingFactorial(S.Half, k) * n F = factorial(k) * n // 2 * n // 2 return -1 * R / F * x**n / 4 def _eval_as_leading_term(self, x, logx=None, cdir=0): # asech arg = self.args[0] x0 = arg.subs(x, 0).cancel() # Handling branch points if x0 in (-S.One, S.Zero, S.One, S.ComplexInfinity): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) # Handling points lying on branch cuts (-oo, 0] U (1, oo) if x0.is_negative or (1 - x0).is_negative: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_positive: if x0.is_positive or (x0 + 1).is_negative: return -self.func(x0) return self.func(x0) - 2*I*pi elif not im(ndir).is_negative: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # asech from sympy.series.order import O arg = self.args[0] arg0 = arg.subs(x, 0) # Handling branch points if arg0 is S.One: t = Dummy('t', positive=True) ser = asech(S.One - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = asech(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else I*pi + O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res # Handling points lying on branch cuts (-oo, 0] U (1, oo) if arg0.is_negative or (1 - arg0).is_negative: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_positive: if arg0.is_positive or (arg0 + 1).is_negative: return -res return res - 2*I*pi elif not im(ndir).is_negative: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sech def _eval_rewrite_as_log(self, arg, **kwargs): return log(1/arg + sqrt(1/arg - 1) * sqrt(1/arg + 1)) _eval_rewrite_as_tractable = _eval_rewrite_as_log def _eval_rewrite_as_acosh(self, arg, **kwargs): return acosh(1/arg) def _eval_rewrite_as_asinh(self, arg, **kwargs): return sqrt(1/arg - 1)/sqrt(1 - 1/arg)*(I*asinh(I/arg) + pi*S.Half) def _eval_rewrite_as_atanh(self, x, **kwargs): return (I*pi*(1 - sqrt(x)*sqrt(1/x) - I/2*sqrt(-x)/sqrt(x) - I/2*sqrt(x**2)/sqrt(-x**2)) + sqrt(1/(x + 1))*sqrt(x + 1)*atanh(sqrt(1 - x**2))) def _eval_rewrite_as_acsch(self, x, **kwargs): return sqrt(1/x - 1)/sqrt(1 - 1/x)*(pi/2 - I*acsch(I*x)) class acsch(InverseHyperbolicFunction): """ ``acsch(x)`` is the inverse hyperbolic cosecant of ``x``. The inverse hyperbolic cosecant function. Examples ======== >>> from sympy import acsch, sqrt, I >>> from sympy.abc import x >>> acsch(x).diff(x) -1/(x**2*sqrt(1 + x**(-2))) >>> acsch(1).diff(x) 0 >>> acsch(1) log(1 + sqrt(2)) >>> acsch(I) -I*pi/2 >>> acsch(-2*I) I*pi/6 >>> acsch(I*(sqrt(6) - sqrt(2))) -5*I*pi/12 See Also ======== asinh References ========== .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function .. [2] http://dlmf.nist.gov/4.37 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcCsch/ """ def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] return -1/(z**2*sqrt(1 + 1/z**2)) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return S.ComplexInfinity elif arg is S.One: return log(1 + sqrt(2)) elif arg is S.NegativeOne: return - log(1 + sqrt(2)) if arg.is_number: cst_table = _acsch_table() if arg in cst_table: return cst_table[arg]*I if arg is S.ComplexInfinity: return S.Zero if arg.is_infinite: return S.Zero if arg.is_zero: return S.ComplexInfinity if arg.could_extract_minus_sign(): return -cls(-arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return log(2 / x) elif n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2 and n > 2: p = previous_terms[-2] return -p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2) else: k = n // 2 R = RisingFactorial(S.Half, k) * n F = factorial(k) * n // 2 * n // 2 return S.NegativeOne**(k +1) * R / F * x**n / 4 def _eval_as_leading_term(self, x, logx=None, cdir=0): # acsch arg = self.args[0] x0 = arg.subs(x, 0).cancel() # Handling branch points if x0 in (-I, I, S.Zero): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) if x0 is S.ComplexInfinity: return (1/arg).as_leading_term(x) # Handling points lying on branch cuts (-I, I) if x0.is_imaginary and (1 + x0**2).is_positive: ndir = arg.dir(x, cdir if cdir else 1) if re(ndir).is_positive: if im(x0).is_positive: return -self.func(x0) - I*pi elif re(ndir).is_negative: if im(x0).is_negative: return -self.func(x0) + I*pi else: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # acsch from sympy.series.order import O arg = self.args[0] arg0 = arg.subs(x, 0) # Handling branch points if arg0 is I: t = Dummy('t', positive=True) ser = acsch(I + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = -I + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else -I*pi/2 + O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() res = ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) return res if arg0 == S.NegativeOne*I: t = Dummy('t', positive=True) ser = acsch(-I + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = I + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else I*pi/2 + O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res # Handling points lying on branch cuts (-I, I) if arg0.is_imaginary and (1 + arg0**2).is_positive: ndir = self.args[0].dir(x, cdir if cdir else 1) if re(ndir).is_positive: if im(arg0).is_positive: return -res - I*pi elif re(ndir).is_negative: if im(arg0).is_negative: return -res + I*pi else: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def inverse(self, argindex=1): """ Returns the inverse of this function. """ return csch def _eval_rewrite_as_log(self, arg, **kwargs): return log(1/arg + sqrt(1/arg**2 + 1)) _eval_rewrite_as_tractable = _eval_rewrite_as_log def _eval_rewrite_as_asinh(self, arg, **kwargs): return asinh(1/arg) def _eval_rewrite_as_acosh(self, arg, **kwargs): return I*(sqrt(1 - I/arg)/sqrt(I/arg - 1)* acosh(I/arg) - pi*S.Half) def _eval_rewrite_as_atanh(self, arg, **kwargs): arg2 = arg**2 arg2p1 = arg2 + 1 return sqrt(-arg2)/arg*(pi*S.Half - sqrt(-arg2p1**2)/arg2p1*atanh(sqrt(arg2p1))) def _eval_is_zero(self): return self.args[0].is_infinite
c30c8477011a4f2a6cfd93c403aebb5bb6ff54b758c1a67671d136bdde5de4d2
from typing import Tuple as tTuple from sympy.core import S, Add, Mul, sympify, Symbol, Dummy, Basic from sympy.core.expr import Expr from sympy.core.exprtools import factor_terms from sympy.core.function import (Function, Derivative, ArgumentIndexError, AppliedUndef, expand_mul) from sympy.core.logic import fuzzy_not, fuzzy_or from sympy.core.numbers import pi, I, oo from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise ############################################################################### ######################### REAL and IMAGINARY PARTS ############################ ############################################################################### class re(Function): """ Returns real part of expression. This function performs only elementary analysis and so it will fail to decompose properly more complicated expressions. If completely simplified result is needed then use ``Basic.as_real_imag()`` or perform complex expansion on instance of this function. Examples ======== >>> from sympy import re, im, I, E, symbols >>> x, y = symbols('x y', real=True) >>> re(2*E) 2*E >>> re(2*I + 17) 17 >>> re(2*I) 0 >>> re(im(x) + x*I + 2) 2 >>> re(5 + I + 2) 7 Parameters ========== arg : Expr Real or complex expression. Returns ======= expr : Expr Real part of expression. See Also ======== im """ args: tTuple[Expr] is_extended_real = True unbranched = True # implicitly works on the projection to C _singularities = True # non-holomorphic @classmethod def eval(cls, arg): if arg is S.NaN: return S.NaN elif arg is S.ComplexInfinity: return S.NaN elif arg.is_extended_real: return arg elif arg.is_imaginary or (I*arg).is_extended_real: return S.Zero elif arg.is_Matrix: return arg.as_real_imag()[0] elif arg.is_Function and isinstance(arg, conjugate): return re(arg.args[0]) else: included, reverted, excluded = [], [], [] args = Add.make_args(arg) for term in args: coeff = term.as_coefficient(I) if coeff is not None: if not coeff.is_extended_real: reverted.append(coeff) elif not term.has(I) and term.is_extended_real: excluded.append(term) else: # Try to do some advanced expansion. If # impossible, don't try to do re(arg) again # (because this is what we are trying to do now). real_imag = term.as_real_imag(ignore=arg) if real_imag: excluded.append(real_imag[0]) else: included.append(term) if len(args) != len(included): a, b, c = (Add(*xs) for xs in [included, reverted, excluded]) return cls(a) - im(b) + c def as_real_imag(self, deep=True, **hints): """ Returns the real number with a zero imaginary part. """ return (self, S.Zero) def _eval_derivative(self, x): if x.is_extended_real or self.args[0].is_extended_real: return re(Derivative(self.args[0], x, evaluate=True)) if x.is_imaginary or self.args[0].is_imaginary: return -I \ * im(Derivative(self.args[0], x, evaluate=True)) def _eval_rewrite_as_im(self, arg, **kwargs): return self.args[0] - I*im(self.args[0]) def _eval_is_algebraic(self): return self.args[0].is_algebraic def _eval_is_zero(self): # is_imaginary implies nonzero return fuzzy_or([self.args[0].is_imaginary, self.args[0].is_zero]) def _eval_is_finite(self): if self.args[0].is_finite: return True def _eval_is_complex(self): if self.args[0].is_finite: return True class im(Function): """ Returns imaginary part of expression. This function performs only elementary analysis and so it will fail to decompose properly more complicated expressions. If completely simplified result is needed then use ``Basic.as_real_imag()`` or perform complex expansion on instance of this function. Examples ======== >>> from sympy import re, im, E, I >>> from sympy.abc import x, y >>> im(2*E) 0 >>> im(2*I + 17) 2 >>> im(x*I) re(x) >>> im(re(x) + y) im(y) >>> im(2 + 3*I) 3 Parameters ========== arg : Expr Real or complex expression. Returns ======= expr : Expr Imaginary part of expression. See Also ======== re """ args: tTuple[Expr] is_extended_real = True unbranched = True # implicitly works on the projection to C _singularities = True # non-holomorphic @classmethod def eval(cls, arg): if arg is S.NaN: return S.NaN elif arg is S.ComplexInfinity: return S.NaN elif arg.is_extended_real: return S.Zero elif arg.is_imaginary or (I*arg).is_extended_real: return -I * arg elif arg.is_Matrix: return arg.as_real_imag()[1] elif arg.is_Function and isinstance(arg, conjugate): return -im(arg.args[0]) else: included, reverted, excluded = [], [], [] args = Add.make_args(arg) for term in args: coeff = term.as_coefficient(I) if coeff is not None: if not coeff.is_extended_real: reverted.append(coeff) else: excluded.append(coeff) elif term.has(I) or not term.is_extended_real: # Try to do some advanced expansion. If # impossible, don't try to do im(arg) again # (because this is what we are trying to do now). real_imag = term.as_real_imag(ignore=arg) if real_imag: excluded.append(real_imag[1]) else: included.append(term) if len(args) != len(included): a, b, c = (Add(*xs) for xs in [included, reverted, excluded]) return cls(a) + re(b) + c def as_real_imag(self, deep=True, **hints): """ Return the imaginary part with a zero real part. """ return (self, S.Zero) def _eval_derivative(self, x): if x.is_extended_real or self.args[0].is_extended_real: return im(Derivative(self.args[0], x, evaluate=True)) if x.is_imaginary or self.args[0].is_imaginary: return -I \ * re(Derivative(self.args[0], x, evaluate=True)) def _eval_rewrite_as_re(self, arg, **kwargs): return -I*(self.args[0] - re(self.args[0])) def _eval_is_algebraic(self): return self.args[0].is_algebraic def _eval_is_zero(self): return self.args[0].is_extended_real def _eval_is_finite(self): if self.args[0].is_finite: return True def _eval_is_complex(self): if self.args[0].is_finite: return True ############################################################################### ############### SIGN, ABSOLUTE VALUE, ARGUMENT and CONJUGATION ################ ############################################################################### class sign(Function): """ Returns the complex sign of an expression: Explanation =========== If the expression is real the sign will be: * $1$ if expression is positive * $0$ if expression is equal to zero * $-1$ if expression is negative If the expression is imaginary the sign will be: * $I$ if im(expression) is positive * $-I$ if im(expression) is negative Otherwise an unevaluated expression will be returned. When evaluated, the result (in general) will be ``cos(arg(expr)) + I*sin(arg(expr))``. Examples ======== >>> from sympy import sign, I >>> sign(-1) -1 >>> sign(0) 0 >>> sign(-3*I) -I >>> sign(1 + I) sign(1 + I) >>> _.evalf() 0.707106781186548 + 0.707106781186548*I Parameters ========== arg : Expr Real or imaginary expression. Returns ======= expr : Expr Complex sign of expression. See Also ======== Abs, conjugate """ is_complex = True _singularities = True def doit(self, **hints): s = super().doit() if s == self and self.args[0].is_zero is False: return self.args[0] / Abs(self.args[0]) return s @classmethod def eval(cls, arg): # handle what we can if arg.is_Mul: c, args = arg.as_coeff_mul() unk = [] s = sign(c) for a in args: if a.is_extended_negative: s = -s elif a.is_extended_positive: pass else: if a.is_imaginary: ai = im(a) if ai.is_comparable: # i.e. a = I*real s *= I if ai.is_extended_negative: # can't use sign(ai) here since ai might not be # a Number s = -s else: unk.append(a) else: unk.append(a) if c is S.One and len(unk) == len(args): return None return s * cls(arg._new_rawargs(*unk)) if arg is S.NaN: return S.NaN if arg.is_zero: # it may be an Expr that is zero return S.Zero if arg.is_extended_positive: return S.One if arg.is_extended_negative: return S.NegativeOne if arg.is_Function: if isinstance(arg, sign): return arg if arg.is_imaginary: if arg.is_Pow and arg.exp is S.Half: # we catch this because non-trivial sqrt args are not expanded # e.g. sqrt(1-sqrt(2)) --x--> to I*sqrt(sqrt(2) - 1) return I arg2 = -I * arg if arg2.is_extended_positive: return I if arg2.is_extended_negative: return -I def _eval_Abs(self): if fuzzy_not(self.args[0].is_zero): return S.One def _eval_conjugate(self): return sign(conjugate(self.args[0])) def _eval_derivative(self, x): if self.args[0].is_extended_real: from sympy.functions.special.delta_functions import DiracDelta return 2 * Derivative(self.args[0], x, evaluate=True) \ * DiracDelta(self.args[0]) elif self.args[0].is_imaginary: from sympy.functions.special.delta_functions import DiracDelta return 2 * Derivative(self.args[0], x, evaluate=True) \ * DiracDelta(-I * self.args[0]) def _eval_is_nonnegative(self): if self.args[0].is_nonnegative: return True def _eval_is_nonpositive(self): if self.args[0].is_nonpositive: return True def _eval_is_imaginary(self): return self.args[0].is_imaginary def _eval_is_integer(self): return self.args[0].is_extended_real def _eval_is_zero(self): return self.args[0].is_zero def _eval_power(self, other): if ( fuzzy_not(self.args[0].is_zero) and other.is_integer and other.is_even ): return S.One def _eval_nseries(self, x, n, logx, cdir=0): arg0 = self.args[0] x0 = arg0.subs(x, 0) if x0 != 0: return self.func(x0) if cdir != 0: cdir = arg0.dir(x, cdir) return -S.One if re(cdir) < 0 else S.One def _eval_rewrite_as_Piecewise(self, arg, **kwargs): if arg.is_extended_real: return Piecewise((1, arg > 0), (-1, arg < 0), (0, True)) def _eval_rewrite_as_Heaviside(self, arg, **kwargs): from sympy.functions.special.delta_functions import Heaviside if arg.is_extended_real: return Heaviside(arg) * 2 - 1 def _eval_rewrite_as_Abs(self, arg, **kwargs): return Piecewise((0, Eq(arg, 0)), (arg / Abs(arg), True)) def _eval_simplify(self, **kwargs): return self.func(factor_terms(self.args[0])) # XXX include doit? class Abs(Function): """ Return the absolute value of the argument. Explanation =========== This is an extension of the built-in function ``abs()`` to accept symbolic values. If you pass a SymPy expression to the built-in ``abs()``, it will pass it automatically to ``Abs()``. Examples ======== >>> from sympy import Abs, Symbol, S, I >>> Abs(-1) 1 >>> x = Symbol('x', real=True) >>> Abs(-x) Abs(x) >>> Abs(x**2) x**2 >>> abs(-x) # The Python built-in Abs(x) >>> Abs(3*x + 2*I) sqrt(9*x**2 + 4) >>> Abs(8*I) 8 Note that the Python built-in will return either an Expr or int depending on the argument:: >>> type(abs(-1)) <... 'int'> >>> type(abs(S.NegativeOne)) <class 'sympy.core.numbers.One'> Abs will always return a SymPy object. Parameters ========== arg : Expr Real or complex expression. Returns ======= expr : Expr Absolute value returned can be an expression or integer depending on input arg. See Also ======== sign, conjugate """ args: tTuple[Expr] is_extended_real = True is_extended_negative = False is_extended_nonnegative = True unbranched = True _singularities = True # non-holomorphic def fdiff(self, argindex=1): """ Get the first derivative of the argument to Abs(). """ if argindex == 1: return sign(self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.simplify.simplify import signsimp if hasattr(arg, '_eval_Abs'): obj = arg._eval_Abs() if obj is not None: return obj if not isinstance(arg, Expr): raise TypeError("Bad argument type for Abs(): %s" % type(arg)) # handle what we can arg = signsimp(arg, evaluate=False) n, d = arg.as_numer_denom() if d.free_symbols and not n.free_symbols: return cls(n)/cls(d) if arg.is_Mul: known = [] unk = [] for t in arg.args: if t.is_Pow and t.exp.is_integer and t.exp.is_negative: bnew = cls(t.base) if isinstance(bnew, cls): unk.append(t) else: known.append(Pow(bnew, t.exp)) else: tnew = cls(t) if isinstance(tnew, cls): unk.append(t) else: known.append(tnew) known = Mul(*known) unk = cls(Mul(*unk), evaluate=False) if unk else S.One return known*unk if arg is S.NaN: return S.NaN if arg is S.ComplexInfinity: return oo from sympy.functions.elementary.exponential import exp, log if arg.is_Pow: base, exponent = arg.as_base_exp() if base.is_extended_real: if exponent.is_integer: if exponent.is_even: return arg if base is S.NegativeOne: return S.One return Abs(base)**exponent if base.is_extended_nonnegative: return base**re(exponent) if base.is_extended_negative: return (-base)**re(exponent)*exp(-pi*im(exponent)) return elif not base.has(Symbol): # complex base # express base**exponent as exp(exponent*log(base)) a, b = log(base).as_real_imag() z = a + I*b return exp(re(exponent*z)) if isinstance(arg, exp): return exp(re(arg.args[0])) if isinstance(arg, AppliedUndef): if arg.is_positive: return arg elif arg.is_negative: return -arg return if arg.is_Add and arg.has(oo, S.NegativeInfinity): if any(a.is_infinite for a in arg.as_real_imag()): return oo if arg.is_zero: return S.Zero if arg.is_extended_nonnegative: return arg if arg.is_extended_nonpositive: return -arg if arg.is_imaginary: arg2 = -I * arg if arg2.is_extended_nonnegative: return arg2 if arg.is_extended_real: return # reject result if all new conjugates are just wrappers around # an expression that was already in the arg conj = signsimp(arg.conjugate(), evaluate=False) new_conj = conj.atoms(conjugate) - arg.atoms(conjugate) if new_conj and all(arg.has(i.args[0]) for i in new_conj): return if arg != conj and arg != -conj: ignore = arg.atoms(Abs) abs_free_arg = arg.xreplace({i: Dummy(real=True) for i in ignore}) unk = [a for a in abs_free_arg.free_symbols if a.is_extended_real is None] if not unk or not all(conj.has(conjugate(u)) for u in unk): return sqrt(expand_mul(arg*conj)) def _eval_is_real(self): if self.args[0].is_finite: return True def _eval_is_integer(self): if self.args[0].is_extended_real: return self.args[0].is_integer def _eval_is_extended_nonzero(self): return fuzzy_not(self._args[0].is_zero) def _eval_is_zero(self): return self._args[0].is_zero def _eval_is_extended_positive(self): return fuzzy_not(self._args[0].is_zero) def _eval_is_rational(self): if self.args[0].is_extended_real: return self.args[0].is_rational def _eval_is_even(self): if self.args[0].is_extended_real: return self.args[0].is_even def _eval_is_odd(self): if self.args[0].is_extended_real: return self.args[0].is_odd def _eval_is_algebraic(self): return self.args[0].is_algebraic def _eval_power(self, exponent): if self.args[0].is_extended_real and exponent.is_integer: if exponent.is_even: return self.args[0]**exponent elif exponent is not S.NegativeOne and exponent.is_Integer: return self.args[0]**(exponent - 1)*self return def _eval_nseries(self, x, n, logx, cdir=0): from sympy.functions.elementary.exponential import log direction = self.args[0].leadterm(x)[0] if direction.has(log(x)): direction = direction.subs(log(x), logx) s = self.args[0]._eval_nseries(x, n=n, logx=logx) return (sign(direction)*s).expand() def _eval_derivative(self, x): if self.args[0].is_extended_real or self.args[0].is_imaginary: return Derivative(self.args[0], x, evaluate=True) \ * sign(conjugate(self.args[0])) rv = (re(self.args[0]) * Derivative(re(self.args[0]), x, evaluate=True) + im(self.args[0]) * Derivative(im(self.args[0]), x, evaluate=True)) / Abs(self.args[0]) return rv.rewrite(sign) def _eval_rewrite_as_Heaviside(self, arg, **kwargs): # Note this only holds for real arg (since Heaviside is not defined # for complex arguments). from sympy.functions.special.delta_functions import Heaviside if arg.is_extended_real: return arg*(Heaviside(arg) - Heaviside(-arg)) def _eval_rewrite_as_Piecewise(self, arg, **kwargs): if arg.is_extended_real: return Piecewise((arg, arg >= 0), (-arg, True)) elif arg.is_imaginary: return Piecewise((I*arg, I*arg >= 0), (-I*arg, True)) def _eval_rewrite_as_sign(self, arg, **kwargs): return arg/sign(arg) def _eval_rewrite_as_conjugate(self, arg, **kwargs): return sqrt(arg*conjugate(arg)) class arg(Function): r""" Returns the argument (in radians) of a complex number. The argument is evaluated in consistent convention with ``atan2`` where the branch-cut is taken along the negative real axis and ``arg(z)`` is in the interval $(-\pi,\pi]$. For a positive number, the argument is always 0; the argument of a negative number is $\pi$; and the argument of 0 is undefined and returns ``nan``. So the ``arg`` function will never nest greater than 3 levels since at the 4th application, the result must be nan; for a real number, nan is returned on the 3rd application. Examples ======== >>> from sympy import arg, I, sqrt, Dummy >>> from sympy.abc import x >>> arg(2.0) 0 >>> arg(I) pi/2 >>> arg(sqrt(2) + I*sqrt(2)) pi/4 >>> arg(sqrt(3)/2 + I/2) pi/6 >>> arg(4 + 3*I) atan(3/4) >>> arg(0.8 + 0.6*I) 0.643501108793284 >>> arg(arg(arg(arg(x)))) nan >>> real = Dummy(real=True) >>> arg(arg(arg(real))) nan Parameters ========== arg : Expr Real or complex expression. Returns ======= value : Expr Returns arc tangent of arg measured in radians. """ is_extended_real = True is_real = True is_finite = True _singularities = True # non-holomorphic @classmethod def eval(cls, arg): a = arg for i in range(3): if isinstance(a, cls): a = a.args[0] else: if i == 2 and a.is_extended_real: return S.NaN break else: return S.NaN from sympy.functions.elementary.exponential import exp_polar if isinstance(arg, exp_polar): return periodic_argument(arg, oo) if not arg.is_Atom: c, arg_ = factor_terms(arg).as_coeff_Mul() if arg_.is_Mul: arg_ = Mul(*[a if (sign(a) not in (-1, 1)) else sign(a) for a in arg_.args]) arg_ = sign(c)*arg_ else: arg_ = arg if any(i.is_extended_positive is None for i in arg_.atoms(AppliedUndef)): return from sympy.functions.elementary.trigonometric import atan2 x, y = arg_.as_real_imag() rv = atan2(y, x) if rv.is_number: return rv if arg_ != arg: return cls(arg_, evaluate=False) def _eval_derivative(self, t): x, y = self.args[0].as_real_imag() return (x * Derivative(y, t, evaluate=True) - y * Derivative(x, t, evaluate=True)) / (x**2 + y**2) def _eval_rewrite_as_atan2(self, arg, **kwargs): from sympy.functions.elementary.trigonometric import atan2 x, y = self.args[0].as_real_imag() return atan2(y, x) class conjugate(Function): """ Returns the *complex conjugate* [1]_ of an argument. In mathematics, the complex conjugate of a complex number is given by changing the sign of the imaginary part. Thus, the conjugate of the complex number :math:`a + ib` (where $a$ and $b$ are real numbers) is :math:`a - ib` Examples ======== >>> from sympy import conjugate, I >>> conjugate(2) 2 >>> conjugate(I) -I >>> conjugate(3 + 2*I) 3 - 2*I >>> conjugate(5 - I) 5 + I Parameters ========== arg : Expr Real or complex expression. Returns ======= arg : Expr Complex conjugate of arg as real, imaginary or mixed expression. See Also ======== sign, Abs References ========== .. [1] https://en.wikipedia.org/wiki/Complex_conjugation """ _singularities = True # non-holomorphic @classmethod def eval(cls, arg): obj = arg._eval_conjugate() if obj is not None: return obj def inverse(self): return conjugate def _eval_Abs(self): return Abs(self.args[0], evaluate=True) def _eval_adjoint(self): return transpose(self.args[0]) def _eval_conjugate(self): return self.args[0] def _eval_derivative(self, x): if x.is_real: return conjugate(Derivative(self.args[0], x, evaluate=True)) elif x.is_imaginary: return -conjugate(Derivative(self.args[0], x, evaluate=True)) def _eval_transpose(self): return adjoint(self.args[0]) def _eval_is_algebraic(self): return self.args[0].is_algebraic class transpose(Function): """ Linear map transposition. Examples ======== >>> from sympy import transpose, Matrix, MatrixSymbol >>> A = MatrixSymbol('A', 25, 9) >>> transpose(A) A.T >>> B = MatrixSymbol('B', 9, 22) >>> transpose(B) B.T >>> transpose(A*B) B.T*A.T >>> M = Matrix([[4, 5], [2, 1], [90, 12]]) >>> M Matrix([ [ 4, 5], [ 2, 1], [90, 12]]) >>> transpose(M) Matrix([ [4, 2, 90], [5, 1, 12]]) Parameters ========== arg : Matrix Matrix or matrix expression to take the transpose of. Returns ======= value : Matrix Transpose of arg. """ @classmethod def eval(cls, arg): obj = arg._eval_transpose() if obj is not None: return obj def _eval_adjoint(self): return conjugate(self.args[0]) def _eval_conjugate(self): return adjoint(self.args[0]) def _eval_transpose(self): return self.args[0] class adjoint(Function): """ Conjugate transpose or Hermite conjugation. Examples ======== >>> from sympy import adjoint, MatrixSymbol >>> A = MatrixSymbol('A', 10, 5) >>> adjoint(A) Adjoint(A) Parameters ========== arg : Matrix Matrix or matrix expression to take the adjoint of. Returns ======= value : Matrix Represents the conjugate transpose or Hermite conjugation of arg. """ @classmethod def eval(cls, arg): obj = arg._eval_adjoint() if obj is not None: return obj obj = arg._eval_transpose() if obj is not None: return conjugate(obj) def _eval_adjoint(self): return self.args[0] def _eval_conjugate(self): return transpose(self.args[0]) def _eval_transpose(self): return conjugate(self.args[0]) def _latex(self, printer, exp=None, *args): arg = printer._print(self.args[0]) tex = r'%s^{\dagger}' % arg if exp: tex = r'\left(%s\right)^{%s}' % (tex, exp) return tex def _pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) if printer._use_unicode: pform = pform**prettyForm('\N{DAGGER}') else: pform = pform**prettyForm('+') return pform ############################################################################### ############### HANDLING OF POLAR NUMBERS ##################################### ############################################################################### class polar_lift(Function): """ Lift argument to the Riemann surface of the logarithm, using the standard branch. Examples ======== >>> from sympy import Symbol, polar_lift, I >>> p = Symbol('p', polar=True) >>> x = Symbol('x') >>> polar_lift(4) 4*exp_polar(0) >>> polar_lift(-4) 4*exp_polar(I*pi) >>> polar_lift(-I) exp_polar(-I*pi/2) >>> polar_lift(I + 2) polar_lift(2 + I) >>> polar_lift(4*x) 4*polar_lift(x) >>> polar_lift(4*p) 4*p Parameters ========== arg : Expr Real or complex expression. See Also ======== sympy.functions.elementary.exponential.exp_polar periodic_argument """ is_polar = True is_comparable = False # Cannot be evalf'd. @classmethod def eval(cls, arg): from sympy.functions.elementary.complexes import arg as argument if arg.is_number: ar = argument(arg) # In general we want to affirm that something is known, # e.g. `not ar.has(argument) and not ar.has(atan)` # but for now we will just be more restrictive and # see that it has evaluated to one of the known values. if ar in (0, pi/2, -pi/2, pi): from sympy.functions.elementary.exponential import exp_polar return exp_polar(I*ar)*abs(arg) if arg.is_Mul: args = arg.args else: args = [arg] included = [] excluded = [] positive = [] for arg in args: if arg.is_polar: included += [arg] elif arg.is_positive: positive += [arg] else: excluded += [arg] if len(excluded) < len(args): if excluded: return Mul(*(included + positive))*polar_lift(Mul(*excluded)) elif included: return Mul(*(included + positive)) else: from sympy.functions.elementary.exponential import exp_polar return Mul(*positive)*exp_polar(0) def _eval_evalf(self, prec): """ Careful! any evalf of polar numbers is flaky """ return self.args[0]._eval_evalf(prec) def _eval_Abs(self): return Abs(self.args[0], evaluate=True) class periodic_argument(Function): r""" Represent the argument on a quotient of the Riemann surface of the logarithm. That is, given a period $P$, always return a value in $(-P/2, P/2]$, by using $\exp(PI) = 1$. Examples ======== >>> from sympy import exp_polar, periodic_argument >>> from sympy import I, pi >>> periodic_argument(exp_polar(10*I*pi), 2*pi) 0 >>> periodic_argument(exp_polar(5*I*pi), 4*pi) pi >>> from sympy import exp_polar, periodic_argument >>> from sympy import I, pi >>> periodic_argument(exp_polar(5*I*pi), 2*pi) pi >>> periodic_argument(exp_polar(5*I*pi), 3*pi) -pi >>> periodic_argument(exp_polar(5*I*pi), pi) 0 Parameters ========== ar : Expr A polar number. period : Expr The period $P$. See Also ======== sympy.functions.elementary.exponential.exp_polar polar_lift : Lift argument to the Riemann surface of the logarithm principal_branch """ @classmethod def _getunbranched(cls, ar): from sympy.functions.elementary.exponential import exp_polar, log if ar.is_Mul: args = ar.args else: args = [ar] unbranched = 0 for a in args: if not a.is_polar: unbranched += arg(a) elif isinstance(a, exp_polar): unbranched += a.exp.as_real_imag()[1] elif a.is_Pow: re, im = a.exp.as_real_imag() unbranched += re*unbranched_argument( a.base) + im*log(abs(a.base)) elif isinstance(a, polar_lift): unbranched += arg(a.args[0]) else: return None return unbranched @classmethod def eval(cls, ar, period): # Our strategy is to evaluate the argument on the Riemann surface of the # logarithm, and then reduce. # NOTE evidently this means it is a rather bad idea to use this with # period != 2*pi and non-polar numbers. if not period.is_extended_positive: return None if period == oo and isinstance(ar, principal_branch): return periodic_argument(*ar.args) if isinstance(ar, polar_lift) and period >= 2*pi: return periodic_argument(ar.args[0], period) if ar.is_Mul: newargs = [x for x in ar.args if not x.is_positive] if len(newargs) != len(ar.args): return periodic_argument(Mul(*newargs), period) unbranched = cls._getunbranched(ar) if unbranched is None: return None from sympy.functions.elementary.trigonometric import atan, atan2 if unbranched.has(periodic_argument, atan2, atan): return None if period == oo: return unbranched if period != oo: from sympy.functions.elementary.integers import ceiling n = ceiling(unbranched/period - S.Half)*period if not n.has(ceiling): return unbranched - n def _eval_evalf(self, prec): z, period = self.args if period == oo: unbranched = periodic_argument._getunbranched(z) if unbranched is None: return self return unbranched._eval_evalf(prec) ub = periodic_argument(z, oo)._eval_evalf(prec) from sympy.functions.elementary.integers import ceiling return (ub - ceiling(ub/period - S.Half)*period)._eval_evalf(prec) def unbranched_argument(arg): ''' Returns periodic argument of arg with period as infinity. Examples ======== >>> from sympy import exp_polar, unbranched_argument >>> from sympy import I, pi >>> unbranched_argument(exp_polar(15*I*pi)) 15*pi >>> unbranched_argument(exp_polar(7*I*pi)) 7*pi See also ======== periodic_argument ''' return periodic_argument(arg, oo) class principal_branch(Function): """ Represent a polar number reduced to its principal branch on a quotient of the Riemann surface of the logarithm. Explanation =========== This is a function of two arguments. The first argument is a polar number `z`, and the second one a positive real number or infinity, `p`. The result is ``z mod exp_polar(I*p)``. Examples ======== >>> from sympy import exp_polar, principal_branch, oo, I, pi >>> from sympy.abc import z >>> principal_branch(z, oo) z >>> principal_branch(exp_polar(2*pi*I)*3, 2*pi) 3*exp_polar(0) >>> principal_branch(exp_polar(2*pi*I)*3*z, 2*pi) 3*principal_branch(z, 2*pi) Parameters ========== x : Expr A polar number. period : Expr Positive real number or infinity. See Also ======== sympy.functions.elementary.exponential.exp_polar polar_lift : Lift argument to the Riemann surface of the logarithm periodic_argument """ is_polar = True is_comparable = False # cannot always be evalf'd @classmethod def eval(self, x, period): from sympy.functions.elementary.exponential import exp_polar if isinstance(x, polar_lift): return principal_branch(x.args[0], period) if period == oo: return x ub = periodic_argument(x, oo) barg = periodic_argument(x, period) if ub != barg and not ub.has(periodic_argument) \ and not barg.has(periodic_argument): pl = polar_lift(x) def mr(expr): if not isinstance(expr, Symbol): return polar_lift(expr) return expr pl = pl.replace(polar_lift, mr) # Recompute unbranched argument ub = periodic_argument(pl, oo) if not pl.has(polar_lift): if ub != barg: res = exp_polar(I*(barg - ub))*pl else: res = pl if not res.is_polar and not res.has(exp_polar): res *= exp_polar(0) return res if not x.free_symbols: c, m = x, () else: c, m = x.as_coeff_mul(*x.free_symbols) others = [] for y in m: if y.is_positive: c *= y else: others += [y] m = tuple(others) arg = periodic_argument(c, period) if arg.has(periodic_argument): return None if arg.is_number and (unbranched_argument(c) != arg or (arg == 0 and m != () and c != 1)): if arg == 0: return abs(c)*principal_branch(Mul(*m), period) return principal_branch(exp_polar(I*arg)*Mul(*m), period)*abs(c) if arg.is_number and ((abs(arg) < period/2) == True or arg == period/2) \ and m == (): return exp_polar(arg*I)*abs(c) def _eval_evalf(self, prec): z, period = self.args p = periodic_argument(z, period)._eval_evalf(prec) if abs(p) > pi or p == -pi: return self # Cannot evalf for this argument. from sympy.functions.elementary.exponential import exp return (abs(z)*exp(I*p))._eval_evalf(prec) def _polarify(eq, lift, pause=False): from sympy.integrals.integrals import Integral if eq.is_polar: return eq if eq.is_number and not pause: return polar_lift(eq) if isinstance(eq, Symbol) and not pause and lift: return polar_lift(eq) elif eq.is_Atom: return eq elif eq.is_Add: r = eq.func(*[_polarify(arg, lift, pause=True) for arg in eq.args]) if lift: return polar_lift(r) return r elif eq.is_Pow and eq.base == S.Exp1: return eq.func(S.Exp1, _polarify(eq.exp, lift, pause=False)) elif eq.is_Function: return eq.func(*[_polarify(arg, lift, pause=False) for arg in eq.args]) elif isinstance(eq, Integral): # Don't lift the integration variable func = _polarify(eq.function, lift, pause=pause) limits = [] for limit in eq.args[1:]: var = _polarify(limit[0], lift=False, pause=pause) rest = _polarify(limit[1:], lift=lift, pause=pause) limits.append((var,) + rest) return Integral(*((func,) + tuple(limits))) else: return eq.func(*[_polarify(arg, lift, pause=pause) if isinstance(arg, Expr) else arg for arg in eq.args]) def polarify(eq, subs=True, lift=False): """ Turn all numbers in eq into their polar equivalents (under the standard choice of argument). Note that no attempt is made to guess a formal convention of adding polar numbers, expressions like $1 + x$ will generally not be altered. Note also that this function does not promote ``exp(x)`` to ``exp_polar(x)``. If ``subs`` is ``True``, all symbols which are not already polar will be substituted for polar dummies; in this case the function behaves much like :func:`~.posify`. If ``lift`` is ``True``, both addition statements and non-polar symbols are changed to their ``polar_lift()``ed versions. Note that ``lift=True`` implies ``subs=False``. Examples ======== >>> from sympy import polarify, sin, I >>> from sympy.abc import x, y >>> expr = (-x)**y >>> expr.expand() (-x)**y >>> polarify(expr) ((_x*exp_polar(I*pi))**_y, {_x: x, _y: y}) >>> polarify(expr)[0].expand() _x**_y*exp_polar(_y*I*pi) >>> polarify(x, lift=True) polar_lift(x) >>> polarify(x*(1+y), lift=True) polar_lift(x)*polar_lift(y + 1) Adds are treated carefully: >>> polarify(1 + sin((1 + I)*x)) (sin(_x*polar_lift(1 + I)) + 1, {_x: x}) """ if lift: subs = False eq = _polarify(sympify(eq), lift) if not subs: return eq reps = {s: Dummy(s.name, polar=True) for s in eq.free_symbols} eq = eq.subs(reps) return eq, {r: s for s, r in reps.items()} def _unpolarify(eq, exponents_only, pause=False): if not isinstance(eq, Basic) or eq.is_Atom: return eq if not pause: from sympy.functions.elementary.exponential import exp, exp_polar if isinstance(eq, exp_polar): return exp(_unpolarify(eq.exp, exponents_only)) if isinstance(eq, principal_branch) and eq.args[1] == 2*pi: return _unpolarify(eq.args[0], exponents_only) if ( eq.is_Add or eq.is_Mul or eq.is_Boolean or eq.is_Relational and ( eq.rel_op in ('==', '!=') and 0 in eq.args or eq.rel_op not in ('==', '!=')) ): return eq.func(*[_unpolarify(x, exponents_only) for x in eq.args]) if isinstance(eq, polar_lift): return _unpolarify(eq.args[0], exponents_only) if eq.is_Pow: expo = _unpolarify(eq.exp, exponents_only) base = _unpolarify(eq.base, exponents_only, not (expo.is_integer and not pause)) return base**expo if eq.is_Function and getattr(eq.func, 'unbranched', False): return eq.func(*[_unpolarify(x, exponents_only, exponents_only) for x in eq.args]) return eq.func(*[_unpolarify(x, exponents_only, True) for x in eq.args]) def unpolarify(eq, subs=None, exponents_only=False): """ If `p` denotes the projection from the Riemann surface of the logarithm to the complex line, return a simplified version `eq'` of `eq` such that `p(eq') = p(eq)`. Also apply the substitution subs in the end. (This is a convenience, since ``unpolarify``, in a certain sense, undoes :func:`polarify`.) Examples ======== >>> from sympy import unpolarify, polar_lift, sin, I >>> unpolarify(polar_lift(I + 2)) 2 + I >>> unpolarify(sin(polar_lift(I + 7))) sin(7 + I) """ if isinstance(eq, bool): return eq eq = sympify(eq) if subs is not None: return unpolarify(eq.subs(subs)) changed = True pause = False if exponents_only: pause = True while changed: changed = False res = _unpolarify(eq, exponents_only, pause) if res != eq: changed = True eq = res if isinstance(res, bool): return res # Finally, replacing Exp(0) by 1 is always correct. # So is polar_lift(0) -> 0. from sympy.functions.elementary.exponential import exp_polar return res.subs({exp_polar(0): 1, polar_lift(0): 0})
79be15a4701c69749f10e222acf963ed2d2bad0833f848a95060b3064e5dd876
"""Hypergeometric and Meijer G-functions""" from functools import reduce from sympy.core import S, ilcm, Mod from sympy.core.add import Add from sympy.core.expr import Expr from sympy.core.function import Function, Derivative, ArgumentIndexError from sympy.core.containers import Tuple from sympy.core.mul import Mul from sympy.core.numbers import I, pi, oo, zoo from sympy.core.relational import Ne from sympy.core.sorting import default_sort_key from sympy.core.symbol import Dummy from sympy.functions import (sqrt, exp, log, sin, cos, asin, atan, sinh, cosh, asinh, acosh, atanh, acoth) from sympy.functions import factorial, RisingFactorial from sympy.functions.elementary.complexes import Abs, re, unpolarify from sympy.functions.elementary.exponential import exp_polar from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.piecewise import Piecewise from sympy.logic.boolalg import (And, Or) class TupleArg(Tuple): def limit(self, x, xlim, dir='+'): """ Compute limit x->xlim. """ from sympy.series.limits import limit return TupleArg(*[limit(f, x, xlim, dir) for f in self.args]) # TODO should __new__ accept **options? # TODO should constructors should check if parameters are sensible? def _prep_tuple(v): """ Turn an iterable argument *v* into a tuple and unpolarify, since both hypergeometric and meijer g-functions are unbranched in their parameters. Examples ======== >>> from sympy.functions.special.hyper import _prep_tuple >>> _prep_tuple([1, 2, 3]) (1, 2, 3) >>> _prep_tuple((4, 5)) (4, 5) >>> _prep_tuple((7, 8, 9)) (7, 8, 9) """ return TupleArg(*[unpolarify(x) for x in v]) class TupleParametersBase(Function): """ Base class that takes care of differentiation, when some of the arguments are actually tuples. """ # This is not deduced automatically since there are Tuples as arguments. is_commutative = True def _eval_derivative(self, s): try: res = 0 if self.args[0].has(s) or self.args[1].has(s): for i, p in enumerate(self._diffargs): m = self._diffargs[i].diff(s) if m != 0: res += self.fdiff((1, i))*m return res + self.fdiff(3)*self.args[2].diff(s) except (ArgumentIndexError, NotImplementedError): return Derivative(self, s) class hyper(TupleParametersBase): r""" The generalized hypergeometric function is defined by a series where the ratios of successive terms are a rational function of the summation index. When convergent, it is continued analytically to the largest possible domain. Explanation =========== The hypergeometric function depends on two vectors of parameters, called the numerator parameters $a_p$, and the denominator parameters $b_q$. It also has an argument $z$. The series definition is .. math :: {}_pF_q\left(\begin{matrix} a_1, \cdots, a_p \\ b_1, \cdots, b_q \end{matrix} \middle| z \right) = \sum_{n=0}^\infty \frac{(a_1)_n \cdots (a_p)_n}{(b_1)_n \cdots (b_q)_n} \frac{z^n}{n!}, where $(a)_n = (a)(a+1)\cdots(a+n-1)$ denotes the rising factorial. If one of the $b_q$ is a non-positive integer then the series is undefined unless one of the $a_p$ is a larger (i.e., smaller in magnitude) non-positive integer. If none of the $b_q$ is a non-positive integer and one of the $a_p$ is a non-positive integer, then the series reduces to a polynomial. To simplify the following discussion, we assume that none of the $a_p$ or $b_q$ is a non-positive integer. For more details, see the references. The series converges for all $z$ if $p \le q$, and thus defines an entire single-valued function in this case. If $p = q+1$ the series converges for $|z| < 1$, and can be continued analytically into a half-plane. If $p > q+1$ the series is divergent for all $z$. Please note the hypergeometric function constructor currently does *not* check if the parameters actually yield a well-defined function. Examples ======== The parameters $a_p$ and $b_q$ can be passed as arbitrary iterables, for example: >>> from sympy import hyper >>> from sympy.abc import x, n, a >>> hyper((1, 2, 3), [3, 4], x) hyper((1, 2, 3), (3, 4), x) There is also pretty printing (it looks better using Unicode): >>> from sympy import pprint >>> pprint(hyper((1, 2, 3), [3, 4], x), use_unicode=False) _ |_ /1, 2, 3 | \ | | | x| 3 2 \ 3, 4 | / The parameters must always be iterables, even if they are vectors of length one or zero: >>> hyper((1, ), [], x) hyper((1,), (), x) But of course they may be variables (but if they depend on $x$ then you should not expect much implemented functionality): >>> hyper((n, a), (n**2,), x) hyper((n, a), (n**2,), x) The hypergeometric function generalizes many named special functions. The function ``hyperexpand()`` tries to express a hypergeometric function using named special functions. For example: >>> from sympy import hyperexpand >>> hyperexpand(hyper([], [], x)) exp(x) You can also use ``expand_func()``: >>> from sympy import expand_func >>> expand_func(x*hyper([1, 1], [2], -x)) log(x + 1) More examples: >>> from sympy import S >>> hyperexpand(hyper([], [S(1)/2], -x**2/4)) cos(x) >>> hyperexpand(x*hyper([S(1)/2, S(1)/2], [S(3)/2], x**2)) asin(x) We can also sometimes ``hyperexpand()`` parametric functions: >>> from sympy.abc import a >>> hyperexpand(hyper([-a], [], x)) (1 - x)**a See Also ======== sympy.simplify.hyperexpand gamma meijerg References ========== .. [1] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 .. [2] https://en.wikipedia.org/wiki/Generalized_hypergeometric_function """ def __new__(cls, ap, bq, z, **kwargs): # TODO should we check convergence conditions? return Function.__new__(cls, _prep_tuple(ap), _prep_tuple(bq), z, **kwargs) @classmethod def eval(cls, ap, bq, z): if len(ap) <= len(bq) or (len(ap) == len(bq) + 1 and (Abs(z) <= 1) == True): nz = unpolarify(z) if z != nz: return hyper(ap, bq, nz) def fdiff(self, argindex=3): if argindex != 3: raise ArgumentIndexError(self, argindex) nap = Tuple(*[a + 1 for a in self.ap]) nbq = Tuple(*[b + 1 for b in self.bq]) fac = Mul(*self.ap)/Mul(*self.bq) return fac*hyper(nap, nbq, self.argument) def _eval_expand_func(self, **hints): from sympy.functions.special.gamma_functions import gamma from sympy.simplify.hyperexpand import hyperexpand if len(self.ap) == 2 and len(self.bq) == 1 and self.argument == 1: a, b = self.ap c = self.bq[0] return gamma(c)*gamma(c - a - b)/gamma(c - a)/gamma(c - b) return hyperexpand(self) def _eval_rewrite_as_Sum(self, ap, bq, z, **kwargs): from sympy.concrete.summations import Sum n = Dummy("n", integer=True) rfap = [RisingFactorial(a, n) for a in ap] rfbq = [RisingFactorial(b, n) for b in bq] coeff = Mul(*rfap) / Mul(*rfbq) return Piecewise((Sum(coeff * z**n / factorial(n), (n, 0, oo)), self.convergence_statement), (self, True)) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[2] x0 = arg.subs(x, 0) if x0 is S.NaN: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 is S.Zero: return S.One return super()._eval_as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): from sympy.series.order import Order arg = self.args[2] x0 = arg.limit(x, 0) ap = self.args[0] bq = self.args[1] if x0 != 0: return super()._eval_nseries(x, n, logx) terms = [] for i in range(n): num = Mul(*[RisingFactorial(a, i) for a in ap]) den = Mul(*[RisingFactorial(b, i) for b in bq]) terms.append(((num/den) * (arg**i)) / factorial(i)) return (Add(*terms) + Order(x**n,x)) @property def argument(self): """ Argument of the hypergeometric function. """ return self.args[2] @property def ap(self): """ Numerator parameters of the hypergeometric function. """ return Tuple(*self.args[0]) @property def bq(self): """ Denominator parameters of the hypergeometric function. """ return Tuple(*self.args[1]) @property def _diffargs(self): return self.ap + self.bq @property def eta(self): """ A quantity related to the convergence of the series. """ return sum(self.ap) - sum(self.bq) @property def radius_of_convergence(self): """ Compute the radius of convergence of the defining series. Explanation =========== Note that even if this is not ``oo``, the function may still be evaluated outside of the radius of convergence by analytic continuation. But if this is zero, then the function is not actually defined anywhere else. Examples ======== >>> from sympy import hyper >>> from sympy.abc import z >>> hyper((1, 2), [3], z).radius_of_convergence 1 >>> hyper((1, 2, 3), [4], z).radius_of_convergence 0 >>> hyper((1, 2), (3, 4), z).radius_of_convergence oo """ if any(a.is_integer and (a <= 0) == True for a in self.ap + self.bq): aints = [a for a in self.ap if a.is_Integer and (a <= 0) == True] bints = [a for a in self.bq if a.is_Integer and (a <= 0) == True] if len(aints) < len(bints): return S.Zero popped = False for b in bints: cancelled = False while aints: a = aints.pop() if a >= b: cancelled = True break popped = True if not cancelled: return S.Zero if aints or popped: # There are still non-positive numerator parameters. # This is a polynomial. return oo if len(self.ap) == len(self.bq) + 1: return S.One elif len(self.ap) <= len(self.bq): return oo else: return S.Zero @property def convergence_statement(self): """ Return a condition on z under which the series converges. """ R = self.radius_of_convergence if R == 0: return False if R == oo: return True # The special functions and their approximations, page 44 e = self.eta z = self.argument c1 = And(re(e) < 0, abs(z) <= 1) c2 = And(0 <= re(e), re(e) < 1, abs(z) <= 1, Ne(z, 1)) c3 = And(re(e) >= 1, abs(z) < 1) return Or(c1, c2, c3) def _eval_simplify(self, **kwargs): from sympy.simplify.hyperexpand import hyperexpand return hyperexpand(self) class meijerg(TupleParametersBase): r""" The Meijer G-function is defined by a Mellin-Barnes type integral that resembles an inverse Mellin transform. It generalizes the hypergeometric functions. Explanation =========== The Meijer G-function depends on four sets of parameters. There are "*numerator parameters*" $a_1, \ldots, a_n$ and $a_{n+1}, \ldots, a_p$, and there are "*denominator parameters*" $b_1, \ldots, b_m$ and $b_{m+1}, \ldots, b_q$. Confusingly, it is traditionally denoted as follows (note the position of $m$, $n$, $p$, $q$, and how they relate to the lengths of the four parameter vectors): .. math :: G_{p,q}^{m,n} \left(\begin{matrix}a_1, \cdots, a_n & a_{n+1}, \cdots, a_p \\ b_1, \cdots, b_m & b_{m+1}, \cdots, b_q \end{matrix} \middle| z \right). However, in SymPy the four parameter vectors are always available separately (see examples), so that there is no need to keep track of the decorating sub- and super-scripts on the G symbol. The G function is defined as the following integral: .. math :: \frac{1}{2 \pi i} \int_L \frac{\prod_{j=1}^m \Gamma(b_j - s) \prod_{j=1}^n \Gamma(1 - a_j + s)}{\prod_{j=m+1}^q \Gamma(1- b_j +s) \prod_{j=n+1}^p \Gamma(a_j - s)} z^s \mathrm{d}s, where $\Gamma(z)$ is the gamma function. There are three possible contours which we will not describe in detail here (see the references). If the integral converges along more than one of them, the definitions agree. The contours all separate the poles of $\Gamma(1-a_j+s)$ from the poles of $\Gamma(b_k-s)$, so in particular the G function is undefined if $a_j - b_k \in \mathbb{Z}_{>0}$ for some $j \le n$ and $k \le m$. The conditions under which one of the contours yields a convergent integral are complicated and we do not state them here, see the references. Please note currently the Meijer G-function constructor does *not* check any convergence conditions. Examples ======== You can pass the parameters either as four separate vectors: >>> from sympy import meijerg, Tuple, pprint >>> from sympy.abc import x, a >>> pprint(meijerg((1, 2), (a, 4), (5,), [], x), use_unicode=False) __1, 2 /1, 2 a, 4 | \ /__ | | x| \_|4, 1 \ 5 | / Or as two nested vectors: >>> pprint(meijerg([(1, 2), (3, 4)], ([5], Tuple()), x), use_unicode=False) __1, 2 /1, 2 3, 4 | \ /__ | | x| \_|4, 1 \ 5 | / As with the hypergeometric function, the parameters may be passed as arbitrary iterables. Vectors of length zero and one also have to be passed as iterables. The parameters need not be constants, but if they depend on the argument then not much implemented functionality should be expected. All the subvectors of parameters are available: >>> from sympy import pprint >>> g = meijerg([1], [2], [3], [4], x) >>> pprint(g, use_unicode=False) __1, 1 /1 2 | \ /__ | | x| \_|2, 2 \3 4 | / >>> g.an (1,) >>> g.ap (1, 2) >>> g.aother (2,) >>> g.bm (3,) >>> g.bq (3, 4) >>> g.bother (4,) The Meijer G-function generalizes the hypergeometric functions. In some cases it can be expressed in terms of hypergeometric functions, using Slater's theorem. For example: >>> from sympy import hyperexpand >>> from sympy.abc import a, b, c >>> hyperexpand(meijerg([a], [], [c], [b], x), allow_hyper=True) x**c*gamma(-a + c + 1)*hyper((-a + c + 1,), (-b + c + 1,), -x)/gamma(-b + c + 1) Thus the Meijer G-function also subsumes many named functions as special cases. You can use ``expand_func()`` or ``hyperexpand()`` to (try to) rewrite a Meijer G-function in terms of named special functions. For example: >>> from sympy import expand_func, S >>> expand_func(meijerg([[],[]], [[0],[]], -x)) exp(x) >>> hyperexpand(meijerg([[],[]], [[S(1)/2],[0]], (x/2)**2)) sin(x)/sqrt(pi) See Also ======== hyper sympy.simplify.hyperexpand References ========== .. [1] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 .. [2] https://en.wikipedia.org/wiki/Meijer_G-function """ def __new__(cls, *args, **kwargs): if len(args) == 5: args = [(args[0], args[1]), (args[2], args[3]), args[4]] if len(args) != 3: raise TypeError("args must be either as, as', bs, bs', z or " "as, bs, z") def tr(p): if len(p) != 2: raise TypeError("wrong argument") return TupleArg(_prep_tuple(p[0]), _prep_tuple(p[1])) arg0, arg1 = tr(args[0]), tr(args[1]) if Tuple(arg0, arg1).has(oo, zoo, -oo): raise ValueError("G-function parameters must be finite") if any((a - b).is_Integer and a - b > 0 for a in arg0[0] for b in arg1[0]): raise ValueError("no parameter a1, ..., an may differ from " "any b1, ..., bm by a positive integer") # TODO should we check convergence conditions? return Function.__new__(cls, arg0, arg1, args[2], **kwargs) def fdiff(self, argindex=3): if argindex != 3: return self._diff_wrt_parameter(argindex[1]) if len(self.an) >= 1: a = list(self.an) a[0] -= 1 G = meijerg(a, self.aother, self.bm, self.bother, self.argument) return 1/self.argument * ((self.an[0] - 1)*self + G) elif len(self.bm) >= 1: b = list(self.bm) b[0] += 1 G = meijerg(self.an, self.aother, b, self.bother, self.argument) return 1/self.argument * (self.bm[0]*self - G) else: return S.Zero def _diff_wrt_parameter(self, idx): # Differentiation wrt a parameter can only be done in very special # cases. In particular, if we want to differentiate with respect to # `a`, all other gamma factors have to reduce to rational functions. # # Let MT denote mellin transform. Suppose T(-s) is the gamma factor # appearing in the definition of G. Then # # MT(log(z)G(z)) = d/ds T(s) = d/da T(s) + ... # # Thus d/da G(z) = log(z)G(z) - ... # The ... can be evaluated as a G function under the above conditions, # the formula being most easily derived by using # # d Gamma(s + n) Gamma(s + n) / 1 1 1 \ # -- ------------ = ------------ | - + ---- + ... + --------- | # ds Gamma(s) Gamma(s) \ s s + 1 s + n - 1 / # # which follows from the difference equation of the digamma function. # (There is a similar equation for -n instead of +n). # We first figure out how to pair the parameters. an = list(self.an) ap = list(self.aother) bm = list(self.bm) bq = list(self.bother) if idx < len(an): an.pop(idx) else: idx -= len(an) if idx < len(ap): ap.pop(idx) else: idx -= len(ap) if idx < len(bm): bm.pop(idx) else: bq.pop(idx - len(bm)) pairs1 = [] pairs2 = [] for l1, l2, pairs in [(an, bq, pairs1), (ap, bm, pairs2)]: while l1: x = l1.pop() found = None for i, y in enumerate(l2): if not Mod((x - y).simplify(), 1): found = i break if found is None: raise NotImplementedError('Derivative not expressible ' 'as G-function?') y = l2[i] l2.pop(i) pairs.append((x, y)) # Now build the result. res = log(self.argument)*self for a, b in pairs1: sign = 1 n = a - b base = b if n < 0: sign = -1 n = b - a base = a for k in range(n): res -= sign*meijerg(self.an + (base + k + 1,), self.aother, self.bm, self.bother + (base + k + 0,), self.argument) for a, b in pairs2: sign = 1 n = b - a base = a if n < 0: sign = -1 n = a - b base = b for k in range(n): res -= sign*meijerg(self.an, self.aother + (base + k + 1,), self.bm + (base + k + 0,), self.bother, self.argument) return res def get_period(self): """ Return a number $P$ such that $G(x*exp(I*P)) == G(x)$. Examples ======== >>> from sympy import meijerg, pi, S >>> from sympy.abc import z >>> meijerg([1], [], [], [], z).get_period() 2*pi >>> meijerg([pi], [], [], [], z).get_period() oo >>> meijerg([1, 2], [], [], [], z).get_period() oo >>> meijerg([1,1], [2], [1, S(1)/2, S(1)/3], [1], z).get_period() 12*pi """ # This follows from slater's theorem. def compute(l): # first check that no two differ by an integer for i, b in enumerate(l): if not b.is_Rational: return oo for j in range(i + 1, len(l)): if not Mod((b - l[j]).simplify(), 1): return oo return reduce(ilcm, (x.q for x in l), 1) beta = compute(self.bm) alpha = compute(self.an) p, q = len(self.ap), len(self.bq) if p == q: if oo in (alpha, beta): return oo return 2*pi*ilcm(alpha, beta) elif p < q: return 2*pi*beta else: return 2*pi*alpha def _eval_expand_func(self, **hints): from sympy.simplify.hyperexpand import hyperexpand return hyperexpand(self) def _eval_evalf(self, prec): # The default code is insufficient for polar arguments. # mpmath provides an optional argument "r", which evaluates # G(z**(1/r)). I am not sure what its intended use is, but we hijack it # here in the following way: to evaluate at a number z of |argument| # less than (say) n*pi, we put r=1/n, compute z' = root(z, n) # (carefully so as not to loose the branch information), and evaluate # G(z'**(1/r)) = G(z'**n) = G(z). import mpmath znum = self.argument._eval_evalf(prec) if znum.has(exp_polar): znum, branch = znum.as_coeff_mul(exp_polar) if len(branch) != 1: return branch = branch[0].args[0]/I else: branch = S.Zero n = ceiling(abs(branch/pi)) + 1 znum = znum**(S.One/n)*exp(I*branch / n) # Convert all args to mpf or mpc try: [z, r, ap, bq] = [arg._to_mpmath(prec) for arg in [znum, 1/n, self.args[0], self.args[1]]] except ValueError: return with mpmath.workprec(prec): v = mpmath.meijerg(ap, bq, z, r) return Expr._from_mpmath(v, prec) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.simplify.hyperexpand import hyperexpand return hyperexpand(self).as_leading_term(x, logx=logx, cdir=cdir) def integrand(self, s): """ Get the defining integrand D(s). """ from sympy.functions.special.gamma_functions import gamma return self.argument**s \ * Mul(*(gamma(b - s) for b in self.bm)) \ * Mul(*(gamma(1 - a + s) for a in self.an)) \ / Mul(*(gamma(1 - b + s) for b in self.bother)) \ / Mul(*(gamma(a - s) for a in self.aother)) @property def argument(self): """ Argument of the Meijer G-function. """ return self.args[2] @property def an(self): """ First set of numerator parameters. """ return Tuple(*self.args[0][0]) @property def ap(self): """ Combined numerator parameters. """ return Tuple(*(self.args[0][0] + self.args[0][1])) @property def aother(self): """ Second set of numerator parameters. """ return Tuple(*self.args[0][1]) @property def bm(self): """ First set of denominator parameters. """ return Tuple(*self.args[1][0]) @property def bq(self): """ Combined denominator parameters. """ return Tuple(*(self.args[1][0] + self.args[1][1])) @property def bother(self): """ Second set of denominator parameters. """ return Tuple(*self.args[1][1]) @property def _diffargs(self): return self.ap + self.bq @property def nu(self): """ A quantity related to the convergence region of the integral, c.f. references. """ return sum(self.bq) - sum(self.ap) @property def delta(self): """ A quantity related to the convergence region of the integral, c.f. references. """ return len(self.bm) + len(self.an) - S(len(self.ap) + len(self.bq))/2 @property def is_number(self): """ Returns true if expression has numeric data only. """ return not self.free_symbols class HyperRep(Function): """ A base class for "hyper representation functions". This is used exclusively in ``hyperexpand()``, but fits more logically here. pFq is branched at 1 if p == q+1. For use with slater-expansion, we want define an "analytic continuation" to all polar numbers, which is continuous on circles and on the ray t*exp_polar(I*pi). Moreover, we want a "nice" expression for the various cases. This base class contains the core logic, concrete derived classes only supply the actual functions. """ @classmethod def eval(cls, *args): newargs = tuple(map(unpolarify, args[:-1])) + args[-1:] if args != newargs: return cls(*newargs) @classmethod def _expr_small(cls, x): """ An expression for F(x) which holds for |x| < 1. """ raise NotImplementedError @classmethod def _expr_small_minus(cls, x): """ An expression for F(-x) which holds for |x| < 1. """ raise NotImplementedError @classmethod def _expr_big(cls, x, n): """ An expression for F(exp_polar(2*I*pi*n)*x), |x| > 1. """ raise NotImplementedError @classmethod def _expr_big_minus(cls, x, n): """ An expression for F(exp_polar(2*I*pi*n + pi*I)*x), |x| > 1. """ raise NotImplementedError def _eval_rewrite_as_nonrep(self, *args, **kwargs): x, n = self.args[-1].extract_branch_factor(allow_half=True) minus = False newargs = self.args[:-1] + (x,) if not n.is_Integer: minus = True n -= S.Half newerargs = newargs + (n,) if minus: small = self._expr_small_minus(*newargs) big = self._expr_big_minus(*newerargs) else: small = self._expr_small(*newargs) big = self._expr_big(*newerargs) if big == small: return small return Piecewise((big, abs(x) > 1), (small, True)) def _eval_rewrite_as_nonrepsmall(self, *args, **kwargs): x, n = self.args[-1].extract_branch_factor(allow_half=True) args = self.args[:-1] + (x,) if not n.is_Integer: return self._expr_small_minus(*args) return self._expr_small(*args) class HyperRep_power1(HyperRep): """ Return a representative for hyper([-a], [], z) == (1 - z)**a. """ @classmethod def _expr_small(cls, a, x): return (1 - x)**a @classmethod def _expr_small_minus(cls, a, x): return (1 + x)**a @classmethod def _expr_big(cls, a, x, n): if a.is_integer: return cls._expr_small(a, x) return (x - 1)**a*exp((2*n - 1)*pi*I*a) @classmethod def _expr_big_minus(cls, a, x, n): if a.is_integer: return cls._expr_small_minus(a, x) return (1 + x)**a*exp(2*n*pi*I*a) class HyperRep_power2(HyperRep): """ Return a representative for hyper([a, a - 1/2], [2*a], z). """ @classmethod def _expr_small(cls, a, x): return 2**(2*a - 1)*(1 + sqrt(1 - x))**(1 - 2*a) @classmethod def _expr_small_minus(cls, a, x): return 2**(2*a - 1)*(1 + sqrt(1 + x))**(1 - 2*a) @classmethod def _expr_big(cls, a, x, n): sgn = -1 if n.is_odd: sgn = 1 n -= 1 return 2**(2*a - 1)*(1 + sgn*I*sqrt(x - 1))**(1 - 2*a) \ *exp(-2*n*pi*I*a) @classmethod def _expr_big_minus(cls, a, x, n): sgn = 1 if n.is_odd: sgn = -1 return sgn*2**(2*a - 1)*(sqrt(1 + x) + sgn)**(1 - 2*a)*exp(-2*pi*I*a*n) class HyperRep_log1(HyperRep): """ Represent -z*hyper([1, 1], [2], z) == log(1 - z). """ @classmethod def _expr_small(cls, x): return log(1 - x) @classmethod def _expr_small_minus(cls, x): return log(1 + x) @classmethod def _expr_big(cls, x, n): return log(x - 1) + (2*n - 1)*pi*I @classmethod def _expr_big_minus(cls, x, n): return log(1 + x) + 2*n*pi*I class HyperRep_atanh(HyperRep): """ Represent hyper([1/2, 1], [3/2], z) == atanh(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, x): return atanh(sqrt(x))/sqrt(x) def _expr_small_minus(cls, x): return atan(sqrt(x))/sqrt(x) def _expr_big(cls, x, n): if n.is_even: return (acoth(sqrt(x)) + I*pi/2)/sqrt(x) else: return (acoth(sqrt(x)) - I*pi/2)/sqrt(x) def _expr_big_minus(cls, x, n): if n.is_even: return atan(sqrt(x))/sqrt(x) else: return (atan(sqrt(x)) - pi)/sqrt(x) class HyperRep_asin1(HyperRep): """ Represent hyper([1/2, 1/2], [3/2], z) == asin(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, z): return asin(sqrt(z))/sqrt(z) @classmethod def _expr_small_minus(cls, z): return asinh(sqrt(z))/sqrt(z) @classmethod def _expr_big(cls, z, n): return S.NegativeOne**n*((S.Half - n)*pi/sqrt(z) + I*acosh(sqrt(z))/sqrt(z)) @classmethod def _expr_big_minus(cls, z, n): return S.NegativeOne**n*(asinh(sqrt(z))/sqrt(z) + n*pi*I/sqrt(z)) class HyperRep_asin2(HyperRep): """ Represent hyper([1, 1], [3/2], z) == asin(sqrt(z))/sqrt(z)/sqrt(1-z). """ # TODO this can be nicer @classmethod def _expr_small(cls, z): return HyperRep_asin1._expr_small(z) \ /HyperRep_power1._expr_small(S.Half, z) @classmethod def _expr_small_minus(cls, z): return HyperRep_asin1._expr_small_minus(z) \ /HyperRep_power1._expr_small_minus(S.Half, z) @classmethod def _expr_big(cls, z, n): return HyperRep_asin1._expr_big(z, n) \ /HyperRep_power1._expr_big(S.Half, z, n) @classmethod def _expr_big_minus(cls, z, n): return HyperRep_asin1._expr_big_minus(z, n) \ /HyperRep_power1._expr_big_minus(S.Half, z, n) class HyperRep_sqrts1(HyperRep): """ Return a representative for hyper([-a, 1/2 - a], [1/2], z). """ @classmethod def _expr_small(cls, a, z): return ((1 - sqrt(z))**(2*a) + (1 + sqrt(z))**(2*a))/2 @classmethod def _expr_small_minus(cls, a, z): return (1 + z)**a*cos(2*a*atan(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): if n.is_even: return ((sqrt(z) + 1)**(2*a)*exp(2*pi*I*n*a) + (sqrt(z) - 1)**(2*a)*exp(2*pi*I*(n - 1)*a))/2 else: n -= 1 return ((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n + 1)) + (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n))/2 @classmethod def _expr_big_minus(cls, a, z, n): if n.is_even: return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z))) else: return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z)) - 2*pi*a) class HyperRep_sqrts2(HyperRep): """ Return a representative for sqrt(z)/2*[(1-sqrt(z))**2a - (1 + sqrt(z))**2a] == -2*z/(2*a+1) d/dz hyper([-a - 1/2, -a], [1/2], z)""" @classmethod def _expr_small(cls, a, z): return sqrt(z)*((1 - sqrt(z))**(2*a) - (1 + sqrt(z))**(2*a))/2 @classmethod def _expr_small_minus(cls, a, z): return sqrt(z)*(1 + z)**a*sin(2*a*atan(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): if n.is_even: return sqrt(z)/2*((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n - 1)) - (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n)) else: n -= 1 return sqrt(z)/2*((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n + 1)) - (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n)) def _expr_big_minus(cls, a, z, n): if n.is_even: return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z)*sin(2*a*atan(sqrt(z))) else: return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z) \ *sin(2*a*atan(sqrt(z)) - 2*pi*a) class HyperRep_log2(HyperRep): """ Represent log(1/2 + sqrt(1 - z)/2) == -z/4*hyper([3/2, 1, 1], [2, 2], z) """ @classmethod def _expr_small(cls, z): return log(S.Half + sqrt(1 - z)/2) @classmethod def _expr_small_minus(cls, z): return log(S.Half + sqrt(1 + z)/2) @classmethod def _expr_big(cls, z, n): if n.is_even: return (n - S.Half)*pi*I + log(sqrt(z)/2) + I*asin(1/sqrt(z)) else: return (n - S.Half)*pi*I + log(sqrt(z)/2) - I*asin(1/sqrt(z)) def _expr_big_minus(cls, z, n): if n.is_even: return pi*I*n + log(S.Half + sqrt(1 + z)/2) else: return pi*I*n + log(sqrt(1 + z)/2 - S.Half) class HyperRep_cosasin(HyperRep): """ Represent hyper([a, -a], [1/2], z) == cos(2*a*asin(sqrt(z))). """ # Note there are many alternative expressions, e.g. as powers of a sum of # square roots. @classmethod def _expr_small(cls, a, z): return cos(2*a*asin(sqrt(z))) @classmethod def _expr_small_minus(cls, a, z): return cosh(2*a*asinh(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): return cosh(2*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1)) @classmethod def _expr_big_minus(cls, a, z, n): return cosh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n) class HyperRep_sinasin(HyperRep): """ Represent 2*a*z*hyper([1 - a, 1 + a], [3/2], z) == sqrt(z)/sqrt(1-z)*sin(2*a*asin(sqrt(z))) """ @classmethod def _expr_small(cls, a, z): return sqrt(z)/sqrt(1 - z)*sin(2*a*asin(sqrt(z))) @classmethod def _expr_small_minus(cls, a, z): return -sqrt(z)/sqrt(1 + z)*sinh(2*a*asinh(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): return -1/sqrt(1 - 1/z)*sinh(2*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1)) @classmethod def _expr_big_minus(cls, a, z, n): return -1/sqrt(1 + 1/z)*sinh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n) class appellf1(Function): r""" This is the Appell hypergeometric function of two variables as: .. math :: F_1(a,b_1,b_2,c,x,y) = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} \frac{(a)_{m+n} (b_1)_m (b_2)_n}{(c)_{m+n}} \frac{x^m y^n}{m! n!}. Examples ======== >>> from sympy import appellf1, symbols >>> x, y, a, b1, b2, c = symbols('x y a b1 b2 c') >>> appellf1(2., 1., 6., 4., 5., 6.) 0.0063339426292673 >>> appellf1(12., 12., 6., 4., 0.5, 0.12) 172870711.659936 >>> appellf1(40, 2, 6, 4, 15, 60) appellf1(40, 2, 6, 4, 15, 60) >>> appellf1(20., 12., 10., 3., 0.5, 0.12) 15605338197184.4 >>> appellf1(40, 2, 6, 4, x, y) appellf1(40, 2, 6, 4, x, y) >>> appellf1(a, b1, b2, c, x, y) appellf1(a, b1, b2, c, x, y) References ========== .. [1] https://en.wikipedia.org/wiki/Appell_series .. [2] http://functions.wolfram.com/HypergeometricFunctions/AppellF1/ """ @classmethod def eval(cls, a, b1, b2, c, x, y): if default_sort_key(b1) > default_sort_key(b2): b1, b2 = b2, b1 x, y = y, x return cls(a, b1, b2, c, x, y) elif b1 == b2 and default_sort_key(x) > default_sort_key(y): x, y = y, x return cls(a, b1, b2, c, x, y) if x == 0 and y == 0: return S.One def fdiff(self, argindex=5): a, b1, b2, c, x, y = self.args if argindex == 5: return (a*b1/c)*appellf1(a + 1, b1 + 1, b2, c + 1, x, y) elif argindex == 6: return (a*b2/c)*appellf1(a + 1, b1, b2 + 1, c + 1, x, y) elif argindex in (1, 2, 3, 4): return Derivative(self, self.args[argindex-1]) else: raise ArgumentIndexError(self, argindex)
eea9a62ca408879861b30da3bbfb090e48c2e7dc5884f696af0c197c286d4db7
from math import prod from sympy.core import Add, S, Dummy, expand_func from sympy.core.expr import Expr from sympy.core.function import Function, ArgumentIndexError, PoleError from sympy.core.logic import fuzzy_and, fuzzy_not from sympy.core.numbers import Rational, pi, oo, I from sympy.core.power import Pow from sympy.functions.special.zeta_functions import zeta from sympy.functions.special.error_functions import erf, erfc, Ei from sympy.functions.elementary.complexes import re, unpolarify from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin, cos, cot from sympy.functions.combinatorial.numbers import bernoulli, harmonic from sympy.functions.combinatorial.factorials import factorial, rf, RisingFactorial from sympy.utilities.misc import as_int from mpmath import mp, workprec from mpmath.libmp.libmpf import prec_to_dps def intlike(n): try: as_int(n, strict=False) return True except ValueError: return False ############################################################################### ############################ COMPLETE GAMMA FUNCTION ########################## ############################################################################### class gamma(Function): r""" The gamma function .. math:: \Gamma(x) := \int^{\infty}_{0} t^{x-1} e^{-t} \mathrm{d}t. Explanation =========== The ``gamma`` function implements the function which passes through the values of the factorial function (i.e., $\Gamma(n) = (n - 1)!$ when n is an integer). More generally, $\Gamma(z)$ is defined in the whole complex plane except at the negative integers where there are simple poles. Examples ======== >>> from sympy import S, I, pi, gamma >>> from sympy.abc import x Several special values are known: >>> gamma(1) 1 >>> gamma(4) 6 >>> gamma(S(3)/2) sqrt(pi)/2 The ``gamma`` function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(gamma(x)) gamma(conjugate(x)) Differentiation with respect to $x$ is supported: >>> from sympy import diff >>> diff(gamma(x), x) gamma(x)*polygamma(0, x) Series expansion is also supported: >>> from sympy import series >>> series(gamma(x), x, 0, 3) 1/x - EulerGamma + x*(EulerGamma**2/2 + pi**2/12) + x**2*(-EulerGamma*pi**2/12 - zeta(3)/3 - EulerGamma**3/6) + O(x**3) We can numerically evaluate the ``gamma`` function to arbitrary precision on the whole complex plane: >>> gamma(pi).evalf(40) 2.288037795340032417959588909060233922890 >>> gamma(1+I).evalf(20) 0.49801566811835604271 - 0.15494982830181068512*I See Also ======== lowergamma: Lower incomplete gamma function. uppergamma: Upper incomplete gamma function. polygamma: Polygamma function. loggamma: Log Gamma function. digamma: Digamma function. trigamma: Trigamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Gamma_function .. [2] http://dlmf.nist.gov/5 .. [3] http://mathworld.wolfram.com/GammaFunction.html .. [4] http://functions.wolfram.com/GammaBetaErf/Gamma/ """ unbranched = True _singularities = (S.ComplexInfinity,) def fdiff(self, argindex=1): if argindex == 1: return self.func(self.args[0])*polygamma(0, self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is oo: return oo elif intlike(arg): if arg.is_positive: return factorial(arg - 1) else: return S.ComplexInfinity elif arg.is_Rational: if arg.q == 2: n = abs(arg.p) // arg.q if arg.is_positive: k, coeff = n, S.One else: n = k = n + 1 if n & 1 == 0: coeff = S.One else: coeff = S.NegativeOne coeff *= prod(range(3, 2*k, 2)) if arg.is_positive: return coeff*sqrt(pi) / 2**n else: return 2**n*sqrt(pi) / coeff def _eval_expand_func(self, **hints): arg = self.args[0] if arg.is_Rational: if abs(arg.p) > arg.q: x = Dummy('x') n = arg.p // arg.q p = arg.p - n*arg.q return self.func(x + n)._eval_expand_func().subs(x, Rational(p, arg.q)) if arg.is_Add: coeff, tail = arg.as_coeff_add() if coeff and coeff.q != 1: intpart = floor(coeff) tail = (coeff - intpart,) + tail coeff = intpart tail = arg._new_rawargs(*tail, reeval=False) return self.func(tail)*RisingFactorial(tail, coeff) return self.func(*self.args) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_real(self): x = self.args[0] if x.is_nonpositive and x.is_integer: return False if intlike(x) and x <= 0: return False if x.is_positive or x.is_noninteger: return True def _eval_is_positive(self): x = self.args[0] if x.is_positive: return True elif x.is_noninteger: return floor(x).is_even def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return exp(loggamma(z)) def _eval_rewrite_as_factorial(self, z, **kwargs): return factorial(z - 1) def _eval_nseries(self, x, n, logx, cdir=0): x0 = self.args[0].limit(x, 0) if not (x0.is_Integer and x0 <= 0): return super()._eval_nseries(x, n, logx) t = self.args[0] - x0 return (self.func(t + 1)/rf(self.args[0], -x0 + 1))._eval_nseries(x, n, logx) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] x0 = arg.subs(x, 0) if x0.is_integer and x0.is_nonpositive: n = -x0 res = S.NegativeOne**n/self.func(n + 1) return res/(arg + n).as_leading_term(x) elif not x0.is_infinite: return self.func(x0) raise PoleError() ############################################################################### ################## LOWER and UPPER INCOMPLETE GAMMA FUNCTIONS ################# ############################################################################### class lowergamma(Function): r""" The lower incomplete gamma function. Explanation =========== It can be defined as the meromorphic continuation of .. math:: \gamma(s, x) := \int_0^x t^{s-1} e^{-t} \mathrm{d}t = \Gamma(s) - \Gamma(s, x). This can be shown to be the same as .. math:: \gamma(s, x) = \frac{x^s}{s} {}_1F_1\left({s \atop s+1} \middle| -x\right), where ${}_1F_1$ is the (confluent) hypergeometric function. Examples ======== >>> from sympy import lowergamma, S >>> from sympy.abc import s, x >>> lowergamma(s, x) lowergamma(s, x) >>> lowergamma(3, x) -2*(x**2/2 + x + 1)*exp(-x) + 2 >>> lowergamma(-S(1)/2, x) -2*sqrt(pi)*erf(sqrt(x)) - 2*exp(-x)/sqrt(x) See Also ======== gamma: Gamma function. uppergamma: Upper incomplete gamma function. polygamma: Polygamma function. loggamma: Log Gamma function. digamma: Digamma function. trigamma: Trigamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Incomplete_gamma_function#Lower_incomplete_Gamma_function .. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6, Section 5, Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables .. [3] http://dlmf.nist.gov/8 .. [4] http://functions.wolfram.com/GammaBetaErf/Gamma2/ .. [5] http://functions.wolfram.com/GammaBetaErf/Gamma3/ """ def fdiff(self, argindex=2): from sympy.functions.special.hyper import meijerg if argindex == 2: a, z = self.args return exp(-unpolarify(z))*z**(a - 1) elif argindex == 1: a, z = self.args return gamma(a)*digamma(a) - log(z)*uppergamma(a, z) \ - meijerg([], [1, 1], [0, 0, a], [], z) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, a, x): # For lack of a better place, we use this one to extract branching # information. The following can be # found in the literature (c/f references given above), albeit scattered: # 1) For fixed x != 0, lowergamma(s, x) is an entire function of s # 2) For fixed positive integers s, lowergamma(s, x) is an entire # function of x. # 3) For fixed non-positive integers s, # lowergamma(s, exp(I*2*pi*n)*x) = # 2*pi*I*n*(-1)**(-s)/factorial(-s) + lowergamma(s, x) # (this follows from lowergamma(s, x).diff(x) = x**(s-1)*exp(-x)). # 4) For fixed non-integral s, # lowergamma(s, x) = x**s*gamma(s)*lowergamma_unbranched(s, x), # where lowergamma_unbranched(s, x) is an entire function (in fact # of both s and x), i.e. # lowergamma(s, exp(2*I*pi*n)*x) = exp(2*pi*I*n*a)*lowergamma(a, x) if x is S.Zero: return S.Zero nx, n = x.extract_branch_factor() if a.is_integer and a.is_positive: nx = unpolarify(x) if nx != x: return lowergamma(a, nx) elif a.is_integer and a.is_nonpositive: if n != 0: return 2*pi*I*n*S.NegativeOne**(-a)/factorial(-a) + lowergamma(a, nx) elif n != 0: return exp(2*pi*I*n*a)*lowergamma(a, nx) # Special values. if a.is_Number: if a is S.One: return S.One - exp(-x) elif a is S.Half: return sqrt(pi)*erf(sqrt(x)) elif a.is_Integer or (2*a).is_Integer: b = a - 1 if b.is_positive: if a.is_integer: return factorial(b) - exp(-x) * factorial(b) * Add(*[x ** k / factorial(k) for k in range(a)]) else: return gamma(a)*(lowergamma(S.Half, x)/sqrt(pi) - exp(-x)*Add(*[x**(k - S.Half)/gamma(S.Half + k) for k in range(1, a + S.Half)])) if not a.is_Integer: return S.NegativeOne**(S.Half - a)*pi*erf(sqrt(x))/gamma(1 - a) + exp(-x)*Add(*[x**(k + a - 1)*gamma(a)/gamma(a + k) for k in range(1, Rational(3, 2) - a)]) if x.is_zero: return S.Zero def _eval_evalf(self, prec): if all(x.is_number for x in self.args): a = self.args[0]._to_mpmath(prec) z = self.args[1]._to_mpmath(prec) with workprec(prec): res = mp.gammainc(a, 0, z) return Expr._from_mpmath(res, prec) else: return self def _eval_conjugate(self): x = self.args[1] if x not in (S.Zero, S.NegativeInfinity): return self.func(self.args[0].conjugate(), x.conjugate()) def _eval_is_meromorphic(self, x, a): # By https://en.wikipedia.org/wiki/Incomplete_gamma_function#Holomorphic_extension, # lowergamma(s, z) = z**s*gamma(s)*gammastar(s, z), # where gammastar(s, z) is holomorphic for all s and z. # Hence the singularities of lowergamma are z = 0 (branch # point) and nonpositive integer values of s (poles of gamma(s)). s, z = self.args args_merom = fuzzy_and([z._eval_is_meromorphic(x, a), s._eval_is_meromorphic(x, a)]) if not args_merom: return args_merom z0 = z.subs(x, a) if s.is_integer: return fuzzy_and([s.is_positive, z0.is_finite]) s0 = s.subs(x, a) return fuzzy_and([s0.is_finite, z0.is_finite, fuzzy_not(z0.is_zero)]) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import O s, z = self.args if args0[0] is oo and not z.has(x): coeff = z**s*exp(-z) sum_expr = sum(z**k/rf(s, k + 1) for k in range(n - 1)) o = O(z**s*s**(-n)) return coeff*sum_expr + o return super()._eval_aseries(n, args0, x, logx) def _eval_rewrite_as_uppergamma(self, s, x, **kwargs): return gamma(s) - uppergamma(s, x) def _eval_rewrite_as_expint(self, s, x, **kwargs): from sympy.functions.special.error_functions import expint if s.is_integer and s.is_nonpositive: return self return self.rewrite(uppergamma).rewrite(expint) def _eval_is_zero(self): x = self.args[1] if x.is_zero: return True class uppergamma(Function): r""" The upper incomplete gamma function. Explanation =========== It can be defined as the meromorphic continuation of .. math:: \Gamma(s, x) := \int_x^\infty t^{s-1} e^{-t} \mathrm{d}t = \Gamma(s) - \gamma(s, x). where $\gamma(s, x)$ is the lower incomplete gamma function, :class:`lowergamma`. This can be shown to be the same as .. math:: \Gamma(s, x) = \Gamma(s) - \frac{x^s}{s} {}_1F_1\left({s \atop s+1} \middle| -x\right), where ${}_1F_1$ is the (confluent) hypergeometric function. The upper incomplete gamma function is also essentially equivalent to the generalized exponential integral: .. math:: \operatorname{E}_{n}(x) = \int_{1}^{\infty}{\frac{e^{-xt}}{t^n} \, dt} = x^{n-1}\Gamma(1-n,x). Examples ======== >>> from sympy import uppergamma, S >>> from sympy.abc import s, x >>> uppergamma(s, x) uppergamma(s, x) >>> uppergamma(3, x) 2*(x**2/2 + x + 1)*exp(-x) >>> uppergamma(-S(1)/2, x) -2*sqrt(pi)*erfc(sqrt(x)) + 2*exp(-x)/sqrt(x) >>> uppergamma(-2, x) expint(3, x)/x**2 See Also ======== gamma: Gamma function. lowergamma: Lower incomplete gamma function. polygamma: Polygamma function. loggamma: Log Gamma function. digamma: Digamma function. trigamma: Trigamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Incomplete_gamma_function#Upper_incomplete_Gamma_function .. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6, Section 5, Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables .. [3] http://dlmf.nist.gov/8 .. [4] http://functions.wolfram.com/GammaBetaErf/Gamma2/ .. [5] http://functions.wolfram.com/GammaBetaErf/Gamma3/ .. [6] https://en.wikipedia.org/wiki/Exponential_integral#Relation_with_other_functions """ def fdiff(self, argindex=2): from sympy.functions.special.hyper import meijerg if argindex == 2: a, z = self.args return -exp(-unpolarify(z))*z**(a - 1) elif argindex == 1: a, z = self.args return uppergamma(a, z)*log(z) + meijerg([], [1, 1], [0, 0, a], [], z) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): if all(x.is_number for x in self.args): a = self.args[0]._to_mpmath(prec) z = self.args[1]._to_mpmath(prec) with workprec(prec): res = mp.gammainc(a, z, mp.inf) return Expr._from_mpmath(res, prec) return self @classmethod def eval(cls, a, z): from sympy.functions.special.error_functions import expint if z.is_Number: if z is S.NaN: return S.NaN elif z is oo: return S.Zero elif z.is_zero: if re(a).is_positive: return gamma(a) # We extract branching information here. C/f lowergamma. nx, n = z.extract_branch_factor() if a.is_integer and a.is_positive: nx = unpolarify(z) if z != nx: return uppergamma(a, nx) elif a.is_integer and a.is_nonpositive: if n != 0: return -2*pi*I*n*S.NegativeOne**(-a)/factorial(-a) + uppergamma(a, nx) elif n != 0: return gamma(a)*(1 - exp(2*pi*I*n*a)) + exp(2*pi*I*n*a)*uppergamma(a, nx) # Special values. if a.is_Number: if a is S.Zero and z.is_positive: return -Ei(-z) elif a is S.One: return exp(-z) elif a is S.Half: return sqrt(pi)*erfc(sqrt(z)) elif a.is_Integer or (2*a).is_Integer: b = a - 1 if b.is_positive: if a.is_integer: return exp(-z) * factorial(b) * Add(*[z**k / factorial(k) for k in range(a)]) else: return (gamma(a) * erfc(sqrt(z)) + S.NegativeOne**(a - S(3)/2) * exp(-z) * sqrt(z) * Add(*[gamma(-S.Half - k) * (-z)**k / gamma(1-a) for k in range(a - S.Half)])) elif b.is_Integer: return expint(-b, z)*unpolarify(z)**(b + 1) if not a.is_Integer: return (S.NegativeOne**(S.Half - a) * pi*erfc(sqrt(z))/gamma(1-a) - z**a * exp(-z) * Add(*[z**k * gamma(a) / gamma(a+k+1) for k in range(S.Half - a)])) if a.is_zero and z.is_positive: return -Ei(-z) if z.is_zero and re(a).is_positive: return gamma(a) def _eval_conjugate(self): z = self.args[1] if z not in (S.Zero, S.NegativeInfinity): return self.func(self.args[0].conjugate(), z.conjugate()) def _eval_is_meromorphic(self, x, a): return lowergamma._eval_is_meromorphic(self, x, a) def _eval_rewrite_as_lowergamma(self, s, x, **kwargs): return gamma(s) - lowergamma(s, x) def _eval_rewrite_as_tractable(self, s, x, **kwargs): return exp(loggamma(s)) - lowergamma(s, x) def _eval_rewrite_as_expint(self, s, x, **kwargs): from sympy.functions.special.error_functions import expint return expint(1 - s, x)*x**s ############################################################################### ###################### POLYGAMMA and LOGGAMMA FUNCTIONS ####################### ############################################################################### class polygamma(Function): r""" The function ``polygamma(n, z)`` returns ``log(gamma(z)).diff(n + 1)``. Explanation =========== It is a meromorphic function on $\mathbb{C}$ and defined as the $(n+1)$-th derivative of the logarithm of the gamma function: .. math:: \psi^{(n)} (z) := \frac{\mathrm{d}^{n+1}}{\mathrm{d} z^{n+1}} \log\Gamma(z). For `n` not a nonnegative integer the generalization by Espinosa and Moll [5]_ is used: .. math:: \psi(s,z) = \frac{\zeta'(s+1, z) + (\gamma + \psi(-s)) \zeta(s+1, z)} {\Gamma(-s)} Examples ======== Several special values are known: >>> from sympy import S, polygamma >>> polygamma(0, 1) -EulerGamma >>> polygamma(0, 1/S(2)) -2*log(2) - EulerGamma >>> polygamma(0, 1/S(3)) -log(3) - sqrt(3)*pi/6 - EulerGamma - log(sqrt(3)) >>> polygamma(0, 1/S(4)) -pi/2 - log(4) - log(2) - EulerGamma >>> polygamma(0, 2) 1 - EulerGamma >>> polygamma(0, 23) 19093197/5173168 - EulerGamma >>> from sympy import oo, I >>> polygamma(0, oo) oo >>> polygamma(0, -oo) oo >>> polygamma(0, I*oo) oo >>> polygamma(0, -I*oo) oo Differentiation with respect to $x$ is supported: >>> from sympy import Symbol, diff >>> x = Symbol("x") >>> diff(polygamma(0, x), x) polygamma(1, x) >>> diff(polygamma(0, x), x, 2) polygamma(2, x) >>> diff(polygamma(0, x), x, 3) polygamma(3, x) >>> diff(polygamma(1, x), x) polygamma(2, x) >>> diff(polygamma(1, x), x, 2) polygamma(3, x) >>> diff(polygamma(2, x), x) polygamma(3, x) >>> diff(polygamma(2, x), x, 2) polygamma(4, x) >>> n = Symbol("n") >>> diff(polygamma(n, x), x) polygamma(n + 1, x) >>> diff(polygamma(n, x), x, 2) polygamma(n + 2, x) We can rewrite ``polygamma`` functions in terms of harmonic numbers: >>> from sympy import harmonic >>> polygamma(0, x).rewrite(harmonic) harmonic(x - 1) - EulerGamma >>> polygamma(2, x).rewrite(harmonic) 2*harmonic(x - 1, 3) - 2*zeta(3) >>> ni = Symbol("n", integer=True) >>> polygamma(ni, x).rewrite(harmonic) (-1)**(n + 1)*(-harmonic(x - 1, n + 1) + zeta(n + 1))*factorial(n) See Also ======== gamma: Gamma function. lowergamma: Lower incomplete gamma function. uppergamma: Upper incomplete gamma function. loggamma: Log Gamma function. digamma: Digamma function. trigamma: Trigamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Polygamma_function .. [2] http://mathworld.wolfram.com/PolygammaFunction.html .. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma/ .. [4] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/ .. [5] O. Espinosa and V. Moll, "A generalized polygamma function", *Integral Transforms and Special Functions* (2004), 101-115. """ @classmethod def eval(cls, n, z): if n is S.NaN or z is S.NaN: return S.NaN elif z is oo: return oo if n.is_zero else S.Zero elif z.is_Integer and z.is_nonpositive: return S.ComplexInfinity elif n is S.NegativeOne: return loggamma(z) - log(2*pi) / 2 elif n.is_zero: if z is -oo or z.extract_multiplicatively(I) in (oo, -oo): return oo elif z.is_Integer: return harmonic(z-1) - S.EulerGamma elif z.is_Rational: # TODO n == 1 also can do some rational z p, q = z.as_numer_denom() # only expand for small denominators to avoid creating long expressions if q <= 6: return expand_func(polygamma(S.Zero, z, evaluate=False)) elif n.is_integer and n.is_nonnegative: nz = unpolarify(z) if z != nz: return polygamma(n, nz) if z.is_Integer: return S.NegativeOne**(n+1) * factorial(n) * zeta(n+1, z) elif z is S.Half: return S.NegativeOne**(n+1) * factorial(n) * (2**(n+1)-1) * zeta(n+1) def _eval_is_real(self): if self.args[0].is_positive and self.args[1].is_positive: return True def _eval_is_complex(self): z = self.args[1] is_negative_integer = fuzzy_and([z.is_negative, z.is_integer]) return fuzzy_and([z.is_complex, fuzzy_not(is_negative_integer)]) def _eval_is_positive(self): n, z = self.args if n.is_positive: if n.is_odd and z.is_real: return True if n.is_even and z.is_positive: return False def _eval_is_negative(self): n, z = self.args if n.is_positive: if n.is_even and z.is_positive: return True if n.is_odd and z.is_real: return False def _eval_expand_func(self, **hints): n, z = self.args if n.is_Integer and n.is_nonnegative: if z.is_Add: coeff = z.args[0] if coeff.is_Integer: e = -(n + 1) if coeff > 0: tail = Add(*[Pow( z - i, e) for i in range(1, int(coeff) + 1)]) else: tail = -Add(*[Pow( z + i, e) for i in range(int(-coeff))]) return polygamma(n, z - coeff) + S.NegativeOne**n*factorial(n)*tail elif z.is_Mul: coeff, z = z.as_two_terms() if coeff.is_Integer and coeff.is_positive: tail = [polygamma(n, z + Rational( i, coeff)) for i in range(int(coeff))] if n == 0: return Add(*tail)/coeff + log(coeff) else: return Add(*tail)/coeff**(n + 1) z *= coeff if n == 0 and z.is_Rational: p, q = z.as_numer_denom() # Reference: # Values of the polygamma functions at rational arguments, J. Choi, 2007 part_1 = -S.EulerGamma - pi * cot(p * pi / q) / 2 - log(q) + Add( *[cos(2 * k * pi * p / q) * log(2 * sin(k * pi / q)) for k in range(1, q)]) if z > 0: n = floor(z) z0 = z - n return part_1 + Add(*[1 / (z0 + k) for k in range(n)]) elif z < 0: n = floor(1 - z) z0 = z + n return part_1 - Add(*[1 / (z0 - 1 - k) for k in range(n)]) if n == -1: return loggamma(z) - log(2*pi) / 2 if n.is_integer is False or n.is_nonnegative is False: s = Dummy("s") dzt = zeta(s, z).diff(s).subs(s, n+1) return (dzt + (S.EulerGamma + digamma(-n)) * zeta(n+1, z)) / gamma(-n) return polygamma(n, z) def _eval_rewrite_as_zeta(self, n, z, **kwargs): if n.is_integer and n.is_positive: return S.NegativeOne**(n + 1)*factorial(n)*zeta(n + 1, z) def _eval_rewrite_as_harmonic(self, n, z, **kwargs): if n.is_integer: if n.is_zero: return harmonic(z - 1) - S.EulerGamma else: return S.NegativeOne**(n+1) * factorial(n) * (zeta(n+1) - harmonic(z-1, n+1)) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order n, z = [a.as_leading_term(x) for a in self.args] o = Order(z, x) if n == 0 and o.contains(1/x): logx = log(x) if logx is None else logx return o.getn() * logx else: return self.func(n, z) def fdiff(self, argindex=2): if argindex == 2: n, z = self.args[:2] return polygamma(n + 1, z) else: raise ArgumentIndexError(self, argindex) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order if args0[1] != oo or not \ (self.args[0].is_Integer and self.args[0].is_nonnegative): return super()._eval_aseries(n, args0, x, logx) z = self.args[1] N = self.args[0] if N == 0: # digamma function series # Abramowitz & Stegun, p. 259, 6.3.18 r = log(z) - 1/(2*z) o = None if n < 2: o = Order(1/z, x) else: m = ceiling((n + 1)//2) l = [bernoulli(2*k) / (2*k*z**(2*k)) for k in range(1, m)] r -= Add(*l) o = Order(1/z**n, x) return r._eval_nseries(x, n, logx) + o else: # proper polygamma function # Abramowitz & Stegun, p. 260, 6.4.10 # We return terms to order higher than O(x**n) on purpose # -- otherwise we would not be able to return any terms for # quite a long time! fac = gamma(N) e0 = fac + N*fac/(2*z) m = ceiling((n + 1)//2) for k in range(1, m): fac = fac*(2*k + N - 1)*(2*k + N - 2) / ((2*k)*(2*k - 1)) e0 += bernoulli(2*k)*fac/z**(2*k) o = Order(1/z**(2*m), x) if n == 0: o = Order(1/z, x) elif n == 1: o = Order(1/z**2, x) r = e0._eval_nseries(z, n, logx) + o return (-1 * (-1/z)**N * r)._eval_nseries(x, n, logx) def _eval_evalf(self, prec): if not all(i.is_number for i in self.args): return s = self.args[0]._to_mpmath(prec+12) z = self.args[1]._to_mpmath(prec+12) if mp.isint(z) and z <= 0: return S.ComplexInfinity with workprec(prec+12): if mp.isint(s) and s >= 0: res = mp.polygamma(s, z) else: zt = mp.zeta(s+1, z) dzt = mp.zeta(s+1, z, 1) res = (dzt + (mp.euler + mp.digamma(-s)) * zt) * mp.rgamma(-s) return Expr._from_mpmath(res, prec) class loggamma(Function): r""" The ``loggamma`` function implements the logarithm of the gamma function (i.e., $\log\Gamma(x)$). Examples ======== Several special values are known. For numerical integral arguments we have: >>> from sympy import loggamma >>> loggamma(-2) oo >>> loggamma(0) oo >>> loggamma(1) 0 >>> loggamma(2) 0 >>> loggamma(3) log(2) And for symbolic values: >>> from sympy import Symbol >>> n = Symbol("n", integer=True, positive=True) >>> loggamma(n) log(gamma(n)) >>> loggamma(-n) oo For half-integral values: >>> from sympy import S >>> loggamma(S(5)/2) log(3*sqrt(pi)/4) >>> loggamma(n/2) log(2**(1 - n)*sqrt(pi)*gamma(n)/gamma(n/2 + 1/2)) And general rational arguments: >>> from sympy import expand_func >>> L = loggamma(S(16)/3) >>> expand_func(L).doit() -5*log(3) + loggamma(1/3) + log(4) + log(7) + log(10) + log(13) >>> L = loggamma(S(19)/4) >>> expand_func(L).doit() -4*log(4) + loggamma(3/4) + log(3) + log(7) + log(11) + log(15) >>> L = loggamma(S(23)/7) >>> expand_func(L).doit() -3*log(7) + log(2) + loggamma(2/7) + log(9) + log(16) The ``loggamma`` function has the following limits towards infinity: >>> from sympy import oo >>> loggamma(oo) oo >>> loggamma(-oo) zoo The ``loggamma`` function obeys the mirror symmetry if $x \in \mathbb{C} \setminus \{-\infty, 0\}$: >>> from sympy.abc import x >>> from sympy import conjugate >>> conjugate(loggamma(x)) loggamma(conjugate(x)) Differentiation with respect to $x$ is supported: >>> from sympy import diff >>> diff(loggamma(x), x) polygamma(0, x) Series expansion is also supported: >>> from sympy import series >>> series(loggamma(x), x, 0, 4).cancel() -log(x) - EulerGamma*x + pi**2*x**2/12 - x**3*zeta(3)/3 + O(x**4) We can numerically evaluate the ``loggamma`` function to arbitrary precision on the whole complex plane: >>> from sympy import I >>> loggamma(5).evalf(30) 3.17805383034794561964694160130 >>> loggamma(I).evalf(20) -0.65092319930185633889 - 1.8724366472624298171*I See Also ======== gamma: Gamma function. lowergamma: Lower incomplete gamma function. uppergamma: Upper incomplete gamma function. polygamma: Polygamma function. digamma: Digamma function. trigamma: Trigamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Gamma_function .. [2] http://dlmf.nist.gov/5 .. [3] http://mathworld.wolfram.com/LogGammaFunction.html .. [4] http://functions.wolfram.com/GammaBetaErf/LogGamma/ """ @classmethod def eval(cls, z): if z.is_integer: if z.is_nonpositive: return oo elif z.is_positive: return log(gamma(z)) elif z.is_rational: p, q = z.as_numer_denom() # Half-integral values: if p.is_positive and q == 2: return log(sqrt(pi) * 2**(1 - p) * gamma(p) / gamma((p + 1)*S.Half)) if z is oo: return oo elif abs(z) is oo: return S.ComplexInfinity if z is S.NaN: return S.NaN def _eval_expand_func(self, **hints): from sympy.concrete.summations import Sum z = self.args[0] if z.is_Rational: p, q = z.as_numer_denom() # General rational arguments (u + p/q) # Split z as n + p/q with p < q n = p // q p = p - n*q if p.is_positive and q.is_positive and p < q: k = Dummy("k") if n.is_positive: return loggamma(p / q) - n*log(q) + Sum(log((k - 1)*q + p), (k, 1, n)) elif n.is_negative: return loggamma(p / q) - n*log(q) + pi*I*n - Sum(log(k*q - p), (k, 1, -n)) elif n.is_zero: return loggamma(p / q) return self def _eval_nseries(self, x, n, logx=None, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_intractable(*self.args) return f._eval_nseries(x, n, logx) return super()._eval_nseries(x, n, logx) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order if args0[0] != oo: return super()._eval_aseries(n, args0, x, logx) z = self.args[0] r = log(z)*(z - S.Half) - z + log(2*pi)/2 l = [bernoulli(2*k) / (2*k*(2*k - 1)*z**(2*k - 1)) for k in range(1, n)] o = None if n == 0: o = Order(1, x) else: o = Order(1/z**n, x) # It is very inefficient to first add the order and then do the nseries return (r + Add(*l))._eval_nseries(x, n, logx) + o def _eval_rewrite_as_intractable(self, z, **kwargs): return log(gamma(z)) def _eval_is_real(self): z = self.args[0] if z.is_positive: return True elif z.is_nonpositive: return False def _eval_conjugate(self): z = self.args[0] if z not in (S.Zero, S.NegativeInfinity): return self.func(z.conjugate()) def fdiff(self, argindex=1): if argindex == 1: return polygamma(0, self.args[0]) else: raise ArgumentIndexError(self, argindex) class digamma(Function): r""" The ``digamma`` function is the first derivative of the ``loggamma`` function .. math:: \psi(x) := \frac{\mathrm{d}}{\mathrm{d} z} \log\Gamma(z) = \frac{\Gamma'(z)}{\Gamma(z) }. In this case, ``digamma(z) = polygamma(0, z)``. Examples ======== >>> from sympy import digamma >>> digamma(0) zoo >>> from sympy import Symbol >>> z = Symbol('z') >>> digamma(z) polygamma(0, z) To retain ``digamma`` as it is: >>> digamma(0, evaluate=False) digamma(0) >>> digamma(z, evaluate=False) digamma(z) See Also ======== gamma: Gamma function. lowergamma: Lower incomplete gamma function. uppergamma: Upper incomplete gamma function. polygamma: Polygamma function. loggamma: Log Gamma function. trigamma: Trigamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Digamma_function .. [2] http://mathworld.wolfram.com/DigammaFunction.html .. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/ """ def _eval_evalf(self, prec): z = self.args[0] nprec = prec_to_dps(prec) return polygamma(0, z).evalf(n=nprec) def fdiff(self, argindex=1): z = self.args[0] return polygamma(0, z).fdiff() def _eval_is_real(self): z = self.args[0] return polygamma(0, z).is_real def _eval_is_positive(self): z = self.args[0] return polygamma(0, z).is_positive def _eval_is_negative(self): z = self.args[0] return polygamma(0, z).is_negative def _eval_aseries(self, n, args0, x, logx): as_polygamma = self.rewrite(polygamma) args0 = [S.Zero,] + args0 return as_polygamma._eval_aseries(n, args0, x, logx) @classmethod def eval(cls, z): return polygamma(0, z) def _eval_expand_func(self, **hints): z = self.args[0] return polygamma(0, z).expand(func=True) def _eval_rewrite_as_harmonic(self, z, **kwargs): return harmonic(z - 1) - S.EulerGamma def _eval_rewrite_as_polygamma(self, z, **kwargs): return polygamma(0, z) def _eval_as_leading_term(self, x, logx=None, cdir=0): z = self.args[0] return polygamma(0, z).as_leading_term(x) class trigamma(Function): r""" The ``trigamma`` function is the second derivative of the ``loggamma`` function .. math:: \psi^{(1)}(z) := \frac{\mathrm{d}^{2}}{\mathrm{d} z^{2}} \log\Gamma(z). In this case, ``trigamma(z) = polygamma(1, z)``. Examples ======== >>> from sympy import trigamma >>> trigamma(0) zoo >>> from sympy import Symbol >>> z = Symbol('z') >>> trigamma(z) polygamma(1, z) To retain ``trigamma`` as it is: >>> trigamma(0, evaluate=False) trigamma(0) >>> trigamma(z, evaluate=False) trigamma(z) See Also ======== gamma: Gamma function. lowergamma: Lower incomplete gamma function. uppergamma: Upper incomplete gamma function. polygamma: Polygamma function. loggamma: Log Gamma function. digamma: Digamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Trigamma_function .. [2] http://mathworld.wolfram.com/TrigammaFunction.html .. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/ """ def _eval_evalf(self, prec): z = self.args[0] nprec = prec_to_dps(prec) return polygamma(1, z).evalf(n=nprec) def fdiff(self, argindex=1): z = self.args[0] return polygamma(1, z).fdiff() def _eval_is_real(self): z = self.args[0] return polygamma(1, z).is_real def _eval_is_positive(self): z = self.args[0] return polygamma(1, z).is_positive def _eval_is_negative(self): z = self.args[0] return polygamma(1, z).is_negative def _eval_aseries(self, n, args0, x, logx): as_polygamma = self.rewrite(polygamma) args0 = [S.One,] + args0 return as_polygamma._eval_aseries(n, args0, x, logx) @classmethod def eval(cls, z): return polygamma(1, z) def _eval_expand_func(self, **hints): z = self.args[0] return polygamma(1, z).expand(func=True) def _eval_rewrite_as_zeta(self, z, **kwargs): return zeta(2, z) def _eval_rewrite_as_polygamma(self, z, **kwargs): return polygamma(1, z) def _eval_rewrite_as_harmonic(self, z, **kwargs): return -harmonic(z - 1, 2) + pi**2 / 6 def _eval_as_leading_term(self, x, logx=None, cdir=0): z = self.args[0] return polygamma(1, z).as_leading_term(x) ############################################################################### ##################### COMPLETE MULTIVARIATE GAMMA FUNCTION #################### ############################################################################### class multigamma(Function): r""" The multivariate gamma function is a generalization of the gamma function .. math:: \Gamma_p(z) = \pi^{p(p-1)/4}\prod_{k=1}^p \Gamma[z + (1 - k)/2]. In a special case, ``multigamma(x, 1) = gamma(x)``. Examples ======== >>> from sympy import S, multigamma >>> from sympy import Symbol >>> x = Symbol('x') >>> p = Symbol('p', positive=True, integer=True) >>> multigamma(x, p) pi**(p*(p - 1)/4)*Product(gamma(-_k/2 + x + 1/2), (_k, 1, p)) Several special values are known: >>> multigamma(1, 1) 1 >>> multigamma(4, 1) 6 >>> multigamma(S(3)/2, 1) sqrt(pi)/2 Writing ``multigamma`` in terms of the ``gamma`` function: >>> multigamma(x, 1) gamma(x) >>> multigamma(x, 2) sqrt(pi)*gamma(x)*gamma(x - 1/2) >>> multigamma(x, 3) pi**(3/2)*gamma(x)*gamma(x - 1)*gamma(x - 1/2) Parameters ========== p : order or dimension of the multivariate gamma function See Also ======== gamma, lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma, beta References ========== .. [1] https://en.wikipedia.org/wiki/Multivariate_gamma_function """ unbranched = True def fdiff(self, argindex=2): from sympy.concrete.summations import Sum if argindex == 2: x, p = self.args k = Dummy("k") return self.func(x, p)*Sum(polygamma(0, x + (1 - k)/2), (k, 1, p)) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, x, p): from sympy.concrete.products import Product if p.is_positive is False or p.is_integer is False: raise ValueError('Order parameter p must be positive integer.') k = Dummy("k") return (pi**(p*(p - 1)/4)*Product(gamma(x + (1 - k)/2), (k, 1, p))).doit() def _eval_conjugate(self): x, p = self.args return self.func(x.conjugate(), p) def _eval_is_real(self): x, p = self.args y = 2*x if y.is_integer and (y <= (p - 1)) is True: return False if intlike(y) and (y <= (p - 1)): return False if y > (p - 1) or y.is_noninteger: return True
d91c10f9e30014147277f43aef12ec045d7c478823a23ea4538d0ba2c04acfa4
from sympy.core import S from sympy.core.function import Function, ArgumentIndexError from sympy.core.symbol import Dummy from sympy.functions.special.gamma_functions import gamma, digamma from sympy.functions.combinatorial.numbers import catalan from sympy.functions.elementary.complexes import conjugate # See mpmath #569 and SymPy #20569 def betainc_mpmath_fix(a, b, x1, x2, reg=0): from mpmath import betainc, mpf if x1 == x2: return mpf(0) else: return betainc(a, b, x1, x2, reg) ############################################################################### ############################ COMPLETE BETA FUNCTION ########################## ############################################################################### class beta(Function): r""" The beta integral is called the Eulerian integral of the first kind by Legendre: .. math:: \mathrm{B}(x,y) \int^{1}_{0} t^{x-1} (1-t)^{y-1} \mathrm{d}t. Explanation =========== The Beta function or Euler's first integral is closely associated with the gamma function. The Beta function is often used in probability theory and mathematical statistics. It satisfies properties like: .. math:: \mathrm{B}(a,1) = \frac{1}{a} \\ \mathrm{B}(a,b) = \mathrm{B}(b,a) \\ \mathrm{B}(a,b) = \frac{\Gamma(a) \Gamma(b)}{\Gamma(a+b)} Therefore for integral values of $a$ and $b$: .. math:: \mathrm{B} = \frac{(a-1)! (b-1)!}{(a+b-1)!} A special case of the Beta function when `x = y` is the Central Beta function. It satisfies properties like: .. math:: \mathrm{B}(x) = 2^{1 - 2x}\mathrm{B}(x, \frac{1}{2}) \mathrm{B}(x) = 2^{1 - 2x} cos(\pi x) \mathrm{B}(\frac{1}{2} - x, x) \mathrm{B}(x) = \int_{0}^{1} \frac{t^x}{(1 + t)^{2x}} dt \mathrm{B}(x) = \frac{2}{x} \prod_{n = 1}^{\infty} \frac{n(n + 2x)}{(n + x)^2} Examples ======== >>> from sympy import I, pi >>> from sympy.abc import x, y The Beta function obeys the mirror symmetry: >>> from sympy import beta, conjugate >>> conjugate(beta(x, y)) beta(conjugate(x), conjugate(y)) Differentiation with respect to both $x$ and $y$ is supported: >>> from sympy import beta, diff >>> diff(beta(x, y), x) (polygamma(0, x) - polygamma(0, x + y))*beta(x, y) >>> diff(beta(x, y), y) (polygamma(0, y) - polygamma(0, x + y))*beta(x, y) >>> diff(beta(x), x) 2*(polygamma(0, x) - polygamma(0, 2*x))*beta(x, x) We can numerically evaluate the Beta function to arbitrary precision for any complex numbers x and y: >>> from sympy import beta >>> beta(pi).evalf(40) 0.02671848900111377452242355235388489324562 >>> beta(1 + I).evalf(20) -0.2112723729365330143 - 0.7655283165378005676*I See Also ======== gamma: Gamma function. uppergamma: Upper incomplete gamma function. lowergamma: Lower incomplete gamma function. polygamma: Polygamma function. loggamma: Log Gamma function. digamma: Digamma function. trigamma: Trigamma function. References ========== .. [1] https://en.wikipedia.org/wiki/Beta_function .. [2] http://mathworld.wolfram.com/BetaFunction.html .. [3] http://dlmf.nist.gov/5.12 """ unbranched = True def fdiff(self, argindex): x, y = self.args if argindex == 1: # Diff wrt x return beta(x, y)*(digamma(x) - digamma(x + y)) elif argindex == 2: # Diff wrt y return beta(x, y)*(digamma(y) - digamma(x + y)) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, x, y=None): if y is None: return beta(x, x) if x.is_Number and y.is_Number: return beta(x, y, evaluate=False).doit() def doit(self, **hints): x = xold = self.args[0] # Deal with unevaluated single argument beta single_argument = len(self.args) == 1 y = yold = self.args[0] if single_argument else self.args[1] if hints.get('deep', True): x = x.doit(**hints) y = y.doit(**hints) if y.is_zero or x.is_zero: return S.ComplexInfinity if y is S.One: return 1/x if x is S.One: return 1/y if y == x + 1: return 1/(x*y*catalan(x)) s = x + y if (s.is_integer and s.is_negative and x.is_integer is False and y.is_integer is False): return S.Zero if x == xold and y == yold and not single_argument: return self return beta(x, y) def _eval_expand_func(self, **hints): x, y = self.args return gamma(x)*gamma(y) / gamma(x + y) def _eval_is_real(self): return self.args[0].is_real and self.args[1].is_real def _eval_conjugate(self): return self.func(self.args[0].conjugate(), self.args[1].conjugate()) def _eval_rewrite_as_gamma(self, x, y, piecewise=True, **kwargs): return self._eval_expand_func(**kwargs) def _eval_rewrite_as_Integral(self, x, y, **kwargs): from sympy.integrals.integrals import Integral t = Dummy('t') return Integral(t**(x - 1)*(1 - t)**(y - 1), (t, 0, 1)) ############################################################################### ########################## INCOMPLETE BETA FUNCTION ########################### ############################################################################### class betainc(Function): r""" The Generalized Incomplete Beta function is defined as .. math:: \mathrm{B}_{(x_1, x_2)}(a, b) = \int_{x_1}^{x_2} t^{a - 1} (1 - t)^{b - 1} dt The Incomplete Beta function is a special case of the Generalized Incomplete Beta function : .. math:: \mathrm{B}_z (a, b) = \mathrm{B}_{(0, z)}(a, b) The Incomplete Beta function satisfies : .. math:: \mathrm{B}_z (a, b) = (-1)^a \mathrm{B}_{\frac{z}{z - 1}} (a, 1 - a - b) The Beta function is a special case of the Incomplete Beta function : .. math:: \mathrm{B}(a, b) = \mathrm{B}_{1}(a, b) Examples ======== >>> from sympy import betainc, symbols, conjugate >>> a, b, x, x1, x2 = symbols('a b x x1 x2') The Generalized Incomplete Beta function is given by: >>> betainc(a, b, x1, x2) betainc(a, b, x1, x2) The Incomplete Beta function can be obtained as follows: >>> betainc(a, b, 0, x) betainc(a, b, 0, x) The Incomplete Beta function obeys the mirror symmetry: >>> conjugate(betainc(a, b, x1, x2)) betainc(conjugate(a), conjugate(b), conjugate(x1), conjugate(x2)) We can numerically evaluate the Incomplete Beta function to arbitrary precision for any complex numbers a, b, x1 and x2: >>> from sympy import betainc, I >>> betainc(2, 3, 4, 5).evalf(10) 56.08333333 >>> betainc(0.75, 1 - 4*I, 0, 2 + 3*I).evalf(25) 0.2241657956955709603655887 + 0.3619619242700451992411724*I The Generalized Incomplete Beta function can be expressed in terms of the Generalized Hypergeometric function. >>> from sympy import hyper >>> betainc(a, b, x1, x2).rewrite(hyper) (-x1**a*hyper((a, 1 - b), (a + 1,), x1) + x2**a*hyper((a, 1 - b), (a + 1,), x2))/a See Also ======== beta: Beta function hyper: Generalized Hypergeometric function References ========== .. [1] https://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function .. [2] https://dlmf.nist.gov/8.17 .. [3] https://functions.wolfram.com/GammaBetaErf/Beta4/ .. [4] https://functions.wolfram.com/GammaBetaErf/BetaRegularized4/02/ """ nargs = 4 unbranched = True def fdiff(self, argindex): a, b, x1, x2 = self.args if argindex == 3: # Diff wrt x1 return -(1 - x1)**(b - 1)*x1**(a - 1) elif argindex == 4: # Diff wrt x2 return (1 - x2)**(b - 1)*x2**(a - 1) else: raise ArgumentIndexError(self, argindex) def _eval_mpmath(self): return betainc_mpmath_fix, self.args def _eval_is_real(self): if all(arg.is_real for arg in self.args): return True def _eval_conjugate(self): return self.func(*map(conjugate, self.args)) def _eval_rewrite_as_Integral(self, a, b, x1, x2, **kwargs): from sympy.integrals.integrals import Integral t = Dummy('t') return Integral(t**(a - 1)*(1 - t)**(b - 1), (t, x1, x2)) def _eval_rewrite_as_hyper(self, a, b, x1, x2, **kwargs): from sympy.functions.special.hyper import hyper return (x2**a * hyper((a, 1 - b), (a + 1,), x2) - x1**a * hyper((a, 1 - b), (a + 1,), x1)) / a ############################################################################### #################### REGULARIZED INCOMPLETE BETA FUNCTION ##################### ############################################################################### class betainc_regularized(Function): r""" The Generalized Regularized Incomplete Beta function is given by .. math:: \mathrm{I}_{(x_1, x_2)}(a, b) = \frac{\mathrm{B}_{(x_1, x_2)}(a, b)}{\mathrm{B}(a, b)} The Regularized Incomplete Beta function is a special case of the Generalized Regularized Incomplete Beta function : .. math:: \mathrm{I}_z (a, b) = \mathrm{I}_{(0, z)}(a, b) The Regularized Incomplete Beta function is the cumulative distribution function of the beta distribution. Examples ======== >>> from sympy import betainc_regularized, symbols, conjugate >>> a, b, x, x1, x2 = symbols('a b x x1 x2') The Generalized Regularized Incomplete Beta function is given by: >>> betainc_regularized(a, b, x1, x2) betainc_regularized(a, b, x1, x2) The Regularized Incomplete Beta function can be obtained as follows: >>> betainc_regularized(a, b, 0, x) betainc_regularized(a, b, 0, x) The Regularized Incomplete Beta function obeys the mirror symmetry: >>> conjugate(betainc_regularized(a, b, x1, x2)) betainc_regularized(conjugate(a), conjugate(b), conjugate(x1), conjugate(x2)) We can numerically evaluate the Regularized Incomplete Beta function to arbitrary precision for any complex numbers a, b, x1 and x2: >>> from sympy import betainc_regularized, pi, E >>> betainc_regularized(1, 2, 0, 0.25).evalf(10) 0.4375000000 >>> betainc_regularized(pi, E, 0, 1).evalf(5) 1.00000 The Generalized Regularized Incomplete Beta function can be expressed in terms of the Generalized Hypergeometric function. >>> from sympy import hyper >>> betainc_regularized(a, b, x1, x2).rewrite(hyper) (-x1**a*hyper((a, 1 - b), (a + 1,), x1) + x2**a*hyper((a, 1 - b), (a + 1,), x2))/(a*beta(a, b)) See Also ======== beta: Beta function hyper: Generalized Hypergeometric function References ========== .. [1] https://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function .. [2] https://dlmf.nist.gov/8.17 .. [3] https://functions.wolfram.com/GammaBetaErf/Beta4/ .. [4] https://functions.wolfram.com/GammaBetaErf/BetaRegularized4/02/ """ nargs = 4 unbranched = True def __new__(cls, a, b, x1, x2): return Function.__new__(cls, a, b, x1, x2) def _eval_mpmath(self): return betainc_mpmath_fix, (*self.args, S(1)) def fdiff(self, argindex): a, b, x1, x2 = self.args if argindex == 3: # Diff wrt x1 return -(1 - x1)**(b - 1)*x1**(a - 1) / beta(a, b) elif argindex == 4: # Diff wrt x2 return (1 - x2)**(b - 1)*x2**(a - 1) / beta(a, b) else: raise ArgumentIndexError(self, argindex) def _eval_is_real(self): if all(arg.is_real for arg in self.args): return True def _eval_conjugate(self): return self.func(*map(conjugate, self.args)) def _eval_rewrite_as_Integral(self, a, b, x1, x2, **kwargs): from sympy.integrals.integrals import Integral t = Dummy('t') integrand = t**(a - 1)*(1 - t)**(b - 1) expr = Integral(integrand, (t, x1, x2)) return expr / Integral(integrand, (t, 0, 1)) def _eval_rewrite_as_hyper(self, a, b, x1, x2, **kwargs): from sympy.functions.special.hyper import hyper expr = (x2**a * hyper((a, 1 - b), (a + 1,), x2) - x1**a * hyper((a, 1 - b), (a + 1,), x1)) / a return expr / beta(a, b)
afe0b477692a7ff9f3a5e41761ecc26ef2fead9fb63b68c7c563771da998d8ee
""" Riemann zeta and related function. """ from sympy.core.add import Add from sympy.core.cache import cacheit from sympy.core.function import ArgumentIndexError, expand_mul, Function from sympy.core.numbers import pi, I, Integer from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.functions.combinatorial.numbers import bernoulli, factorial, genocchi, harmonic from sympy.functions.elementary.complexes import re, unpolarify, Abs, polar_lift from sympy.functions.elementary.exponential import log, exp_polar, exp from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.polys.polytools import Poly ############################################################################### ###################### LERCH TRANSCENDENT ##################################### ############################################################################### class lerchphi(Function): r""" Lerch transcendent (Lerch phi function). Explanation =========== For $\operatorname{Re}(a) > 0$, $|z| < 1$ and $s \in \mathbb{C}$, the Lerch transcendent is defined as .. math :: \Phi(z, s, a) = \sum_{n=0}^\infty \frac{z^n}{(n + a)^s}, where the standard branch of the argument is used for $n + a$, and by analytic continuation for other values of the parameters. A commonly used related function is the Lerch zeta function, defined by .. math:: L(q, s, a) = \Phi(e^{2\pi i q}, s, a). **Analytic Continuation and Branching Behavior** It can be shown that .. math:: \Phi(z, s, a) = z\Phi(z, s, a+1) + a^{-s}. This provides the analytic continuation to $\operatorname{Re}(a) \le 0$. Assume now $\operatorname{Re}(a) > 0$. The integral representation .. math:: \Phi_0(z, s, a) = \int_0^\infty \frac{t^{s-1} e^{-at}}{1 - ze^{-t}} \frac{\mathrm{d}t}{\Gamma(s)} provides an analytic continuation to $\mathbb{C} - [1, \infty)$. Finally, for $x \in (1, \infty)$ we find .. math:: \lim_{\epsilon \to 0^+} \Phi_0(x + i\epsilon, s, a) -\lim_{\epsilon \to 0^+} \Phi_0(x - i\epsilon, s, a) = \frac{2\pi i \log^{s-1}{x}}{x^a \Gamma(s)}, using the standard branch for both $\log{x}$ and $\log{\log{x}}$ (a branch of $\log{\log{x}}$ is needed to evaluate $\log{x}^{s-1}$). This concludes the analytic continuation. The Lerch transcendent is thus branched at $z \in \{0, 1, \infty\}$ and $a \in \mathbb{Z}_{\le 0}$. For fixed $z, a$ outside these branch points, it is an entire function of $s$. Examples ======== The Lerch transcendent is a fairly general function, for this reason it does not automatically evaluate to simpler functions. Use ``expand_func()`` to achieve this. If $z=1$, the Lerch transcendent reduces to the Hurwitz zeta function: >>> from sympy import lerchphi, expand_func >>> from sympy.abc import z, s, a >>> expand_func(lerchphi(1, s, a)) zeta(s, a) More generally, if $z$ is a root of unity, the Lerch transcendent reduces to a sum of Hurwitz zeta functions: >>> expand_func(lerchphi(-1, s, a)) zeta(s, a/2)/2**s - zeta(s, a/2 + 1/2)/2**s If $a=1$, the Lerch transcendent reduces to the polylogarithm: >>> expand_func(lerchphi(z, s, 1)) polylog(s, z)/z More generally, if $a$ is rational, the Lerch transcendent reduces to a sum of polylogarithms: >>> from sympy import S >>> expand_func(lerchphi(z, s, S(1)/2)) 2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) - polylog(s, sqrt(z)*exp_polar(I*pi))/sqrt(z)) >>> expand_func(lerchphi(z, s, S(3)/2)) -2**s/z + 2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) - polylog(s, sqrt(z)*exp_polar(I*pi))/sqrt(z))/z The derivatives with respect to $z$ and $a$ can be computed in closed form: >>> lerchphi(z, s, a).diff(z) (-a*lerchphi(z, s, a) + lerchphi(z, s - 1, a))/z >>> lerchphi(z, s, a).diff(a) -s*lerchphi(z, s + 1, a) See Also ======== polylog, zeta References ========== .. [1] Bateman, H.; Erdelyi, A. (1953), Higher Transcendental Functions, Vol. I, New York: McGraw-Hill. Section 1.11. .. [2] http://dlmf.nist.gov/25.14 .. [3] https://en.wikipedia.org/wiki/Lerch_transcendent """ def _eval_expand_func(self, **hints): z, s, a = self.args if z == 1: return zeta(s, a) if s.is_Integer and s <= 0: t = Dummy('t') p = Poly((t + a)**(-s), t) start = 1/(1 - t) res = S.Zero for c in reversed(p.all_coeffs()): res += c*start start = t*start.diff(t) return res.subs(t, z) if a.is_Rational: # See section 18 of # Kelly B. Roach. Hypergeometric Function Representations. # In: Proceedings of the 1997 International Symposium on Symbolic and # Algebraic Computation, pages 205-211, New York, 1997. ACM. # TODO should something be polarified here? add = S.Zero mul = S.One # First reduce a to the interaval (0, 1] if a > 1: n = floor(a) if n == a: n -= 1 a -= n mul = z**(-n) add = Add(*[-z**(k - n)/(a + k)**s for k in range(n)]) elif a <= 0: n = floor(-a) + 1 a += n mul = z**n add = Add(*[z**(n - 1 - k)/(a - k - 1)**s for k in range(n)]) m, n = S([a.p, a.q]) zet = exp_polar(2*pi*I/n) root = z**(1/n) up_zet = unpolarify(zet) addargs = [] for k in range(n): p = polylog(s, zet**k*root) if isinstance(p, polylog): p = p._eval_expand_func(**hints) addargs.append(p/(up_zet**k*root)**m) return add + mul*n**(s - 1)*Add(*addargs) # TODO use minpoly instead of ad-hoc methods when issue 5888 is fixed if isinstance(z, exp) and (z.args[0]/(pi*I)).is_Rational or z in [-1, I, -I]: # TODO reference? if z == -1: p, q = S([1, 2]) elif z == I: p, q = S([1, 4]) elif z == -I: p, q = S([-1, 4]) else: arg = z.args[0]/(2*pi*I) p, q = S([arg.p, arg.q]) return Add(*[exp(2*pi*I*k*p/q)/q**s*zeta(s, (k + a)/q) for k in range(q)]) return lerchphi(z, s, a) def fdiff(self, argindex=1): z, s, a = self.args if argindex == 3: return -s*lerchphi(z, s + 1, a) elif argindex == 1: return (lerchphi(z, s - 1, a) - a*lerchphi(z, s, a))/z else: raise ArgumentIndexError def _eval_rewrite_helper(self, target): res = self._eval_expand_func() if res.has(target): return res else: return self def _eval_rewrite_as_zeta(self, z, s, a, **kwargs): return self._eval_rewrite_helper(zeta) def _eval_rewrite_as_polylog(self, z, s, a, **kwargs): return self._eval_rewrite_helper(polylog) ############################################################################### ###################### POLYLOGARITHM ########################################## ############################################################################### class polylog(Function): r""" Polylogarithm function. Explanation =========== For $|z| < 1$ and $s \in \mathbb{C}$, the polylogarithm is defined by .. math:: \operatorname{Li}_s(z) = \sum_{n=1}^\infty \frac{z^n}{n^s}, where the standard branch of the argument is used for $n$. It admits an analytic continuation which is branched at $z=1$ (notably not on the sheet of initial definition), $z=0$ and $z=\infty$. The name polylogarithm comes from the fact that for $s=1$, the polylogarithm is related to the ordinary logarithm (see examples), and that .. math:: \operatorname{Li}_{s+1}(z) = \int_0^z \frac{\operatorname{Li}_s(t)}{t} \mathrm{d}t. The polylogarithm is a special case of the Lerch transcendent: .. math:: \operatorname{Li}_{s}(z) = z \Phi(z, s, 1). Examples ======== For $z \in \{0, 1, -1\}$, the polylogarithm is automatically expressed using other functions: >>> from sympy import polylog >>> from sympy.abc import s >>> polylog(s, 0) 0 >>> polylog(s, 1) zeta(s) >>> polylog(s, -1) -dirichlet_eta(s) If $s$ is a negative integer, $0$ or $1$, the polylogarithm can be expressed using elementary functions. This can be done using ``expand_func()``: >>> from sympy import expand_func >>> from sympy.abc import z >>> expand_func(polylog(1, z)) -log(1 - z) >>> expand_func(polylog(0, z)) z/(1 - z) The derivative with respect to $z$ can be computed in closed form: >>> polylog(s, z).diff(z) polylog(s - 1, z)/z The polylogarithm can be expressed in terms of the lerch transcendent: >>> from sympy import lerchphi >>> polylog(s, z).rewrite(lerchphi) z*lerchphi(z, s, 1) See Also ======== zeta, lerchphi """ @classmethod def eval(cls, s, z): if z.is_number: if z is S.One: return zeta(s) elif z is S.NegativeOne: return -dirichlet_eta(s) elif z is S.Zero: return S.Zero elif s == 2: dilogtable = _dilogtable() if z in dilogtable: return dilogtable[z] if z.is_zero: return S.Zero # Make an effort to determine if z is 1 to avoid replacing into # expression with singularity zone = z.equals(S.One) if zone: return zeta(s) elif zone is False: # For s = 0 or -1 use explicit formulas to evaluate, but # automatically expanding polylog(1, z) to -log(1-z) seems # undesirable for summation methods based on hypergeometric # functions if s is S.Zero: return z/(1 - z) elif s is S.NegativeOne: return z/(1 - z)**2 if s.is_zero: return z/(1 - z) # polylog is branched, but not over the unit disk if z.has(exp_polar, polar_lift) and (zone or (Abs(z) <= S.One) == True): return cls(s, unpolarify(z)) def fdiff(self, argindex=1): s, z = self.args if argindex == 2: return polylog(s - 1, z)/z raise ArgumentIndexError def _eval_rewrite_as_lerchphi(self, s, z, **kwargs): return z*lerchphi(z, s, 1) def _eval_expand_func(self, **hints): s, z = self.args if s == 1: return -log(1 - z) if s.is_Integer and s <= 0: u = Dummy('u') start = u/(1 - u) for _ in range(-s): start = u*start.diff(u) return expand_mul(start).subs(u, z) return polylog(s, z) def _eval_is_zero(self): z = self.args[1] if z.is_zero: return True def _eval_nseries(self, x, n, logx, cdir=0): from sympy.series.order import Order nu, z = self.args z0 = z.subs(x, 0) if z0 is S.NaN: z0 = z.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if z0.is_zero: # In case of powers less than 1, number of terms need to be computed # separately to avoid repeated callings of _eval_nseries with wrong n try: _, exp = z.leadterm(x) except (ValueError, NotImplementedError): return self if exp.is_positive: newn = ceiling(n/exp) o = Order(x**n, x) r = z._eval_nseries(x, n, logx, cdir).removeO() if r is S.Zero: return o term = r s = [term] for k in range(2, newn): term *= r s.append(term/k**nu) return Add(*s) + o return super(polylog, self)._eval_nseries(x, n, logx, cdir) ############################################################################### ###################### HURWITZ GENERALIZED ZETA FUNCTION ###################### ############################################################################### class zeta(Function): r""" Hurwitz zeta function (or Riemann zeta function). Explanation =========== For $\operatorname{Re}(a) > 0$ and $\operatorname{Re}(s) > 1$, this function is defined as .. math:: \zeta(s, a) = \sum_{n=0}^\infty \frac{1}{(n + a)^s}, where the standard choice of argument for $n + a$ is used. For fixed $a$ not a nonpositive integer the Hurwitz zeta function admits a meromorphic continuation to all of $\mathbb{C}$; it is an unbranched function with a simple pole at $s = 1$. The Hurwitz zeta function is a special case of the Lerch transcendent: .. math:: \zeta(s, a) = \Phi(1, s, a). This formula defines an analytic continuation for all possible values of $s$ and $a$ (also $\operatorname{Re}(a) < 0$), see the documentation of :class:`lerchphi` for a description of the branching behavior. If no value is passed for $a$ a default value of $a = 1$ is assumed, yielding the Riemann zeta function. Examples ======== For $a = 1$ the Hurwitz zeta function reduces to the famous Riemann zeta function: .. math:: \zeta(s, 1) = \zeta(s) = \sum_{n=1}^\infty \frac{1}{n^s}. >>> from sympy import zeta >>> from sympy.abc import s >>> zeta(s, 1) zeta(s) >>> zeta(s) zeta(s) The Riemann zeta function can also be expressed using the Dirichlet eta function: >>> from sympy import dirichlet_eta >>> zeta(s).rewrite(dirichlet_eta) dirichlet_eta(s)/(1 - 2**(1 - s)) The Riemann zeta function at nonnegative even and negative integer values is related to the Bernoulli numbers and polynomials: >>> zeta(2) pi**2/6 >>> zeta(4) pi**4/90 >>> zeta(0) -1/2 >>> zeta(-1) -1/12 >>> zeta(-4) 0 The specific formulae are: .. math:: \zeta(2n) = -\frac{(2\pi i)^{2n} B_{2n}}{2(2n)!} .. math:: \zeta(-n,a) = -\frac{B_{n+1}(a)}{n+1} No closed-form expressions are known at positive odd integers, but numerical evaluation is possible: >>> zeta(3).n() 1.20205690315959 The derivative of $\zeta(s, a)$ with respect to $a$ can be computed: >>> from sympy.abc import a >>> zeta(s, a).diff(a) -s*zeta(s + 1, a) However the derivative with respect to $s$ has no useful closed form expression: >>> zeta(s, a).diff(s) Derivative(zeta(s, a), s) The Hurwitz zeta function can be expressed in terms of the Lerch transcendent, :class:`~.lerchphi`: >>> from sympy import lerchphi >>> zeta(s, a).rewrite(lerchphi) lerchphi(1, s, a) See Also ======== dirichlet_eta, lerchphi, polylog References ========== .. [1] http://dlmf.nist.gov/25.11 .. [2] https://en.wikipedia.org/wiki/Hurwitz_zeta_function """ @classmethod def eval(cls, s, a=None): if a is S.One: return cls(s) elif s is S.NaN or a is S.NaN: return S.NaN elif s is S.One: return S.ComplexInfinity elif s is S.Infinity: return S.One elif a is S.Infinity: return S.Zero sint = s.is_Integer if a is None: a = S.One if sint and s.is_nonpositive: return bernoulli(1-s, a) / (s-1) elif a is S.One: if sint and s.is_even: return -(2*pi*I)**s * bernoulli(s) / (2*factorial(s)) elif sint and a.is_Integer and a.is_positive: return cls(s) - harmonic(a-1, s) elif a.is_Integer and a.is_nonpositive and \ (s.is_integer is False or s.is_nonpositive is False): return S.NaN def _eval_rewrite_as_bernoulli(self, s, a=1, **kwargs): if a == 1 and s.is_integer and s.is_nonnegative and s.is_even: return -(2*pi*I)**s * bernoulli(s) / (2*factorial(s)) return bernoulli(1-s, a) / (s-1) def _eval_rewrite_as_dirichlet_eta(self, s, a=1, **kwargs): if a != 1: return self s = self.args[0] return dirichlet_eta(s)/(1 - 2**(1 - s)) def _eval_rewrite_as_lerchphi(self, s, a=1, **kwargs): return lerchphi(1, s, a) def _eval_is_finite(self): arg_is_one = (self.args[0] - 1).is_zero if arg_is_one is not None: return not arg_is_one def _eval_expand_func(self, **hints): s = self.args[0] a = self.args[1] if len(self.args) > 1 else S.One if a.is_integer: if a.is_positive: return zeta(s) - harmonic(a-1, s) if a.is_nonpositive and (s.is_integer is False or s.is_nonpositive is False): return S.NaN return self def fdiff(self, argindex=1): if len(self.args) == 2: s, a = self.args else: s, a = self.args + (1,) if argindex == 2: return -s*zeta(s + 1, a) else: raise ArgumentIndexError def _eval_as_leading_term(self, x, logx=None, cdir=0): if len(self.args) == 2: s, a = self.args else: s, a = self.args + (S.One,) try: c, e = a.leadterm(x) except NotImplementedError: return self if e.is_negative and not s.is_positive: raise NotImplementedError return super(zeta, self)._eval_as_leading_term(x, logx, cdir) class dirichlet_eta(Function): r""" Dirichlet eta function. Explanation =========== For $\operatorname{Re}(s) > 0$ and $0 < x \le 1$, this function is defined as .. math:: \eta(s, a) = \sum_{n=0}^\infty \frac{(-1)^n}{(n+a)^s}. It admits a unique analytic continuation to all of $\mathbb{C}$ for any fixed $a$ not a nonpositive integer. It is an entire, unbranched function. It can be expressed using the Hurwitz zeta function as .. math:: \eta(s, a) = \zeta(s,a) - 2^{1-s} \zeta\left(s, \frac{a+1}{2}\right) and using the generalized Genocchi function as .. math:: \eta(s, a) = \frac{G(1-s, a)}{2(s-1)}. In both cases the limiting value of $\log2 - \psi(a) + \psi\left(\frac{a+1}{2}\right)$ is used when $s = 1$. Examples ======== >>> from sympy import dirichlet_eta, zeta >>> from sympy.abc import s >>> dirichlet_eta(s).rewrite(zeta) Piecewise((log(2), Eq(s, 1)), ((1 - 2**(1 - s))*zeta(s), True)) See Also ======== zeta References ========== .. [1] https://en.wikipedia.org/wiki/Dirichlet_eta_function .. [2] Peter Luschny, "An introduction to the Bernoulli function", https://arxiv.org/abs/2009.06743 """ @classmethod def eval(cls, s, a=None): if a is S.One: return cls(s) if a is None: if s == 1: return log(2) z = zeta(s) if not z.has(zeta): return (1 - 2**(1-s)) * z return elif s == 1: from sympy.functions.special.gamma_functions import digamma return log(2) - digamma(a) + digamma((a+1)/2) z1 = zeta(s, a) z2 = zeta(s, (a+1)/2) if not z1.has(zeta) and not z2.has(zeta): return z1 - 2**(1-s) * z2 def _eval_rewrite_as_zeta(self, s, a=1, **kwargs): from sympy.functions.special.gamma_functions import digamma if a == 1: return Piecewise((log(2), Eq(s, 1)), ((1 - 2**(1-s)) * zeta(s), True)) return Piecewise((log(2) - digamma(a) + digamma((a+1)/2), Eq(s, 1)), (zeta(s, a) - 2**(1-s) * zeta(s, (a+1)/2), True)) def _eval_rewrite_as_genocchi(self, s, a=S.One, **kwargs): from sympy.functions.special.gamma_functions import digamma return Piecewise((log(2) - digamma(a) + digamma((a+1)/2), Eq(s, 1)), (genocchi(1-s, a) / (2 * (s-1)), True)) def _eval_evalf(self, prec): if all(i.is_number for i in self.args): return self.rewrite(zeta)._eval_evalf(prec) class riemann_xi(Function): r""" Riemann Xi function. Examples ======== The Riemann Xi function is closely related to the Riemann zeta function. The zeros of Riemann Xi function are precisely the non-trivial zeros of the zeta function. >>> from sympy import riemann_xi, zeta >>> from sympy.abc import s >>> riemann_xi(s).rewrite(zeta) s*(s - 1)*gamma(s/2)*zeta(s)/(2*pi**(s/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Riemann_Xi_function """ @classmethod def eval(cls, s): from sympy.functions.special.gamma_functions import gamma z = zeta(s) if s in (S.Zero, S.One): return S.Half if not isinstance(z, zeta): return s*(s - 1)*gamma(s/2)*z/(2*pi**(s/2)) def _eval_rewrite_as_zeta(self, s, **kwargs): from sympy.functions.special.gamma_functions import gamma return s*(s - 1)*gamma(s/2)*zeta(s)/(2*pi**(s/2)) class stieltjes(Function): r""" Represents Stieltjes constants, $\gamma_{k}$ that occur in Laurent Series expansion of the Riemann zeta function. Examples ======== >>> from sympy import stieltjes >>> from sympy.abc import n, m >>> stieltjes(n) stieltjes(n) The zero'th stieltjes constant: >>> stieltjes(0) EulerGamma >>> stieltjes(0, 1) EulerGamma For generalized stieltjes constants: >>> stieltjes(n, m) stieltjes(n, m) Constants are only defined for integers >= 0: >>> stieltjes(-1) zoo References ========== .. [1] https://en.wikipedia.org/wiki/Stieltjes_constants """ @classmethod def eval(cls, n, a=None): if a is not None: a = sympify(a) if a is S.NaN: return S.NaN if a.is_Integer and a.is_nonpositive: return S.ComplexInfinity if n.is_Number: if n is S.NaN: return S.NaN elif n < 0: return S.ComplexInfinity elif not n.is_Integer: return S.ComplexInfinity elif n is S.Zero and a in [None, 1]: return S.EulerGamma if n.is_extended_negative: return S.ComplexInfinity if n.is_zero and a in [None, 1]: return S.EulerGamma if n.is_integer == False: return S.ComplexInfinity @cacheit def _dilogtable(): return { S.Half: pi**2/12 - log(2)**2/2, Integer(2) : pi**2/4 - I*pi*log(2), -(sqrt(5) - 1)/2 : -pi**2/15 + log((sqrt(5)-1)/2)**2/2, -(sqrt(5) + 1)/2 : -pi**2/10 - log((sqrt(5)+1)/2)**2, (3 - sqrt(5))/2 : pi**2/15 - log((sqrt(5)-1)/2)**2, (sqrt(5) - 1)/2 : pi**2/10 - log((sqrt(5)-1)/2)**2, I : I*S.Catalan - pi**2/48, -I : -I*S.Catalan - pi**2/48, 1 - I : pi**2/16 - I*S.Catalan - pi*I/4*log(2), 1 + I : pi**2/16 + I*S.Catalan + pi*I/4*log(2), (1 - I)/2 : -log(2)**2/8 + pi*I*log(2)/8 + 5*pi**2/96 - I*S.Catalan }
e720c7bf040dd7a612d0bec2d248f7e17237a34abefe4e0e831214468ffd4994
from sympy.core import S, oo, diff from sympy.core.function import Function, ArgumentIndexError from sympy.core.logic import fuzzy_not from sympy.core.relational import Eq from sympy.functions.elementary.complexes import im from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.delta_functions import Heaviside ############################################################################### ############################# SINGULARITY FUNCTION ############################ ############################################################################### class SingularityFunction(Function): r""" Singularity functions are a class of discontinuous functions. Explanation =========== Singularity functions take a variable, an offset, and an exponent as arguments. These functions are represented using Macaulay brackets as: SingularityFunction(x, a, n) := <x - a>^n The singularity function will automatically evaluate to ``Derivative(DiracDelta(x - a), x, -n - 1)`` if ``n < 0`` and ``(x - a)**n*Heaviside(x - a)`` if ``n >= 0``. Examples ======== >>> from sympy import SingularityFunction, diff, Piecewise, DiracDelta, Heaviside, Symbol >>> from sympy.abc import x, a, n >>> SingularityFunction(x, a, n) SingularityFunction(x, a, n) >>> y = Symbol('y', positive=True) >>> n = Symbol('n', nonnegative=True) >>> SingularityFunction(y, -10, n) (y + 10)**n >>> y = Symbol('y', negative=True) >>> SingularityFunction(y, 10, n) 0 >>> SingularityFunction(x, 4, -1).subs(x, 4) oo >>> SingularityFunction(x, 10, -2).subs(x, 10) oo >>> SingularityFunction(4, 1, 5) 243 >>> diff(SingularityFunction(x, 1, 5) + SingularityFunction(x, 1, 4), x) 4*SingularityFunction(x, 1, 3) + 5*SingularityFunction(x, 1, 4) >>> diff(SingularityFunction(x, 4, 0), x, 2) SingularityFunction(x, 4, -2) >>> SingularityFunction(x, 4, 5).rewrite(Piecewise) Piecewise(((x - 4)**5, x > 4), (0, True)) >>> expr = SingularityFunction(x, a, n) >>> y = Symbol('y', positive=True) >>> n = Symbol('n', nonnegative=True) >>> expr.subs({x: y, a: -10, n: n}) (y + 10)**n The methods ``rewrite(DiracDelta)``, ``rewrite(Heaviside)``, and ``rewrite('HeavisideDiracDelta')`` returns the same output. One can use any of these methods according to their choice. >>> expr = SingularityFunction(x, 4, 5) + SingularityFunction(x, -3, -1) - SingularityFunction(x, 0, -2) >>> expr.rewrite(Heaviside) (x - 4)**5*Heaviside(x - 4) + DiracDelta(x + 3) - DiracDelta(x, 1) >>> expr.rewrite(DiracDelta) (x - 4)**5*Heaviside(x - 4) + DiracDelta(x + 3) - DiracDelta(x, 1) >>> expr.rewrite('HeavisideDiracDelta') (x - 4)**5*Heaviside(x - 4) + DiracDelta(x + 3) - DiracDelta(x, 1) See Also ======== DiracDelta, Heaviside References ========== .. [1] https://en.wikipedia.org/wiki/Singularity_function """ is_real = True def fdiff(self, argindex=1): """ Returns the first derivative of a DiracDelta Function. Explanation =========== The difference between ``diff()`` and ``fdiff()`` is: ``diff()`` is the user-level function and ``fdiff()`` is an object method. ``fdiff()`` is a convenience method available in the ``Function`` class. It returns the derivative of the function without considering the chain rule. ``diff(function, x)`` calls ``Function._eval_derivative`` which in turn calls ``fdiff()`` internally to compute the derivative of the function. """ if argindex == 1: x, a, n = self.args if n in (S.Zero, S.NegativeOne): return self.func(x, a, n-1) elif n.is_positive: return n*self.func(x, a, n-1) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, variable, offset, exponent): """ Returns a simplified form or a value of Singularity Function depending on the argument passed by the object. Explanation =========== The ``eval()`` method is automatically called when the ``SingularityFunction`` class is about to be instantiated and it returns either some simplified instance or the unevaluated instance depending on the argument passed. In other words, ``eval()`` method is not needed to be called explicitly, it is being called and evaluated once the object is called. Examples ======== >>> from sympy import SingularityFunction, Symbol, nan >>> from sympy.abc import x, a, n >>> SingularityFunction(x, a, n) SingularityFunction(x, a, n) >>> SingularityFunction(5, 3, 2) 4 >>> SingularityFunction(x, a, nan) nan >>> SingularityFunction(x, 3, 0).subs(x, 3) 1 >>> SingularityFunction(4, 1, 5) 243 >>> x = Symbol('x', positive = True) >>> a = Symbol('a', negative = True) >>> n = Symbol('n', nonnegative = True) >>> SingularityFunction(x, a, n) (-a + x)**n >>> x = Symbol('x', negative = True) >>> a = Symbol('a', positive = True) >>> SingularityFunction(x, a, n) 0 """ x = variable a = offset n = exponent shift = (x - a) if fuzzy_not(im(shift).is_zero): raise ValueError("Singularity Functions are defined only for Real Numbers.") if fuzzy_not(im(n).is_zero): raise ValueError("Singularity Functions are not defined for imaginary exponents.") if shift is S.NaN or n is S.NaN: return S.NaN if (n + 2).is_negative: raise ValueError("Singularity Functions are not defined for exponents less than -2.") if shift.is_extended_negative: return S.Zero if n.is_nonnegative and shift.is_extended_nonnegative: return (x - a)**n if n in (S.NegativeOne, -2): if shift.is_negative or shift.is_extended_positive: return S.Zero if shift.is_zero: return oo def _eval_rewrite_as_Piecewise(self, *args, **kwargs): ''' Converts a Singularity Function expression into its Piecewise form. ''' x, a, n = self.args if n in (S.NegativeOne, S(-2)): return Piecewise((oo, Eq((x - a), 0)), (0, True)) elif n.is_nonnegative: return Piecewise(((x - a)**n, (x - a) > 0), (0, True)) def _eval_rewrite_as_Heaviside(self, *args, **kwargs): ''' Rewrites a Singularity Function expression using Heavisides and DiracDeltas. ''' x, a, n = self.args if n == -2: return diff(Heaviside(x - a), x.free_symbols.pop(), 2) if n == -1: return diff(Heaviside(x - a), x.free_symbols.pop(), 1) if n.is_nonnegative: return (x - a)**n*Heaviside(x - a) def _eval_as_leading_term(self, x, logx=None, cdir=0): z, a, n = self.args shift = (z - a).subs(x, 0) if n < 0: return S.Zero elif n.is_zero and shift.is_zero: return S.Zero if cdir == -1 else S.One elif shift.is_positive: return shift**n return S.Zero def _eval_nseries(self, x, n, logx=None, cdir=0): z, a, n = self.args shift = (z - a).subs(x, 0) if n < 0: return S.Zero elif n.is_zero and shift.is_zero: return S.Zero if cdir == -1 else S.One elif shift.is_positive: return ((z - a)**n)._eval_nseries(x, n, logx=logx, cdir=cdir) return S.Zero _eval_rewrite_as_DiracDelta = _eval_rewrite_as_Heaviside _eval_rewrite_as_HeavisideDiracDelta = _eval_rewrite_as_Heaviside
fc361c9a03f502091475e74ab1f7ce87ccd2264aa85bb80c72168f8952b740f8
from functools import wraps from sympy.core import S from sympy.core.add import Add from sympy.core.cache import cacheit from sympy.core.expr import Expr from sympy.core.function import Function, ArgumentIndexError, _mexpand from sympy.core.logic import fuzzy_or, fuzzy_not from sympy.core.numbers import Rational, pi, I from sympy.core.power import Pow from sympy.core.symbol import Dummy, Wild from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.trigonometric import sin, cos, csc, cot from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.miscellaneous import cbrt, sqrt, root from sympy.functions.elementary.complexes import (Abs, re, im, polar_lift, unpolarify) from sympy.functions.special.gamma_functions import gamma, digamma, uppergamma from sympy.functions.special.hyper import hyper from sympy.polys.orthopolys import spherical_bessel_fn from mpmath import mp, workprec # TODO # o Scorer functions G1 and G2 # o Asymptotic expansions # These are possible, e.g. for fixed order, but since the bessel type # functions are oscillatory they are not actually tractable at # infinity, so this is not particularly useful right now. # o Nicer series expansions. # o More rewriting. # o Add solvers to ode.py (or rather add solvers for the hypergeometric equation). class BesselBase(Function): """ Abstract base class for Bessel-type functions. This class is meant to reduce code duplication. All Bessel-type functions can 1) be differentiated, with the derivatives expressed in terms of similar functions, and 2) be rewritten in terms of other Bessel-type functions. Here, Bessel-type functions are assumed to have one complex parameter. To use this base class, define class attributes ``_a`` and ``_b`` such that ``2*F_n' = -_a*F_{n+1} + b*F_{n-1}``. """ @property def order(self): """ The order of the Bessel-type function. """ return self.args[0] @property def argument(self): """ The argument of the Bessel-type function. """ return self.args[1] @classmethod def eval(cls, nu, z): return def fdiff(self, argindex=2): if argindex != 2: raise ArgumentIndexError(self, argindex) return (self._b/2 * self.__class__(self.order - 1, self.argument) - self._a/2 * self.__class__(self.order + 1, self.argument)) def _eval_conjugate(self): z = self.argument if z.is_extended_negative is False: return self.__class__(self.order.conjugate(), z.conjugate()) def _eval_is_meromorphic(self, x, a): nu, z = self.order, self.argument if nu.has(x): return False if not z._eval_is_meromorphic(x, a): return None z0 = z.subs(x, a) if nu.is_integer: if isinstance(self, (besselj, besseli, hn1, hn2, jn, yn)) or not nu.is_zero: return fuzzy_not(z0.is_infinite) return fuzzy_not(fuzzy_or([z0.is_zero, z0.is_infinite])) def _eval_expand_func(self, **hints): nu, z, f = self.order, self.argument, self.__class__ if nu.is_real: if (nu - 1).is_positive: return (-self._a*self._b*f(nu - 2, z)._eval_expand_func() + 2*self._a*(nu - 1)*f(nu - 1, z)._eval_expand_func()/z) elif (nu + 1).is_negative: return (2*self._b*(nu + 1)*f(nu + 1, z)._eval_expand_func()/z - self._a*self._b*f(nu + 2, z)._eval_expand_func()) return self def _eval_simplify(self, **kwargs): from sympy.simplify.simplify import besselsimp return besselsimp(self) class besselj(BesselBase): r""" Bessel function of the first kind. Explanation =========== The Bessel $J$ function of order $\nu$ is defined to be the function satisfying Bessel's differential equation .. math :: z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2} + z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu^2) w = 0, with Laurent expansion .. math :: J_\nu(z) = z^\nu \left(\frac{1}{\Gamma(\nu + 1) 2^\nu} + O(z^2) \right), if $\nu$ is not a negative integer. If $\nu=-n \in \mathbb{Z}_{<0}$ *is* a negative integer, then the definition is .. math :: J_{-n}(z) = (-1)^n J_n(z). Examples ======== Create a Bessel function object: >>> from sympy import besselj, jn >>> from sympy.abc import z, n >>> b = besselj(n, z) Differentiate it: >>> b.diff(z) besselj(n - 1, z)/2 - besselj(n + 1, z)/2 Rewrite in terms of spherical Bessel functions: >>> b.rewrite(jn) sqrt(2)*sqrt(z)*jn(n - 1/2, z)/sqrt(pi) Access the parameter and argument: >>> b.order n >>> b.argument z See Also ======== bessely, besseli, besselk References ========== .. [1] Abramowitz, Milton; Stegun, Irene A., eds. (1965), "Chapter 9", Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables .. [2] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 .. [3] https://en.wikipedia.org/wiki/Bessel_function .. [4] http://functions.wolfram.com/Bessel-TypeFunctions/BesselJ/ """ _a = S.One _b = S.One @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.One elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive: return S.Zero elif re(nu).is_negative and not (nu.is_integer is True): return S.ComplexInfinity elif nu.is_imaginary: return S.NaN if z in (S.Infinity, S.NegativeInfinity): return S.Zero if z.could_extract_minus_sign(): return (z)**nu*(-z)**(-nu)*besselj(nu, -z) if nu.is_integer: if nu.could_extract_minus_sign(): return S.NegativeOne**(-nu)*besselj(-nu, z) newz = z.extract_multiplicatively(I) if newz: # NOTE we don't want to change the function if z==0 return I**(nu)*besseli(nu, newz) # branch handling: if nu.is_integer: newz = unpolarify(z) if newz != z: return besselj(nu, newz) else: newz, n = z.extract_branch_factor() if n != 0: return exp(2*n*pi*nu*I)*besselj(nu, newz) nnu = unpolarify(nu) if nu != nnu: return besselj(nnu, z) def _eval_rewrite_as_besseli(self, nu, z, **kwargs): return exp(I*pi*nu/2)*besseli(nu, polar_lift(-I)*z) def _eval_rewrite_as_bessely(self, nu, z, **kwargs): if nu.is_integer is False: return csc(pi*nu)*bessely(-nu, z) - cot(pi*nu)*bessely(nu, z) def _eval_rewrite_as_jn(self, nu, z, **kwargs): return sqrt(2*z/pi)*jn(nu - S.Half, self.argument) def _eval_as_leading_term(self, x, logx=None, cdir=0): nu, z = self.args try: arg = z.as_leading_term(x) except NotImplementedError: return self c, e = arg.as_coeff_exponent(x) if e.is_positive: return arg**nu/(2**nu*gamma(nu + 1)) elif e.is_negative: cdir = 1 if cdir == 0 else cdir sign = c*cdir**e if not sign.is_negative: # Refer Abramowitz and Stegun 1965, p. 364 for more information on # asymptotic approximation of besselj function. return sqrt(2)*cos(z - pi*(2*nu + 1)/4)/sqrt(pi*z) return self return super(besselj, self)._eval_as_leading_term(x, logx, cdir) def _eval_is_extended_real(self): nu, z = self.args if nu.is_integer and z.is_extended_real: return True def _eval_nseries(self, x, n, logx, cdir=0): # Refer https://functions.wolfram.com/Bessel-TypeFunctions/BesselJ/06/01/04/01/01/0003/ # for more information on nseries expansion of besselj function. from sympy.series.order import Order nu, z = self.args # In case of powers less than 1, number of terms need to be computed # separately to avoid repeated callings of _eval_nseries with wrong n try: _, exp = z.leadterm(x) except (ValueError, NotImplementedError): return self if exp.is_positive: newn = ceiling(n/exp) o = Order(x**n, x) r = (z/2)._eval_nseries(x, n, logx, cdir).removeO() if r is S.Zero: return o t = (_mexpand(r**2) + o).removeO() term = r**nu/gamma(nu + 1) s = [term] for k in range(1, (newn + 1)//2): term *= -t/(k*(nu + k)) term = (_mexpand(term) + o).removeO() s.append(term) return Add(*s) + o return super(besselj, self)._eval_nseries(x, n, logx, cdir) class bessely(BesselBase): r""" Bessel function of the second kind. Explanation =========== The Bessel $Y$ function of order $\nu$ is defined as .. math :: Y_\nu(z) = \lim_{\mu \to \nu} \frac{J_\mu(z) \cos(\pi \mu) - J_{-\mu}(z)}{\sin(\pi \mu)}, where $J_\mu(z)$ is the Bessel function of the first kind. It is a solution to Bessel's equation, and linearly independent from $J_\nu$. Examples ======== >>> from sympy import bessely, yn >>> from sympy.abc import z, n >>> b = bessely(n, z) >>> b.diff(z) bessely(n - 1, z)/2 - bessely(n + 1, z)/2 >>> b.rewrite(yn) sqrt(2)*sqrt(z)*yn(n - 1/2, z)/sqrt(pi) See Also ======== besselj, besseli, besselk References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselY/ """ _a = S.One _b = S.One @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.NegativeInfinity elif re(nu).is_zero is False: return S.ComplexInfinity elif re(nu).is_zero: return S.NaN if z in (S.Infinity, S.NegativeInfinity): return S.Zero if z == I*S.Infinity: return exp(I*pi*(nu + 1)/2) * S.Infinity if z == I*S.NegativeInfinity: return exp(-I*pi*(nu + 1)/2) * S.Infinity if nu.is_integer: if nu.could_extract_minus_sign(): return S.NegativeOne**(-nu)*bessely(-nu, z) def _eval_rewrite_as_besselj(self, nu, z, **kwargs): if nu.is_integer is False: return csc(pi*nu)*(cos(pi*nu)*besselj(nu, z) - besselj(-nu, z)) def _eval_rewrite_as_besseli(self, nu, z, **kwargs): aj = self._eval_rewrite_as_besselj(*self.args) if aj: return aj.rewrite(besseli) def _eval_rewrite_as_yn(self, nu, z, **kwargs): return sqrt(2*z/pi) * yn(nu - S.Half, self.argument) def _eval_as_leading_term(self, x, logx=None, cdir=0): nu, z = self.args try: arg = z.as_leading_term(x) except NotImplementedError: return self c, e = arg.as_coeff_exponent(x) if e.is_positive: term_one = ((2/pi)*log(z/2)*besselj(nu, z)) term_two = -(z/2)**(-nu)*factorial(nu - 1)/pi if (nu).is_positive else S.Zero term_three = -(z/2)**nu/(pi*factorial(nu))*(digamma(nu + 1) - S.EulerGamma) arg = Add(*[term_one, term_two, term_three]).as_leading_term(x, logx=logx) return arg elif e.is_negative: cdir = 1 if cdir == 0 else cdir sign = c*cdir**e if not sign.is_negative: # Refer Abramowitz and Stegun 1965, p. 364 for more information on # asymptotic approximation of bessely function. return sqrt(2)*(-sin(pi*nu/2 - z + pi/4) + 3*cos(pi*nu/2 - z + pi/4)/(8*z))*sqrt(1/z)/sqrt(pi) return self return super(bessely, self)._eval_as_leading_term(x, logx, cdir) def _eval_is_extended_real(self): nu, z = self.args if nu.is_integer and z.is_positive: return True def _eval_nseries(self, x, n, logx, cdir=0): # Refer https://functions.wolfram.com/Bessel-TypeFunctions/BesselY/06/01/04/01/02/0008/ # for more information on nseries expansion of bessely function. from sympy.series.order import Order nu, z = self.args # In case of powers less than 1, number of terms need to be computed # separately to avoid repeated callings of _eval_nseries with wrong n try: _, exp = z.leadterm(x) except (ValueError, NotImplementedError): return self if exp.is_positive and nu.is_integer: newn = ceiling(n/exp) bn = besselj(nu, z) a = ((2/pi)*log(z/2)*bn)._eval_nseries(x, n, logx, cdir) b, c = [], [] o = Order(x**n, x) r = (z/2)._eval_nseries(x, n, logx, cdir).removeO() if r is S.Zero: return o t = (_mexpand(r**2) + o).removeO() if nu > S.Zero: term = r**(-nu)*factorial(nu - 1)/pi b.append(term) for k in range(1, nu): denom = (nu - k)*k if denom == S.Zero: term *= t/k else: term *= t/denom term = (_mexpand(term) + o).removeO() b.append(term) p = r**nu/(pi*factorial(nu)) term = p*(digamma(nu + 1) - S.EulerGamma) c.append(term) for k in range(1, (newn + 1)//2): p *= -t/(k*(k + nu)) p = (_mexpand(p) + o).removeO() term = p*(digamma(k + nu + 1) + digamma(k + 1)) c.append(term) return a - Add(*b) - Add(*c) # Order term comes from a return super(bessely, self)._eval_nseries(x, n, logx, cdir) class besseli(BesselBase): r""" Modified Bessel function of the first kind. Explanation =========== The Bessel $I$ function is a solution to the modified Bessel equation .. math :: z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2} + z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 + \nu^2)^2 w = 0. It can be defined as .. math :: I_\nu(z) = i^{-\nu} J_\nu(iz), where $J_\nu(z)$ is the Bessel function of the first kind. Examples ======== >>> from sympy import besseli >>> from sympy.abc import z, n >>> besseli(n, z).diff(z) besseli(n - 1, z)/2 + besseli(n + 1, z)/2 See Also ======== besselj, bessely, besselk References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselI/ """ _a = -S.One _b = S.One @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.One elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive: return S.Zero elif re(nu).is_negative and not (nu.is_integer is True): return S.ComplexInfinity elif nu.is_imaginary: return S.NaN if im(z) in (S.Infinity, S.NegativeInfinity): return S.Zero if z is S.Infinity: return S.Infinity if z is S.NegativeInfinity: return (-1)**nu*S.Infinity if z.could_extract_minus_sign(): return (z)**nu*(-z)**(-nu)*besseli(nu, -z) if nu.is_integer: if nu.could_extract_minus_sign(): return besseli(-nu, z) newz = z.extract_multiplicatively(I) if newz: # NOTE we don't want to change the function if z==0 return I**(-nu)*besselj(nu, -newz) # branch handling: if nu.is_integer: newz = unpolarify(z) if newz != z: return besseli(nu, newz) else: newz, n = z.extract_branch_factor() if n != 0: return exp(2*n*pi*nu*I)*besseli(nu, newz) nnu = unpolarify(nu) if nu != nnu: return besseli(nnu, z) def _eval_rewrite_as_besselj(self, nu, z, **kwargs): return exp(-I*pi*nu/2)*besselj(nu, polar_lift(I)*z) def _eval_rewrite_as_bessely(self, nu, z, **kwargs): aj = self._eval_rewrite_as_besselj(*self.args) if aj: return aj.rewrite(bessely) def _eval_rewrite_as_jn(self, nu, z, **kwargs): return self._eval_rewrite_as_besselj(*self.args).rewrite(jn) def _eval_is_extended_real(self): nu, z = self.args if nu.is_integer and z.is_extended_real: return True def _eval_as_leading_term(self, x, logx=None, cdir=0): nu, z = self.args try: arg = z.as_leading_term(x) except NotImplementedError: return self c, e = arg.as_coeff_exponent(x) if e.is_positive: return arg**nu/(2**nu*gamma(nu + 1)) elif e.is_negative: cdir = 1 if cdir == 0 else cdir sign = c*cdir**e if not sign.is_negative: # Refer Abramowitz and Stegun 1965, p. 377 for more information on # asymptotic approximation of besseli function. return exp(z)/sqrt(2*pi*z) return self return super(besseli, self)._eval_as_leading_term(x, logx, cdir) def _eval_nseries(self, x, n, logx, cdir=0): # Refer https://functions.wolfram.com/Bessel-TypeFunctions/BesselI/06/01/04/01/01/0003/ # for more information on nseries expansion of besseli function. from sympy.series.order import Order nu, z = self.args # In case of powers less than 1, number of terms need to be computed # separately to avoid repeated callings of _eval_nseries with wrong n try: _, exp = z.leadterm(x) except (ValueError, NotImplementedError): return self if exp.is_positive: newn = ceiling(n/exp) o = Order(x**n, x) r = (z/2)._eval_nseries(x, n, logx, cdir).removeO() if r is S.Zero: return o t = (_mexpand(r**2) + o).removeO() term = r**nu/gamma(nu + 1) s = [term] for k in range(1, (newn + 1)//2): term *= t/(k*(nu + k)) term = (_mexpand(term) + o).removeO() s.append(term) return Add(*s) + o return super(besseli, self)._eval_nseries(x, n, logx, cdir) class besselk(BesselBase): r""" Modified Bessel function of the second kind. Explanation =========== The Bessel $K$ function of order $\nu$ is defined as .. math :: K_\nu(z) = \lim_{\mu \to \nu} \frac{\pi}{2} \frac{I_{-\mu}(z) -I_\mu(z)}{\sin(\pi \mu)}, where $I_\mu(z)$ is the modified Bessel function of the first kind. It is a solution of the modified Bessel equation, and linearly independent from $Y_\nu$. Examples ======== >>> from sympy import besselk >>> from sympy.abc import z, n >>> besselk(n, z).diff(z) -besselk(n - 1, z)/2 - besselk(n + 1, z)/2 See Also ======== besselj, besseli, bessely References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselK/ """ _a = S.One _b = -S.One @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.Infinity elif re(nu).is_zero is False: return S.ComplexInfinity elif re(nu).is_zero: return S.NaN if z in (S.Infinity, I*S.Infinity, I*S.NegativeInfinity): return S.Zero if nu.is_integer: if nu.could_extract_minus_sign(): return besselk(-nu, z) def _eval_rewrite_as_besseli(self, nu, z, **kwargs): if nu.is_integer is False: return pi*csc(pi*nu)*(besseli(-nu, z) - besseli(nu, z))/2 def _eval_rewrite_as_besselj(self, nu, z, **kwargs): ai = self._eval_rewrite_as_besseli(*self.args) if ai: return ai.rewrite(besselj) def _eval_rewrite_as_bessely(self, nu, z, **kwargs): aj = self._eval_rewrite_as_besselj(*self.args) if aj: return aj.rewrite(bessely) def _eval_rewrite_as_yn(self, nu, z, **kwargs): ay = self._eval_rewrite_as_bessely(*self.args) if ay: return ay.rewrite(yn) def _eval_is_extended_real(self): nu, z = self.args if nu.is_integer and z.is_positive: return True def _eval_as_leading_term(self, x, logx=None, cdir=0): nu, z = self.args try: arg = z.as_leading_term(x) except NotImplementedError: return self _, e = arg.as_coeff_exponent(x) if e.is_positive: term_one = ((-1)**(nu -1)*log(z/2)*besseli(nu, z)) term_two = (z/2)**(-nu)*factorial(nu - 1)/2 if (nu).is_positive else S.Zero term_three = (-1)**nu*(z/2)**nu/(2*factorial(nu))*(digamma(nu + 1) - S.EulerGamma) arg = Add(*[term_one, term_two, term_three]).as_leading_term(x, logx=logx) return arg elif e.is_negative: # Refer Abramowitz and Stegun 1965, p. 378 for more information on # asymptotic approximation of besselk function. return sqrt(pi)*exp(-z)/sqrt(2*z) return super(besselk, self)._eval_as_leading_term(x, logx, cdir) def _eval_nseries(self, x, n, logx, cdir=0): # Refer https://functions.wolfram.com/Bessel-TypeFunctions/BesselK/06/01/04/01/02/0008/ # for more information on nseries expansion of besselk function. from sympy.series.order import Order nu, z = self.args # In case of powers less than 1, number of terms need to be computed # separately to avoid repeated callings of _eval_nseries with wrong n try: _, exp = z.leadterm(x) except (ValueError, NotImplementedError): return self if exp.is_positive and nu.is_integer: newn = ceiling(n/exp) bn = besseli(nu, z) a = ((-1)**(nu - 1)*log(z/2)*bn)._eval_nseries(x, n, logx, cdir) b, c = [], [] o = Order(x**n, x) r = (z/2)._eval_nseries(x, n, logx, cdir).removeO() if r is S.Zero: return o t = (_mexpand(r**2) + o).removeO() if nu > S.Zero: term = r**(-nu)*factorial(nu - 1)/2 b.append(term) for k in range(1, nu): denom = (k - nu)*k if denom == S.Zero: term *= t/k else: term *= t/denom term = (_mexpand(term) + o).removeO() b.append(term) p = r**nu*(-1)**nu/(2*factorial(nu)) term = p*(digamma(nu + 1) - S.EulerGamma) c.append(term) for k in range(1, (newn + 1)//2): p *= t/(k*(k + nu)) p = (_mexpand(p) + o).removeO() term = p*(digamma(k + nu + 1) + digamma(k + 1)) c.append(term) return a + Add(*b) + Add(*c) # Order term comes from a return super(besselk, self)._eval_nseries(x, n, logx, cdir) class hankel1(BesselBase): r""" Hankel function of the first kind. Explanation =========== This function is defined as .. math :: H_\nu^{(1)} = J_\nu(z) + iY_\nu(z), where $J_\nu(z)$ is the Bessel function of the first kind, and $Y_\nu(z)$ is the Bessel function of the second kind. It is a solution to Bessel's equation. Examples ======== >>> from sympy import hankel1 >>> from sympy.abc import z, n >>> hankel1(n, z).diff(z) hankel1(n - 1, z)/2 - hankel1(n + 1, z)/2 See Also ======== hankel2, besselj, bessely References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/HankelH1/ """ _a = S.One _b = S.One def _eval_conjugate(self): z = self.argument if z.is_extended_negative is False: return hankel2(self.order.conjugate(), z.conjugate()) class hankel2(BesselBase): r""" Hankel function of the second kind. Explanation =========== This function is defined as .. math :: H_\nu^{(2)} = J_\nu(z) - iY_\nu(z), where $J_\nu(z)$ is the Bessel function of the first kind, and $Y_\nu(z)$ is the Bessel function of the second kind. It is a solution to Bessel's equation, and linearly independent from $H_\nu^{(1)}$. Examples ======== >>> from sympy import hankel2 >>> from sympy.abc import z, n >>> hankel2(n, z).diff(z) hankel2(n - 1, z)/2 - hankel2(n + 1, z)/2 See Also ======== hankel1, besselj, bessely References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/HankelH2/ """ _a = S.One _b = S.One def _eval_conjugate(self): z = self.argument if z.is_extended_negative is False: return hankel1(self.order.conjugate(), z.conjugate()) def assume_integer_order(fn): @wraps(fn) def g(self, nu, z): if nu.is_integer: return fn(self, nu, z) return g class SphericalBesselBase(BesselBase): """ Base class for spherical Bessel functions. These are thin wrappers around ordinary Bessel functions, since spherical Bessel functions differ from the ordinary ones just by a slight change in order. To use this class, define the ``_eval_evalf()`` and ``_expand()`` methods. """ def _expand(self, **hints): """ Expand self into a polynomial. Nu is guaranteed to be Integer. """ raise NotImplementedError('expansion') def _eval_expand_func(self, **hints): if self.order.is_Integer: return self._expand(**hints) return self def fdiff(self, argindex=2): if argindex != 2: raise ArgumentIndexError(self, argindex) return self.__class__(self.order - 1, self.argument) - \ self * (self.order + 1)/self.argument def _jn(n, z): return (spherical_bessel_fn(n, z)*sin(z) + S.NegativeOne**(n + 1)*spherical_bessel_fn(-n - 1, z)*cos(z)) def _yn(n, z): # (-1)**(n + 1) * _jn(-n - 1, z) return (S.NegativeOne**(n + 1) * spherical_bessel_fn(-n - 1, z)*sin(z) - spherical_bessel_fn(n, z)*cos(z)) class jn(SphericalBesselBase): r""" Spherical Bessel function of the first kind. Explanation =========== This function is a solution to the spherical Bessel equation .. math :: z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2} + 2z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu(\nu + 1)) w = 0. It can be defined as .. math :: j_\nu(z) = \sqrt{\frac{\pi}{2z}} J_{\nu + \frac{1}{2}}(z), where $J_\nu(z)$ is the Bessel function of the first kind. The spherical Bessel functions of integral order are calculated using the formula: .. math:: j_n(z) = f_n(z) \sin{z} + (-1)^{n+1} f_{-n-1}(z) \cos{z}, where the coefficients $f_n(z)$ are available as :func:`sympy.polys.orthopolys.spherical_bessel_fn`. Examples ======== >>> from sympy import Symbol, jn, sin, cos, expand_func, besselj, bessely >>> z = Symbol("z") >>> nu = Symbol("nu", integer=True) >>> print(expand_func(jn(0, z))) sin(z)/z >>> expand_func(jn(1, z)) == sin(z)/z**2 - cos(z)/z True >>> expand_func(jn(3, z)) (-6/z**2 + 15/z**4)*sin(z) + (1/z - 15/z**3)*cos(z) >>> jn(nu, z).rewrite(besselj) sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(nu + 1/2, z)/2 >>> jn(nu, z).rewrite(bessely) (-1)**nu*sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(-nu - 1/2, z)/2 >>> jn(2, 5.2+0.3j).evalf(20) 0.099419756723640344491 - 0.054525080242173562897*I See Also ======== besselj, bessely, besselk, yn References ========== .. [1] http://dlmf.nist.gov/10.47 """ @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.One elif nu.is_integer: if nu.is_positive: return S.Zero else: return S.ComplexInfinity if z in (S.NegativeInfinity, S.Infinity): return S.Zero def _eval_rewrite_as_besselj(self, nu, z, **kwargs): return sqrt(pi/(2*z)) * besselj(nu + S.Half, z) def _eval_rewrite_as_bessely(self, nu, z, **kwargs): return S.NegativeOne**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z) def _eval_rewrite_as_yn(self, nu, z, **kwargs): return S.NegativeOne**(nu) * yn(-nu - 1, z) def _expand(self, **hints): return _jn(self.order, self.argument) def _eval_evalf(self, prec): if self.order.is_Integer: return self.rewrite(besselj)._eval_evalf(prec) class yn(SphericalBesselBase): r""" Spherical Bessel function of the second kind. Explanation =========== This function is another solution to the spherical Bessel equation, and linearly independent from $j_n$. It can be defined as .. math :: y_\nu(z) = \sqrt{\frac{\pi}{2z}} Y_{\nu + \frac{1}{2}}(z), where $Y_\nu(z)$ is the Bessel function of the second kind. For integral orders $n$, $y_n$ is calculated using the formula: .. math:: y_n(z) = (-1)^{n+1} j_{-n-1}(z) Examples ======== >>> from sympy import Symbol, yn, sin, cos, expand_func, besselj, bessely >>> z = Symbol("z") >>> nu = Symbol("nu", integer=True) >>> print(expand_func(yn(0, z))) -cos(z)/z >>> expand_func(yn(1, z)) == -cos(z)/z**2-sin(z)/z True >>> yn(nu, z).rewrite(besselj) (-1)**(nu + 1)*sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(-nu - 1/2, z)/2 >>> yn(nu, z).rewrite(bessely) sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(nu + 1/2, z)/2 >>> yn(2, 5.2+0.3j).evalf(20) 0.18525034196069722536 + 0.014895573969924817587*I See Also ======== besselj, bessely, besselk, jn References ========== .. [1] http://dlmf.nist.gov/10.47 """ @assume_integer_order def _eval_rewrite_as_besselj(self, nu, z, **kwargs): return S.NegativeOne**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z) @assume_integer_order def _eval_rewrite_as_bessely(self, nu, z, **kwargs): return sqrt(pi/(2*z)) * bessely(nu + S.Half, z) def _eval_rewrite_as_jn(self, nu, z, **kwargs): return S.NegativeOne**(nu + 1) * jn(-nu - 1, z) def _expand(self, **hints): return _yn(self.order, self.argument) def _eval_evalf(self, prec): if self.order.is_Integer: return self.rewrite(bessely)._eval_evalf(prec) class SphericalHankelBase(SphericalBesselBase): @assume_integer_order def _eval_rewrite_as_besselj(self, nu, z, **kwargs): # jn +- I*yn # jn as beeselj: sqrt(pi/(2*z)) * besselj(nu + S.Half, z) # yn as besselj: (-1)**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z) hks = self._hankel_kind_sign return sqrt(pi/(2*z))*(besselj(nu + S.Half, z) + hks*I*S.NegativeOne**(nu+1)*besselj(-nu - S.Half, z)) @assume_integer_order def _eval_rewrite_as_bessely(self, nu, z, **kwargs): # jn +- I*yn # jn as bessely: (-1)**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z) # yn as bessely: sqrt(pi/(2*z)) * bessely(nu + S.Half, z) hks = self._hankel_kind_sign return sqrt(pi/(2*z))*(S.NegativeOne**nu*bessely(-nu - S.Half, z) + hks*I*bessely(nu + S.Half, z)) def _eval_rewrite_as_yn(self, nu, z, **kwargs): hks = self._hankel_kind_sign return jn(nu, z).rewrite(yn) + hks*I*yn(nu, z) def _eval_rewrite_as_jn(self, nu, z, **kwargs): hks = self._hankel_kind_sign return jn(nu, z) + hks*I*yn(nu, z).rewrite(jn) def _eval_expand_func(self, **hints): if self.order.is_Integer: return self._expand(**hints) else: nu = self.order z = self.argument hks = self._hankel_kind_sign return jn(nu, z) + hks*I*yn(nu, z) def _expand(self, **hints): n = self.order z = self.argument hks = self._hankel_kind_sign # fully expanded version # return ((fn(n, z) * sin(z) + # (-1)**(n + 1) * fn(-n - 1, z) * cos(z)) + # jn # (hks * I * (-1)**(n + 1) * # (fn(-n - 1, z) * hk * I * sin(z) + # (-1)**(-n) * fn(n, z) * I * cos(z))) # +-I*yn # ) return (_jn(n, z) + hks*I*_yn(n, z)).expand() def _eval_evalf(self, prec): if self.order.is_Integer: return self.rewrite(besselj)._eval_evalf(prec) class hn1(SphericalHankelBase): r""" Spherical Hankel function of the first kind. Explanation =========== This function is defined as .. math:: h_\nu^(1)(z) = j_\nu(z) + i y_\nu(z), where $j_\nu(z)$ and $y_\nu(z)$ are the spherical Bessel function of the first and second kinds. For integral orders $n$, $h_n^(1)$ is calculated using the formula: .. math:: h_n^(1)(z) = j_{n}(z) + i (-1)^{n+1} j_{-n-1}(z) Examples ======== >>> from sympy import Symbol, hn1, hankel1, expand_func, yn, jn >>> z = Symbol("z") >>> nu = Symbol("nu", integer=True) >>> print(expand_func(hn1(nu, z))) jn(nu, z) + I*yn(nu, z) >>> print(expand_func(hn1(0, z))) sin(z)/z - I*cos(z)/z >>> print(expand_func(hn1(1, z))) -I*sin(z)/z - cos(z)/z + sin(z)/z**2 - I*cos(z)/z**2 >>> hn1(nu, z).rewrite(jn) (-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z) >>> hn1(nu, z).rewrite(yn) (-1)**nu*yn(-nu - 1, z) + I*yn(nu, z) >>> hn1(nu, z).rewrite(hankel1) sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel1(nu, z)/2 See Also ======== hn2, jn, yn, hankel1, hankel2 References ========== .. [1] http://dlmf.nist.gov/10.47 """ _hankel_kind_sign = S.One @assume_integer_order def _eval_rewrite_as_hankel1(self, nu, z, **kwargs): return sqrt(pi/(2*z))*hankel1(nu, z) class hn2(SphericalHankelBase): r""" Spherical Hankel function of the second kind. Explanation =========== This function is defined as .. math:: h_\nu^(2)(z) = j_\nu(z) - i y_\nu(z), where $j_\nu(z)$ and $y_\nu(z)$ are the spherical Bessel function of the first and second kinds. For integral orders $n$, $h_n^(2)$ is calculated using the formula: .. math:: h_n^(2)(z) = j_{n} - i (-1)^{n+1} j_{-n-1}(z) Examples ======== >>> from sympy import Symbol, hn2, hankel2, expand_func, jn, yn >>> z = Symbol("z") >>> nu = Symbol("nu", integer=True) >>> print(expand_func(hn2(nu, z))) jn(nu, z) - I*yn(nu, z) >>> print(expand_func(hn2(0, z))) sin(z)/z + I*cos(z)/z >>> print(expand_func(hn2(1, z))) I*sin(z)/z - cos(z)/z + sin(z)/z**2 + I*cos(z)/z**2 >>> hn2(nu, z).rewrite(hankel2) sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel2(nu, z)/2 >>> hn2(nu, z).rewrite(jn) -(-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z) >>> hn2(nu, z).rewrite(yn) (-1)**nu*yn(-nu - 1, z) - I*yn(nu, z) See Also ======== hn1, jn, yn, hankel1, hankel2 References ========== .. [1] http://dlmf.nist.gov/10.47 """ _hankel_kind_sign = -S.One @assume_integer_order def _eval_rewrite_as_hankel2(self, nu, z, **kwargs): return sqrt(pi/(2*z))*hankel2(nu, z) def jn_zeros(n, k, method="sympy", dps=15): """ Zeros of the spherical Bessel function of the first kind. Explanation =========== This returns an array of zeros of $jn$ up to the $k$-th zero. * method = "sympy": uses `mpmath.besseljzero <http://mpmath.org/doc/current/functions/bessel.html#mpmath.besseljzero>`_ * method = "scipy": uses the `SciPy's sph_jn <http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.jn_zeros.html>`_ and `newton <http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html>`_ to find all roots, which is faster than computing the zeros using a general numerical solver, but it requires SciPy and only works with low precision floating point numbers. (The function used with method="sympy" is a recent addition to mpmath; before that a general solver was used.) Examples ======== >>> from sympy import jn_zeros >>> jn_zeros(2, 4, dps=5) [5.7635, 9.095, 12.323, 15.515] See Also ======== jn, yn, besselj, besselk, bessely Parameters ========== n : integer order of Bessel function k : integer number of zeros to return """ from math import pi as math_pi if method == "sympy": from mpmath import besseljzero from mpmath.libmp.libmpf import dps_to_prec prec = dps_to_prec(dps) return [Expr._from_mpmath(besseljzero(S(n + 0.5)._to_mpmath(prec), int(l)), prec) for l in range(1, k + 1)] elif method == "scipy": from scipy.optimize import newton try: from scipy.special import spherical_jn f = lambda x: spherical_jn(n, x) except ImportError: from scipy.special import sph_jn f = lambda x: sph_jn(n, x)[0][-1] else: raise NotImplementedError("Unknown method.") def solver(f, x): if method == "scipy": root = newton(f, x) else: raise NotImplementedError("Unknown method.") return root # we need to approximate the position of the first root: root = n + math_pi # determine the first root exactly: root = solver(f, root) roots = [root] for i in range(k - 1): # estimate the position of the next root using the last root + pi: root = solver(f, root + math_pi) roots.append(root) return roots class AiryBase(Function): """ Abstract base class for Airy functions. This class is meant to reduce code duplication. """ def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_extended_real(self): return self.args[0].is_extended_real def as_real_imag(self, deep=True, **hints): z = self.args[0] zc = z.conjugate() f = self.func u = (f(z)+f(zc))/2 v = I*(f(zc)-f(z))/2 return u, v def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=deep, **hints) return re_part + im_part*I class airyai(AiryBase): r""" The Airy function $\operatorname{Ai}$ of the first kind. Explanation =========== The Airy function $\operatorname{Ai}(z)$ is defined to be the function satisfying Airy's differential equation .. math:: \frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = 0. Equivalently, for real $z$ .. math:: \operatorname{Ai}(z) := \frac{1}{\pi} \int_0^\infty \cos\left(\frac{t^3}{3} + z t\right) \mathrm{d}t. Examples ======== Create an Airy function object: >>> from sympy import airyai >>> from sympy.abc import z >>> airyai(z) airyai(z) Several special values are known: >>> airyai(0) 3**(1/3)/(3*gamma(2/3)) >>> from sympy import oo >>> airyai(oo) 0 >>> airyai(-oo) 0 The Airy function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(airyai(z)) airyai(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(airyai(z), z) airyaiprime(z) >>> diff(airyai(z), z, 2) z*airyai(z) Series expansion is also supported: >>> from sympy import series >>> series(airyai(z), z, 0, 3) 3**(5/6)*gamma(1/3)/(6*pi) - 3**(1/6)*z*gamma(2/3)/(2*pi) + O(z**3) We can numerically evaluate the Airy function to arbitrary precision on the whole complex plane: >>> airyai(-2).evalf(50) 0.22740742820168557599192443603787379946077222541710 Rewrite $\operatorname{Ai}(z)$ in terms of hypergeometric functions: >>> from sympy import hyper >>> airyai(z).rewrite(hyper) -3**(2/3)*z*hyper((), (4/3,), z**3/9)/(3*gamma(1/3)) + 3**(1/3)*hyper((), (2/3,), z**3/9)/(3*gamma(2/3)) See Also ======== airybi: Airy function of the second kind. airyaiprime: Derivative of the Airy function of the first kind. airybiprime: Derivative of the Airy function of the second kind. References ========== .. [1] https://en.wikipedia.org/wiki/Airy_function .. [2] http://dlmf.nist.gov/9 .. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions .. [4] http://mathworld.wolfram.com/AiryFunctions.html """ nargs = 1 unbranched = True @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return S.One / (3**Rational(2, 3) * gamma(Rational(2, 3))) if arg.is_zero: return S.One / (3**Rational(2, 3) * gamma(Rational(2, 3))) def fdiff(self, argindex=1): if argindex == 1: return airyaiprime(self.args[0]) else: raise ArgumentIndexError(self, argindex) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 1: p = previous_terms[-1] return ((cbrt(3)*x)**(-n)*(cbrt(3)*x)**(n + 1)*sin(pi*(n*Rational(2, 3) + Rational(4, 3)))*factorial(n) * gamma(n/3 + Rational(2, 3))/(sin(pi*(n*Rational(2, 3) + Rational(2, 3)))*factorial(n + 1)*gamma(n/3 + Rational(1, 3))) * p) else: return (S.One/(3**Rational(2, 3)*pi) * gamma((n+S.One)/S(3)) * sin(Rational(2, 3)*pi*(n+S.One)) / factorial(n) * (cbrt(3)*x)**n) def _eval_rewrite_as_besselj(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = Pow(-z, Rational(3, 2)) if re(z).is_negative: return ot*sqrt(-z) * (besselj(-ot, tt*a) + besselj(ot, tt*a)) def _eval_rewrite_as_besseli(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = Pow(z, Rational(3, 2)) if re(z).is_positive: return ot*sqrt(z) * (besseli(-ot, tt*a) - besseli(ot, tt*a)) else: return ot*(Pow(a, ot)*besseli(-ot, tt*a) - z*Pow(a, -ot)*besseli(ot, tt*a)) def _eval_rewrite_as_hyper(self, z, **kwargs): pf1 = S.One / (3**Rational(2, 3)*gamma(Rational(2, 3))) pf2 = z / (root(3, 3)*gamma(Rational(1, 3))) return pf1 * hyper([], [Rational(2, 3)], z**3/9) - pf2 * hyper([], [Rational(4, 3)], z**3/9) def _eval_expand_func(self, **hints): arg = self.args[0] symbs = arg.free_symbols if len(symbs) == 1: z = symbs.pop() c = Wild("c", exclude=[z]) d = Wild("d", exclude=[z]) m = Wild("m", exclude=[z]) n = Wild("n", exclude=[z]) M = arg.match(c*(d*z**n)**m) if M is not None: m = M[m] # The transformation is given by 03.05.16.0001.01 # http://functions.wolfram.com/Bessel-TypeFunctions/AiryAi/16/01/01/0001/ if (3*m).is_integer: c = M[c] d = M[d] n = M[n] pf = (d * z**n)**m / (d**m * z**(m*n)) newarg = c * d**m * z**(m*n) return S.Half * ((pf + S.One)*airyai(newarg) - (pf - S.One)/sqrt(3)*airybi(newarg)) class airybi(AiryBase): r""" The Airy function $\operatorname{Bi}$ of the second kind. Explanation =========== The Airy function $\operatorname{Bi}(z)$ is defined to be the function satisfying Airy's differential equation .. math:: \frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = 0. Equivalently, for real $z$ .. math:: \operatorname{Bi}(z) := \frac{1}{\pi} \int_0^\infty \exp\left(-\frac{t^3}{3} + z t\right) + \sin\left(\frac{t^3}{3} + z t\right) \mathrm{d}t. Examples ======== Create an Airy function object: >>> from sympy import airybi >>> from sympy.abc import z >>> airybi(z) airybi(z) Several special values are known: >>> airybi(0) 3**(5/6)/(3*gamma(2/3)) >>> from sympy import oo >>> airybi(oo) oo >>> airybi(-oo) 0 The Airy function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(airybi(z)) airybi(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(airybi(z), z) airybiprime(z) >>> diff(airybi(z), z, 2) z*airybi(z) Series expansion is also supported: >>> from sympy import series >>> series(airybi(z), z, 0, 3) 3**(1/3)*gamma(1/3)/(2*pi) + 3**(2/3)*z*gamma(2/3)/(2*pi) + O(z**3) We can numerically evaluate the Airy function to arbitrary precision on the whole complex plane: >>> airybi(-2).evalf(50) -0.41230258795639848808323405461146104203453483447240 Rewrite $\operatorname{Bi}(z)$ in terms of hypergeometric functions: >>> from sympy import hyper >>> airybi(z).rewrite(hyper) 3**(1/6)*z*hyper((), (4/3,), z**3/9)/gamma(1/3) + 3**(5/6)*hyper((), (2/3,), z**3/9)/(3*gamma(2/3)) See Also ======== airyai: Airy function of the first kind. airyaiprime: Derivative of the Airy function of the first kind. airybiprime: Derivative of the Airy function of the second kind. References ========== .. [1] https://en.wikipedia.org/wiki/Airy_function .. [2] http://dlmf.nist.gov/9 .. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions .. [4] http://mathworld.wolfram.com/AiryFunctions.html """ nargs = 1 unbranched = True @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return S.One / (3**Rational(1, 6) * gamma(Rational(2, 3))) if arg.is_zero: return S.One / (3**Rational(1, 6) * gamma(Rational(2, 3))) def fdiff(self, argindex=1): if argindex == 1: return airybiprime(self.args[0]) else: raise ArgumentIndexError(self, argindex) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 1: p = previous_terms[-1] return (cbrt(3)*x * Abs(sin(Rational(2, 3)*pi*(n + S.One))) * factorial((n - S.One)/S(3)) / ((n + S.One) * Abs(cos(Rational(2, 3)*pi*(n + S.Half))) * factorial((n - 2)/S(3))) * p) else: return (S.One/(root(3, 6)*pi) * gamma((n + S.One)/S(3)) * Abs(sin(Rational(2, 3)*pi*(n + S.One))) / factorial(n) * (cbrt(3)*x)**n) def _eval_rewrite_as_besselj(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = Pow(-z, Rational(3, 2)) if re(z).is_negative: return sqrt(-z/3) * (besselj(-ot, tt*a) - besselj(ot, tt*a)) def _eval_rewrite_as_besseli(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = Pow(z, Rational(3, 2)) if re(z).is_positive: return sqrt(z)/sqrt(3) * (besseli(-ot, tt*a) + besseli(ot, tt*a)) else: b = Pow(a, ot) c = Pow(a, -ot) return sqrt(ot)*(b*besseli(-ot, tt*a) + z*c*besseli(ot, tt*a)) def _eval_rewrite_as_hyper(self, z, **kwargs): pf1 = S.One / (root(3, 6)*gamma(Rational(2, 3))) pf2 = z*root(3, 6) / gamma(Rational(1, 3)) return pf1 * hyper([], [Rational(2, 3)], z**3/9) + pf2 * hyper([], [Rational(4, 3)], z**3/9) def _eval_expand_func(self, **hints): arg = self.args[0] symbs = arg.free_symbols if len(symbs) == 1: z = symbs.pop() c = Wild("c", exclude=[z]) d = Wild("d", exclude=[z]) m = Wild("m", exclude=[z]) n = Wild("n", exclude=[z]) M = arg.match(c*(d*z**n)**m) if M is not None: m = M[m] # The transformation is given by 03.06.16.0001.01 # http://functions.wolfram.com/Bessel-TypeFunctions/AiryBi/16/01/01/0001/ if (3*m).is_integer: c = M[c] d = M[d] n = M[n] pf = (d * z**n)**m / (d**m * z**(m*n)) newarg = c * d**m * z**(m*n) return S.Half * (sqrt(3)*(S.One - pf)*airyai(newarg) + (S.One + pf)*airybi(newarg)) class airyaiprime(AiryBase): r""" The derivative $\operatorname{Ai}^\prime$ of the Airy function of the first kind. Explanation =========== The Airy function $\operatorname{Ai}^\prime(z)$ is defined to be the function .. math:: \operatorname{Ai}^\prime(z) := \frac{\mathrm{d} \operatorname{Ai}(z)}{\mathrm{d} z}. Examples ======== Create an Airy function object: >>> from sympy import airyaiprime >>> from sympy.abc import z >>> airyaiprime(z) airyaiprime(z) Several special values are known: >>> airyaiprime(0) -3**(2/3)/(3*gamma(1/3)) >>> from sympy import oo >>> airyaiprime(oo) 0 The Airy function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(airyaiprime(z)) airyaiprime(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(airyaiprime(z), z) z*airyai(z) >>> diff(airyaiprime(z), z, 2) z*airyaiprime(z) + airyai(z) Series expansion is also supported: >>> from sympy import series >>> series(airyaiprime(z), z, 0, 3) -3**(2/3)/(3*gamma(1/3)) + 3**(1/3)*z**2/(6*gamma(2/3)) + O(z**3) We can numerically evaluate the Airy function to arbitrary precision on the whole complex plane: >>> airyaiprime(-2).evalf(50) 0.61825902074169104140626429133247528291577794512415 Rewrite $\operatorname{Ai}^\prime(z)$ in terms of hypergeometric functions: >>> from sympy import hyper >>> airyaiprime(z).rewrite(hyper) 3**(1/3)*z**2*hyper((), (5/3,), z**3/9)/(6*gamma(2/3)) - 3**(2/3)*hyper((), (1/3,), z**3/9)/(3*gamma(1/3)) See Also ======== airyai: Airy function of the first kind. airybi: Airy function of the second kind. airybiprime: Derivative of the Airy function of the second kind. References ========== .. [1] https://en.wikipedia.org/wiki/Airy_function .. [2] http://dlmf.nist.gov/9 .. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions .. [4] http://mathworld.wolfram.com/AiryFunctions.html """ nargs = 1 unbranched = True @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero if arg.is_zero: return S.NegativeOne / (3**Rational(1, 3) * gamma(Rational(1, 3))) def fdiff(self, argindex=1): if argindex == 1: return self.args[0]*airyai(self.args[0]) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): z = self.args[0]._to_mpmath(prec) with workprec(prec): res = mp.airyai(z, derivative=1) return Expr._from_mpmath(res, prec) def _eval_rewrite_as_besselj(self, z, **kwargs): tt = Rational(2, 3) a = Pow(-z, Rational(3, 2)) if re(z).is_negative: return z/3 * (besselj(-tt, tt*a) - besselj(tt, tt*a)) def _eval_rewrite_as_besseli(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = tt * Pow(z, Rational(3, 2)) if re(z).is_positive: return z/3 * (besseli(tt, a) - besseli(-tt, a)) else: a = Pow(z, Rational(3, 2)) b = Pow(a, tt) c = Pow(a, -tt) return ot * (z**2*c*besseli(tt, tt*a) - b*besseli(-ot, tt*a)) def _eval_rewrite_as_hyper(self, z, **kwargs): pf1 = z**2 / (2*3**Rational(2, 3)*gamma(Rational(2, 3))) pf2 = 1 / (root(3, 3)*gamma(Rational(1, 3))) return pf1 * hyper([], [Rational(5, 3)], z**3/9) - pf2 * hyper([], [Rational(1, 3)], z**3/9) def _eval_expand_func(self, **hints): arg = self.args[0] symbs = arg.free_symbols if len(symbs) == 1: z = symbs.pop() c = Wild("c", exclude=[z]) d = Wild("d", exclude=[z]) m = Wild("m", exclude=[z]) n = Wild("n", exclude=[z]) M = arg.match(c*(d*z**n)**m) if M is not None: m = M[m] # The transformation is in principle # given by 03.07.16.0001.01 but note # that there is an error in this formula. # http://functions.wolfram.com/Bessel-TypeFunctions/AiryAiPrime/16/01/01/0001/ if (3*m).is_integer: c = M[c] d = M[d] n = M[n] pf = (d**m * z**(n*m)) / (d * z**n)**m newarg = c * d**m * z**(n*m) return S.Half * ((pf + S.One)*airyaiprime(newarg) + (pf - S.One)/sqrt(3)*airybiprime(newarg)) class airybiprime(AiryBase): r""" The derivative $\operatorname{Bi}^\prime$ of the Airy function of the first kind. Explanation =========== The Airy function $\operatorname{Bi}^\prime(z)$ is defined to be the function .. math:: \operatorname{Bi}^\prime(z) := \frac{\mathrm{d} \operatorname{Bi}(z)}{\mathrm{d} z}. Examples ======== Create an Airy function object: >>> from sympy import airybiprime >>> from sympy.abc import z >>> airybiprime(z) airybiprime(z) Several special values are known: >>> airybiprime(0) 3**(1/6)/gamma(1/3) >>> from sympy import oo >>> airybiprime(oo) oo >>> airybiprime(-oo) 0 The Airy function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(airybiprime(z)) airybiprime(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(airybiprime(z), z) z*airybi(z) >>> diff(airybiprime(z), z, 2) z*airybiprime(z) + airybi(z) Series expansion is also supported: >>> from sympy import series >>> series(airybiprime(z), z, 0, 3) 3**(1/6)/gamma(1/3) + 3**(5/6)*z**2/(6*gamma(2/3)) + O(z**3) We can numerically evaluate the Airy function to arbitrary precision on the whole complex plane: >>> airybiprime(-2).evalf(50) 0.27879516692116952268509756941098324140300059345163 Rewrite $\operatorname{Bi}^\prime(z)$ in terms of hypergeometric functions: >>> from sympy import hyper >>> airybiprime(z).rewrite(hyper) 3**(5/6)*z**2*hyper((), (5/3,), z**3/9)/(6*gamma(2/3)) + 3**(1/6)*hyper((), (1/3,), z**3/9)/gamma(1/3) See Also ======== airyai: Airy function of the first kind. airybi: Airy function of the second kind. airyaiprime: Derivative of the Airy function of the first kind. References ========== .. [1] https://en.wikipedia.org/wiki/Airy_function .. [2] http://dlmf.nist.gov/9 .. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions .. [4] http://mathworld.wolfram.com/AiryFunctions.html """ nargs = 1 unbranched = True @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return 3**Rational(1, 6) / gamma(Rational(1, 3)) if arg.is_zero: return 3**Rational(1, 6) / gamma(Rational(1, 3)) def fdiff(self, argindex=1): if argindex == 1: return self.args[0]*airybi(self.args[0]) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): z = self.args[0]._to_mpmath(prec) with workprec(prec): res = mp.airybi(z, derivative=1) return Expr._from_mpmath(res, prec) def _eval_rewrite_as_besselj(self, z, **kwargs): tt = Rational(2, 3) a = tt * Pow(-z, Rational(3, 2)) if re(z).is_negative: return -z/sqrt(3) * (besselj(-tt, a) + besselj(tt, a)) def _eval_rewrite_as_besseli(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = tt * Pow(z, Rational(3, 2)) if re(z).is_positive: return z/sqrt(3) * (besseli(-tt, a) + besseli(tt, a)) else: a = Pow(z, Rational(3, 2)) b = Pow(a, tt) c = Pow(a, -tt) return sqrt(ot) * (b*besseli(-tt, tt*a) + z**2*c*besseli(tt, tt*a)) def _eval_rewrite_as_hyper(self, z, **kwargs): pf1 = z**2 / (2*root(3, 6)*gamma(Rational(2, 3))) pf2 = root(3, 6) / gamma(Rational(1, 3)) return pf1 * hyper([], [Rational(5, 3)], z**3/9) + pf2 * hyper([], [Rational(1, 3)], z**3/9) def _eval_expand_func(self, **hints): arg = self.args[0] symbs = arg.free_symbols if len(symbs) == 1: z = symbs.pop() c = Wild("c", exclude=[z]) d = Wild("d", exclude=[z]) m = Wild("m", exclude=[z]) n = Wild("n", exclude=[z]) M = arg.match(c*(d*z**n)**m) if M is not None: m = M[m] # The transformation is in principle # given by 03.08.16.0001.01 but note # that there is an error in this formula. # http://functions.wolfram.com/Bessel-TypeFunctions/AiryBiPrime/16/01/01/0001/ if (3*m).is_integer: c = M[c] d = M[d] n = M[n] pf = (d**m * z**(n*m)) / (d * z**n)**m newarg = c * d**m * z**(n*m) return S.Half * (sqrt(3)*(pf - S.One)*airyaiprime(newarg) + (pf + S.One)*airybiprime(newarg)) class marcumq(Function): r""" The Marcum Q-function. Explanation =========== The Marcum Q-function is defined by the meromorphic continuation of .. math:: Q_m(a, b) = a^{- m + 1} \int_{b}^{\infty} x^{m} e^{- \frac{a^{2}}{2} - \frac{x^{2}}{2}} I_{m - 1}\left(a x\right)\, dx Examples ======== >>> from sympy import marcumq >>> from sympy.abc import m, a, b >>> marcumq(m, a, b) marcumq(m, a, b) Special values: >>> marcumq(m, 0, b) uppergamma(m, b**2/2)/gamma(m) >>> marcumq(0, 0, 0) 0 >>> marcumq(0, a, 0) 1 - exp(-a**2/2) >>> marcumq(1, a, a) 1/2 + exp(-a**2)*besseli(0, a**2)/2 >>> marcumq(2, a, a) 1/2 + exp(-a**2)*besseli(0, a**2)/2 + exp(-a**2)*besseli(1, a**2) Differentiation with respect to $a$ and $b$ is supported: >>> from sympy import diff >>> diff(marcumq(m, a, b), a) a*(-marcumq(m, a, b) + marcumq(m + 1, a, b)) >>> diff(marcumq(m, a, b), b) -a**(1 - m)*b**m*exp(-a**2/2 - b**2/2)*besseli(m - 1, a*b) References ========== .. [1] https://en.wikipedia.org/wiki/Marcum_Q-function .. [2] http://mathworld.wolfram.com/MarcumQ-Function.html """ @classmethod def eval(cls, m, a, b): if a is S.Zero: if m is S.Zero and b is S.Zero: return S.Zero return uppergamma(m, b**2 * S.Half) / gamma(m) if m is S.Zero and b is S.Zero: return 1 - 1 / exp(a**2 * S.Half) if a == b: if m is S.One: return (1 + exp(-a**2) * besseli(0, a**2))*S.Half if m == 2: return S.Half + S.Half * exp(-a**2) * besseli(0, a**2) + exp(-a**2) * besseli(1, a**2) if a.is_zero: if m.is_zero and b.is_zero: return S.Zero return uppergamma(m, b**2*S.Half) / gamma(m) if m.is_zero and b.is_zero: return 1 - 1 / exp(a**2*S.Half) def fdiff(self, argindex=2): m, a, b = self.args if argindex == 2: return a * (-marcumq(m, a, b) + marcumq(1+m, a, b)) elif argindex == 3: return (-b**m / a**(m-1)) * exp(-(a**2 + b**2)/2) * besseli(m-1, a*b) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_Integral(self, m, a, b, **kwargs): from sympy.integrals.integrals import Integral x = kwargs.get('x', Dummy('x')) return a ** (1 - m) * \ Integral(x**m * exp(-(x**2 + a**2)/2) * besseli(m-1, a*x), [x, b, S.Infinity]) def _eval_rewrite_as_Sum(self, m, a, b, **kwargs): from sympy.concrete.summations import Sum k = kwargs.get('k', Dummy('k')) return exp(-(a**2 + b**2) / 2) * Sum((a/b)**k * besseli(k, a*b), [k, 1-m, S.Infinity]) def _eval_rewrite_as_besseli(self, m, a, b, **kwargs): if a == b: if m == 1: return (1 + exp(-a**2) * besseli(0, a**2)) / 2 if m.is_Integer and m >= 2: s = sum([besseli(i, a**2) for i in range(1, m)]) return S.Half + exp(-a**2) * besseli(0, a**2) / 2 + exp(-a**2) * s def _eval_is_zero(self): if all(arg.is_zero for arg in self.args): return True
ee264dd5e851b0ba0f1094a9d5694e4bcf8a45402084e865106d9fb5034598ca
""" This module contains various functions that are special cases of incomplete gamma functions. It should probably be renamed. """ from sympy.core import EulerGamma # Must be imported from core, not core.numbers from sympy.core.add import Add from sympy.core.cache import cacheit from sympy.core.function import Function, ArgumentIndexError, expand_mul from sympy.core.numbers import I, pi, Rational from sympy.core.relational import is_eq from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial, factorial2, RisingFactorial from sympy.functions.elementary.complexes import polar_lift, re, unpolarify from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.miscellaneous import sqrt, root from sympy.functions.elementary.exponential import exp, log, exp_polar from sympy.functions.elementary.hyperbolic import cosh, sinh from sympy.functions.elementary.trigonometric import cos, sin, sinc from sympy.functions.special.hyper import hyper, meijerg # TODO series expansions # TODO see the "Note:" in Ei # Helper function def real_to_real_as_real_imag(self, deep=True, **hints): if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: x, y = self.args[0].expand(deep, **hints).as_real_imag() else: x, y = self.args[0].as_real_imag() re = (self.func(x + I*y) + self.func(x - I*y))/2 im = (self.func(x + I*y) - self.func(x - I*y))/(2*I) return (re, im) ############################################################################### ################################ ERROR FUNCTION ############################### ############################################################################### class erf(Function): r""" The Gauss error function. Explanation =========== This function is defined as: .. math :: \mathrm{erf}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{-t^2} \mathrm{d}t. Examples ======== >>> from sympy import I, oo, erf >>> from sympy.abc import z Several special values are known: >>> erf(0) 0 >>> erf(oo) 1 >>> erf(-oo) -1 >>> erf(I*oo) oo*I >>> erf(-I*oo) -oo*I In general one can pull out factors of -1 and $I$ from the argument: >>> erf(-z) -erf(z) The error function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(erf(z)) erf(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(erf(z), z) 2*exp(-z**2)/sqrt(pi) We can numerically evaluate the error function to arbitrary precision on the whole complex plane: >>> erf(4).evalf(30) 0.999999984582742099719981147840 >>> erf(-4*I).evalf(30) -1296959.73071763923152794095062*I See Also ======== erfc: Complementary error function. erfi: Imaginary error function. erf2: Two-argument error function. erfinv: Inverse error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function .. [2] http://dlmf.nist.gov/7 .. [3] http://mathworld.wolfram.com/Erf.html .. [4] http://functions.wolfram.com/GammaBetaErf/Erf """ unbranched = True def fdiff(self, argindex=1): if argindex == 1: return 2*exp(-self.args[0]**2)/sqrt(pi) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return erfinv @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.One elif arg is S.NegativeInfinity: return S.NegativeOne elif arg.is_zero: return S.Zero if isinstance(arg, erfinv): return arg.args[0] if isinstance(arg, erfcinv): return S.One - arg.args[0] if arg.is_zero: return S.Zero # Only happens with unevaluated erf2inv if isinstance(arg, erf2inv) and arg.args[0].is_zero: return arg.args[1] # Try to pull out factors of I t = arg.extract_multiplicatively(I) if t in (S.Infinity, S.NegativeInfinity): return arg # Try to pull out factors of -1 if arg.could_extract_minus_sign(): return -cls(-arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) k = floor((n - 1)/S(2)) if len(previous_terms) > 2: return -previous_terms[-2] * x**2 * (n - 2)/(n*k) else: return 2*S.NegativeOne**k * x**n/(n*factorial(k)*sqrt(pi)) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_real(self): return self.args[0].is_extended_real def _eval_is_finite(self): if self.args[0].is_finite: return True else: return self.args[0].is_extended_real def _eval_is_zero(self): return self.args[0].is_zero def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return sqrt(z**2)/z*(S.One - uppergamma(S.Half, z**2)/sqrt(pi)) def _eval_rewrite_as_fresnels(self, z, **kwargs): arg = (S.One - I)*z/sqrt(pi) return (S.One + I)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_fresnelc(self, z, **kwargs): arg = (S.One - I)*z/sqrt(pi) return (S.One + I)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_meijerg(self, z, **kwargs): return z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2) def _eval_rewrite_as_hyper(self, z, **kwargs): return 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], -z**2) def _eval_rewrite_as_expint(self, z, **kwargs): return sqrt(z**2)/z - z*expint(S.Half, z**2)/sqrt(pi) def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): from sympy.series.limits import limit if limitvar: lim = limit(z, limitvar, S.Infinity) if lim is S.NegativeInfinity: return S.NegativeOne + _erfs(-z)*exp(-z**2) return S.One - _erfs(z)*exp(-z**2) def _eval_rewrite_as_erfc(self, z, **kwargs): return S.One - erfc(z) def _eval_rewrite_as_erfi(self, z, **kwargs): return -I*erfi(I*z) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.ComplexInfinity: arg0 = arg.limit(x, 0, dir='-' if cdir == -1 else '+') if x in arg.free_symbols and arg0.is_zero: return 2*arg/sqrt(pi) else: return self.func(arg0) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] if point in [S.Infinity, S.NegativeInfinity]: z = self.args[0] try: _, ex = z.leadterm(x) except (ValueError, NotImplementedError): return self ex = -ex # as x->1/x for aseries if ex.is_positive: newn = ceiling(n/ex) s = [S.NegativeOne**k * factorial2(2*k - 1) / (z**(2*k + 1) * 2**k) for k in range(newn)] + [Order(1/z**newn, x)] return S.One - (exp(-z**2)/sqrt(pi)) * Add(*s) return super(erf, self)._eval_aseries(n, args0, x, logx) as_real_imag = real_to_real_as_real_imag class erfc(Function): r""" Complementary Error Function. Explanation =========== The function is defined as: .. math :: \mathrm{erfc}(x) = \frac{2}{\sqrt{\pi}} \int_x^\infty e^{-t^2} \mathrm{d}t Examples ======== >>> from sympy import I, oo, erfc >>> from sympy.abc import z Several special values are known: >>> erfc(0) 1 >>> erfc(oo) 0 >>> erfc(-oo) 2 >>> erfc(I*oo) -oo*I >>> erfc(-I*oo) oo*I The error function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(erfc(z)) erfc(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(erfc(z), z) -2*exp(-z**2)/sqrt(pi) It also follows >>> erfc(-z) 2 - erfc(z) We can numerically evaluate the complementary error function to arbitrary precision on the whole complex plane: >>> erfc(4).evalf(30) 0.0000000154172579002800188521596734869 >>> erfc(4*I).evalf(30) 1.0 - 1296959.73071763923152794095062*I See Also ======== erf: Gaussian error function. erfi: Imaginary error function. erf2: Two-argument error function. erfinv: Inverse error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function .. [2] http://dlmf.nist.gov/7 .. [3] http://mathworld.wolfram.com/Erfc.html .. [4] http://functions.wolfram.com/GammaBetaErf/Erfc """ unbranched = True def fdiff(self, argindex=1): if argindex == 1: return -2*exp(-self.args[0]**2)/sqrt(pi) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return erfcinv @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg.is_zero: return S.One if isinstance(arg, erfinv): return S.One - arg.args[0] if isinstance(arg, erfcinv): return arg.args[0] if arg.is_zero: return S.One # Try to pull out factors of I t = arg.extract_multiplicatively(I) if t in (S.Infinity, S.NegativeInfinity): return -arg # Try to pull out factors of -1 if arg.could_extract_minus_sign(): return 2 - cls(-arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.One elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) k = floor((n - 1)/S(2)) if len(previous_terms) > 2: return -previous_terms[-2] * x**2 * (n - 2)/(n*k) else: return -2*S.NegativeOne**k * x**n/(n*factorial(k)*sqrt(pi)) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_real(self): return self.args[0].is_extended_real def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return self.rewrite(erf).rewrite("tractable", deep=True, limitvar=limitvar) def _eval_rewrite_as_erf(self, z, **kwargs): return S.One - erf(z) def _eval_rewrite_as_erfi(self, z, **kwargs): return S.One + I*erfi(I*z) def _eval_rewrite_as_fresnels(self, z, **kwargs): arg = (S.One - I)*z/sqrt(pi) return S.One - (S.One + I)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_fresnelc(self, z, **kwargs): arg = (S.One-I)*z/sqrt(pi) return S.One - (S.One + I)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_meijerg(self, z, **kwargs): return S.One - z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2) def _eval_rewrite_as_hyper(self, z, **kwargs): return S.One - 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], -z**2) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return S.One - sqrt(z**2)/z*(S.One - uppergamma(S.Half, z**2)/sqrt(pi)) def _eval_rewrite_as_expint(self, z, **kwargs): return S.One - sqrt(z**2)/z + z*expint(S.Half, z**2)/sqrt(pi) def _eval_expand_func(self, **hints): return self.rewrite(erf) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.ComplexInfinity: arg0 = arg.limit(x, 0, dir='-' if cdir == -1 else '+') if arg0.is_zero: return S.One else: return self.func(arg0) as_real_imag = real_to_real_as_real_imag def _eval_aseries(self, n, args0, x, logx): return S.One - erf(*self.args)._eval_aseries(n, args0, x, logx) class erfi(Function): r""" Imaginary error function. Explanation =========== The function erfi is defined as: .. math :: \mathrm{erfi}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{t^2} \mathrm{d}t Examples ======== >>> from sympy import I, oo, erfi >>> from sympy.abc import z Several special values are known: >>> erfi(0) 0 >>> erfi(oo) oo >>> erfi(-oo) -oo >>> erfi(I*oo) I >>> erfi(-I*oo) -I In general one can pull out factors of -1 and $I$ from the argument: >>> erfi(-z) -erfi(z) >>> from sympy import conjugate >>> conjugate(erfi(z)) erfi(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(erfi(z), z) 2*exp(z**2)/sqrt(pi) We can numerically evaluate the imaginary error function to arbitrary precision on the whole complex plane: >>> erfi(2).evalf(30) 18.5648024145755525987042919132 >>> erfi(-2*I).evalf(30) -0.995322265018952734162069256367*I See Also ======== erf: Gaussian error function. erfc: Complementary error function. erf2: Two-argument error function. erfinv: Inverse error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function .. [2] http://mathworld.wolfram.com/Erfi.html .. [3] http://functions.wolfram.com/GammaBetaErf/Erfi """ unbranched = True def fdiff(self, argindex=1): if argindex == 1: return 2*exp(self.args[0]**2)/sqrt(pi) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, z): if z.is_Number: if z is S.NaN: return S.NaN elif z.is_zero: return S.Zero elif z is S.Infinity: return S.Infinity if z.is_zero: return S.Zero # Try to pull out factors of -1 if z.could_extract_minus_sign(): return -cls(-z) # Try to pull out factors of I nz = z.extract_multiplicatively(I) if nz is not None: if nz is S.Infinity: return I if isinstance(nz, erfinv): return I*nz.args[0] if isinstance(nz, erfcinv): return I*(S.One - nz.args[0]) # Only happens with unevaluated erf2inv if isinstance(nz, erf2inv) and nz.args[0].is_zero: return I*nz.args[1] @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) k = floor((n - 1)/S(2)) if len(previous_terms) > 2: return previous_terms[-2] * x**2 * (n - 2)/(n*k) else: return 2 * x**n/(n*factorial(k)*sqrt(pi)) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_extended_real(self): return self.args[0].is_extended_real def _eval_is_zero(self): return self.args[0].is_zero def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return self.rewrite(erf).rewrite("tractable", deep=True, limitvar=limitvar) def _eval_rewrite_as_erf(self, z, **kwargs): return -I*erf(I*z) def _eval_rewrite_as_erfc(self, z, **kwargs): return I*erfc(I*z) - I def _eval_rewrite_as_fresnels(self, z, **kwargs): arg = (S.One + I)*z/sqrt(pi) return (S.One - I)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_fresnelc(self, z, **kwargs): arg = (S.One + I)*z/sqrt(pi) return (S.One - I)*(fresnelc(arg) - I*fresnels(arg)) def _eval_rewrite_as_meijerg(self, z, **kwargs): return z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], -z**2) def _eval_rewrite_as_hyper(self, z, **kwargs): return 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], z**2) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return sqrt(-z**2)/z*(uppergamma(S.Half, -z**2)/sqrt(pi) - S.One) def _eval_rewrite_as_expint(self, z, **kwargs): return sqrt(-z**2)/z - z*expint(S.Half, -z**2)/sqrt(pi) def _eval_expand_func(self, **hints): return self.rewrite(erf) as_real_imag = real_to_real_as_real_imag def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if x in arg.free_symbols and arg0.is_zero: return 2*arg/sqrt(pi) elif arg0.is_finite: return self.func(arg0) return self.func(arg) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] if point is S.Infinity: z = self.args[0] s = [factorial2(2*k - 1) / (2**k * z**(2*k + 1)) for k in range(n)] + [Order(1/z**n, x)] return -I + (exp(z**2)/sqrt(pi)) * Add(*s) return super(erfi, self)._eval_aseries(n, args0, x, logx) class erf2(Function): r""" Two-argument error function. Explanation =========== This function is defined as: .. math :: \mathrm{erf2}(x, y) = \frac{2}{\sqrt{\pi}} \int_x^y e^{-t^2} \mathrm{d}t Examples ======== >>> from sympy import oo, erf2 >>> from sympy.abc import x, y Several special values are known: >>> erf2(0, 0) 0 >>> erf2(x, x) 0 >>> erf2(x, oo) 1 - erf(x) >>> erf2(x, -oo) -erf(x) - 1 >>> erf2(oo, y) erf(y) - 1 >>> erf2(-oo, y) erf(y) + 1 In general one can pull out factors of -1: >>> erf2(-x, -y) -erf2(x, y) The error function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(erf2(x, y)) erf2(conjugate(x), conjugate(y)) Differentiation with respect to $x$, $y$ is supported: >>> from sympy import diff >>> diff(erf2(x, y), x) -2*exp(-x**2)/sqrt(pi) >>> diff(erf2(x, y), y) 2*exp(-y**2)/sqrt(pi) See Also ======== erf: Gaussian error function. erfc: Complementary error function. erfi: Imaginary error function. erfinv: Inverse error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] http://functions.wolfram.com/GammaBetaErf/Erf2/ """ def fdiff(self, argindex): x, y = self.args if argindex == 1: return -2*exp(-x**2)/sqrt(pi) elif argindex == 2: return 2*exp(-y**2)/sqrt(pi) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, x, y): chk = (S.Infinity, S.NegativeInfinity, S.Zero) if x is S.NaN or y is S.NaN: return S.NaN elif x == y: return S.Zero elif x in chk or y in chk: return erf(y) - erf(x) if isinstance(y, erf2inv) and y.args[0] == x: return y.args[1] if x.is_zero or y.is_zero or x.is_extended_real and x.is_infinite or \ y.is_extended_real and y.is_infinite: return erf(y) - erf(x) #Try to pull out -1 factor sign_x = x.could_extract_minus_sign() sign_y = y.could_extract_minus_sign() if (sign_x and sign_y): return -cls(-x, -y) elif (sign_x or sign_y): return erf(y)-erf(x) def _eval_conjugate(self): return self.func(self.args[0].conjugate(), self.args[1].conjugate()) def _eval_is_extended_real(self): return self.args[0].is_extended_real and self.args[1].is_extended_real def _eval_rewrite_as_erf(self, x, y, **kwargs): return erf(y) - erf(x) def _eval_rewrite_as_erfc(self, x, y, **kwargs): return erfc(x) - erfc(y) def _eval_rewrite_as_erfi(self, x, y, **kwargs): return I*(erfi(I*x)-erfi(I*y)) def _eval_rewrite_as_fresnels(self, x, y, **kwargs): return erf(y).rewrite(fresnels) - erf(x).rewrite(fresnels) def _eval_rewrite_as_fresnelc(self, x, y, **kwargs): return erf(y).rewrite(fresnelc) - erf(x).rewrite(fresnelc) def _eval_rewrite_as_meijerg(self, x, y, **kwargs): return erf(y).rewrite(meijerg) - erf(x).rewrite(meijerg) def _eval_rewrite_as_hyper(self, x, y, **kwargs): return erf(y).rewrite(hyper) - erf(x).rewrite(hyper) def _eval_rewrite_as_uppergamma(self, x, y, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return (sqrt(y**2)/y*(S.One - uppergamma(S.Half, y**2)/sqrt(pi)) - sqrt(x**2)/x*(S.One - uppergamma(S.Half, x**2)/sqrt(pi))) def _eval_rewrite_as_expint(self, x, y, **kwargs): return erf(y).rewrite(expint) - erf(x).rewrite(expint) def _eval_expand_func(self, **hints): return self.rewrite(erf) def _eval_is_zero(self): return is_eq(*self.args) class erfinv(Function): r""" Inverse Error Function. The erfinv function is defined as: .. math :: \mathrm{erf}(x) = y \quad \Rightarrow \quad \mathrm{erfinv}(y) = x Examples ======== >>> from sympy import erfinv >>> from sympy.abc import x Several special values are known: >>> erfinv(0) 0 >>> erfinv(1) oo Differentiation with respect to $x$ is supported: >>> from sympy import diff >>> diff(erfinv(x), x) sqrt(pi)*exp(erfinv(x)**2)/2 We can numerically evaluate the inverse error function to arbitrary precision on [-1, 1]: >>> erfinv(0.2).evalf(30) 0.179143454621291692285822705344 See Also ======== erf: Gaussian error function. erfc: Complementary error function. erfi: Imaginary error function. erf2: Two-argument error function. erfcinv: Inverse Complementary error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function#Inverse_functions .. [2] http://functions.wolfram.com/GammaBetaErf/InverseErf/ """ def fdiff(self, argindex =1): if argindex == 1: return sqrt(pi)*exp(self.func(self.args[0])**2)*S.Half else : raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return erf @classmethod def eval(cls, z): if z is S.NaN: return S.NaN elif z is S.NegativeOne: return S.NegativeInfinity elif z.is_zero: return S.Zero elif z is S.One: return S.Infinity if isinstance(z, erf) and z.args[0].is_extended_real: return z.args[0] if z.is_zero: return S.Zero # Try to pull out factors of -1 nz = z.extract_multiplicatively(-1) if nz is not None and (isinstance(nz, erf) and (nz.args[0]).is_extended_real): return -nz.args[0] def _eval_rewrite_as_erfcinv(self, z, **kwargs): return erfcinv(1-z) def _eval_is_zero(self): return self.args[0].is_zero class erfcinv (Function): r""" Inverse Complementary Error Function. The erfcinv function is defined as: .. math :: \mathrm{erfc}(x) = y \quad \Rightarrow \quad \mathrm{erfcinv}(y) = x Examples ======== >>> from sympy import erfcinv >>> from sympy.abc import x Several special values are known: >>> erfcinv(1) 0 >>> erfcinv(0) oo Differentiation with respect to $x$ is supported: >>> from sympy import diff >>> diff(erfcinv(x), x) -sqrt(pi)*exp(erfcinv(x)**2)/2 See Also ======== erf: Gaussian error function. erfc: Complementary error function. erfi: Imaginary error function. erf2: Two-argument error function. erfinv: Inverse error function. erf2inv: Inverse two-argument error function. References ========== .. [1] https://en.wikipedia.org/wiki/Error_function#Inverse_functions .. [2] http://functions.wolfram.com/GammaBetaErf/InverseErfc/ """ def fdiff(self, argindex =1): if argindex == 1: return -sqrt(pi)*exp(self.func(self.args[0])**2)*S.Half else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return erfc @classmethod def eval(cls, z): if z is S.NaN: return S.NaN elif z.is_zero: return S.Infinity elif z is S.One: return S.Zero elif z == 2: return S.NegativeInfinity if z.is_zero: return S.Infinity def _eval_rewrite_as_erfinv(self, z, **kwargs): return erfinv(1-z) def _eval_is_zero(self): return (self.args[0] - 1).is_zero def _eval_is_infinite(self): return self.args[0].is_zero class erf2inv(Function): r""" Two-argument Inverse error function. The erf2inv function is defined as: .. math :: \mathrm{erf2}(x, w) = y \quad \Rightarrow \quad \mathrm{erf2inv}(x, y) = w Examples ======== >>> from sympy import erf2inv, oo >>> from sympy.abc import x, y Several special values are known: >>> erf2inv(0, 0) 0 >>> erf2inv(1, 0) 1 >>> erf2inv(0, 1) oo >>> erf2inv(0, y) erfinv(y) >>> erf2inv(oo, y) erfcinv(-y) Differentiation with respect to $x$ and $y$ is supported: >>> from sympy import diff >>> diff(erf2inv(x, y), x) exp(-x**2 + erf2inv(x, y)**2) >>> diff(erf2inv(x, y), y) sqrt(pi)*exp(erf2inv(x, y)**2)/2 See Also ======== erf: Gaussian error function. erfc: Complementary error function. erfi: Imaginary error function. erf2: Two-argument error function. erfinv: Inverse error function. erfcinv: Inverse complementary error function. References ========== .. [1] http://functions.wolfram.com/GammaBetaErf/InverseErf2/ """ def fdiff(self, argindex): x, y = self.args if argindex == 1: return exp(self.func(x,y)**2-x**2) elif argindex == 2: return sqrt(pi)*S.Half*exp(self.func(x,y)**2) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, x, y): if x is S.NaN or y is S.NaN: return S.NaN elif x.is_zero and y.is_zero: return S.Zero elif x.is_zero and y is S.One: return S.Infinity elif x is S.One and y.is_zero: return S.One elif x.is_zero: return erfinv(y) elif x is S.Infinity: return erfcinv(-y) elif y.is_zero: return x elif y is S.Infinity: return erfinv(x) if x.is_zero: if y.is_zero: return S.Zero else: return erfinv(y) if y.is_zero: return x def _eval_is_zero(self): x, y = self.args if x.is_zero and y.is_zero: return True ############################################################################### #################### EXPONENTIAL INTEGRALS #################################### ############################################################################### class Ei(Function): r""" The classical exponential integral. Explanation =========== For use in SymPy, this function is defined as .. math:: \operatorname{Ei}(x) = \sum_{n=1}^\infty \frac{x^n}{n\, n!} + \log(x) + \gamma, where $\gamma$ is the Euler-Mascheroni constant. If $x$ is a polar number, this defines an analytic function on the Riemann surface of the logarithm. Otherwise this defines an analytic function in the cut plane $\mathbb{C} \setminus (-\infty, 0]$. **Background** The name exponential integral comes from the following statement: .. math:: \operatorname{Ei}(x) = \int_{-\infty}^x \frac{e^t}{t} \mathrm{d}t If the integral is interpreted as a Cauchy principal value, this statement holds for $x > 0$ and $\operatorname{Ei}(x)$ as defined above. Examples ======== >>> from sympy import Ei, polar_lift, exp_polar, I, pi >>> from sympy.abc import x >>> Ei(-1) Ei(-1) This yields a real value: >>> Ei(-1).n(chop=True) -0.219383934395520 On the other hand the analytic continuation is not real: >>> Ei(polar_lift(-1)).n(chop=True) -0.21938393439552 + 3.14159265358979*I The exponential integral has a logarithmic branch point at the origin: >>> Ei(x*exp_polar(2*I*pi)) Ei(x) + 2*I*pi Differentiation is supported: >>> Ei(x).diff(x) exp(x)/x The exponential integral is related to many other special functions. For example: >>> from sympy import expint, Shi >>> Ei(x).rewrite(expint) -expint(1, x*exp_polar(I*pi)) - I*pi >>> Ei(x).rewrite(Shi) Chi(x) + Shi(x) See Also ======== expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. uppergamma: Upper incomplete gamma function. References ========== .. [1] http://dlmf.nist.gov/6.6 .. [2] https://en.wikipedia.org/wiki/Exponential_integral .. [3] Abramowitz & Stegun, section 5: http://people.math.sfu.ca/~cbm/aands/page_228.htm """ @classmethod def eval(cls, z): if z.is_zero: return S.NegativeInfinity elif z is S.Infinity: return S.Infinity elif z is S.NegativeInfinity: return S.Zero if z.is_zero: return S.NegativeInfinity nz, n = z.extract_branch_factor() if n: return Ei(nz) + 2*I*pi*n def fdiff(self, argindex=1): arg = unpolarify(self.args[0]) if argindex == 1: return exp(arg)/arg else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): if (self.args[0]/polar_lift(-1)).is_positive: return Function._eval_evalf(self, prec) + (I*pi)._eval_evalf(prec) return Function._eval_evalf(self, prec) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma # XXX this does not currently work usefully because uppergamma # immediately turns into expint return -uppergamma(0, polar_lift(-1)*z) - I*pi def _eval_rewrite_as_expint(self, z, **kwargs): return -expint(1, polar_lift(-1)*z) - I*pi def _eval_rewrite_as_li(self, z, **kwargs): if isinstance(z, log): return li(z.args[0]) # TODO: # Actually it only holds that: # Ei(z) = li(exp(z)) # for -pi < imag(z) <= pi return li(exp(z)) def _eval_rewrite_as_Si(self, z, **kwargs): if z.is_negative: return Shi(z) + Chi(z) - I*pi else: return Shi(z) + Chi(z) _eval_rewrite_as_Ci = _eval_rewrite_as_Si _eval_rewrite_as_Chi = _eval_rewrite_as_Si _eval_rewrite_as_Shi = _eval_rewrite_as_Si def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return exp(z) * _eis(z) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy import re x0 = self.args[0].limit(x, 0) arg = self.args[0].as_leading_term(x, cdir=cdir) cdir = arg.dir(x, cdir) if x0.is_zero: c, e = arg.as_coeff_exponent(x) logx = log(x) if logx is None else logx return log(c) + e*logx + EulerGamma - ( I*pi if re(cdir).is_negative else S.Zero) return super()._eval_as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_Si(*self.args) return f._eval_nseries(x, n, logx) return super()._eval_nseries(x, n, logx) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] if point is S.Infinity: z = self.args[0] s = [factorial(k) / (z)**k for k in range(n)] + \ [Order(1/z**n, x)] return (exp(z)/z) * Add(*s) return super(Ei, self)._eval_aseries(n, args0, x, logx) class expint(Function): r""" Generalized exponential integral. Explanation =========== This function is defined as .. math:: \operatorname{E}_\nu(z) = z^{\nu - 1} \Gamma(1 - \nu, z), where $\Gamma(1 - \nu, z)$ is the upper incomplete gamma function (``uppergamma``). Hence for $z$ with positive real part we have .. math:: \operatorname{E}_\nu(z) = \int_1^\infty \frac{e^{-zt}}{t^\nu} \mathrm{d}t, which explains the name. The representation as an incomplete gamma function provides an analytic continuation for $\operatorname{E}_\nu(z)$. If $\nu$ is a non-positive integer, the exponential integral is thus an unbranched function of $z$, otherwise there is a branch point at the origin. Refer to the incomplete gamma function documentation for details of the branching behavior. Examples ======== >>> from sympy import expint, S >>> from sympy.abc import nu, z Differentiation is supported. Differentiation with respect to $z$ further explains the name: for integral orders, the exponential integral is an iterated integral of the exponential function. >>> expint(nu, z).diff(z) -expint(nu - 1, z) Differentiation with respect to $\nu$ has no classical expression: >>> expint(nu, z).diff(nu) -z**(nu - 1)*meijerg(((), (1, 1)), ((0, 0, 1 - nu), ()), z) At non-postive integer orders, the exponential integral reduces to the exponential function: >>> expint(0, z) exp(-z)/z >>> expint(-1, z) exp(-z)/z + exp(-z)/z**2 At half-integers it reduces to error functions: >>> expint(S(1)/2, z) sqrt(pi)*erfc(sqrt(z))/sqrt(z) At positive integer orders it can be rewritten in terms of exponentials and ``expint(1, z)``. Use ``expand_func()`` to do this: >>> from sympy import expand_func >>> expand_func(expint(5, z)) z**4*expint(1, z)/24 + (-z**3 + z**2 - 2*z + 6)*exp(-z)/24 The generalised exponential integral is essentially equivalent to the incomplete gamma function: >>> from sympy import uppergamma >>> expint(nu, z).rewrite(uppergamma) z**(nu - 1)*uppergamma(1 - nu, z) As such it is branched at the origin: >>> from sympy import exp_polar, pi, I >>> expint(4, z*exp_polar(2*pi*I)) I*pi*z**3/3 + expint(4, z) >>> expint(nu, z*exp_polar(2*pi*I)) z**(nu - 1)*(exp(2*I*pi*nu) - 1)*gamma(1 - nu) + expint(nu, z) See Also ======== Ei: Another related function called exponential integral. E1: The classical case, returns expint(1, z). li: Logarithmic integral. Li: Offset logarithmic integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. uppergamma References ========== .. [1] http://dlmf.nist.gov/8.19 .. [2] http://functions.wolfram.com/GammaBetaErf/ExpIntegralE/ .. [3] https://en.wikipedia.org/wiki/Exponential_integral """ @classmethod def eval(cls, nu, z): from sympy.functions.special.gamma_functions import (gamma, uppergamma) nu2 = unpolarify(nu) if nu != nu2: return expint(nu2, z) if nu.is_Integer and nu <= 0 or (not nu.is_Integer and (2*nu).is_Integer): return unpolarify(expand_mul(z**(nu - 1)*uppergamma(1 - nu, z))) # Extract branching information. This can be deduced from what is # explained in lowergamma.eval(). z, n = z.extract_branch_factor() if n is S.Zero: return if nu.is_integer: if not nu > 0: return return expint(nu, z) \ - 2*pi*I*n*S.NegativeOne**(nu - 1)/factorial(nu - 1)*unpolarify(z)**(nu - 1) else: return (exp(2*I*pi*nu*n) - 1)*z**(nu - 1)*gamma(1 - nu) + expint(nu, z) def fdiff(self, argindex): nu, z = self.args if argindex == 1: return -z**(nu - 1)*meijerg([], [1, 1], [0, 0, 1 - nu], [], z) elif argindex == 2: return -expint(nu - 1, z) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_uppergamma(self, nu, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return z**(nu - 1)*uppergamma(1 - nu, z) def _eval_rewrite_as_Ei(self, nu, z, **kwargs): if nu == 1: return -Ei(z*exp_polar(-I*pi)) - I*pi elif nu.is_Integer and nu > 1: # DLMF, 8.19.7 x = -unpolarify(z) return x**(nu - 1)/factorial(nu - 1)*E1(z).rewrite(Ei) + \ exp(x)/factorial(nu - 1) * \ Add(*[factorial(nu - k - 2)*x**k for k in range(nu - 1)]) else: return self def _eval_expand_func(self, **hints): return self.rewrite(Ei).rewrite(expint, **hints) def _eval_rewrite_as_Si(self, nu, z, **kwargs): if nu != 1: return self return Shi(z) - Chi(z) _eval_rewrite_as_Ci = _eval_rewrite_as_Si _eval_rewrite_as_Chi = _eval_rewrite_as_Si _eval_rewrite_as_Shi = _eval_rewrite_as_Si def _eval_nseries(self, x, n, logx, cdir=0): if not self.args[0].has(x): nu = self.args[0] if nu == 1: f = self._eval_rewrite_as_Si(*self.args) return f._eval_nseries(x, n, logx) elif nu.is_Integer and nu > 1: f = self._eval_rewrite_as_Ei(*self.args) return f._eval_nseries(x, n, logx) return super()._eval_nseries(x, n, logx) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[1] nu = self.args[0] if point is S.Infinity: z = self.args[1] s = [S.NegativeOne**k * RisingFactorial(nu, k) / z**k for k in range(n)] + [Order(1/z**n, x)] return (exp(-z)/z) * Add(*s) return super(expint, self)._eval_aseries(n, args0, x, logx) def E1(z): """ Classical case of the generalized exponential integral. Explanation =========== This is equivalent to ``expint(1, z)``. Examples ======== >>> from sympy import E1 >>> E1(0) expint(1, 0) >>> E1(5) expint(1, 5) See Also ======== Ei: Exponential integral. expint: Generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. """ return expint(1, z) class li(Function): r""" The classical logarithmic integral. Explanation =========== For use in SymPy, this function is defined as .. math:: \operatorname{li}(x) = \int_0^x \frac{1}{\log(t)} \mathrm{d}t \,. Examples ======== >>> from sympy import I, oo, li >>> from sympy.abc import z Several special values are known: >>> li(0) 0 >>> li(1) -oo >>> li(oo) oo Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(li(z), z) 1/log(z) Defining the ``li`` function via an integral: >>> from sympy import integrate >>> integrate(li(z)) z*li(z) - Ei(2*log(z)) >>> integrate(li(z),z) z*li(z) - Ei(2*log(z)) The logarithmic integral can also be defined in terms of ``Ei``: >>> from sympy import Ei >>> li(z).rewrite(Ei) Ei(log(z)) >>> diff(li(z).rewrite(Ei), z) 1/log(z) We can numerically evaluate the logarithmic integral to arbitrary precision on the whole complex plane (except the singular points): >>> li(2).evalf(30) 1.04516378011749278484458888919 >>> li(2*I).evalf(30) 1.0652795784357498247001125598 + 3.08346052231061726610939702133*I We can even compute Soldner's constant by the help of mpmath: >>> from mpmath import findroot >>> findroot(li, 2) 1.45136923488338 Further transformations include rewriting ``li`` in terms of the trigonometric integrals ``Si``, ``Ci``, ``Shi`` and ``Chi``: >>> from sympy import Si, Ci, Shi, Chi >>> li(z).rewrite(Si) -log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z)) >>> li(z).rewrite(Ci) -log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z)) >>> li(z).rewrite(Shi) -log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z)) >>> li(z).rewrite(Chi) -log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z)) See Also ======== Li: Offset logarithmic integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. References ========== .. [1] https://en.wikipedia.org/wiki/Logarithmic_integral .. [2] http://mathworld.wolfram.com/LogarithmicIntegral.html .. [3] http://dlmf.nist.gov/6 .. [4] http://mathworld.wolfram.com/SoldnersConstant.html """ @classmethod def eval(cls, z): if z.is_zero: return S.Zero elif z is S.One: return S.NegativeInfinity elif z is S.Infinity: return S.Infinity if z.is_zero: return S.Zero def fdiff(self, argindex=1): arg = self.args[0] if argindex == 1: return S.One / log(arg) else: raise ArgumentIndexError(self, argindex) def _eval_conjugate(self): z = self.args[0] # Exclude values on the branch cut (-oo, 0) if not z.is_extended_negative: return self.func(z.conjugate()) def _eval_rewrite_as_Li(self, z, **kwargs): return Li(z) + li(2) def _eval_rewrite_as_Ei(self, z, **kwargs): return Ei(log(z)) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return (-uppergamma(0, -log(z)) + S.Half*(log(log(z)) - log(S.One/log(z))) - log(-log(z))) def _eval_rewrite_as_Si(self, z, **kwargs): return (Ci(I*log(z)) - I*Si(I*log(z)) - S.Half*(log(S.One/log(z)) - log(log(z))) - log(I*log(z))) _eval_rewrite_as_Ci = _eval_rewrite_as_Si def _eval_rewrite_as_Shi(self, z, **kwargs): return (Chi(log(z)) - Shi(log(z)) - S.Half*(log(S.One/log(z)) - log(log(z)))) _eval_rewrite_as_Chi = _eval_rewrite_as_Shi def _eval_rewrite_as_hyper(self, z, **kwargs): return (log(z)*hyper((1, 1), (2, 2), log(z)) + S.Half*(log(log(z)) - log(S.One/log(z))) + EulerGamma) def _eval_rewrite_as_meijerg(self, z, **kwargs): return (-log(-log(z)) - S.Half*(log(S.One/log(z)) - log(log(z))) - meijerg(((), (1,)), ((0, 0), ()), -log(z))) def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return z * _eis(log(z)) def _eval_nseries(self, x, n, logx, cdir=0): z = self.args[0] s = [(log(z))**k / (factorial(k) * k) for k in range(1, n)] return EulerGamma + log(log(z)) + Add(*s) def _eval_is_zero(self): z = self.args[0] if z.is_zero: return True class Li(Function): r""" The offset logarithmic integral. Explanation =========== For use in SymPy, this function is defined as .. math:: \operatorname{Li}(x) = \operatorname{li}(x) - \operatorname{li}(2) Examples ======== >>> from sympy import Li >>> from sympy.abc import z The following special value is known: >>> Li(2) 0 Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(Li(z), z) 1/log(z) The shifted logarithmic integral can be written in terms of $li(z)$: >>> from sympy import li >>> Li(z).rewrite(li) li(z) - li(2) We can numerically evaluate the logarithmic integral to arbitrary precision on the whole complex plane (except the singular points): >>> Li(2).evalf(30) 0 >>> Li(4).evalf(30) 1.92242131492155809316615998938 See Also ======== li: Logarithmic integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. References ========== .. [1] https://en.wikipedia.org/wiki/Logarithmic_integral .. [2] http://mathworld.wolfram.com/LogarithmicIntegral.html .. [3] http://dlmf.nist.gov/6 """ @classmethod def eval(cls, z): if z is S.Infinity: return S.Infinity elif z == S(2): return S.Zero def fdiff(self, argindex=1): arg = self.args[0] if argindex == 1: return S.One / log(arg) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): return self.rewrite(li).evalf(prec) def _eval_rewrite_as_li(self, z, **kwargs): return li(z) - li(2) def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return self.rewrite(li).rewrite("tractable", deep=True) def _eval_nseries(self, x, n, logx, cdir=0): f = self._eval_rewrite_as_li(*self.args) return f._eval_nseries(x, n, logx) ############################################################################### #################### TRIGONOMETRIC INTEGRALS ################################## ############################################################################### class TrigonometricIntegral(Function): """ Base class for trigonometric integrals. """ @classmethod def eval(cls, z): if z is S.Zero: return cls._atzero elif z is S.Infinity: return cls._atinf() elif z is S.NegativeInfinity: return cls._atneginf() if z.is_zero: return cls._atzero nz = z.extract_multiplicatively(polar_lift(I)) if nz is None and cls._trigfunc(0) == 0: nz = z.extract_multiplicatively(I) if nz is not None: return cls._Ifactor(nz, 1) nz = z.extract_multiplicatively(polar_lift(-I)) if nz is not None: return cls._Ifactor(nz, -1) nz = z.extract_multiplicatively(polar_lift(-1)) if nz is None and cls._trigfunc(0) == 0: nz = z.extract_multiplicatively(-1) if nz is not None: return cls._minusfactor(nz) nz, n = z.extract_branch_factor() if n == 0 and nz == z: return return 2*pi*I*n*cls._trigfunc(0) + cls(nz) def fdiff(self, argindex=1): arg = unpolarify(self.args[0]) if argindex == 1: return self._trigfunc(arg)/arg else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_Ei(self, z, **kwargs): return self._eval_rewrite_as_expint(z).rewrite(Ei) def _eval_rewrite_as_uppergamma(self, z, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return self._eval_rewrite_as_expint(z).rewrite(uppergamma) def _eval_nseries(self, x, n, logx, cdir=0): # NOTE this is fairly inefficient n += 1 if self.args[0].subs(x, 0) != 0: return super()._eval_nseries(x, n, logx) baseseries = self._trigfunc(x)._eval_nseries(x, n, logx) if self._trigfunc(0) != 0: baseseries -= 1 baseseries = baseseries.replace(Pow, lambda t, n: t**n/n, simultaneous=False) if self._trigfunc(0) != 0: baseseries += EulerGamma + log(x) return baseseries.subs(x, self.args[0])._eval_nseries(x, n, logx) class Si(TrigonometricIntegral): r""" Sine integral. Explanation =========== This function is defined by .. math:: \operatorname{Si}(z) = \int_0^z \frac{\sin{t}}{t} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import Si >>> from sympy.abc import z The sine integral is an antiderivative of $sin(z)/z$: >>> Si(z).diff(z) sin(z)/z It is unbranched: >>> from sympy import exp_polar, I, pi >>> Si(z*exp_polar(2*I*pi)) Si(z) Sine integral behaves much like ordinary sine under multiplication by ``I``: >>> Si(I*z) I*Shi(z) >>> Si(-z) -Si(z) It can also be expressed in terms of exponential integrals, but beware that the latter is branched: >>> from sympy import expint >>> Si(z).rewrite(expint) -I*(-expint(1, z*exp_polar(-I*pi/2))/2 + expint(1, z*exp_polar(I*pi/2))/2) + pi/2 It can be rewritten in the form of sinc function (by definition): >>> from sympy import sinc >>> Si(z).rewrite(sinc) Integral(sinc(t), (t, 0, z)) See Also ======== Ci: Cosine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. Ei: Exponential integral. expint: Generalised exponential integral. sinc: unnormalized sinc function E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral """ _trigfunc = sin _atzero = S.Zero @classmethod def _atinf(cls): return pi*S.Half @classmethod def _atneginf(cls): return -pi*S.Half @classmethod def _minusfactor(cls, z): return -Si(z) @classmethod def _Ifactor(cls, z, sign): return I*Shi(z)*sign def _eval_rewrite_as_expint(self, z, **kwargs): # XXX should we polarify z? return pi/2 + (E1(polar_lift(I)*z) - E1(polar_lift(-I)*z))/2/I def _eval_rewrite_as_sinc(self, z, **kwargs): from sympy.integrals.integrals import Integral t = Symbol('t', Dummy=True) return Integral(sinc(t), (t, 0, z)) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo if point is S.Infinity: z = self.args[0] p = [S.NegativeOne**k * factorial(2*k) / z**(2*k) for k in range(int((n - 1)/2))] + [Order(1/z**n, x)] q = [S.NegativeOne**k * factorial(2*k + 1) / z**(2*k + 1) for k in range(int(n/2) - 1)] + [Order(1/z**n, x)] return pi/2 - (cos(z)/z)*Add(*p) - (sin(z)/z)*Add(*q) # All other points are not handled return super(Si, self)._eval_aseries(n, args0, x, logx) def _eval_is_zero(self): z = self.args[0] if z.is_zero: return True class Ci(TrigonometricIntegral): r""" Cosine integral. Explanation =========== This function is defined for positive $x$ by .. math:: \operatorname{Ci}(x) = \gamma + \log{x} + \int_0^x \frac{\cos{t} - 1}{t} \mathrm{d}t = -\int_x^\infty \frac{\cos{t}}{t} \mathrm{d}t, where $\gamma$ is the Euler-Mascheroni constant. We have .. math:: \operatorname{Ci}(z) = -\frac{\operatorname{E}_1\left(e^{i\pi/2} z\right) + \operatorname{E}_1\left(e^{-i \pi/2} z\right)}{2} which holds for all polar $z$ and thus provides an analytic continuation to the Riemann surface of the logarithm. The formula also holds as stated for $z \in \mathbb{C}$ with $\Re(z) > 0$. By lifting to the principal branch, we obtain an analytic function on the cut complex plane. Examples ======== >>> from sympy import Ci >>> from sympy.abc import z The cosine integral is a primitive of $\cos(z)/z$: >>> Ci(z).diff(z) cos(z)/z It has a logarithmic branch point at the origin: >>> from sympy import exp_polar, I, pi >>> Ci(z*exp_polar(2*I*pi)) Ci(z) + 2*I*pi The cosine integral behaves somewhat like ordinary $\cos$ under multiplication by $i$: >>> from sympy import polar_lift >>> Ci(polar_lift(I)*z) Chi(z) + I*pi/2 >>> Ci(polar_lift(-1)*z) Ci(z) + I*pi It can also be expressed in terms of exponential integrals: >>> from sympy import expint >>> Ci(z).rewrite(expint) -expint(1, z*exp_polar(-I*pi/2))/2 - expint(1, z*exp_polar(I*pi/2))/2 See Also ======== Si: Sine integral. Shi: Hyperbolic sine integral. Chi: Hyperbolic cosine integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral """ _trigfunc = cos _atzero = S.ComplexInfinity @classmethod def _atinf(cls): return S.Zero @classmethod def _atneginf(cls): return I*pi @classmethod def _minusfactor(cls, z): return Ci(z) + I*pi @classmethod def _Ifactor(cls, z, sign): return Chi(z) + I*pi/2*sign def _eval_rewrite_as_expint(self, z, **kwargs): return -(E1(polar_lift(I)*z) + E1(polar_lift(-I)*z))/2 def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: c, e = arg.as_coeff_exponent(x) logx = log(x) if logx is None else logx return log(c) + e*logx + EulerGamma elif arg0.is_finite: return self.func(arg0) else: return self def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo if point is S.Infinity: z = self.args[0] p = [S.NegativeOne**k * factorial(2*k) / z**(2*k) for k in range(int((n - 1)/2))] + [Order(1/z**n, x)] q = [S.NegativeOne**k * factorial(2*k + 1) / z**(2*k + 1) for k in range(int(n/2) - 1)] + [Order(1/z**n, x)] return (sin(z)/z)*Add(*p) - (cos(z)/z)*Add(*q) # All other points are not handled return super(Ci, self)._eval_aseries(n, args0, x, logx) class Shi(TrigonometricIntegral): r""" Sinh integral. Explanation =========== This function is defined by .. math:: \operatorname{Shi}(z) = \int_0^z \frac{\sinh{t}}{t} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import Shi >>> from sympy.abc import z The Sinh integral is a primitive of $\sinh(z)/z$: >>> Shi(z).diff(z) sinh(z)/z It is unbranched: >>> from sympy import exp_polar, I, pi >>> Shi(z*exp_polar(2*I*pi)) Shi(z) The $\sinh$ integral behaves much like ordinary $\sinh$ under multiplication by $i$: >>> Shi(I*z) I*Si(z) >>> Shi(-z) -Shi(z) It can also be expressed in terms of exponential integrals, but beware that the latter is branched: >>> from sympy import expint >>> Shi(z).rewrite(expint) expint(1, z)/2 - expint(1, z*exp_polar(I*pi))/2 - I*pi/2 See Also ======== Si: Sine integral. Ci: Cosine integral. Chi: Hyperbolic cosine integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral """ _trigfunc = sinh _atzero = S.Zero @classmethod def _atinf(cls): return S.Infinity @classmethod def _atneginf(cls): return S.NegativeInfinity @classmethod def _minusfactor(cls, z): return -Shi(z) @classmethod def _Ifactor(cls, z, sign): return I*Si(z)*sign def _eval_rewrite_as_expint(self, z, **kwargs): # XXX should we polarify z? return (E1(z) - E1(exp_polar(I*pi)*z))/2 - I*pi/2 def _eval_is_zero(self): z = self.args[0] if z.is_zero: return True def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return arg elif not arg0.is_infinite: return self.func(arg0) else: return self class Chi(TrigonometricIntegral): r""" Cosh integral. Explanation =========== This function is defined for positive $x$ by .. math:: \operatorname{Chi}(x) = \gamma + \log{x} + \int_0^x \frac{\cosh{t} - 1}{t} \mathrm{d}t, where $\gamma$ is the Euler-Mascheroni constant. We have .. math:: \operatorname{Chi}(z) = \operatorname{Ci}\left(e^{i \pi/2}z\right) - i\frac{\pi}{2}, which holds for all polar $z$ and thus provides an analytic continuation to the Riemann surface of the logarithm. By lifting to the principal branch we obtain an analytic function on the cut complex plane. Examples ======== >>> from sympy import Chi >>> from sympy.abc import z The $\cosh$ integral is a primitive of $\cosh(z)/z$: >>> Chi(z).diff(z) cosh(z)/z It has a logarithmic branch point at the origin: >>> from sympy import exp_polar, I, pi >>> Chi(z*exp_polar(2*I*pi)) Chi(z) + 2*I*pi The $\cosh$ integral behaves somewhat like ordinary $\cosh$ under multiplication by $i$: >>> from sympy import polar_lift >>> Chi(polar_lift(I)*z) Ci(z) + I*pi/2 >>> Chi(polar_lift(-1)*z) Chi(z) + I*pi It can also be expressed in terms of exponential integrals: >>> from sympy import expint >>> Chi(z).rewrite(expint) -expint(1, z)/2 - expint(1, z*exp_polar(I*pi))/2 - I*pi/2 See Also ======== Si: Sine integral. Ci: Cosine integral. Shi: Hyperbolic sine integral. Ei: Exponential integral. expint: Generalised exponential integral. E1: Special case of the generalised exponential integral. li: Logarithmic integral. Li: Offset logarithmic integral. References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral """ _trigfunc = cosh _atzero = S.ComplexInfinity @classmethod def _atinf(cls): return S.Infinity @classmethod def _atneginf(cls): return S.Infinity @classmethod def _minusfactor(cls, z): return Chi(z) + I*pi @classmethod def _Ifactor(cls, z, sign): return Ci(z) + I*pi/2*sign def _eval_rewrite_as_expint(self, z, **kwargs): return -I*pi/2 - (E1(z) + E1(exp_polar(I*pi)*z))/2 def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: c, e = arg.as_coeff_exponent(x) logx = log(x) if logx is None else logx return log(c) + e*logx + EulerGamma elif arg0.is_finite: return self.func(arg0) else: return self ############################################################################### #################### FRESNEL INTEGRALS ######################################## ############################################################################### class FresnelIntegral(Function): """ Base class for the Fresnel integrals.""" unbranched = True @classmethod def eval(cls, z): # Values at positive infinities signs # if any were extracted automatically if z is S.Infinity: return S.Half # Value at zero if z.is_zero: return S.Zero # Try to pull out factors of -1 and I prefact = S.One newarg = z changed = False nz = newarg.extract_multiplicatively(-1) if nz is not None: prefact = -prefact newarg = nz changed = True nz = newarg.extract_multiplicatively(I) if nz is not None: prefact = cls._sign*I*prefact newarg = nz changed = True if changed: return prefact*cls(newarg) def fdiff(self, argindex=1): if argindex == 1: return self._trigfunc(S.Half*pi*self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_extended_real(self): return self.args[0].is_extended_real _eval_is_finite = _eval_is_extended_real def _eval_is_zero(self): return self.args[0].is_zero def _eval_conjugate(self): return self.func(self.args[0].conjugate()) as_real_imag = real_to_real_as_real_imag class fresnels(FresnelIntegral): r""" Fresnel integral S. Explanation =========== This function is defined by .. math:: \operatorname{S}(z) = \int_0^z \sin{\frac{\pi}{2} t^2} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import I, oo, fresnels >>> from sympy.abc import z Several special values are known: >>> fresnels(0) 0 >>> fresnels(oo) 1/2 >>> fresnels(-oo) -1/2 >>> fresnels(I*oo) -I/2 >>> fresnels(-I*oo) I/2 In general one can pull out factors of -1 and $i$ from the argument: >>> fresnels(-z) -fresnels(z) >>> fresnels(I*z) -I*fresnels(z) The Fresnel S integral obeys the mirror symmetry $\overline{S(z)} = S(\bar{z})$: >>> from sympy import conjugate >>> conjugate(fresnels(z)) fresnels(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(fresnels(z), z) sin(pi*z**2/2) Defining the Fresnel functions via an integral: >>> from sympy import integrate, pi, sin, expand_func >>> integrate(sin(pi*z**2/2), z) 3*fresnels(z)*gamma(3/4)/(4*gamma(7/4)) >>> expand_func(integrate(sin(pi*z**2/2), z)) fresnels(z) We can numerically evaluate the Fresnel integral to arbitrary precision on the whole complex plane: >>> fresnels(2).evalf(30) 0.343415678363698242195300815958 >>> fresnels(-2*I).evalf(30) 0.343415678363698242195300815958*I See Also ======== fresnelc: Fresnel cosine integral. References ========== .. [1] https://en.wikipedia.org/wiki/Fresnel_integral .. [2] http://dlmf.nist.gov/7 .. [3] http://mathworld.wolfram.com/FresnelIntegrals.html .. [4] http://functions.wolfram.com/GammaBetaErf/FresnelS .. [5] The converging factors for the fresnel integrals by John W. Wrench Jr. and Vicki Alley """ _trigfunc = sin _sign = -S.One @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 1: p = previous_terms[-1] return (-pi**2*x**4*(4*n - 1)/(8*n*(2*n + 1)*(4*n + 3))) * p else: return x**3 * (-x**4)**n * (S(2)**(-2*n - 1)*pi**(2*n + 1)) / ((4*n + 3)*factorial(2*n + 1)) def _eval_rewrite_as_erf(self, z, **kwargs): return (S.One + I)/4 * (erf((S.One + I)/2*sqrt(pi)*z) - I*erf((S.One - I)/2*sqrt(pi)*z)) def _eval_rewrite_as_hyper(self, z, **kwargs): return pi*z**3/6 * hyper([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)], -pi**2*z**4/16) def _eval_rewrite_as_meijerg(self, z, **kwargs): return (pi*z**Rational(9, 4) / (sqrt(2)*(z**2)**Rational(3, 4)*(-z)**Rational(3, 4)) * meijerg([], [1], [Rational(3, 4)], [Rational(1, 4), 0], -pi**2*z**4/16)) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.ComplexInfinity: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return pi*arg**3/6 elif arg0 in [S.Infinity, S.NegativeInfinity]: s = 1 if arg0 is S.Infinity else -1 return s*S.Half + Order(x, x) else: return self.func(arg0) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo and -oo if point in [S.Infinity, -S.Infinity]: z = self.args[0] # expansion of S(x) = S1(x*sqrt(pi/2)), see reference[5] page 1-8 # as only real infinities are dealt with, sin and cos are O(1) p = [S.NegativeOne**k * factorial(4*k + 1) / (2**(2*k + 2) * z**(4*k + 3) * 2**(2*k)*factorial(2*k)) for k in range(0, n) if 4*k + 3 < n] q = [1/(2*z)] + [S.NegativeOne**k * factorial(4*k - 1) / (2**(2*k + 1) * z**(4*k + 1) * 2**(2*k - 1)*factorial(2*k - 1)) for k in range(1, n) if 4*k + 1 < n] p = [-sqrt(2/pi)*t for t in p] q = [-sqrt(2/pi)*t for t in q] s = 1 if point is S.Infinity else -1 # The expansion at oo is 1/2 + some odd powers of z # To get the expansion at -oo, replace z by -z and flip the sign # The result -1/2 + the same odd powers of z as before. return s*S.Half + (sin(z**2)*Add(*p) + cos(z**2)*Add(*q) ).subs(x, sqrt(2/pi)*x) + Order(1/z**n, x) # All other points are not handled return super()._eval_aseries(n, args0, x, logx) class fresnelc(FresnelIntegral): r""" Fresnel integral C. Explanation =========== This function is defined by .. math:: \operatorname{C}(z) = \int_0^z \cos{\frac{\pi}{2} t^2} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import I, oo, fresnelc >>> from sympy.abc import z Several special values are known: >>> fresnelc(0) 0 >>> fresnelc(oo) 1/2 >>> fresnelc(-oo) -1/2 >>> fresnelc(I*oo) I/2 >>> fresnelc(-I*oo) -I/2 In general one can pull out factors of -1 and $i$ from the argument: >>> fresnelc(-z) -fresnelc(z) >>> fresnelc(I*z) I*fresnelc(z) The Fresnel C integral obeys the mirror symmetry $\overline{C(z)} = C(\bar{z})$: >>> from sympy import conjugate >>> conjugate(fresnelc(z)) fresnelc(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(fresnelc(z), z) cos(pi*z**2/2) Defining the Fresnel functions via an integral: >>> from sympy import integrate, pi, cos, expand_func >>> integrate(cos(pi*z**2/2), z) fresnelc(z)*gamma(1/4)/(4*gamma(5/4)) >>> expand_func(integrate(cos(pi*z**2/2), z)) fresnelc(z) We can numerically evaluate the Fresnel integral to arbitrary precision on the whole complex plane: >>> fresnelc(2).evalf(30) 0.488253406075340754500223503357 >>> fresnelc(-2*I).evalf(30) -0.488253406075340754500223503357*I See Also ======== fresnels: Fresnel sine integral. References ========== .. [1] https://en.wikipedia.org/wiki/Fresnel_integral .. [2] http://dlmf.nist.gov/7 .. [3] http://mathworld.wolfram.com/FresnelIntegrals.html .. [4] http://functions.wolfram.com/GammaBetaErf/FresnelC .. [5] The converging factors for the fresnel integrals by John W. Wrench Jr. and Vicki Alley """ _trigfunc = cos _sign = S.One @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 1: p = previous_terms[-1] return (-pi**2*x**4*(4*n - 3)/(8*n*(2*n - 1)*(4*n + 1))) * p else: return x * (-x**4)**n * (S(2)**(-2*n)*pi**(2*n)) / ((4*n + 1)*factorial(2*n)) def _eval_rewrite_as_erf(self, z, **kwargs): return (S.One - I)/4 * (erf((S.One + I)/2*sqrt(pi)*z) + I*erf((S.One - I)/2*sqrt(pi)*z)) def _eval_rewrite_as_hyper(self, z, **kwargs): return z * hyper([Rational(1, 4)], [S.Half, Rational(5, 4)], -pi**2*z**4/16) def _eval_rewrite_as_meijerg(self, z, **kwargs): return (pi*z**Rational(3, 4) / (sqrt(2)*root(z**2, 4)*root(-z, 4)) * meijerg([], [1], [Rational(1, 4)], [Rational(3, 4), 0], -pi**2*z**4/16)) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.ComplexInfinity: arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if arg0.is_zero: return arg elif arg0 in [S.Infinity, S.NegativeInfinity]: s = 1 if arg0 is S.Infinity else -1 return s*S.Half + Order(x, x) else: return self.func(arg0) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo if point in [S.Infinity, -S.Infinity]: z = self.args[0] # expansion of C(x) = C1(x*sqrt(pi/2)), see reference[5] page 1-8 # as only real infinities are dealt with, sin and cos are O(1) p = [S.NegativeOne**k * factorial(4*k + 1) / (2**(2*k + 2) * z**(4*k + 3) * 2**(2*k)*factorial(2*k)) for k in range(n) if 4*k + 3 < n] q = [1/(2*z)] + [S.NegativeOne**k * factorial(4*k - 1) / (2**(2*k + 1) * z**(4*k + 1) * 2**(2*k - 1)*factorial(2*k - 1)) for k in range(1, n) if 4*k + 1 < n] p = [-sqrt(2/pi)*t for t in p] q = [ sqrt(2/pi)*t for t in q] s = 1 if point is S.Infinity else -1 # The expansion at oo is 1/2 + some odd powers of z # To get the expansion at -oo, replace z by -z and flip the sign # The result -1/2 + the same odd powers of z as before. return s*S.Half + (cos(z**2)*Add(*p) + sin(z**2)*Add(*q) ).subs(x, sqrt(2/pi)*x) + Order(1/z**n, x) # All other points are not handled return super()._eval_aseries(n, args0, x, logx) ############################################################################### #################### HELPER FUNCTIONS ######################################### ############################################################################### class _erfs(Function): """ Helper function to make the $\\mathrm{erf}(z)$ function tractable for the Gruntz algorithm. """ @classmethod def eval(cls, arg): if arg.is_zero: return S.One def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order point = args0[0] # Expansion at oo if point is S.Infinity: z = self.args[0] l = [1/sqrt(pi) * factorial(2*k)*(-S( 4))**(-k)/factorial(k) * (1/z)**(2*k + 1) for k in range(n)] o = Order(1/z**(2*n + 1), x) # It is very inefficient to first add the order and then do the nseries return (Add(*l))._eval_nseries(x, n, logx) + o # Expansion at I*oo t = point.extract_multiplicatively(I) if t is S.Infinity: z = self.args[0] # TODO: is the series really correct? l = [1/sqrt(pi) * factorial(2*k)*(-S( 4))**(-k)/factorial(k) * (1/z)**(2*k + 1) for k in range(n)] o = Order(1/z**(2*n + 1), x) # It is very inefficient to first add the order and then do the nseries return (Add(*l))._eval_nseries(x, n, logx) + o # All other points are not handled return super()._eval_aseries(n, args0, x, logx) def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] return -2/sqrt(pi) + 2*z*_erfs(z) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_intractable(self, z, **kwargs): return (S.One - erf(z))*exp(z**2) class _eis(Function): """ Helper function to make the $\\mathrm{Ei}(z)$ and $\\mathrm{li}(z)$ functions tractable for the Gruntz algorithm. """ def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order if args0[0] != S.Infinity: return super(_erfs, self)._eval_aseries(n, args0, x, logx) z = self.args[0] l = [factorial(k) * (1/z)**(k + 1) for k in range(n)] o = Order(1/z**(n + 1), x) # It is very inefficient to first add the order and then do the nseries return (Add(*l))._eval_nseries(x, n, logx) + o def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] return S.One / z - _eis(z) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_intractable(self, z, **kwargs): return exp(-z)*Ei(z) def _eval_as_leading_term(self, x, logx=None, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_intractable(*self.args) return f._eval_as_leading_term(x, logx=logx, cdir=cdir) return super()._eval_as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_intractable(*self.args) return f._eval_nseries(x, n, logx) return super()._eval_nseries(x, n, logx)
cb17e0bbec2634478c7da1400620c7626b99a59ba9f454e9d1961eae573a8617
from sympy.core.function import (diff, expand_func) from sympy.core.numbers import I, Rational, pi from sympy.core.singleton import S from sympy.core.symbol import (Dummy, symbols) from sympy.functions.combinatorial.numbers import catalan from sympy.functions.elementary.complexes import conjugate from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.special.beta_functions import (beta, betainc, betainc_regularized) from sympy.functions.special.gamma_functions import gamma, polygamma from sympy.functions.special.hyper import hyper from sympy.integrals.integrals import Integral from sympy.core.function import ArgumentIndexError from sympy.core.expr import unchanged from sympy.testing.pytest import raises def test_beta(): x, y = symbols('x y') t = Dummy('t') assert unchanged(beta, x, y) assert unchanged(beta, x, x) assert beta(5, -3).is_real == True assert beta(3, y).is_real is None assert expand_func(beta(x, y)) == gamma(x)*gamma(y)/gamma(x + y) assert expand_func(beta(x, y) - beta(y, x)) == 0 # Symmetric assert expand_func(beta(x, y)) == expand_func(beta(x, y + 1) + beta(x + 1, y)).simplify() assert diff(beta(x, y), x) == beta(x, y)*(polygamma(0, x) - polygamma(0, x + y)) assert diff(beta(x, y), y) == beta(x, y)*(polygamma(0, y) - polygamma(0, x + y)) assert conjugate(beta(x, y)) == beta(conjugate(x), conjugate(y)) raises(ArgumentIndexError, lambda: beta(x, y).fdiff(3)) assert beta(x, y).rewrite(gamma) == gamma(x)*gamma(y)/gamma(x + y) assert beta(x).rewrite(gamma) == gamma(x)**2/gamma(2*x) assert beta(x, y).rewrite(Integral).dummy_eq(Integral(t**(x - 1) * (1 - t)**(y - 1), (t, 0, 1))) assert beta(Rational(-19, 10), Rational(-1, 10)) == S.Zero assert beta(Rational(-19, 10), Rational(-9, 10)) == \ 800*2**(S(4)/5)*sqrt(pi)*gamma(S.One/10)/(171*gamma(-S(7)/5)) assert beta(Rational(19, 10), Rational(29, 10)) == 100/(551*catalan(Rational(19, 10))) assert beta(1, 0) == S.ComplexInfinity assert beta(0, 1) == S.ComplexInfinity assert beta(2, 3) == S.One/12 assert unchanged(beta, x, x + 1) assert unchanged(beta, x, 1) assert unchanged(beta, 1, y) assert beta(x, x + 1).doit() == 1/(x*(x+1)*catalan(x)) assert beta(1, y).doit() == 1/y assert beta(x, 1).doit() == 1/x assert beta(Rational(-19, 10), Rational(-1, 10), evaluate=False).doit() == S.Zero assert beta(2) == beta(2, 2) assert beta(x, evaluate=False) != beta(x, x) assert beta(x, evaluate=False).doit() == beta(x, x) def test_betainc(): a, b, x1, x2 = symbols('a b x1 x2') assert unchanged(betainc, a, b, x1, x2) assert unchanged(betainc, a, b, 0, x1) assert betainc(1, 2, 0, -5).is_real == True assert betainc(1, 2, 0, x2).is_real is None assert conjugate(betainc(I, 2, 3 - I, 1 + 4*I)) == betainc(-I, 2, 3 + I, 1 - 4*I) assert betainc(a, b, 0, 1).rewrite(Integral).dummy_eq(beta(a, b).rewrite(Integral)) assert betainc(1, 2, 0, x2).rewrite(hyper) == x2*hyper((1, -1), (2,), x2) assert betainc(1, 2, 3, 3).evalf() == 0 def test_betainc_regularized(): a, b, x1, x2 = symbols('a b x1 x2') assert unchanged(betainc_regularized, a, b, x1, x2) assert unchanged(betainc_regularized, a, b, 0, x1) assert betainc_regularized(3, 5, 0, -1).is_real == True assert betainc_regularized(3, 5, 0, x2).is_real is None assert conjugate(betainc_regularized(3*I, 1, 2 + I, 1 + 2*I)) == betainc_regularized(-3*I, 1, 2 - I, 1 - 2*I) assert betainc_regularized(a, b, 0, 1).rewrite(Integral) == 1 assert betainc_regularized(1, 2, x1, x2).rewrite(hyper) == 2*x2*hyper((1, -1), (2,), x2) - 2*x1*hyper((1, -1), (2,), x1) assert betainc_regularized(4, 1, 5, 5).evalf() == 0
b92d662dff72c34e76e62576e83bbe7078ac22ee1ef95c469aa787961b532321
from sympy.core.add import Add from sympy.core.assumptions import check_assumptions from sympy.core.containers import Tuple from sympy.core.exprtools import factor_terms from sympy.core.function import _mexpand from sympy.core.mul import Mul from sympy.core.numbers import Rational from sympy.core.numbers import igcdex, ilcm, igcd from sympy.core.power import integer_nthroot, isqrt from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import Symbol, symbols from sympy.core.sympify import _sympify from sympy.functions.elementary.complexes import sign from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.matrices.dense import MutableDenseMatrix as Matrix from sympy.ntheory.factor_ import ( divisors, factorint, multiplicity, perfect_power) from sympy.ntheory.generate import nextprime from sympy.ntheory.primetest import is_square, isprime from sympy.ntheory.residue_ntheory import sqrt_mod from sympy.polys.polyerrors import GeneratorsNeeded from sympy.polys.polytools import Poly, factor_list from sympy.simplify.simplify import signsimp from sympy.solvers.solveset import solveset_real from sympy.utilities import numbered_symbols from sympy.utilities.misc import as_int, filldedent from sympy.utilities.iterables import (is_sequence, subsets, permute_signs, signed_permutations, ordered_partitions) # these are imported with 'from sympy.solvers.diophantine import * __all__ = ['diophantine', 'classify_diop'] class DiophantineSolutionSet(set): """ Container for a set of solutions to a particular diophantine equation. The base representation is a set of tuples representing each of the solutions. Parameters ========== symbols : list List of free symbols in the original equation. parameters: list List of parameters to be used in the solution. Examples ======== Adding solutions: >>> from sympy.solvers.diophantine.diophantine import DiophantineSolutionSet >>> from sympy.abc import x, y, t, u >>> s1 = DiophantineSolutionSet([x, y], [t, u]) >>> s1 set() >>> s1.add((2, 3)) >>> s1.add((-1, u)) >>> s1 {(-1, u), (2, 3)} >>> s2 = DiophantineSolutionSet([x, y], [t, u]) >>> s2.add((3, 4)) >>> s1.update(*s2) >>> s1 {(-1, u), (2, 3), (3, 4)} Conversion of solutions into dicts: >>> list(s1.dict_iterator()) [{x: -1, y: u}, {x: 2, y: 3}, {x: 3, y: 4}] Substituting values: >>> s3 = DiophantineSolutionSet([x, y], [t, u]) >>> s3.add((t**2, t + u)) >>> s3 {(t**2, t + u)} >>> s3.subs({t: 2, u: 3}) {(4, 5)} >>> s3.subs(t, -1) {(1, u - 1)} >>> s3.subs(t, 3) {(9, u + 3)} Evaluation at specific values. Positional arguments are given in the same order as the parameters: >>> s3(-2, 3) {(4, 1)} >>> s3(5) {(25, u + 5)} >>> s3(None, 2) {(t**2, t + 2)} """ def __init__(self, symbols_seq, parameters): super().__init__() if not is_sequence(symbols_seq): raise ValueError("Symbols must be given as a sequence.") if not is_sequence(parameters): raise ValueError("Parameters must be given as a sequence.") self.symbols = tuple(symbols_seq) self.parameters = tuple(parameters) def add(self, solution): if len(solution) != len(self.symbols): raise ValueError("Solution should have a length of %s, not %s" % (len(self.symbols), len(solution))) super().add(Tuple(*solution)) def update(self, *solutions): for solution in solutions: self.add(solution) def dict_iterator(self): for solution in ordered(self): yield dict(zip(self.symbols, solution)) def subs(self, *args, **kwargs): result = DiophantineSolutionSet(self.symbols, self.parameters) for solution in self: result.add(solution.subs(*args, **kwargs)) return result def __call__(self, *args): if len(args) > len(self.parameters): raise ValueError("Evaluation should have at most %s values, not %s" % (len(self.parameters), len(args))) rep = {p: v for p, v in zip(self.parameters, args) if v is not None} return self.subs(rep) class DiophantineEquationType: """ Internal representation of a particular diophantine equation type. Parameters ========== equation : The diophantine equation that is being solved. free_symbols : list (optional) The symbols being solved for. Attributes ========== total_degree : The maximum of the degrees of all terms in the equation homogeneous : Does the equation contain a term of degree 0 homogeneous_order : Does the equation contain any coefficient that is in the symbols being solved for dimension : The number of symbols being solved for """ name = None # type: str def __init__(self, equation, free_symbols=None): self.equation = _sympify(equation).expand(force=True) if free_symbols is not None: self.free_symbols = free_symbols else: self.free_symbols = list(self.equation.free_symbols) self.free_symbols.sort(key=default_sort_key) if not self.free_symbols: raise ValueError('equation should have 1 or more free symbols') self.coeff = self.equation.as_coefficients_dict() if not all(_is_int(c) for c in self.coeff.values()): raise TypeError("Coefficients should be Integers") self.total_degree = Poly(self.equation).total_degree() self.homogeneous = 1 not in self.coeff self.homogeneous_order = not (set(self.coeff) & set(self.free_symbols)) self.dimension = len(self.free_symbols) self._parameters = None def matches(self): """ Determine whether the given equation can be matched to the particular equation type. """ return False @property def n_parameters(self): return self.dimension @property def parameters(self): if self._parameters is None: self._parameters = symbols('t_:%i' % (self.n_parameters,), integer=True) return self._parameters def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet: raise NotImplementedError('No solver has been written for %s.' % self.name) def pre_solve(self, parameters=None): if not self.matches(): raise ValueError("This equation does not match the %s equation type." % self.name) if parameters is not None: if len(parameters) != self.n_parameters: raise ValueError("Expected %s parameter(s) but got %s" % (self.n_parameters, len(parameters))) self._parameters = parameters class Univariate(DiophantineEquationType): """ Representation of a univariate diophantine equation. A univariate diophantine equation is an equation of the form `a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are integer constants and `x` is an integer variable. Examples ======== >>> from sympy.solvers.diophantine.diophantine import Univariate >>> from sympy.abc import x >>> Univariate((x - 2)*(x - 3)**2).solve() # solves equation (x - 2)*(x - 3)**2 == 0 {(2,), (3,)} """ name = 'univariate' def matches(self): return self.dimension == 1 def solve(self, parameters=None, limit=None): self.pre_solve(parameters) result = DiophantineSolutionSet(self.free_symbols, parameters=self.parameters) for i in solveset_real(self.equation, self.free_symbols[0]).intersect(S.Integers): result.add((i,)) return result class Linear(DiophantineEquationType): """ Representation of a linear diophantine equation. A linear diophantine equation is an equation of the form `a_{1}x_{1} + a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables. Examples ======== >>> from sympy.solvers.diophantine.diophantine import Linear >>> from sympy.abc import x, y, z >>> l1 = Linear(2*x - 3*y - 5) >>> l1.matches() # is this equation linear True >>> l1.solve() # solves equation 2*x - 3*y - 5 == 0 {(3*t_0 - 5, 2*t_0 - 5)} Here x = -3*t_0 - 5 and y = -2*t_0 - 5 >>> Linear(2*x - 3*y - 4*z -3).solve() {(t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3)} """ name = 'linear' def matches(self): return self.total_degree == 1 def solve(self, parameters=None, limit=None): self.pre_solve(parameters) coeff = self.coeff var = self.free_symbols if 1 in coeff: # negate coeff[] because input is of the form: ax + by + c == 0 # but is used as: ax + by == -c c = -coeff[1] else: c = 0 result = DiophantineSolutionSet(var, parameters=self.parameters) params = result.parameters if len(var) == 1: q, r = divmod(c, coeff[var[0]]) if not r: result.add((q,)) return result else: return result ''' base_solution_linear() can solve diophantine equations of the form: a*x + b*y == c We break down multivariate linear diophantine equations into a series of bivariate linear diophantine equations which can then be solved individually by base_solution_linear(). Consider the following: a_0*x_0 + a_1*x_1 + a_2*x_2 == c which can be re-written as: a_0*x_0 + g_0*y_0 == c where g_0 == gcd(a_1, a_2) and y == (a_1*x_1)/g_0 + (a_2*x_2)/g_0 This leaves us with two binary linear diophantine equations. For the first equation: a == a_0 b == g_0 c == c For the second: a == a_1/g_0 b == a_2/g_0 c == the solution we find for y_0 in the first equation. The arrays A and B are the arrays of integers used for 'a' and 'b' in each of the n-1 bivariate equations we solve. ''' A = [coeff[v] for v in var] B = [] if len(var) > 2: B.append(igcd(A[-2], A[-1])) A[-2] = A[-2] // B[0] A[-1] = A[-1] // B[0] for i in range(len(A) - 3, 0, -1): gcd = igcd(B[0], A[i]) B[0] = B[0] // gcd A[i] = A[i] // gcd B.insert(0, gcd) B.append(A[-1]) ''' Consider the trivariate linear equation: 4*x_0 + 6*x_1 + 3*x_2 == 2 This can be re-written as: 4*x_0 + 3*y_0 == 2 where y_0 == 2*x_1 + x_2 (Note that gcd(3, 6) == 3) The complete integral solution to this equation is: x_0 == 2 + 3*t_0 y_0 == -2 - 4*t_0 where 't_0' is any integer. Now that we have a solution for 'x_0', find 'x_1' and 'x_2': 2*x_1 + x_2 == -2 - 4*t_0 We can then solve for '-2' and '-4' independently, and combine the results: 2*x_1a + x_2a == -2 x_1a == 0 + t_0 x_2a == -2 - 2*t_0 2*x_1b + x_2b == -4*t_0 x_1b == 0*t_0 + t_1 x_2b == -4*t_0 - 2*t_1 ==> x_1 == t_0 + t_1 x_2 == -2 - 6*t_0 - 2*t_1 where 't_0' and 't_1' are any integers. Note that: 4*(2 + 3*t_0) + 6*(t_0 + t_1) + 3*(-2 - 6*t_0 - 2*t_1) == 2 for any integral values of 't_0', 't_1'; as required. This method is generalised for many variables, below. ''' solutions = [] for Ai, Bi in zip(A, B): tot_x, tot_y = [], [] for j, arg in enumerate(Add.make_args(c)): if arg.is_Integer: # example: 5 -> k = 5 k, p = arg, S.One pnew = params[0] else: # arg is a Mul or Symbol # example: 3*t_1 -> k = 3 # example: t_0 -> k = 1 k, p = arg.as_coeff_Mul() pnew = params[params.index(p) + 1] sol = sol_x, sol_y = base_solution_linear(k, Ai, Bi, pnew) if p is S.One: if None in sol: return result else: # convert a + b*pnew -> a*p + b*pnew if isinstance(sol_x, Add): sol_x = sol_x.args[0]*p + sol_x.args[1] if isinstance(sol_y, Add): sol_y = sol_y.args[0]*p + sol_y.args[1] tot_x.append(sol_x) tot_y.append(sol_y) solutions.append(Add(*tot_x)) c = Add(*tot_y) solutions.append(c) result.add(solutions) return result class BinaryQuadratic(DiophantineEquationType): """ Representation of a binary quadratic diophantine equation. A binary quadratic diophantine equation is an equation of the form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`, where `A, B, C, D, E, F` are integer constants and `x` and `y` are integer variables. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import BinaryQuadratic >>> b1 = BinaryQuadratic(x**3 + y**2 + 1) >>> b1.matches() False >>> b2 = BinaryQuadratic(x**2 + y**2 + 2*x + 2*y + 2) >>> b2.matches() True >>> b2.solve() {(-1, -1)} References ========== .. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online], Available: http://www.alpertron.com.ar/METHODS.HTM .. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online], Available: https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf """ name = 'binary_quadratic' def matches(self): return self.total_degree == 2 and self.dimension == 2 def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet: self.pre_solve(parameters) var = self.free_symbols coeff = self.coeff x, y = var A = coeff[x**2] B = coeff[x*y] C = coeff[y**2] D = coeff[x] E = coeff[y] F = coeff[S.One] A, B, C, D, E, F = [as_int(i) for i in _remove_gcd(A, B, C, D, E, F)] # (1) Simple-Hyperbolic case: A = C = 0, B != 0 # In this case equation can be converted to (Bx + E)(By + D) = DE - BF # We consider two cases; DE - BF = 0 and DE - BF != 0 # More details, http://www.alpertron.com.ar/METHODS.HTM#SHyperb result = DiophantineSolutionSet(var, self.parameters) t, u = result.parameters discr = B**2 - 4*A*C if A == 0 and C == 0 and B != 0: if D*E - B*F == 0: q, r = divmod(E, B) if not r: result.add((-q, t)) q, r = divmod(D, B) if not r: result.add((t, -q)) else: div = divisors(D*E - B*F) div = div + [-term for term in div] for d in div: x0, r = divmod(d - E, B) if not r: q, r = divmod(D*E - B*F, d) if not r: y0, r = divmod(q - D, B) if not r: result.add((x0, y0)) # (2) Parabolic case: B**2 - 4*A*C = 0 # There are two subcases to be considered in this case. # sqrt(c)D - sqrt(a)E = 0 and sqrt(c)D - sqrt(a)E != 0 # More Details, http://www.alpertron.com.ar/METHODS.HTM#Parabol elif discr == 0: if A == 0: s = BinaryQuadratic(self.equation, free_symbols=[y, x]).solve(parameters=[t, u]) for soln in s: result.add((soln[1], soln[0])) else: g = sign(A)*igcd(A, C) a = A // g c = C // g e = sign(B / A) sqa = isqrt(a) sqc = isqrt(c) _c = e*sqc*D - sqa*E if not _c: z = Symbol("z", real=True) eq = sqa*g*z**2 + D*z + sqa*F roots = solveset_real(eq, z).intersect(S.Integers) for root in roots: ans = diop_solve(sqa*x + e*sqc*y - root) result.add((ans[0], ans[1])) elif _is_int(c): solve_x = lambda u: -e*sqc*g*_c*t**2 - (E + 2*e*sqc*g*u)*t \ - (e*sqc*g*u**2 + E*u + e*sqc*F) // _c solve_y = lambda u: sqa*g*_c*t**2 + (D + 2*sqa*g*u)*t \ + (sqa*g*u**2 + D*u + sqa*F) // _c for z0 in range(0, abs(_c)): # Check if the coefficients of y and x obtained are integers or not if (divisible(sqa*g*z0**2 + D*z0 + sqa*F, _c) and divisible(e*sqc*g*z0**2 + E*z0 + e*sqc*F, _c)): result.add((solve_x(z0), solve_y(z0))) # (3) Method used when B**2 - 4*A*C is a square, is described in p. 6 of the below paper # by John P. Robertson. # https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf elif is_square(discr): if A != 0: r = sqrt(discr) u, v = symbols("u, v", integer=True) eq = _mexpand( 4*A*r*u*v + 4*A*D*(B*v + r*u + r*v - B*u) + 2*A*4*A*E*(u - v) + 4*A*r*4*A*F) solution = diop_solve(eq, t) for s0, t0 in solution: num = B*t0 + r*s0 + r*t0 - B*s0 x_0 = S(num) / (4*A*r) y_0 = S(s0 - t0) / (2*r) if isinstance(s0, Symbol) or isinstance(t0, Symbol): if len(check_param(x_0, y_0, 4*A*r, parameters)) > 0: ans = check_param(x_0, y_0, 4*A*r, parameters) result.update(*ans) elif x_0.is_Integer and y_0.is_Integer: if is_solution_quad(var, coeff, x_0, y_0): result.add((x_0, y_0)) else: s = BinaryQuadratic(self.equation, free_symbols=var[::-1]).solve(parameters=[t, u]) # Interchange x and y while s: result.add(s.pop()[::-1]) # and solution <--------+ # (4) B**2 - 4*A*C > 0 and B**2 - 4*A*C not a square or B**2 - 4*A*C < 0 else: P, Q = _transformation_to_DN(var, coeff) D, N = _find_DN(var, coeff) solns_pell = diop_DN(D, N) if D < 0: for x0, y0 in solns_pell: for x in [-x0, x0]: for y in [-y0, y0]: s = P*Matrix([x, y]) + Q try: result.add([as_int(_) for _ in s]) except ValueError: pass else: # In this case equation can be transformed into a Pell equation solns_pell = set(solns_pell) for X, Y in list(solns_pell): solns_pell.add((-X, -Y)) a = diop_DN(D, 1) T = a[0][0] U = a[0][1] if all(_is_int(_) for _ in P[:4] + Q[:2]): for r, s in solns_pell: _a = (r + s*sqrt(D))*(T + U*sqrt(D))**t _b = (r - s*sqrt(D))*(T - U*sqrt(D))**t x_n = _mexpand(S(_a + _b) / 2) y_n = _mexpand(S(_a - _b) / (2*sqrt(D))) s = P*Matrix([x_n, y_n]) + Q result.add(s) else: L = ilcm(*[_.q for _ in P[:4] + Q[:2]]) k = 1 T_k = T U_k = U while (T_k - 1) % L != 0 or U_k % L != 0: T_k, U_k = T_k*T + D*U_k*U, T_k*U + U_k*T k += 1 for X, Y in solns_pell: for i in range(k): if all(_is_int(_) for _ in P*Matrix([X, Y]) + Q): _a = (X + sqrt(D)*Y)*(T_k + sqrt(D)*U_k)**t _b = (X - sqrt(D)*Y)*(T_k - sqrt(D)*U_k)**t Xt = S(_a + _b) / 2 Yt = S(_a - _b) / (2*sqrt(D)) s = P*Matrix([Xt, Yt]) + Q result.add(s) X, Y = X*T + D*U*Y, X*U + Y*T return result class InhomogeneousTernaryQuadratic(DiophantineEquationType): """ Representation of an inhomogeneous ternary quadratic. No solver is currently implemented for this equation type. """ name = 'inhomogeneous_ternary_quadratic' def matches(self): if not (self.total_degree == 2 and self.dimension == 3): return False if not self.homogeneous: return False return not self.homogeneous_order class HomogeneousTernaryQuadraticNormal(DiophantineEquationType): """ Representation of a homogeneous ternary quadratic normal diophantine equation. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import HomogeneousTernaryQuadraticNormal >>> HomogeneousTernaryQuadraticNormal(4*x**2 - 5*y**2 + z**2).solve() {(1, 2, 4)} """ name = 'homogeneous_ternary_quadratic_normal' def matches(self): if not (self.total_degree == 2 and self.dimension == 3): return False if not self.homogeneous: return False if not self.homogeneous_order: return False nonzero = [k for k in self.coeff if self.coeff[k]] return len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols) def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet: self.pre_solve(parameters) var = self.free_symbols coeff = self.coeff x, y, z = var a = coeff[x**2] b = coeff[y**2] c = coeff[z**2] (sqf_of_a, sqf_of_b, sqf_of_c), (a_1, b_1, c_1), (a_2, b_2, c_2) = \ sqf_normal(a, b, c, steps=True) A = -a_2*c_2 B = -b_2*c_2 result = DiophantineSolutionSet(var, parameters=self.parameters) # If following two conditions are satisfied then there are no solutions if A < 0 and B < 0: return result if ( sqrt_mod(-b_2*c_2, a_2) is None or sqrt_mod(-c_2*a_2, b_2) is None or sqrt_mod(-a_2*b_2, c_2) is None): return result z_0, x_0, y_0 = descent(A, B) z_0, q = _rational_pq(z_0, abs(c_2)) x_0 *= q y_0 *= q x_0, y_0, z_0 = _remove_gcd(x_0, y_0, z_0) # Holzer reduction if sign(a) == sign(b): x_0, y_0, z_0 = holzer(x_0, y_0, z_0, abs(a_2), abs(b_2), abs(c_2)) elif sign(a) == sign(c): x_0, z_0, y_0 = holzer(x_0, z_0, y_0, abs(a_2), abs(c_2), abs(b_2)) else: y_0, z_0, x_0 = holzer(y_0, z_0, x_0, abs(b_2), abs(c_2), abs(a_2)) x_0 = reconstruct(b_1, c_1, x_0) y_0 = reconstruct(a_1, c_1, y_0) z_0 = reconstruct(a_1, b_1, z_0) sq_lcm = ilcm(sqf_of_a, sqf_of_b, sqf_of_c) x_0 = abs(x_0*sq_lcm // sqf_of_a) y_0 = abs(y_0*sq_lcm // sqf_of_b) z_0 = abs(z_0*sq_lcm // sqf_of_c) result.add(_remove_gcd(x_0, y_0, z_0)) return result class HomogeneousTernaryQuadratic(DiophantineEquationType): """ Representation of a homogeneous ternary quadratic diophantine equation. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import HomogeneousTernaryQuadratic >>> HomogeneousTernaryQuadratic(x**2 + y**2 - 3*z**2 + x*y).solve() {(-1, 2, 1)} >>> HomogeneousTernaryQuadratic(3*x**2 + y**2 - 3*z**2 + 5*x*y + y*z).solve() {(3, 12, 13)} """ name = 'homogeneous_ternary_quadratic' def matches(self): if not (self.total_degree == 2 and self.dimension == 3): return False if not self.homogeneous: return False if not self.homogeneous_order: return False nonzero = [k for k in self.coeff if self.coeff[k]] return not (len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols)) def solve(self, parameters=None, limit=None): self.pre_solve(parameters) _var = self.free_symbols coeff = self.coeff x, y, z = _var var = [x, y, z] # Equations of the form B*x*y + C*z*x + E*y*z = 0 and At least two of the # coefficients A, B, C are non-zero. # There are infinitely many solutions for the equation. # Ex: (0, 0, t), (0, t, 0), (t, 0, 0) # Equation can be re-written as y*(B*x + E*z) = -C*x*z and we can find rather # unobvious solutions. Set y = -C and B*x + E*z = x*z. The latter can be solved by # using methods for binary quadratic diophantine equations. Let's select the # solution which minimizes |x| + |z| result = DiophantineSolutionSet(var, parameters=self.parameters) def unpack_sol(sol): if len(sol) > 0: return list(sol)[0] return None, None, None if not any(coeff[i**2] for i in var): if coeff[x*z]: sols = diophantine(coeff[x*y]*x + coeff[y*z]*z - x*z) s = sols.pop() min_sum = abs(s[0]) + abs(s[1]) for r in sols: m = abs(r[0]) + abs(r[1]) if m < min_sum: s = r min_sum = m result.add(_remove_gcd(s[0], -coeff[x*z], s[1])) return result else: var[0], var[1] = _var[1], _var[0] y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) if x_0 is not None: result.add((x_0, y_0, z_0)) return result if coeff[x**2] == 0: # If the coefficient of x is zero change the variables if coeff[y**2] == 0: var[0], var[2] = _var[2], _var[0] z_0, y_0, x_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) else: var[0], var[1] = _var[1], _var[0] y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) else: if coeff[x*y] or coeff[x*z]: # Apply the transformation x --> X - (B*y + C*z)/(2*A) A = coeff[x**2] B = coeff[x*y] C = coeff[x*z] D = coeff[y**2] E = coeff[y*z] F = coeff[z**2] _coeff = {} _coeff[x**2] = 4*A**2 _coeff[y**2] = 4*A*D - B**2 _coeff[z**2] = 4*A*F - C**2 _coeff[y*z] = 4*A*E - 2*B*C _coeff[x*y] = 0 _coeff[x*z] = 0 x_0, y_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, _coeff)) if x_0 is None: return result p, q = _rational_pq(B*y_0 + C*z_0, 2*A) x_0, y_0, z_0 = x_0*q - p, y_0*q, z_0*q elif coeff[z*y] != 0: if coeff[y**2] == 0: if coeff[z**2] == 0: # Equations of the form A*x**2 + E*yz = 0. A = coeff[x**2] E = coeff[y*z] b, a = _rational_pq(-E, A) x_0, y_0, z_0 = b, a, b else: # Ax**2 + E*y*z + F*z**2 = 0 var[0], var[2] = _var[2], _var[0] z_0, y_0, x_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) else: # A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, C may be zero var[0], var[1] = _var[1], _var[0] y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) else: # Ax**2 + D*y**2 + F*z**2 = 0, C may be zero x_0, y_0, z_0 = unpack_sol(_diop_ternary_quadratic_normal(var, coeff)) if x_0 is None: return result result.add(_remove_gcd(x_0, y_0, z_0)) return result class InhomogeneousGeneralQuadratic(DiophantineEquationType): """ Representation of an inhomogeneous general quadratic. No solver is currently implemented for this equation type. """ name = 'inhomogeneous_general_quadratic' def matches(self): if not (self.total_degree == 2 and self.dimension >= 3): return False if not self.homogeneous_order: return True else: # there may be Pow keys like x**2 or Mul keys like x*y if any(k.is_Mul for k in self.coeff): # cross terms return not self.homogeneous return False class HomogeneousGeneralQuadratic(DiophantineEquationType): """ Representation of a homogeneous general quadratic. No solver is currently implemented for this equation type. """ name = 'homogeneous_general_quadratic' def matches(self): if not (self.total_degree == 2 and self.dimension >= 3): return False if not self.homogeneous_order: return False else: # there may be Pow keys like x**2 or Mul keys like x*y if any(k.is_Mul for k in self.coeff): # cross terms return self.homogeneous return False class GeneralSumOfSquares(DiophantineEquationType): r""" Representation of the diophantine equation `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`. Details ======= When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be no solutions. Refer [1]_ for more details. Examples ======== >>> from sympy.solvers.diophantine.diophantine import GeneralSumOfSquares >>> from sympy.abc import a, b, c, d, e >>> GeneralSumOfSquares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345).solve() {(15, 22, 22, 24, 24)} By default only 1 solution is returned. Use the `limit` keyword for more: >>> sorted(GeneralSumOfSquares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345).solve(limit=3)) [(15, 22, 22, 24, 24), (16, 19, 24, 24, 24), (16, 20, 22, 23, 26)] References ========== .. [1] Representing an integer as a sum of three squares, [online], Available: http://www.proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares """ name = 'general_sum_of_squares' def matches(self): if not (self.total_degree == 2 and self.dimension >= 3): return False if not self.homogeneous_order: return False if any(k.is_Mul for k in self.coeff): return False return all(self.coeff[k] == 1 for k in self.coeff if k != 1) def solve(self, parameters=None, limit=1): self.pre_solve(parameters) var = self.free_symbols k = -int(self.coeff[1]) n = self.dimension result = DiophantineSolutionSet(var, parameters=self.parameters) if k < 0 or limit < 1: return result signs = [-1 if x.is_nonpositive else 1 for x in var] negs = signs.count(-1) != 0 took = 0 for t in sum_of_squares(k, n, zeros=True): if negs: result.add([signs[i]*j for i, j in enumerate(t)]) else: result.add(t) took += 1 if took == limit: break return result class GeneralPythagorean(DiophantineEquationType): """ Representation of the general pythagorean equation, `a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import GeneralPythagorean >>> from sympy.abc import a, b, c, d, e, x, y, z, t >>> GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve() {(t_0**2 + t_1**2 - t_2**2, 2*t_0*t_2, 2*t_1*t_2, t_0**2 + t_1**2 + t_2**2)} >>> GeneralPythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2).solve(parameters=[x, y, z, t]) {(-10*t**2 + 10*x**2 + 10*y**2 + 10*z**2, 15*t**2 + 15*x**2 + 15*y**2 + 15*z**2, 15*t*x, 12*t*y, 60*t*z)} """ name = 'general_pythagorean' def matches(self): if not (self.total_degree == 2 and self.dimension >= 3): return False if not self.homogeneous_order: return False if any(k.is_Mul for k in self.coeff): return False if all(self.coeff[k] == 1 for k in self.coeff if k != 1): return False if not all(is_square(abs(self.coeff[k])) for k in self.coeff): return False # all but one has the same sign # e.g. 4*x**2 + y**2 - 4*z**2 return abs(sum(sign(self.coeff[k]) for k in self.coeff)) == self.dimension - 2 @property def n_parameters(self): return self.dimension - 1 def solve(self, parameters=None, limit=1): self.pre_solve(parameters) coeff = self.coeff var = self.free_symbols n = self.dimension if sign(coeff[var[0] ** 2]) + sign(coeff[var[1] ** 2]) + sign(coeff[var[2] ** 2]) < 0: for key in coeff.keys(): coeff[key] = -coeff[key] result = DiophantineSolutionSet(var, parameters=self.parameters) index = 0 for i, v in enumerate(var): if sign(coeff[v ** 2]) == -1: index = i m = result.parameters ith = sum(m_i ** 2 for m_i in m) L = [ith - 2 * m[n - 2] ** 2] L.extend([2 * m[i] * m[n - 2] for i in range(n - 2)]) sol = L[:index] + [ith] + L[index:] lcm = 1 for i, v in enumerate(var): if i == index or (index > 0 and i == 0) or (index == 0 and i == 1): lcm = ilcm(lcm, sqrt(abs(coeff[v ** 2]))) else: s = sqrt(coeff[v ** 2]) lcm = ilcm(lcm, s if _odd(s) else s // 2) for i, v in enumerate(var): sol[i] = (lcm * sol[i]) / sqrt(abs(coeff[v ** 2])) result.add(sol) return result class CubicThue(DiophantineEquationType): """ Representation of a cubic Thue diophantine equation. A cubic Thue diophantine equation is a polynomial of the form `f(x, y) = r` of degree 3, where `x` and `y` are integers and `r` is a rational number. No solver is currently implemented for this equation type. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import CubicThue >>> c1 = CubicThue(x**3 + y**2 + 1) >>> c1.matches() True """ name = 'cubic_thue' def matches(self): return self.total_degree == 3 and self.dimension == 2 class GeneralSumOfEvenPowers(DiophantineEquationType): """ Representation of the diophantine equation `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0` where `e` is an even, integer power. Examples ======== >>> from sympy.solvers.diophantine.diophantine import GeneralSumOfEvenPowers >>> from sympy.abc import a, b >>> GeneralSumOfEvenPowers(a**4 + b**4 - (2**4 + 3**4)).solve() {(2, 3)} """ name = 'general_sum_of_even_powers' def matches(self): if not self.total_degree > 3: return False if self.total_degree % 2 != 0: return False if not all(k.is_Pow and k.exp == self.total_degree for k in self.coeff if k != 1): return False return all(self.coeff[k] == 1 for k in self.coeff if k != 1) def solve(self, parameters=None, limit=1): self.pre_solve(parameters) var = self.free_symbols coeff = self.coeff p = None for q in coeff.keys(): if q.is_Pow and coeff[q]: p = q.exp k = len(var) n = -coeff[1] result = DiophantineSolutionSet(var, parameters=self.parameters) if n < 0 or limit < 1: return result sign = [-1 if x.is_nonpositive else 1 for x in var] negs = sign.count(-1) != 0 took = 0 for t in power_representation(n, p, k): if negs: result.add([sign[i]*j for i, j in enumerate(t)]) else: result.add(t) took += 1 if took == limit: break return result # these types are known (but not necessarily handled) # note that order is important here (in the current solver state) all_diop_classes = [ Linear, Univariate, BinaryQuadratic, InhomogeneousTernaryQuadratic, HomogeneousTernaryQuadraticNormal, HomogeneousTernaryQuadratic, InhomogeneousGeneralQuadratic, HomogeneousGeneralQuadratic, GeneralSumOfSquares, GeneralPythagorean, CubicThue, GeneralSumOfEvenPowers, ] diop_known = {diop_class.name for diop_class in all_diop_classes} def _is_int(i): try: as_int(i) return True except ValueError: pass def _sorted_tuple(*i): return tuple(sorted(i)) def _remove_gcd(*x): try: g = igcd(*x) except ValueError: fx = list(filter(None, x)) if len(fx) < 2: return x g = igcd(*[i.as_content_primitive()[0] for i in fx]) except TypeError: raise TypeError('_remove_gcd(a,b,c) or _remove_gcd(*container)') if g == 1: return x return tuple([i//g for i in x]) def _rational_pq(a, b): # return `(numer, denom)` for a/b; sign in numer and gcd removed return _remove_gcd(sign(b)*a, abs(b)) def _nint_or_floor(p, q): # return nearest int to p/q; in case of tie return floor(p/q) w, r = divmod(p, q) if abs(r) <= abs(q)//2: return w return w + 1 def _odd(i): return i % 2 != 0 def _even(i): return i % 2 == 0 def diophantine(eq, param=symbols("t", integer=True), syms=None, permute=False): """ Simplify the solution procedure of diophantine equation ``eq`` by converting it into a product of terms which should equal zero. Explanation =========== For example, when solving, `x^2 - y^2 = 0` this is treated as `(x + y)(x - y) = 0` and `x + y = 0` and `x - y = 0` are solved independently and combined. Each term is solved by calling ``diop_solve()``. (Although it is possible to call ``diop_solve()`` directly, one must be careful to pass an equation in the correct form and to interpret the output correctly; ``diophantine()`` is the public-facing function to use in general.) Output of ``diophantine()`` is a set of tuples. The elements of the tuple are the solutions for each variable in the equation and are arranged according to the alphabetic ordering of the variables. e.g. For an equation with two variables, `a` and `b`, the first element of the tuple is the solution for `a` and the second for `b`. Usage ===== ``diophantine(eq, t, syms)``: Solve the diophantine equation ``eq``. ``t`` is the optional parameter to be used by ``diop_solve()``. ``syms`` is an optional list of symbols which determines the order of the elements in the returned tuple. By default, only the base solution is returned. If ``permute`` is set to True then permutations of the base solution and/or permutations of the signs of the values will be returned when applicable. Examples ======== >>> from sympy import diophantine >>> from sympy.abc import a, b >>> eq = a**4 + b**4 - (2**4 + 3**4) >>> diophantine(eq) {(2, 3)} >>> diophantine(eq, permute=True) {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)} Details ======= ``eq`` should be an expression which is assumed to be zero. ``t`` is the parameter to be used in the solution. Examples ======== >>> from sympy.abc import x, y, z >>> diophantine(x**2 - y**2) {(t_0, -t_0), (t_0, t_0)} >>> diophantine(x*(2*x + 3*y - z)) {(0, n1, n2), (t_0, t_1, 2*t_0 + 3*t_1)} >>> diophantine(x**2 + 3*x*y + 4*x) {(0, n1), (3*t_0 - 4, -t_0)} See Also ======== diop_solve() sympy.utilities.iterables.permute_signs sympy.utilities.iterables.signed_permutations """ eq = _sympify(eq) if isinstance(eq, Eq): eq = eq.lhs - eq.rhs try: var = list(eq.expand(force=True).free_symbols) var.sort(key=default_sort_key) if syms: if not is_sequence(syms): raise TypeError( 'syms should be given as a sequence, e.g. a list') syms = [i for i in syms if i in var] if syms != var: dict_sym_index = dict(zip(syms, range(len(syms)))) return {tuple([t[dict_sym_index[i]] for i in var]) for t in diophantine(eq, param, permute=permute)} n, d = eq.as_numer_denom() if n.is_number: return set() if not d.is_number: dsol = diophantine(d) good = diophantine(n) - dsol return {s for s in good if _mexpand(d.subs(zip(var, s)))} else: eq = n eq = factor_terms(eq) assert not eq.is_number eq = eq.as_independent(*var, as_Add=False)[1] p = Poly(eq) assert not any(g.is_number for g in p.gens) eq = p.as_expr() assert eq.is_polynomial() except (GeneratorsNeeded, AssertionError): raise TypeError(filldedent(''' Equation should be a polynomial with Rational coefficients.''')) # permute only sign do_permute_signs = False # permute sign and values do_permute_signs_var = False # permute few signs permute_few_signs = False try: # if we know that factoring should not be attempted, skip # the factoring step v, c, t = classify_diop(eq) # check for permute sign if permute: len_var = len(v) permute_signs_for = [ GeneralSumOfSquares.name, GeneralSumOfEvenPowers.name] permute_signs_check = [ HomogeneousTernaryQuadratic.name, HomogeneousTernaryQuadraticNormal.name, BinaryQuadratic.name] if t in permute_signs_for: do_permute_signs_var = True elif t in permute_signs_check: # if all the variables in eq have even powers # then do_permute_sign = True if len_var == 3: var_mul = list(subsets(v, 2)) # here var_mul is like [(x, y), (x, z), (y, z)] xy_coeff = True x_coeff = True var1_mul_var2 = map(lambda a: a[0]*a[1], var_mul) # if coeff(y*z), coeff(y*x), coeff(x*z) is not 0 then # `xy_coeff` => True and do_permute_sign => False. # Means no permuted solution. for v1_mul_v2 in var1_mul_var2: try: coeff = c[v1_mul_v2] except KeyError: coeff = 0 xy_coeff = bool(xy_coeff) and bool(coeff) var_mul = list(subsets(v, 1)) # here var_mul is like [(x,), (y, )] for v1 in var_mul: try: coeff = c[v1[0]] except KeyError: coeff = 0 x_coeff = bool(x_coeff) and bool(coeff) if not any((xy_coeff, x_coeff)): # means only x**2, y**2, z**2, const is present do_permute_signs = True elif not x_coeff: permute_few_signs = True elif len_var == 2: var_mul = list(subsets(v, 2)) # here var_mul is like [(x, y)] xy_coeff = True x_coeff = True var1_mul_var2 = map(lambda x: x[0]*x[1], var_mul) for v1_mul_v2 in var1_mul_var2: try: coeff = c[v1_mul_v2] except KeyError: coeff = 0 xy_coeff = bool(xy_coeff) and bool(coeff) var_mul = list(subsets(v, 1)) # here var_mul is like [(x,), (y, )] for v1 in var_mul: try: coeff = c[v1[0]] except KeyError: coeff = 0 x_coeff = bool(x_coeff) and bool(coeff) if not any((xy_coeff, x_coeff)): # means only x**2, y**2 and const is present # so we can get more soln by permuting this soln. do_permute_signs = True elif not x_coeff: # when coeff(x), coeff(y) is not present then signs of # x, y can be permuted such that their sign are same # as sign of x*y. # e.g 1. (x_val,y_val)=> (x_val,y_val), (-x_val,-y_val) # 2. (-x_vall, y_val)=> (-x_val,y_val), (x_val,-y_val) permute_few_signs = True if t == 'general_sum_of_squares': # trying to factor such expressions will sometimes hang terms = [(eq, 1)] else: raise TypeError except (TypeError, NotImplementedError): fl = factor_list(eq) if fl[0].is_Rational and fl[0] != 1: return diophantine(eq/fl[0], param=param, syms=syms, permute=permute) terms = fl[1] sols = set() for term in terms: base, _ = term var_t, _, eq_type = classify_diop(base, _dict=False) _, base = signsimp(base, evaluate=False).as_coeff_Mul() solution = diop_solve(base, param) if eq_type in [ Linear.name, HomogeneousTernaryQuadratic.name, HomogeneousTernaryQuadraticNormal.name, GeneralPythagorean.name]: sols.add(merge_solution(var, var_t, solution)) elif eq_type in [ BinaryQuadratic.name, GeneralSumOfSquares.name, GeneralSumOfEvenPowers.name, Univariate.name]: for sol in solution: sols.add(merge_solution(var, var_t, sol)) else: raise NotImplementedError('unhandled type: %s' % eq_type) # remove null merge results if () in sols: sols.remove(()) null = tuple([0]*len(var)) # if there is no solution, return trivial solution if not sols and eq.subs(zip(var, null)).is_zero: sols.add(null) final_soln = set() for sol in sols: if all(_is_int(s) for s in sol): if do_permute_signs: permuted_sign = set(permute_signs(sol)) final_soln.update(permuted_sign) elif permute_few_signs: lst = list(permute_signs(sol)) lst = list(filter(lambda x: x[0]*x[1] == sol[1]*sol[0], lst)) permuted_sign = set(lst) final_soln.update(permuted_sign) elif do_permute_signs_var: permuted_sign_var = set(signed_permutations(sol)) final_soln.update(permuted_sign_var) else: final_soln.add(sol) else: final_soln.add(sol) return final_soln def merge_solution(var, var_t, solution): """ This is used to construct the full solution from the solutions of sub equations. Explanation =========== For example when solving the equation `(x - y)(x^2 + y^2 - z^2) = 0`, solutions for each of the equations `x - y = 0` and `x^2 + y^2 - z^2` are found independently. Solutions for `x - y = 0` are `(x, y) = (t, t)`. But we should introduce a value for z when we output the solution for the original equation. This function converts `(t, t)` into `(t, t, n_{1})` where `n_{1}` is an integer parameter. """ sol = [] if None in solution: return () solution = iter(solution) params = numbered_symbols("n", integer=True, start=1) for v in var: if v in var_t: sol.append(next(solution)) else: sol.append(next(params)) for val, symb in zip(sol, var): if check_assumptions(val, **symb.assumptions0) is False: return tuple() return tuple(sol) def _diop_solve(eq, params=None): for diop_type in all_diop_classes: if diop_type(eq).matches(): return diop_type(eq).solve(parameters=params) def diop_solve(eq, param=symbols("t", integer=True)): """ Solves the diophantine equation ``eq``. Explanation =========== Unlike ``diophantine()``, factoring of ``eq`` is not attempted. Uses ``classify_diop()`` to determine the type of the equation and calls the appropriate solver function. Use of ``diophantine()`` is recommended over other helper functions. ``diop_solve()`` can return either a set or a tuple depending on the nature of the equation. Usage ===== ``diop_solve(eq, t)``: Solve diophantine equation, ``eq`` using ``t`` as a parameter if needed. Details ======= ``eq`` should be an expression which is assumed to be zero. ``t`` is a parameter to be used in the solution. Examples ======== >>> from sympy.solvers.diophantine import diop_solve >>> from sympy.abc import x, y, z, w >>> diop_solve(2*x + 3*y - 5) (3*t_0 - 5, 5 - 2*t_0) >>> diop_solve(4*x + 3*y - 4*z + 5) (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5) >>> diop_solve(x + 3*y - 4*z + w - 6) (t_0, t_0 + t_1, 6*t_0 + 5*t_1 + 4*t_2 - 6, 5*t_0 + 4*t_1 + 3*t_2 - 6) >>> diop_solve(x**2 + y**2 - 5) {(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)} See Also ======== diophantine() """ var, coeff, eq_type = classify_diop(eq, _dict=False) if eq_type == Linear.name: return diop_linear(eq, param) elif eq_type == BinaryQuadratic.name: return diop_quadratic(eq, param) elif eq_type == HomogeneousTernaryQuadratic.name: return diop_ternary_quadratic(eq, parameterize=True) elif eq_type == HomogeneousTernaryQuadraticNormal.name: return diop_ternary_quadratic_normal(eq, parameterize=True) elif eq_type == GeneralPythagorean.name: return diop_general_pythagorean(eq, param) elif eq_type == Univariate.name: return diop_univariate(eq) elif eq_type == GeneralSumOfSquares.name: return diop_general_sum_of_squares(eq, limit=S.Infinity) elif eq_type == GeneralSumOfEvenPowers.name: return diop_general_sum_of_even_powers(eq, limit=S.Infinity) if eq_type is not None and eq_type not in diop_known: raise ValueError(filldedent(''' Alhough this type of equation was identified, it is not yet handled. It should, however, be listed in `diop_known` at the top of this file. Developers should see comments at the end of `classify_diop`. ''')) # pragma: no cover else: raise NotImplementedError( 'No solver has been written for %s.' % eq_type) def classify_diop(eq, _dict=True): # docstring supplied externally matched = False diop_type = None for diop_class in all_diop_classes: diop_type = diop_class(eq) if diop_type.matches(): matched = True break if matched: return diop_type.free_symbols, dict(diop_type.coeff) if _dict else diop_type.coeff, diop_type.name # new diop type instructions # -------------------------- # if this error raises and the equation *can* be classified, # * it should be identified in the if-block above # * the type should be added to the diop_known # if a solver can be written for it, # * a dedicated handler should be written (e.g. diop_linear) # * it should be passed to that handler in diop_solve raise NotImplementedError(filldedent(''' This equation is not yet recognized or else has not been simplified sufficiently to put it in a form recognized by diop_classify().''')) classify_diop.func_doc = ( # type: ignore ''' Helper routine used by diop_solve() to find information about ``eq``. Explanation =========== Returns a tuple containing the type of the diophantine equation along with the variables (free symbols) and their coefficients. Variables are returned as a list and coefficients are returned as a dict with the key being the respective term and the constant term is keyed to 1. The type is one of the following: * %s Usage ===== ``classify_diop(eq)``: Return variables, coefficients and type of the ``eq``. Details ======= ``eq`` should be an expression which is assumed to be zero. ``_dict`` is for internal use: when True (default) a dict is returned, otherwise a defaultdict which supplies 0 for missing keys is returned. Examples ======== >>> from sympy.solvers.diophantine import classify_diop >>> from sympy.abc import x, y, z, w, t >>> classify_diop(4*x + 6*y - 4) ([x, y], {1: -4, x: 4, y: 6}, 'linear') >>> classify_diop(x + 3*y -4*z + 5) ([x, y, z], {1: 5, x: 1, y: 3, z: -4}, 'linear') >>> classify_diop(x**2 + y**2 - x*y + x + 5) ([x, y], {1: 5, x: 1, x**2: 1, y**2: 1, x*y: -1}, 'binary_quadratic') ''' % ('\n * '.join(sorted(diop_known)))) def diop_linear(eq, param=symbols("t", integer=True)): """ Solves linear diophantine equations. A linear diophantine equation is an equation of the form `a_{1}x_{1} + a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables. Usage ===== ``diop_linear(eq)``: Returns a tuple containing solutions to the diophantine equation ``eq``. Values in the tuple is arranged in the same order as the sorted variables. Details ======= ``eq`` is a linear diophantine equation which is assumed to be zero. ``param`` is the parameter to be used in the solution. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_linear >>> from sympy.abc import x, y, z >>> diop_linear(2*x - 3*y - 5) # solves equation 2*x - 3*y - 5 == 0 (3*t_0 - 5, 2*t_0 - 5) Here x = -3*t_0 - 5 and y = -2*t_0 - 5 >>> diop_linear(2*x - 3*y - 4*z -3) (t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3) See Also ======== diop_quadratic(), diop_ternary_quadratic(), diop_general_pythagorean(), diop_general_sum_of_squares() """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == Linear.name: parameters = None if param is not None: parameters = symbols('%s_0:%i' % (param, len(var)), integer=True) result = Linear(eq).solve(parameters=parameters) if param is None: result = result(*[0]*len(result.parameters)) if len(result) > 0: return list(result)[0] else: return tuple([None]*len(result.parameters)) def base_solution_linear(c, a, b, t=None): """ Return the base solution for the linear equation, `ax + by = c`. Explanation =========== Used by ``diop_linear()`` to find the base solution of a linear Diophantine equation. If ``t`` is given then the parametrized solution is returned. Usage ===== ``base_solution_linear(c, a, b, t)``: ``a``, ``b``, ``c`` are coefficients in `ax + by = c` and ``t`` is the parameter to be used in the solution. Examples ======== >>> from sympy.solvers.diophantine.diophantine import base_solution_linear >>> from sympy.abc import t >>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5 (-5, 5) >>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0 (0, 0) >>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5 (3*t - 5, 5 - 2*t) >>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0 (7*t, -5*t) """ a, b, c = _remove_gcd(a, b, c) if c == 0: if t is not None: if b < 0: t = -t return (b*t, -a*t) else: return (0, 0) else: x0, y0, d = igcdex(abs(a), abs(b)) x0 *= sign(a) y0 *= sign(b) if divisible(c, d): if t is not None: if b < 0: t = -t return (c*x0 + b*t, c*y0 - a*t) else: return (c*x0, c*y0) else: return (None, None) def diop_univariate(eq): """ Solves a univariate diophantine equations. Explanation =========== A univariate diophantine equation is an equation of the form `a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are integer constants and `x` is an integer variable. Usage ===== ``diop_univariate(eq)``: Returns a set containing solutions to the diophantine equation ``eq``. Details ======= ``eq`` is a univariate diophantine equation which is assumed to be zero. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_univariate >>> from sympy.abc import x >>> diop_univariate((x - 2)*(x - 3)**2) # solves equation (x - 2)*(x - 3)**2 == 0 {(2,), (3,)} """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == Univariate.name: return {(int(i),) for i in solveset_real( eq, var[0]).intersect(S.Integers)} def divisible(a, b): """ Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise. """ return not a % b def diop_quadratic(eq, param=symbols("t", integer=True)): """ Solves quadratic diophantine equations. i.e. equations of the form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`. Returns a set containing the tuples `(x, y)` which contains the solutions. If there are no solutions then `(None, None)` is returned. Usage ===== ``diop_quadratic(eq, param)``: ``eq`` is a quadratic binary diophantine equation. ``param`` is used to indicate the parameter to be used in the solution. Details ======= ``eq`` should be an expression which is assumed to be zero. ``param`` is a parameter to be used in the solution. Examples ======== >>> from sympy.abc import x, y, t >>> from sympy.solvers.diophantine.diophantine import diop_quadratic >>> diop_quadratic(x**2 + y**2 + 2*x + 2*y + 2, t) {(-1, -1)} References ========== .. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online], Available: http://www.alpertron.com.ar/METHODS.HTM .. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online], Available: https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf See Also ======== diop_linear(), diop_ternary_quadratic(), diop_general_sum_of_squares(), diop_general_pythagorean() """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == BinaryQuadratic.name: if param is not None: parameters = [param, Symbol("u", integer=True)] else: parameters = None return set(BinaryQuadratic(eq).solve(parameters=parameters)) def is_solution_quad(var, coeff, u, v): """ Check whether `(u, v)` is solution to the quadratic binary diophantine equation with the variable list ``var`` and coefficient dictionary ``coeff``. Not intended for use by normal users. """ reps = dict(zip(var, (u, v))) eq = Add(*[j*i.xreplace(reps) for i, j in coeff.items()]) return _mexpand(eq) == 0 def diop_DN(D, N, t=symbols("t", integer=True)): """ Solves the equation `x^2 - Dy^2 = N`. Explanation =========== Mainly concerned with the case `D > 0, D` is not a perfect square, which is the same as the generalized Pell equation. The LMM algorithm [1]_ is used to solve this equation. Returns one solution tuple, (`x, y)` for each class of the solutions. Other solutions of the class can be constructed according to the values of ``D`` and ``N``. Usage ===== ``diop_DN(D, N, t)``: D and N are integers as in `x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions. Details ======= ``D`` and ``N`` correspond to D and N in the equation. ``t`` is the parameter to be used in the solutions. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_DN >>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4 [(3, 1), (393, 109), (36, 10)] The output can be interpreted as follows: There are three fundamental solutions to the equation `x^2 - 13y^2 = -4` given by (3, 1), (393, 109) and (36, 10). Each tuple is in the form (x, y), i.e. solution (3, 1) means that `x = 3` and `y = 1`. >>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1 [(49299, 1570)] See Also ======== find_DN(), diop_bf_DN() References ========== .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004, Pages 16 - 17. [online], Available: https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf """ if D < 0: if N == 0: return [(0, 0)] elif N < 0: return [] elif N > 0: sol = [] for d in divisors(square_factor(N)): sols = cornacchia(1, -D, N // d**2) if sols: for x, y in sols: sol.append((d*x, d*y)) if D == -1: sol.append((d*y, d*x)) return sol elif D == 0: if N < 0: return [] if N == 0: return [(0, t)] sN, _exact = integer_nthroot(N, 2) if _exact: return [(sN, t)] else: return [] else: # D > 0 sD, _exact = integer_nthroot(D, 2) if _exact: if N == 0: return [(sD*t, t)] else: sol = [] for y in range(floor(sign(N)*(N - 1)/(2*sD)) + 1): try: sq, _exact = integer_nthroot(D*y**2 + N, 2) except ValueError: _exact = False if _exact: sol.append((sq, y)) return sol elif 1 < N**2 < D: # It is much faster to call `_special_diop_DN`. return _special_diop_DN(D, N) else: if N == 0: return [(0, 0)] elif abs(N) == 1: pqa = PQa(0, 1, D) j = 0 G = [] B = [] for i in pqa: a = i[2] G.append(i[5]) B.append(i[4]) if j != 0 and a == 2*sD: break j = j + 1 if _odd(j): if N == -1: x = G[j - 1] y = B[j - 1] else: count = j while count < 2*j - 1: i = next(pqa) G.append(i[5]) B.append(i[4]) count += 1 x = G[count] y = B[count] else: if N == 1: x = G[j - 1] y = B[j - 1] else: return [] return [(x, y)] else: fs = [] sol = [] div = divisors(N) for d in div: if divisible(N, d**2): fs.append(d) for f in fs: m = N // f**2 zs = sqrt_mod(D, abs(m), all_roots=True) zs = [i for i in zs if i <= abs(m) // 2 ] if abs(m) != 2: zs = zs + [-i for i in zs if i] # omit dupl 0 for z in zs: pqa = PQa(z, abs(m), D) j = 0 G = [] B = [] for i in pqa: G.append(i[5]) B.append(i[4]) if j != 0 and abs(i[1]) == 1: r = G[j-1] s = B[j-1] if r**2 - D*s**2 == m: sol.append((f*r, f*s)) elif diop_DN(D, -1) != []: a = diop_DN(D, -1) sol.append((f*(r*a[0][0] + a[0][1]*s*D), f*(r*a[0][1] + s*a[0][0]))) break j = j + 1 if j == length(z, abs(m), D): break return sol def _special_diop_DN(D, N): """ Solves the equation `x^2 - Dy^2 = N` for the special case where `1 < N**2 < D` and `D` is not a perfect square. It is better to call `diop_DN` rather than this function, as the former checks the condition `1 < N**2 < D`, and calls the latter only if appropriate. Usage ===== WARNING: Internal method. Do not call directly! ``_special_diop_DN(D, N)``: D and N are integers as in `x^2 - Dy^2 = N`. Details ======= ``D`` and ``N`` correspond to D and N in the equation. Examples ======== >>> from sympy.solvers.diophantine.diophantine import _special_diop_DN >>> _special_diop_DN(13, -3) # Solves equation x**2 - 13*y**2 = -3 [(7, 2), (137, 38)] The output can be interpreted as follows: There are two fundamental solutions to the equation `x^2 - 13y^2 = -3` given by (7, 2) and (137, 38). Each tuple is in the form (x, y), i.e. solution (7, 2) means that `x = 7` and `y = 2`. >>> _special_diop_DN(2445, -20) # Solves equation x**2 - 2445*y**2 = -20 [(445, 9), (17625560, 356454), (698095554475, 14118073569)] See Also ======== diop_DN() References ========== .. [1] Section 4.4.4 of the following book: Quadratic Diophantine Equations, T. Andreescu and D. Andrica, Springer, 2015. """ # The following assertion was removed for efficiency, with the understanding # that this method is not called directly. The parent method, `diop_DN` # is responsible for performing the appropriate checks. # # assert (1 < N**2 < D) and (not integer_nthroot(D, 2)[1]) sqrt_D = sqrt(D) F = [(N, 1)] f = 2 while True: f2 = f**2 if f2 > abs(N): break n, r = divmod(N, f2) if r == 0: F.append((n, f)) f += 1 P = 0 Q = 1 G0, G1 = 0, 1 B0, B1 = 1, 0 solutions = [] i = 0 while True: a = floor((P + sqrt_D) / Q) P = a*Q - P Q = (D - P**2) // Q G2 = a*G1 + G0 B2 = a*B1 + B0 for n, f in F: if G2**2 - D*B2**2 == n: solutions.append((f*G2, f*B2)) i += 1 if Q == 1 and i % 2 == 0: break G0, G1 = G1, G2 B0, B1 = B1, B2 return solutions def cornacchia(a, b, m): r""" Solves `ax^2 + by^2 = m` where `\gcd(a, b) = 1 = gcd(a, m)` and `a, b > 0`. Explanation =========== Uses the algorithm due to Cornacchia. The method only finds primitive solutions, i.e. ones with `\gcd(x, y) = 1`. So this method cannot be used to find the solutions of `x^2 + y^2 = 20` since the only solution to former is `(x, y) = (4, 2)` and it is not primitive. When `a = b`, only the solutions with `x \leq y` are found. For more details, see the References. Examples ======== >>> from sympy.solvers.diophantine.diophantine import cornacchia >>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35 {(2, 3), (4, 1)} >>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25 {(4, 3)} References =========== .. [1] A. Nitaj, "L'algorithme de Cornacchia" .. [2] Solving the diophantine equation ax**2 + by**2 = m by Cornacchia's method, [online], Available: http://www.numbertheory.org/php/cornacchia.html See Also ======== sympy.utilities.iterables.signed_permutations """ sols = set() a1 = igcdex(a, m)[0] v = sqrt_mod(-b*a1, m, all_roots=True) if not v: return None for t in v: if t < m // 2: continue u, r = t, m while True: u, r = r, u % r if a*r**2 < m: break m1 = m - a*r**2 if m1 % b == 0: m1 = m1 // b s, _exact = integer_nthroot(m1, 2) if _exact: if a == b and r < s: r, s = s, r sols.add((int(r), int(s))) return sols def PQa(P_0, Q_0, D): r""" Returns useful information needed to solve the Pell equation. Explanation =========== There are six sequences of integers defined related to the continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`, namely {`P_{i}`}, {`Q_{i}`}, {`a_{i}`},{`A_{i}`}, {`B_{i}`}, {`G_{i}`}. ``PQa()`` Returns these values as a 6-tuple in the same order as mentioned above. Refer [1]_ for more detailed information. Usage ===== ``PQa(P_0, Q_0, D)``: ``P_0``, ``Q_0`` and ``D`` are integers corresponding to `P_{0}`, `Q_{0}` and `D` in the continued fraction `\\frac{P_{0} + \sqrt{D}}{Q_{0}}`. Also it's assumed that `P_{0}^2 == D mod(|Q_{0}|)` and `D` is square free. Examples ======== >>> from sympy.solvers.diophantine.diophantine import PQa >>> pqa = PQa(13, 4, 5) # (13 + sqrt(5))/4 >>> next(pqa) # (P_0, Q_0, a_0, A_0, B_0, G_0) (13, 4, 3, 3, 1, -1) >>> next(pqa) # (P_1, Q_1, a_1, A_1, B_1, G_1) (-1, 1, 1, 4, 1, 3) References ========== .. [1] Solving the generalized Pell equation x^2 - Dy^2 = N, John P. Robertson, July 31, 2004, Pages 4 - 8. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf """ A_i_2 = B_i_1 = 0 A_i_1 = B_i_2 = 1 G_i_2 = -P_0 G_i_1 = Q_0 P_i = P_0 Q_i = Q_0 while True: a_i = floor((P_i + sqrt(D))/Q_i) A_i = a_i*A_i_1 + A_i_2 B_i = a_i*B_i_1 + B_i_2 G_i = a_i*G_i_1 + G_i_2 yield P_i, Q_i, a_i, A_i, B_i, G_i A_i_1, A_i_2 = A_i, A_i_1 B_i_1, B_i_2 = B_i, B_i_1 G_i_1, G_i_2 = G_i, G_i_1 P_i = a_i*Q_i - P_i Q_i = (D - P_i**2)/Q_i def diop_bf_DN(D, N, t=symbols("t", integer=True)): r""" Uses brute force to solve the equation, `x^2 - Dy^2 = N`. Explanation =========== Mainly concerned with the generalized Pell equation which is the case when `D > 0, D` is not a perfect square. For more information on the case refer [1]_. Let `(t, u)` be the minimal positive solution of the equation `x^2 - Dy^2 = 1`. Then this method requires `\sqrt{\\frac{\mid N \mid (t \pm 1)}{2D}}` to be small. Usage ===== ``diop_bf_DN(D, N, t)``: ``D`` and ``N`` are coefficients in `x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions. Details ======= ``D`` and ``N`` correspond to D and N in the equation. ``t`` is the parameter to be used in the solutions. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_bf_DN >>> diop_bf_DN(13, -4) [(3, 1), (-3, 1), (36, 10)] >>> diop_bf_DN(986, 1) [(49299, 1570)] See Also ======== diop_DN() References ========== .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004, Page 15. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf """ D = as_int(D) N = as_int(N) sol = [] a = diop_DN(D, 1) u = a[0][0] if abs(N) == 1: return diop_DN(D, N) elif N > 1: L1 = 0 L2 = integer_nthroot(int(N*(u - 1)/(2*D)), 2)[0] + 1 elif N < -1: L1, _exact = integer_nthroot(-int(N/D), 2) if not _exact: L1 += 1 L2 = integer_nthroot(-int(N*(u + 1)/(2*D)), 2)[0] + 1 else: # N = 0 if D < 0: return [(0, 0)] elif D == 0: return [(0, t)] else: sD, _exact = integer_nthroot(D, 2) if _exact: return [(sD*t, t), (-sD*t, t)] else: return [(0, 0)] for y in range(L1, L2): try: x, _exact = integer_nthroot(N + D*y**2, 2) except ValueError: _exact = False if _exact: sol.append((x, y)) if not equivalent(x, y, -x, y, D, N): sol.append((-x, y)) return sol def equivalent(u, v, r, s, D, N): """ Returns True if two solutions `(u, v)` and `(r, s)` of `x^2 - Dy^2 = N` belongs to the same equivalence class and False otherwise. Explanation =========== Two solutions `(u, v)` and `(r, s)` to the above equation fall to the same equivalence class iff both `(ur - Dvs)` and `(us - vr)` are divisible by `N`. See reference [1]_. No test is performed to test whether `(u, v)` and `(r, s)` are actually solutions to the equation. User should take care of this. Usage ===== ``equivalent(u, v, r, s, D, N)``: `(u, v)` and `(r, s)` are two solutions of the equation `x^2 - Dy^2 = N` and all parameters involved are integers. Examples ======== >>> from sympy.solvers.diophantine.diophantine import equivalent >>> equivalent(18, 5, -18, -5, 13, -1) True >>> equivalent(3, 1, -18, 393, 109, -4) False References ========== .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004, Page 12. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf """ return divisible(u*r - D*v*s, N) and divisible(u*s - v*r, N) def length(P, Q, D): r""" Returns the (length of aperiodic part + length of periodic part) of continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`. It is important to remember that this does NOT return the length of the periodic part but the sum of the lengths of the two parts as mentioned above. Usage ===== ``length(P, Q, D)``: ``P``, ``Q`` and ``D`` are integers corresponding to the continued fraction `\\frac{P + \sqrt{D}}{Q}`. Details ======= ``P``, ``D`` and ``Q`` corresponds to P, D and Q in the continued fraction, `\\frac{P + \sqrt{D}}{Q}`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import length >>> length(-2, 4, 5) # (-2 + sqrt(5))/4 3 >>> length(-5, 4, 17) # (-5 + sqrt(17))/4 4 See Also ======== sympy.ntheory.continued_fraction.continued_fraction_periodic """ from sympy.ntheory.continued_fraction import continued_fraction_periodic v = continued_fraction_periodic(P, Q, D) if isinstance(v[-1], list): rpt = len(v[-1]) nonrpt = len(v) - 1 else: rpt = 0 nonrpt = len(v) return rpt + nonrpt def transformation_to_DN(eq): """ This function transforms general quadratic, `ax^2 + bxy + cy^2 + dx + ey + f = 0` to more easy to deal with `X^2 - DY^2 = N` form. Explanation =========== This is used to solve the general quadratic equation by transforming it to the latter form. Refer to [1]_ for more detailed information on the transformation. This function returns a tuple (A, B) where A is a 2 X 2 matrix and B is a 2 X 1 matrix such that, Transpose([x y]) = A * Transpose([X Y]) + B Usage ===== ``transformation_to_DN(eq)``: where ``eq`` is the quadratic to be transformed. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import transformation_to_DN >>> A, B = transformation_to_DN(x**2 - 3*x*y - y**2 - 2*y + 1) >>> A Matrix([ [1/26, 3/26], [ 0, 1/13]]) >>> B Matrix([ [-6/13], [-4/13]]) A, B returned are such that Transpose((x y)) = A * Transpose((X Y)) + B. Substituting these values for `x` and `y` and a bit of simplifying work will give an equation of the form `x^2 - Dy^2 = N`. >>> from sympy.abc import X, Y >>> from sympy import Matrix, simplify >>> u = (A*Matrix([X, Y]) + B)[0] # Transformation for x >>> u X/26 + 3*Y/26 - 6/13 >>> v = (A*Matrix([X, Y]) + B)[1] # Transformation for y >>> v Y/13 - 4/13 Next we will substitute these formulas for `x` and `y` and do ``simplify()``. >>> eq = simplify((x**2 - 3*x*y - y**2 - 2*y + 1).subs(zip((x, y), (u, v)))) >>> eq X**2/676 - Y**2/52 + 17/13 By multiplying the denominator appropriately, we can get a Pell equation in the standard form. >>> eq * 676 X**2 - 13*Y**2 + 884 If only the final equation is needed, ``find_DN()`` can be used. See Also ======== find_DN() References ========== .. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0, John P.Robertson, May 8, 2003, Page 7 - 11. https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == BinaryQuadratic.name: return _transformation_to_DN(var, coeff) def _transformation_to_DN(var, coeff): x, y = var a = coeff[x**2] b = coeff[x*y] c = coeff[y**2] d = coeff[x] e = coeff[y] f = coeff[1] a, b, c, d, e, f = [as_int(i) for i in _remove_gcd(a, b, c, d, e, f)] X, Y = symbols("X, Y", integer=True) if b: B, C = _rational_pq(2*a, b) A, T = _rational_pq(a, B**2) # eq_1 = A*B*X**2 + B*(c*T - A*C**2)*Y**2 + d*T*X + (B*e*T - d*T*C)*Y + f*T*B coeff = {X**2: A*B, X*Y: 0, Y**2: B*(c*T - A*C**2), X: d*T, Y: B*e*T - d*T*C, 1: f*T*B} A_0, B_0 = _transformation_to_DN([X, Y], coeff) return Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*A_0, Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*B_0 else: if d: B, C = _rational_pq(2*a, d) A, T = _rational_pq(a, B**2) # eq_2 = A*X**2 + c*T*Y**2 + e*T*Y + f*T - A*C**2 coeff = {X**2: A, X*Y: 0, Y**2: c*T, X: 0, Y: e*T, 1: f*T - A*C**2} A_0, B_0 = _transformation_to_DN([X, Y], coeff) return Matrix(2, 2, [S.One/B, 0, 0, 1])*A_0, Matrix(2, 2, [S.One/B, 0, 0, 1])*B_0 + Matrix([-S(C)/B, 0]) else: if e: B, C = _rational_pq(2*c, e) A, T = _rational_pq(c, B**2) # eq_3 = a*T*X**2 + A*Y**2 + f*T - A*C**2 coeff = {X**2: a*T, X*Y: 0, Y**2: A, X: 0, Y: 0, 1: f*T - A*C**2} A_0, B_0 = _transformation_to_DN([X, Y], coeff) return Matrix(2, 2, [1, 0, 0, S.One/B])*A_0, Matrix(2, 2, [1, 0, 0, S.One/B])*B_0 + Matrix([0, -S(C)/B]) else: # TODO: pre-simplification: Not necessary but may simplify # the equation. return Matrix(2, 2, [S.One/a, 0, 0, 1]), Matrix([0, 0]) def find_DN(eq): """ This function returns a tuple, `(D, N)` of the simplified form, `x^2 - Dy^2 = N`, corresponding to the general quadratic, `ax^2 + bxy + cy^2 + dx + ey + f = 0`. Solving the general quadratic is then equivalent to solving the equation `X^2 - DY^2 = N` and transforming the solutions by using the transformation matrices returned by ``transformation_to_DN()``. Usage ===== ``find_DN(eq)``: where ``eq`` is the quadratic to be transformed. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import find_DN >>> find_DN(x**2 - 3*x*y - y**2 - 2*y + 1) (13, -884) Interpretation of the output is that we get `X^2 -13Y^2 = -884` after transforming `x^2 - 3xy - y^2 - 2y + 1` using the transformation returned by ``transformation_to_DN()``. See Also ======== transformation_to_DN() References ========== .. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0, John P.Robertson, May 8, 2003, Page 7 - 11. https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == BinaryQuadratic.name: return _find_DN(var, coeff) def _find_DN(var, coeff): x, y = var X, Y = symbols("X, Y", integer=True) A, B = _transformation_to_DN(var, coeff) u = (A*Matrix([X, Y]) + B)[0] v = (A*Matrix([X, Y]) + B)[1] eq = x**2*coeff[x**2] + x*y*coeff[x*y] + y**2*coeff[y**2] + x*coeff[x] + y*coeff[y] + coeff[1] simplified = _mexpand(eq.subs(zip((x, y), (u, v)))) coeff = simplified.as_coefficients_dict() return -coeff[Y**2]/coeff[X**2], -coeff[1]/coeff[X**2] def check_param(x, y, a, params): """ If there is a number modulo ``a`` such that ``x`` and ``y`` are both integers, then return a parametric representation for ``x`` and ``y`` else return (None, None). Here ``x`` and ``y`` are functions of ``t``. """ from sympy.simplify.simplify import clear_coefficients if x.is_number and not x.is_Integer: return DiophantineSolutionSet([x, y], parameters=params) if y.is_number and not y.is_Integer: return DiophantineSolutionSet([x, y], parameters=params) m, n = symbols("m, n", integer=True) c, p = (m*x + n*y).as_content_primitive() if a % c.q: return DiophantineSolutionSet([x, y], parameters=params) # clear_coefficients(mx + b, R)[1] -> (R - b)/m eq = clear_coefficients(x, m)[1] - clear_coefficients(y, n)[1] junk, eq = eq.as_content_primitive() return _diop_solve(eq, params=params) def diop_ternary_quadratic(eq, parameterize=False): """ Solves the general quadratic ternary form, `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`. Returns a tuple `(x, y, z)` which is a base solution for the above equation. If there are no solutions, `(None, None, None)` is returned. Usage ===== ``diop_ternary_quadratic(eq)``: Return a tuple containing a basic solution to ``eq``. Details ======= ``eq`` should be an homogeneous expression of degree two in three variables and it is assumed to be zero. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic >>> diop_ternary_quadratic(x**2 + 3*y**2 - z**2) (1, 0, 1) >>> diop_ternary_quadratic(4*x**2 + 5*y**2 - z**2) (1, 0, 2) >>> diop_ternary_quadratic(45*x**2 - 7*y**2 - 8*x*y - z**2) (28, 45, 105) >>> diop_ternary_quadratic(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y) (9, 1, 5) """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type in ( HomogeneousTernaryQuadratic.name, HomogeneousTernaryQuadraticNormal.name): sol = _diop_ternary_quadratic(var, coeff) if len(sol) > 0: x_0, y_0, z_0 = list(sol)[0] else: x_0, y_0, z_0 = None, None, None if parameterize: return _parametrize_ternary_quadratic( (x_0, y_0, z_0), var, coeff) return x_0, y_0, z_0 def _diop_ternary_quadratic(_var, coeff): eq = sum([i*coeff[i] for i in coeff]) if HomogeneousTernaryQuadratic(eq).matches(): return HomogeneousTernaryQuadratic(eq, free_symbols=_var).solve() elif HomogeneousTernaryQuadraticNormal(eq).matches(): return HomogeneousTernaryQuadraticNormal(eq, free_symbols=_var).solve() def transformation_to_normal(eq): """ Returns the transformation Matrix that converts a general ternary quadratic equation ``eq`` (`ax^2 + by^2 + cz^2 + dxy + eyz + fxz`) to a form without cross terms: `ax^2 + by^2 + cz^2 = 0`. This is not used in solving ternary quadratics; it is only implemented for the sake of completeness. """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type in ( "homogeneous_ternary_quadratic", "homogeneous_ternary_quadratic_normal"): return _transformation_to_normal(var, coeff) def _transformation_to_normal(var, coeff): _var = list(var) # copy x, y, z = var if not any(coeff[i**2] for i in var): # https://math.stackexchange.com/questions/448051/transform-quadratic-ternary-form-to-normal-form/448065#448065 a = coeff[x*y] b = coeff[y*z] c = coeff[x*z] swap = False if not a: # b can't be 0 or else there aren't 3 vars swap = True a, b = b, a T = Matrix(((1, 1, -b/a), (1, -1, -c/a), (0, 0, 1))) if swap: T.row_swap(0, 1) T.col_swap(0, 1) return T if coeff[x**2] == 0: # If the coefficient of x is zero change the variables if coeff[y**2] == 0: _var[0], _var[2] = var[2], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 2) T.col_swap(0, 2) return T else: _var[0], _var[1] = var[1], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 1) T.col_swap(0, 1) return T # Apply the transformation x --> X - (B*Y + C*Z)/(2*A) if coeff[x*y] != 0 or coeff[x*z] != 0: A = coeff[x**2] B = coeff[x*y] C = coeff[x*z] D = coeff[y**2] E = coeff[y*z] F = coeff[z**2] _coeff = {} _coeff[x**2] = 4*A**2 _coeff[y**2] = 4*A*D - B**2 _coeff[z**2] = 4*A*F - C**2 _coeff[y*z] = 4*A*E - 2*B*C _coeff[x*y] = 0 _coeff[x*z] = 0 T_0 = _transformation_to_normal(_var, _coeff) return Matrix(3, 3, [1, S(-B)/(2*A), S(-C)/(2*A), 0, 1, 0, 0, 0, 1])*T_0 elif coeff[y*z] != 0: if coeff[y**2] == 0: if coeff[z**2] == 0: # Equations of the form A*x**2 + E*yz = 0. # Apply transformation y -> Y + Z ans z -> Y - Z return Matrix(3, 3, [1, 0, 0, 0, 1, 1, 0, 1, -1]) else: # Ax**2 + E*y*z + F*z**2 = 0 _var[0], _var[2] = var[2], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 2) T.col_swap(0, 2) return T else: # A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, F may be zero _var[0], _var[1] = var[1], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 1) T.col_swap(0, 1) return T else: return Matrix.eye(3) def parametrize_ternary_quadratic(eq): """ Returns the parametrized general solution for the ternary quadratic equation ``eq`` which has the form `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`. Examples ======== >>> from sympy import Tuple, ordered >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import parametrize_ternary_quadratic The parametrized solution may be returned with three parameters: >>> parametrize_ternary_quadratic(2*x**2 + y**2 - 2*z**2) (p**2 - 2*q**2, -2*p**2 + 4*p*q - 4*p*r - 4*q**2, p**2 - 4*p*q + 2*q**2 - 4*q*r) There might also be only two parameters: >>> parametrize_ternary_quadratic(4*x**2 + 2*y**2 - 3*z**2) (2*p**2 - 3*q**2, -4*p**2 + 12*p*q - 6*q**2, 4*p**2 - 8*p*q + 6*q**2) Notes ===== Consider ``p`` and ``q`` in the previous 2-parameter solution and observe that more than one solution can be represented by a given pair of parameters. If `p` and ``q`` are not coprime, this is trivially true since the common factor will also be a common factor of the solution values. But it may also be true even when ``p`` and ``q`` are coprime: >>> sol = Tuple(*_) >>> p, q = ordered(sol.free_symbols) >>> sol.subs([(p, 3), (q, 2)]) (6, 12, 12) >>> sol.subs([(q, 1), (p, 1)]) (-1, 2, 2) >>> sol.subs([(q, 0), (p, 1)]) (2, -4, 4) >>> sol.subs([(q, 1), (p, 0)]) (-3, -6, 6) Except for sign and a common factor, these are equivalent to the solution of (1, 2, 2). References ========== .. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart, London Mathematical Society Student Texts 41, Cambridge University Press, Cambridge, 1998. """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type in ( "homogeneous_ternary_quadratic", "homogeneous_ternary_quadratic_normal"): x_0, y_0, z_0 = list(_diop_ternary_quadratic(var, coeff))[0] return _parametrize_ternary_quadratic( (x_0, y_0, z_0), var, coeff) def _parametrize_ternary_quadratic(solution, _var, coeff): # called for a*x**2 + b*y**2 + c*z**2 + d*x*y + e*y*z + f*x*z = 0 assert 1 not in coeff x_0, y_0, z_0 = solution v = list(_var) # copy if x_0 is None: return (None, None, None) if solution.count(0) >= 2: # if there are 2 zeros the equation reduces # to k*X**2 == 0 where X is x, y, or z so X must # be zero, too. So there is only the trivial # solution. return (None, None, None) if x_0 == 0: v[0], v[1] = v[1], v[0] y_p, x_p, z_p = _parametrize_ternary_quadratic( (y_0, x_0, z_0), v, coeff) return x_p, y_p, z_p x, y, z = v r, p, q = symbols("r, p, q", integer=True) eq = sum(k*v for k, v in coeff.items()) eq_1 = _mexpand(eq.subs(zip( (x, y, z), (r*x_0, r*y_0 + p, r*z_0 + q)))) A, B = eq_1.as_independent(r, as_Add=True) x = A*x_0 y = (A*y_0 - _mexpand(B/r*p)) z = (A*z_0 - _mexpand(B/r*q)) return _remove_gcd(x, y, z) def diop_ternary_quadratic_normal(eq, parameterize=False): """ Solves the quadratic ternary diophantine equation, `ax^2 + by^2 + cz^2 = 0`. Explanation =========== Here the coefficients `a`, `b`, and `c` should be non zero. Otherwise the equation will be a quadratic binary or univariate equation. If solvable, returns a tuple `(x, y, z)` that satisfies the given equation. If the equation does not have integer solutions, `(None, None, None)` is returned. Usage ===== ``diop_ternary_quadratic_normal(eq)``: where ``eq`` is an equation of the form `ax^2 + by^2 + cz^2 = 0`. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic_normal >>> diop_ternary_quadratic_normal(x**2 + 3*y**2 - z**2) (1, 0, 1) >>> diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) (1, 0, 2) >>> diop_ternary_quadratic_normal(34*x**2 - 3*y**2 - 301*z**2) (4, 9, 1) """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == HomogeneousTernaryQuadraticNormal.name: sol = _diop_ternary_quadratic_normal(var, coeff) if len(sol) > 0: x_0, y_0, z_0 = list(sol)[0] else: x_0, y_0, z_0 = None, None, None if parameterize: return _parametrize_ternary_quadratic( (x_0, y_0, z_0), var, coeff) return x_0, y_0, z_0 def _diop_ternary_quadratic_normal(var, coeff): eq = sum([i * coeff[i] for i in coeff]) return HomogeneousTernaryQuadraticNormal(eq, free_symbols=var).solve() def sqf_normal(a, b, c, steps=False): """ Return `a', b', c'`, the coefficients of the square-free normal form of `ax^2 + by^2 + cz^2 = 0`, where `a', b', c'` are pairwise prime. If `steps` is True then also return three tuples: `sq`, `sqf`, and `(a', b', c')` where `sq` contains the square factors of `a`, `b` and `c` after removing the `gcd(a, b, c)`; `sqf` contains the values of `a`, `b` and `c` after removing both the `gcd(a, b, c)` and the square factors. The solutions for `ax^2 + by^2 + cz^2 = 0` can be recovered from the solutions of `a'x^2 + b'y^2 + c'z^2 = 0`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sqf_normal >>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11) (11, 1, 5) >>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11, True) ((3, 1, 7), (5, 55, 11), (11, 1, 5)) References ========== .. [1] Legendre's Theorem, Legrange's Descent, http://public.csusm.edu/aitken_html/notes/legendre.pdf See Also ======== reconstruct() """ ABC = _remove_gcd(a, b, c) sq = tuple(square_factor(i) for i in ABC) sqf = A, B, C = tuple([i//j**2 for i,j in zip(ABC, sq)]) pc = igcd(A, B) A /= pc B /= pc pa = igcd(B, C) B /= pa C /= pa pb = igcd(A, C) A /= pb B /= pb A *= pa B *= pb C *= pc if steps: return (sq, sqf, (A, B, C)) else: return A, B, C def square_factor(a): r""" Returns an integer `c` s.t. `a = c^2k, \ c,k \in Z`. Here `k` is square free. `a` can be given as an integer or a dictionary of factors. Examples ======== >>> from sympy.solvers.diophantine.diophantine import square_factor >>> square_factor(24) 2 >>> square_factor(-36*3) 6 >>> square_factor(1) 1 >>> square_factor({3: 2, 2: 1, -1: 1}) # -18 3 See Also ======== sympy.ntheory.factor_.core """ f = a if isinstance(a, dict) else factorint(a) return Mul(*[p**(e//2) for p, e in f.items()]) def reconstruct(A, B, z): """ Reconstruct the `z` value of an equivalent solution of `ax^2 + by^2 + cz^2` from the `z` value of a solution of the square-free normal form of the equation, `a'*x^2 + b'*y^2 + c'*z^2`, where `a'`, `b'` and `c'` are square free and `gcd(a', b', c') == 1`. """ f = factorint(igcd(A, B)) for p, e in f.items(): if e != 1: raise ValueError('a and b should be square-free') z *= p return z def ldescent(A, B): """ Return a non-trivial solution to `w^2 = Ax^2 + By^2` using Lagrange's method; return None if there is no such solution. . Here, `A \\neq 0` and `B \\neq 0` and `A` and `B` are square free. Output a tuple `(w_0, x_0, y_0)` which is a solution to the above equation. Examples ======== >>> from sympy.solvers.diophantine.diophantine import ldescent >>> ldescent(1, 1) # w^2 = x^2 + y^2 (1, 1, 0) >>> ldescent(4, -7) # w^2 = 4x^2 - 7y^2 (2, -1, 0) This means that `x = -1, y = 0` and `w = 2` is a solution to the equation `w^2 = 4x^2 - 7y^2` >>> ldescent(5, -1) # w^2 = 5x^2 - y^2 (2, 1, -1) References ========== .. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart, London Mathematical Society Student Texts 41, Cambridge University Press, Cambridge, 1998. .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, [online], Available: https://nottingham-repository.worktribe.com/output/1023265/efficient-solution-of-rational-conics """ if abs(A) > abs(B): w, y, x = ldescent(B, A) return w, x, y if A == 1: return (1, 1, 0) if B == 1: return (1, 0, 1) if B == -1: # and A == -1 return r = sqrt_mod(A, B) Q = (r**2 - A) // B if Q == 0: B_0 = 1 d = 0 else: div = divisors(Q) B_0 = None for i in div: sQ, _exact = integer_nthroot(abs(Q) // i, 2) if _exact: B_0, d = sign(Q)*i, sQ break if B_0 is not None: W, X, Y = ldescent(A, B_0) return _remove_gcd((-A*X + r*W), (r*X - W), Y*(B_0*d)) def descent(A, B): """ Returns a non-trivial solution, (x, y, z), to `x^2 = Ay^2 + Bz^2` using Lagrange's descent method with lattice-reduction. `A` and `B` are assumed to be valid for such a solution to exist. This is faster than the normal Lagrange's descent algorithm because the Gaussian reduction is used. Examples ======== >>> from sympy.solvers.diophantine.diophantine import descent >>> descent(3, 1) # x**2 = 3*y**2 + z**2 (1, 0, 1) `(x, y, z) = (1, 0, 1)` is a solution to the above equation. >>> descent(41, -113) (-16, -3, 1) References ========== .. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. """ if abs(A) > abs(B): x, y, z = descent(B, A) return x, z, y if B == 1: return (1, 0, 1) if A == 1: return (1, 1, 0) if B == -A: return (0, 1, 1) if B == A: x, z, y = descent(-1, A) return (A*y, z, x) w = sqrt_mod(A, B) x_0, z_0 = gaussian_reduce(w, A, B) t = (x_0**2 - A*z_0**2) // B t_2 = square_factor(t) t_1 = t // t_2**2 x_1, z_1, y_1 = descent(A, t_1) return _remove_gcd(x_0*x_1 + A*z_0*z_1, z_0*x_1 + x_0*z_1, t_1*t_2*y_1) def gaussian_reduce(w, a, b): r""" Returns a reduced solution `(x, z)` to the congruence `X^2 - aZ^2 \equiv 0 \ (mod \ b)` so that `x^2 + |a|z^2` is minimal. Details ======= Here ``w`` is a solution of the congruence `x^2 \equiv a \ (mod \ b)` References ========== .. [1] Gaussian lattice Reduction [online]. Available: http://home.ie.cuhk.edu.hk/~wkshum/wordpress/?p=404 .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. """ u = (0, 1) v = (1, 0) if dot(u, v, w, a, b) < 0: v = (-v[0], -v[1]) if norm(u, w, a, b) < norm(v, w, a, b): u, v = v, u while norm(u, w, a, b) > norm(v, w, a, b): k = dot(u, v, w, a, b) // dot(v, v, w, a, b) u, v = v, (u[0]- k*v[0], u[1]- k*v[1]) u, v = v, u if dot(u, v, w, a, b) < dot(v, v, w, a, b)/2 or norm((u[0]-v[0], u[1]-v[1]), w, a, b) > norm(v, w, a, b): c = v else: c = (u[0] - v[0], u[1] - v[1]) return c[0]*w + b*c[1], c[0] def dot(u, v, w, a, b): r""" Returns a special dot product of the vectors `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})` which is defined in order to reduce solution of the congruence equation `X^2 - aZ^2 \equiv 0 \ (mod \ b)`. """ u_1, u_2 = u v_1, v_2 = v return (w*u_1 + b*u_2)*(w*v_1 + b*v_2) + abs(a)*u_1*v_1 def norm(u, w, a, b): r""" Returns the norm of the vector `u = (u_{1}, u_{2})` under the dot product defined by `u \cdot v = (wu_{1} + bu_{2})(w*v_{1} + bv_{2}) + |a|*u_{1}*v_{1}` where `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})`. """ u_1, u_2 = u return sqrt(dot((u_1, u_2), (u_1, u_2), w, a, b)) def holzer(x, y, z, a, b, c): r""" Simplify the solution `(x, y, z)` of the equation `ax^2 + by^2 = cz^2` with `a, b, c > 0` and `z^2 \geq \mid ab \mid` to a new reduced solution `(x', y', z')` such that `z'^2 \leq \mid ab \mid`. The algorithm is an interpretation of Mordell's reduction as described on page 8 of Cremona and Rusin's paper [1]_ and the work of Mordell in reference [2]_. References ========== .. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. .. [2] Diophantine Equations, L. J. Mordell, page 48. """ if _odd(c): k = 2*c else: k = c//2 small = a*b*c step = 0 while True: t1, t2, t3 = a*x**2, b*y**2, c*z**2 # check that it's a solution if t1 + t2 != t3: if step == 0: raise ValueError('bad starting solution') break x_0, y_0, z_0 = x, y, z if max(t1, t2, t3) <= small: # Holzer condition break uv = u, v = base_solution_linear(k, y_0, -x_0) if None in uv: break p, q = -(a*u*x_0 + b*v*y_0), c*z_0 r = Rational(p, q) if _even(c): w = _nint_or_floor(p, q) assert abs(w - r) <= S.Half else: w = p//q # floor if _odd(a*u + b*v + c*w): w += 1 assert abs(w - r) <= S.One A = (a*u**2 + b*v**2 + c*w**2) B = (a*u*x_0 + b*v*y_0 + c*w*z_0) x = Rational(x_0*A - 2*u*B, k) y = Rational(y_0*A - 2*v*B, k) z = Rational(z_0*A - 2*w*B, k) assert all(i.is_Integer for i in (x, y, z)) step += 1 return tuple([int(i) for i in (x_0, y_0, z_0)]) def diop_general_pythagorean(eq, param=symbols("m", integer=True)): """ Solves the general pythagorean equation, `a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`. Returns a tuple which contains a parametrized solution to the equation, sorted in the same order as the input variables. Usage ===== ``diop_general_pythagorean(eq, param)``: where ``eq`` is a general pythagorean equation which is assumed to be zero and ``param`` is the base parameter used to construct other parameters by subscripting. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_general_pythagorean >>> from sympy.abc import a, b, c, d, e >>> diop_general_pythagorean(a**2 + b**2 + c**2 - d**2) (m1**2 + m2**2 - m3**2, 2*m1*m3, 2*m2*m3, m1**2 + m2**2 + m3**2) >>> diop_general_pythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2) (10*m1**2 + 10*m2**2 + 10*m3**2 - 10*m4**2, 15*m1**2 + 15*m2**2 + 15*m3**2 + 15*m4**2, 15*m1*m4, 12*m2*m4, 60*m3*m4) """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == GeneralPythagorean.name: if param is None: params = None else: params = symbols('%s1:%i' % (param, len(var)), integer=True) return list(GeneralPythagorean(eq).solve(parameters=params))[0] def diop_general_sum_of_squares(eq, limit=1): r""" Solves the equation `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`. Returns at most ``limit`` number of solutions. Usage ===== ``general_sum_of_squares(eq, limit)`` : Here ``eq`` is an expression which is assumed to be zero. Also, ``eq`` should be in the form, `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`. Details ======= When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be no solutions. Refer to [1]_ for more details. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_squares >>> from sympy.abc import a, b, c, d, e >>> diop_general_sum_of_squares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345) {(15, 22, 22, 24, 24)} Reference ========= .. [1] Representing an integer as a sum of three squares, [online], Available: http://www.proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == GeneralSumOfSquares.name: return set(GeneralSumOfSquares(eq).solve(limit=limit)) def diop_general_sum_of_even_powers(eq, limit=1): """ Solves the equation `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0` where `e` is an even, integer power. Returns at most ``limit`` number of solutions. Usage ===== ``general_sum_of_even_powers(eq, limit)`` : Here ``eq`` is an expression which is assumed to be zero. Also, ``eq`` should be in the form, `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_even_powers >>> from sympy.abc import a, b >>> diop_general_sum_of_even_powers(a**4 + b**4 - (2**4 + 3**4)) {(2, 3)} See Also ======== power_representation """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == GeneralSumOfEvenPowers.name: return set(GeneralSumOfEvenPowers(eq).solve(limit=limit)) ## Functions below this comment can be more suitably grouped under ## an Additive number theory module rather than the Diophantine ## equation module. def partition(n, k=None, zeros=False): """ Returns a generator that can be used to generate partitions of an integer `n`. Explanation =========== A partition of `n` is a set of positive integers which add up to `n`. For example, partitions of 3 are 3, 1 + 2, 1 + 1 + 1. A partition is returned as a tuple. If ``k`` equals None, then all possible partitions are returned irrespective of their size, otherwise only the partitions of size ``k`` are returned. If the ``zero`` parameter is set to True then a suitable number of zeros are added at the end of every partition of size less than ``k``. ``zero`` parameter is considered only if ``k`` is not None. When the partitions are over, the last `next()` call throws the ``StopIteration`` exception, so this function should always be used inside a try - except block. Details ======= ``partition(n, k)``: Here ``n`` is a positive integer and ``k`` is the size of the partition which is also positive integer. Examples ======== >>> from sympy.solvers.diophantine.diophantine import partition >>> f = partition(5) >>> next(f) (1, 1, 1, 1, 1) >>> next(f) (1, 1, 1, 2) >>> g = partition(5, 3) >>> next(g) (1, 1, 3) >>> next(g) (1, 2, 2) >>> g = partition(5, 3, zeros=True) >>> next(g) (0, 0, 5) """ if not zeros or k is None: for i in ordered_partitions(n, k): yield tuple(i) else: for m in range(1, k + 1): for i in ordered_partitions(n, m): i = tuple(i) yield (0,)*(k - len(i)) + i def prime_as_sum_of_two_squares(p): """ Represent a prime `p` as a unique sum of two squares; this can only be done if the prime is congruent to 1 mod 4. Examples ======== >>> from sympy.solvers.diophantine.diophantine import prime_as_sum_of_two_squares >>> prime_as_sum_of_two_squares(7) # can't be done >>> prime_as_sum_of_two_squares(5) (1, 2) Reference ========= .. [1] Representing a number as a sum of four squares, [online], Available: http://schorn.ch/lagrange.html See Also ======== sum_of_squares() """ if not p % 4 == 1: return if p % 8 == 5: b = 2 else: b = 3 while pow(b, (p - 1) // 2, p) == 1: b = nextprime(b) b = pow(b, (p - 1) // 4, p) a = p while b**2 > p: a, b = b, a % b return (int(a % b), int(b)) # convert from long def sum_of_three_squares(n): r""" Returns a 3-tuple $(a, b, c)$ such that $a^2 + b^2 + c^2 = n$ and $a, b, c \geq 0$. Returns None if $n = 4^a(8m + 7)$ for some `a, m \in \mathbb{Z}`. See [1]_ for more details. Usage ===== ``sum_of_three_squares(n)``: Here ``n`` is a non-negative integer. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sum_of_three_squares >>> sum_of_three_squares(44542) (18, 37, 207) References ========== .. [1] Representing a number as a sum of three squares, [online], Available: http://schorn.ch/lagrange.html See Also ======== sum_of_squares() """ special = {1:(1, 0, 0), 2:(1, 1, 0), 3:(1, 1, 1), 10: (1, 3, 0), 34: (3, 3, 4), 58:(3, 7, 0), 85:(6, 7, 0), 130:(3, 11, 0), 214:(3, 6, 13), 226:(8, 9, 9), 370:(8, 9, 15), 526:(6, 7, 21), 706:(15, 15, 16), 730:(1, 27, 0), 1414:(6, 17, 33), 1906:(13, 21, 36), 2986: (21, 32, 39), 9634: (56, 57, 57)} v = 0 if n == 0: return (0, 0, 0) v = multiplicity(4, n) n //= 4**v if n % 8 == 7: return if n in special.keys(): x, y, z = special[n] return _sorted_tuple(2**v*x, 2**v*y, 2**v*z) s, _exact = integer_nthroot(n, 2) if _exact: return (2**v*s, 0, 0) x = None if n % 8 == 3: s = s if _odd(s) else s - 1 for x in range(s, -1, -2): N = (n - x**2) // 2 if isprime(N): y, z = prime_as_sum_of_two_squares(N) return _sorted_tuple(2**v*x, 2**v*(y + z), 2**v*abs(y - z)) return if n % 8 in (2, 6): s = s if _odd(s) else s - 1 else: s = s - 1 if _odd(s) else s for x in range(s, -1, -2): N = n - x**2 if isprime(N): y, z = prime_as_sum_of_two_squares(N) return _sorted_tuple(2**v*x, 2**v*y, 2**v*z) def sum_of_four_squares(n): r""" Returns a 4-tuple `(a, b, c, d)` such that `a^2 + b^2 + c^2 + d^2 = n`. Here `a, b, c, d \geq 0`. Usage ===== ``sum_of_four_squares(n)``: Here ``n`` is a non-negative integer. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sum_of_four_squares >>> sum_of_four_squares(3456) (8, 8, 32, 48) >>> sum_of_four_squares(1294585930293) (0, 1234, 2161, 1137796) References ========== .. [1] Representing a number as a sum of four squares, [online], Available: http://schorn.ch/lagrange.html See Also ======== sum_of_squares() """ if n == 0: return (0, 0, 0, 0) v = multiplicity(4, n) n //= 4**v if n % 8 == 7: d = 2 n = n - 4 elif n % 8 in (2, 6): d = 1 n = n - 1 else: d = 0 x, y, z = sum_of_three_squares(n) return _sorted_tuple(2**v*d, 2**v*x, 2**v*y, 2**v*z) def power_representation(n, p, k, zeros=False): r""" Returns a generator for finding k-tuples of integers, `(n_{1}, n_{2}, . . . n_{k})`, such that `n = n_{1}^p + n_{2}^p + . . . n_{k}^p`. Usage ===== ``power_representation(n, p, k, zeros)``: Represent non-negative number ``n`` as a sum of ``k`` ``p``\ th powers. If ``zeros`` is true, then the solutions is allowed to contain zeros. Examples ======== >>> from sympy.solvers.diophantine.diophantine import power_representation Represent 1729 as a sum of two cubes: >>> f = power_representation(1729, 3, 2) >>> next(f) (9, 10) >>> next(f) (1, 12) If the flag `zeros` is True, the solution may contain tuples with zeros; any such solutions will be generated after the solutions without zeros: >>> list(power_representation(125, 2, 3, zeros=True)) [(5, 6, 8), (3, 4, 10), (0, 5, 10), (0, 2, 11)] For even `p` the `permute_sign` function can be used to get all signed values: >>> from sympy.utilities.iterables import permute_signs >>> list(permute_signs((1, 12))) [(1, 12), (-1, 12), (1, -12), (-1, -12)] All possible signed permutations can also be obtained: >>> from sympy.utilities.iterables import signed_permutations >>> list(signed_permutations((1, 12))) [(1, 12), (-1, 12), (1, -12), (-1, -12), (12, 1), (-12, 1), (12, -1), (-12, -1)] """ n, p, k = [as_int(i) for i in (n, p, k)] if n < 0: if p % 2: for t in power_representation(-n, p, k, zeros): yield tuple(-i for i in t) return if p < 1 or k < 1: raise ValueError(filldedent(''' Expecting positive integers for `(p, k)`, but got `(%s, %s)`''' % (p, k))) if n == 0: if zeros: yield (0,)*k return if k == 1: if p == 1: yield (n,) else: be = perfect_power(n) if be: b, e = be d, r = divmod(e, p) if not r: yield (b**d,) return if p == 1: for t in partition(n, k, zeros=zeros): yield t return if p == 2: feasible = _can_do_sum_of_squares(n, k) if not feasible: return if not zeros and n > 33 and k >= 5 and k <= n and n - k in ( 13, 10, 7, 5, 4, 2, 1): '''Todd G. Will, "When Is n^2 a Sum of k Squares?", [online]. Available: https://www.maa.org/sites/default/files/Will-MMz-201037918.pdf''' return if feasible is not True: # it's prime and k == 2 yield prime_as_sum_of_two_squares(n) return if k == 2 and p > 2: be = perfect_power(n) if be and be[1] % p == 0: return # Fermat: a**n + b**n = c**n has no solution for n > 2 if n >= k: a = integer_nthroot(n - (k - 1), p)[0] for t in pow_rep_recursive(a, k, n, [], p): yield tuple(reversed(t)) if zeros: a = integer_nthroot(n, p)[0] for i in range(1, k): for t in pow_rep_recursive(a, i, n, [], p): yield tuple(reversed(t + (0,)*(k - i))) sum_of_powers = power_representation def pow_rep_recursive(n_i, k, n_remaining, terms, p): # Invalid arguments if n_i <= 0 or k <= 0: return # No solutions may exist if n_remaining < k: return if k * pow(n_i, p) < n_remaining: return if k == 0 and n_remaining == 0: yield tuple(terms) elif k == 1: # next_term^p must equal to n_remaining next_term, exact = integer_nthroot(n_remaining, p) if exact and next_term <= n_i: yield tuple(terms + [next_term]) return else: # TODO: Fall back to diop_DN when k = 2 if n_i >= 1 and k > 0: for next_term in range(1, n_i + 1): residual = n_remaining - pow(next_term, p) if residual < 0: break yield from pow_rep_recursive(next_term, k - 1, residual, terms + [next_term], p) def sum_of_squares(n, k, zeros=False): """Return a generator that yields the k-tuples of nonnegative values, the squares of which sum to n. If zeros is False (default) then the solution will not contain zeros. The nonnegative elements of a tuple are sorted. * If k == 1 and n is square, (n,) is returned. * If k == 2 then n can only be written as a sum of squares if every prime in the factorization of n that has the form 4*k + 3 has an even multiplicity. If n is prime then it can only be written as a sum of two squares if it is in the form 4*k + 1. * if k == 3 then n can be written as a sum of squares if it does not have the form 4**m*(8*k + 7). * all integers can be written as the sum of 4 squares. * if k > 4 then n can be partitioned and each partition can be written as a sum of 4 squares; if n is not evenly divisible by 4 then n can be written as a sum of squares only if the an additional partition can be written as sum of squares. For example, if k = 6 then n is partitioned into two parts, the first being written as a sum of 4 squares and the second being written as a sum of 2 squares -- which can only be done if the condition above for k = 2 can be met, so this will automatically reject certain partitions of n. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sum_of_squares >>> list(sum_of_squares(25, 2)) [(3, 4)] >>> list(sum_of_squares(25, 2, True)) [(3, 4), (0, 5)] >>> list(sum_of_squares(25, 4)) [(1, 2, 2, 4)] See Also ======== sympy.utilities.iterables.signed_permutations """ yield from power_representation(n, 2, k, zeros) def _can_do_sum_of_squares(n, k): """Return True if n can be written as the sum of k squares, False if it cannot, or 1 if ``k == 2`` and ``n`` is prime (in which case it *can* be written as a sum of two squares). A False is returned only if it cannot be written as ``k``-squares, even if 0s are allowed. """ if k < 1: return False if n < 0: return False if n == 0: return True if k == 1: return is_square(n) if k == 2: if n in (1, 2): return True if isprime(n): if n % 4 == 1: return 1 # signal that it was prime return False else: f = factorint(n) for p, m in f.items(): # we can proceed iff no prime factor in the form 4*k + 3 # has an odd multiplicity if (p % 4 == 3) and m % 2: return False return True if k == 3: if (n//4**multiplicity(4, n)) % 8 == 7: return False # every number can be written as a sum of 4 squares; for k > 4 partitions # can be 0 return True
3a236640b6cf2005510e91421ba1c62ff6ab56457bd8436d6116ca6bca12daf6
from sympy.assumptions.ask import (Q, ask) from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.function import (Derivative, Function, diff) from sympy.core.mul import Mul from sympy.core import (GoldenRatio, TribonacciConstant) from sympy.core.numbers import (E, Float, I, Rational, oo, pi) from sympy.core.relational import (Eq, Gt, Lt, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, Wild, symbols) from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import binomial from sympy.functions.elementary.complexes import (Abs, arg, conjugate, im, re) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.hyperbolic import (atanh, cosh, sinh, tanh) from sympy.functions.elementary.miscellaneous import (cbrt, root, sqrt) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, asin, atan, atan2, cos, sec, sin, tan) from sympy.functions.special.error_functions import (erf, erfc, erfcinv, erfinv) from sympy.integrals.integrals import Integral from sympy.logic.boolalg import (And, Or) from sympy.matrices.dense import Matrix from sympy.matrices import SparseMatrix from sympy.polys.polytools import Poly from sympy.printing.str import sstr from sympy.simplify.radsimp import denom from sympy.solvers.solvers import (nsolve, solve, solve_linear) from sympy.core.function import nfloat from sympy.solvers import solve_linear_system, solve_linear_system_LU, \ solve_undetermined_coeffs from sympy.solvers.bivariate import _filtered_gens, _solve_lambert, _lambert from sympy.solvers.solvers import _invert, unrad, checksol, posify, _ispow, \ det_quick, det_perm, det_minor, _simple_dens, denoms from sympy.physics.units import cm from sympy.polys.rootoftools import CRootOf from sympy.testing.pytest import slow, XFAIL, SKIP, raises from sympy.core.random import verify_numerically as tn from sympy.abc import a, b, c, d, e, k, h, p, x, y, z, t, q, m, R def NS(e, n=15, **options): return sstr(sympify(e).evalf(n, **options), full_prec=True) def test_swap_back(): f, g = map(Function, 'fg') fx, gx = f(x), g(x) assert solve([fx + y - 2, fx - gx - 5], fx, y, gx) == \ {fx: gx + 5, y: -gx - 3} assert solve(fx + gx*x - 2, [fx, gx], dict=True) == [{fx: 2, gx: 0}] assert solve(fx + gx**2*x - y, [fx, gx], dict=True) == [{fx: y, gx: 0}] assert solve([f(1) - 2, x + 2], dict=True) == [{x: -2, f(1): 2}] def guess_solve_strategy(eq, symbol): try: solve(eq, symbol) return True except (TypeError, NotImplementedError): return False def test_guess_poly(): # polynomial equations assert guess_solve_strategy( S(4), x ) # == GS_POLY assert guess_solve_strategy( x, x ) # == GS_POLY assert guess_solve_strategy( x + a, x ) # == GS_POLY assert guess_solve_strategy( 2*x, x ) # == GS_POLY assert guess_solve_strategy( x + sqrt(2), x) # == GS_POLY assert guess_solve_strategy( x + 2**Rational(1, 4), x) # == GS_POLY assert guess_solve_strategy( x**2 + 1, x ) # == GS_POLY assert guess_solve_strategy( x**2 - 1, x ) # == GS_POLY assert guess_solve_strategy( x*y + y, x ) # == GS_POLY assert guess_solve_strategy( x*exp(y) + y, x) # == GS_POLY assert guess_solve_strategy( (x - y**3)/(y**2*sqrt(1 - y**2)), x) # == GS_POLY def test_guess_poly_cv(): # polynomial equations via a change of variable assert guess_solve_strategy( sqrt(x) + 1, x ) # == GS_POLY_CV_1 assert guess_solve_strategy( x**Rational(1, 3) + sqrt(x) + 1, x ) # == GS_POLY_CV_1 assert guess_solve_strategy( 4*x*(1 - sqrt(x)), x ) # == GS_POLY_CV_1 # polynomial equation multiplying both sides by x**n assert guess_solve_strategy( x + 1/x + y, x ) # == GS_POLY_CV_2 def test_guess_rational_cv(): # rational functions assert guess_solve_strategy( (x + 1)/(x**2 + 2), x) # == GS_RATIONAL assert guess_solve_strategy( (x - y**3)/(y**2*sqrt(1 - y**2)), y) # == GS_RATIONAL_CV_1 # rational functions via the change of variable y -> x**n assert guess_solve_strategy( (sqrt(x) + 1)/(x**Rational(1, 3) + sqrt(x) + 1), x ) \ #== GS_RATIONAL_CV_1 def test_guess_transcendental(): #transcendental functions assert guess_solve_strategy( exp(x) + 1, x ) # == GS_TRANSCENDENTAL assert guess_solve_strategy( 2*cos(x) - y, x ) # == GS_TRANSCENDENTAL assert guess_solve_strategy( exp(x) + exp(-x) - y, x ) # == GS_TRANSCENDENTAL assert guess_solve_strategy(3**x - 10, x) # == GS_TRANSCENDENTAL assert guess_solve_strategy(-3**x + 10, x) # == GS_TRANSCENDENTAL assert guess_solve_strategy(a*x**b - y, x) # == GS_TRANSCENDENTAL def test_solve_args(): # equation container, issue 5113 ans = {x: -3, y: 1} eqs = (x + 5*y - 2, -3*x + 6*y - 15) assert all(solve(container(eqs), x, y) == ans for container in (tuple, list, set, frozenset)) assert solve(Tuple(*eqs), x, y) == ans # implicit symbol to solve for assert set(solve(x**2 - 4)) == {S(2), -S(2)} assert solve([x + y - 3, x - y - 5]) == {x: 4, y: -1} assert solve(x - exp(x), x, implicit=True) == [exp(x)] # no symbol to solve for assert solve(42) == solve(42, x) == [] assert solve([1, 2]) == [] assert solve([sqrt(2)],[x]) == [] # duplicate symbols raises raises(ValueError, lambda: solve((x - 3, y + 2), x, y, x)) raises(ValueError, lambda: solve(x, x, x)) # no error in exclude assert solve(x, x, exclude=[y, y]) == [0] # duplicate symbols raises raises(ValueError, lambda: solve((x - 3, y + 2), x, y, x)) raises(ValueError, lambda: solve(x, x, x)) # no error in exclude assert solve(x, x, exclude=[y, y]) == [0] # unordered symbols # only 1 assert solve(y - 3, {y}) == [3] # more than 1 assert solve(y - 3, {x, y}) == [{y: 3}] # multiple symbols: take the first linear solution+ # - return as tuple with values for all requested symbols assert solve(x + y - 3, [x, y]) == [(3 - y, y)] # - unless dict is True assert solve(x + y - 3, [x, y], dict=True) == [{x: 3 - y}] # - or no symbols are given assert solve(x + y - 3) == [{x: 3 - y}] # multiple symbols might represent an undetermined coefficients system assert solve(a + b*x - 2, [a, b]) == {a: 2, b: 0} assert solve((a + b)*x + b - c, [a, b]) == {a: -c, b: c} eq = a*x**2 + b*x + c - ((x - h)**2 + 4*p*k)/4/p # - check that flags are obeyed sol = solve(eq, [h, p, k], exclude=[a, b, c]) assert sol == {h: -b/(2*a), k: (4*a*c - b**2)/(4*a), p: 1/(4*a)} assert solve(eq, [h, p, k], dict=True) == [sol] assert solve(eq, [h, p, k], set=True) == \ ([h, p, k], {(-b/(2*a), 1/(4*a), (4*a*c - b**2)/(4*a))}) # issue 23889 - polysys not simplified assert solve(eq, [h, p, k], exclude=[a, b, c], simplify=False) == \ {h: -b/(2*a), k: (4*a*c - b**2)/(4*a), p: 1/(4*a)} # but this only happens when system has a single solution args = (a + b)*x - b**2 + 2, a, b assert solve(*args) == [((b**2 - b*x - 2)/x, b)] # and if the system has a solution; the following doesn't so # an algebraic solution is returned assert solve(a*x + b**2/(x + 4) - 3*x - 4/x, a, b, dict=True) == \ [{a: (-b**2*x + 3*x**3 + 12*x**2 + 4*x + 16)/(x**2*(x + 4))}] # failed single equation assert solve(1/(1/x - y + exp(y))) == [] raises( NotImplementedError, lambda: solve(exp(x) + sin(x) + exp(y) + sin(y))) # failed system # -- when no symbols given, 1 fails assert solve([y, exp(x) + x]) == [{x: -LambertW(1), y: 0}] # both fail assert solve( (exp(x) - x, exp(y) - y)) == [{x: -LambertW(-1), y: -LambertW(-1)}] # -- when symbols given assert solve([y, exp(x) + x], x, y) == [(-LambertW(1), 0)] # symbol is a number assert solve(x**2 - pi, pi) == [x**2] # no equations assert solve([], [x]) == [] # nonlinear systen assert solve((x**2 - 4, y - 2), x, y) == [(-2, 2), (2, 2)] assert solve((x**2 - 4, y - 2), y, x) == [(2, -2), (2, 2)] assert solve((x**2 - 4 + z, y - 2 - z), a, z, y, x, set=True ) == ([a, z, y, x], { (a, z, z + 2, -sqrt(4 - z)), (a, z, z + 2, sqrt(4 - z))}) # overdetermined system # - nonlinear assert solve([(x + y)**2 - 4, x + y - 2]) == [{x: -y + 2}] # - linear assert solve((x + y - 2, 2*x + 2*y - 4)) == {x: -y + 2} # When one or more args are Boolean assert solve(Eq(x**2, 0.0)) == [0] # issue 19048 assert solve([True, Eq(x, 0)], [x], dict=True) == [{x: 0}] assert solve([Eq(x, x), Eq(x, 0), Eq(x, x+1)], [x], dict=True) == [] assert not solve([Eq(x, x+1), x < 2], x) assert solve([Eq(x, 0), x+1<2]) == Eq(x, 0) assert solve([Eq(x, x), Eq(x, x+1)], x) == [] assert solve(True, x) == [] assert solve([x - 1, False], [x], set=True) == ([], set()) assert solve([-y*(x + y - 1)/2, (y - 1)/x/y + 1/y], set=True, check=False) == ([x, y], {(1 - y, y), (x, 0)}) # ordering should be canonical, fastest to order by keys instead # of by size assert list(solve((y - 1, x - sqrt(3)*z)).keys()) == [x, y] # as set always returns as symbols, set even if no solution assert solve([x - 1, x], (y, x), set=True) == ([y, x], set()) assert solve([x - 1, x], {y, x}, set=True) == ([x, y], set()) def test_solve_polynomial1(): assert solve(3*x - 2, x) == [Rational(2, 3)] assert solve(Eq(3*x, 2), x) == [Rational(2, 3)] assert set(solve(x**2 - 1, x)) == {-S.One, S.One} assert set(solve(Eq(x**2, 1), x)) == {-S.One, S.One} assert solve(x - y**3, x) == [y**3] rx = root(x, 3) assert solve(x - y**3, y) == [ rx, -rx/2 - sqrt(3)*I*rx/2, -rx/2 + sqrt(3)*I*rx/2] a11, a12, a21, a22, b1, b2 = symbols('a11,a12,a21,a22,b1,b2') assert solve([a11*x + a12*y - b1, a21*x + a22*y - b2], x, y) == \ { x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21), y: (a11*b2 - a21*b1)/(a11*a22 - a12*a21), } solution = {x: S.Zero, y: S.Zero} assert solve((x - y, x + y), x, y ) == solution assert solve((x - y, x + y), (x, y)) == solution assert solve((x - y, x + y), [x, y]) == solution assert set(solve(x**3 - 15*x - 4, x)) == { -2 + 3**S.Half, S(4), -2 - 3**S.Half } assert set(solve((x**2 - 1)**2 - a, x)) == \ {sqrt(1 + sqrt(a)), -sqrt(1 + sqrt(a)), sqrt(1 - sqrt(a)), -sqrt(1 - sqrt(a))} def test_solve_polynomial2(): assert solve(4, x) == [] def test_solve_polynomial_cv_1a(): """ Test for solving on equations that can be converted to a polynomial equation using the change of variable y -> x**Rational(p, q) """ assert solve( sqrt(x) - 1, x) == [1] assert solve( sqrt(x) - 2, x) == [4] assert solve( x**Rational(1, 4) - 2, x) == [16] assert solve( x**Rational(1, 3) - 3, x) == [27] assert solve(sqrt(x) + x**Rational(1, 3) + x**Rational(1, 4), x) == [0] def test_solve_polynomial_cv_1b(): assert set(solve(4*x*(1 - a*sqrt(x)), x)) == {S.Zero, 1/a**2} assert set(solve(x*(root(x, 3) - 3), x)) == {S.Zero, S(27)} def test_solve_polynomial_cv_2(): """ Test for solving on equations that can be converted to a polynomial equation multiplying both sides of the equation by x**m """ assert solve(x + 1/x - 1, x) in \ [[ S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2], [ S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2]] def test_quintics_1(): f = x**5 - 110*x**3 - 55*x**2 + 2310*x + 979 s = solve(f, check=False) for r in s: res = f.subs(x, r.n()).n() assert tn(res, 0) f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20 s = solve(f) for r in s: assert r.func == CRootOf # if one uses solve to get the roots of a polynomial that has a CRootOf # solution, make sure that the use of nfloat during the solve process # doesn't fail. Note: if you want numerical solutions to a polynomial # it is *much* faster to use nroots to get them than to solve the # equation only to get RootOf solutions which are then numerically # evaluated. So for eq = x**5 + 3*x + 7 do Poly(eq).nroots() rather # than [i.n() for i in solve(eq)] to get the numerical roots of eq. assert nfloat(solve(x**5 + 3*x**3 + 7)[0], exponent=False) == \ CRootOf(x**5 + 3*x**3 + 7, 0).n() def test_quintics_2(): f = x**5 + 15*x + 12 s = solve(f, check=False) for r in s: res = f.subs(x, r.n()).n() assert tn(res, 0) f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20 s = solve(f) for r in s: assert r.func == CRootOf assert solve(x**5 - 6*x**3 - 6*x**2 + x - 6) == [ CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 0), CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 1), CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 2), CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 3), CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 4)] def test_quintics_3(): y = x**5 + x**3 - 2**Rational(1, 3) assert solve(y) == solve(-y) == [] def test_highorder_poly(): # just testing that the uniq generator is unpacked sol = solve(x**6 - 2*x + 2) assert all(isinstance(i, CRootOf) for i in sol) and len(sol) == 6 def test_solve_rational(): """Test solve for rational functions""" assert solve( ( x - y**3 )/( (y**2)*sqrt(1 - y**2) ), x) == [y**3] def test_solve_conjugate(): """Test solve for simple conjugate functions""" assert solve(conjugate(x) -3 + I) == [3 + I] def test_solve_nonlinear(): assert solve(x**2 - y**2, x, y, dict=True) == [{x: -y}, {x: y}] assert solve(x**2 - y**2/exp(x), y, x, dict=True) == [{y: -x*sqrt(exp(x))}, {y: x*sqrt(exp(x))}] def test_issue_8666(): x = symbols('x') assert solve(Eq(x**2 - 1/(x**2 - 4), 4 - 1/(x**2 - 4)), x) == [] assert solve(Eq(x + 1/x, 1/x), x) == [] def test_issue_7228(): assert solve(4**(2*(x**2) + 2*x) - 8, x) == [Rational(-3, 2), S.Half] def test_issue_7190(): assert solve(log(x-3) + log(x+3), x) == [sqrt(10)] def test_issue_21004(): x = symbols('x') f = x/sqrt(x**2+1) f_diff = f.diff(x) assert solve(f_diff, x) == [] def test_linear_system(): x, y, z, t, n = symbols('x, y, z, t, n') assert solve([x - 1, x - y, x - 2*y, y - 1], [x, y]) == [] assert solve([x - 1, x - y, x - 2*y, x - 1], [x, y]) == [] assert solve([x - 1, x - 1, x - y, x - 2*y], [x, y]) == [] assert solve([x + 5*y - 2, -3*x + 6*y - 15], x, y) == {x: -3, y: 1} M = Matrix([[0, 0, n*(n + 1), (n + 1)**2, 0], [n + 1, n + 1, -2*n - 1, -(n + 1), 0], [-1, 0, 1, 0, 0]]) assert solve_linear_system(M, x, y, z, t) == \ {x: t*(-n-1)/n, y: 0, z: t*(-n-1)/n} assert solve([x + y + z + t, -z - t], x, y, z, t) == {x: -y, z: -t} @XFAIL def test_linear_system_xfail(): # https://github.com/sympy/sympy/issues/6420 M = Matrix([[0, 15.0, 10.0, 700.0], [1, 1, 1, 100.0], [0, 10.0, 5.0, 200.0], [-5.0, 0, 0, 0 ]]) assert solve_linear_system(M, x, y, z) == {x: 0, y: -60.0, z: 160.0} def test_linear_system_function(): a = Function('a') assert solve([a(0, 0) + a(0, 1) + a(1, 0) + a(1, 1), -a(1, 0) - a(1, 1)], a(0, 0), a(0, 1), a(1, 0), a(1, 1)) == {a(1, 0): -a(1, 1), a(0, 0): -a(0, 1)} def test_linear_system_symbols_doesnt_hang_1(): def _mk_eqs(wy): # Equations for fitting a wy*2 - 1 degree polynomial between two points, # at end points derivatives are known up to order: wy - 1 order = 2*wy - 1 x, x0, x1 = symbols('x, x0, x1', real=True) y0s = symbols('y0_:{}'.format(wy), real=True) y1s = symbols('y1_:{}'.format(wy), real=True) c = symbols('c_:{}'.format(order+1), real=True) expr = sum([coeff*x**o for o, coeff in enumerate(c)]) eqs = [] for i in range(wy): eqs.append(expr.diff(x, i).subs({x: x0}) - y0s[i]) eqs.append(expr.diff(x, i).subs({x: x1}) - y1s[i]) return eqs, c # # The purpose of this test is just to see that these calls don't hang. The # expressions returned are complicated so are not included here. Testing # their correctness takes longer than solving the system. # for n in range(1, 7+1): eqs, c = _mk_eqs(n) solve(eqs, c) def test_linear_system_symbols_doesnt_hang_2(): M = Matrix([ [66, 24, 39, 50, 88, 40, 37, 96, 16, 65, 31, 11, 37, 72, 16, 19, 55, 37, 28, 76], [10, 93, 34, 98, 59, 44, 67, 74, 74, 94, 71, 61, 60, 23, 6, 2, 57, 8, 29, 78], [19, 91, 57, 13, 64, 65, 24, 53, 77, 34, 85, 58, 87, 39, 39, 7, 36, 67, 91, 3], [74, 70, 15, 53, 68, 43, 86, 83, 81, 72, 25, 46, 67, 17, 59, 25, 78, 39, 63, 6], [69, 40, 67, 21, 67, 40, 17, 13, 93, 44, 46, 89, 62, 31, 30, 38, 18, 20, 12, 81], [50, 22, 74, 76, 34, 45, 19, 76, 28, 28, 11, 99, 97, 82, 8, 46, 99, 57, 68, 35], [58, 18, 45, 88, 10, 64, 9, 34, 90, 82, 17, 41, 43, 81, 45, 83, 22, 88, 24, 39], [42, 21, 70, 68, 6, 33, 64, 81, 83, 15, 86, 75, 86, 17, 77, 34, 62, 72, 20, 24], [ 7, 8, 2, 72, 71, 52, 96, 5, 32, 51, 31, 36, 79, 88, 25, 77, 29, 26, 33, 13], [19, 31, 30, 85, 81, 39, 63, 28, 19, 12, 16, 49, 37, 66, 38, 13, 3, 71, 61, 51], [29, 82, 80, 49, 26, 85, 1, 37, 2, 74, 54, 82, 26, 47, 54, 9, 35, 0, 99, 40], [15, 49, 82, 91, 93, 57, 45, 25, 45, 97, 15, 98, 48, 52, 66, 24, 62, 54, 97, 37], [62, 23, 73, 53, 52, 86, 28, 38, 0, 74, 92, 38, 97, 70, 71, 29, 26, 90, 67, 45], [ 2, 32, 23, 24, 71, 37, 25, 71, 5, 41, 97, 65, 93, 13, 65, 45, 25, 88, 69, 50], [40, 56, 1, 29, 79, 98, 79, 62, 37, 28, 45, 47, 3, 1, 32, 74, 98, 35, 84, 32], [33, 15, 87, 79, 65, 9, 14, 63, 24, 19, 46, 28, 74, 20, 29, 96, 84, 91, 93, 1], [97, 18, 12, 52, 1, 2, 50, 14, 52, 76, 19, 82, 41, 73, 51, 79, 13, 3, 82, 96], [40, 28, 52, 10, 10, 71, 56, 78, 82, 5, 29, 48, 1, 26, 16, 18, 50, 76, 86, 52], [38, 89, 83, 43, 29, 52, 90, 77, 57, 0, 67, 20, 81, 88, 48, 96, 88, 58, 14, 3]]) syms = x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18 = symbols('x:19') sol = { x0: -S(1967374186044955317099186851240896179)/3166636564687820453598895768302256588, x1: -S(84268280268757263347292368432053826)/791659141171955113399723942075564147, x2: -S(229962957341664730974463872411844965)/1583318282343910226799447884151128294, x3: S(990156781744251750886760432229180537)/6333273129375640907197791536604513176, x4: -S(2169830351210066092046760299593096265)/18999819388126922721593374609813539528, x5: S(4680868883477577389628494526618745355)/9499909694063461360796687304906769764, x6: -S(1590820774344371990683178396480879213)/3166636564687820453598895768302256588, x7: -S(54104723404825537735226491634383072)/339282489073695048599881689460956063, x8: S(3182076494196560075964847771774733847)/6333273129375640907197791536604513176, x9: -S(10870817431029210431989147852497539675)/18999819388126922721593374609813539528, x10: -S(13118019242576506476316318268573312603)/18999819388126922721593374609813539528, x11: -S(5173852969886775824855781403820641259)/4749954847031730680398343652453384882, x12: S(4261112042731942783763341580651820563)/4749954847031730680398343652453384882, x13: -S(821833082694661608993818117038209051)/6333273129375640907197791536604513176, x14: S(906881575107250690508618713632090559)/904753304196520129599684505229216168, x15: -S(732162528717458388995329317371283987)/6333273129375640907197791536604513176, x16: S(4524215476705983545537087360959896817)/9499909694063461360796687304906769764, x17: -S(3898571347562055611881270844646055217)/6333273129375640907197791536604513176, x18: S(7513502486176995632751685137907442269)/18999819388126922721593374609813539528 } eqs = list(M * Matrix(syms + (1,))) assert solve(eqs, syms) == sol y = Symbol('y') eqs = list(y * M * Matrix(syms + (1,))) assert solve(eqs, syms) == sol def test_linear_systemLU(): n = Symbol('n') M = Matrix([[1, 2, 0, 1], [1, 3, 2*n, 1], [4, -1, n**2, 1]]) assert solve_linear_system_LU(M, [x, y, z]) == {z: -3/(n**2 + 18*n), x: 1 - 12*n/(n**2 + 18*n), y: 6*n/(n**2 + 18*n)} # Note: multiple solutions exist for some of these equations, so the tests # should be expected to break if the implementation of the solver changes # in such a way that a different branch is chosen @slow def test_solve_transcendental(): from sympy.abc import a, b assert solve(exp(x) - 3, x) == [log(3)] assert set(solve((a*x + b)*(exp(x) - 3), x)) == {-b/a, log(3)} assert solve(cos(x) - y, x) == [-acos(y) + 2*pi, acos(y)] assert solve(2*cos(x) - y, x) == [-acos(y/2) + 2*pi, acos(y/2)] assert solve(Eq(cos(x), sin(x)), x) == [pi/4] assert set(solve(exp(x) + exp(-x) - y, x)) in [{ log(y/2 - sqrt(y**2 - 4)/2), log(y/2 + sqrt(y**2 - 4)/2), }, { log(y - sqrt(y**2 - 4)) - log(2), log(y + sqrt(y**2 - 4)) - log(2)}, { log(y/2 - sqrt((y - 2)*(y + 2))/2), log(y/2 + sqrt((y - 2)*(y + 2))/2)}] assert solve(exp(x) - 3, x) == [log(3)] assert solve(Eq(exp(x), 3), x) == [log(3)] assert solve(log(x) - 3, x) == [exp(3)] assert solve(sqrt(3*x) - 4, x) == [Rational(16, 3)] assert solve(3**(x + 2), x) == [] assert solve(3**(2 - x), x) == [] assert solve(x + 2**x, x) == [-LambertW(log(2))/log(2)] assert solve(2*x + 5 + log(3*x - 2), x) == \ [Rational(2, 3) + LambertW(2*exp(Rational(-19, 3))/3)/2] assert solve(3*x + log(4*x), x) == [LambertW(Rational(3, 4))/3] assert set(solve((2*x + 8)*(8 + exp(x)), x)) == {S(-4), log(8) + pi*I} eq = 2*exp(3*x + 4) - 3 ans = solve(eq, x) # this generated a failure in flatten assert len(ans) == 3 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans) assert solve(2*log(3*x + 4) - 3, x) == [(exp(Rational(3, 2)) - 4)/3] assert solve(exp(x) + 1, x) == [pi*I] eq = 2*(3*x + 4)**5 - 6*7**(3*x + 9) result = solve(eq, x) x0 = -log(2401) x1 = 3**Rational(1, 5) x2 = log(7**(7*x1/20)) x3 = sqrt(2) x4 = sqrt(5) x5 = x3*sqrt(x4 - 5) x6 = x4 + 1 x7 = 1/(3*log(7)) x8 = -x4 x9 = x3*sqrt(x8 - 5) x10 = x8 + 1 ans = [x7*(x0 - 5*LambertW(x2*(-x5 + x6))), x7*(x0 - 5*LambertW(x2*(x5 + x6))), x7*(x0 - 5*LambertW(x2*(x10 - x9))), x7*(x0 - 5*LambertW(x2*(x10 + x9))), x7*(x0 - 5*LambertW(-log(7**(7*x1/5))))] assert result == ans, result # it works if expanded, too assert solve(eq.expand(), x) == result assert solve(z*cos(x) - y, x) == [-acos(y/z) + 2*pi, acos(y/z)] assert solve(z*cos(2*x) - y, x) == [-acos(y/z)/2 + pi, acos(y/z)/2] assert solve(z*cos(sin(x)) - y, x) == [ pi - asin(acos(y/z)), asin(acos(y/z) - 2*pi) + pi, -asin(acos(y/z) - 2*pi), asin(acos(y/z))] assert solve(z*cos(x), x) == [pi/2, pi*Rational(3, 2)] # issue 4508 assert solve(y - b*x/(a + x), x) in [[-a*y/(y - b)], [a*y/(b - y)]] assert solve(y - b*exp(a/x), x) == [a/log(y/b)] # issue 4507 assert solve(y - b/(1 + a*x), x) in [[(b - y)/(a*y)], [-((y - b)/(a*y))]] # issue 4506 assert solve(y - a*x**b, x) == [(y/a)**(1/b)] # issue 4505 assert solve(z**x - y, x) == [log(y)/log(z)] # issue 4504 assert solve(2**x - 10, x) == [1 + log(5)/log(2)] # issue 6744 assert solve(x*y) == [{x: 0}, {y: 0}] assert solve([x*y]) == [{x: 0}, {y: 0}] assert solve(x**y - 1) == [{x: 1}, {y: 0}] assert solve([x**y - 1]) == [{x: 1}, {y: 0}] assert solve(x*y*(x**2 - y**2)) == [{x: 0}, {x: -y}, {x: y}, {y: 0}] assert solve([x*y*(x**2 - y**2)]) == [{x: 0}, {x: -y}, {x: y}, {y: 0}] # issue 4739 assert solve(exp(log(5)*x) - 2**x, x) == [0] # issue 14791 assert solve(exp(log(5)*x) - exp(log(2)*x), x) == [0] f = Function('f') assert solve(y*f(log(5)*x) - y*f(log(2)*x), x) == [0] assert solve(f(x) - f(0), x) == [0] assert solve(f(x) - f(2 - x), x) == [1] raises(NotImplementedError, lambda: solve(f(x, y) - f(1, 2), x)) raises(NotImplementedError, lambda: solve(f(x, y) - f(2 - x, 2), x)) raises(ValueError, lambda: solve(f(x, y) - f(1 - x), x)) raises(ValueError, lambda: solve(f(x, y) - f(1), x)) # misc # make sure that the right variables is picked up in tsolve # shouldn't generate a GeneratorsNeeded error in _tsolve when the NaN is generated # for eq_down. Actual answers, as determined numerically are approx. +/- 0.83 raises(NotImplementedError, lambda: solve(sinh(x)*sinh(sinh(x)) + cosh(x)*cosh(sinh(x)) - 3)) # watch out for recursive loop in tsolve raises(NotImplementedError, lambda: solve((x + 2)**y*x - 3, x)) # issue 7245 assert solve(sin(sqrt(x))) == [0, pi**2] # issue 7602 a, b = symbols('a, b', real=True, negative=False) assert str(solve(Eq(a, 0.5 - cos(pi*b)/2), b)) == \ '[2.0 - 0.318309886183791*acos(1.0 - 2.0*a), 0.318309886183791*acos(1.0 - 2.0*a)]' # issue 15325 assert solve(y**(1/x) - z, x) == [log(y)/log(z)] def test_solve_for_functions_derivatives(): t = Symbol('t') x = Function('x')(t) y = Function('y')(t) a11, a12, a21, a22, b1, b2 = symbols('a11,a12,a21,a22,b1,b2') soln = solve([a11*x + a12*y - b1, a21*x + a22*y - b2], x, y) assert soln == { x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21), y: (a11*b2 - a21*b1)/(a11*a22 - a12*a21), } assert solve(x - 1, x) == [1] assert solve(3*x - 2, x) == [Rational(2, 3)] soln = solve([a11*x.diff(t) + a12*y.diff(t) - b1, a21*x.diff(t) + a22*y.diff(t) - b2], x.diff(t), y.diff(t)) assert soln == { y.diff(t): (a11*b2 - a21*b1)/(a11*a22 - a12*a21), x.diff(t): (a22*b1 - a12*b2)/(a11*a22 - a12*a21) } assert solve(x.diff(t) - 1, x.diff(t)) == [1] assert solve(3*x.diff(t) - 2, x.diff(t)) == [Rational(2, 3)] eqns = {3*x - 1, 2*y - 4} assert solve(eqns, {x, y}) == { x: Rational(1, 3), y: 2 } x = Symbol('x') f = Function('f') F = x**2 + f(x)**2 - 4*x - 1 assert solve(F.diff(x), diff(f(x), x)) == [(-x + 2)/f(x)] # Mixed cased with a Symbol and a Function x = Symbol('x') y = Function('y')(t) soln = solve([a11*x + a12*y.diff(t) - b1, a21*x + a22*y.diff(t) - b2], x, y.diff(t)) assert soln == { y.diff(t): (a11*b2 - a21*b1)/(a11*a22 - a12*a21), x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21) } # issue 13263 x = Symbol('x') f = Function('f') soln = solve([f(x).diff(x) + f(x).diff(x, 2) - 1, f(x).diff(x) - f(x).diff(x, 2)], f(x).diff(x), f(x).diff(x, 2)) assert soln == { f(x).diff(x, 2): 1/2, f(x).diff(x): 1/2 } soln = solve([f(x).diff(x, 2) + f(x).diff(x, 3) - 1, 1 - f(x).diff(x, 2) - f(x).diff(x, 3), 1 - f(x).diff(x,3)], f(x).diff(x, 2), f(x).diff(x, 3)) assert soln == { f(x).diff(x, 2): 0, f(x).diff(x, 3): 1 } def test_issue_3725(): f = Function('f') F = x**2 + f(x)**2 - 4*x - 1 e = F.diff(x) assert solve(e, f(x).diff(x)) in [[(2 - x)/f(x)], [-((x - 2)/f(x))]] def test_issue_3870(): a, b, c, d = symbols('a b c d') A = Matrix(2, 2, [a, b, c, d]) B = Matrix(2, 2, [0, 2, -3, 0]) C = Matrix(2, 2, [1, 2, 3, 4]) assert solve(A*B - C, [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1} assert solve([A*B - C], [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1} assert solve(Eq(A*B, C), [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1} assert solve([A*B - B*A], [a, b, c, d]) == {a: d, b: Rational(-2, 3)*c} assert solve([A*C - C*A], [a, b, c, d]) == {a: d - c, b: Rational(2, 3)*c} assert solve([A*B - B*A, A*C - C*A], [a, b, c, d]) == {a: d, b: 0, c: 0} assert solve([Eq(A*B, B*A)], [a, b, c, d]) == {a: d, b: Rational(-2, 3)*c} assert solve([Eq(A*C, C*A)], [a, b, c, d]) == {a: d - c, b: Rational(2, 3)*c} assert solve([Eq(A*B, B*A), Eq(A*C, C*A)], [a, b, c, d]) == {a: d, b: 0, c: 0} def test_solve_linear(): w = Wild('w') assert solve_linear(x, x) == (0, 1) assert solve_linear(x, exclude=[x]) == (0, 1) assert solve_linear(x, symbols=[w]) == (0, 1) assert solve_linear(x, y - 2*x) in [(x, y/3), (y, 3*x)] assert solve_linear(x, y - 2*x, exclude=[x]) == (y, 3*x) assert solve_linear(3*x - y, 0) in [(x, y/3), (y, 3*x)] assert solve_linear(3*x - y, 0, [x]) == (x, y/3) assert solve_linear(3*x - y, 0, [y]) == (y, 3*x) assert solve_linear(x**2/y, 1) == (y, x**2) assert solve_linear(w, x) in [(w, x), (x, w)] assert solve_linear(cos(x)**2 + sin(x)**2 + 2 + y) == \ (y, -2 - cos(x)**2 - sin(x)**2) assert solve_linear(cos(x)**2 + sin(x)**2 + 2 + y, symbols=[x]) == (0, 1) assert solve_linear(Eq(x, 3)) == (x, 3) assert solve_linear(1/(1/x - 2)) == (0, 0) assert solve_linear((x + 1)*exp(-x), symbols=[x]) == (x, -1) assert solve_linear((x + 1)*exp(x), symbols=[x]) == ((x + 1)*exp(x), 1) assert solve_linear(x*exp(-x**2), symbols=[x]) == (x, 0) assert solve_linear(0**x - 1) == (0**x - 1, 1) assert solve_linear(1 + 1/(x - 1)) == (x, 0) eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0 assert solve_linear(eq) == (0, 1) eq = cos(x)**2 + sin(x)**2 # = 1 assert solve_linear(eq) == (0, 1) raises(ValueError, lambda: solve_linear(Eq(x, 3), 3)) def test_solve_undetermined_coeffs(): assert solve_undetermined_coeffs( a*x**2 + b*x**2 + b*x + 2*c*x + c + 1, [a, b, c], x ) == {a: -2, b: 2, c: -1} # Test that rational functions work assert solve_undetermined_coeffs(a/x + b/(x + 1) - (2*x + 1)/(x**2 + x), [a, b], x) == {a: 1, b: 1} # Test cancellation in rational functions assert solve_undetermined_coeffs( ((c + 1)*a*x**2 + (c + 1)*b*x**2 + (c + 1)*b*x + (c + 1)*2*c*x + (c + 1)**2)/(c + 1), [a, b, c], x) == \ {a: -2, b: 2, c: -1} # multivariate X, Y, Z = y, x**y, y*x**y eq = a*X + b*Y + c*Z - X - 2*Y - 3*Z coeffs = a, b, c syms = x, y assert solve_undetermined_coeffs(eq, coeffs) == { a: 1, b: 2, c: 3} assert solve_undetermined_coeffs(eq, coeffs, syms) == { a: 1, b: 2, c: 3} assert solve_undetermined_coeffs(eq, coeffs, *syms) == { a: 1, b: 2, c: 3} # check output format assert solve_undetermined_coeffs(a*x + a - 2, [a]) == [] assert solve_undetermined_coeffs(a**2*x - 4*x, [a]) == [ {a: -2}, {a: 2}] assert solve_undetermined_coeffs(0, [a]) == [] assert solve_undetermined_coeffs(0, [a], dict=True) == [] assert solve_undetermined_coeffs(0, [a], set=True) == ([], {}) assert solve_undetermined_coeffs(1, [a]) == [] abeq = a*x - 2*x + b - 3 s = {b, a} assert solve_undetermined_coeffs(abeq, s, x) == {a: 2, b: 3} assert solve_undetermined_coeffs(abeq, s, x, set=True) == ([a, b], {(2, 3)}) assert solve_undetermined_coeffs(sin(a*x) - sin(2*x), (a,)) is None assert solve_undetermined_coeffs(a*x + b*x - 2*x, (a, b)) == {a: 2 - b} def test_solve_inequalities(): x = Symbol('x') sol = And(S.Zero < x, x < oo) assert solve(x + 1 > 1) == sol assert solve([x + 1 > 1]) == sol assert solve([x + 1 > 1], x) == sol assert solve([x + 1 > 1], [x]) == sol system = [Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)] assert solve(system) == \ And(Or(And(Lt(-sqrt(2), x), Lt(x, -1)), And(Lt(1, x), Lt(x, sqrt(2)))), Eq(0, 0)) x = Symbol('x', real=True) system = [Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)] assert solve(system) == \ Or(And(Lt(-sqrt(2), x), Lt(x, -1)), And(Lt(1, x), Lt(x, sqrt(2)))) # issues 6627, 3448 assert solve((x - 3)/(x - 2) < 0, x) == And(Lt(2, x), Lt(x, 3)) assert solve(x/(x + 1) > 1, x) == And(Lt(-oo, x), Lt(x, -1)) assert solve(sin(x) > S.Half) == And(pi/6 < x, x < pi*Rational(5, 6)) assert solve(Eq(False, x < 1)) == (S.One <= x) & (x < oo) assert solve(Eq(True, x < 1)) == (-oo < x) & (x < 1) assert solve(Eq(x < 1, False)) == (S.One <= x) & (x < oo) assert solve(Eq(x < 1, True)) == (-oo < x) & (x < 1) assert solve(Eq(False, x)) == False assert solve(Eq(0, x)) == [0] assert solve(Eq(True, x)) == True assert solve(Eq(1, x)) == [1] assert solve(Eq(False, ~x)) == True assert solve(Eq(True, ~x)) == False assert solve(Ne(True, x)) == False assert solve(Ne(1, x)) == (x > -oo) & (x < oo) & Ne(x, 1) def test_issue_4793(): assert solve(1/x) == [] assert solve(x*(1 - 5/x)) == [5] assert solve(x + sqrt(x) - 2) == [1] assert solve(-(1 + x)/(2 + x)**2 + 1/(2 + x)) == [] assert solve(-x**2 - 2*x + (x + 1)**2 - 1) == [] assert solve((x/(x + 1) + 3)**(-2)) == [] assert solve(x/sqrt(x**2 + 1), x) == [0] assert solve(exp(x) - y, x) == [log(y)] assert solve(exp(x)) == [] assert solve(x**2 + x + sin(y)**2 + cos(y)**2 - 1, x) in [[0, -1], [-1, 0]] eq = 4*3**(5*x + 2) - 7 ans = solve(eq, x) assert len(ans) == 5 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans) assert solve(log(x**2) - y**2/exp(x), x, y, set=True) == ( [x, y], {(x, sqrt(exp(x) * log(x ** 2))), (x, -sqrt(exp(x) * log(x ** 2)))}) assert solve(x**2*z**2 - z**2*y**2) == [{x: -y}, {x: y}, {z: 0}] assert solve((x - 1)/(1 + 1/(x - 1))) == [] assert solve(x**(y*z) - x, x) == [1] raises(NotImplementedError, lambda: solve(log(x) - exp(x), x)) raises(NotImplementedError, lambda: solve(2**x - exp(x) - 3)) def test_PR1964(): # issue 5171 assert solve(sqrt(x)) == solve(sqrt(x**3)) == [0] assert solve(sqrt(x - 1)) == [1] # issue 4462 a = Symbol('a') assert solve(-3*a/sqrt(x), x) == [] # issue 4486 assert solve(2*x/(x + 2) - 1, x) == [2] # issue 4496 assert set(solve((x**2/(7 - x)).diff(x))) == {S.Zero, S(14)} # issue 4695 f = Function('f') assert solve((3 - 5*x/f(x))*f(x), f(x)) == [x*Rational(5, 3)] # issue 4497 assert solve(1/root(5 + x, 5) - 9, x) == [Rational(-295244, 59049)] assert solve(sqrt(x) + sqrt(sqrt(x)) - 4) == [(Rational(-1, 2) + sqrt(17)/2)**4] assert set(solve(Poly(sqrt(exp(x)) + sqrt(exp(-x)) - 4))) in \ [ {log((-sqrt(3) + 2)**2), log((sqrt(3) + 2)**2)}, {2*log(-sqrt(3) + 2), 2*log(sqrt(3) + 2)}, {log(-4*sqrt(3) + 7), log(4*sqrt(3) + 7)}, ] assert set(solve(Poly(exp(x) + exp(-x) - 4))) == \ {log(-sqrt(3) + 2), log(sqrt(3) + 2)} assert set(solve(x**y + x**(2*y) - 1, x)) == \ {(Rational(-1, 2) + sqrt(5)/2)**(1/y), (Rational(-1, 2) - sqrt(5)/2)**(1/y)} assert solve(exp(x/y)*exp(-z/y) - 2, y) == [(x - z)/log(2)] assert solve( x**z*y**z - 2, z) in [[log(2)/(log(x) + log(y))], [log(2)/(log(x*y))]] # if you do inversion too soon then multiple roots (as for the following) # will be missed, e.g. if exp(3*x) = exp(3) -> 3*x = 3 E = S.Exp1 assert solve(exp(3*x) - exp(3), x) in [ [1, log(E*(Rational(-1, 2) - sqrt(3)*I/2)), log(E*(Rational(-1, 2) + sqrt(3)*I/2))], [1, log(-E/2 - sqrt(3)*E*I/2), log(-E/2 + sqrt(3)*E*I/2)], ] # coverage test p = Symbol('p', positive=True) assert solve((1/p + 1)**(p + 1)) == [] def test_issue_5197(): x = Symbol('x', real=True) assert solve(x**2 + 1, x) == [] n = Symbol('n', integer=True, positive=True) assert solve((n - 1)*(n + 2)*(2*n - 1), n) == [1] x = Symbol('x', positive=True) y = Symbol('y') assert solve([x + 5*y - 2, -3*x + 6*y - 15], x, y) == [] # not {x: -3, y: 1} b/c x is positive # The solution following should not contain (-sqrt(2), sqrt(2)) assert solve([(x + y), 2 - y**2], x, y) == [(sqrt(2), -sqrt(2))] y = Symbol('y', positive=True) # The solution following should not contain {y: -x*exp(x/2)} assert solve(x**2 - y**2/exp(x), y, x, dict=True) == [{y: x*exp(x/2)}] x, y, z = symbols('x y z', positive=True) assert solve(z**2*x**2 - z**2*y**2/exp(x), y, x, z, dict=True) == [{y: x*exp(x/2)}] def test_checking(): assert set( solve(x*(x - y/x), x, check=False)) == {sqrt(y), S.Zero, -sqrt(y)} assert set(solve(x*(x - y/x), x, check=True)) == {sqrt(y), -sqrt(y)} # {x: 0, y: 4} sets denominator to 0 in the following so system should return None assert solve((1/(1/x + 2), 1/(y - 3) - 1)) == [] # 0 sets denominator of 1/x to zero so None is returned assert solve(1/(1/x + 2)) == [] def test_issue_4671_4463_4467(): assert solve(sqrt(x**2 - 1) - 2) in ([sqrt(5), -sqrt(5)], [-sqrt(5), sqrt(5)]) assert solve((2**exp(y**2/x) + 2)/(x**2 + 15), y) == [ -sqrt(x*log(1 + I*pi/log(2))), sqrt(x*log(1 + I*pi/log(2)))] C1, C2 = symbols('C1 C2') f = Function('f') assert solve(C1 + C2/x**2 - exp(-f(x)), f(x)) == [log(x**2/(C1*x**2 + C2))] a = Symbol('a') E = S.Exp1 assert solve(1 - log(a + 4*x**2), x) in ( [-sqrt(-a + E)/2, sqrt(-a + E)/2], [sqrt(-a + E)/2, -sqrt(-a + E)/2] ) assert solve(log(a**(-3) - x**2)/a, x) in ( [-sqrt(-1 + a**(-3)), sqrt(-1 + a**(-3))], [sqrt(-1 + a**(-3)), -sqrt(-1 + a**(-3))],) assert solve(1 - log(a + 4*x**2), x) in ( [-sqrt(-a + E)/2, sqrt(-a + E)/2], [sqrt(-a + E)/2, -sqrt(-a + E)/2],) assert solve((a**2 + 1)*(sin(a*x) + cos(a*x)), x) == [-pi/(4*a)] assert solve(3 - (sinh(a*x) + cosh(a*x)), x) == [log(3)/a] assert set(solve(3 - (sinh(a*x) + cosh(a*x)**2), x)) == \ {log(-2 + sqrt(5))/a, log(-sqrt(2) + 1)/a, log(-sqrt(5) - 2)/a, log(1 + sqrt(2))/a} assert solve(atan(x) - 1) == [tan(1)] def test_issue_5132(): r, t = symbols('r,t') assert set(solve([r - x**2 - y**2, tan(t) - y/x], [x, y])) == \ {( -sqrt(r*cos(t)**2), -1*sqrt(r*cos(t)**2)*tan(t)), (sqrt(r*cos(t)**2), sqrt(r*cos(t)**2)*tan(t))} assert solve([exp(x) - sin(y), 1/y - 3], [x, y]) == \ [(log(sin(Rational(1, 3))), Rational(1, 3))] assert solve([exp(x) - sin(y), 1/exp(y) - 3], [x, y]) == \ [(log(-sin(log(3))), -log(3))] assert set(solve([exp(x) - sin(y), y**2 - 4], [x, y])) == \ {(log(-sin(2)), -S(2)), (log(sin(2)), S(2))} eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3] assert solve(eqs, set=True) == \ ([y, z], { (-log(3), sqrt(-exp(2*x) - sin(log(3)))), (-log(3), -sqrt(-exp(2*x) - sin(log(3))))}) assert solve(eqs, x, z, set=True) == ( [x, z], {(x, sqrt(-exp(2*x) + sin(y))), (x, -sqrt(-exp(2*x) + sin(y)))}) assert set(solve(eqs, x, y)) == \ { (log(-sqrt(-z**2 - sin(log(3)))), -log(3)), (log(-z**2 - sin(log(3)))/2, -log(3))} assert set(solve(eqs, y, z)) == \ { (-log(3), -sqrt(-exp(2*x) - sin(log(3)))), (-log(3), sqrt(-exp(2*x) - sin(log(3))))} eqs = [exp(x)**2 - sin(y) + z, 1/exp(y) - 3] assert solve(eqs, set=True) == ([y, z], { (-log(3), -exp(2*x) - sin(log(3)))}) assert solve(eqs, x, z, set=True) == ( [x, z], {(x, -exp(2*x) + sin(y))}) assert set(solve(eqs, x, y)) == { (log(-sqrt(-z - sin(log(3)))), -log(3)), (log(-z - sin(log(3)))/2, -log(3))} assert solve(eqs, z, y) == \ [(-exp(2*x) - sin(log(3)), -log(3))] assert solve((sqrt(x**2 + y**2) - sqrt(10), x + y - 4), set=True) == ( [x, y], {(S.One, S(3)), (S(3), S.One)}) assert set(solve((sqrt(x**2 + y**2) - sqrt(10), x + y - 4), x, y)) == \ {(S.One, S(3)), (S(3), S.One)} def test_issue_5335(): lam, a0, conc = symbols('lam a0 conc') a = 0.005 b = 0.743436700916726 eqs = [lam + 2*y - a0*(1 - x/2)*x - a*x/2*x, a0*(1 - x/2)*x - 1*y - b*y, x + y - conc] sym = [x, y, a0] # there are 4 solutions obtained manually but only two are valid assert len(solve(eqs, sym, manual=True, minimal=True)) == 2 assert len(solve(eqs, sym)) == 2 # cf below with rational=False @SKIP("Hangs") def _test_issue_5335_float(): # gives ZeroDivisionError: polynomial division lam, a0, conc = symbols('lam a0 conc') a = 0.005 b = 0.743436700916726 eqs = [lam + 2*y - a0*(1 - x/2)*x - a*x/2*x, a0*(1 - x/2)*x - 1*y - b*y, x + y - conc] sym = [x, y, a0] assert len(solve(eqs, sym, rational=False)) == 2 def test_issue_5767(): assert set(solve([x**2 + y + 4], [x])) == \ {(-sqrt(-y - 4),), (sqrt(-y - 4),)} def test_polysys(): assert set(solve([x**2 + 2/y - 2, x + y - 3], [x, y])) == \ {(S.One, S(2)), (1 + sqrt(5), 2 - sqrt(5)), (1 - sqrt(5), 2 + sqrt(5))} assert solve([x**2 + y - 2, x**2 + y]) == [] # the ordering should be whatever the user requested assert solve([x**2 + y - 3, x - y - 4], (x, y)) != solve([x**2 + y - 3, x - y - 4], (y, x)) @slow def test_unrad1(): raises(NotImplementedError, lambda: unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) + 3)) raises(NotImplementedError, lambda: unrad(sqrt(x) + (x + 1)**Rational(1, 3) + 2*sqrt(y))) s = symbols('s', cls=Dummy) # checkers to deal with possibility of answer coming # back with a sign change (cf issue 5203) def check(rv, ans): assert bool(rv[1]) == bool(ans[1]) if ans[1]: return s_check(rv, ans) e = rv[0].expand() a = ans[0].expand() return e in [a, -a] and rv[1] == ans[1] def s_check(rv, ans): # get the dummy rv = list(rv) d = rv[0].atoms(Dummy) reps = list(zip(d, [s]*len(d))) # replace s with this dummy rv = (rv[0].subs(reps).expand(), [rv[1][0].subs(reps), rv[1][1].subs(reps)]) ans = (ans[0].subs(reps).expand(), [ans[1][0].subs(reps), ans[1][1].subs(reps)]) return str(rv[0]) in [str(ans[0]), str(-ans[0])] and \ str(rv[1]) == str(ans[1]) assert unrad(1) is None assert check(unrad(sqrt(x)), (x, [])) assert check(unrad(sqrt(x) + 1), (x - 1, [])) assert check(unrad(sqrt(x) + root(x, 3) + 2), (s**3 + s**2 + 2, [s, s**6 - x])) assert check(unrad(sqrt(x)*root(x, 3) + 2), (x**5 - 64, [])) assert check(unrad(sqrt(x) + (x + 1)**Rational(1, 3)), (x**3 - (x + 1)**2, [])) assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(2*x)), (-2*sqrt(2)*x - 2*x + 1, [])) assert check(unrad(sqrt(x) + sqrt(x + 1) + 2), (16*x - 9, [])) assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - x)), (5*x**2 - 4*x, [])) assert check(unrad(a*sqrt(x) + b*sqrt(x) + c*sqrt(y) + d*sqrt(y)), ((a*sqrt(x) + b*sqrt(x))**2 - (c*sqrt(y) + d*sqrt(y))**2, [])) assert check(unrad(sqrt(x) + sqrt(1 - x)), (2*x - 1, [])) assert check(unrad(sqrt(x) + sqrt(1 - x) - 3), (x**2 - x + 16, [])) assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x)), (5*x**2 - 2*x + 1, [])) assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - 3) in [ (25*x**4 + 376*x**3 + 1256*x**2 - 2272*x + 784, []), (25*x**8 - 476*x**6 + 2534*x**4 - 1468*x**2 + 169, [])] assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - sqrt(1 - 2*x)) == \ (41*x**4 + 40*x**3 + 232*x**2 - 160*x + 16, []) # orig root at 0.487 assert check(unrad(sqrt(x) + sqrt(x + 1)), (S.One, [])) eq = sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) assert check(unrad(eq), (16*x**2 - 9*x, [])) assert set(solve(eq, check=False)) == {S.Zero, Rational(9, 16)} assert solve(eq) == [] # but this one really does have those solutions assert set(solve(sqrt(x) - sqrt(x + 1) + sqrt(1 - sqrt(x)))) == \ {S.Zero, Rational(9, 16)} assert check(unrad(sqrt(x) + root(x + 1, 3) + 2*sqrt(y), y), (S('2*sqrt(x)*(x + 1)**(1/3) + x - 4*y + (x + 1)**(2/3)'), [])) assert check(unrad(sqrt(x/(1 - x)) + (x + 1)**Rational(1, 3)), (x**5 - x**4 - x**3 + 2*x**2 + x - 1, [])) assert check(unrad(sqrt(x/(1 - x)) + 2*sqrt(y), y), (4*x*y + x - 4*y, [])) assert check(unrad(sqrt(x)*sqrt(1 - x) + 2, x), (x**2 - x + 4, [])) # http://tutorial.math.lamar.edu/ # Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a assert solve(Eq(x, sqrt(x + 6))) == [3] assert solve(Eq(x + sqrt(x - 4), 4)) == [4] assert solve(Eq(1, x + sqrt(2*x - 3))) == [] assert set(solve(Eq(sqrt(5*x + 6) - 2, x))) == {-S.One, S(2)} assert set(solve(Eq(sqrt(2*x - 1) - sqrt(x - 4), 2))) == {S(5), S(13)} assert solve(Eq(sqrt(x + 7) + 2, sqrt(3 - x))) == [-6] # http://www.purplemath.com/modules/solverad.htm assert solve((2*x - 5)**Rational(1, 3) - 3) == [16] assert set(solve(x + 1 - root(x**4 + 4*x**3 - x, 4))) == \ {Rational(-1, 2), Rational(-1, 3)} assert set(solve(sqrt(2*x**2 - 7) - (3 - x))) == {-S(8), S(2)} assert solve(sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4)) == [0] assert solve(sqrt(x + 4) + sqrt(2*x - 1) - 3*sqrt(x - 1)) == [5] assert solve(sqrt(x)*sqrt(x - 7) - 12) == [16] assert solve(sqrt(x - 3) + sqrt(x) - 3) == [4] assert solve(sqrt(9*x**2 + 4) - (3*x + 2)) == [0] assert solve(sqrt(x) - 2 - 5) == [49] assert solve(sqrt(x - 3) - sqrt(x) - 3) == [] assert solve(sqrt(x - 1) - x + 7) == [10] assert solve(sqrt(x - 2) - 5) == [27] assert solve(sqrt(17*x - sqrt(x**2 - 5)) - 7) == [3] assert solve(sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x))) == [] # don't posify the expression in unrad and do use _mexpand z = sqrt(2*x + 1)/sqrt(x) - sqrt(2 + 1/x) p = posify(z)[0] assert solve(p) == [] assert solve(z) == [] assert solve(z + 6*I) == [Rational(-1, 11)] assert solve(p + 6*I) == [] # issue 8622 assert unrad(root(x + 1, 5) - root(x, 3)) == ( -(x**5 - x**3 - 3*x**2 - 3*x - 1), []) # issue #8679 assert check(unrad(x + root(x, 3) + root(x, 3)**2 + sqrt(y), x), (s**3 + s**2 + s + sqrt(y), [s, s**3 - x])) # for coverage assert check(unrad(sqrt(x) + root(x, 3) + y), (s**3 + s**2 + y, [s, s**6 - x])) assert solve(sqrt(x) + root(x, 3) - 2) == [1] raises(NotImplementedError, lambda: solve(sqrt(x) + root(x, 3) + root(x + 1, 5) - 2)) # fails through a different code path raises(NotImplementedError, lambda: solve(-sqrt(2) + cosh(x)/x)) # unrad some assert solve(sqrt(x + root(x, 3))+root(x - y, 5), y) == [ x + (x**Rational(1, 3) + x)**Rational(5, 2)] assert check(unrad(sqrt(x) - root(x + 1, 3)*sqrt(x + 2) + 2), (s**10 + 8*s**8 + 24*s**6 - 12*s**5 - 22*s**4 - 160*s**3 - 212*s**2 - 192*s - 56, [s, s**2 - x])) e = root(x + 1, 3) + root(x, 3) assert unrad(e) == (2*x + 1, []) eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5) assert check(unrad(eq), (15625*x**4 + 173000*x**3 + 355600*x**2 - 817920*x + 331776, [])) assert check(unrad(root(x, 4) + root(x, 4)**3 - 1), (s**3 + s - 1, [s, s**4 - x])) assert check(unrad(root(x, 2) + root(x, 2)**3 - 1), (x**3 + 2*x**2 + x - 1, [])) assert unrad(x**0.5) is None assert check(unrad(t + root(x + y, 5) + root(x + y, 5)**3), (s**3 + s + t, [s, s**5 - x - y])) assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, y), (s**3 + s + x, [s, s**5 - x - y])) assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, x), (s**5 + s**3 + s - y, [s, s**5 - x - y])) assert check(unrad(root(x - 1, 3) + root(x + 1, 5) + root(2, 5)), (s**5 + 5*2**Rational(1, 5)*s**4 + s**3 + 10*2**Rational(2, 5)*s**3 + 10*2**Rational(3, 5)*s**2 + 5*2**Rational(4, 5)*s + 4, [s, s**3 - x + 1])) raises(NotImplementedError, lambda: unrad((root(x, 2) + root(x, 3) + root(x, 4)).subs(x, x**5 - x + 1))) # the simplify flag should be reset to False for unrad results; # if it's not then this next test will take a long time assert solve(root(x, 3) + root(x, 5) - 2) == [1] eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5) assert check(unrad(eq), ((5*x - 4)*(3125*x**3 + 37100*x**2 + 100800*x - 82944), [])) ans = S(''' [4/5, -1484/375 + 172564/(140625*(114*sqrt(12657)/78125 + 12459439/52734375)**(1/3)) + 4*(114*sqrt(12657)/78125 + 12459439/52734375)**(1/3)]''') assert solve(eq) == ans # duplicate radical handling assert check(unrad(sqrt(x + root(x + 1, 3)) - root(x + 1, 3) - 2), (s**3 - s**2 - 3*s - 5, [s, s**3 - x - 1])) # cov post-processing e = root(x**2 + 1, 3) - root(x**2 - 1, 5) - 2 assert check(unrad(e), (s**5 - 10*s**4 + 39*s**3 - 80*s**2 + 80*s - 30, [s, s**3 - x**2 - 1])) e = sqrt(x + root(x + 1, 2)) - root(x + 1, 3) - 2 assert check(unrad(e), (s**6 - 2*s**5 - 7*s**4 - 3*s**3 + 26*s**2 + 40*s + 25, [s, s**3 - x - 1])) assert check(unrad(e, _reverse=True), (s**6 - 14*s**5 + 73*s**4 - 187*s**3 + 276*s**2 - 228*s + 89, [s, s**2 - x - sqrt(x + 1)])) # this one needs r0, r1 reversal to work assert check(unrad(sqrt(x + sqrt(root(x, 3) - 1)) - root(x, 6) - 2), (s**12 - 2*s**8 - 8*s**7 - 8*s**6 + s**4 + 8*s**3 + 23*s**2 + 32*s + 17, [s, s**6 - x])) # why does this pass assert unrad(root(cosh(x), 3)/x*root(x + 1, 5) - 1) == ( -(x**15 - x**3*cosh(x)**5 - 3*x**2*cosh(x)**5 - 3*x*cosh(x)**5 - cosh(x)**5), []) # and this fail? #assert unrad(sqrt(cosh(x)/x) + root(x + 1, 3)*sqrt(x) - 1) == ( # -s**6 + 6*s**5 - 15*s**4 + 20*s**3 - 15*s**2 + 6*s + x**5 + # 2*x**4 + x**3 - 1, [s, s**2 - cosh(x)/x]) # watch for symbols in exponents assert unrad(S('(x+y)**(2*y/3) + (x+y)**(1/3) + 1')) is None assert check(unrad(S('(x+y)**(2*y/3) + (x+y)**(1/3) + 1'), x), (s**(2*y) + s + 1, [s, s**3 - x - y])) # should _Q be so lenient? assert unrad(x**(S.Half/y) + y, x) == (x**(1/y) - y**2, []) # This tests two things: that if full unrad is attempted and fails # the solution should still be found; also it tests that the use of # composite assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3 assert len(solve(-512*y**3 + 1344*(x + 2)**Rational(1, 3)*y**2 - 1176*(x + 2)**Rational(2, 3)*y - 169*x + 686, y, _unrad=False)) == 3 # watch out for when the cov doesn't involve the symbol of interest eq = S('-x + (7*y/8 - (27*x/2 + 27*sqrt(x**2)/2)**(1/3)/3)**3 - 1') assert solve(eq, y) == [ 2**(S(2)/3)*(27*x + 27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 + S(512)/343)**(S(1)/3)*(-S(1)/2 - sqrt(3)*I/2), 2**(S(2)/3)*(27*x + 27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 + S(512)/343)**(S(1)/3)*(-S(1)/2 + sqrt(3)*I/2), 2**(S(2)/3)*(27*x + 27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 + S(512)/343)**(S(1)/3)] eq = root(x + 1, 3) - (root(x, 3) + root(x, 5)) assert check(unrad(eq), (3*s**13 + 3*s**11 + s**9 - 1, [s, s**15 - x])) assert check(unrad(eq - 2), (3*s**13 + 3*s**11 + 6*s**10 + s**9 + 12*s**8 + 6*s**6 + 12*s**5 + 12*s**3 + 7, [s, s**15 - x])) assert check(unrad(root(x, 3) - root(x + 1, 4)/2 + root(x + 2, 3)), (s*(4096*s**9 + 960*s**8 + 48*s**7 - s**6 - 1728), [s, s**4 - x - 1])) # orig expr has two real roots: -1, -.389 assert check(unrad(root(x, 3) + root(x + 1, 4) - root(x + 2, 3)/2), (343*s**13 + 2904*s**12 + 1344*s**11 + 512*s**10 - 1323*s**9 - 3024*s**8 - 1728*s**7 + 1701*s**5 + 216*s**4 - 729*s, [s, s**4 - x - 1])) # orig expr has one real root: -0.048 assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3)), (729*s**13 - 216*s**12 + 1728*s**11 - 512*s**10 + 1701*s**9 - 3024*s**8 + 1344*s**7 + 1323*s**5 - 2904*s**4 + 343*s, [s, s**4 - x - 1])) # orig expr has 2 real roots: -0.91, -0.15 assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3) - 2), (729*s**13 + 1242*s**12 + 18496*s**10 + 129701*s**9 + 388602*s**8 + 453312*s**7 - 612864*s**6 - 3337173*s**5 - 6332418*s**4 - 7134912*s**3 - 5064768*s**2 - 2111913*s - 398034, [s, s**4 - x - 1])) # orig expr has 1 real root: 19.53 ans = solve(sqrt(x) + sqrt(x + 1) - sqrt(1 - x) - sqrt(2 + x)) assert len(ans) == 1 and NS(ans[0])[:4] == '0.73' # the fence optimization problem # https://github.com/sympy/sympy/issues/4793#issuecomment-36994519 F = Symbol('F') eq = F - (2*x + 2*y + sqrt(x**2 + y**2)) ans = F*Rational(2, 7) - sqrt(2)*F/14 X = solve(eq, x, check=False) for xi in reversed(X): # reverse since currently, ans is the 2nd one Y = solve((x*y).subs(x, xi).diff(y), y, simplify=False, check=False) if any((a - ans).expand().is_zero for a in Y): break else: assert None # no answer was found assert solve(sqrt(x + 1) + root(x, 3) - 2) == S(''' [(-11/(9*(47/54 + sqrt(93)/6)**(1/3)) + 1/3 + (47/54 + sqrt(93)/6)**(1/3))**3]''') assert solve(sqrt(sqrt(x + 1)) + x**Rational(1, 3) - 2) == S(''' [(-sqrt(-2*(-1/16 + sqrt(6913)/16)**(1/3) + 6/(-1/16 + sqrt(6913)/16)**(1/3) + 17/2 + 121/(4*sqrt(-6/(-1/16 + sqrt(6913)/16)**(1/3) + 2*(-1/16 + sqrt(6913)/16)**(1/3) + 17/4)))/2 + sqrt(-6/(-1/16 + sqrt(6913)/16)**(1/3) + 2*(-1/16 + sqrt(6913)/16)**(1/3) + 17/4)/2 + 9/4)**3]''') assert solve(sqrt(x) + root(sqrt(x) + 1, 3) - 2) == S(''' [(-(81/2 + 3*sqrt(741)/2)**(1/3)/3 + (81/2 + 3*sqrt(741)/2)**(-1/3) + 2)**2]''') eq = S(''' -x + (1/2 - sqrt(3)*I/2)*(3*x**3/2 - x*(3*x**2 - 34)/2 + sqrt((-3*x**3 + x*(3*x**2 - 34) + 90)**2/4 - 39304/27) - 45)**(1/3) + 34/(3*(1/2 - sqrt(3)*I/2)*(3*x**3/2 - x*(3*x**2 - 34)/2 + sqrt((-3*x**3 + x*(3*x**2 - 34) + 90)**2/4 - 39304/27) - 45)**(1/3))''') assert check(unrad(eq), (s*-(-s**6 + sqrt(3)*s**6*I - 153*2**Rational(2, 3)*3**Rational(1, 3)*s**4 + 51*12**Rational(1, 3)*s**4 - 102*2**Rational(2, 3)*3**Rational(5, 6)*s**4*I - 1620*s**3 + 1620*sqrt(3)*s**3*I + 13872*18**Rational(1, 3)*s**2 - 471648 + 471648*sqrt(3)*I), [s, s**3 - 306*x - sqrt(3)*sqrt(31212*x**2 - 165240*x + 61484) + 810])) assert solve(eq) == [] # not other code errors eq = root(x, 3) - root(y, 3) + root(x, 5) assert check(unrad(eq), (s**15 + 3*s**13 + 3*s**11 + s**9 - y, [s, s**15 - x])) eq = root(x, 3) + root(y, 3) + root(x*y, 4) assert check(unrad(eq), (s*y*(-s**12 - 3*s**11*y - 3*s**10*y**2 - s**9*y**3 - 3*s**8*y**2 + 21*s**7*y**3 - 3*s**6*y**4 - 3*s**4*y**4 - 3*s**3*y**5 - y**6), [s, s**4 - x*y])) raises(NotImplementedError, lambda: unrad(root(x, 3) + root(y, 3) + root(x*y, 5))) # Test unrad with an Equality eq = Eq(-x**(S(1)/5) + x**(S(1)/3), -3**(S(1)/3) - (-1)**(S(3)/5)*3**(S(1)/5)) assert check(unrad(eq), (-s**5 + s**3 - 3**(S(1)/3) - (-1)**(S(3)/5)*3**(S(1)/5), [s, s**15 - x])) # make sure buried radicals are exposed s = sqrt(x) - 1 assert unrad(s**2 - s**3) == (x**3 - 6*x**2 + 9*x - 4, []) # make sure numerators which are already polynomial are rejected assert unrad((x/(x + 1) + 3)**(-2), x) is None # https://github.com/sympy/sympy/issues/23707 eq = sqrt(x - y)*exp(t*sqrt(x - y)) - exp(t*sqrt(x - y)) assert solve(eq, y) == [x - 1] assert unrad(eq) is None @slow def test_unrad_slow(): # this has roots with multiplicity > 1; there should be no # repeats in roots obtained, however eq = (sqrt(1 + sqrt(1 - 4*x**2)) - x*(1 + sqrt(1 + 2*sqrt(1 - 4*x**2)))) assert solve(eq) == [S.Half] @XFAIL def test_unrad_fail(): # this only works if we check real_root(eq.subs(x, Rational(1, 3))) # but checksol doesn't work like that assert solve(root(x**3 - 3*x**2, 3) + 1 - x) == [Rational(1, 3)] assert solve(root(x + 1, 3) + root(x**2 - 2, 5) + 1) == [ -1, -1 + CRootOf(x**5 + x**4 + 5*x**3 + 8*x**2 + 10*x + 5, 0)**3] def test_checksol(): x, y, r, t = symbols('x, y, r, t') eq = r - x**2 - y**2 dict_var_soln = {y: - sqrt(r) / sqrt(tan(t)**2 + 1), x: -sqrt(r)*tan(t)/sqrt(tan(t)**2 + 1)} assert checksol(eq, dict_var_soln) == True assert checksol(Eq(x, False), {x: False}) is True assert checksol(Ne(x, False), {x: False}) is False assert checksol(Eq(x < 1, True), {x: 0}) is True assert checksol(Eq(x < 1, True), {x: 1}) is False assert checksol(Eq(x < 1, False), {x: 1}) is True assert checksol(Eq(x < 1, False), {x: 0}) is False assert checksol(Eq(x + 1, x**2 + 1), {x: 1}) is True assert checksol([x - 1, x**2 - 1], x, 1) is True assert checksol([x - 1, x**2 - 2], x, 1) is False assert checksol(Poly(x**2 - 1), x, 1) is True assert checksol(0, {}) is True assert checksol([1e-10, x - 2], x, 2) is False assert checksol([0.5, 0, x], x, 0) is False assert checksol(y, x, 2) is False assert checksol(x+1e-10, x, 0, numerical=True) is True assert checksol(x+1e-10, x, 0, numerical=False) is False assert checksol(exp(92*x), {x: log(sqrt(2)/2)}) is False assert checksol(exp(92*x), {x: log(sqrt(2)/2) + I*pi}) is False assert checksol(1/x**5, x, 1000) is False raises(ValueError, lambda: checksol(x, 1)) raises(ValueError, lambda: checksol([], x, 1)) def test__invert(): assert _invert(x - 2) == (2, x) assert _invert(2) == (2, 0) assert _invert(exp(1/x) - 3, x) == (1/log(3), x) assert _invert(exp(1/x + a/x) - 3, x) == ((a + 1)/log(3), x) assert _invert(a, x) == (a, 0) def test_issue_4463(): assert solve(-a*x + 2*x*log(x), x) == [exp(a/2)] assert solve(x**x) == [] assert solve(x**x - 2) == [exp(LambertW(log(2)))] assert solve(((x - 3)*(x - 2))**((x - 3)*(x - 4))) == [2] @slow def test_issue_5114_solvers(): a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('a:r') # there is no 'a' in the equation set but this is how the # problem was originally posed syms = a, b, c, f, h, k, n eqs = [b + r/d - c/d, c*(1/d + 1/e + 1/g) - f/g - r/d, f*(1/g + 1/i + 1/j) - c/g - h/i, h*(1/i + 1/l + 1/m) - f/i - k/m, k*(1/m + 1/o + 1/p) - h/m - n/p, n*(1/p + 1/q) - k/p] assert len(solve(eqs, syms, manual=True, check=False, simplify=False)) == 1 def test_issue_5849(): # # XXX: This system does not have a solution for most values of the # parameters. Generally solve returns the empty set for systems that are # generically inconsistent. # I1, I2, I3, I4, I5, I6 = symbols('I1:7') dI1, dI4, dQ2, dQ4, Q2, Q4 = symbols('dI1,dI4,dQ2,dQ4,Q2,Q4') e = ( I1 - I2 - I3, I3 - I4 - I5, I4 + I5 - I6, -I1 + I2 + I6, -2*I1 - 2*I3 - 2*I5 - 3*I6 - dI1/2 + 12, -I4 + dQ4, -I2 + dQ2, 2*I3 + 2*I5 + 3*I6 - Q2, I4 - 2*I5 + 2*Q4 + dI4 ) ans = [{ I1: I2 + I3, dI1: -4*I2 - 8*I3 - 4*I5 - 6*I6 + 24, I4: I3 - I5, dQ4: I3 - I5, Q4: -I3/2 + 3*I5/2 - dI4/2, dQ2: I2, Q2: 2*I3 + 2*I5 + 3*I6}] v = I1, I4, Q2, Q4, dI1, dI4, dQ2, dQ4 assert solve(e, *v, manual=True, check=False, dict=True) == ans assert solve(e, *v, manual=True, check=False) == [ tuple([a.get(i, i) for i in v]) for a in ans] assert solve(e, *v, manual=True) == [] assert solve(e, *v) == [] # the matrix solver (tested below) doesn't like this because it produces # a zero row in the matrix. Is this related to issue 4551? assert [ei.subs( ans[0]) for ei in e] == [0, 0, I3 - I6, -I3 + I6, 0, 0, 0, 0, 0] def test_issue_5849_matrix(): '''Same as test_issue_5849 but solved with the matrix solver. A solution only exists if I3 == I6 which is not generically true, but `solve` does not return conditions under which the solution is valid, only a solution that is canonical and consistent with the input. ''' # a simple example with the same issue # assert solve([x+y+z, x+y], [x, y]) == {x: y} # the longer example I1, I2, I3, I4, I5, I6 = symbols('I1:7') dI1, dI4, dQ2, dQ4, Q2, Q4 = symbols('dI1,dI4,dQ2,dQ4,Q2,Q4') e = ( I1 - I2 - I3, I3 - I4 - I5, I4 + I5 - I6, -I1 + I2 + I6, -2*I1 - 2*I3 - 2*I5 - 3*I6 - dI1/2 + 12, -I4 + dQ4, -I2 + dQ2, 2*I3 + 2*I5 + 3*I6 - Q2, I4 - 2*I5 + 2*Q4 + dI4 ) assert solve(e, I1, I4, Q2, Q4, dI1, dI4, dQ2, dQ4) == [] def test_issue_21882(): a, b, c, d, f, g, k = unknowns = symbols('a, b, c, d, f, g, k') equations = [ -k*a + b + 5*f/6 + 2*c/9 + 5*d/6 + 4*a/3, -k*f + 4*f/3 + d/2, -k*d + f/6 + d, 13*b/18 + 13*c/18 + 13*a/18, -k*c + b/2 + 20*c/9 + a, -k*b + b + c/18 + a/6, 5*b/3 + c/3 + a, 2*b/3 + 2*c + 4*a/3, -g, ] answer = [ {a: 0, f: 0, b: 0, d: 0, c: 0, g: 0}, {a: 0, f: -d, b: 0, k: S(5)/6, c: 0, g: 0}, {a: -2*c, f: 0, b: c, d: 0, k: S(13)/18, g: 0}] # but not {a: 0, f: 0, b: 0, k: S(3)/2, c: 0, d: 0, g: 0} # since this is already covered by the first solution got = solve(equations, unknowns, dict=True) assert got == answer, (got,answer) def test_issue_5901(): f, g, h = map(Function, 'fgh') a = Symbol('a') D = Derivative(f(x), x) G = Derivative(g(a), a) assert solve(f(x) + f(x).diff(x), f(x)) == \ [-D] assert solve(f(x) - 3, f(x)) == \ [3] assert solve(f(x) - 3*f(x).diff(x), f(x)) == \ [3*D] assert solve([f(x) - 3*f(x).diff(x)], f(x)) == \ {f(x): 3*D} assert solve([f(x) - 3*f(x).diff(x), f(x)**2 - y + 4], f(x), y) == \ [(3*D, 9*D**2 + 4)] assert solve(-f(a)**2*g(a)**2 + f(a)**2*h(a)**2 + g(a).diff(a), h(a), g(a), set=True) == \ ([h(a), g(a)], { (-sqrt(f(a)**2*g(a)**2 - G)/f(a), g(a)), (sqrt(f(a)**2*g(a)**2 - G)/f(a), g(a))}), solve(-f(a)**2*g(a)**2 + f(a)**2*h(a)**2 + g(a).diff(a), h(a), g(a), set=True) args = [[f(x).diff(x, 2)*(f(x) + g(x)), 2 - g(x)**2], f(x), g(x)] assert solve(*args, set=True)[1] == \ {(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))} eqs = [f(x)**2 + g(x) - 2*f(x).diff(x), g(x)**2 - 4] assert solve(eqs, f(x), g(x), set=True) == \ ([f(x), g(x)], { (-sqrt(2*D - 2), S(2)), (sqrt(2*D - 2), S(2)), (-sqrt(2*D + 2), -S(2)), (sqrt(2*D + 2), -S(2))}) # the underlying problem was in solve_linear that was not masking off # anything but a Mul or Add; it now raises an error if it gets anything # but a symbol and solve handles the substitutions necessary so solve_linear # won't make this error raises( ValueError, lambda: solve_linear(f(x) + f(x).diff(x), symbols=[f(x)])) assert solve_linear(f(x) + f(x).diff(x), symbols=[x]) == \ (f(x) + Derivative(f(x), x), 1) assert solve_linear(f(x) + Integral(x, (x, y)), symbols=[x]) == \ (f(x) + Integral(x, (x, y)), 1) assert solve_linear(f(x) + Integral(x, (x, y)) + x, symbols=[x]) == \ (x + f(x) + Integral(x, (x, y)), 1) assert solve_linear(f(y) + Integral(x, (x, y)) + x, symbols=[x]) == \ (x, -f(y) - Integral(x, (x, y))) assert solve_linear(x - f(x)/a + (f(x) - 1)/a, symbols=[x]) == \ (x, 1/a) assert solve_linear(x + Derivative(2*x, x)) == \ (x, -2) assert solve_linear(x + Integral(x, y), symbols=[x]) == \ (x, 0) assert solve_linear(x + Integral(x, y) - 2, symbols=[x]) == \ (x, 2/(y + 1)) assert set(solve(x + exp(x)**2, exp(x))) == \ {-sqrt(-x), sqrt(-x)} assert solve(x + exp(x), x, implicit=True) == \ [-exp(x)] assert solve(cos(x) - sin(x), x, implicit=True) == [] assert solve(x - sin(x), x, implicit=True) == \ [sin(x)] assert solve(x**2 + x - 3, x, implicit=True) == \ [-x**2 + 3] assert solve(x**2 + x - 3, x**2, implicit=True) == \ [-x + 3] def test_issue_5912(): assert set(solve(x**2 - x - 0.1, rational=True)) == \ {S.Half + sqrt(35)/10, -sqrt(35)/10 + S.Half} ans = solve(x**2 - x - 0.1, rational=False) assert len(ans) == 2 and all(a.is_Number for a in ans) ans = solve(x**2 - x - 0.1) assert len(ans) == 2 and all(a.is_Number for a in ans) def test_float_handling(): def test(e1, e2): return len(e1.atoms(Float)) == len(e2.atoms(Float)) assert solve(x - 0.5, rational=True)[0].is_Rational assert solve(x - 0.5, rational=False)[0].is_Float assert solve(x - S.Half, rational=False)[0].is_Rational assert solve(x - 0.5, rational=None)[0].is_Float assert solve(x - S.Half, rational=None)[0].is_Rational assert test(nfloat(1 + 2*x), 1.0 + 2.0*x) for contain in [list, tuple, set]: ans = nfloat(contain([1 + 2*x])) assert type(ans) is contain and test(list(ans)[0], 1.0 + 2.0*x) k, v = list(nfloat({2*x: [1 + 2*x]}).items())[0] assert test(k, 2*x) and test(v[0], 1.0 + 2.0*x) assert test(nfloat(cos(2*x)), cos(2.0*x)) assert test(nfloat(3*x**2), 3.0*x**2) assert test(nfloat(3*x**2, exponent=True), 3.0*x**2.0) assert test(nfloat(exp(2*x)), exp(2.0*x)) assert test(nfloat(x/3), x/3.0) assert test(nfloat(x**4 + 2*x + cos(Rational(1, 3)) + 1), x**4 + 2.0*x + 1.94495694631474) # don't call nfloat if there is no solution tot = 100 + c + z + t assert solve(((.7 + c)/tot - .6, (.2 + z)/tot - .3, t/tot - .1)) == [] def test_check_assumptions(): x = symbols('x', positive=True) assert solve(x**2 - 1) == [1] def test_issue_6056(): assert solve(tanh(x + 3)*tanh(x - 3) - 1) == [] assert solve(tanh(x - 1)*tanh(x + 1) + 1) == \ [I*pi*Rational(-3, 4), -I*pi/4, I*pi/4, I*pi*Rational(3, 4)] assert solve((tanh(x + 3)*tanh(x - 3) + 1)**2) == \ [I*pi*Rational(-3, 4), -I*pi/4, I*pi/4, I*pi*Rational(3, 4)] def test_issue_5673(): eq = -x + exp(exp(LambertW(log(x)))*LambertW(log(x))) assert checksol(eq, x, 2) is True assert checksol(eq, x, 2, numerical=False) is None def test_exclude(): R, C, Ri, Vout, V1, Vminus, Vplus, s = \ symbols('R, C, Ri, Vout, V1, Vminus, Vplus, s') Rf = symbols('Rf', positive=True) # to eliminate Rf = 0 soln eqs = [C*V1*s + Vplus*(-2*C*s - 1/R), Vminus*(-1/Ri - 1/Rf) + Vout/Rf, C*Vplus*s + V1*(-C*s - 1/R) + Vout/R, -Vminus + Vplus] assert solve(eqs, exclude=s*C*R) == [ { Rf: Ri*(C*R*s + 1)**2/(C*R*s), Vminus: Vplus, V1: 2*Vplus + Vplus/(C*R*s), Vout: C*R*Vplus*s + 3*Vplus + Vplus/(C*R*s)}, { Vplus: 0, Vminus: 0, V1: 0, Vout: 0}, ] # TODO: Investigate why currently solution [0] is preferred over [1]. assert solve(eqs, exclude=[Vplus, s, C]) in [[{ Vminus: Vplus, V1: Vout/2 + Vplus/2 + sqrt((Vout - 5*Vplus)*(Vout - Vplus))/2, R: (Vout - 3*Vplus - sqrt(Vout**2 - 6*Vout*Vplus + 5*Vplus**2))/(2*C*Vplus*s), Rf: Ri*(Vout - Vplus)/Vplus, }, { Vminus: Vplus, V1: Vout/2 + Vplus/2 - sqrt((Vout - 5*Vplus)*(Vout - Vplus))/2, R: (Vout - 3*Vplus + sqrt(Vout**2 - 6*Vout*Vplus + 5*Vplus**2))/(2*C*Vplus*s), Rf: Ri*(Vout - Vplus)/Vplus, }], [{ Vminus: Vplus, Vout: (V1**2 - V1*Vplus - Vplus**2)/(V1 - 2*Vplus), Rf: Ri*(V1 - Vplus)**2/(Vplus*(V1 - 2*Vplus)), R: Vplus/(C*s*(V1 - 2*Vplus)), }]] def test_high_order_roots(): s = x**5 + 4*x**3 + 3*x**2 + Rational(7, 4) assert set(solve(s)) == set(Poly(s*4, domain='ZZ').all_roots()) def test_minsolve_linear_system(): pqt = dict(quick=True, particular=True) pqf = dict(quick=False, particular=True) assert solve([x + y - 5, 2*x - y - 1], **pqt) == {x: 2, y: 3} assert solve([x + y - 5, 2*x - y - 1], **pqf) == {x: 2, y: 3} def count(dic): return len([x for x in dic.values() if x == 0]) assert count(solve([x + y + z, y + z + a + t], **pqt)) == 3 assert count(solve([x + y + z, y + z + a + t], **pqf)) == 3 assert count(solve([x + y + z, y + z + a], **pqt)) == 1 assert count(solve([x + y + z, y + z + a], **pqf)) == 2 # issue 22718 A = Matrix([ [ 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0], [ 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, -1, -1, 0, 0], [-1, -1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 1, 0, 1], [ 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, -1, 0, -1, 0], [-1, 0, -1, 0, 0, -1, 0, 0, 0, 0, 1, 0, 1, 1], [-1, 0, 0, -1, 0, 0, -1, 0, 0, 0, -1, 0, 0, -1], [ 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, -1, -1, 0], [ 0, -1, -1, 0, 0, 0, 0, -1, 0, 0, 0, 1, 1, 1], [ 0, -1, 0, -1, 0, 0, 0, 0, -1, 0, 0, -1, 0, -1], [ 0, 0, -1, -1, 0, 0, 0, 0, 0, -1, 0, 0, -1, -1], [ 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [ 0, 0, 0, 0, -1, -1, 0, -1, 0, 0, 0, 0, 0, 0]]) v = Matrix(symbols("v:14", integer=True)) B = Matrix([[2], [-2], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]) eqs = A@v-B assert solve(eqs) == [] assert solve(eqs, particular=True) == [] # assumption violated assert all(v for v in solve([x + y + z, y + z + a]).values()) for _q in (True, False): assert not all(v for v in solve( [x + y + z, y + z + a], quick=_q, particular=True).values()) # raise error if quick used w/o particular=True raises(ValueError, lambda: solve([x + 1], quick=_q)) raises(ValueError, lambda: solve([x + 1], quick=_q, particular=False)) # and give a good error message if someone tries to use # particular with a single equation raises(ValueError, lambda: solve(x + 1, particular=True)) def test_real_roots(): # cf. issue 6650 x = Symbol('x', real=True) assert len(solve(x**5 + x**3 + 1)) == 1 def test_issue_6528(): eqs = [ 327600995*x**2 - 37869137*x + 1809975124*y**2 - 9998905626, 895613949*x**2 - 273830224*x*y + 530506983*y**2 - 10000000000] # two expressions encountered are > 1400 ops long so if this hangs # it is likely because simplification is being done assert len(solve(eqs, y, x, check=False)) == 4 def test_overdetermined(): x = symbols('x', real=True) eqs = [Abs(4*x - 7) - 5, Abs(3 - 8*x) - 1] assert solve(eqs, x) == [(S.Half,)] assert solve(eqs, x, manual=True) == [(S.Half,)] assert solve(eqs, x, manual=True, check=False) == [(S.Half,), (S(3),)] def test_issue_6605(): x = symbols('x') assert solve(4**(x/2) - 2**(x/3)) == [0, 3*I*pi/log(2)] # while the first one passed, this one failed x = symbols('x', real=True) assert solve(5**(x/2) - 2**(x/3)) == [0] b = sqrt(6)*sqrt(log(2))/sqrt(log(5)) assert solve(5**(x/2) - 2**(3/x)) == [-b, b] def test__ispow(): assert _ispow(x**2) assert not _ispow(x) assert not _ispow(True) def test_issue_6644(): eq = -sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) + sqrt((-m**2/2 - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2) sol = solve(eq, q, simplify=False, check=False) assert len(sol) == 5 def test_issue_6752(): assert solve([a**2 + a, a - b], [a, b]) == [(-1, -1), (0, 0)] assert solve([a**2 + a*c, a - b], [a, b]) == [(0, 0), (-c, -c)] def test_issue_6792(): assert solve(x*(x - 1)**2*(x + 1)*(x**6 - x + 1)) == [ -1, 0, 1, CRootOf(x**6 - x + 1, 0), CRootOf(x**6 - x + 1, 1), CRootOf(x**6 - x + 1, 2), CRootOf(x**6 - x + 1, 3), CRootOf(x**6 - x + 1, 4), CRootOf(x**6 - x + 1, 5)] def test_issues_6819_6820_6821_6248_8692(): # issue 6821 x, y = symbols('x y', real=True) assert solve(abs(x + 3) - 2*abs(x - 3)) == [1, 9] assert solve([abs(x) - 2, arg(x) - pi], x) == [(-2,)] assert set(solve(abs(x - 7) - 8)) == {-S.One, S(15)} # issue 8692 assert solve(Eq(Abs(x + 1) + Abs(x**2 - 7), 9), x) == [ Rational(-1, 2) + sqrt(61)/2, -sqrt(69)/2 + S.Half] # issue 7145 assert solve(2*abs(x) - abs(x - 1)) == [-1, Rational(1, 3)] x = symbols('x') assert solve([re(x) - 1, im(x) - 2], x) == [ {re(x): 1, x: 1 + 2*I, im(x): 2}] # check for 'dict' handling of solution eq = sqrt(re(x)**2 + im(x)**2) - 3 assert solve(eq) == solve(eq, x) i = symbols('i', imaginary=True) assert solve(abs(i) - 3) == [-3*I, 3*I] raises(NotImplementedError, lambda: solve(abs(x) - 3)) w = symbols('w', integer=True) assert solve(2*x**w - 4*y**w, w) == solve((x/y)**w - 2, w) x, y = symbols('x y', real=True) assert solve(x + y*I + 3) == {y: 0, x: -3} # issue 2642 assert solve(x*(1 + I)) == [0] x, y = symbols('x y', imaginary=True) assert solve(x + y*I + 3 + 2*I) == {x: -2*I, y: 3*I} x = symbols('x', real=True) assert solve(x + y + 3 + 2*I) == {x: -3, y: -2*I} # issue 6248 f = Function('f') assert solve(f(x + 1) - f(2*x - 1)) == [2] assert solve(log(x + 1) - log(2*x - 1)) == [2] x = symbols('x') assert solve(2**x + 4**x) == [I*pi/log(2)] def test_issue_14607(): # issue 14607 s, tau_c, tau_1, tau_2, phi, K = symbols( 's, tau_c, tau_1, tau_2, phi, K') target = (s**2*tau_1*tau_2 + s*tau_1 + s*tau_2 + 1)/(K*s*(-phi + tau_c)) K_C, tau_I, tau_D = symbols('K_C, tau_I, tau_D', positive=True, nonzero=True) PID = K_C*(1 + 1/(tau_I*s) + tau_D*s) eq = (target - PID).together() eq *= denom(eq).simplify() eq = Poly(eq, s) c = eq.coeffs() vars = [K_C, tau_I, tau_D] s = solve(c, vars, dict=True) assert len(s) == 1 knownsolution = {K_C: -(tau_1 + tau_2)/(K*(phi - tau_c)), tau_I: tau_1 + tau_2, tau_D: tau_1*tau_2/(tau_1 + tau_2)} for var in vars: assert s[0][var].simplify() == knownsolution[var].simplify() def test_lambert_multivariate(): from sympy.abc import x, y assert _filtered_gens(Poly(x + 1/x + exp(x) + y), x) == {x, exp(x)} assert _lambert(x, x) == [] assert solve((x**2 - 2*x + 1).subs(x, log(x) + 3*x)) == [LambertW(3*S.Exp1)/3] assert solve((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1)) == \ [LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3] assert solve((x**2 - 2*x - 2).subs(x, log(x) + 3*x)) == \ [LambertW(3*exp(1 - sqrt(3)))/3, LambertW(3*exp(1 + sqrt(3)))/3] eq = (x*exp(x) - 3).subs(x, x*exp(x)) assert solve(eq) == [LambertW(3*exp(-LambertW(3)))] # coverage test raises(NotImplementedError, lambda: solve(x - sin(x)*log(y - x), x)) ans = [3, -3*LambertW(-log(3)/3)/log(3)] # 3 and 2.478... assert solve(x**3 - 3**x, x) == ans assert set(solve(3*log(x) - x*log(3))) == set(ans) assert solve(LambertW(2*x) - y, x) == [y*exp(y)/2] @XFAIL def test_other_lambert(): assert solve(3*sin(x) - x*sin(3), x) == [3] assert set(solve(x**a - a**x), x) == { a, -a*LambertW(-log(a)/a)/log(a)} @slow def test_lambert_bivariate(): # tests passing current implementation assert solve((x**2 + x)*exp(x**2 + x) - 1) == [ Rational(-1, 2) + sqrt(1 + 4*LambertW(1))/2, Rational(-1, 2) - sqrt(1 + 4*LambertW(1))/2] assert solve((x**2 + x)*exp((x**2 + x)*2) - 1) == [ Rational(-1, 2) + sqrt(1 + 2*LambertW(2))/2, Rational(-1, 2) - sqrt(1 + 2*LambertW(2))/2] assert solve(a/x + exp(x/2), x) == [2*LambertW(-a/2)] assert solve((a/x + exp(x/2)).diff(x), x) == \ [4*LambertW(-sqrt(2)*sqrt(a)/4), 4*LambertW(sqrt(2)*sqrt(a)/4)] assert solve((1/x + exp(x/2)).diff(x), x) == \ [4*LambertW(-sqrt(2)/4), 4*LambertW(sqrt(2)/4), # nsimplifies as 2*2**(141/299)*3**(206/299)*5**(205/299)*7**(37/299)/21 4*LambertW(-sqrt(2)/4, -1)] assert solve(x*log(x) + 3*x + 1, x) == \ [exp(-3 + LambertW(-exp(3)))] assert solve(-x**2 + 2**x, x) == [2, 4, -2*LambertW(log(2)/2)/log(2)] assert solve(x**2 - 2**x, x) == [2, 4, -2*LambertW(log(2)/2)/log(2)] ans = solve(3*x + 5 + 2**(-5*x + 3), x) assert len(ans) == 1 and ans[0].expand() == \ Rational(-5, 3) + LambertW(-10240*root(2, 3)*log(2)/3)/(5*log(2)) assert solve(5*x - 1 + 3*exp(2 - 7*x), x) == \ [Rational(1, 5) + LambertW(-21*exp(Rational(3, 5))/5)/7] assert solve((log(x) + x).subs(x, x**2 + 1)) == [ -I*sqrt(-LambertW(1) + 1), sqrt(-1 + LambertW(1))] # check collection ax = a**(3*x + 5) ans = solve(3*log(ax) + b*log(ax) + ax, x) x0 = 1/log(a) x1 = sqrt(3)*I x2 = b + 3 x3 = x2*LambertW(1/x2)/a**5 x4 = x3**Rational(1, 3)/2 assert ans == [ x0*log(x4*(-x1 - 1)), x0*log(x4*(x1 - 1)), x0*log(x3)/3] x1 = LambertW(Rational(1, 3)) x2 = a**(-5) x3 = -3**Rational(1, 3) x4 = 3**Rational(5, 6)*I x5 = x1**Rational(1, 3)*x2**Rational(1, 3)/2 ans = solve(3*log(ax) + ax, x) assert ans == [ x0*log(3*x1*x2)/3, x0*log(x5*(x3 - x4)), x0*log(x5*(x3 + x4))] # coverage p = symbols('p', positive=True) eq = 4*2**(2*p + 3) - 2*p - 3 assert _solve_lambert(eq, p, _filtered_gens(Poly(eq), p)) == [ Rational(-3, 2) - LambertW(-4*log(2))/(2*log(2))] assert set(solve(3**cos(x) - cos(x)**3)) == { acos(3), acos(-3*LambertW(-log(3)/3)/log(3))} # should give only one solution after using `uniq` assert solve(2*log(x) - 2*log(z) + log(z + log(x) + log(z)), x) == [ exp(-z + LambertW(2*z**4*exp(2*z))/2)/z] # cases when p != S.One # issue 4271 ans = solve((a/x + exp(x/2)).diff(x, 2), x) x0 = (-a)**Rational(1, 3) x1 = sqrt(3)*I x2 = x0/6 assert ans == [ 6*LambertW(x0/3), 6*LambertW(x2*(-x1 - 1)), 6*LambertW(x2*(x1 - 1))] assert solve((1/x + exp(x/2)).diff(x, 2), x) == \ [6*LambertW(Rational(-1, 3)), 6*LambertW(Rational(1, 6) - sqrt(3)*I/6), \ 6*LambertW(Rational(1, 6) + sqrt(3)*I/6), 6*LambertW(Rational(-1, 3), -1)] assert solve(x**2 - y**2/exp(x), x, y, dict=True) == \ [{x: 2*LambertW(-y/2)}, {x: 2*LambertW(y/2)}] # this is slow but not exceedingly slow assert solve((x**3)**(x/2) + pi/2, x) == [ exp(LambertW(-2*log(2)/3 + 2*log(pi)/3 + I*pi*Rational(2, 3)))] # issue 23253 assert solve((1/log(sqrt(x) + 2)**2 - 1/x)) == [ (LambertW(-exp(-2), -1) + 2)**2] assert solve((1/log(1/sqrt(x) + 2)**2 - x)) == [ (LambertW(-exp(-2), -1) + 2)**-2] assert solve((1/log(x**2 + 2)**2 - x**-4)) == [ -I*sqrt(2 - LambertW(exp(2))), -I*sqrt(LambertW(-exp(-2)) + 2), sqrt(-2 - LambertW(-exp(-2))), sqrt(-2 + LambertW(exp(2))), -sqrt(-2 - LambertW(-exp(-2), -1)), sqrt(-2 - LambertW(-exp(-2), -1))] def test_rewrite_trig(): assert solve(sin(x) + tan(x)) == [0, -pi, pi, 2*pi] assert solve(sin(x) + sec(x)) == [ -2*atan(Rational(-1, 2) + sqrt(2)*sqrt(1 - sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half - sqrt(2)*sqrt(1 + sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half + sqrt(2)*sqrt(1 + sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half - sqrt(3)*I/2 + sqrt(2)*sqrt(1 - sqrt(3)*I)/2)] assert solve(sinh(x) + tanh(x)) == [0, I*pi] # issue 6157 assert solve(2*sin(x) - cos(x), x) == [atan(S.Half)] @XFAIL def test_rewrite_trigh(): # if this import passes then the test below should also pass from sympy.functions.elementary.hyperbolic import sech assert solve(sinh(x) + sech(x)) == [ 2*atanh(Rational(-1, 2) + sqrt(5)/2 - sqrt(-2*sqrt(5) + 2)/2), 2*atanh(Rational(-1, 2) + sqrt(5)/2 + sqrt(-2*sqrt(5) + 2)/2), 2*atanh(-sqrt(5)/2 - S.Half + sqrt(2 + 2*sqrt(5))/2), 2*atanh(-sqrt(2 + 2*sqrt(5))/2 - sqrt(5)/2 - S.Half)] def test_uselogcombine(): eq = z - log(x) + log(y/(x*(-1 + y**2/x**2))) assert solve(eq, x, force=True) == [-sqrt(y*(y - exp(z))), sqrt(y*(y - exp(z)))] assert solve(log(x + 3) + log(1 + 3/x) - 3) in [ [-3 + sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 + exp(3)/2, -sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 - 3 + exp(3)/2], [-3 + sqrt(-36 + (-exp(3) + 6)**2)/2 + exp(3)/2, -3 - sqrt(-36 + (-exp(3) + 6)**2)/2 + exp(3)/2], ] assert solve(log(exp(2*x) + 1) + log(-tanh(x) + 1) - log(2)) == [] def test_atan2(): assert solve(atan2(x, 2) - pi/3, x) == [2*sqrt(3)] def test_errorinverses(): assert solve(erf(x) - y, x) == [erfinv(y)] assert solve(erfinv(x) - y, x) == [erf(y)] assert solve(erfc(x) - y, x) == [erfcinv(y)] assert solve(erfcinv(x) - y, x) == [erfc(y)] def test_issue_2725(): R = Symbol('R') eq = sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1) sol = solve(eq, R, set=True)[1] assert sol == {(Rational(5, 3) + (Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3) + 40/(9*((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3))),), (Rational(5, 3) + 40/(9*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)) + (Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3),)} def test_issue_5114_6611(): # See that it doesn't hang; this solves in about 2 seconds. # Also check that the solution is relatively small. # Note: the system in issue 6611 solves in about 5 seconds and has # an op-count of 138336 (with simplify=False). b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('b:r') eqs = Matrix([ [b - c/d + r/d], [c*(1/g + 1/e + 1/d) - f/g - r/d], [-c/g + f*(1/j + 1/i + 1/g) - h/i], [-f/i + h*(1/m + 1/l + 1/i) - k/m], [-h/m + k*(1/p + 1/o + 1/m) - n/p], [-k/p + n*(1/q + 1/p)]]) v = Matrix([f, h, k, n, b, c]) ans = solve(list(eqs), list(v), simplify=False) # If time is taken to simplify then then 2617 below becomes # 1168 and the time is about 50 seconds instead of 2. assert sum([s.count_ops() for s in ans.values()]) <= 3270 def test_det_quick(): m = Matrix(3, 3, symbols('a:9')) assert m.det() == det_quick(m) # calls det_perm m[0, 0] = 1 assert m.det() == det_quick(m) # calls det_minor m = Matrix(3, 3, list(range(9))) assert m.det() == det_quick(m) # defaults to .det() # make sure they work with Sparse s = SparseMatrix(2, 2, (1, 2, 1, 4)) assert det_perm(s) == det_minor(s) == s.det() def test_real_imag_splitting(): a, b = symbols('a b', real=True) assert solve(sqrt(a**2 + b**2) - 3, a) == \ [-sqrt(-b**2 + 9), sqrt(-b**2 + 9)] a, b = symbols('a b', imaginary=True) assert solve(sqrt(a**2 + b**2) - 3, a) == [] def test_issue_7110(): y = -2*x**3 + 4*x**2 - 2*x + 5 assert any(ask(Q.real(i)) for i in solve(y)) def test_units(): assert solve(1/x - 1/(2*cm)) == [2*cm] def test_issue_7547(): A, B, V = symbols('A,B,V') eq1 = Eq(630.26*(V - 39.0)*V*(V + 39) - A + B, 0) eq2 = Eq(B, 1.36*10**8*(V - 39)) eq3 = Eq(A, 5.75*10**5*V*(V + 39.0)) sol = Matrix(nsolve(Tuple(eq1, eq2, eq3), [A, B, V], (0, 0, 0))) assert str(sol) == str(Matrix( [['4442890172.68209'], ['4289299466.1432'], ['70.5389666628177']])) def test_issue_7895(): r = symbols('r', real=True) assert solve(sqrt(r) - 2) == [4] def test_issue_2777(): # the equations represent two circles x, y = symbols('x y', real=True) e1, e2 = sqrt(x**2 + y**2) - 10, sqrt(y**2 + (-x + 10)**2) - 3 a, b = Rational(191, 20), 3*sqrt(391)/20 ans = [(a, -b), (a, b)] assert solve((e1, e2), (x, y)) == ans assert solve((e1, e2/(x - a)), (x, y)) == [] # make the 2nd circle's radius be -3 e2 += 6 assert solve((e1, e2), (x, y)) == [] assert solve((e1, e2), (x, y), check=False) == ans def test_issue_7322(): number = 5.62527e-35 assert solve(x - number, x)[0] == number def test_nsolve(): raises(ValueError, lambda: nsolve(x, (-1, 1), method='bisect')) raises(TypeError, lambda: nsolve((x - y + 3,x + y,z - y),(x,y,z),(-50,50))) raises(TypeError, lambda: nsolve((x + y, x - y), (0, 1))) @slow def test_high_order_multivariate(): assert len(solve(a*x**3 - x + 1, x)) == 3 assert len(solve(a*x**4 - x + 1, x)) == 4 assert solve(a*x**5 - x + 1, x) == [] # incomplete solution allowed raises(NotImplementedError, lambda: solve(a*x**5 - x + 1, x, incomplete=False)) # result checking must always consider the denominator and CRootOf # must be checked, too d = x**5 - x + 1 assert solve(d*(1 + 1/d)) == [CRootOf(d + 1, i) for i in range(5)] d = x - 1 assert solve(d*(2 + 1/d)) == [S.Half] def test_base_0_exp_0(): assert solve(0**x - 1) == [0] assert solve(0**(x - 2) - 1) == [2] assert solve(S('x*(1/x**0 - x)', evaluate=False)) == \ [0, 1] def test__simple_dens(): assert _simple_dens(1/x**0, [x]) == set() assert _simple_dens(1/x**y, [x]) == {x**y} assert _simple_dens(1/root(x, 3), [x]) == {x} def test_issue_8755(): # This tests two things: that if full unrad is attempted and fails # the solution should still be found; also it tests the use of # keyword `composite`. assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3 assert len(solve(-512*y**3 + 1344*(x + 2)**Rational(1, 3)*y**2 - 1176*(x + 2)**Rational(2, 3)*y - 169*x + 686, y, _unrad=False)) == 3 @slow def test_issue_8828(): x1 = 0 y1 = -620 r1 = 920 x2 = 126 y2 = 276 x3 = 51 y3 = 205 r3 = 104 v = x, y, z f1 = (x - x1)**2 + (y - y1)**2 - (r1 - z)**2 f2 = (x - x2)**2 + (y - y2)**2 - z**2 f3 = (x - x3)**2 + (y - y3)**2 - (r3 - z)**2 F = f1,f2,f3 g1 = sqrt((x - x1)**2 + (y - y1)**2) + z - r1 g2 = f2 g3 = sqrt((x - x3)**2 + (y - y3)**2) + z - r3 G = g1,g2,g3 A = solve(F, v) B = solve(G, v) C = solve(G, v, manual=True) p, q, r = [{tuple(i.evalf(2) for i in j) for j in R} for R in [A, B, C]] assert p == q == r @slow def test_issue_2840_8155(): assert solve(sin(3*x) + sin(6*x)) == [ 0, pi*Rational(-5, 3), pi*Rational(-4, 3), -pi, pi*Rational(-2, 3), pi*Rational(-4, 9), -pi/3, pi*Rational(-2, 9), pi*Rational(2, 9), pi/3, pi*Rational(4, 9), pi*Rational(2, 3), pi, pi*Rational(4, 3), pi*Rational(14, 9), pi*Rational(5, 3), pi*Rational(16, 9), 2*pi, -2*I*log(-(-1)**Rational(1, 9)), -2*I*log(-(-1)**Rational(2, 9)), -2*I*log(-sin(pi/18) - I*cos(pi/18)), -2*I*log(-sin(pi/18) + I*cos(pi/18)), -2*I*log(sin(pi/18) - I*cos(pi/18)), -2*I*log(sin(pi/18) + I*cos(pi/18))] assert solve(2*sin(x) - 2*sin(2*x)) == [ 0, pi*Rational(-5, 3), -pi, -pi/3, pi/3, pi, pi*Rational(5, 3)] def test_issue_9567(): assert solve(1 + 1/(x - 1)) == [0] def test_issue_11538(): assert solve(x + E) == [-E] assert solve(x**2 + E) == [-I*sqrt(E), I*sqrt(E)] assert solve(x**3 + 2*E) == [ -cbrt(2 * E), cbrt(2)*cbrt(E)/2 - cbrt(2)*sqrt(3)*I*cbrt(E)/2, cbrt(2)*cbrt(E)/2 + cbrt(2)*sqrt(3)*I*cbrt(E)/2] assert solve([x + 4, y + E], x, y) == {x: -4, y: -E} assert solve([x**2 + 4, y + E], x, y) == [ (-2*I, -E), (2*I, -E)] e1 = x - y**3 + 4 e2 = x + y + 4 + 4 * E assert len(solve([e1, e2], x, y)) == 3 @slow def test_issue_12114(): a, b, c, d, e, f, g = symbols('a,b,c,d,e,f,g') terms = [1 + a*b + d*e, 1 + a*c + d*f, 1 + b*c + e*f, g - a**2 - d**2, g - b**2 - e**2, g - c**2 - f**2] sol = solve(terms, [a, b, c, d, e, f, g], dict=True) s = sqrt(-f**2 - 1) s2 = sqrt(2 - f**2) s3 = sqrt(6 - 3*f**2) s4 = sqrt(3)*f s5 = sqrt(3)*s2 assert sol == [ {a: -s, b: -s, c: -s, d: f, e: f, g: -1}, {a: s, b: s, c: s, d: f, e: f, g: -1}, {a: -s4/2 - s2/2, b: s4/2 - s2/2, c: s2, d: -f/2 + s3/2, e: -f/2 - s5/2, g: 2}, {a: -s4/2 + s2/2, b: s4/2 + s2/2, c: -s2, d: -f/2 - s3/2, e: -f/2 + s5/2, g: 2}, {a: s4/2 - s2/2, b: -s4/2 - s2/2, c: s2, d: -f/2 - s3/2, e: -f/2 + s5/2, g: 2}, {a: s4/2 + s2/2, b: -s4/2 + s2/2, c: -s2, d: -f/2 + s3/2, e: -f/2 - s5/2, g: 2}] def test_inf(): assert solve(1 - oo*x) == [] assert solve(oo*x, x) == [] assert solve(oo*x - oo, x) == [] def test_issue_12448(): f = Function('f') fun = [f(i) for i in range(15)] sym = symbols('x:15') reps = dict(zip(fun, sym)) (x, y, z), c = sym[:3], sym[3:] ssym = solve([c[4*i]*x + c[4*i + 1]*y + c[4*i + 2]*z + c[4*i + 3] for i in range(3)], (x, y, z)) (x, y, z), c = fun[:3], fun[3:] sfun = solve([c[4*i]*x + c[4*i + 1]*y + c[4*i + 2]*z + c[4*i + 3] for i in range(3)], (x, y, z)) assert sfun[fun[0]].xreplace(reps).count_ops() == \ ssym[sym[0]].count_ops() def test_denoms(): assert denoms(x/2 + 1/y) == {2, y} assert denoms(x/2 + 1/y, y) == {y} assert denoms(x/2 + 1/y, [y]) == {y} assert denoms(1/x + 1/y + 1/z, [x, y]) == {x, y} assert denoms(1/x + 1/y + 1/z, x, y) == {x, y} assert denoms(1/x + 1/y + 1/z, {x, y}) == {x, y} def test_issue_12476(): x0, x1, x2, x3, x4, x5 = symbols('x0 x1 x2 x3 x4 x5') eqns = [x0**2 - x0, x0*x1 - x1, x0*x2 - x2, x0*x3 - x3, x0*x4 - x4, x0*x5 - x5, x0*x1 - x1, -x0/3 + x1**2 - 2*x2/3, x1*x2 - x1/3 - x2/3 - x3/3, x1*x3 - x2/3 - x3/3 - x4/3, x1*x4 - 2*x3/3 - x5/3, x1*x5 - x4, x0*x2 - x2, x1*x2 - x1/3 - x2/3 - x3/3, -x0/6 - x1/6 + x2**2 - x2/6 - x3/3 - x4/6, -x1/6 + x2*x3 - x2/3 - x3/6 - x4/6 - x5/6, x2*x4 - x2/3 - x3/3 - x4/3, x2*x5 - x3, x0*x3 - x3, x1*x3 - x2/3 - x3/3 - x4/3, -x1/6 + x2*x3 - x2/3 - x3/6 - x4/6 - x5/6, -x0/6 - x1/6 - x2/6 + x3**2 - x3/3 - x4/6, -x1/3 - x2/3 + x3*x4 - x3/3, -x2 + x3*x5, x0*x4 - x4, x1*x4 - 2*x3/3 - x5/3, x2*x4 - x2/3 - x3/3 - x4/3, -x1/3 - x2/3 + x3*x4 - x3/3, -x0/3 - 2*x2/3 + x4**2, -x1 + x4*x5, x0*x5 - x5, x1*x5 - x4, x2*x5 - x3, -x2 + x3*x5, -x1 + x4*x5, -x0 + x5**2, x0 - 1] sols = [{x0: 1, x3: Rational(1, 6), x2: Rational(1, 6), x4: Rational(-2, 3), x1: Rational(-2, 3), x5: 1}, {x0: 1, x3: S.Half, x2: Rational(-1, 2), x4: 0, x1: 0, x5: -1}, {x0: 1, x3: Rational(-1, 3), x2: Rational(-1, 3), x4: Rational(1, 3), x1: Rational(1, 3), x5: 1}, {x0: 1, x3: 1, x2: 1, x4: 1, x1: 1, x5: 1}, {x0: 1, x3: Rational(-1, 3), x2: Rational(1, 3), x4: sqrt(5)/3, x1: -sqrt(5)/3, x5: -1}, {x0: 1, x3: Rational(-1, 3), x2: Rational(1, 3), x4: -sqrt(5)/3, x1: sqrt(5)/3, x5: -1}] assert solve(eqns) == sols def test_issue_13849(): t = symbols('t') assert solve((t*(sqrt(5) + sqrt(2)) - sqrt(2), t), t) == [] def test_issue_14860(): from sympy.physics.units import newton, kilo assert solve(8*kilo*newton + x + y, x) == [-8000*newton - y] def test_issue_14721(): k, h, a, b = symbols(':4') assert solve([ -1 + (-k + 1)**2/b**2 + (-h - 1)**2/a**2, -1 + (-k + 1)**2/b**2 + (-h + 1)**2/a**2, h, k + 2], h, k, a, b) == [ (0, -2, -b*sqrt(1/(b**2 - 9)), b), (0, -2, b*sqrt(1/(b**2 - 9)), b)] assert solve([ h, h/a + 1/b**2 - 2, -h/2 + 1/b**2 - 2], a, h, b) == [ (a, 0, -sqrt(2)/2), (a, 0, sqrt(2)/2)] assert solve((a + b**2 - 1, a + b**2 - 2)) == [] def test_issue_14779(): x = symbols('x', real=True) assert solve(sqrt(x**4 - 130*x**2 + 1089) + sqrt(x**4 - 130*x**2 + 3969) - 96*Abs(x)/x,x) == [sqrt(130)] def test_issue_15307(): assert solve((y - 2, Mul(x + 3,x - 2, evaluate=False))) == \ [{x: -3, y: 2}, {x: 2, y: 2}] assert solve((y - 2, Mul(3, x - 2, evaluate=False))) == \ {x: 2, y: 2} assert solve((y - 2, Add(x + 4, x - 2, evaluate=False))) == \ {x: -1, y: 2} eq1 = Eq(12513*x + 2*y - 219093, -5726*x - y) eq2 = Eq(-2*x + 8, 2*x - 40) assert solve([eq1, eq2]) == {x:12, y:75} def test_issue_15415(): assert solve(x - 3, x) == [3] assert solve([x - 3], x) == {x:3} assert solve(Eq(y + 3*x**2/2, y + 3*x), y) == [] assert solve([Eq(y + 3*x**2/2, y + 3*x)], y) == [] assert solve([Eq(y + 3*x**2/2, y + 3*x), Eq(x, 1)], y) == [] @slow def test_issue_15731(): # f(x)**g(x)=c assert solve(Eq((x**2 - 7*x + 11)**(x**2 - 13*x + 42), 1)) == [2, 3, 4, 5, 6, 7] assert solve((x)**(x + 4) - 4) == [-2] assert solve((-x)**(-x + 4) - 4) == [2] assert solve((x**2 - 6)**(x**2 - 2) - 4) == [-2, 2] assert solve((x**2 - 2*x - 1)**(x**2 - 3) - 1/(1 - 2*sqrt(2))) == [sqrt(2)] assert solve(x**(x + S.Half) - 4*sqrt(2)) == [S(2)] assert solve((x**2 + 1)**x - 25) == [2] assert solve(x**(2/x) - 2) == [2, 4] assert solve((x/2)**(2/x) - sqrt(2)) == [4, 8] assert solve(x**(x + S.Half) - Rational(9, 4)) == [Rational(3, 2)] # a**g(x)=c assert solve((-sqrt(sqrt(2)))**x - 2) == [4, log(2)/(log(2**Rational(1, 4)) + I*pi)] assert solve((sqrt(2))**x - sqrt(sqrt(2))) == [S.Half] assert solve((-sqrt(2))**x + 2*(sqrt(2))) == [3, (3*log(2)**2 + 4*pi**2 - 4*I*pi*log(2))/(log(2)**2 + 4*pi**2)] assert solve((sqrt(2))**x - 2*(sqrt(2))) == [3] assert solve(I**x + 1) == [2] assert solve((1 + I)**x - 2*I) == [2] assert solve((sqrt(2) + sqrt(3))**x - (2*sqrt(6) + 5)**Rational(1, 3)) == [Rational(2, 3)] # bases of both sides are equal b = Symbol('b') assert solve(b**x - b**2, x) == [2] assert solve(b**x - 1/b, x) == [-1] assert solve(b**x - b, x) == [1] b = Symbol('b', positive=True) assert solve(b**x - b**2, x) == [2] assert solve(b**x - 1/b, x) == [-1] def test_issue_10933(): assert solve(x**4 + y*(x + 0.1), x) # doesn't fail assert solve(I*x**4 + x**3 + x**2 + 1.) # doesn't fail def test_Abs_handling(): x = symbols('x', real=True) assert solve(abs(x/y), x) == [0] def test_issue_7982(): x = Symbol('x') # Test that no exception happens assert solve([2*x**2 + 5*x + 20 <= 0, x >= 1.5], x) is S.false # From #8040 assert solve([x**3 - 8.08*x**2 - 56.48*x/5 - 106 >= 0, x - 1 <= 0], [x]) is S.false def test_issue_14645(): x, y = symbols('x y') assert solve([x*y - x - y, x*y - x - y], [x, y]) == [(y/(y - 1), y)] def test_issue_12024(): x, y = symbols('x y') assert solve(Piecewise((0.0, x < 0.1), (x, x >= 0.1)) - y) == \ [{y: Piecewise((0.0, x < 0.1), (x, True))}] def test_issue_17452(): assert solve((7**x)**x + pi, x) == [-sqrt(log(pi) + I*pi)/sqrt(log(7)), sqrt(log(pi) + I*pi)/sqrt(log(7))] assert solve(x**(x/11) + pi/11, x) == [exp(LambertW(-11*log(11) + 11*log(pi) + 11*I*pi))] def test_issue_17799(): assert solve(-erf(x**(S(1)/3))**pi + I, x) == [] def test_issue_17650(): x = Symbol('x', real=True) assert solve(abs(abs(x**2 - 1) - x) - x) == [1, -1 + sqrt(2), 1 + sqrt(2)] def test_issue_17882(): eq = -8*x**2/(9*(x**2 - 1)**(S(4)/3)) + 4/(3*(x**2 - 1)**(S(1)/3)) assert unrad(eq) is None def test_issue_17949(): assert solve(exp(+x+x**2), x) == [] assert solve(exp(-x+x**2), x) == [] assert solve(exp(+x-x**2), x) == [] assert solve(exp(-x-x**2), x) == [] def test_issue_10993(): assert solve(Eq(binomial(x, 2), 3)) == [-2, 3] assert solve(Eq(pow(x, 2) + binomial(x, 3), x)) == [-4, 0, 1] assert solve(Eq(binomial(x, 2), 0)) == [0, 1] assert solve(a+binomial(x, 3), a) == [-binomial(x, 3)] assert solve(x-binomial(a, 3) + binomial(y, 2) + sin(a), x) == [-sin(a) + binomial(a, 3) - binomial(y, 2)] assert solve((x+1)-binomial(x+1, 3), x) == [-2, -1, 3] def test_issue_11553(): eq1 = x + y + 1 eq2 = x + GoldenRatio assert solve([eq1, eq2], x, y) == {x: -GoldenRatio, y: -1 + GoldenRatio} eq3 = x + 2 + TribonacciConstant assert solve([eq1, eq3], x, y) == {x: -2 - TribonacciConstant, y: 1 + TribonacciConstant} def test_issue_19113_19102(): t = S(1)/3 solve(cos(x)**5-sin(x)**5) assert solve(4*cos(x)**3 - 2*sin(x)**3) == [ atan(2**(t)), -atan(2**(t)*(1 - sqrt(3)*I)/2), -atan(2**(t)*(1 + sqrt(3)*I)/2)] h = S.Half assert solve(cos(x)**2 + sin(x)) == [ 2*atan(-h + sqrt(5)/2 + sqrt(2)*sqrt(1 - sqrt(5))/2), -2*atan(h + sqrt(5)/2 + sqrt(2)*sqrt(1 + sqrt(5))/2), -2*atan(-sqrt(5)/2 + h + sqrt(2)*sqrt(1 - sqrt(5))/2), -2*atan(-sqrt(2)*sqrt(1 + sqrt(5))/2 + h + sqrt(5)/2)] assert solve(3*cos(x) - sin(x)) == [atan(3)] def test_issue_19509(): a = S(3)/4 b = S(5)/8 c = sqrt(5)/8 d = sqrt(5)/4 assert solve(1/(x -1)**5 - 1) == [2, -d + a - sqrt(-b + c), -d + a + sqrt(-b + c), d + a - sqrt(-b - c), d + a + sqrt(-b - c)] def test_issue_20747(): THT, HT, DBH, dib, c0, c1, c2, c3, c4 = symbols('THT HT DBH dib c0 c1 c2 c3 c4') f = DBH*c3 + THT*c4 + c2 rhs = 1 - ((HT - 1)/(THT - 1))**c1*(1 - exp(c0/f)) eq = dib - DBH*(c0 - f*log(rhs)) term = ((1 - exp((DBH*c0 - dib)/(DBH*(DBH*c3 + THT*c4 + c2)))) / (1 - exp(c0/(DBH*c3 + THT*c4 + c2)))) sol = [THT*term**(1/c1) - term**(1/c1) + 1] assert solve(eq, HT) == sol def test_issue_20902(): f = (t / ((1 + t) ** 2)) assert solve(f.subs({t: 3 * x + 2}).diff(x) > 0, x) == (S(-1) < x) & (x < S(-1)/3) assert solve(f.subs({t: 3 * x + 3}).diff(x) > 0, x) == (S(-4)/3 < x) & (x < S(-2)/3) assert solve(f.subs({t: 3 * x + 4}).diff(x) > 0, x) == (S(-5)/3 < x) & (x < S(-1)) assert solve(f.subs({t: 3 * x + 2}).diff(x) > 0, x) == (S(-1) < x) & (x < S(-1)/3) def test_issue_21034(): a = symbols('a', real=True) system = [x - cosh(cos(4)), y - sinh(cos(a)), z - tanh(x)] # constants inside hyperbolic functions should not be rewritten in terms of exp assert solve(system, x, y, z) == [(cosh(cos(4)), sinh(cos(a)), tanh(cosh(cos(4))))] # but if the variable of interest is present in a hyperbolic function, # then it should be rewritten in terms of exp and solved further newsystem = [(exp(x) - exp(-x)) - tanh(x)*(exp(x) + exp(-x)) + x - 5] assert solve(newsystem, x) == {x: 5} def test_issue_4886(): z = a*sqrt(R**2*a**2 + R**2*b**2 - c**2)/(a**2 + b**2) t = b*c/(a**2 + b**2) sol = [((b*(t - z) - c)/(-a), t - z), ((b*(t + z) - c)/(-a), t + z)] assert solve([x**2 + y**2 - R**2, a*x + b*y - c], x, y) == sol def test_issue_6819(): a, b, c, d = symbols('a b c d', positive=True) assert solve(a*b**x - c*d**x, x) == [log(c/a)/log(b/d)] def test_issue_17454(): x = Symbol('x') assert solve((1 - x - I)**4, x) == [1 - I] def test_issue_21852(): solution = [21 - 21*sqrt(2)/2] assert solve(2*x + sqrt(2*x**2) - 21) == solution def test_issue_21942(): eq = -d + (a*c**(1 - e) + b**(1 - e)*(1 - a))**(1/(1 - e)) sol = solve(eq, c, simplify=False, check=False) assert sol == [((a*b**(1 - e) - b**(1 - e) + d**(1 - e))/a)**(1/(1 - e))] def test_solver_flags(): root = solve(x**5 + x**2 - x - 1, cubics=False) rad = solve(x**5 + x**2 - x - 1, cubics=True) assert root != rad def test_issue_22768(): eq = 2*x**3 - 16*(y - 1)**6*z**3 assert solve(eq.expand(), x, simplify=False ) == [2*z*(y - 1)**2, z*(-1 + sqrt(3)*I)*(y - 1)**2, -z*(1 + sqrt(3)*I)*(y - 1)**2] def test_issue_22717(): assert solve((-y**2 + log(y**2/x) + 2, -2*x*y + 2*x/y)) == [ {y: -1, x: E}, {y: 1, x: E}] def test_issue_10169(): eq = S(-8*a - x**5*(a + b + c + e) - x**4*(4*a - 2**Rational(3,4)*c + 4*c + d + 2**Rational(3,4)*e + 4*e + k) - x**3*(-4*2**Rational(3,4)*c + sqrt(2)*c - 2**Rational(3,4)*d + 4*d + sqrt(2)*e + 4*2**Rational(3,4)*e + 2**Rational(3,4)*k + 4*k) - x**2*(4*sqrt(2)*c - 4*2**Rational(3,4)*d + sqrt(2)*d + 4*sqrt(2)*e + sqrt(2)*k + 4*2**Rational(3,4)*k) - x*(2*a + 2*b + 4*sqrt(2)*d + 4*sqrt(2)*k) + 5) assert solve_undetermined_coeffs(eq, [a, b, c, d, e, k], x) == { a: Rational(5,8), b: Rational(-5,1032), c: Rational(-40,129) - 5*2**Rational(3,4)/129 + 5*2**Rational(1,4)/1032, d: -20*2**Rational(3,4)/129 - 10*sqrt(2)/129 - 5*2**Rational(1,4)/258, e: Rational(-40,129) - 5*2**Rational(1,4)/1032 + 5*2**Rational(3,4)/129, k: -10*sqrt(2)/129 + 5*2**Rational(1,4)/258 + 20*2**Rational(3,4)/129 } def test_solve_undetermined_coeffs_issue_23927(): A, B, r, phi = symbols('A, B, r, phi') eq = Eq(A*sin(t) + B*cos(t), r*sin(t - phi)).rewrite(Add).expand(trig=True) soln = solve_undetermined_coeffs(eq, (r, phi), t) assert soln == [{ phi: 2*atan((A - sqrt(A**2 + B**2))/B), r: (-A**2 + A*sqrt(A**2 + B**2) - B**2)/(A - sqrt(A**2 + B**2)) }, { phi: 2*atan((A + sqrt(A**2 + B**2))/B), r: (A**2 + A*sqrt(A**2 + B**2) + B**2)/(A + sqrt(A**2 + B**2))/-1 }]
ac4afe0b2924037bff2f0e76f10ac1fe9a36672d0c451a66ac7d4dc69e809476
# Tests that require installed backends go into # sympy/test_external/test_autowrap import os import tempfile import shutil from io import StringIO from sympy.core import symbols, Eq from sympy.utilities.autowrap import (autowrap, binary_function, CythonCodeWrapper, UfuncifyCodeWrapper, CodeWrapper) from sympy.utilities.codegen import ( CCodeGen, C99CodeGen, CodeGenArgumentListError, make_routine ) from sympy.testing.pytest import raises from sympy.testing.tmpfiles import TmpFileManager def get_string(dump_fn, routines, prefix="file", **kwargs): """Wrapper for dump_fn. dump_fn writes its results to a stream object and this wrapper returns the contents of that stream as a string. This auxiliary function is used by many tests below. The header and the empty lines are not generator to facilitate the testing of the output. """ output = StringIO() dump_fn(routines, output, prefix, **kwargs) source = output.getvalue() output.close() return source def test_cython_wrapper_scalar_function(): x, y, z = symbols('x,y,z') expr = (x + y)*z routine = make_routine("test", expr) code_gen = CythonCodeWrapper(CCodeGen()) source = get_string(code_gen.dump_pyx, [routine]) expected = ( "cdef extern from 'file.h':\n" " double test(double x, double y, double z)\n" "\n" "def test_c(double x, double y, double z):\n" "\n" " return test(x, y, z)") assert source == expected def test_cython_wrapper_outarg(): from sympy.core.relational import Equality x, y, z = symbols('x,y,z') code_gen = CythonCodeWrapper(C99CodeGen()) routine = make_routine("test", Equality(z, x + y)) source = get_string(code_gen.dump_pyx, [routine]) expected = ( "cdef extern from 'file.h':\n" " void test(double x, double y, double *z)\n" "\n" "def test_c(double x, double y):\n" "\n" " cdef double z = 0\n" " test(x, y, &z)\n" " return z") assert source == expected def test_cython_wrapper_inoutarg(): from sympy.core.relational import Equality x, y, z = symbols('x,y,z') code_gen = CythonCodeWrapper(C99CodeGen()) routine = make_routine("test", Equality(z, x + y + z)) source = get_string(code_gen.dump_pyx, [routine]) expected = ( "cdef extern from 'file.h':\n" " void test(double x, double y, double *z)\n" "\n" "def test_c(double x, double y, double z):\n" "\n" " test(x, y, &z)\n" " return z") assert source == expected def test_cython_wrapper_compile_flags(): from sympy.core.relational import Equality x, y, z = symbols('x,y,z') routine = make_routine("test", Equality(z, x + y)) code_gen = CythonCodeWrapper(CCodeGen()) expected = """\ try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize cy_opts = {'compiler_directives': {'language_level': '3'}} ext_mods = [Extension( 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], include_dirs=[], library_dirs=[], libraries=[], extra_compile_args=['-std=c99'], extra_link_args=[] )] setup(ext_modules=cythonize(ext_mods, **cy_opts)) """ % {'num': CodeWrapper._module_counter} temp_dir = tempfile.mkdtemp() TmpFileManager.tmp_folder(temp_dir) setup_file_path = os.path.join(temp_dir, 'setup.py') code_gen._prepare_files(routine, build_dir=temp_dir) with open(setup_file_path) as f: setup_text = f.read() assert setup_text == expected code_gen = CythonCodeWrapper(CCodeGen(), include_dirs=['/usr/local/include', '/opt/booger/include'], library_dirs=['/user/local/lib'], libraries=['thelib', 'nilib'], extra_compile_args=['-slow-math'], extra_link_args=['-lswamp', '-ltrident'], cythonize_options={'compiler_directives': {'boundscheck': False}} ) expected = """\ try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize cy_opts = {'compiler_directives': {'boundscheck': False}} ext_mods = [Extension( 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], include_dirs=['/usr/local/include', '/opt/booger/include'], library_dirs=['/user/local/lib'], libraries=['thelib', 'nilib'], extra_compile_args=['-slow-math', '-std=c99'], extra_link_args=['-lswamp', '-ltrident'] )] setup(ext_modules=cythonize(ext_mods, **cy_opts)) """ % {'num': CodeWrapper._module_counter} code_gen._prepare_files(routine, build_dir=temp_dir) with open(setup_file_path) as f: setup_text = f.read() assert setup_text == expected expected = """\ try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize cy_opts = {'compiler_directives': {'boundscheck': False}} import numpy as np ext_mods = [Extension( 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], include_dirs=['/usr/local/include', '/opt/booger/include', np.get_include()], library_dirs=['/user/local/lib'], libraries=['thelib', 'nilib'], extra_compile_args=['-slow-math', '-std=c99'], extra_link_args=['-lswamp', '-ltrident'] )] setup(ext_modules=cythonize(ext_mods, **cy_opts)) """ % {'num': CodeWrapper._module_counter} code_gen._need_numpy = True code_gen._prepare_files(routine, build_dir=temp_dir) with open(setup_file_path) as f: setup_text = f.read() assert setup_text == expected TmpFileManager.cleanup() def test_cython_wrapper_unique_dummyvars(): from sympy.core.relational import Equality from sympy.core.symbol import Dummy x, y, z = Dummy('x'), Dummy('y'), Dummy('z') x_id, y_id, z_id = [str(d.dummy_index) for d in [x, y, z]] expr = Equality(z, x + y) routine = make_routine("test", expr) code_gen = CythonCodeWrapper(CCodeGen()) source = get_string(code_gen.dump_pyx, [routine]) expected_template = ( "cdef extern from 'file.h':\n" " void test(double x_{x_id}, double y_{y_id}, double *z_{z_id})\n" "\n" "def test_c(double x_{x_id}, double y_{y_id}):\n" "\n" " cdef double z_{z_id} = 0\n" " test(x_{x_id}, y_{y_id}, &z_{z_id})\n" " return z_{z_id}") expected = expected_template.format(x_id=x_id, y_id=y_id, z_id=z_id) assert source == expected def test_autowrap_dummy(): x, y, z = symbols('x y z') # Uses DummyWrapper to test that codegen works as expected f = autowrap(x + y, backend='dummy') assert f() == str(x + y) assert f.args == "x, y" assert f.returns == "nameless" f = autowrap(Eq(z, x + y), backend='dummy') assert f() == str(x + y) assert f.args == "x, y" assert f.returns == "z" f = autowrap(Eq(z, x + y + z), backend='dummy') assert f() == str(x + y + z) assert f.args == "x, y, z" assert f.returns == "z" def test_autowrap_args(): x, y, z = symbols('x y z') raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y), backend='dummy', args=[x])) f = autowrap(Eq(z, x + y), backend='dummy', args=[y, x]) assert f() == str(x + y) assert f.args == "y, x" assert f.returns == "z" raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y + z), backend='dummy', args=[x, y])) f = autowrap(Eq(z, x + y + z), backend='dummy', args=[y, x, z]) assert f() == str(x + y + z) assert f.args == "y, x, z" assert f.returns == "z" f = autowrap(Eq(z, x + y + z), backend='dummy', args=(y, x, z)) assert f() == str(x + y + z) assert f.args == "y, x, z" assert f.returns == "z" def test_autowrap_store_files(): x, y = symbols('x y') tmp = tempfile.mkdtemp() TmpFileManager.tmp_folder(tmp) f = autowrap(x + y, backend='dummy', tempdir=tmp) assert f() == str(x + y) assert os.access(tmp, os.F_OK) TmpFileManager.cleanup() def test_autowrap_store_files_issue_gh12939(): x, y = symbols('x y') tmp = './tmp' saved_cwd = os.getcwd() temp_cwd = tempfile.mkdtemp() try: os.chdir(temp_cwd) f = autowrap(x + y, backend='dummy', tempdir=tmp) assert f() == str(x + y) assert os.access(tmp, os.F_OK) finally: os.chdir(saved_cwd) shutil.rmtree(temp_cwd) def test_binary_function(): x, y = symbols('x y') f = binary_function('f', x + y, backend='dummy') assert f._imp_() == str(x + y) def test_ufuncify_source(): x, y, z = symbols('x,y,z') code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) routine = make_routine("test", x + y + z) source = get_string(code_wrapper.dump_c, [routine]) expected = """\ #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/halffloat.h" #include "file.h" static PyMethodDef wrapper_module_%(num)sMethods[] = { {NULL, NULL, 0, NULL} }; static void test_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; char *in0 = args[0]; char *in1 = args[1]; char *in2 = args[2]; char *out0 = args[3]; npy_intp in0_step = steps[0]; npy_intp in1_step = steps[1]; npy_intp in2_step = steps[2]; npy_intp out0_step = steps[3]; for (i = 0; i < n; i++) { *((double *)out0) = test(*(double *)in0, *(double *)in1, *(double *)in2); in0 += in0_step; in1 += in1_step; in2 += in2_step; out0 += out0_step; } } PyUFuncGenericFunction test_funcs[1] = {&test_ufunc}; static char test_types[4] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; static void *test_data[1] = {NULL}; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "wrapper_module_%(num)s", NULL, -1, wrapper_module_%(num)sMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) { PyObject *m, *d; PyObject *ufunc0; m = PyModule_Create(&moduledef); if (!m) { return NULL; } import_array(); import_umath(); d = PyModule_GetDict(m); ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); PyDict_SetItemString(d, "test", ufunc0); Py_DECREF(ufunc0); return m; } #else PyMODINIT_FUNC initwrapper_module_%(num)s(void) { PyObject *m, *d; PyObject *ufunc0; m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); if (m == NULL) { return; } import_array(); import_umath(); d = PyModule_GetDict(m); ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); PyDict_SetItemString(d, "test", ufunc0); Py_DECREF(ufunc0); } #endif""" % {'num': CodeWrapper._module_counter} assert source == expected def test_ufuncify_source_multioutput(): x, y, z = symbols('x,y,z') var_symbols = (x, y, z) expr = x + y**3 + 10*z**2 code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) routines = [make_routine("func{}".format(i), expr.diff(var_symbols[i]), var_symbols) for i in range(len(var_symbols))] source = get_string(code_wrapper.dump_c, routines, funcname='multitest') expected = """\ #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/halffloat.h" #include "file.h" static PyMethodDef wrapper_module_%(num)sMethods[] = { {NULL, NULL, 0, NULL} }; static void multitest_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; char *in0 = args[0]; char *in1 = args[1]; char *in2 = args[2]; char *out0 = args[3]; char *out1 = args[4]; char *out2 = args[5]; npy_intp in0_step = steps[0]; npy_intp in1_step = steps[1]; npy_intp in2_step = steps[2]; npy_intp out0_step = steps[3]; npy_intp out1_step = steps[4]; npy_intp out2_step = steps[5]; for (i = 0; i < n; i++) { *((double *)out0) = func0(*(double *)in0, *(double *)in1, *(double *)in2); *((double *)out1) = func1(*(double *)in0, *(double *)in1, *(double *)in2); *((double *)out2) = func2(*(double *)in0, *(double *)in1, *(double *)in2); in0 += in0_step; in1 += in1_step; in2 += in2_step; out0 += out0_step; out1 += out1_step; out2 += out2_step; } } PyUFuncGenericFunction multitest_funcs[1] = {&multitest_ufunc}; static char multitest_types[6] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; static void *multitest_data[1] = {NULL}; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "wrapper_module_%(num)s", NULL, -1, wrapper_module_%(num)sMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) { PyObject *m, *d; PyObject *ufunc0; m = PyModule_Create(&moduledef); if (!m) { return NULL; } import_array(); import_umath(); d = PyModule_GetDict(m); ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); PyDict_SetItemString(d, "multitest", ufunc0); Py_DECREF(ufunc0); return m; } #else PyMODINIT_FUNC initwrapper_module_%(num)s(void) { PyObject *m, *d; PyObject *ufunc0; m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); if (m == NULL) { return; } import_array(); import_umath(); d = PyModule_GetDict(m); ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); PyDict_SetItemString(d, "multitest", ufunc0); Py_DECREF(ufunc0); } #endif""" % {'num': CodeWrapper._module_counter} assert source == expected
edcaa6c788591da52b01d190e4534509177ee114f30980fb18b22ded4fe102c3
from sympy import MatAdd from sympy.algebras.quaternion import Quaternion from sympy.assumptions.ask import Q from sympy.calculus.accumulationbounds import AccumBounds from sympy.combinatorics.partitions import Partition from sympy.concrete.summations import (Sum, summation) from sympy.core.add import Add from sympy.core.containers import (Dict, Tuple) from sympy.core.expr import UnevaluatedExpr, Expr from sympy.core.function import (Derivative, Function, Lambda, Subs, WildFunction) from sympy.core.mul import Mul from sympy.core import (Catalan, EulerGamma, GoldenRatio, TribonacciConstant) from sympy.core.numbers import (E, Float, I, Integer, Rational, nan, oo, pi, zoo) from sympy.core.parameters import _exp_is_pow from sympy.core.power import Pow from sympy.core.relational import (Eq, Rel, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, Wild, symbols) from sympy.functions.combinatorial.factorials import (factorial, factorial2, subfactorial) from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.zeta_functions import zeta from sympy.integrals.integrals import Integral from sympy.logic.boolalg import (Equivalent, false, true, Xor) from sympy.matrices.dense import Matrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.slice import MatrixSlice from sympy.matrices import SparseMatrix from sympy.polys.polytools import factor from sympy.series.limits import Limit from sympy.series.order import O from sympy.sets.sets import (Complement, FiniteSet, Interval, SymmetricDifference) from sympy.external import import_module from sympy.physics.control.lti import TransferFunction, Series, Parallel, \ Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback from sympy.physics.units import second, joule from sympy.polys import (Poly, rootof, RootSum, groebner, ring, field, ZZ, QQ, ZZ_I, QQ_I, lex, grlex) from sympy.geometry import Point, Circle, Polygon, Ellipse, Triangle from sympy.tensor import NDimArray from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElement from sympy.testing.pytest import raises, warns_deprecated_sympy from sympy.printing import sstr, sstrrepr, StrPrinter from sympy.physics.quantum.trace import Tr x, y, z, w, t = symbols('x,y,z,w,t') d = Dummy('d') def test_printmethod(): class R(Abs): def _sympystr(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert sstr(R(x)) == "foo(x)" class R(Abs): def _sympystr(self, printer): return "foo" assert sstr(R(x)) == "foo" def test_Abs(): assert str(Abs(x)) == "Abs(x)" assert str(Abs(Rational(1, 6))) == "1/6" assert str(Abs(Rational(-1, 6))) == "1/6" def test_Add(): assert str(x + y) == "x + y" assert str(x + 1) == "x + 1" assert str(x + x**2) == "x**2 + x" assert str(Add(0, 1, evaluate=False)) == "0 + 1" assert str(Add(0, 0, 1, evaluate=False)) == "0 + 0 + 1" assert str(1.0*x) == "1.0*x" assert str(5 + x + y + x*y + x**2 + y**2) == "x**2 + x*y + x + y**2 + y + 5" assert str(1 + x + x**2/2 + x**3/3) == "x**3/3 + x**2/2 + x + 1" assert str(2*x - 7*x**2 + 2 + 3*y) == "-7*x**2 + 2*x + 3*y + 2" assert str(x - y) == "x - y" assert str(2 - x) == "2 - x" assert str(x - 2) == "x - 2" assert str(x - y - z - w) == "-w + x - y - z" assert str(x - z*y**2*z*w) == "-w*y**2*z**2 + x" assert str(x - 1*y*x*y) == "-x*y**2 + x" assert str(sin(x).series(x, 0, 15)) == "x - x**3/6 + x**5/120 - x**7/5040 + x**9/362880 - x**11/39916800 + x**13/6227020800 + O(x**15)" assert str(Add(Add(-w, x, evaluate=False), Add(-y, z, evaluate=False), evaluate=False)) == "(-w + x) + (-y + z)" assert str(Add(Add(-x, -y, evaluate=False), -z, evaluate=False)) == "-z + (-x - y)" assert str(Add(Add(Add(-x, -y, evaluate=False), -z, evaluate=False), -t, evaluate=False)) == "-t + (-z + (-x - y))" def test_Catalan(): assert str(Catalan) == "Catalan" def test_ComplexInfinity(): assert str(zoo) == "zoo" def test_Derivative(): assert str(Derivative(x, y)) == "Derivative(x, y)" assert str(Derivative(x**2, x, evaluate=False)) == "Derivative(x**2, x)" assert str(Derivative( x**2/y, x, y, evaluate=False)) == "Derivative(x**2/y, x, y)" def test_dict(): assert str({1: 1 + x}) == sstr({1: 1 + x}) == "{1: x + 1}" assert str({1: x**2, 2: y*x}) in ("{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}") assert sstr({1: x**2, 2: y*x}) == "{1: x**2, 2: x*y}" def test_Dict(): assert str(Dict({1: 1 + x})) == sstr({1: 1 + x}) == "{1: x + 1}" assert str(Dict({1: x**2, 2: y*x})) in ( "{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}") assert sstr(Dict({1: x**2, 2: y*x})) == "{1: x**2, 2: x*y}" def test_Dummy(): assert str(d) == "_d" assert str(d + x) == "_d + x" def test_EulerGamma(): assert str(EulerGamma) == "EulerGamma" def test_Exp(): assert str(E) == "E" with _exp_is_pow(True): assert str(exp(x)) == "E**x" def test_factorial(): n = Symbol('n', integer=True) assert str(factorial(-2)) == "zoo" assert str(factorial(0)) == "1" assert str(factorial(7)) == "5040" assert str(factorial(n)) == "factorial(n)" assert str(factorial(2*n)) == "factorial(2*n)" assert str(factorial(factorial(n))) == 'factorial(factorial(n))' assert str(factorial(factorial2(n))) == 'factorial(factorial2(n))' assert str(factorial2(factorial(n))) == 'factorial2(factorial(n))' assert str(factorial2(factorial2(n))) == 'factorial2(factorial2(n))' assert str(subfactorial(3)) == "2" assert str(subfactorial(n)) == "subfactorial(n)" assert str(subfactorial(2*n)) == "subfactorial(2*n)" def test_Function(): f = Function('f') fx = f(x) w = WildFunction('w') assert str(f) == "f" assert str(fx) == "f(x)" assert str(w) == "w_" def test_Geometry(): assert sstr(Point(0, 0)) == 'Point2D(0, 0)' assert sstr(Circle(Point(0, 0), 3)) == 'Circle(Point2D(0, 0), 3)' assert sstr(Ellipse(Point(1, 2), 3, 4)) == 'Ellipse(Point2D(1, 2), 3, 4)' assert sstr(Triangle(Point(1, 1), Point(7, 8), Point(0, -1))) == \ 'Triangle(Point2D(1, 1), Point2D(7, 8), Point2D(0, -1))' assert sstr(Polygon(Point(5, 6), Point(-2, -3), Point(0, 0), Point(4, 7))) == \ 'Polygon(Point2D(5, 6), Point2D(-2, -3), Point2D(0, 0), Point2D(4, 7))' assert sstr(Triangle(Point(0, 0), Point(1, 0), Point(0, 1)), sympy_integers=True) == \ 'Triangle(Point2D(S(0), S(0)), Point2D(S(1), S(0)), Point2D(S(0), S(1)))' assert sstr(Ellipse(Point(1, 2), 3, 4), sympy_integers=True) == \ 'Ellipse(Point2D(S(1), S(2)), S(3), S(4))' def test_GoldenRatio(): assert str(GoldenRatio) == "GoldenRatio" def test_Heaviside(): assert str(Heaviside(x)) == str(Heaviside(x, S.Half)) == "Heaviside(x)" assert str(Heaviside(x, 1)) == "Heaviside(x, 1)" def test_TribonacciConstant(): assert str(TribonacciConstant) == "TribonacciConstant" def test_ImaginaryUnit(): assert str(I) == "I" def test_Infinity(): assert str(oo) == "oo" assert str(oo*I) == "oo*I" def test_Integer(): assert str(Integer(-1)) == "-1" assert str(Integer(1)) == "1" assert str(Integer(-3)) == "-3" assert str(Integer(0)) == "0" assert str(Integer(25)) == "25" def test_Integral(): assert str(Integral(sin(x), y)) == "Integral(sin(x), y)" assert str(Integral(sin(x), (y, 0, 1))) == "Integral(sin(x), (y, 0, 1))" def test_Interval(): n = (S.NegativeInfinity, 1, 2, S.Infinity) for i in range(len(n)): for j in range(i + 1, len(n)): for l in (True, False): for r in (True, False): ival = Interval(n[i], n[j], l, r) assert S(str(ival)) == ival def test_AccumBounds(): a = Symbol('a', real=True) assert str(AccumBounds(0, a)) == "AccumBounds(0, a)" assert str(AccumBounds(0, 1)) == "AccumBounds(0, 1)" def test_Lambda(): assert str(Lambda(d, d**2)) == "Lambda(_d, _d**2)" # issue 2908 assert str(Lambda((), 1)) == "Lambda((), 1)" assert str(Lambda((), x)) == "Lambda((), x)" assert str(Lambda((x, y), x+y)) == "Lambda((x, y), x + y)" assert str(Lambda(((x, y),), x+y)) == "Lambda(((x, y),), x + y)" def test_Limit(): assert str(Limit(sin(x)/x, x, y)) == "Limit(sin(x)/x, x, y)" assert str(Limit(1/x, x, 0)) == "Limit(1/x, x, 0)" assert str( Limit(sin(x)/x, x, y, dir="-")) == "Limit(sin(x)/x, x, y, dir='-')" def test_list(): assert str([x]) == sstr([x]) == "[x]" assert str([x**2, x*y + 1]) == sstr([x**2, x*y + 1]) == "[x**2, x*y + 1]" assert str([x**2, [y + x]]) == sstr([x**2, [y + x]]) == "[x**2, [x + y]]" def test_Matrix_str(): M = Matrix([[x**+1, 1], [y, x + y]]) assert str(M) == "Matrix([[x, 1], [y, x + y]])" assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])" M = Matrix([[1]]) assert str(M) == sstr(M) == "Matrix([[1]])" M = Matrix([[1, 2]]) assert str(M) == sstr(M) == "Matrix([[1, 2]])" M = Matrix() assert str(M) == sstr(M) == "Matrix(0, 0, [])" M = Matrix(0, 1, lambda i, j: 0) assert str(M) == sstr(M) == "Matrix(0, 1, [])" def test_Mul(): assert str(x/y) == "x/y" assert str(y/x) == "y/x" assert str(x/y/z) == "x/(y*z)" assert str((x + 1)/(y + 2)) == "(x + 1)/(y + 2)" assert str(2*x/3) == '2*x/3' assert str(-2*x/3) == '-2*x/3' assert str(-1.0*x) == '-1.0*x' assert str(1.0*x) == '1.0*x' assert str(Mul(0, 1, evaluate=False)) == '0*1' assert str(Mul(1, 0, evaluate=False)) == '1*0' assert str(Mul(1, 1, evaluate=False)) == '1*1' assert str(Mul(1, 1, 1, evaluate=False)) == '1*1*1' assert str(Mul(1, 2, evaluate=False)) == '1*2' assert str(Mul(1, S.Half, evaluate=False)) == '1*(1/2)' assert str(Mul(1, 1, S.Half, evaluate=False)) == '1*1*(1/2)' assert str(Mul(1, 1, 2, 3, x, evaluate=False)) == '1*1*2*3*x' assert str(Mul(1, -1, evaluate=False)) == '1*(-1)' assert str(Mul(-1, 1, evaluate=False)) == '-1*1' assert str(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == '4*3*2*1*0*y*x' assert str(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == '4*3*2*(z + 1)*0*y*x' assert str(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == '(2/3)*(5/7)' # For issue 14160 assert str(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), evaluate=False)) == '-2*x/(y*y)' # issue 21537 assert str(Mul(x, Pow(1/y, -1, evaluate=False), evaluate=False)) == 'x/(1/y)' # Issue 24108 from sympy.core.parameters import evaluate with evaluate(False): assert str(Mul(Pow(Integer(2), Integer(-1)), Add(Integer(-1), Mul(Integer(-1), Integer(1))))) == "(-1 - 1*1)/2" class CustomClass1(Expr): is_commutative = True class CustomClass2(Expr): is_commutative = True cc1 = CustomClass1() cc2 = CustomClass2() assert str(Rational(2)*cc1) == '2*CustomClass1()' assert str(cc1*Rational(2)) == '2*CustomClass1()' assert str(cc1*Float("1.5")) == '1.5*CustomClass1()' assert str(cc2*Rational(2)) == '2*CustomClass2()' assert str(cc2*Rational(2)*cc1) == '2*CustomClass1()*CustomClass2()' assert str(cc1*Rational(2)*cc2) == '2*CustomClass1()*CustomClass2()' def test_NaN(): assert str(nan) == "nan" def test_NegativeInfinity(): assert str(-oo) == "-oo" def test_Order(): assert str(O(x)) == "O(x)" assert str(O(x**2)) == "O(x**2)" assert str(O(x*y)) == "O(x*y, x, y)" assert str(O(x, x)) == "O(x)" assert str(O(x, (x, 0))) == "O(x)" assert str(O(x, (x, oo))) == "O(x, (x, oo))" assert str(O(x, x, y)) == "O(x, x, y)" assert str(O(x, x, y)) == "O(x, x, y)" assert str(O(x, (x, oo), (y, oo))) == "O(x, (x, oo), (y, oo))" def test_Permutation_Cycle(): from sympy.combinatorics import Permutation, Cycle # general principle: economically, canonically show all moved elements # and the size of the permutation. for p, s in [ (Cycle(), '()'), (Cycle(2), '(2)'), (Cycle(2, 1), '(1 2)'), (Cycle(1, 2)(5)(6, 7)(10), '(1 2)(6 7)(10)'), (Cycle(3, 4)(1, 2)(3, 4), '(1 2)(4)'), ]: assert sstr(p) == s for p, s in [ (Permutation([]), 'Permutation([])'), (Permutation([], size=1), 'Permutation([0])'), (Permutation([], size=2), 'Permutation([0, 1])'), (Permutation([], size=10), 'Permutation([], size=10)'), (Permutation([1, 0, 2]), 'Permutation([1, 0, 2])'), (Permutation([1, 0, 2, 3, 4, 5]), 'Permutation([1, 0], size=6)'), (Permutation([1, 0, 2, 3, 4, 5], size=10), 'Permutation([1, 0], size=10)'), ]: assert sstr(p, perm_cyclic=False) == s for p, s in [ (Permutation([]), '()'), (Permutation([], size=1), '(0)'), (Permutation([], size=2), '(1)'), (Permutation([], size=10), '(9)'), (Permutation([1, 0, 2]), '(2)(0 1)'), (Permutation([1, 0, 2, 3, 4, 5]), '(5)(0 1)'), (Permutation([1, 0, 2, 3, 4, 5], size=10), '(9)(0 1)'), (Permutation([0, 1, 3, 2, 4, 5], size=10), '(9)(2 3)'), ]: assert sstr(p) == s with warns_deprecated_sympy(): old_print_cyclic = Permutation.print_cyclic Permutation.print_cyclic = False assert sstr(Permutation([1, 0, 2])) == 'Permutation([1, 0, 2])' Permutation.print_cyclic = old_print_cyclic def test_Pi(): assert str(pi) == "pi" def test_Poly(): assert str(Poly(0, x)) == "Poly(0, x, domain='ZZ')" assert str(Poly(1, x)) == "Poly(1, x, domain='ZZ')" assert str(Poly(x, x)) == "Poly(x, x, domain='ZZ')" assert str(Poly(2*x + 1, x)) == "Poly(2*x + 1, x, domain='ZZ')" assert str(Poly(2*x - 1, x)) == "Poly(2*x - 1, x, domain='ZZ')" assert str(Poly(-1, x)) == "Poly(-1, x, domain='ZZ')" assert str(Poly(-x, x)) == "Poly(-x, x, domain='ZZ')" assert str(Poly(-2*x + 1, x)) == "Poly(-2*x + 1, x, domain='ZZ')" assert str(Poly(-2*x - 1, x)) == "Poly(-2*x - 1, x, domain='ZZ')" assert str(Poly(x - 1, x)) == "Poly(x - 1, x, domain='ZZ')" assert str(Poly(2*x + x**5, x)) == "Poly(x**5 + 2*x, x, domain='ZZ')" assert str(Poly(3**(2*x), 3**x)) == "Poly((3**x)**2, 3**x, domain='ZZ')" assert str(Poly((x**2)**x)) == "Poly(((x**2)**x), (x**2)**x, domain='ZZ')" assert str(Poly((x + y)**3, (x + y), expand=False) ) == "Poly((x + y)**3, x + y, domain='ZZ')" assert str(Poly((x - 1)**2, (x - 1), expand=False) ) == "Poly((x - 1)**2, x - 1, domain='ZZ')" assert str( Poly(x**2 + 1 + y, x)) == "Poly(x**2 + y + 1, x, domain='ZZ[y]')" assert str( Poly(x**2 - 1 + y, x)) == "Poly(x**2 + y - 1, x, domain='ZZ[y]')" assert str(Poly(x**2 + I*x, x)) == "Poly(x**2 + I*x, x, domain='ZZ_I')" assert str(Poly(x**2 - I*x, x)) == "Poly(x**2 - I*x, x, domain='ZZ_I')" assert str(Poly(-x*y*z + x*y - 1, x, y, z) ) == "Poly(-x*y*z + x*y - 1, x, y, z, domain='ZZ')" assert str(Poly(-w*x**21*y**7*z + (1 + w)*z**3 - 2*x*z + 1, x, y, z)) == \ "Poly(-w*x**21*y**7*z - 2*x*z + (w + 1)*z**3 + 1, x, y, z, domain='ZZ[w]')" assert str(Poly(x**2 + 1, x, modulus=2)) == "Poly(x**2 + 1, x, modulus=2)" assert str(Poly(2*x**2 + 3*x + 4, x, modulus=17)) == "Poly(2*x**2 + 3*x + 4, x, modulus=17)" def test_PolyRing(): assert str(ring("x", ZZ, lex)[0]) == "Polynomial ring in x over ZZ with lex order" assert str(ring("x,y", QQ, grlex)[0]) == "Polynomial ring in x, y over QQ with grlex order" assert str(ring("x,y,z", ZZ["t"], lex)[0]) == "Polynomial ring in x, y, z over ZZ[t] with lex order" def test_FracField(): assert str(field("x", ZZ, lex)[0]) == "Rational function field in x over ZZ with lex order" assert str(field("x,y", QQ, grlex)[0]) == "Rational function field in x, y over QQ with grlex order" assert str(field("x,y,z", ZZ["t"], lex)[0]) == "Rational function field in x, y, z over ZZ[t] with lex order" def test_PolyElement(): Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) Rx_zzi, xz = ring("x", ZZ_I) assert str(x - x) == "0" assert str(x - 1) == "x - 1" assert str(x + 1) == "x + 1" assert str(x**2) == "x**2" assert str(x**(-2)) == "x**(-2)" assert str(x**QQ(1, 2)) == "x**(1/2)" assert str((u**2 + 3*u*v + 1)*x**2*y + u + 1) == "(u**2 + 3*u*v + 1)*x**2*y + u + 1" assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x" assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1" assert str((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == "-(u**2 - 3*u*v + 1)*x**2*y - (u + 1)*x - 1" assert str(-(v**2 + v + 1)*x + 3*u*v + 1) == "-(v**2 + v + 1)*x + 3*u*v + 1" assert str(-(v**2 + v + 1)*x - 3*u*v + 1) == "-(v**2 + v + 1)*x - 3*u*v + 1" assert str((1+I)*xz + 2) == "(1 + 1*I)*x + (2 + 0*I)" def test_FracElement(): Fuv, u,v = field("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Fuv) Rx_zzi, xz = field("x", QQ_I) i = QQ_I(0, 1) assert str(x - x) == "0" assert str(x - 1) == "x - 1" assert str(x + 1) == "x + 1" assert str(x/3) == "x/3" assert str(x/z) == "x/z" assert str(x*y/z) == "x*y/z" assert str(x/(z*t)) == "x/(z*t)" assert str(x*y/(z*t)) == "x*y/(z*t)" assert str((x - 1)/y) == "(x - 1)/y" assert str((x + 1)/y) == "(x + 1)/y" assert str((-x - 1)/y) == "(-x - 1)/y" assert str((x + 1)/(y*z)) == "(x + 1)/(y*z)" assert str(-y/(x + 1)) == "-y/(x + 1)" assert str(y*z/(x + 1)) == "y*z/(x + 1)" assert str(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - 1)" assert str(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - u*v*t - 1)" assert str((1+i)/xz) == "(1 + 1*I)/x" assert str(((1+i)*xz - i)/xz) == "((1 + 1*I)*x + (0 + -1*I))/x" def test_GaussianInteger(): assert str(ZZ_I(1, 0)) == "1" assert str(ZZ_I(-1, 0)) == "-1" assert str(ZZ_I(0, 1)) == "I" assert str(ZZ_I(0, -1)) == "-I" assert str(ZZ_I(0, 2)) == "2*I" assert str(ZZ_I(0, -2)) == "-2*I" assert str(ZZ_I(1, 1)) == "1 + I" assert str(ZZ_I(-1, -1)) == "-1 - I" assert str(ZZ_I(-1, -2)) == "-1 - 2*I" def test_GaussianRational(): assert str(QQ_I(1, 0)) == "1" assert str(QQ_I(QQ(2, 3), 0)) == "2/3" assert str(QQ_I(0, QQ(2, 3))) == "2*I/3" assert str(QQ_I(QQ(1, 2), QQ(-2, 3))) == "1/2 - 2*I/3" def test_Pow(): assert str(x**-1) == "1/x" assert str(x**-2) == "x**(-2)" assert str(x**2) == "x**2" assert str((x + y)**-1) == "1/(x + y)" assert str((x + y)**-2) == "(x + y)**(-2)" assert str((x + y)**2) == "(x + y)**2" assert str((x + y)**(1 + x)) == "(x + y)**(x + 1)" assert str(x**Rational(1, 3)) == "x**(1/3)" assert str(1/x**Rational(1, 3)) == "x**(-1/3)" assert str(sqrt(sqrt(x))) == "x**(1/4)" # not the same as x**-1 assert str(x**-1.0) == 'x**(-1.0)' # see issue #2860 assert str(Pow(S(2), -1.0, evaluate=False)) == '2**(-1.0)' def test_sqrt(): assert str(sqrt(x)) == "sqrt(x)" assert str(sqrt(x**2)) == "sqrt(x**2)" assert str(1/sqrt(x)) == "1/sqrt(x)" assert str(1/sqrt(x**2)) == "1/sqrt(x**2)" assert str(y/sqrt(x)) == "y/sqrt(x)" assert str(x**0.5) == "x**0.5" assert str(1/x**0.5) == "x**(-0.5)" def test_Rational(): n1 = Rational(1, 4) n2 = Rational(1, 3) n3 = Rational(2, 4) n4 = Rational(2, -4) n5 = Rational(0) n7 = Rational(3) n8 = Rational(-3) assert str(n1*n2) == "1/12" assert str(n1*n2) == "1/12" assert str(n3) == "1/2" assert str(n1*n3) == "1/8" assert str(n1 + n3) == "3/4" assert str(n1 + n2) == "7/12" assert str(n1 + n4) == "-1/4" assert str(n4*n4) == "1/4" assert str(n4 + n2) == "-1/6" assert str(n4 + n5) == "-1/2" assert str(n4*n5) == "0" assert str(n3 + n4) == "0" assert str(n1**n7) == "1/64" assert str(n2**n7) == "1/27" assert str(n2**n8) == "27" assert str(n7**n8) == "1/27" assert str(Rational("-25")) == "-25" assert str(Rational("1.25")) == "5/4" assert str(Rational("-2.6e-2")) == "-13/500" assert str(S("25/7")) == "25/7" assert str(S("-123/569")) == "-123/569" assert str(S("0.1[23]", rational=1)) == "61/495" assert str(S("5.1[666]", rational=1)) == "31/6" assert str(S("-5.1[666]", rational=1)) == "-31/6" assert str(S("0.[9]", rational=1)) == "1" assert str(S("-0.[9]", rational=1)) == "-1" assert str(sqrt(Rational(1, 4))) == "1/2" assert str(sqrt(Rational(1, 36))) == "1/6" assert str((123**25) ** Rational(1, 25)) == "123" assert str((123**25 + 1)**Rational(1, 25)) != "123" assert str((123**25 - 1)**Rational(1, 25)) != "123" assert str((123**25 - 1)**Rational(1, 25)) != "122" assert str(sqrt(Rational(81, 36))**3) == "27/8" assert str(1/sqrt(Rational(81, 36))**3) == "8/27" assert str(sqrt(-4)) == str(2*I) assert str(2**Rational(1, 10**10)) == "2**(1/10000000000)" assert sstr(Rational(2, 3), sympy_integers=True) == "S(2)/3" x = Symbol("x") assert sstr(x**Rational(2, 3), sympy_integers=True) == "x**(S(2)/3)" assert sstr(Eq(x, Rational(2, 3)), sympy_integers=True) == "Eq(x, S(2)/3)" assert sstr(Limit(x, x, Rational(7, 2)), sympy_integers=True) == \ "Limit(x, x, S(7)/2)" def test_Float(): # NOTE dps is the whole number of decimal digits assert str(Float('1.23', dps=1 + 2)) == '1.23' assert str(Float('1.23456789', dps=1 + 8)) == '1.23456789' assert str( Float('1.234567890123456789', dps=1 + 18)) == '1.234567890123456789' assert str(pi.evalf(1 + 2)) == '3.14' assert str(pi.evalf(1 + 14)) == '3.14159265358979' assert str(pi.evalf(1 + 64)) == ('3.141592653589793238462643383279' '5028841971693993751058209749445923') assert str(pi.round(-1)) == '0.0' assert str((pi**400 - (pi**400).round(1)).n(2)) == '-0.e+88' assert sstr(Float("100"), full_prec=False, min=-2, max=2) == '1.0e+2' assert sstr(Float("100"), full_prec=False, min=-2, max=3) == '100.0' assert sstr(Float("0.1"), full_prec=False, min=-2, max=3) == '0.1' assert sstr(Float("0.099"), min=-2, max=3) == '9.90000000000000e-2' def test_Relational(): assert str(Rel(x, y, "<")) == "x < y" assert str(Rel(x + y, y, "==")) == "Eq(x + y, y)" assert str(Rel(x, y, "!=")) == "Ne(x, y)" assert str(Eq(x, 1) | Eq(x, 2)) == "Eq(x, 1) | Eq(x, 2)" assert str(Ne(x, 1) & Ne(x, 2)) == "Ne(x, 1) & Ne(x, 2)" def test_AppliedBinaryRelation(): assert str(Q.eq(x, y)) == "Q.eq(x, y)" assert str(Q.ne(x, y)) == "Q.ne(x, y)" def test_CRootOf(): assert str(rootof(x**5 + 2*x - 1, 0)) == "CRootOf(x**5 + 2*x - 1, 0)" def test_RootSum(): f = x**5 + 2*x - 1 assert str( RootSum(f, Lambda(z, z), auto=False)) == "RootSum(x**5 + 2*x - 1)" assert str(RootSum(f, Lambda( z, z**2), auto=False)) == "RootSum(x**5 + 2*x - 1, Lambda(z, z**2))" def test_GroebnerBasis(): assert str(groebner( [], x, y)) == "GroebnerBasis([], x, y, domain='ZZ', order='lex')" F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] assert str(groebner(F, order='grlex')) == \ "GroebnerBasis([x**2 - x - 3*y + 1, y**2 - 2*x + y - 1], x, y, domain='ZZ', order='grlex')" assert str(groebner(F, order='lex')) == \ "GroebnerBasis([2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7], x, y, domain='ZZ', order='lex')" def test_set(): assert sstr(set()) == 'set()' assert sstr(frozenset()) == 'frozenset()' assert sstr({1}) == '{1}' assert sstr(frozenset([1])) == 'frozenset({1})' assert sstr({1, 2, 3}) == '{1, 2, 3}' assert sstr(frozenset([1, 2, 3])) == 'frozenset({1, 2, 3})' assert sstr( {1, x, x**2, x**3, x**4}) == '{1, x, x**2, x**3, x**4}' assert sstr( frozenset([1, x, x**2, x**3, x**4])) == 'frozenset({1, x, x**2, x**3, x**4})' def test_SparseMatrix(): M = SparseMatrix([[x**+1, 1], [y, x + y]]) assert str(M) == "Matrix([[x, 1], [y, x + y]])" assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])" def test_Sum(): assert str(summation(cos(3*z), (z, x, y))) == "Sum(cos(3*z), (z, x, y))" assert str(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \ "Sum(x*y**2, (x, -2, 2), (y, -5, 5))" def test_Symbol(): assert str(y) == "y" assert str(x) == "x" e = x assert str(e) == "x" def test_tuple(): assert str((x,)) == sstr((x,)) == "(x,)" assert str((x + y, 1 + x)) == sstr((x + y, 1 + x)) == "(x + y, x + 1)" assert str((x + y, ( 1 + x, x**2))) == sstr((x + y, (1 + x, x**2))) == "(x + y, (x + 1, x**2))" def test_Series_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert str(Series(tf1, tf2)) == \ "Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y))" assert str(Series(tf1, tf2, tf3)) == \ "Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y), TransferFunction(t*x**2 - t**w*x + w, t - y, y))" assert str(Series(-tf2, tf1)) == \ "Series(TransferFunction(-x + y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y))" def test_MIMOSeries_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) assert str(MIMOSeries(tfm_1, tfm_2)) == \ "MIMOSeries(TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), "\ "(TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)))), "\ "TransferFunctionMatrix(((TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)), "\ "(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)))))" def test_TransferFunction_str(): tf1 = TransferFunction(x - 1, x + 1, x) assert str(tf1) == "TransferFunction(x - 1, x + 1, x)" tf2 = TransferFunction(x + 1, 2 - y, x) assert str(tf2) == "TransferFunction(x + 1, 2 - y, x)" tf3 = TransferFunction(y, y**2 + 2*y + 3, y) assert str(tf3) == "TransferFunction(y, y**2 + 2*y + 3, y)" def test_Parallel_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert str(Parallel(tf1, tf2)) == \ "Parallel(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y))" assert str(Parallel(tf1, tf2, tf3)) == \ "Parallel(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y), TransferFunction(t*x**2 - t**w*x + w, t - y, y))" assert str(Parallel(-tf2, tf1)) == \ "Parallel(TransferFunction(-x + y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y))" def test_MIMOParallel_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) assert str(MIMOParallel(tfm_1, tfm_2)) == \ "MIMOParallel(TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), "\ "(TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)))), "\ "TransferFunctionMatrix(((TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)), "\ "(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)))))" def test_Feedback_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert str(Feedback(tf1*tf2, tf3)) == \ "Feedback(Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), " \ "TransferFunction(t*x**2 - t**w*x + w, t - y, y), -1)" assert str(Feedback(tf1, TransferFunction(1, 1, y), 1)) == \ "Feedback(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(1, 1, y), 1)" def test_MIMOFeedback_str(): tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) assert (str(MIMOFeedback(tfm_1, tfm_2)) \ == "MIMOFeedback(TransferFunctionMatrix(((TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x))," \ " (TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)))), " \ "TransferFunctionMatrix(((TransferFunction(x**2 - y**3, y - z, x), " \ "TransferFunction(-x + y, y + z, x)), (TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)))), -1)") assert (str(MIMOFeedback(tfm_1, tfm_2, 1)) \ == "MIMOFeedback(TransferFunctionMatrix(((TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)), " \ "(TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)))), " \ "TransferFunctionMatrix(((TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)), "\ "(TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)))), 1)") def test_TransferFunctionMatrix_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert str(TransferFunctionMatrix([[tf1], [tf2]])) == \ "TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y),), (TransferFunction(x - y, x + y, y),)))" assert str(TransferFunctionMatrix([[tf1, tf2], [tf3, tf2]])) == \ "TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), (TransferFunction(t*x**2 - t**w*x + w, t - y, y), TransferFunction(x - y, x + y, y))))" def test_Quaternion_str_printer(): q = Quaternion(x, y, z, t) assert str(q) == "x + y*i + z*j + t*k" q = Quaternion(x,y,z,x*t) assert str(q) == "x + y*i + z*j + t*x*k" q = Quaternion(x,y,z,x+t) assert str(q) == "x + y*i + z*j + (t + x)*k" def test_Quantity_str(): assert sstr(second, abbrev=True) == "s" assert sstr(joule, abbrev=True) == "J" assert str(second) == "second" assert str(joule) == "joule" def test_wild_str(): # Check expressions containing Wild not causing infinite recursion w = Wild('x') assert str(w + 1) == 'x_ + 1' assert str(exp(2**w) + 5) == 'exp(2**x_) + 5' assert str(3*w + 1) == '3*x_ + 1' assert str(1/w + 1) == '1 + 1/x_' assert str(w**2 + 1) == 'x_**2 + 1' assert str(1/(1 - w)) == '1/(1 - x_)' def test_wild_matchpy(): from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar matchpy = import_module("matchpy") if matchpy is None: return wd = WildDot('w_') wp = WildPlus('w__') ws = WildStar('w___') assert str(wd) == 'w_' assert str(wp) == 'w__' assert str(ws) == 'w___' assert str(wp/ws + 2**wd) == '2**w_ + w__/w___' assert str(sin(wd)*cos(wp)*sqrt(ws)) == 'sqrt(w___)*sin(w_)*cos(w__)' def test_zeta(): assert str(zeta(3)) == "zeta(3)" def test_issue_3101(): e = x - y a = str(e) b = str(e) assert a == b def test_issue_3103(): e = -2*sqrt(x) - y/sqrt(x)/2 assert str(e) not in ["(-2)*x**1/2(-1/2)*x**(-1/2)*y", "-2*x**1/2(-1/2)*x**(-1/2)*y", "-2*x**1/2-1/2*x**-1/2*w"] assert str(e) == "-2*sqrt(x) - y/(2*sqrt(x))" def test_issue_4021(): e = Integral(x, x) + 1 assert str(e) == 'Integral(x, x) + 1' def test_sstrrepr(): assert sstr('abc') == 'abc' assert sstrrepr('abc') == "'abc'" e = ['a', 'b', 'c', x] assert sstr(e) == "[a, b, c, x]" assert sstrrepr(e) == "['a', 'b', 'c', x]" def test_infinity(): assert sstr(oo*I) == "oo*I" def test_full_prec(): assert sstr(S("0.3"), full_prec=True) == "0.300000000000000" assert sstr(S("0.3"), full_prec="auto") == "0.300000000000000" assert sstr(S("0.3"), full_prec=False) == "0.3" assert sstr(S("0.3")*x, full_prec=True) in [ "0.300000000000000*x", "x*0.300000000000000" ] assert sstr(S("0.3")*x, full_prec="auto") in [ "0.3*x", "x*0.3" ] assert sstr(S("0.3")*x, full_prec=False) in [ "0.3*x", "x*0.3" ] def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) assert sstr(A*B*C**-1) == "A*B*C**(-1)" assert sstr(C**-1*A*B) == "C**(-1)*A*B" assert sstr(A*C**-1*B) == "A*C**(-1)*B" assert sstr(sqrt(A)) == "sqrt(A)" assert sstr(1/sqrt(A)) == "A**(-1/2)" def test_empty_printer(): str_printer = StrPrinter() assert str_printer.emptyPrinter("foo") == "foo" assert str_printer.emptyPrinter(x*y) == "x*y" assert str_printer.emptyPrinter(32) == "32" def test_settings(): raises(TypeError, lambda: sstr(S(4), method="garbage")) def test_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where X = Normal('x1', 0, 1) assert str(where(X > 0)) == "Domain: (0 < x1) & (x1 < oo)" D = Die('d1', 6) assert str(where(D > 4)) == "Domain: Eq(d1, 5) | Eq(d1, 6)" A = Exponential('a', 1) B = Exponential('b', 1) assert str(pspace(Tuple(A, B)).domain) == "Domain: (0 <= a) & (0 <= b) & (a < oo) & (b < oo)" def test_FiniteSet(): assert str(FiniteSet(*range(1, 51))) == ( '{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,' ' 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,' ' 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}' ) assert str(FiniteSet(*range(1, 6))) == '{1, 2, 3, 4, 5}' assert str(FiniteSet(*[x*y, x**2])) == '{x**2, x*y}' assert str(FiniteSet(FiniteSet(FiniteSet(x, y), 5), FiniteSet(x,y), 5) ) == 'FiniteSet(5, FiniteSet(5, {x, y}), {x, y})' def test_Partition(): assert str(Partition(FiniteSet(x, y), {z})) == 'Partition({z}, {x, y})' def test_UniversalSet(): assert str(S.UniversalSet) == 'UniversalSet' def test_PrettyPoly(): F = QQ.frac_field(x, y) R = QQ[x, y] assert sstr(F.convert(x/(x + y))) == sstr(x/(x + y)) assert sstr(R.convert(x + y)) == sstr(x + y) def test_categories(): from sympy.categories import (Object, NamedMorphism, IdentityMorphism, Category) A = Object("A") B = Object("B") f = NamedMorphism(A, B, "f") id_A = IdentityMorphism(A) K = Category("K") assert str(A) == 'Object("A")' assert str(f) == 'NamedMorphism(Object("A"), Object("B"), "f")' assert str(id_A) == 'IdentityMorphism(Object("A"))' assert str(K) == 'Category("K")' def test_Tr(): A, B = symbols('A B', commutative=False) t = Tr(A*B) assert str(t) == 'Tr(A*B)' def test_issue_6387(): assert str(factor(-3.0*z + 3)) == '-3.0*(1.0*z - 1.0)' def test_MatMul_MatAdd(): X, Y = MatrixSymbol("X", 2, 2), MatrixSymbol("Y", 2, 2) assert str(2*(X + Y)) == "2*X + 2*Y" assert str(I*X) == "I*X" assert str(-I*X) == "-I*X" assert str((1 + I)*X) == '(1 + I)*X' assert str(-(1 + I)*X) == '(-1 - I)*X' assert str(MatAdd(MatAdd(X, Y), MatAdd(X, Y))) == '(X + Y) + (X + Y)' def test_MatrixSlice(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', 10, 10) Z = MatrixSymbol('Z', 10, 10) assert str(MatrixSlice(X, (None, None, None), (None, None, None))) == 'X[:, :]' assert str(X[x:x + 1, y:y + 1]) == 'X[x:x + 1, y:y + 1]' assert str(X[x:x + 1:2, y:y + 1:2]) == 'X[x:x + 1:2, y:y + 1:2]' assert str(X[:x, y:]) == 'X[:x, y:]' assert str(X[:x, y:]) == 'X[:x, y:]' assert str(X[x:, :y]) == 'X[x:, :y]' assert str(X[x:y, z:w]) == 'X[x:y, z:w]' assert str(X[x:y:t, w:t:x]) == 'X[x:y:t, w:t:x]' assert str(X[x::y, t::w]) == 'X[x::y, t::w]' assert str(X[:x:y, :t:w]) == 'X[:x:y, :t:w]' assert str(X[::x, ::y]) == 'X[::x, ::y]' assert str(MatrixSlice(X, (0, None, None), (0, None, None))) == 'X[:, :]' assert str(MatrixSlice(X, (None, n, None), (None, n, None))) == 'X[:, :]' assert str(MatrixSlice(X, (0, n, None), (0, n, None))) == 'X[:, :]' assert str(MatrixSlice(X, (0, n, 2), (0, n, 2))) == 'X[::2, ::2]' assert str(X[1:2:3, 4:5:6]) == 'X[1:2:3, 4:5:6]' assert str(X[1:3:5, 4:6:8]) == 'X[1:3:5, 4:6:8]' assert str(X[1:10:2]) == 'X[1:10:2, :]' assert str(Y[:5, 1:9:2]) == 'Y[:5, 1:9:2]' assert str(Y[:5, 1:10:2]) == 'Y[:5, 1::2]' assert str(Y[5, :5:2]) == 'Y[5:6, :5:2]' assert str(X[0:1, 0:1]) == 'X[:1, :1]' assert str(X[0:1:2, 0:1:2]) == 'X[:1:2, :1:2]' assert str((Y + Z)[2:, 2:]) == '(Y + Z)[2:, 2:]' def test_true_false(): assert str(true) == repr(true) == sstr(true) == "True" assert str(false) == repr(false) == sstr(false) == "False" def test_Equivalent(): assert str(Equivalent(y, x)) == "Equivalent(x, y)" def test_Xor(): assert str(Xor(y, x, evaluate=False)) == "x ^ y" def test_Complement(): assert str(Complement(S.Reals, S.Naturals)) == 'Complement(Reals, Naturals)' def test_SymmetricDifference(): assert str(SymmetricDifference(Interval(2, 3), Interval(3, 4),evaluate=False)) == \ 'SymmetricDifference(Interval(2, 3), Interval(3, 4))' def test_UnevaluatedExpr(): a, b = symbols("a b") expr1 = 2*UnevaluatedExpr(a+b) assert str(expr1) == "2*(a + b)" def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(str(A[0, 0]) == "A[0, 0]") assert(str(3 * A[0, 0]) == "3*A[0, 0]") F = C[0, 0].subs(C, A - B) assert str(F) == "(A - B)[0, 0]" def test_MatrixSymbol_printing(): A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert str(A - A*B - B) == "A - A*B - B" assert str(A*B - (A+B)) == "-A + A*B - B" assert str(A**(-1)) == "A**(-1)" assert str(A**3) == "A**3" def test_MatrixExpressions(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) assert str(X) == "X" # Apply function elementwise (`ElementwiseApplyFunc`): expr = (X.T*X).applyfunc(sin) assert str(expr) == 'Lambda(_d, sin(_d)).(X.T*X)' lamda = Lambda(x, 1/x) expr = (n*X).applyfunc(lamda) assert str(expr) == 'Lambda(x, 1/x).(n*X)' def test_Subs_printing(): assert str(Subs(x, (x,), (1,))) == 'Subs(x, x, 1)' assert str(Subs(x + y, (x, y), (1, 2))) == 'Subs(x + y, (x, y), (1, 2))' def test_issue_15716(): e = Integral(factorial(x), (x, -oo, oo)) assert e.as_terms() == ([(e, ((1.0, 0.0), (1,), ()))], [e]) def test_str_special_matrices(): from sympy.matrices import Identity, ZeroMatrix, OneMatrix assert str(Identity(4)) == 'I' assert str(ZeroMatrix(2, 2)) == '0' assert str(OneMatrix(2, 2)) == '1' def test_issue_14567(): assert factorial(Sum(-1, (x, 0, 0))) + y # doesn't raise an error def test_issue_21823(): assert str(Partition([1, 2])) == 'Partition({1, 2})' assert str(Partition({1, 2})) == 'Partition({1, 2})' def test_issue_22689(): assert str(Mul(Pow(x,-2, evaluate=False), Pow(3,-1,evaluate=False), evaluate=False)) == "1/(x**2*3)" def test_issue_21119_21460(): ss = lambda x: str(S(x, evaluate=False)) assert ss('4/2') == '4/2' assert ss('4/-2') == '4/(-2)' assert ss('-4/2') == '-4/2' assert ss('-4/-2') == '-4/(-2)' assert ss('-2*3/-1') == '-2*3/(-1)' assert ss('-2*3/-1/2') == '-2*3/(-1*2)' assert ss('4/2/1') == '4/(2*1)' assert ss('-2/-1/2') == '-2/(-1*2)' assert ss('2*3*4**(-2*3)') == '2*3/4**(2*3)' assert ss('2*3*1*4**(-2*3)') == '2*3*1/4**(2*3)' def test_Str(): from sympy.core.symbol import Str assert str(Str('x')) == 'x' assert sstrrepr(Str('x')) == "Str('x')" def test_diffgeom(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField x,y = symbols('x y', real=True) m = Manifold('M', 2) assert str(m) == "M" p = Patch('P', m) assert str(p) == "P" rect = CoordSystem('rect', p, [x, y]) assert str(rect) == "rect" b = BaseScalarField(rect, 0) assert str(b) == "x" def test_NDimArray(): assert sstr(NDimArray(1.0), full_prec=True) == '1.00000000000000' assert sstr(NDimArray(1.0), full_prec=False) == '1.0' assert sstr(NDimArray([1.0, 2.0]), full_prec=True) == '[1.00000000000000, 2.00000000000000]' assert sstr(NDimArray([1.0, 2.0]), full_prec=False) == '[1.0, 2.0]' def test_Predicate(): assert sstr(Q.even) == 'Q.even' def test_AppliedPredicate(): assert sstr(Q.even(x)) == 'Q.even(x)' def test_printing_str_array_expressions(): assert sstr(ArraySymbol("A", (2, 3, 4))) == "A" assert sstr(ArrayElement("A", (2, 1/(1-x), 0))) == "A[2, 1/(1 - x), 0]" M = MatrixSymbol("M", 3, 3) N = MatrixSymbol("N", 3, 3) assert sstr(ArrayElement(M*N, [x, 0])) == "(M*N)[x, 0]"
9bc501c6e96e1747c46282d238c33bf55b70844ce4a888a8baeeafb1a6751b87
from sympy import MatAdd, MatMul, Array from sympy.algebras.quaternion import Quaternion from sympy.calculus.accumulationbounds import AccumBounds from sympy.combinatorics.permutations import Cycle, Permutation, AppliedPermutation from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.core.containers import Tuple, Dict from sympy.core.expr import UnevaluatedExpr from sympy.core.function import (Derivative, Function, Lambda, Subs, diff) from sympy.core.mod import Mod from sympy.core.mul import Mul from sympy.core.numbers import (AlgebraicNumber, Float, I, Integer, Rational, oo, pi) from sympy.core.parameters import evaluate from sympy.core.power import Pow from sympy.core.relational import Eq, Ne from sympy.core.singleton import S from sympy.core.symbol import (Symbol, Wild, symbols) from sympy.functions.combinatorial.factorials import (FallingFactorial, RisingFactorial, binomial, factorial, factorial2, subfactorial) from sympy.functions.combinatorial.numbers import bernoulli, bell, catalan, euler, genocchi, lucas, fibonacci, tribonacci from sympy.functions.elementary.complexes import (Abs, arg, conjugate, im, polar_lift, re) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.hyperbolic import (asinh, coth) from sympy.functions.elementary.integers import (ceiling, floor, frac) from sympy.functions.elementary.miscellaneous import (Max, Min, root, sqrt) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acsc, asin, cos, cot, sin, tan) from sympy.functions.special.beta_functions import beta from sympy.functions.special.delta_functions import (DiracDelta, Heaviside) from sympy.functions.special.elliptic_integrals import (elliptic_e, elliptic_f, elliptic_k, elliptic_pi) from sympy.functions.special.error_functions import (Chi, Ci, Ei, Shi, Si, expint) from sympy.functions.special.gamma_functions import (gamma, uppergamma) from sympy.functions.special.hyper import (hyper, meijerg) from sympy.functions.special.mathieu_functions import (mathieuc, mathieucprime, mathieus, mathieusprime) from sympy.functions.special.polynomials import (assoc_laguerre, assoc_legendre, chebyshevt, chebyshevu, gegenbauer, hermite, jacobi, laguerre, legendre) from sympy.functions.special.singularity_functions import SingularityFunction from sympy.functions.special.spherical_harmonics import (Ynm, Znm) from sympy.functions.special.tensor_functions import (KroneckerDelta, LeviCivita) from sympy.functions.special.zeta_functions import (dirichlet_eta, lerchphi, polylog, stieltjes, zeta) from sympy.integrals.integrals import Integral from sympy.integrals.transforms import (CosineTransform, FourierTransform, InverseCosineTransform, InverseFourierTransform, InverseLaplaceTransform, InverseMellinTransform, InverseSineTransform, LaplaceTransform, MellinTransform, SineTransform) from sympy.logic import Implies from sympy.logic.boolalg import (And, Or, Xor, Equivalent, false, Not, true) from sympy.matrices.dense import Matrix from sympy.matrices.expressions.kronecker import KroneckerProduct from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.permutation import PermutationMatrix from sympy.matrices.expressions.slice import MatrixSlice from sympy.physics.control.lti import TransferFunction, Series, Parallel, Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback from sympy.ntheory.factor_ import (divisor_sigma, primenu, primeomega, reduced_totient, totient, udivisor_sigma) from sympy.physics.quantum import Commutator, Operator from sympy.physics.quantum.trace import Tr from sympy.physics.units import meter, gibibyte, gram, microgram, second, milli, micro from sympy.polys.domains.integerring import ZZ from sympy.polys.fields import field from sympy.polys.polytools import Poly from sympy.polys.rings import ring from sympy.polys.rootoftools import (RootSum, rootof) from sympy.series.formal import fps from sympy.series.fourier import fourier_series from sympy.series.limits import Limit from sympy.series.order import Order from sympy.series.sequences import (SeqAdd, SeqFormula, SeqMul, SeqPer) from sympy.sets.conditionset import ConditionSet from sympy.sets.contains import Contains from sympy.sets.fancysets import (ComplexRegion, ImageSet, Range) from sympy.sets.ordinals import Ordinal, OrdinalOmega, OmegaPower from sympy.sets.powerset import PowerSet from sympy.sets.sets import (FiniteSet, Interval, Union, Intersection, Complement, SymmetricDifference, ProductSet) from sympy.sets.setexpr import SetExpr from sympy.stats.crv_types import Normal from sympy.stats.symbolic_probability import (Covariance, Expectation, Probability, Variance) from sympy.tensor.array import (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableSparseNDimArray, MutableDenseNDimArray, tensorproduct) from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElement from sympy.tensor.indexed import (Idx, Indexed, IndexedBase) from sympy.tensor.toperators import PartialDerivative from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian from sympy.testing.pytest import (XFAIL, raises, _both_exp_pow, warns_deprecated_sympy) from sympy.printing.latex import (latex, translate, greek_letters_set, tex_greek_dictionary, multiline_latex, latex_escape, LatexPrinter) import sympy as sym from sympy.abc import mu, tau class lowergamma(sym.lowergamma): pass # testing notation inheritance by a subclass with same name x, y, z, t, w, a, b, c, s, p = symbols('x y z t w a b c s p') k, m, n = symbols('k m n', integer=True) def test_printmethod(): class R(Abs): def _latex(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert latex(R(x)) == r"foo(x)" class R(Abs): def _latex(self, printer): return "foo" assert latex(R(x)) == r"foo" def test_latex_basic(): assert latex(1 + x) == r"x + 1" assert latex(x**2) == r"x^{2}" assert latex(x**(1 + x)) == r"x^{x + 1}" assert latex(x**3 + x + 1 + x**2) == r"x^{3} + x^{2} + x + 1" assert latex(2*x*y) == r"2 x y" assert latex(2*x*y, mul_symbol='dot') == r"2 \cdot x \cdot y" assert latex(3*x**2*y, mul_symbol='\\,') == r"3\,x^{2}\,y" assert latex(1.5*3**x, mul_symbol='\\,') == r"1.5 \cdot 3^{x}" assert latex(x**S.Half**5) == r"\sqrt[32]{x}" assert latex(Mul(S.Half, x**2, -5, evaluate=False)) == r"\frac{1}{2} x^{2} \left(-5\right)" assert latex(Mul(S.Half, x**2, 5, evaluate=False)) == r"\frac{1}{2} x^{2} \cdot 5" assert latex(Mul(-5, -5, evaluate=False)) == r"\left(-5\right) \left(-5\right)" assert latex(Mul(5, -5, evaluate=False)) == r"5 \left(-5\right)" assert latex(Mul(S.Half, -5, S.Half, evaluate=False)) == r"\frac{1}{2} \left(-5\right) \frac{1}{2}" assert latex(Mul(5, I, 5, evaluate=False)) == r"5 i 5" assert latex(Mul(5, I, -5, evaluate=False)) == r"5 i \left(-5\right)" assert latex(Mul(0, 1, evaluate=False)) == r'0 \cdot 1' assert latex(Mul(1, 0, evaluate=False)) == r'1 \cdot 0' assert latex(Mul(1, 1, evaluate=False)) == r'1 \cdot 1' assert latex(Mul(-1, 1, evaluate=False)) == r'\left(-1\right) 1' assert latex(Mul(1, 1, 1, evaluate=False)) == r'1 \cdot 1 \cdot 1' assert latex(Mul(1, 2, evaluate=False)) == r'1 \cdot 2' assert latex(Mul(1, S.Half, evaluate=False)) == r'1 \cdot \frac{1}{2}' assert latex(Mul(1, 1, S.Half, evaluate=False)) == \ r'1 \cdot 1 \cdot \frac{1}{2}' assert latex(Mul(1, 1, 2, 3, x, evaluate=False)) == \ r'1 \cdot 1 \cdot 2 \cdot 3 x' assert latex(Mul(1, -1, evaluate=False)) == r'1 \left(-1\right)' assert latex(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == \ r'4 \cdot 3 \cdot 2 \cdot 1 \cdot 0 y x' assert latex(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == \ r'4 \cdot 3 \cdot 2 \left(z + 1\right) 0 y x' assert latex(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == \ r'\frac{2}{3} \cdot \frac{5}{7}' assert latex(1/x) == r"\frac{1}{x}" assert latex(1/x, fold_short_frac=True) == r"1 / x" assert latex(-S(3)/2) == r"- \frac{3}{2}" assert latex(-S(3)/2, fold_short_frac=True) == r"- 3 / 2" assert latex(1/x**2) == r"\frac{1}{x^{2}}" assert latex(1/(x + y)/2) == r"\frac{1}{2 \left(x + y\right)}" assert latex(x/2) == r"\frac{x}{2}" assert latex(x/2, fold_short_frac=True) == r"x / 2" assert latex((x + y)/(2*x)) == r"\frac{x + y}{2 x}" assert latex((x + y)/(2*x), fold_short_frac=True) == \ r"\left(x + y\right) / 2 x" assert latex((x + y)/(2*x), long_frac_ratio=0) == \ r"\frac{1}{2 x} \left(x + y\right)" assert latex((x + y)/x) == r"\frac{x + y}{x}" assert latex((x + y)/x, long_frac_ratio=3) == r"\frac{x + y}{x}" assert latex((2*sqrt(2)*x)/3) == r"\frac{2 \sqrt{2} x}{3}" assert latex((2*sqrt(2)*x)/3, long_frac_ratio=2) == \ r"\frac{2 x}{3} \sqrt{2}" assert latex(binomial(x, y)) == r"{\binom{x}{y}}" x_star = Symbol('x^*') f = Function('f') assert latex(x_star**2) == r"\left(x^{*}\right)^{2}" assert latex(x_star**2, parenthesize_super=False) == r"{x^{*}}^{2}" assert latex(Derivative(f(x_star), x_star,2)) == r"\frac{d^{2}}{d \left(x^{*}\right)^{2}} f{\left(x^{*} \right)}" assert latex(Derivative(f(x_star), x_star,2), parenthesize_super=False) == r"\frac{d^{2}}{d {x^{*}}^{2}} f{\left(x^{*} \right)}" assert latex(2*Integral(x, x)/3) == r"\frac{2 \int x\, dx}{3}" assert latex(2*Integral(x, x)/3, fold_short_frac=True) == \ r"\left(2 \int x\, dx\right) / 3" assert latex(sqrt(x)) == r"\sqrt{x}" assert latex(x**Rational(1, 3)) == r"\sqrt[3]{x}" assert latex(x**Rational(1, 3), root_notation=False) == r"x^{\frac{1}{3}}" assert latex(sqrt(x)**3) == r"x^{\frac{3}{2}}" assert latex(sqrt(x), itex=True) == r"\sqrt{x}" assert latex(x**Rational(1, 3), itex=True) == r"\root{3}{x}" assert latex(sqrt(x)**3, itex=True) == r"x^{\frac{3}{2}}" assert latex(x**Rational(3, 4)) == r"x^{\frac{3}{4}}" assert latex(x**Rational(3, 4), fold_frac_powers=True) == r"x^{3/4}" assert latex((x + 1)**Rational(3, 4)) == \ r"\left(x + 1\right)^{\frac{3}{4}}" assert latex((x + 1)**Rational(3, 4), fold_frac_powers=True) == \ r"\left(x + 1\right)^{3/4}" assert latex(AlgebraicNumber(sqrt(2))) == r"\sqrt{2}" assert latex(AlgebraicNumber(sqrt(2), [3, -7])) == r"-7 + 3 \sqrt{2}" assert latex(AlgebraicNumber(sqrt(2), alias='alpha')) == r"\alpha" assert latex(AlgebraicNumber(sqrt(2), [3, -7], alias='alpha')) == \ r"3 \alpha - 7" assert latex(AlgebraicNumber(2**(S(1)/3), [1, 3, -7], alias='beta')) == \ r"\beta^{2} + 3 \beta - 7" k = ZZ.cyclotomic_field(5) assert latex(k.ext.field_element([1, 2, 3, 4])) == \ r"\zeta^{3} + 2 \zeta^{2} + 3 \zeta + 4" assert latex(k.ext.field_element([1, 2, 3, 4]), order='old') == \ r"4 + 3 \zeta + 2 \zeta^{2} + \zeta^{3}" assert latex(k.primes_above(19)[0]) == \ r"\left(19, \zeta^{2} + 5 \zeta + 1\right)" assert latex(k.primes_above(19)[0], order='old') == \ r"\left(19, 1 + 5 \zeta + \zeta^{2}\right)" assert latex(k.primes_above(7)[0]) == r"\left(7\right)" assert latex(1.5e20*x) == r"1.5 \cdot 10^{20} x" assert latex(1.5e20*x, mul_symbol='dot') == r"1.5 \cdot 10^{20} \cdot x" assert latex(1.5e20*x, mul_symbol='times') == \ r"1.5 \times 10^{20} \times x" assert latex(1/sin(x)) == r"\frac{1}{\sin{\left(x \right)}}" assert latex(sin(x)**-1) == r"\frac{1}{\sin{\left(x \right)}}" assert latex(sin(x)**Rational(3, 2)) == \ r"\sin^{\frac{3}{2}}{\left(x \right)}" assert latex(sin(x)**Rational(3, 2), fold_frac_powers=True) == \ r"\sin^{3/2}{\left(x \right)}" assert latex(~x) == r"\neg x" assert latex(x & y) == r"x \wedge y" assert latex(x & y & z) == r"x \wedge y \wedge z" assert latex(x | y) == r"x \vee y" assert latex(x | y | z) == r"x \vee y \vee z" assert latex((x & y) | z) == r"z \vee \left(x \wedge y\right)" assert latex(Implies(x, y)) == r"x \Rightarrow y" assert latex(~(x >> ~y)) == r"x \not\Rightarrow \neg y" assert latex(Implies(Or(x,y), z)) == r"\left(x \vee y\right) \Rightarrow z" assert latex(Implies(z, Or(x,y))) == r"z \Rightarrow \left(x \vee y\right)" assert latex(~(x & y)) == r"\neg \left(x \wedge y\right)" assert latex(~x, symbol_names={x: "x_i"}) == r"\neg x_i" assert latex(x & y, symbol_names={x: "x_i", y: "y_i"}) == \ r"x_i \wedge y_i" assert latex(x & y & z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"x_i \wedge y_i \wedge z_i" assert latex(x | y, symbol_names={x: "x_i", y: "y_i"}) == r"x_i \vee y_i" assert latex(x | y | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"x_i \vee y_i \vee z_i" assert latex((x & y) | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"z_i \vee \left(x_i \wedge y_i\right)" assert latex(Implies(x, y), symbol_names={x: "x_i", y: "y_i"}) == \ r"x_i \Rightarrow y_i" assert latex(Pow(Rational(1, 3), -1, evaluate=False)) == r"\frac{1}{\frac{1}{3}}" assert latex(Pow(Rational(1, 3), -2, evaluate=False)) == r"\frac{1}{(\frac{1}{3})^{2}}" assert latex(Pow(Integer(1)/100, -1, evaluate=False)) == r"\frac{1}{\frac{1}{100}}" p = Symbol('p', positive=True) assert latex(exp(-p)*log(p)) == r"e^{- p} \log{\left(p \right)}" def test_latex_builtins(): assert latex(True) == r"\text{True}" assert latex(False) == r"\text{False}" assert latex(None) == r"\text{None}" assert latex(true) == r"\text{True}" assert latex(false) == r'\text{False}' def test_latex_SingularityFunction(): assert latex(SingularityFunction(x, 4, 5)) == \ r"{\left\langle x - 4 \right\rangle}^{5}" assert latex(SingularityFunction(x, -3, 4)) == \ r"{\left\langle x + 3 \right\rangle}^{4}" assert latex(SingularityFunction(x, 0, 4)) == \ r"{\left\langle x \right\rangle}^{4}" assert latex(SingularityFunction(x, a, n)) == \ r"{\left\langle - a + x \right\rangle}^{n}" assert latex(SingularityFunction(x, 4, -2)) == \ r"{\left\langle x - 4 \right\rangle}^{-2}" assert latex(SingularityFunction(x, 4, -1)) == \ r"{\left\langle x - 4 \right\rangle}^{-1}" assert latex(SingularityFunction(x, 4, 5)**3) == \ r"{\left({\langle x - 4 \rangle}^{5}\right)}^{3}" assert latex(SingularityFunction(x, -3, 4)**3) == \ r"{\left({\langle x + 3 \rangle}^{4}\right)}^{3}" assert latex(SingularityFunction(x, 0, 4)**3) == \ r"{\left({\langle x \rangle}^{4}\right)}^{3}" assert latex(SingularityFunction(x, a, n)**3) == \ r"{\left({\langle - a + x \rangle}^{n}\right)}^{3}" assert latex(SingularityFunction(x, 4, -2)**3) == \ r"{\left({\langle x - 4 \rangle}^{-2}\right)}^{3}" assert latex((SingularityFunction(x, 4, -1)**3)**3) == \ r"{\left({\langle x - 4 \rangle}^{-1}\right)}^{9}" def test_latex_cycle(): assert latex(Cycle(1, 2, 4)) == r"\left( 1\; 2\; 4\right)" assert latex(Cycle(1, 2)(4, 5, 6)) == \ r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)" assert latex(Cycle()) == r"\left( \right)" def test_latex_permutation(): assert latex(Permutation(1, 2, 4)) == r"\left( 1\; 2\; 4\right)" assert latex(Permutation(1, 2)(4, 5, 6)) == \ r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)" assert latex(Permutation()) == r"\left( \right)" assert latex(Permutation(2, 4)*Permutation(5)) == \ r"\left( 2\; 4\right)\left( 5\right)" assert latex(Permutation(5)) == r"\left( 5\right)" assert latex(Permutation(0, 1), perm_cyclic=False) == \ r"\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}" assert latex(Permutation(0, 1)(2, 3), perm_cyclic=False) == \ r"\begin{pmatrix} 0 & 1 & 2 & 3 \\ 1 & 0 & 3 & 2 \end{pmatrix}" assert latex(Permutation(), perm_cyclic=False) == \ r"\left( \right)" with warns_deprecated_sympy(): old_print_cyclic = Permutation.print_cyclic Permutation.print_cyclic = False assert latex(Permutation(0, 1)(2, 3)) == \ r"\begin{pmatrix} 0 & 1 & 2 & 3 \\ 1 & 0 & 3 & 2 \end{pmatrix}" Permutation.print_cyclic = old_print_cyclic def test_latex_Float(): assert latex(Float(1.0e100)) == r"1.0 \cdot 10^{100}" assert latex(Float(1.0e-100)) == r"1.0 \cdot 10^{-100}" assert latex(Float(1.0e-100), mul_symbol="times") == \ r"1.0 \times 10^{-100}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=2) == \ r"1.0 \cdot 10^{4}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=4) == \ r"1.0 \cdot 10^{4}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=5) == \ r"10000.0" assert latex(Float('0.099999'), full_prec=True, min=-2, max=5) == \ r"9.99990000000000 \cdot 10^{-2}" def test_latex_vector_expressions(): A = CoordSys3D('A') assert latex(Cross(A.i, A.j*A.x*3+A.k)) == \ r"\mathbf{\hat{i}_{A}} \times \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)" assert latex(Cross(A.i, A.j)) == \ r"\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}" assert latex(x*Cross(A.i, A.j)) == \ r"x \left(\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}\right)" assert latex(Cross(x*A.i, A.j)) == \ r'- \mathbf{\hat{j}_{A}} \times \left(\left(x\right)\mathbf{\hat{i}_{A}}\right)' assert latex(Curl(3*A.x*A.j)) == \ r"\nabla\times \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)" assert latex(Curl(3*A.x*A.j+A.i)) == \ r"\nabla\times \left(\mathbf{\hat{i}_{A}} + \left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)" assert latex(Curl(3*x*A.x*A.j)) == \ r"\nabla\times \left(\left(3 \mathbf{{x}_{A}} x\right)\mathbf{\hat{j}_{A}}\right)" assert latex(x*Curl(3*A.x*A.j)) == \ r"x \left(\nabla\times \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)\right)" assert latex(Divergence(3*A.x*A.j+A.i)) == \ r"\nabla\cdot \left(\mathbf{\hat{i}_{A}} + \left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)" assert latex(Divergence(3*A.x*A.j)) == \ r"\nabla\cdot \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)" assert latex(x*Divergence(3*A.x*A.j)) == \ r"x \left(\nabla\cdot \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)\right)" assert latex(Dot(A.i, A.j*A.x*3+A.k)) == \ r"\mathbf{\hat{i}_{A}} \cdot \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)" assert latex(Dot(A.i, A.j)) == \ r"\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}" assert latex(Dot(x*A.i, A.j)) == \ r"\mathbf{\hat{j}_{A}} \cdot \left(\left(x\right)\mathbf{\hat{i}_{A}}\right)" assert latex(x*Dot(A.i, A.j)) == \ r"x \left(\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}\right)" assert latex(Gradient(A.x)) == r"\nabla \mathbf{{x}_{A}}" assert latex(Gradient(A.x + 3*A.y)) == \ r"\nabla \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)" assert latex(x*Gradient(A.x)) == r"x \left(\nabla \mathbf{{x}_{A}}\right)" assert latex(Gradient(x*A.x)) == r"\nabla \left(\mathbf{{x}_{A}} x\right)" assert latex(Laplacian(A.x)) == r"\Delta \mathbf{{x}_{A}}" assert latex(Laplacian(A.x + 3*A.y)) == \ r"\Delta \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)" assert latex(x*Laplacian(A.x)) == r"x \left(\Delta \mathbf{{x}_{A}}\right)" assert latex(Laplacian(x*A.x)) == r"\Delta \left(\mathbf{{x}_{A}} x\right)" def test_latex_symbols(): Gamma, lmbda, rho = symbols('Gamma, lambda, rho') tau, Tau, TAU, taU = symbols('tau, Tau, TAU, taU') assert latex(tau) == r"\tau" assert latex(Tau) == r"\mathrm{T}" assert latex(TAU) == r"\tau" assert latex(taU) == r"\tau" # Check that all capitalized greek letters are handled explicitly capitalized_letters = {l.capitalize() for l in greek_letters_set} assert len(capitalized_letters - set(tex_greek_dictionary.keys())) == 0 assert latex(Gamma + lmbda) == r"\Gamma + \lambda" assert latex(Gamma * lmbda) == r"\Gamma \lambda" assert latex(Symbol('q1')) == r"q_{1}" assert latex(Symbol('q21')) == r"q_{21}" assert latex(Symbol('epsilon0')) == r"\epsilon_{0}" assert latex(Symbol('omega1')) == r"\omega_{1}" assert latex(Symbol('91')) == r"91" assert latex(Symbol('alpha_new')) == r"\alpha_{new}" assert latex(Symbol('C^orig')) == r"C^{orig}" assert latex(Symbol('x^alpha')) == r"x^{\alpha}" assert latex(Symbol('beta^alpha')) == r"\beta^{\alpha}" assert latex(Symbol('e^Alpha')) == r"e^{\mathrm{A}}" assert latex(Symbol('omega_alpha^beta')) == r"\omega^{\beta}_{\alpha}" assert latex(Symbol('omega') ** Symbol('beta')) == r"\omega^{\beta}" @XFAIL def test_latex_symbols_failing(): rho, mass, volume = symbols('rho, mass, volume') assert latex( volume * rho == mass) == r"\rho \mathrm{volume} = \mathrm{mass}" assert latex(volume / mass * rho == 1) == \ r"\rho \mathrm{volume} {\mathrm{mass}}^{(-1)} = 1" assert latex(mass**3 * volume**3) == \ r"{\mathrm{mass}}^{3} \cdot {\mathrm{volume}}^{3}" @_both_exp_pow def test_latex_functions(): assert latex(exp(x)) == r"e^{x}" assert latex(exp(1) + exp(2)) == r"e + e^{2}" f = Function('f') assert latex(f(x)) == r'f{\left(x \right)}' assert latex(f) == r'f' g = Function('g') assert latex(g(x, y)) == r'g{\left(x,y \right)}' assert latex(g) == r'g' h = Function('h') assert latex(h(x, y, z)) == r'h{\left(x,y,z \right)}' assert latex(h) == r'h' Li = Function('Li') assert latex(Li) == r'\operatorname{Li}' assert latex(Li(x)) == r'\operatorname{Li}{\left(x \right)}' mybeta = Function('beta') # not to be confused with the beta function assert latex(mybeta(x, y, z)) == r"\beta{\left(x,y,z \right)}" assert latex(beta(x, y)) == r'\operatorname{B}\left(x, y\right)' assert latex(beta(x, evaluate=False)) == r'\operatorname{B}\left(x, x\right)' assert latex(beta(x, y)**2) == r'\operatorname{B}^{2}\left(x, y\right)' assert latex(mybeta(x)) == r"\beta{\left(x \right)}" assert latex(mybeta) == r"\beta" g = Function('gamma') # not to be confused with the gamma function assert latex(g(x, y, z)) == r"\gamma{\left(x,y,z \right)}" assert latex(g(x)) == r"\gamma{\left(x \right)}" assert latex(g) == r"\gamma" a_1 = Function('a_1') assert latex(a_1) == r"a_{1}" assert latex(a_1(x)) == r"a_{1}{\left(x \right)}" assert latex(Function('a_1')) == r"a_{1}" # Issue #16925 # multi letter function names # > simple assert latex(Function('ab')) == r"\operatorname{ab}" assert latex(Function('ab1')) == r"\operatorname{ab}_{1}" assert latex(Function('ab12')) == r"\operatorname{ab}_{12}" assert latex(Function('ab_1')) == r"\operatorname{ab}_{1}" assert latex(Function('ab_12')) == r"\operatorname{ab}_{12}" assert latex(Function('ab_c')) == r"\operatorname{ab}_{c}" assert latex(Function('ab_cd')) == r"\operatorname{ab}_{cd}" # > with argument assert latex(Function('ab')(Symbol('x'))) == r"\operatorname{ab}{\left(x \right)}" assert latex(Function('ab1')(Symbol('x'))) == r"\operatorname{ab}_{1}{\left(x \right)}" assert latex(Function('ab12')(Symbol('x'))) == r"\operatorname{ab}_{12}{\left(x \right)}" assert latex(Function('ab_1')(Symbol('x'))) == r"\operatorname{ab}_{1}{\left(x \right)}" assert latex(Function('ab_c')(Symbol('x'))) == r"\operatorname{ab}_{c}{\left(x \right)}" assert latex(Function('ab_cd')(Symbol('x'))) == r"\operatorname{ab}_{cd}{\left(x \right)}" # > with power # does not work on functions without brackets # > with argument and power combined assert latex(Function('ab')()**2) == r"\operatorname{ab}^{2}{\left( \right)}" assert latex(Function('ab1')()**2) == r"\operatorname{ab}_{1}^{2}{\left( \right)}" assert latex(Function('ab12')()**2) == r"\operatorname{ab}_{12}^{2}{\left( \right)}" assert latex(Function('ab_1')()**2) == r"\operatorname{ab}_{1}^{2}{\left( \right)}" assert latex(Function('ab_12')()**2) == r"\operatorname{ab}_{12}^{2}{\left( \right)}" assert latex(Function('ab')(Symbol('x'))**2) == r"\operatorname{ab}^{2}{\left(x \right)}" assert latex(Function('ab1')(Symbol('x'))**2) == r"\operatorname{ab}_{1}^{2}{\left(x \right)}" assert latex(Function('ab12')(Symbol('x'))**2) == r"\operatorname{ab}_{12}^{2}{\left(x \right)}" assert latex(Function('ab_1')(Symbol('x'))**2) == r"\operatorname{ab}_{1}^{2}{\left(x \right)}" assert latex(Function('ab_12')(Symbol('x'))**2) == \ r"\operatorname{ab}_{12}^{2}{\left(x \right)}" # single letter function names # > simple assert latex(Function('a')) == r"a" assert latex(Function('a1')) == r"a_{1}" assert latex(Function('a12')) == r"a_{12}" assert latex(Function('a_1')) == r"a_{1}" assert latex(Function('a_12')) == r"a_{12}" # > with argument assert latex(Function('a')()) == r"a{\left( \right)}" assert latex(Function('a1')()) == r"a_{1}{\left( \right)}" assert latex(Function('a12')()) == r"a_{12}{\left( \right)}" assert latex(Function('a_1')()) == r"a_{1}{\left( \right)}" assert latex(Function('a_12')()) == r"a_{12}{\left( \right)}" # > with power # does not work on functions without brackets # > with argument and power combined assert latex(Function('a')()**2) == r"a^{2}{\left( \right)}" assert latex(Function('a1')()**2) == r"a_{1}^{2}{\left( \right)}" assert latex(Function('a12')()**2) == r"a_{12}^{2}{\left( \right)}" assert latex(Function('a_1')()**2) == r"a_{1}^{2}{\left( \right)}" assert latex(Function('a_12')()**2) == r"a_{12}^{2}{\left( \right)}" assert latex(Function('a')(Symbol('x'))**2) == r"a^{2}{\left(x \right)}" assert latex(Function('a1')(Symbol('x'))**2) == r"a_{1}^{2}{\left(x \right)}" assert latex(Function('a12')(Symbol('x'))**2) == r"a_{12}^{2}{\left(x \right)}" assert latex(Function('a_1')(Symbol('x'))**2) == r"a_{1}^{2}{\left(x \right)}" assert latex(Function('a_12')(Symbol('x'))**2) == r"a_{12}^{2}{\left(x \right)}" assert latex(Function('a')()**32) == r"a^{32}{\left( \right)}" assert latex(Function('a1')()**32) == r"a_{1}^{32}{\left( \right)}" assert latex(Function('a12')()**32) == r"a_{12}^{32}{\left( \right)}" assert latex(Function('a_1')()**32) == r"a_{1}^{32}{\left( \right)}" assert latex(Function('a_12')()**32) == r"a_{12}^{32}{\left( \right)}" assert latex(Function('a')(Symbol('x'))**32) == r"a^{32}{\left(x \right)}" assert latex(Function('a1')(Symbol('x'))**32) == r"a_{1}^{32}{\left(x \right)}" assert latex(Function('a12')(Symbol('x'))**32) == r"a_{12}^{32}{\left(x \right)}" assert latex(Function('a_1')(Symbol('x'))**32) == r"a_{1}^{32}{\left(x \right)}" assert latex(Function('a_12')(Symbol('x'))**32) == r"a_{12}^{32}{\left(x \right)}" assert latex(Function('a')()**a) == r"a^{a}{\left( \right)}" assert latex(Function('a1')()**a) == r"a_{1}^{a}{\left( \right)}" assert latex(Function('a12')()**a) == r"a_{12}^{a}{\left( \right)}" assert latex(Function('a_1')()**a) == r"a_{1}^{a}{\left( \right)}" assert latex(Function('a_12')()**a) == r"a_{12}^{a}{\left( \right)}" assert latex(Function('a')(Symbol('x'))**a) == r"a^{a}{\left(x \right)}" assert latex(Function('a1')(Symbol('x'))**a) == r"a_{1}^{a}{\left(x \right)}" assert latex(Function('a12')(Symbol('x'))**a) == r"a_{12}^{a}{\left(x \right)}" assert latex(Function('a_1')(Symbol('x'))**a) == r"a_{1}^{a}{\left(x \right)}" assert latex(Function('a_12')(Symbol('x'))**a) == r"a_{12}^{a}{\left(x \right)}" ab = Symbol('ab') assert latex(Function('a')()**ab) == r"a^{ab}{\left( \right)}" assert latex(Function('a1')()**ab) == r"a_{1}^{ab}{\left( \right)}" assert latex(Function('a12')()**ab) == r"a_{12}^{ab}{\left( \right)}" assert latex(Function('a_1')()**ab) == r"a_{1}^{ab}{\left( \right)}" assert latex(Function('a_12')()**ab) == r"a_{12}^{ab}{\left( \right)}" assert latex(Function('a')(Symbol('x'))**ab) == r"a^{ab}{\left(x \right)}" assert latex(Function('a1')(Symbol('x'))**ab) == r"a_{1}^{ab}{\left(x \right)}" assert latex(Function('a12')(Symbol('x'))**ab) == r"a_{12}^{ab}{\left(x \right)}" assert latex(Function('a_1')(Symbol('x'))**ab) == r"a_{1}^{ab}{\left(x \right)}" assert latex(Function('a_12')(Symbol('x'))**ab) == r"a_{12}^{ab}{\left(x \right)}" assert latex(Function('a^12')(x)) == R"a^{12}{\left(x \right)}" assert latex(Function('a^12')(x) ** ab) == R"\left(a^{12}\right)^{ab}{\left(x \right)}" assert latex(Function('a__12')(x)) == R"a^{12}{\left(x \right)}" assert latex(Function('a__12')(x) ** ab) == R"\left(a^{12}\right)^{ab}{\left(x \right)}" assert latex(Function('a_1__1_2')(x)) == R"a^{1}_{1 2}{\left(x \right)}" # issue 5868 omega1 = Function('omega1') assert latex(omega1) == r"\omega_{1}" assert latex(omega1(x)) == r"\omega_{1}{\left(x \right)}" assert latex(sin(x)) == r"\sin{\left(x \right)}" assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}" assert latex(sin(2*x**2), fold_func_brackets=True) == \ r"\sin {2 x^{2}}" assert latex(sin(x**2), fold_func_brackets=True) == \ r"\sin {x^{2}}" assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left(x \right)}" assert latex(asin(x)**2, inv_trig_style="full") == \ r"\arcsin^{2}{\left(x \right)}" assert latex(asin(x)**2, inv_trig_style="power") == \ r"\sin^{-1}{\left(x \right)}^{2}" assert latex(asin(x**2), inv_trig_style="power", fold_func_brackets=True) == \ r"\sin^{-1} {x^{2}}" assert latex(acsc(x), inv_trig_style="full") == \ r"\operatorname{arccsc}{\left(x \right)}" assert latex(asinh(x), inv_trig_style="full") == \ r"\operatorname{arsinh}{\left(x \right)}" assert latex(factorial(k)) == r"k!" assert latex(factorial(-k)) == r"\left(- k\right)!" assert latex(factorial(k)**2) == r"k!^{2}" assert latex(subfactorial(k)) == r"!k" assert latex(subfactorial(-k)) == r"!\left(- k\right)" assert latex(subfactorial(k)**2) == r"\left(!k\right)^{2}" assert latex(factorial2(k)) == r"k!!" assert latex(factorial2(-k)) == r"\left(- k\right)!!" assert latex(factorial2(k)**2) == r"k!!^{2}" assert latex(binomial(2, k)) == r"{\binom{2}{k}}" assert latex(binomial(2, k)**2) == r"{\binom{2}{k}}^{2}" assert latex(FallingFactorial(3, k)) == r"{\left(3\right)}_{k}" assert latex(RisingFactorial(3, k)) == r"{3}^{\left(k\right)}" assert latex(floor(x)) == r"\left\lfloor{x}\right\rfloor" assert latex(ceiling(x)) == r"\left\lceil{x}\right\rceil" assert latex(frac(x)) == r"\operatorname{frac}{\left(x\right)}" assert latex(floor(x)**2) == r"\left\lfloor{x}\right\rfloor^{2}" assert latex(ceiling(x)**2) == r"\left\lceil{x}\right\rceil^{2}" assert latex(frac(x)**2) == r"\operatorname{frac}{\left(x\right)}^{2}" assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)" assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}" assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)" assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}" assert latex(Abs(x)) == r"\left|{x}\right|" assert latex(Abs(x)**2) == r"\left|{x}\right|^{2}" assert latex(re(x)) == r"\operatorname{re}{\left(x\right)}" assert latex(re(x + y)) == \ r"\operatorname{re}{\left(x\right)} + \operatorname{re}{\left(y\right)}" assert latex(im(x)) == r"\operatorname{im}{\left(x\right)}" assert latex(conjugate(x)) == r"\overline{x}" assert latex(conjugate(x)**2) == r"\overline{x}^{2}" assert latex(conjugate(x**2)) == r"\overline{x}^{2}" assert latex(gamma(x)) == r"\Gamma\left(x\right)" w = Wild('w') assert latex(gamma(w)) == r"\Gamma\left(w\right)" assert latex(Order(x)) == r"O\left(x\right)" assert latex(Order(x, x)) == r"O\left(x\right)" assert latex(Order(x, (x, 0))) == r"O\left(x\right)" assert latex(Order(x, (x, oo))) == r"O\left(x; x\rightarrow \infty\right)" assert latex(Order(x - y, (x, y))) == \ r"O\left(x - y; x\rightarrow y\right)" assert latex(Order(x, x, y)) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)" assert latex(Order(x, x, y)) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)" assert latex(Order(x, (x, oo), (y, oo))) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( \infty, \ \infty\right)\right)" assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)' assert latex(lowergamma(x, y)**2) == r'\gamma^{2}\left(x, y\right)' assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)' assert latex(uppergamma(x, y)**2) == r'\Gamma^{2}\left(x, y\right)' assert latex(cot(x)) == r'\cot{\left(x \right)}' assert latex(coth(x)) == r'\coth{\left(x \right)}' assert latex(re(x)) == r'\operatorname{re}{\left(x\right)}' assert latex(im(x)) == r'\operatorname{im}{\left(x\right)}' assert latex(root(x, y)) == r'x^{\frac{1}{y}}' assert latex(arg(x)) == r'\arg{\left(x \right)}' assert latex(zeta(x)) == r"\zeta\left(x\right)" assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)" assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)" assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)" assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)" assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)" assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)" assert latex( polylog(x, y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)" assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)" assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)" assert latex(stieltjes(x)) == r"\gamma_{x}" assert latex(stieltjes(x)**2) == r"\gamma_{x}^{2}" assert latex(stieltjes(x, y)) == r"\gamma_{x}\left(y\right)" assert latex(stieltjes(x, y)**2) == r"\gamma_{x}\left(y\right)^{2}" assert latex(elliptic_k(z)) == r"K\left(z\right)" assert latex(elliptic_k(z)**2) == r"K^{2}\left(z\right)" assert latex(elliptic_f(x, y)) == r"F\left(x\middle| y\right)" assert latex(elliptic_f(x, y)**2) == r"F^{2}\left(x\middle| y\right)" assert latex(elliptic_e(x, y)) == r"E\left(x\middle| y\right)" assert latex(elliptic_e(x, y)**2) == r"E^{2}\left(x\middle| y\right)" assert latex(elliptic_e(z)) == r"E\left(z\right)" assert latex(elliptic_e(z)**2) == r"E^{2}\left(z\right)" assert latex(elliptic_pi(x, y, z)) == r"\Pi\left(x; y\middle| z\right)" assert latex(elliptic_pi(x, y, z)**2) == \ r"\Pi^{2}\left(x; y\middle| z\right)" assert latex(elliptic_pi(x, y)) == r"\Pi\left(x\middle| y\right)" assert latex(elliptic_pi(x, y)**2) == r"\Pi^{2}\left(x\middle| y\right)" assert latex(Ei(x)) == r'\operatorname{Ei}{\left(x \right)}' assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left(x \right)}' assert latex(expint(x, y)) == r'\operatorname{E}_{x}\left(y\right)' assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)' assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left(x \right)}' assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left(x \right)}' assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left(x \right)}' assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}\left(x\right)' assert latex(Chi(x)) == r'\operatorname{Chi}\left(x\right)' assert latex(jacobi(n, a, b, x)) == \ r'P_{n}^{\left(a,b\right)}\left(x\right)' assert latex(jacobi(n, a, b, x)**2) == \ r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}' assert latex(gegenbauer(n, a, x)) == \ r'C_{n}^{\left(a\right)}\left(x\right)' assert latex(gegenbauer(n, a, x)**2) == \ r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)' assert latex(chebyshevt(n, x)**2) == \ r'\left(T_{n}\left(x\right)\right)^{2}' assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)' assert latex(chebyshevu(n, x)**2) == \ r'\left(U_{n}\left(x\right)\right)^{2}' assert latex(legendre(n, x)) == r'P_{n}\left(x\right)' assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}' assert latex(assoc_legendre(n, a, x)) == \ r'P_{n}^{\left(a\right)}\left(x\right)' assert latex(assoc_legendre(n, a, x)**2) == \ r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)' assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}' assert latex(assoc_laguerre(n, a, x)) == \ r'L_{n}^{\left(a\right)}\left(x\right)' assert latex(assoc_laguerre(n, a, x)**2) == \ r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(hermite(n, x)) == r'H_{n}\left(x\right)' assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}' theta = Symbol("theta", real=True) phi = Symbol("phi", real=True) assert latex(Ynm(n, m, theta, phi)) == r'Y_{n}^{m}\left(\theta,\phi\right)' assert latex(Ynm(n, m, theta, phi)**3) == \ r'\left(Y_{n}^{m}\left(\theta,\phi\right)\right)^{3}' assert latex(Znm(n, m, theta, phi)) == r'Z_{n}^{m}\left(\theta,\phi\right)' assert latex(Znm(n, m, theta, phi)**3) == \ r'\left(Z_{n}^{m}\left(\theta,\phi\right)\right)^{3}' # Test latex printing of function names with "_" assert latex(polar_lift(0)) == \ r"\operatorname{polar\_lift}{\left(0 \right)}" assert latex(polar_lift(0)**3) == \ r"\operatorname{polar\_lift}^{3}{\left(0 \right)}" assert latex(totient(n)) == r'\phi\left(n\right)' assert latex(totient(n) ** 2) == r'\left(\phi\left(n\right)\right)^{2}' assert latex(reduced_totient(n)) == r'\lambda\left(n\right)' assert latex(reduced_totient(n) ** 2) == \ r'\left(\lambda\left(n\right)\right)^{2}' assert latex(divisor_sigma(x)) == r"\sigma\left(x\right)" assert latex(divisor_sigma(x)**2) == r"\sigma^{2}\left(x\right)" assert latex(divisor_sigma(x, y)) == r"\sigma_y\left(x\right)" assert latex(divisor_sigma(x, y)**2) == r"\sigma^{2}_y\left(x\right)" assert latex(udivisor_sigma(x)) == r"\sigma^*\left(x\right)" assert latex(udivisor_sigma(x)**2) == r"\sigma^*^{2}\left(x\right)" assert latex(udivisor_sigma(x, y)) == r"\sigma^*_y\left(x\right)" assert latex(udivisor_sigma(x, y)**2) == r"\sigma^*^{2}_y\left(x\right)" assert latex(primenu(n)) == r'\nu\left(n\right)' assert latex(primenu(n) ** 2) == r'\left(\nu\left(n\right)\right)^{2}' assert latex(primeomega(n)) == r'\Omega\left(n\right)' assert latex(primeomega(n) ** 2) == \ r'\left(\Omega\left(n\right)\right)^{2}' assert latex(LambertW(n)) == r'W\left(n\right)' assert latex(LambertW(n, -1)) == r'W_{-1}\left(n\right)' assert latex(LambertW(n, k)) == r'W_{k}\left(n\right)' assert latex(LambertW(n) * LambertW(n)) == r"W^{2}\left(n\right)" assert latex(Pow(LambertW(n), 2)) == r"W^{2}\left(n\right)" assert latex(LambertW(n)**k) == r"W^{k}\left(n\right)" assert latex(LambertW(n, k)**p) == r"W^{p}_{k}\left(n\right)" assert latex(Mod(x, 7)) == r'x \bmod 7' assert latex(Mod(x + 1, 7)) == r'\left(x + 1\right) \bmod 7' assert latex(Mod(7, x + 1)) == r'7 \bmod \left(x + 1\right)' assert latex(Mod(2 * x, 7)) == r'2 x \bmod 7' assert latex(Mod(7, 2 * x)) == r'7 \bmod 2 x' assert latex(Mod(x, 7) + 1) == r'\left(x \bmod 7\right) + 1' assert latex(2 * Mod(x, 7)) == r'2 \left(x \bmod 7\right)' assert latex(Mod(7, 2 * x)**n) == r'\left(7 \bmod 2 x\right)^{n}' # some unknown function name should get rendered with \operatorname fjlkd = Function('fjlkd') assert latex(fjlkd(x)) == r'\operatorname{fjlkd}{\left(x \right)}' # even when it is referred to without an argument assert latex(fjlkd) == r'\operatorname{fjlkd}' # test that notation passes to subclasses of the same name only def test_function_subclass_different_name(): class mygamma(gamma): pass assert latex(mygamma) == r"\operatorname{mygamma}" assert latex(mygamma(x)) == r"\operatorname{mygamma}{\left(x \right)}" def test_hyper_printing(): from sympy.abc import x, z assert latex(meijerg(Tuple(pi, pi, x), Tuple(1), (0, 1), Tuple(1, 2, 3/pi), z)) == \ r'{G_{4, 5}^{2, 3}\left(\begin{matrix} \pi, \pi, x & 1 \\0, 1 & 1, 2, '\ r'\frac{3}{\pi} \end{matrix} \middle| {z} \right)}' assert latex(meijerg(Tuple(), Tuple(1), (0,), Tuple(), z)) == \ r'{G_{1, 1}^{1, 0}\left(\begin{matrix} & 1 \\0 & \end{matrix} \middle| {z} \right)}' assert latex(hyper((x, 2), (3,), z)) == \ r'{{}_{2}F_{1}\left(\begin{matrix} x, 2 ' \ r'\\ 3 \end{matrix}\middle| {z} \right)}' assert latex(hyper(Tuple(), Tuple(1), z)) == \ r'{{}_{0}F_{1}\left(\begin{matrix} ' \ r'\\ 1 \end{matrix}\middle| {z} \right)}' def test_latex_bessel(): from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn, hn1, hn2) from sympy.abc import z assert latex(besselj(n, z**2)**k) == r'J^{k}_{n}\left(z^{2}\right)' assert latex(bessely(n, z)) == r'Y_{n}\left(z\right)' assert latex(besseli(n, z)) == r'I_{n}\left(z\right)' assert latex(besselk(n, z)) == r'K_{n}\left(z\right)' assert latex(hankel1(n, z**2)**2) == \ r'\left(H^{(1)}_{n}\left(z^{2}\right)\right)^{2}' assert latex(hankel2(n, z)) == r'H^{(2)}_{n}\left(z\right)' assert latex(jn(n, z)) == r'j_{n}\left(z\right)' assert latex(yn(n, z)) == r'y_{n}\left(z\right)' assert latex(hn1(n, z)) == r'h^{(1)}_{n}\left(z\right)' assert latex(hn2(n, z)) == r'h^{(2)}_{n}\left(z\right)' def test_latex_fresnel(): from sympy.functions.special.error_functions import (fresnels, fresnelc) from sympy.abc import z assert latex(fresnels(z)) == r'S\left(z\right)' assert latex(fresnelc(z)) == r'C\left(z\right)' assert latex(fresnels(z)**2) == r'S^{2}\left(z\right)' assert latex(fresnelc(z)**2) == r'C^{2}\left(z\right)' def test_latex_brackets(): assert latex((-1)**x) == r"\left(-1\right)^{x}" def test_latex_indexed(): Psi_symbol = Symbol('Psi_0', complex=True, real=False) Psi_indexed = IndexedBase(Symbol('Psi', complex=True, real=False)) symbol_latex = latex(Psi_symbol * conjugate(Psi_symbol)) indexed_latex = latex(Psi_indexed[0] * conjugate(Psi_indexed[0])) # \\overline{{\\Psi}_{0}} {\\Psi}_{0} vs. \\Psi_{0} \\overline{\\Psi_{0}} assert symbol_latex == r'\Psi_{0} \overline{\Psi_{0}}' assert indexed_latex == r'\overline{{\Psi}_{0}} {\Psi}_{0}' # Symbol('gamma') gives r'\gamma' interval = '\\mathrel{..}\\nobreak ' assert latex(Indexed('x1', Symbol('i'))) == r'{x_{1}}_{i}' assert latex(Indexed('x2', Idx('i'))) == r'{x_{2}}_{i}' assert latex(Indexed('x3', Idx('i', Symbol('N')))) == r'{x_{3}}_{{i}_{0'+interval+'N - 1}}' assert latex(Indexed('x3', Idx('i', Symbol('N')+1))) == r'{x_{3}}_{{i}_{0'+interval+'N}}' assert latex(Indexed('x4', Idx('i', (Symbol('a'),Symbol('b'))))) == r'{x_{4}}_{{i}_{a'+interval+'b}}' assert latex(IndexedBase('gamma')) == r'\gamma' assert latex(IndexedBase('a b')) == r'a b' assert latex(IndexedBase('a_b')) == r'a_{b}' def test_latex_derivatives(): # regular "d" for ordinary derivatives assert latex(diff(x**3, x, evaluate=False)) == \ r"\frac{d}{d x} x^{3}" assert latex(diff(sin(x) + x**2, x, evaluate=False)) == \ r"\frac{d}{d x} \left(x^{2} + \sin{\left(x \right)}\right)" assert latex(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False))\ == \ r"\frac{d^{2}}{d x^{2}} \left(x^{2} + \sin{\left(x \right)}\right)" assert latex(diff(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False), evaluate=False)) == \ r"\frac{d^{3}}{d x^{3}} \left(x^{2} + \sin{\left(x \right)}\right)" # \partial for partial derivatives assert latex(diff(sin(x * y), x, evaluate=False)) == \ r"\frac{\partial}{\partial x} \sin{\left(x y \right)}" assert latex(diff(sin(x * y) + x**2, x, evaluate=False)) == \ r"\frac{\partial}{\partial x} \left(x^{2} + \sin{\left(x y \right)}\right)" assert latex(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False)) == \ r"\frac{\partial^{2}}{\partial x^{2}} \left(x^{2} + \sin{\left(x y \right)}\right)" assert latex(diff(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False), x, evaluate=False)) == \ r"\frac{\partial^{3}}{\partial x^{3}} \left(x^{2} + \sin{\left(x y \right)}\right)" # mixed partial derivatives f = Function("f") assert latex(diff(diff(f(x, y), x, evaluate=False), y, evaluate=False)) == \ r"\frac{\partial^{2}}{\partial y\partial x} " + latex(f(x, y)) assert latex(diff(diff(diff(f(x, y), x, evaluate=False), x, evaluate=False), y, evaluate=False)) == \ r"\frac{\partial^{3}}{\partial y\partial x^{2}} " + latex(f(x, y)) # for negative nested Derivative assert latex(diff(-diff(y**2,x,evaluate=False),x,evaluate=False)) == r'\frac{d}{d x} \left(- \frac{d}{d x} y^{2}\right)' assert latex(diff(diff(-diff(diff(y,x,evaluate=False),x,evaluate=False),x,evaluate=False),x,evaluate=False)) == \ r'\frac{d^{2}}{d x^{2}} \left(- \frac{d^{2}}{d x^{2}} y\right)' # use ordinary d when one of the variables has been integrated out assert latex(diff(Integral(exp(-x*y), (x, 0, oo)), y, evaluate=False)) == \ r"\frac{d}{d y} \int\limits_{0}^{\infty} e^{- x y}\, dx" # Derivative wrapped in power: assert latex(diff(x, x, evaluate=False)**2) == \ r"\left(\frac{d}{d x} x\right)^{2}" assert latex(diff(f(x), x)**2) == \ r"\left(\frac{d}{d x} f{\left(x \right)}\right)^{2}" assert latex(diff(f(x), (x, n))) == \ r"\frac{d^{n}}{d x^{n}} f{\left(x \right)}" x1 = Symbol('x1') x2 = Symbol('x2') assert latex(diff(f(x1, x2), x1)) == r'\frac{\partial}{\partial x_{1}} f{\left(x_{1},x_{2} \right)}' n1 = Symbol('n1') assert latex(diff(f(x), (x, n1))) == r'\frac{d^{n_{1}}}{d x^{n_{1}}} f{\left(x \right)}' n2 = Symbol('n2') assert latex(diff(f(x), (x, Max(n1, n2)))) == \ r'\frac{d^{\max\left(n_{1}, n_{2}\right)}}{d x^{\max\left(n_{1}, n_{2}\right)}} f{\left(x \right)}' # set diff operator assert latex(diff(f(x), x), diff_operator="rd") == r'\frac{\mathrm{d}}{\mathrm{d} x} f{\left(x \right)}' def test_latex_subs(): assert latex(Subs(x*y, (x, y), (1, 2))) == r'\left. x y \right|_{\substack{ x=1\\ y=2 }}' def test_latex_integrals(): assert latex(Integral(log(x), x)) == r"\int \log{\left(x \right)}\, dx" assert latex(Integral(x**2, (x, 0, 1))) == \ r"\int\limits_{0}^{1} x^{2}\, dx" assert latex(Integral(x**2, (x, 10, 20))) == \ r"\int\limits_{10}^{20} x^{2}\, dx" assert latex(Integral(y*x**2, (x, 0, 1), y)) == \ r"\int\int\limits_{0}^{1} x^{2} y\, dx\, dy" assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*') == \ r"\begin{equation*}\int\int\limits_{0}^{1} x^{2} y\, dx\, dy\end{equation*}" assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*', itex=True) \ == r"$$\int\int_{0}^{1} x^{2} y\, dx\, dy$$" assert latex(Integral(x, (x, 0))) == r"\int\limits^{0} x\, dx" assert latex(Integral(x*y, x, y)) == r"\iint x y\, dx\, dy" assert latex(Integral(x*y*z, x, y, z)) == r"\iiint x y z\, dx\, dy\, dz" assert latex(Integral(x*y*z*t, x, y, z, t)) == \ r"\iiiint t x y z\, dx\, dy\, dz\, dt" assert latex(Integral(x, x, x, x, x, x, x)) == \ r"\int\int\int\int\int\int x\, dx\, dx\, dx\, dx\, dx\, dx" assert latex(Integral(x, x, y, (z, 0, 1))) == \ r"\int\limits_{0}^{1}\int\int x\, dx\, dy\, dz" # for negative nested Integral assert latex(Integral(-Integral(y**2,x),x)) == \ r'\int \left(- \int y^{2}\, dx\right)\, dx' assert latex(Integral(-Integral(-Integral(y,x),x),x)) == \ r'\int \left(- \int \left(- \int y\, dx\right)\, dx\right)\, dx' # fix issue #10806 assert latex(Integral(z, z)**2) == r"\left(\int z\, dz\right)^{2}" assert latex(Integral(x + z, z)) == r"\int \left(x + z\right)\, dz" assert latex(Integral(x+z/2, z)) == \ r"\int \left(x + \frac{z}{2}\right)\, dz" assert latex(Integral(x**y, z)) == r"\int x^{y}\, dz" # set diff operator assert latex(Integral(x, x), diff_operator="rd") == r'\int x\, \mathrm{d}x' assert latex(Integral(x, (x, 0, 1)), diff_operator="rd") == r'\int\limits_{0}^{1} x\, \mathrm{d}x' def test_latex_sets(): for s in (frozenset, set): assert latex(s([x*y, x**2])) == r"\left\{x^{2}, x y\right\}" assert latex(s(range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}" assert latex(s(range(1, 13))) == \ r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}" s = FiniteSet assert latex(s(*[x*y, x**2])) == r"\left\{x^{2}, x y\right\}" assert latex(s(*range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}" assert latex(s(*range(1, 13))) == \ r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}" def test_latex_SetExpr(): iv = Interval(1, 3) se = SetExpr(iv) assert latex(se) == r"SetExpr\left(\left[1, 3\right]\right)" def test_latex_Range(): assert latex(Range(1, 51)) == r'\left\{1, 2, \ldots, 50\right\}' assert latex(Range(1, 4)) == r'\left\{1, 2, 3\right\}' assert latex(Range(0, 3, 1)) == r'\left\{0, 1, 2\right\}' assert latex(Range(0, 30, 1)) == r'\left\{0, 1, \ldots, 29\right\}' assert latex(Range(30, 1, -1)) == r'\left\{30, 29, \ldots, 2\right\}' assert latex(Range(0, oo, 2)) == r'\left\{0, 2, \ldots\right\}' assert latex(Range(oo, -2, -2)) == r'\left\{\ldots, 2, 0\right\}' assert latex(Range(-2, -oo, -1)) == r'\left\{-2, -3, \ldots\right\}' assert latex(Range(-oo, oo)) == r'\left\{\ldots, -1, 0, 1, \ldots\right\}' assert latex(Range(oo, -oo, -1)) == r'\left\{\ldots, 1, 0, -1, \ldots\right\}' a, b, c = symbols('a:c') assert latex(Range(a, b, c)) == r'\text{Range}\left(a, b, c\right)' assert latex(Range(a, 10, 1)) == r'\text{Range}\left(a, 10\right)' assert latex(Range(0, b, 1)) == r'\text{Range}\left(b\right)' assert latex(Range(0, 10, c)) == r'\text{Range}\left(0, 10, c\right)' i = Symbol('i', integer=True) n = Symbol('n', negative=True, integer=True) p = Symbol('p', positive=True, integer=True) assert latex(Range(i, i + 3)) == r'\left\{i, i + 1, i + 2\right\}' assert latex(Range(-oo, n, 2)) == r'\left\{\ldots, n - 4, n - 2\right\}' assert latex(Range(p, oo)) == r'\left\{p, p + 1, \ldots\right\}' # The following will work if __iter__ is improved # assert latex(Range(-3, p + 7)) == r'\left\{-3, -2, \ldots, p + 6\right\}' # Must have integer assumptions assert latex(Range(a, a + 3)) == r'\text{Range}\left(a, a + 3\right)' def test_latex_sequences(): s1 = SeqFormula(a**2, (0, oo)) s2 = SeqPer((1, 2)) latex_str = r'\left[0, 1, 4, 9, \ldots\right]' assert latex(s1) == latex_str latex_str = r'\left[1, 2, 1, 2, \ldots\right]' assert latex(s2) == latex_str s3 = SeqFormula(a**2, (0, 2)) s4 = SeqPer((1, 2), (0, 2)) latex_str = r'\left[0, 1, 4\right]' assert latex(s3) == latex_str latex_str = r'\left[1, 2, 1\right]' assert latex(s4) == latex_str s5 = SeqFormula(a**2, (-oo, 0)) s6 = SeqPer((1, 2), (-oo, 0)) latex_str = r'\left[\ldots, 9, 4, 1, 0\right]' assert latex(s5) == latex_str latex_str = r'\left[\ldots, 2, 1, 2, 1\right]' assert latex(s6) == latex_str latex_str = r'\left[1, 3, 5, 11, \ldots\right]' assert latex(SeqAdd(s1, s2)) == latex_str latex_str = r'\left[1, 3, 5\right]' assert latex(SeqAdd(s3, s4)) == latex_str latex_str = r'\left[\ldots, 11, 5, 3, 1\right]' assert latex(SeqAdd(s5, s6)) == latex_str latex_str = r'\left[0, 2, 4, 18, \ldots\right]' assert latex(SeqMul(s1, s2)) == latex_str latex_str = r'\left[0, 2, 4\right]' assert latex(SeqMul(s3, s4)) == latex_str latex_str = r'\left[\ldots, 18, 4, 2, 0\right]' assert latex(SeqMul(s5, s6)) == latex_str # Sequences with symbolic limits, issue 12629 s7 = SeqFormula(a**2, (a, 0, x)) latex_str = r'\left\{a^{2}\right\}_{a=0}^{x}' assert latex(s7) == latex_str b = Symbol('b') s8 = SeqFormula(b*a**2, (a, 0, 2)) latex_str = r'\left[0, b, 4 b\right]' assert latex(s8) == latex_str def test_latex_FourierSeries(): latex_str = \ r'2 \sin{\left(x \right)} - \sin{\left(2 x \right)} + \frac{2 \sin{\left(3 x \right)}}{3} + \ldots' assert latex(fourier_series(x, (x, -pi, pi))) == latex_str def test_latex_FormalPowerSeries(): latex_str = r'\sum_{k=1}^{\infty} - \frac{\left(-1\right)^{- k} x^{k}}{k}' assert latex(fps(log(1 + x))) == latex_str def test_latex_intervals(): a = Symbol('a', real=True) assert latex(Interval(0, 0)) == r"\left\{0\right\}" assert latex(Interval(0, a)) == r"\left[0, a\right]" assert latex(Interval(0, a, False, False)) == r"\left[0, a\right]" assert latex(Interval(0, a, True, False)) == r"\left(0, a\right]" assert latex(Interval(0, a, False, True)) == r"\left[0, a\right)" assert latex(Interval(0, a, True, True)) == r"\left(0, a\right)" def test_latex_AccumuBounds(): a = Symbol('a', real=True) assert latex(AccumBounds(0, 1)) == r"\left\langle 0, 1\right\rangle" assert latex(AccumBounds(0, a)) == r"\left\langle 0, a\right\rangle" assert latex(AccumBounds(a + 1, a + 2)) == \ r"\left\langle a + 1, a + 2\right\rangle" def test_latex_emptyset(): assert latex(S.EmptySet) == r"\emptyset" def test_latex_universalset(): assert latex(S.UniversalSet) == r"\mathbb{U}" def test_latex_commutator(): A = Operator('A') B = Operator('B') comm = Commutator(B, A) assert latex(comm.doit()) == r"- (A B - B A)" def test_latex_union(): assert latex(Union(Interval(0, 1), Interval(2, 3))) == \ r"\left[0, 1\right] \cup \left[2, 3\right]" assert latex(Union(Interval(1, 1), Interval(2, 2), Interval(3, 4))) == \ r"\left\{1, 2\right\} \cup \left[3, 4\right]" def test_latex_intersection(): assert latex(Intersection(Interval(0, 1), Interval(x, y))) == \ r"\left[0, 1\right] \cap \left[x, y\right]" def test_latex_symmetric_difference(): assert latex(SymmetricDifference(Interval(2, 5), Interval(4, 7), evaluate=False)) == \ r'\left[2, 5\right] \triangle \left[4, 7\right]' def test_latex_Complement(): assert latex(Complement(S.Reals, S.Naturals)) == \ r"\mathbb{R} \setminus \mathbb{N}" def test_latex_productset(): line = Interval(0, 1) bigline = Interval(0, 10) fset = FiniteSet(1, 2, 3) assert latex(line**2) == r"%s^{2}" % latex(line) assert latex(line**10) == r"%s^{10}" % latex(line) assert latex((line * bigline * fset).flatten()) == r"%s \times %s \times %s" % ( latex(line), latex(bigline), latex(fset)) def test_latex_powerset(): fset = FiniteSet(1, 2, 3) assert latex(PowerSet(fset)) == r'\mathcal{P}\left(\left\{1, 2, 3\right\}\right)' def test_latex_ordinals(): w = OrdinalOmega() assert latex(w) == r"\omega" wp = OmegaPower(2, 3) assert latex(wp) == r'3 \omega^{2}' assert latex(Ordinal(wp, OmegaPower(1, 1))) == r'3 \omega^{2} + \omega' assert latex(Ordinal(OmegaPower(2, 1), OmegaPower(1, 2))) == r'\omega^{2} + 2 \omega' def test_set_operators_parenthesis(): a, b, c, d = symbols('a:d') A = FiniteSet(a) B = FiniteSet(b) C = FiniteSet(c) D = FiniteSet(d) U1 = Union(A, B, evaluate=False) U2 = Union(C, D, evaluate=False) I1 = Intersection(A, B, evaluate=False) I2 = Intersection(C, D, evaluate=False) C1 = Complement(A, B, evaluate=False) C2 = Complement(C, D, evaluate=False) D1 = SymmetricDifference(A, B, evaluate=False) D2 = SymmetricDifference(C, D, evaluate=False) # XXX ProductSet does not support evaluate keyword P1 = ProductSet(A, B) P2 = ProductSet(C, D) assert latex(Intersection(A, U2, evaluate=False)) == \ r'\left\{a\right\} \cap ' \ r'\left(\left\{c\right\} \cup \left\{d\right\}\right)' assert latex(Intersection(U1, U2, evaluate=False)) == \ r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \ r'\cap \left(\left\{c\right\} \cup \left\{d\right\}\right)' assert latex(Intersection(C1, C2, evaluate=False)) == \ r'\left(\left\{a\right\} \setminus ' \ r'\left\{b\right\}\right) \cap \left(\left\{c\right\} ' \ r'\setminus \left\{d\right\}\right)' assert latex(Intersection(D1, D2, evaluate=False)) == \ r'\left(\left\{a\right\} \triangle ' \ r'\left\{b\right\}\right) \cap \left(\left\{c\right\} ' \ r'\triangle \left\{d\right\}\right)' assert latex(Intersection(P1, P2, evaluate=False)) == \ r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \ r'\cap \left(\left\{c\right\} \times ' \ r'\left\{d\right\}\right)' assert latex(Union(A, I2, evaluate=False)) == \ r'\left\{a\right\} \cup ' \ r'\left(\left\{c\right\} \cap \left\{d\right\}\right)' assert latex(Union(I1, I2, evaluate=False)) == \ r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \ r'\cup \left(\left\{c\right\} \cap \left\{d\right\}\right)' assert latex(Union(C1, C2, evaluate=False)) == \ r'\left(\left\{a\right\} \setminus ' \ r'\left\{b\right\}\right) \cup \left(\left\{c\right\} ' \ r'\setminus \left\{d\right\}\right)' assert latex(Union(D1, D2, evaluate=False)) == \ r'\left(\left\{a\right\} \triangle ' \ r'\left\{b\right\}\right) \cup \left(\left\{c\right\} ' \ r'\triangle \left\{d\right\}\right)' assert latex(Union(P1, P2, evaluate=False)) == \ r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \ r'\cup \left(\left\{c\right\} \times ' \ r'\left\{d\right\}\right)' assert latex(Complement(A, C2, evaluate=False)) == \ r'\left\{a\right\} \setminus \left(\left\{c\right\} ' \ r'\setminus \left\{d\right\}\right)' assert latex(Complement(U1, U2, evaluate=False)) == \ r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \ r'\setminus \left(\left\{c\right\} \cup ' \ r'\left\{d\right\}\right)' assert latex(Complement(I1, I2, evaluate=False)) == \ r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \ r'\setminus \left(\left\{c\right\} \cap ' \ r'\left\{d\right\}\right)' assert latex(Complement(D1, D2, evaluate=False)) == \ r'\left(\left\{a\right\} \triangle ' \ r'\left\{b\right\}\right) \setminus ' \ r'\left(\left\{c\right\} \triangle \left\{d\right\}\right)' assert latex(Complement(P1, P2, evaluate=False)) == \ r'\left(\left\{a\right\} \times \left\{b\right\}\right) '\ r'\setminus \left(\left\{c\right\} \times '\ r'\left\{d\right\}\right)' assert latex(SymmetricDifference(A, D2, evaluate=False)) == \ r'\left\{a\right\} \triangle \left(\left\{c\right\} ' \ r'\triangle \left\{d\right\}\right)' assert latex(SymmetricDifference(U1, U2, evaluate=False)) == \ r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \ r'\triangle \left(\left\{c\right\} \cup ' \ r'\left\{d\right\}\right)' assert latex(SymmetricDifference(I1, I2, evaluate=False)) == \ r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \ r'\triangle \left(\left\{c\right\} \cap ' \ r'\left\{d\right\}\right)' assert latex(SymmetricDifference(C1, C2, evaluate=False)) == \ r'\left(\left\{a\right\} \setminus ' \ r'\left\{b\right\}\right) \triangle ' \ r'\left(\left\{c\right\} \setminus \left\{d\right\}\right)' assert latex(SymmetricDifference(P1, P2, evaluate=False)) == \ r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \ r'\triangle \left(\left\{c\right\} \times ' \ r'\left\{d\right\}\right)' # XXX This can be incorrect since cartesian product is not associative assert latex(ProductSet(A, P2).flatten()) == \ r'\left\{a\right\} \times \left\{c\right\} \times ' \ r'\left\{d\right\}' assert latex(ProductSet(U1, U2)) == \ r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \ r'\times \left(\left\{c\right\} \cup ' \ r'\left\{d\right\}\right)' assert latex(ProductSet(I1, I2)) == \ r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \ r'\times \left(\left\{c\right\} \cap ' \ r'\left\{d\right\}\right)' assert latex(ProductSet(C1, C2)) == \ r'\left(\left\{a\right\} \setminus ' \ r'\left\{b\right\}\right) \times \left(\left\{c\right\} ' \ r'\setminus \left\{d\right\}\right)' assert latex(ProductSet(D1, D2)) == \ r'\left(\left\{a\right\} \triangle ' \ r'\left\{b\right\}\right) \times \left(\left\{c\right\} ' \ r'\triangle \left\{d\right\}\right)' def test_latex_Complexes(): assert latex(S.Complexes) == r"\mathbb{C}" def test_latex_Naturals(): assert latex(S.Naturals) == r"\mathbb{N}" def test_latex_Naturals0(): assert latex(S.Naturals0) == r"\mathbb{N}_0" def test_latex_Integers(): assert latex(S.Integers) == r"\mathbb{Z}" def test_latex_ImageSet(): x = Symbol('x') assert latex(ImageSet(Lambda(x, x**2), S.Naturals)) == \ r"\left\{x^{2}\; \middle|\; x \in \mathbb{N}\right\}" y = Symbol('y') imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4}) assert latex(imgset) == \ r"\left\{x + y\; \middle|\; x \in \left\{1, 2, 3\right\}, y \in \left\{3, 4\right\}\right\}" imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4})) assert latex(imgset) == \ r"\left\{x + y\; \middle|\; \left( x, \ y\right) \in \left\{1, 2, 3\right\} \times \left\{3, 4\right\}\right\}" def test_latex_ConditionSet(): x = Symbol('x') assert latex(ConditionSet(x, Eq(x**2, 1), S.Reals)) == \ r"\left\{x\; \middle|\; x \in \mathbb{R} \wedge x^{2} = 1 \right\}" assert latex(ConditionSet(x, Eq(x**2, 1), S.UniversalSet)) == \ r"\left\{x\; \middle|\; x^{2} = 1 \right\}" def test_latex_ComplexRegion(): assert latex(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == \ r"\left\{x + y i\; \middle|\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}" assert latex(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \ r"\left\{r \left(i \sin{\left(\theta \right)} + \cos{\left(\theta "\ r"\right)}\right)\; \middle|\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}" def test_latex_Contains(): x = Symbol('x') assert latex(Contains(x, S.Naturals)) == r"x \in \mathbb{N}" def test_latex_sum(): assert latex(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \ r"\sum_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}" assert latex(Sum(x**2, (x, -2, 2))) == \ r"\sum_{x=-2}^{2} x^{2}" assert latex(Sum(x**2 + y, (x, -2, 2))) == \ r"\sum_{x=-2}^{2} \left(x^{2} + y\right)" assert latex(Sum(x**2 + y, (x, -2, 2))**2) == \ r"\left(\sum_{x=-2}^{2} \left(x^{2} + y\right)\right)^{2}" def test_latex_product(): assert latex(Product(x*y**2, (x, -2, 2), (y, -5, 5))) == \ r"\prod_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}" assert latex(Product(x**2, (x, -2, 2))) == \ r"\prod_{x=-2}^{2} x^{2}" assert latex(Product(x**2 + y, (x, -2, 2))) == \ r"\prod_{x=-2}^{2} \left(x^{2} + y\right)" assert latex(Product(x, (x, -2, 2))**2) == \ r"\left(\prod_{x=-2}^{2} x\right)^{2}" def test_latex_limits(): assert latex(Limit(x, x, oo)) == r"\lim_{x \to \infty} x" # issue 8175 f = Function('f') assert latex(Limit(f(x), x, 0)) == r"\lim_{x \to 0^+} f{\left(x \right)}" assert latex(Limit(f(x), x, 0, "-")) == \ r"\lim_{x \to 0^-} f{\left(x \right)}" # issue #10806 assert latex(Limit(f(x), x, 0)**2) == \ r"\left(\lim_{x \to 0^+} f{\left(x \right)}\right)^{2}" # bi-directional limit assert latex(Limit(f(x), x, 0, dir='+-')) == \ r"\lim_{x \to 0} f{\left(x \right)}" def test_latex_log(): assert latex(log(x)) == r"\log{\left(x \right)}" assert latex(log(x), ln_notation=True) == r"\ln{\left(x \right)}" assert latex(log(x) + log(y)) == \ r"\log{\left(x \right)} + \log{\left(y \right)}" assert latex(log(x) + log(y), ln_notation=True) == \ r"\ln{\left(x \right)} + \ln{\left(y \right)}" assert latex(pow(log(x), x)) == r"\log{\left(x \right)}^{x}" assert latex(pow(log(x), x), ln_notation=True) == \ r"\ln{\left(x \right)}^{x}" def test_issue_3568(): beta = Symbol(r'\beta') y = beta + x assert latex(y) in [r'\beta + x', r'x + \beta'] beta = Symbol(r'beta') y = beta + x assert latex(y) in [r'\beta + x', r'x + \beta'] def test_latex(): assert latex((2*tau)**Rational(7, 2)) == r"8 \sqrt{2} \tau^{\frac{7}{2}}" assert latex((2*mu)**Rational(7, 2), mode='equation*') == \ r"\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}" assert latex((2*mu)**Rational(7, 2), mode='equation', itex=True) == \ r"$$8 \sqrt{2} \mu^{\frac{7}{2}}$$" assert latex([2/x, y]) == r"\left[ \frac{2}{x}, \ y\right]" def test_latex_dict(): d = {Rational(1): 1, x**2: 2, x: 3, x**3: 4} assert latex(d) == \ r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}' D = Dict(d) assert latex(D) == \ r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}' def test_latex_list(): ll = [Symbol('omega1'), Symbol('a'), Symbol('alpha')] assert latex(ll) == r'\left[ \omega_{1}, \ a, \ \alpha\right]' def test_latex_NumberSymbols(): assert latex(S.Catalan) == "G" assert latex(S.EulerGamma) == r"\gamma" assert latex(S.Exp1) == "e" assert latex(S.GoldenRatio) == r"\phi" assert latex(S.Pi) == r"\pi" assert latex(S.TribonacciConstant) == r"\text{TribonacciConstant}" def test_latex_rational(): # tests issue 3973 assert latex(-Rational(1, 2)) == r"- \frac{1}{2}" assert latex(Rational(-1, 2)) == r"- \frac{1}{2}" assert latex(Rational(1, -2)) == r"- \frac{1}{2}" assert latex(-Rational(-1, 2)) == r"\frac{1}{2}" assert latex(-Rational(1, 2)*x) == r"- \frac{x}{2}" assert latex(-Rational(1, 2)*x + Rational(-2, 3)*y) == \ r"- \frac{x}{2} - \frac{2 y}{3}" def test_latex_inverse(): # tests issue 4129 assert latex(1/x) == r"\frac{1}{x}" assert latex(1/(x + y)) == r"\frac{1}{x + y}" def test_latex_DiracDelta(): assert latex(DiracDelta(x)) == r"\delta\left(x\right)" assert latex(DiracDelta(x)**2) == r"\left(\delta\left(x\right)\right)^{2}" assert latex(DiracDelta(x, 0)) == r"\delta\left(x\right)" assert latex(DiracDelta(x, 5)) == \ r"\delta^{\left( 5 \right)}\left( x \right)" assert latex(DiracDelta(x, 5)**2) == \ r"\left(\delta^{\left( 5 \right)}\left( x \right)\right)^{2}" def test_latex_Heaviside(): assert latex(Heaviside(x)) == r"\theta\left(x\right)" assert latex(Heaviside(x)**2) == r"\left(\theta\left(x\right)\right)^{2}" def test_latex_KroneckerDelta(): assert latex(KroneckerDelta(x, y)) == r"\delta_{x y}" assert latex(KroneckerDelta(x, y + 1)) == r"\delta_{x, y + 1}" # issue 6578 assert latex(KroneckerDelta(x + 1, y)) == r"\delta_{y, x + 1}" assert latex(Pow(KroneckerDelta(x, y), 2, evaluate=False)) == \ r"\left(\delta_{x y}\right)^{2}" def test_latex_LeviCivita(): assert latex(LeviCivita(x, y, z)) == r"\varepsilon_{x y z}" assert latex(LeviCivita(x, y, z)**2) == \ r"\left(\varepsilon_{x y z}\right)^{2}" assert latex(LeviCivita(x, y, z + 1)) == r"\varepsilon_{x, y, z + 1}" assert latex(LeviCivita(x, y + 1, z)) == r"\varepsilon_{x, y + 1, z}" assert latex(LeviCivita(x + 1, y, z)) == r"\varepsilon_{x + 1, y, z}" def test_mode(): expr = x + y assert latex(expr) == r'x + y' assert latex(expr, mode='plain') == r'x + y' assert latex(expr, mode='inline') == r'$x + y$' assert latex( expr, mode='equation*') == r'\begin{equation*}x + y\end{equation*}' assert latex( expr, mode='equation') == r'\begin{equation}x + y\end{equation}' raises(ValueError, lambda: latex(expr, mode='foo')) def test_latex_mathieu(): assert latex(mathieuc(x, y, z)) == r"C\left(x, y, z\right)" assert latex(mathieus(x, y, z)) == r"S\left(x, y, z\right)" assert latex(mathieuc(x, y, z)**2) == r"C\left(x, y, z\right)^{2}" assert latex(mathieus(x, y, z)**2) == r"S\left(x, y, z\right)^{2}" assert latex(mathieucprime(x, y, z)) == r"C^{\prime}\left(x, y, z\right)" assert latex(mathieusprime(x, y, z)) == r"S^{\prime}\left(x, y, z\right)" assert latex(mathieucprime(x, y, z)**2) == r"C^{\prime}\left(x, y, z\right)^{2}" assert latex(mathieusprime(x, y, z)**2) == r"S^{\prime}\left(x, y, z\right)^{2}" def test_latex_Piecewise(): p = Piecewise((x, x < 1), (x**2, True)) assert latex(p) == r"\begin{cases} x & \text{for}\: x < 1 \\x^{2} &" \ r" \text{otherwise} \end{cases}" assert latex(p, itex=True) == \ r"\begin{cases} x & \text{for}\: x \lt 1 \\x^{2} &" \ r" \text{otherwise} \end{cases}" p = Piecewise((x, x < 0), (0, x >= 0)) assert latex(p) == r'\begin{cases} x & \text{for}\: x < 0 \\0 &' \ r' \text{otherwise} \end{cases}' A, B = symbols("A B", commutative=False) p = Piecewise((A**2, Eq(A, B)), (A*B, True)) s = r"\begin{cases} A^{2} & \text{for}\: A = B \\A B & \text{otherwise} \end{cases}" assert latex(p) == s assert latex(A*p) == r"A \left(%s\right)" % s assert latex(p*A) == r"\left(%s\right) A" % s assert latex(Piecewise((x, x < 1), (x**2, x < 2))) == \ r'\begin{cases} x & ' \ r'\text{for}\: x < 1 \\x^{2} & \text{for}\: x < 2 \end{cases}' def test_latex_Matrix(): M = Matrix([[1 + x, y], [y, x - 1]]) assert latex(M) == \ r'\left[\begin{matrix}x + 1 & y\\y & x - 1\end{matrix}\right]' assert latex(M, mode='inline') == \ r'$\left[\begin{smallmatrix}x + 1 & y\\' \ r'y & x - 1\end{smallmatrix}\right]$' assert latex(M, mat_str='array') == \ r'\left[\begin{array}{cc}x + 1 & y\\y & x - 1\end{array}\right]' assert latex(M, mat_str='bmatrix') == \ r'\left[\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}\right]' assert latex(M, mat_delim=None, mat_str='bmatrix') == \ r'\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}' M2 = Matrix(1, 11, range(11)) assert latex(M2) == \ r'\left[\begin{array}{ccccccccccc}' \ r'0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\end{array}\right]' def test_latex_matrix_with_functions(): t = symbols('t') theta1 = symbols('theta1', cls=Function) M = Matrix([[sin(theta1(t)), cos(theta1(t))], [cos(theta1(t).diff(t)), sin(theta1(t).diff(t))]]) expected = (r'\left[\begin{matrix}\sin{\left(' r'\theta_{1}{\left(t \right)} \right)} & ' r'\cos{\left(\theta_{1}{\left(t \right)} \right)' r'}\\\cos{\left(\frac{d}{d t} \theta_{1}{\left(t ' r'\right)} \right)} & \sin{\left(\frac{d}{d t} ' r'\theta_{1}{\left(t \right)} \right' r')}\end{matrix}\right]') assert latex(M) == expected def test_latex_NDimArray(): x, y, z, w = symbols("x y z w") for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray): # Basic: scalar array M = ArrayType(x) assert latex(M) == r"x" M = ArrayType([[1 / x, y], [z, w]]) M1 = ArrayType([1 / x, y, z]) M2 = tensorproduct(M1, M) M3 = tensorproduct(M, M) assert latex(M) == \ r'\left[\begin{matrix}\frac{1}{x} & y\\z & w\end{matrix}\right]' assert latex(M1) == \ r"\left[\begin{matrix}\frac{1}{x} & y & z\end{matrix}\right]" assert latex(M2) == \ r"\left[\begin{matrix}" \ r"\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & " \ r"\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right] & " \ r"\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right]" \ r"\end{matrix}\right]" assert latex(M3) == \ r"""\left[\begin{matrix}"""\ r"""\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & """\ r"""\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right]\\"""\ r"""\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right] & """\ r"""\left[\begin{matrix}\frac{w}{x} & w y\\w z & w^{2}\end{matrix}\right]"""\ r"""\end{matrix}\right]""" Mrow = ArrayType([[x, y, 1/z]]) Mcolumn = ArrayType([[x], [y], [1/z]]) Mcol2 = ArrayType([Mcolumn.tolist()]) assert latex(Mrow) == \ r"\left[\left[\begin{matrix}x & y & \frac{1}{z}\end{matrix}\right]\right]" assert latex(Mcolumn) == \ r"\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]" assert latex(Mcol2) == \ r'\left[\begin{matrix}\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]\end{matrix}\right]' def test_latex_mul_symbol(): assert latex(4*4**x, mul_symbol='times') == r"4 \times 4^{x}" assert latex(4*4**x, mul_symbol='dot') == r"4 \cdot 4^{x}" assert latex(4*4**x, mul_symbol='ldot') == r"4 \,.\, 4^{x}" assert latex(4*x, mul_symbol='times') == r"4 \times x" assert latex(4*x, mul_symbol='dot') == r"4 \cdot x" assert latex(4*x, mul_symbol='ldot') == r"4 \,.\, x" def test_latex_issue_4381(): y = 4*4**log(2) assert latex(y) == r'4 \cdot 4^{\log{\left(2 \right)}}' assert latex(1/y) == r'\frac{1}{4 \cdot 4^{\log{\left(2 \right)}}}' def test_latex_issue_4576(): assert latex(Symbol("beta_13_2")) == r"\beta_{13 2}" assert latex(Symbol("beta_132_20")) == r"\beta_{132 20}" assert latex(Symbol("beta_13")) == r"\beta_{13}" assert latex(Symbol("x_a_b")) == r"x_{a b}" assert latex(Symbol("x_1_2_3")) == r"x_{1 2 3}" assert latex(Symbol("x_a_b1")) == r"x_{a b1}" assert latex(Symbol("x_a_1")) == r"x_{a 1}" assert latex(Symbol("x_1_a")) == r"x_{1 a}" assert latex(Symbol("x_1^aa")) == r"x^{aa}_{1}" assert latex(Symbol("x_1__aa")) == r"x^{aa}_{1}" assert latex(Symbol("x_11^a")) == r"x^{a}_{11}" assert latex(Symbol("x_11__a")) == r"x^{a}_{11}" assert latex(Symbol("x_a_a_a_a")) == r"x_{a a a a}" assert latex(Symbol("x_a_a^a^a")) == r"x^{a a}_{a a}" assert latex(Symbol("x_a_a__a__a")) == r"x^{a a}_{a a}" assert latex(Symbol("alpha_11")) == r"\alpha_{11}" assert latex(Symbol("alpha_11_11")) == r"\alpha_{11 11}" assert latex(Symbol("alpha_alpha")) == r"\alpha_{\alpha}" assert latex(Symbol("alpha^aleph")) == r"\alpha^{\aleph}" assert latex(Symbol("alpha__aleph")) == r"\alpha^{\aleph}" def test_latex_pow_fraction(): x = Symbol('x') # Testing exp assert r'e^{-x}' in latex(exp(-x)/2).replace(' ', '') # Remove Whitespace # Testing e^{-x} in case future changes alter behavior of muls or fracs # In particular current output is \frac{1}{2}e^{- x} but perhaps this will # change to \frac{e^{-x}}{2} # Testing general, non-exp, power assert r'3^{-x}' in latex(3**-x/2).replace(' ', '') def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) assert latex(A*B*C**-1) == r"A B C^{-1}" assert latex(C**-1*A*B) == r"C^{-1} A B" assert latex(A*C**-1*B) == r"A C^{-1} B" def test_latex_order(): expr = x**3 + x**2*y + y**4 + 3*x*y**3 assert latex(expr, order='lex') == r"x^{3} + x^{2} y + 3 x y^{3} + y^{4}" assert latex( expr, order='rev-lex') == r"y^{4} + 3 x y^{3} + x^{2} y + x^{3}" assert latex(expr, order='none') == r"x^{3} + y^{4} + y x^{2} + 3 x y^{3}" def test_latex_Lambda(): assert latex(Lambda(x, x + 1)) == r"\left( x \mapsto x + 1 \right)" assert latex(Lambda((x, y), x + 1)) == r"\left( \left( x, \ y\right) \mapsto x + 1 \right)" assert latex(Lambda(x, x)) == r"\left( x \mapsto x \right)" def test_latex_PolyElement(): Ruv, u, v = ring("u,v", ZZ) Rxyz, x, y, z = ring("x,y,z", Ruv) assert latex(x - x) == r"0" assert latex(x - 1) == r"x - 1" assert latex(x + 1) == r"x + 1" assert latex((u**2 + 3*u*v + 1)*x**2*y + u + 1) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + u + 1" assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x" assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x + 1" assert latex((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == \ r"-\left({u}^{2} - 3 u v + 1\right) {x}^{2} y - \left(u + 1\right) x - 1" assert latex(-(v**2 + v + 1)*x + 3*u*v + 1) == \ r"-\left({v}^{2} + v + 1\right) x + 3 u v + 1" assert latex(-(v**2 + v + 1)*x - 3*u*v + 1) == \ r"-\left({v}^{2} + v + 1\right) x - 3 u v + 1" def test_latex_FracElement(): Fuv, u, v = field("u,v", ZZ) Fxyzt, x, y, z, t = field("x,y,z,t", Fuv) assert latex(x - x) == r"0" assert latex(x - 1) == r"x - 1" assert latex(x + 1) == r"x + 1" assert latex(x/3) == r"\frac{x}{3}" assert latex(x/z) == r"\frac{x}{z}" assert latex(x*y/z) == r"\frac{x y}{z}" assert latex(x/(z*t)) == r"\frac{x}{z t}" assert latex(x*y/(z*t)) == r"\frac{x y}{z t}" assert latex((x - 1)/y) == r"\frac{x - 1}{y}" assert latex((x + 1)/y) == r"\frac{x + 1}{y}" assert latex((-x - 1)/y) == r"\frac{-x - 1}{y}" assert latex((x + 1)/(y*z)) == r"\frac{x + 1}{y z}" assert latex(-y/(x + 1)) == r"\frac{-y}{x + 1}" assert latex(y*z/(x + 1)) == r"\frac{y z}{x + 1}" assert latex(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == \ r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - 1}" assert latex(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == \ r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - u v t - 1}" def test_latex_Poly(): assert latex(Poly(x**2 + 2 * x, x)) == \ r"\operatorname{Poly}{\left( x^{2} + 2 x, x, domain=\mathbb{Z} \right)}" assert latex(Poly(x/y, x)) == \ r"\operatorname{Poly}{\left( \frac{1}{y} x, x, domain=\mathbb{Z}\left(y\right) \right)}" assert latex(Poly(2.0*x + y)) == \ r"\operatorname{Poly}{\left( 2.0 x + 1.0 y, x, y, domain=\mathbb{R} \right)}" def test_latex_Poly_order(): assert latex(Poly([a, 1, b, 2, c, 3], x)) == \ r'\operatorname{Poly}{\left( a x^{5} + x^{4} + b x^{3} + 2 x^{2} + c'\ r' x + 3, x, domain=\mathbb{Z}\left[a, b, c\right] \right)}' assert latex(Poly([a, 1, b+c, 2, 3], x)) == \ r'\operatorname{Poly}{\left( a x^{4} + x^{3} + \left(b + c\right) '\ r'x^{2} + 2 x + 3, x, domain=\mathbb{Z}\left[a, b, c\right] \right)}' assert latex(Poly(a*x**3 + x**2*y - x*y - c*y**3 - b*x*y**2 + y - a*x + b, (x, y))) == \ r'\operatorname{Poly}{\left( a x^{3} + x^{2}y - b xy^{2} - xy - '\ r'a x - c y^{3} + y + b, x, y, domain=\mathbb{Z}\left[a, b, c\right] \right)}' def test_latex_ComplexRootOf(): assert latex(rootof(x**5 + x + 3, 0)) == \ r"\operatorname{CRootOf} {\left(x^{5} + x + 3, 0\right)}" def test_latex_RootSum(): assert latex(RootSum(x**5 + x + 3, sin)) == \ r"\operatorname{RootSum} {\left(x^{5} + x + 3, \left( x \mapsto \sin{\left(x \right)} \right)\right)}" def test_settings(): raises(TypeError, lambda: latex(x*y, method="garbage")) def test_latex_numbers(): assert latex(catalan(n)) == r"C_{n}" assert latex(catalan(n)**2) == r"C_{n}^{2}" assert latex(bernoulli(n)) == r"B_{n}" assert latex(bernoulli(n, x)) == r"B_{n}\left(x\right)" assert latex(bernoulli(n)**2) == r"B_{n}^{2}" assert latex(bernoulli(n, x)**2) == r"B_{n}^{2}\left(x\right)" assert latex(genocchi(n)) == r"G_{n}" assert latex(genocchi(n, x)) == r"G_{n}\left(x\right)" assert latex(genocchi(n)**2) == r"G_{n}^{2}" assert latex(genocchi(n, x)**2) == r"G_{n}^{2}\left(x\right)" assert latex(bell(n)) == r"B_{n}" assert latex(bell(n, x)) == r"B_{n}\left(x\right)" assert latex(bell(n, m, (x, y))) == r"B_{n, m}\left(x, y\right)" assert latex(bell(n)**2) == r"B_{n}^{2}" assert latex(bell(n, x)**2) == r"B_{n}^{2}\left(x\right)" assert latex(bell(n, m, (x, y))**2) == r"B_{n, m}^{2}\left(x, y\right)" assert latex(fibonacci(n)) == r"F_{n}" assert latex(fibonacci(n, x)) == r"F_{n}\left(x\right)" assert latex(fibonacci(n)**2) == r"F_{n}^{2}" assert latex(fibonacci(n, x)**2) == r"F_{n}^{2}\left(x\right)" assert latex(lucas(n)) == r"L_{n}" assert latex(lucas(n)**2) == r"L_{n}^{2}" assert latex(tribonacci(n)) == r"T_{n}" assert latex(tribonacci(n, x)) == r"T_{n}\left(x\right)" assert latex(tribonacci(n)**2) == r"T_{n}^{2}" assert latex(tribonacci(n, x)**2) == r"T_{n}^{2}\left(x\right)" def test_latex_euler(): assert latex(euler(n)) == r"E_{n}" assert latex(euler(n, x)) == r"E_{n}\left(x\right)" assert latex(euler(n, x)**2) == r"E_{n}^{2}\left(x\right)" def test_lamda(): assert latex(Symbol('lamda')) == r"\lambda" assert latex(Symbol('Lamda')) == r"\Lambda" def test_custom_symbol_names(): x = Symbol('x') y = Symbol('y') assert latex(x) == r"x" assert latex(x, symbol_names={x: "x_i"}) == r"x_i" assert latex(x + y, symbol_names={x: "x_i"}) == r"x_i + y" assert latex(x**2, symbol_names={x: "x_i"}) == r"x_i^{2}" assert latex(x + y, symbol_names={x: "x_i", y: "y_j"}) == r"x_i + y_j" def test_matAdd(): C = MatrixSymbol('C', 5, 5) B = MatrixSymbol('B', 5, 5) n = symbols("n") h = MatrixSymbol("h", 1, 1) assert latex(C - 2*B) in [r'- 2 B + C', r'C -2 B'] assert latex(C + 2*B) in [r'2 B + C', r'C + 2 B'] assert latex(B - 2*C) in [r'B - 2 C', r'- 2 C + B'] assert latex(B + 2*C) in [r'B + 2 C', r'2 C + B'] assert latex(n * h - (-h + h.T) * (h + h.T)) == 'n h - \\left(- h + h^{T}\\right) \\left(h + h^{T}\\right)' assert latex(MatAdd(MatAdd(h, h), MatAdd(h, h))) == '\\left(h + h\\right) + \\left(h + h\\right)' assert latex(MatMul(MatMul(h, h), MatMul(h, h))) == '\\left(h h\\right) \\left(h h\\right)' def test_matMul(): A = MatrixSymbol('A', 5, 5) B = MatrixSymbol('B', 5, 5) x = Symbol('x') assert latex(2*A) == r'2 A' assert latex(2*x*A) == r'2 x A' assert latex(-2*A) == r'- 2 A' assert latex(1.5*A) == r'1.5 A' assert latex(sqrt(2)*A) == r'\sqrt{2} A' assert latex(-sqrt(2)*A) == r'- \sqrt{2} A' assert latex(2*sqrt(2)*x*A) == r'2 \sqrt{2} x A' assert latex(-2*A*(A + 2*B)) in [r'- 2 A \left(A + 2 B\right)', r'- 2 A \left(2 B + A\right)'] def test_latex_MatrixSlice(): n = Symbol('n', integer=True) x, y, z, w, t, = symbols('x y z w t') X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', 10, 10) Z = MatrixSymbol('Z', 10, 10) assert latex(MatrixSlice(X, (None, None, None), (None, None, None))) == r'X\left[:, :\right]' assert latex(X[x:x + 1, y:y + 1]) == r'X\left[x:x + 1, y:y + 1\right]' assert latex(X[x:x + 1:2, y:y + 1:2]) == r'X\left[x:x + 1:2, y:y + 1:2\right]' assert latex(X[:x, y:]) == r'X\left[:x, y:\right]' assert latex(X[:x, y:]) == r'X\left[:x, y:\right]' assert latex(X[x:, :y]) == r'X\left[x:, :y\right]' assert latex(X[x:y, z:w]) == r'X\left[x:y, z:w\right]' assert latex(X[x:y:t, w:t:x]) == r'X\left[x:y:t, w:t:x\right]' assert latex(X[x::y, t::w]) == r'X\left[x::y, t::w\right]' assert latex(X[:x:y, :t:w]) == r'X\left[:x:y, :t:w\right]' assert latex(X[::x, ::y]) == r'X\left[::x, ::y\right]' assert latex(MatrixSlice(X, (0, None, None), (0, None, None))) == r'X\left[:, :\right]' assert latex(MatrixSlice(X, (None, n, None), (None, n, None))) == r'X\left[:, :\right]' assert latex(MatrixSlice(X, (0, n, None), (0, n, None))) == r'X\left[:, :\right]' assert latex(MatrixSlice(X, (0, n, 2), (0, n, 2))) == r'X\left[::2, ::2\right]' assert latex(X[1:2:3, 4:5:6]) == r'X\left[1:2:3, 4:5:6\right]' assert latex(X[1:3:5, 4:6:8]) == r'X\left[1:3:5, 4:6:8\right]' assert latex(X[1:10:2]) == r'X\left[1:10:2, :\right]' assert latex(Y[:5, 1:9:2]) == r'Y\left[:5, 1:9:2\right]' assert latex(Y[:5, 1:10:2]) == r'Y\left[:5, 1::2\right]' assert latex(Y[5, :5:2]) == r'Y\left[5:6, :5:2\right]' assert latex(X[0:1, 0:1]) == r'X\left[:1, :1\right]' assert latex(X[0:1:2, 0:1:2]) == r'X\left[:1:2, :1:2\right]' assert latex((Y + Z)[2:, 2:]) == r'\left(Y + Z\right)\left[2:, 2:\right]' def test_latex_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where from sympy.stats.rv import RandomDomain X = Normal('x1', 0, 1) assert latex(where(X > 0)) == r"\text{Domain: }0 < x_{1} \wedge x_{1} < \infty" D = Die('d1', 6) assert latex(where(D > 4)) == r"\text{Domain: }d_{1} = 5 \vee d_{1} = 6" A = Exponential('a', 1) B = Exponential('b', 1) assert latex( pspace(Tuple(A, B)).domain) == \ r"\text{Domain: }0 \leq a \wedge 0 \leq b \wedge a < \infty \wedge b < \infty" assert latex(RandomDomain(FiniteSet(x), FiniteSet(1, 2))) == \ r'\text{Domain: }\left\{x\right\} \in \left\{1, 2\right\}' def test_PrettyPoly(): from sympy.polys.domains import QQ F = QQ.frac_field(x, y) R = QQ[x, y] assert latex(F.convert(x/(x + y))) == latex(x/(x + y)) assert latex(R.convert(x + y)) == latex(x + y) def test_integral_transforms(): x = Symbol("x") k = Symbol("k") f = Function("f") a = Symbol("a") b = Symbol("b") assert latex(MellinTransform(f(x), x, k)) == \ r"\mathcal{M}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseMellinTransform(f(k), k, x, a, b)) == \ r"\mathcal{M}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(LaplaceTransform(f(x), x, k)) == \ r"\mathcal{L}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseLaplaceTransform(f(k), k, x, (a, b))) == \ r"\mathcal{L}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(FourierTransform(f(x), x, k)) == \ r"\mathcal{F}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseFourierTransform(f(k), k, x)) == \ r"\mathcal{F}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(CosineTransform(f(x), x, k)) == \ r"\mathcal{COS}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseCosineTransform(f(k), k, x)) == \ r"\mathcal{COS}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(SineTransform(f(x), x, k)) == \ r"\mathcal{SIN}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseSineTransform(f(k), k, x)) == \ r"\mathcal{SIN}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" def test_PolynomialRingBase(): from sympy.polys.domains import QQ assert latex(QQ.old_poly_ring(x, y)) == r"\mathbb{Q}\left[x, y\right]" assert latex(QQ.old_poly_ring(x, y, order="ilex")) == \ r"S_<^{-1}\mathbb{Q}\left[x, y\right]" def test_categories(): from sympy.categories import (Object, IdentityMorphism, NamedMorphism, Category, Diagram, DiagramGrid) A1 = Object("A1") A2 = Object("A2") A3 = Object("A3") f1 = NamedMorphism(A1, A2, "f1") f2 = NamedMorphism(A2, A3, "f2") id_A1 = IdentityMorphism(A1) K1 = Category("K1") assert latex(A1) == r"A_{1}" assert latex(f1) == r"f_{1}:A_{1}\rightarrow A_{2}" assert latex(id_A1) == r"id:A_{1}\rightarrow A_{1}" assert latex(f2*f1) == r"f_{2}\circ f_{1}:A_{1}\rightarrow A_{3}" assert latex(K1) == r"\mathbf{K_{1}}" d = Diagram() assert latex(d) == r"\emptyset" d = Diagram({f1: "unique", f2: S.EmptySet}) assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \ r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \ r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \ r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}, " \ r"\ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"}) assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \ r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \ r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \ r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}," \ r" \ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" \ r"\Longrightarrow \left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \left\{unique\right\}\right\}" # A linear diagram. A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") d = Diagram([f, g]) grid = DiagramGrid(d) assert latex(grid) == r"\begin{array}{cc}" + "\n" \ r"A & B \\" + "\n" \ r" & C " + "\n" \ r"\end{array}" + "\n" def test_Modules(): from sympy.polys.domains import QQ from sympy.polys.agca import homomorphism R = QQ.old_poly_ring(x, y) F = R.free_module(2) M = F.submodule([x, y], [1, x**2]) assert latex(F) == r"{\mathbb{Q}\left[x, y\right]}^{2}" assert latex(M) == \ r"\left\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle" I = R.ideal(x**2, y) assert latex(I) == r"\left\langle {x^{2}},{y} \right\rangle" Q = F / M assert latex(Q) == \ r"\frac{{\mathbb{Q}\left[x, y\right]}^{2}}{\left\langle {\left[ {x},"\ r"{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}" assert latex(Q.submodule([1, x**3/2], [2, y])) == \ r"\left\langle {{\left[ {1},{\frac{x^{3}}{2}} \right]} + {\left"\ r"\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} "\ r"\right\rangle}},{{\left[ {2},{y} \right]} + {\left\langle {\left[ "\ r"{x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}} \right\rangle" h = homomorphism(QQ.old_poly_ring(x).free_module(2), QQ.old_poly_ring(x).free_module(2), [0, 0]) assert latex(h) == \ r"{\left[\begin{matrix}0 & 0\\0 & 0\end{matrix}\right]} : "\ r"{{\mathbb{Q}\left[x\right]}^{2}} \to {{\mathbb{Q}\left[x\right]}^{2}}" def test_QuotientRing(): from sympy.polys.domains import QQ R = QQ.old_poly_ring(x)/[x**2 + 1] assert latex(R) == \ r"\frac{\mathbb{Q}\left[x\right]}{\left\langle {x^{2} + 1} \right\rangle}" assert latex(R.one) == r"{1} + {\left\langle {x^{2} + 1} \right\rangle}" def test_Tr(): #TODO: Handle indices A, B = symbols('A B', commutative=False) t = Tr(A*B) assert latex(t) == r'\operatorname{tr}\left(A B\right)' def test_Determinant(): from sympy.matrices import Determinant, Inverse, BlockMatrix, OneMatrix, ZeroMatrix m = Matrix(((1, 2), (3, 4))) assert latex(Determinant(m)) == '\\left|{\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}}\\right|' assert latex(Determinant(Inverse(m))) == \ '\\left|{\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]^{-1}}\\right|' X = MatrixSymbol('X', 2, 2) assert latex(Determinant(X)) == '\\left|{X}\\right|' assert latex(Determinant(X + m)) == \ '\\left|{\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] + X}\\right|' assert latex(Determinant(BlockMatrix(((OneMatrix(2, 2), X), (m, ZeroMatrix(2, 2)))))) == \ '\\left|{\\begin{matrix}1 & X\\\\\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] & 0\\end{matrix}}\\right|' def test_Adjoint(): from sympy.matrices import Adjoint, Inverse, Transpose X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(Adjoint(X)) == r'X^{\dagger}' assert latex(Adjoint(X + Y)) == r'\left(X + Y\right)^{\dagger}' assert latex(Adjoint(X) + Adjoint(Y)) == r'X^{\dagger} + Y^{\dagger}' assert latex(Adjoint(X*Y)) == r'\left(X Y\right)^{\dagger}' assert latex(Adjoint(Y)*Adjoint(X)) == r'Y^{\dagger} X^{\dagger}' assert latex(Adjoint(X**2)) == r'\left(X^{2}\right)^{\dagger}' assert latex(Adjoint(X)**2) == r'\left(X^{\dagger}\right)^{2}' assert latex(Adjoint(Inverse(X))) == r'\left(X^{-1}\right)^{\dagger}' assert latex(Inverse(Adjoint(X))) == r'\left(X^{\dagger}\right)^{-1}' assert latex(Adjoint(Transpose(X))) == r'\left(X^{T}\right)^{\dagger}' assert latex(Transpose(Adjoint(X))) == r'\left(X^{\dagger}\right)^{T}' assert latex(Transpose(Adjoint(X) + Y)) == r'\left(X^{\dagger} + Y\right)^{T}' m = Matrix(((1, 2), (3, 4))) assert latex(Adjoint(m)) == '\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]^{\\dagger}' assert latex(Adjoint(m+X)) == \ '\\left(\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] + X\\right)^{\\dagger}' from sympy.matrices import BlockMatrix, OneMatrix, ZeroMatrix assert latex(Adjoint(BlockMatrix(((OneMatrix(2, 2), X), (m, ZeroMatrix(2, 2)))))) == \ '\\left[\\begin{matrix}1 & X\\\\\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] & 0\\end{matrix}\\right]^{\\dagger}' # Issue 20959 Mx = MatrixSymbol('M^x', 2, 2) assert latex(Adjoint(Mx)) == r'\left(M^{x}\right)^{\dagger}' def test_Transpose(): from sympy.matrices import Transpose, MatPow, HadamardPower X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(Transpose(X)) == r'X^{T}' assert latex(Transpose(X + Y)) == r'\left(X + Y\right)^{T}' assert latex(Transpose(HadamardPower(X, 2))) == r'\left(X^{\circ {2}}\right)^{T}' assert latex(HadamardPower(Transpose(X), 2)) == r'\left(X^{T}\right)^{\circ {2}}' assert latex(Transpose(MatPow(X, 2))) == r'\left(X^{2}\right)^{T}' assert latex(MatPow(Transpose(X), 2)) == r'\left(X^{T}\right)^{2}' m = Matrix(((1, 2), (3, 4))) assert latex(Transpose(m)) == '\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]^{T}' assert latex(Transpose(m+X)) == \ '\\left(\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] + X\\right)^{T}' from sympy.matrices import BlockMatrix, OneMatrix, ZeroMatrix assert latex(Transpose(BlockMatrix(((OneMatrix(2, 2), X), (m, ZeroMatrix(2, 2)))))) == \ '\\left[\\begin{matrix}1 & X\\\\\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] & 0\\end{matrix}\\right]^{T}' # Issue 20959 Mx = MatrixSymbol('M^x', 2, 2) assert latex(Transpose(Mx)) == r'\left(M^{x}\right)^{T}' def test_Hadamard(): from sympy.matrices import HadamardProduct, HadamardPower from sympy.matrices.expressions import MatAdd, MatMul, MatPow X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(HadamardProduct(X, Y*Y)) == r'X \circ Y^{2}' assert latex(HadamardProduct(X, Y)*Y) == r'\left(X \circ Y\right) Y' assert latex(HadamardPower(X, 2)) == r'X^{\circ {2}}' assert latex(HadamardPower(X, -1)) == r'X^{\circ \left({-1}\right)}' assert latex(HadamardPower(MatAdd(X, Y), 2)) == \ r'\left(X + Y\right)^{\circ {2}}' assert latex(HadamardPower(MatMul(X, Y), 2)) == \ r'\left(X Y\right)^{\circ {2}}' assert latex(HadamardPower(MatPow(X, -1), -1)) == \ r'\left(X^{-1}\right)^{\circ \left({-1}\right)}' assert latex(MatPow(HadamardPower(X, -1), -1)) == \ r'\left(X^{\circ \left({-1}\right)}\right)^{-1}' assert latex(HadamardPower(X, n+1)) == \ r'X^{\circ \left({n + 1}\right)}' def test_MatPow(): from sympy.matrices.expressions import MatPow X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(MatPow(X, 2)) == 'X^{2}' assert latex(MatPow(X*X, 2)) == '\\left(X^{2}\\right)^{2}' assert latex(MatPow(X*Y, 2)) == '\\left(X Y\\right)^{2}' assert latex(MatPow(X + Y, 2)) == '\\left(X + Y\\right)^{2}' assert latex(MatPow(X + X, 2)) == '\\left(2 X\\right)^{2}' # Issue 20959 Mx = MatrixSymbol('M^x', 2, 2) assert latex(MatPow(Mx, 2)) == r'\left(M^{x}\right)^{2}' def test_ElementwiseApplyFunction(): X = MatrixSymbol('X', 2, 2) expr = (X.T*X).applyfunc(sin) assert latex(expr) == r"{\left( d \mapsto \sin{\left(d \right)} \right)}_{\circ}\left({X^{T} X}\right)" expr = X.applyfunc(Lambda(x, 1/x)) assert latex(expr) == r'{\left( x \mapsto \frac{1}{x} \right)}_{\circ}\left({X}\right)' def test_ZeroMatrix(): from sympy.matrices.expressions.special import ZeroMatrix assert latex(ZeroMatrix(1, 1), mat_symbol_style='plain') == r"0" assert latex(ZeroMatrix(1, 1), mat_symbol_style='bold') == r"\mathbf{0}" def test_OneMatrix(): from sympy.matrices.expressions.special import OneMatrix assert latex(OneMatrix(3, 4), mat_symbol_style='plain') == r"1" assert latex(OneMatrix(3, 4), mat_symbol_style='bold') == r"\mathbf{1}" def test_Identity(): from sympy.matrices.expressions.special import Identity assert latex(Identity(1), mat_symbol_style='plain') == r"\mathbb{I}" assert latex(Identity(1), mat_symbol_style='bold') == r"\mathbf{I}" def test_latex_DFT_IDFT(): from sympy.matrices.expressions.fourier import DFT, IDFT assert latex(DFT(13)) == r"\text{DFT}_{13}" assert latex(IDFT(x)) == r"\text{IDFT}_{x}" def test_boolean_args_order(): syms = symbols('a:f') expr = And(*syms) assert latex(expr) == r'a \wedge b \wedge c \wedge d \wedge e \wedge f' expr = Or(*syms) assert latex(expr) == r'a \vee b \vee c \vee d \vee e \vee f' expr = Equivalent(*syms) assert latex(expr) == \ r'a \Leftrightarrow b \Leftrightarrow c \Leftrightarrow d \Leftrightarrow e \Leftrightarrow f' expr = Xor(*syms) assert latex(expr) == \ r'a \veebar b \veebar c \veebar d \veebar e \veebar f' def test_imaginary(): i = sqrt(-1) assert latex(i) == r'i' def test_builtins_without_args(): assert latex(sin) == r'\sin' assert latex(cos) == r'\cos' assert latex(tan) == r'\tan' assert latex(log) == r'\log' assert latex(Ei) == r'\operatorname{Ei}' assert latex(zeta) == r'\zeta' def test_latex_greek_functions(): # bug because capital greeks that have roman equivalents should not use # \Alpha, \Beta, \Eta, etc. s = Function('Alpha') assert latex(s) == r'\mathrm{A}' assert latex(s(x)) == r'\mathrm{A}{\left(x \right)}' s = Function('Beta') assert latex(s) == r'\mathrm{B}' s = Function('Eta') assert latex(s) == r'\mathrm{H}' assert latex(s(x)) == r'\mathrm{H}{\left(x \right)}' # bug because sympy.core.numbers.Pi is special p = Function('Pi') # assert latex(p(x)) == r'\Pi{\left(x \right)}' assert latex(p) == r'\Pi' # bug because not all greeks are included c = Function('chi') assert latex(c(x)) == r'\chi{\left(x \right)}' assert latex(c) == r'\chi' def test_translate(): s = 'Alpha' assert translate(s) == r'\mathrm{A}' s = 'Beta' assert translate(s) == r'\mathrm{B}' s = 'Eta' assert translate(s) == r'\mathrm{H}' s = 'omicron' assert translate(s) == r'o' s = 'Pi' assert translate(s) == r'\Pi' s = 'pi' assert translate(s) == r'\pi' s = 'LamdaHatDOT' assert translate(s) == r'\dot{\hat{\Lambda}}' def test_other_symbols(): from sympy.printing.latex import other_symbols for s in other_symbols: assert latex(symbols(s)) == r"" "\\" + s def test_modifiers(): # Test each modifier individually in the simplest case # (with funny capitalizations) assert latex(symbols("xMathring")) == r"\mathring{x}" assert latex(symbols("xCheck")) == r"\check{x}" assert latex(symbols("xBreve")) == r"\breve{x}" assert latex(symbols("xAcute")) == r"\acute{x}" assert latex(symbols("xGrave")) == r"\grave{x}" assert latex(symbols("xTilde")) == r"\tilde{x}" assert latex(symbols("xPrime")) == r"{x}'" assert latex(symbols("xddDDot")) == r"\ddddot{x}" assert latex(symbols("xDdDot")) == r"\dddot{x}" assert latex(symbols("xDDot")) == r"\ddot{x}" assert latex(symbols("xBold")) == r"\boldsymbol{x}" assert latex(symbols("xnOrM")) == r"\left\|{x}\right\|" assert latex(symbols("xAVG")) == r"\left\langle{x}\right\rangle" assert latex(symbols("xHat")) == r"\hat{x}" assert latex(symbols("xDot")) == r"\dot{x}" assert latex(symbols("xBar")) == r"\bar{x}" assert latex(symbols("xVec")) == r"\vec{x}" assert latex(symbols("xAbs")) == r"\left|{x}\right|" assert latex(symbols("xMag")) == r"\left|{x}\right|" assert latex(symbols("xPrM")) == r"{x}'" assert latex(symbols("xBM")) == r"\boldsymbol{x}" # Test strings that are *only* the names of modifiers assert latex(symbols("Mathring")) == r"Mathring" assert latex(symbols("Check")) == r"Check" assert latex(symbols("Breve")) == r"Breve" assert latex(symbols("Acute")) == r"Acute" assert latex(symbols("Grave")) == r"Grave" assert latex(symbols("Tilde")) == r"Tilde" assert latex(symbols("Prime")) == r"Prime" assert latex(symbols("DDot")) == r"\dot{D}" assert latex(symbols("Bold")) == r"Bold" assert latex(symbols("NORm")) == r"NORm" assert latex(symbols("AVG")) == r"AVG" assert latex(symbols("Hat")) == r"Hat" assert latex(symbols("Dot")) == r"Dot" assert latex(symbols("Bar")) == r"Bar" assert latex(symbols("Vec")) == r"Vec" assert latex(symbols("Abs")) == r"Abs" assert latex(symbols("Mag")) == r"Mag" assert latex(symbols("PrM")) == r"PrM" assert latex(symbols("BM")) == r"BM" assert latex(symbols("hbar")) == r"\hbar" # Check a few combinations assert latex(symbols("xvecdot")) == r"\dot{\vec{x}}" assert latex(symbols("xDotVec")) == r"\vec{\dot{x}}" assert latex(symbols("xHATNorm")) == r"\left\|{\hat{x}}\right\|" # Check a couple big, ugly combinations assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == \ r"\boldsymbol{\mathring{x}}^{\left|{\breve{z}}\right|}_{{\check{y}}'}" assert latex(symbols('alphadothat_nVECDOT__tTildePrime')) == \ r"\hat{\dot{\alpha}}^{{\tilde{t}}'}_{\dot{\vec{n}}}" def test_greek_symbols(): assert latex(Symbol('alpha')) == r'\alpha' assert latex(Symbol('beta')) == r'\beta' assert latex(Symbol('gamma')) == r'\gamma' assert latex(Symbol('delta')) == r'\delta' assert latex(Symbol('epsilon')) == r'\epsilon' assert latex(Symbol('zeta')) == r'\zeta' assert latex(Symbol('eta')) == r'\eta' assert latex(Symbol('theta')) == r'\theta' assert latex(Symbol('iota')) == r'\iota' assert latex(Symbol('kappa')) == r'\kappa' assert latex(Symbol('lambda')) == r'\lambda' assert latex(Symbol('mu')) == r'\mu' assert latex(Symbol('nu')) == r'\nu' assert latex(Symbol('xi')) == r'\xi' assert latex(Symbol('omicron')) == r'o' assert latex(Symbol('pi')) == r'\pi' assert latex(Symbol('rho')) == r'\rho' assert latex(Symbol('sigma')) == r'\sigma' assert latex(Symbol('tau')) == r'\tau' assert latex(Symbol('upsilon')) == r'\upsilon' assert latex(Symbol('phi')) == r'\phi' assert latex(Symbol('chi')) == r'\chi' assert latex(Symbol('psi')) == r'\psi' assert latex(Symbol('omega')) == r'\omega' assert latex(Symbol('Alpha')) == r'\mathrm{A}' assert latex(Symbol('Beta')) == r'\mathrm{B}' assert latex(Symbol('Gamma')) == r'\Gamma' assert latex(Symbol('Delta')) == r'\Delta' assert latex(Symbol('Epsilon')) == r'\mathrm{E}' assert latex(Symbol('Zeta')) == r'\mathrm{Z}' assert latex(Symbol('Eta')) == r'\mathrm{H}' assert latex(Symbol('Theta')) == r'\Theta' assert latex(Symbol('Iota')) == r'\mathrm{I}' assert latex(Symbol('Kappa')) == r'\mathrm{K}' assert latex(Symbol('Lambda')) == r'\Lambda' assert latex(Symbol('Mu')) == r'\mathrm{M}' assert latex(Symbol('Nu')) == r'\mathrm{N}' assert latex(Symbol('Xi')) == r'\Xi' assert latex(Symbol('Omicron')) == r'\mathrm{O}' assert latex(Symbol('Pi')) == r'\Pi' assert latex(Symbol('Rho')) == r'\mathrm{P}' assert latex(Symbol('Sigma')) == r'\Sigma' assert latex(Symbol('Tau')) == r'\mathrm{T}' assert latex(Symbol('Upsilon')) == r'\Upsilon' assert latex(Symbol('Phi')) == r'\Phi' assert latex(Symbol('Chi')) == r'\mathrm{X}' assert latex(Symbol('Psi')) == r'\Psi' assert latex(Symbol('Omega')) == r'\Omega' assert latex(Symbol('varepsilon')) == r'\varepsilon' assert latex(Symbol('varkappa')) == r'\varkappa' assert latex(Symbol('varphi')) == r'\varphi' assert latex(Symbol('varpi')) == r'\varpi' assert latex(Symbol('varrho')) == r'\varrho' assert latex(Symbol('varsigma')) == r'\varsigma' assert latex(Symbol('vartheta')) == r'\vartheta' def test_fancyset_symbols(): assert latex(S.Rationals) == r'\mathbb{Q}' assert latex(S.Naturals) == r'\mathbb{N}' assert latex(S.Naturals0) == r'\mathbb{N}_0' assert latex(S.Integers) == r'\mathbb{Z}' assert latex(S.Reals) == r'\mathbb{R}' assert latex(S.Complexes) == r'\mathbb{C}' @XFAIL def test_builtin_without_args_mismatched_names(): assert latex(CosineTransform) == r'\mathcal{COS}' def test_builtin_no_args(): assert latex(Chi) == r'\operatorname{Chi}' assert latex(beta) == r'\operatorname{B}' assert latex(gamma) == r'\Gamma' assert latex(KroneckerDelta) == r'\delta' assert latex(DiracDelta) == r'\delta' assert latex(lowergamma) == r'\gamma' def test_issue_6853(): p = Function('Pi') assert latex(p(x)) == r"\Pi{\left(x \right)}" def test_Mul(): e = Mul(-2, x + 1, evaluate=False) assert latex(e) == r'- 2 \left(x + 1\right)' e = Mul(2, x + 1, evaluate=False) assert latex(e) == r'2 \left(x + 1\right)' e = Mul(S.Half, x + 1, evaluate=False) assert latex(e) == r'\frac{x + 1}{2}' e = Mul(y, x + 1, evaluate=False) assert latex(e) == r'y \left(x + 1\right)' e = Mul(-y, x + 1, evaluate=False) assert latex(e) == r'- y \left(x + 1\right)' e = Mul(-2, x + 1) assert latex(e) == r'- 2 x - 2' e = Mul(2, x + 1) assert latex(e) == r'2 x + 2' def test_Pow(): e = Pow(2, 2, evaluate=False) assert latex(e) == r'2^{2}' assert latex(x**(Rational(-1, 3))) == r'\frac{1}{\sqrt[3]{x}}' x2 = Symbol(r'x^2') assert latex(x2**2) == r'\left(x^{2}\right)^{2}' def test_issue_7180(): assert latex(Equivalent(x, y)) == r"x \Leftrightarrow y" assert latex(Not(Equivalent(x, y))) == r"x \not\Leftrightarrow y" def test_issue_8409(): assert latex(S.Half**n) == r"\left(\frac{1}{2}\right)^{n}" def test_issue_8470(): from sympy.parsing.sympy_parser import parse_expr e = parse_expr("-B*A", evaluate=False) assert latex(e) == r"A \left(- B\right)" def test_issue_15439(): x = MatrixSymbol('x', 2, 2) y = MatrixSymbol('y', 2, 2) assert latex((x * y).subs(y, -y)) == r"x \left(- y\right)" assert latex((x * y).subs(y, -2*y)) == r"x \left(- 2 y\right)" assert latex((x * y).subs(x, -x)) == r"\left(- x\right) y" def test_issue_2934(): assert latex(Symbol(r'\frac{a_1}{b_1}')) == r'\frac{a_1}{b_1}' def test_issue_10489(): latexSymbolWithBrace = r'C_{x_{0}}' s = Symbol(latexSymbolWithBrace) assert latex(s) == latexSymbolWithBrace assert latex(cos(s)) == r'\cos{\left(C_{x_{0}} \right)}' def test_issue_12886(): m__1, l__1 = symbols('m__1, l__1') assert latex(m__1**2 + l__1**2) == \ r'\left(l^{1}\right)^{2} + \left(m^{1}\right)^{2}' def test_issue_13559(): from sympy.parsing.sympy_parser import parse_expr expr = parse_expr('5/1', evaluate=False) assert latex(expr) == r"\frac{5}{1}" def test_issue_13651(): expr = c + Mul(-1, a + b, evaluate=False) assert latex(expr) == r"c - \left(a + b\right)" def test_latex_UnevaluatedExpr(): x = symbols("x") he = UnevaluatedExpr(1/x) assert latex(he) == latex(1/x) == r"\frac{1}{x}" assert latex(he**2) == r"\left(\frac{1}{x}\right)^{2}" assert latex(he + 1) == r"1 + \frac{1}{x}" assert latex(x*he) == r"x \frac{1}{x}" def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert latex(A[0, 0]) == r"A_{0, 0}" assert latex(3 * A[0, 0]) == r"3 A_{0, 0}" F = C[0, 0].subs(C, A - B) assert latex(F) == r"\left(A - B\right)_{0, 0}" i, j, k = symbols("i j k") M = MatrixSymbol("M", k, k) N = MatrixSymbol("N", k, k) assert latex((M*N)[i, j]) == \ r'\sum_{i_{1}=0}^{k - 1} M_{i, i_{1}} N_{i_{1}, j}' def test_MatrixSymbol_printing(): # test cases for issue #14237 A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert latex(-A) == r"- A" assert latex(A - A*B - B) == r"A - A B - B" assert latex(-A*B - A*B*C - B) == r"- A B - A B C - B" def test_KroneckerProduct_printing(): A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 2, 2) assert latex(KroneckerProduct(A, B)) == r'A \otimes B' def test_Series_printing(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert latex(Series(tf1, tf2)) == \ r'\left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right) \left(\frac{x - y}{x + y}\right)' assert latex(Series(tf1, tf2, tf3)) == \ r'\left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right) \left(\frac{x - y}{x + y}\right) \left(\frac{t x^{2} - t^{w} x + w}{t - y}\right)' assert latex(Series(-tf2, tf1)) == \ r'\left(\frac{- x + y}{x + y}\right) \left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right)' M_1 = Matrix([[5/s], [5/(2*s)]]) T_1 = TransferFunctionMatrix.from_Matrix(M_1, s) M_2 = Matrix([[5, 6*s**3]]) T_2 = TransferFunctionMatrix.from_Matrix(M_2, s) # Brackets assert latex(T_1*(T_2 + T_2)) == \ r'\left[\begin{matrix}\frac{5}{s}\\\frac{5}{2 s}\end{matrix}\right]_\tau\cdot\left(\left[\begin{matrix}\frac{5}{1} &' \ r' \frac{6 s^{3}}{1}\end{matrix}\right]_\tau + \left[\begin{matrix}\frac{5}{1} & \frac{6 s^{3}}{1}\end{matrix}\right]_\tau\right)' \ == latex(MIMOSeries(MIMOParallel(T_2, T_2), T_1)) # No Brackets M_3 = Matrix([[5, 6], [6, 5/s]]) T_3 = TransferFunctionMatrix.from_Matrix(M_3, s) assert latex(T_1*T_2 + T_3) == r'\left[\begin{matrix}\frac{5}{s}\\\frac{5}{2 s}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}' \ r'\frac{5}{1} & \frac{6 s^{3}}{1}\end{matrix}\right]_\tau + \left[\begin{matrix}\frac{5}{1} & \frac{6}{1}\\\frac{6}{1} & ' \ r'\frac{5}{s}\end{matrix}\right]_\tau' == latex(MIMOParallel(MIMOSeries(T_2, T_1), T_3)) def test_TransferFunction_printing(): tf1 = TransferFunction(x - 1, x + 1, x) assert latex(tf1) == r"\frac{x - 1}{x + 1}" tf2 = TransferFunction(x + 1, 2 - y, x) assert latex(tf2) == r"\frac{x + 1}{2 - y}" tf3 = TransferFunction(y, y**2 + 2*y + 3, y) assert latex(tf3) == r"\frac{y}{y^{2} + 2 y + 3}" def test_Parallel_printing(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) assert latex(Parallel(tf1, tf2)) == \ r'\frac{x y^{2} - z}{- t^{3} + y^{3}} + \frac{x - y}{x + y}' assert latex(Parallel(-tf2, tf1)) == \ r'\frac{- x + y}{x + y} + \frac{x y^{2} - z}{- t^{3} + y^{3}}' M_1 = Matrix([[5, 6], [6, 5/s]]) T_1 = TransferFunctionMatrix.from_Matrix(M_1, s) M_2 = Matrix([[5/s, 6], [6, 5/(s - 1)]]) T_2 = TransferFunctionMatrix.from_Matrix(M_2, s) M_3 = Matrix([[6, 5/(s*(s - 1))], [5, 6]]) T_3 = TransferFunctionMatrix.from_Matrix(M_3, s) assert latex(T_1 + T_2 + T_3) == r'\left[\begin{matrix}\frac{5}{1} & \frac{6}{1}\\\frac{6}{1} & \frac{5}{s}\end{matrix}\right]' \ r'_\tau + \left[\begin{matrix}\frac{5}{s} & \frac{6}{1}\\\frac{6}{1} & \frac{5}{s - 1}\end{matrix}\right]_\tau + \left[\begin{matrix}' \ r'\frac{6}{1} & \frac{5}{s \left(s - 1\right)}\\\frac{5}{1} & \frac{6}{1}\end{matrix}\right]_\tau' \ == latex(MIMOParallel(T_1, T_2, T_3)) == latex(MIMOParallel(T_1, MIMOParallel(T_2, T_3))) == latex(MIMOParallel(MIMOParallel(T_1, T_2), T_3)) def test_TransferFunctionMatrix_printing(): tf1 = TransferFunction(p, p + x, p) tf2 = TransferFunction(-s + p, p + s, p) tf3 = TransferFunction(p, y**2 + 2*y + 3, p) assert latex(TransferFunctionMatrix([[tf1], [tf2]])) == \ r'\left[\begin{matrix}\frac{p}{p + x}\\\frac{p - s}{p + s}\end{matrix}\right]_\tau' assert latex(TransferFunctionMatrix([[tf1, tf2], [tf3, -tf1]])) == \ r'\left[\begin{matrix}\frac{p}{p + x} & \frac{p - s}{p + s}\\\frac{p}{y^{2} + 2 y + 3} & \frac{\left(-1\right) p}{p + x}\end{matrix}\right]_\tau' def test_Feedback_printing(): tf1 = TransferFunction(p, p + x, p) tf2 = TransferFunction(-s + p, p + s, p) # Negative Feedback (Default) assert latex(Feedback(tf1, tf2)) == \ r'\frac{\frac{p}{p + x}}{\frac{1}{1} + \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}' assert latex(Feedback(tf1*tf2, TransferFunction(1, 1, p))) == \ r'\frac{\left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}{\frac{1}{1} + \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}' # Positive Feedback assert latex(Feedback(tf1, tf2, 1)) == \ r'\frac{\frac{p}{p + x}}{\frac{1}{1} - \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}' assert latex(Feedback(tf1*tf2, sign=1)) == \ r'\frac{\left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}{\frac{1}{1} - \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}' def test_MIMOFeedback_printing(): tf1 = TransferFunction(1, s, s) tf2 = TransferFunction(s, s**2 - 1, s) tf3 = TransferFunction(s, s - 1, s) tf4 = TransferFunction(s**2, s**2 - 1, s) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]]) tfm_2 = TransferFunctionMatrix([[tf4, tf3], [tf2, tf1]]) # Negative Feedback (Default) assert latex(MIMOFeedback(tfm_1, tfm_2)) == \ r'\left(I_{\tau} + \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left[' \ r'\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1} & \frac{1}{s}\end{matrix}\right]_\tau\right)^{-1} \cdot \left[\begin{matrix}' \ r'\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau' # Positive Feedback assert latex(MIMOFeedback(tfm_1*tfm_2, tfm_1, 1)) == \ r'\left(I_{\tau} - \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left' \ r'[\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1} & \frac{1}{s}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}' \ r'\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\right)^{-1} \cdot \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}' \ r'\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1}' \ r' & \frac{1}{s}\end{matrix}\right]_\tau' def test_Quaternion_latex_printing(): q = Quaternion(x, y, z, t) assert latex(q) == r"x + y i + z j + t k" q = Quaternion(x, y, z, x*t) assert latex(q) == r"x + y i + z j + t x k" q = Quaternion(x, y, z, x + t) assert latex(q) == r"x + y i + z j + \left(t + x\right) k" def test_TensorProduct_printing(): from sympy.tensor.functions import TensorProduct A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert latex(TensorProduct(A, B)) == r"A \otimes B" def test_WedgeProduct_printing(): from sympy.diffgeom.rn import R2 from sympy.diffgeom import WedgeProduct wp = WedgeProduct(R2.dx, R2.dy) assert latex(wp) == r"\operatorname{d}x \wedge \operatorname{d}y" def test_issue_9216(): expr_1 = Pow(1, -1, evaluate=False) assert latex(expr_1) == r"1^{-1}" expr_2 = Pow(1, Pow(1, -1, evaluate=False), evaluate=False) assert latex(expr_2) == r"1^{1^{-1}}" expr_3 = Pow(3, -2, evaluate=False) assert latex(expr_3) == r"\frac{1}{9}" expr_4 = Pow(1, -2, evaluate=False) assert latex(expr_4) == r"1^{-2}" def test_latex_printer_tensor(): from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, tensor_heads L = TensorIndexType("L") i, j, k, l = tensor_indices("i j k l", L) i0 = tensor_indices("i_0", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) K = TensorHead("K", [L, L, L, L]) assert latex(i) == r"{}^{i}" assert latex(-i) == r"{}_{i}" expr = A(i) assert latex(expr) == r"A{}^{i}" expr = A(i0) assert latex(expr) == r"A{}^{i_{0}}" expr = A(-i) assert latex(expr) == r"A{}_{i}" expr = -3*A(i) assert latex(expr) == r"-3A{}^{i}" expr = K(i, j, -k, -i0) assert latex(expr) == r"K{}^{ij}{}_{ki_{0}}" expr = K(i, -j, -k, i0) assert latex(expr) == r"K{}^{i}{}_{jk}{}^{i_{0}}" expr = K(i, -j, k, -i0) assert latex(expr) == r"K{}^{i}{}_{j}{}^{k}{}_{i_{0}}" expr = H(i, -j) assert latex(expr) == r"H{}^{i}{}_{j}" expr = H(i, j) assert latex(expr) == r"H{}^{ij}" expr = H(-i, -j) assert latex(expr) == r"H{}_{ij}" expr = (1+x)*A(i) assert latex(expr) == r"\left(x + 1\right)A{}^{i}" expr = H(i, -i) assert latex(expr) == r"H{}^{L_{0}}{}_{L_{0}}" expr = H(i, -j)*A(j)*B(k) assert latex(expr) == r"H{}^{i}{}_{L_{0}}A{}^{L_{0}}B{}^{k}" expr = A(i) + 3*B(i) assert latex(expr) == r"3B{}^{i} + A{}^{i}" # Test ``TensorElement``: from sympy.tensor.tensor import TensorElement expr = TensorElement(K(i, j, k, l), {i: 3, k: 2}) assert latex(expr) == r'K{}^{i=3,j,k=2,l}' expr = TensorElement(K(i, j, k, l), {i: 3}) assert latex(expr) == r'K{}^{i=3,jkl}' expr = TensorElement(K(i, -j, k, l), {i: 3, k: 2}) assert latex(expr) == r'K{}^{i=3}{}_{j}{}^{k=2,l}' expr = TensorElement(K(i, -j, k, -l), {i: 3, k: 2}) assert latex(expr) == r'K{}^{i=3}{}_{j}{}^{k=2}{}_{l}' expr = TensorElement(K(i, j, -k, -l), {i: 3, -k: 2}) assert latex(expr) == r'K{}^{i=3,j}{}_{k=2,l}' expr = TensorElement(K(i, j, -k, -l), {i: 3}) assert latex(expr) == r'K{}^{i=3,j}{}_{kl}' expr = PartialDerivative(A(i), A(i)) assert latex(expr) == r"\frac{\partial}{\partial {A{}^{L_{0}}}}{A{}^{L_{0}}}" expr = PartialDerivative(A(-i), A(-j)) assert latex(expr) == r"\frac{\partial}{\partial {A{}_{j}}}{A{}_{i}}" expr = PartialDerivative(K(i, j, -k, -l), A(m), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}^{m}} \partial {A{}_{n}}}{K{}^{ij}{}_{kl}}" expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(A{}_{i} + B{}_{i}\right)}" expr = PartialDerivative(3*A(-i), A(-j), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(3A{}_{i}\right)}" def test_multiline_latex(): a, b, c, d, e, f = symbols('a b c d e f') expr = -a + 2*b -3*c +4*d -5*e expected = r"\begin{eqnarray}" + "\n"\ r"f & = &- a \nonumber\\" + "\n"\ r"& & + 2 b \nonumber\\" + "\n"\ r"& & - 3 c \nonumber\\" + "\n"\ r"& & + 4 d \nonumber\\" + "\n"\ r"& & - 5 e " + "\n"\ r"\end{eqnarray}" assert multiline_latex(f, expr, environment="eqnarray") == expected expected2 = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b \nonumber\\' + '\n'\ r'& & - 3 c + 4 d \nonumber\\' + '\n'\ r'& & - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 2, environment="eqnarray") == expected2 expected3 = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b - 3 c \nonumber\\'+ '\n'\ r'& & + 4 d - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 3, environment="eqnarray") == expected3 expected3dots = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b - 3 c \dots\nonumber\\'+ '\n'\ r'& & + 4 d - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 3, environment="eqnarray", use_dots=True) == expected3dots expected3align = r'\begin{align*}' + '\n'\ r'f = &- a + 2 b - 3 c \\'+ '\n'\ r'& + 4 d - 5 e ' + '\n'\ r'\end{align*}' assert multiline_latex(f, expr, 3) == expected3align assert multiline_latex(f, expr, 3, environment='align*') == expected3align expected2ieee = r'\begin{IEEEeqnarray}{rCl}' + '\n'\ r'f & = &- a + 2 b \nonumber\\' + '\n'\ r'& & - 3 c + 4 d \nonumber\\' + '\n'\ r'& & - 5 e ' + '\n'\ r'\end{IEEEeqnarray}' assert multiline_latex(f, expr, 2, environment="IEEEeqnarray") == expected2ieee raises(ValueError, lambda: multiline_latex(f, expr, environment="foo")) def test_issue_15353(): a, x = symbols('a x') # Obtained from nonlinsolve([(sin(a*x)),cos(a*x)],[x,a]) sol = ConditionSet( Tuple(x, a), Eq(sin(a*x), 0) & Eq(cos(a*x), 0), S.Complexes**2) assert latex(sol) == \ r'\left\{\left( x, \ a\right)\; \middle|\; \left( x, \ a\right) \in ' \ r'\mathbb{C}^{2} \wedge \sin{\left(a x \right)} = 0 \wedge ' \ r'\cos{\left(a x \right)} = 0 \right\}' def test_latex_symbolic_probability(): mu = symbols("mu") sigma = symbols("sigma", positive=True) X = Normal("X", mu, sigma) assert latex(Expectation(X)) == r'\operatorname{E}\left[X\right]' assert latex(Variance(X)) == r'\operatorname{Var}\left(X\right)' assert latex(Probability(X > 0)) == r'\operatorname{P}\left(X > 0\right)' Y = Normal("Y", mu, sigma) assert latex(Covariance(X, Y)) == r'\operatorname{Cov}\left(X, Y\right)' def test_trace(): # Issue 15303 from sympy.matrices.expressions.trace import trace A = MatrixSymbol("A", 2, 2) assert latex(trace(A)) == r"\operatorname{tr}\left(A \right)" assert latex(trace(A**2)) == r"\operatorname{tr}\left(A^{2} \right)" def test_print_basic(): # Issue 15303 from sympy.core.basic import Basic from sympy.core.expr import Expr # dummy class for testing printing where the function is not # implemented in latex.py class UnimplementedExpr(Expr): def __new__(cls, e): return Basic.__new__(cls, e) # dummy function for testing def unimplemented_expr(expr): return UnimplementedExpr(expr).doit() # override class name to use superscript / subscript def unimplemented_expr_sup_sub(expr): result = UnimplementedExpr(expr) result.__class__.__name__ = 'UnimplementedExpr_x^1' return result assert latex(unimplemented_expr(x)) == r'\operatorname{UnimplementedExpr}\left(x\right)' assert latex(unimplemented_expr(x**2)) == \ r'\operatorname{UnimplementedExpr}\left(x^{2}\right)' assert latex(unimplemented_expr_sup_sub(x)) == \ r'\operatorname{UnimplementedExpr^{1}_{x}}\left(x\right)' def test_MatrixSymbol_bold(): # Issue #15871 from sympy.matrices.expressions.trace import trace A = MatrixSymbol("A", 2, 2) assert latex(trace(A), mat_symbol_style='bold') == \ r"\operatorname{tr}\left(\mathbf{A} \right)" assert latex(trace(A), mat_symbol_style='plain') == \ r"\operatorname{tr}\left(A \right)" A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert latex(-A, mat_symbol_style='bold') == r"- \mathbf{A}" assert latex(A - A*B - B, mat_symbol_style='bold') == \ r"\mathbf{A} - \mathbf{A} \mathbf{B} - \mathbf{B}" assert latex(-A*B - A*B*C - B, mat_symbol_style='bold') == \ r"- \mathbf{A} \mathbf{B} - \mathbf{A} \mathbf{B} \mathbf{C} - \mathbf{B}" A_k = MatrixSymbol("A_k", 3, 3) assert latex(A_k, mat_symbol_style='bold') == r"\mathbf{A}_{k}" A = MatrixSymbol(r"\nabla_k", 3, 3) assert latex(A, mat_symbol_style='bold') == r"\mathbf{\nabla}_{k}" def test_AppliedPermutation(): p = Permutation(0, 1, 2) x = Symbol('x') assert latex(AppliedPermutation(p, x)) == \ r'\sigma_{\left( 0\; 1\; 2\right)}(x)' def test_PermutationMatrix(): p = Permutation(0, 1, 2) assert latex(PermutationMatrix(p)) == r'P_{\left( 0\; 1\; 2\right)}' p = Permutation(0, 3)(1, 2) assert latex(PermutationMatrix(p)) == \ r'P_{\left( 0\; 3\right)\left( 1\; 2\right)}' def test_issue_21758(): from sympy.functions.elementary.piecewise import piecewise_fold from sympy.series.fourier import FourierSeries x = Symbol('x') k, n = symbols('k n') fo = FourierSeries(x, (x, -pi, pi), (0, SeqFormula(0, (k, 1, oo)), SeqFormula( Piecewise((-2*pi*cos(n*pi)/n + 2*sin(n*pi)/n**2, (n > -oo) & (n < oo) & Ne(n, 0)), (0, True))*sin(n*x)/pi, (n, 1, oo)))) assert latex(piecewise_fold(fo)) == '\\begin{cases} 2 \\sin{\\left(x \\right)}' \ ' - \\sin{\\left(2 x \\right)} + \\frac{2 \\sin{\\left(3 x \\right)}}{3} +' \ ' \\ldots & \\text{for}\\: n > -\\infty \\wedge n < \\infty \\wedge ' \ 'n \\neq 0 \\\\0 & \\text{otherwise} \\end{cases}' assert latex(FourierSeries(x, (x, -pi, pi), (0, SeqFormula(0, (k, 1, oo)), SeqFormula(0, (n, 1, oo))))) == '0' def test_imaginary_unit(): assert latex(1 + I) == r'1 + i' assert latex(1 + I, imaginary_unit='i') == r'1 + i' assert latex(1 + I, imaginary_unit='j') == r'1 + j' assert latex(1 + I, imaginary_unit='foo') == r'1 + foo' assert latex(I, imaginary_unit="ti") == r'\text{i}' assert latex(I, imaginary_unit="tj") == r'\text{j}' def test_text_re_im(): assert latex(im(x), gothic_re_im=True) == r'\Im{\left(x\right)}' assert latex(im(x), gothic_re_im=False) == r'\operatorname{im}{\left(x\right)}' assert latex(re(x), gothic_re_im=True) == r'\Re{\left(x\right)}' assert latex(re(x), gothic_re_im=False) == r'\operatorname{re}{\left(x\right)}' def test_latex_diffgeom(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential from sympy.diffgeom.rn import R2 x,y = symbols('x y', real=True) m = Manifold('M', 2) assert latex(m) == r'\text{M}' p = Patch('P', m) assert latex(p) == r'\text{P}_{\text{M}}' rect = CoordSystem('rect', p, [x, y]) assert latex(rect) == r'\text{rect}^{\text{P}}_{\text{M}}' b = BaseScalarField(rect, 0) assert latex(b) == r'\mathbf{x}' g = Function('g') s_field = g(R2.x, R2.y) assert latex(Differential(s_field)) == \ r'\operatorname{d}\left(g{\left(\mathbf{x},\mathbf{y} \right)}\right)' def test_unit_printing(): assert latex(5*meter) == r'5 \text{m}' assert latex(3*gibibyte) == r'3 \text{gibibyte}' assert latex(4*microgram/second) == r'\frac{4 \mu\text{g}}{\text{s}}' assert latex(4*micro*gram/second) == r'\frac{4 \mu \text{g}}{\text{s}}' assert latex(5*milli*meter) == r'5 \text{m} \text{m}' assert latex(milli) == r'\text{m}' def test_issue_17092(): x_star = Symbol('x^*') assert latex(Derivative(x_star, x_star,2)) == r'\frac{d^{2}}{d \left(x^{*}\right)^{2}} x^{*}' def test_latex_decimal_separator(): x, y, z, t = symbols('x y z t') k, m, n = symbols('k m n', integer=True) f, g, h = symbols('f g h', cls=Function) # comma decimal_separator assert(latex([1, 2.3, 4.5], decimal_separator='comma') == r'\left[ 1; \ 2{,}3; \ 4{,}5\right]') assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='comma') == r'\left\{1; 2{,}3; 4{,}5\right\}') assert(latex((1, 2.3, 4.6), decimal_separator = 'comma') == r'\left( 1; \ 2{,}3; \ 4{,}6\right)') assert(latex((1,), decimal_separator='comma') == r'\left( 1;\right)') # period decimal_separator assert(latex([1, 2.3, 4.5], decimal_separator='period') == r'\left[ 1, \ 2.3, \ 4.5\right]' ) assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}') assert(latex((1, 2.3, 4.6), decimal_separator = 'period') == r'\left( 1, \ 2.3, \ 4.6\right)') assert(latex((1,), decimal_separator='period') == r'\left( 1,\right)') # default decimal_separator assert(latex([1, 2.3, 4.5]) == r'\left[ 1, \ 2.3, \ 4.5\right]') assert(latex(FiniteSet(1, 2.3, 4.5)) == r'\left\{1, 2.3, 4.5\right\}') assert(latex((1, 2.3, 4.6)) == r'\left( 1, \ 2.3, \ 4.6\right)') assert(latex((1,)) == r'\left( 1,\right)') assert(latex(Mul(3.4,5.3), decimal_separator = 'comma') == r'18{,}02') assert(latex(3.4*5.3, decimal_separator = 'comma') == r'18{,}02') x = symbols('x') y = symbols('y') z = symbols('z') assert(latex(x*5.3 + 2**y**3.4 + 4.5 + z, decimal_separator = 'comma') == r'2^{y^{3{,}4}} + 5{,}3 x + z + 4{,}5') assert(latex(0.987, decimal_separator='comma') == r'0{,}987') assert(latex(S(0.987), decimal_separator='comma') == r'0{,}987') assert(latex(.3, decimal_separator='comma') == r'0{,}3') assert(latex(S(.3), decimal_separator='comma') == r'0{,}3') assert(latex(5.8*10**(-7), decimal_separator='comma') == r'5{,}8 \cdot 10^{-7}') assert(latex(S(5.7)*10**(-7), decimal_separator='comma') == r'5{,}7 \cdot 10^{-7}') assert(latex(S(5.7*10**(-7)), decimal_separator='comma') == r'5{,}7 \cdot 10^{-7}') x = symbols('x') assert(latex(1.2*x+3.4, decimal_separator='comma') == r'1{,}2 x + 3{,}4') assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}') # Error Handling tests raises(ValueError, lambda: latex([1,2.3,4.5], decimal_separator='non_existing_decimal_separator_in_list')) raises(ValueError, lambda: latex(FiniteSet(1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_set')) raises(ValueError, lambda: latex((1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_tuple')) def test_Str(): from sympy.core.symbol import Str assert str(Str('x')) == r'x' def test_latex_escape(): assert latex_escape(r"~^\&%$#_{}") == "".join([ r'\textasciitilde', r'\textasciicircum', r'\textbackslash', r'\&', r'\%', r'\$', r'\#', r'\_', r'\{', r'\}', ]) def test_emptyPrinter(): class MyObject: def __repr__(self): return "<MyObject with {...}>" # unknown objects are monospaced assert latex(MyObject()) == r"\mathtt{\text{<MyObject with \{...\}>}}" # even if they are nested within other objects assert latex((MyObject(),)) == r"\left( \mathtt{\text{<MyObject with \{...\}>}},\right)" def test_global_settings(): import inspect # settings should be visible in the signature of `latex` assert inspect.signature(latex).parameters['imaginary_unit'].default == r'i' assert latex(I) == r'i' try: # but changing the defaults... LatexPrinter.set_global_settings(imaginary_unit='j') # ... should change the signature assert inspect.signature(latex).parameters['imaginary_unit'].default == r'j' assert latex(I) == r'j' finally: # there's no public API to undo this, but we need to make sure we do # so as not to impact other tests del LatexPrinter._global_settings['imaginary_unit'] # check we really did undo it assert inspect.signature(latex).parameters['imaginary_unit'].default == r'i' assert latex(I) == r'i' def test_pickleable(): # this tests that the _PrintFunction instance is pickleable import pickle assert pickle.loads(pickle.dumps(latex)) is latex def test_printing_latex_array_expressions(): assert latex(ArraySymbol("A", (2, 3, 4))) == "A" assert latex(ArrayElement("A", (2, 1/(1-x), 0))) == "{{A}_{2, \\frac{1}{1 - x}, 0}}" M = MatrixSymbol("M", 3, 3) N = MatrixSymbol("N", 3, 3) assert latex(ArrayElement(M*N, [x, 0])) == "{{\\left(M N\\right)}_{x, 0}}" def test_Array(): arr = Array(range(10)) assert latex(arr) == r'\left[\begin{matrix}0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9\end{matrix}\right]' arr = Array(range(11)) # added empty arguments {} assert latex(arr) == r'\left[\begin{array}{}0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\end{array}\right]' def test_latex_with_unevaluated(): with evaluate(False): assert latex(a * a) == r"a a"
e3fb2a9de7ffdf4ea5416b0bac4723a495cae298608c528e2b15c3fceaa3b66d
"""Tests for algorithms for computing symbolic roots of polynomials. """ from sympy.core.numbers import (I, Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, Wild, symbols) from sympy.functions.elementary.complexes import (conjugate, im, re) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import (root, sqrt) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, cos, sin) from sympy.polys.domains.integerring import ZZ from sympy.sets.sets import Interval from sympy.simplify.powsimp import powsimp from sympy.polys import Poly, cyclotomic_poly, intervals, nroots, rootof from sympy.polys.polyroots import (root_factors, roots_linear, roots_quadratic, roots_cubic, roots_quartic, roots_quintic, roots_cyclotomic, roots_binomial, preprocess_roots, roots) from sympy.polys.orthopolys import legendre_poly from sympy.polys.polyerrors import PolynomialError, \ UnsolvableFactorError from sympy.polys.polyutils import _nsort from sympy.testing.pytest import raises, slow from sympy.core.random import verify_numerically import mpmath from itertools import product a, b, c, d, e, q, t, x, y, z = symbols('a,b,c,d,e,q,t,x,y,z') def _check(roots): # this is the desired invariant for roots returned # by all_roots. It is trivially true for linear # polynomials. nreal = sum([1 if i.is_real else 0 for i in roots]) assert list(sorted(roots[:nreal])) == list(roots[:nreal]) for ix in range(nreal, len(roots), 2): if not ( roots[ix + 1] == roots[ix] or roots[ix + 1] == conjugate(roots[ix])): return False return True def test_roots_linear(): assert roots_linear(Poly(2*x + 1, x)) == [Rational(-1, 2)] def test_roots_quadratic(): assert roots_quadratic(Poly(2*x**2, x)) == [0, 0] assert roots_quadratic(Poly(2*x**2 + 3*x, x)) == [Rational(-3, 2), 0] assert roots_quadratic(Poly(2*x**2 + 3, x)) == [-I*sqrt(6)/2, I*sqrt(6)/2] assert roots_quadratic(Poly(2*x**2 + 4*x + 3, x)) == [-1 - I*sqrt(2)/2, -1 + I*sqrt(2)/2] _check(Poly(2*x**2 + 4*x + 3, x).all_roots()) f = x**2 + (2*a*e + 2*c*e)/(a - c)*x + (d - b + a*e**2 - c*e**2)/(a - c) assert roots_quadratic(Poly(f, x)) == \ [-e*(a + c)/(a - c) - sqrt(a*b + c*d - a*d - b*c + 4*a*c*e**2)/(a - c), -e*(a + c)/(a - c) + sqrt(a*b + c*d - a*d - b*c + 4*a*c*e**2)/(a - c)] # check for simplification f = Poly(y*x**2 - 2*x - 2*y, x) assert roots_quadratic(f) == \ [-sqrt(2*y**2 + 1)/y + 1/y, sqrt(2*y**2 + 1)/y + 1/y] f = Poly(x**2 + (-y**2 - 2)*x + y**2 + 1, x) assert roots_quadratic(f) == \ [1,y**2 + 1] f = Poly(sqrt(2)*x**2 - 1, x) r = roots_quadratic(f) assert r == _nsort(r) # issue 8255 f = Poly(-24*x**2 - 180*x + 264) assert [w.n(2) for w in f.all_roots(radicals=True)] == \ [w.n(2) for w in f.all_roots(radicals=False)] for _a, _b, _c in product((-2, 2), (-2, 2), (0, -1)): f = Poly(_a*x**2 + _b*x + _c) roots = roots_quadratic(f) assert roots == _nsort(roots) def test_issue_7724(): eq = Poly(x**4*I + x**2 + I, x) assert roots(eq) == { sqrt(I/2 + sqrt(5)*I/2): 1, sqrt(-sqrt(5)*I/2 + I/2): 1, -sqrt(I/2 + sqrt(5)*I/2): 1, -sqrt(-sqrt(5)*I/2 + I/2): 1} def test_issue_8438(): p = Poly([1, y, -2, -3], x).as_expr() roots = roots_cubic(Poly(p, x), x) z = Rational(-3, 2) - I*7/2 # this will fail in code given in commit msg post = [r.subs(y, z) for r in roots] assert set(post) == \ set(roots_cubic(Poly(p.subs(y, z), x))) # /!\ if p is not made an expression, this is *very* slow assert all(p.subs({y: z, x: i}).n(2, chop=True) == 0 for i in post) def test_issue_8285(): roots = (Poly(4*x**8 - 1, x)*Poly(x**2 + 1)).all_roots() assert _check(roots) f = Poly(x**4 + 5*x**2 + 6, x) ro = [rootof(f, i) for i in range(4)] roots = Poly(x**4 + 5*x**2 + 6, x).all_roots() assert roots == ro assert _check(roots) # more than 2 complex roots from which to identify the # imaginary ones roots = Poly(2*x**8 - 1).all_roots() assert _check(roots) assert len(Poly(2*x**10 - 1).all_roots()) == 10 # doesn't fail def test_issue_8289(): roots = (Poly(x**2 + 2)*Poly(x**4 + 2)).all_roots() assert _check(roots) roots = Poly(x**6 + 3*x**3 + 2, x).all_roots() assert _check(roots) roots = Poly(x**6 - x + 1).all_roots() assert _check(roots) # all imaginary roots with multiplicity of 2 roots = Poly(x**4 + 4*x**2 + 4, x).all_roots() assert _check(roots) def test_issue_14291(): assert Poly(((x - 1)**2 + 1)*((x - 1)**2 + 2)*(x - 1) ).all_roots() == [1, 1 - I, 1 + I, 1 - sqrt(2)*I, 1 + sqrt(2)*I] p = x**4 + 10*x**2 + 1 ans = [rootof(p, i) for i in range(4)] assert Poly(p).all_roots() == ans _check(ans) def test_issue_13340(): eq = Poly(y**3 + exp(x)*y + x, y, domain='EX') roots_d = roots(eq) assert len(roots_d) == 3 def test_issue_14522(): eq = Poly(x**4 + x**3*(16 + 32*I) + x**2*(-285 + 386*I) + x*(-2824 - 448*I) - 2058 - 6053*I, x) roots_eq = roots(eq) assert all(eq(r) == 0 for r in roots_eq) def test_issue_15076(): sol = roots_quartic(Poly(t**4 - 6*t**2 + t/x - 3, t)) assert sol[0].has(x) def test_issue_16589(): eq = Poly(x**4 - 8*sqrt(2)*x**3 + 4*x**3 - 64*sqrt(2)*x**2 + 1024*x, x) roots_eq = roots(eq) assert 0 in roots_eq def test_roots_cubic(): assert roots_cubic(Poly(2*x**3, x)) == [0, 0, 0] assert roots_cubic(Poly(x**3 - 3*x**2 + 3*x - 1, x)) == [1, 1, 1] # valid for arbitrary y (issue 21263) r = root(y, 3) assert roots_cubic(Poly(x**3 - y, x)) == [r, r*(-S.Half + sqrt(3)*I/2), r*(-S.Half - sqrt(3)*I/2)] # simpler form when y is negative assert roots_cubic(Poly(x**3 - -1, x)) == \ [-1, S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2] assert roots_cubic(Poly(2*x**3 - 3*x**2 - 3*x - 1, x))[0] == \ S.Half + 3**Rational(1, 3)/2 + 3**Rational(2, 3)/2 eq = -x**3 + 2*x**2 + 3*x - 2 assert roots(eq, trig=True, multiple=True) == \ roots_cubic(Poly(eq, x), trig=True) == [ Rational(2, 3) + 2*sqrt(13)*cos(acos(8*sqrt(13)/169)/3)/3, -2*sqrt(13)*sin(-acos(8*sqrt(13)/169)/3 + pi/6)/3 + Rational(2, 3), -2*sqrt(13)*cos(-acos(8*sqrt(13)/169)/3 + pi/3)/3 + Rational(2, 3), ] def test_roots_quartic(): assert roots_quartic(Poly(x**4, x)) == [0, 0, 0, 0] assert roots_quartic(Poly(x**4 + x**3, x)) in [ [-1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1] ] assert roots_quartic(Poly(x**4 - x**3, x)) in [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1] ] lhs = roots_quartic(Poly(x**4 + x, x)) rhs = [S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2, S.Zero, -S.One] assert sorted(lhs, key=hash) == sorted(rhs, key=hash) # test of all branches of roots quartic for i, (a, b, c, d) in enumerate([(1, 2, 3, 0), (3, -7, -9, 9), (1, 2, 3, 4), (1, 2, 3, 4), (-7, -3, 3, -6), (-3, 5, -6, -4), (6, -5, -10, -3)]): if i == 2: c = -a*(a**2/S(8) - b/S(2)) elif i == 3: d = a*(a*(a**2*Rational(3, 256) - b/S(16)) + c/S(4)) eq = x**4 + a*x**3 + b*x**2 + c*x + d ans = roots_quartic(Poly(eq, x)) assert all(eq.subs(x, ai).n(chop=True) == 0 for ai in ans) # not all symbolic quartics are unresolvable eq = Poly(q*x + q/4 + x**4 + x**3 + 2*x**2 - Rational(1, 3), x) sol = roots_quartic(eq) assert all(verify_numerically(eq.subs(x, i), 0) for i in sol) z = symbols('z', negative=True) eq = x**4 + 2*x**3 + 3*x**2 + x*(z + 11) + 5 zans = roots_quartic(Poly(eq, x)) assert all([verify_numerically(eq.subs(((x, i), (z, -1))), 0) for i in zans]) # but some are (see also issue 4989) # it's ok if the solution is not Piecewise, but the tests below should pass eq = Poly(y*x**4 + x**3 - x + z, x) ans = roots_quartic(eq) assert all(type(i) == Piecewise for i in ans) reps = ( dict(y=Rational(-1, 3), z=Rational(-1, 4)), # 4 real dict(y=Rational(-1, 3), z=Rational(-1, 2)), # 2 real dict(y=Rational(-1, 3), z=-2)) # 0 real for rep in reps: sol = roots_quartic(Poly(eq.subs(rep), x)) assert all([verify_numerically(w.subs(rep) - s, 0) for w, s in zip(ans, sol)]) def test_issue_21287(): assert not any(isinstance(i, Piecewise) for i in roots_quartic( Poly(x**4 - x**2*(3 + 5*I) + 2*x*(-1 + I) - 1 + 3*I, x))) def test_roots_quintic(): eqs = (x**5 - 2, (x/2 + 1)**5 - 5*(x/2 + 1) + 12, x**5 - 110*x**3 - 55*x**2 + 2310*x + 979) for eq in eqs: roots = roots_quintic(Poly(eq)) assert len(roots) == 5 assert all(eq.subs(x, r.n(10)).n(chop = 1e-5) == 0 for r in roots) def test_roots_cyclotomic(): assert roots_cyclotomic(cyclotomic_poly(1, x, polys=True)) == [1] assert roots_cyclotomic(cyclotomic_poly(2, x, polys=True)) == [-1] assert roots_cyclotomic(cyclotomic_poly( 3, x, polys=True)) == [Rational(-1, 2) - I*sqrt(3)/2, Rational(-1, 2) + I*sqrt(3)/2] assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True)) == [-I, I] assert roots_cyclotomic(cyclotomic_poly( 6, x, polys=True)) == [S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2] assert roots_cyclotomic(cyclotomic_poly(7, x, polys=True)) == [ -cos(pi/7) - I*sin(pi/7), -cos(pi/7) + I*sin(pi/7), -cos(pi*Rational(3, 7)) - I*sin(pi*Rational(3, 7)), -cos(pi*Rational(3, 7)) + I*sin(pi*Rational(3, 7)), cos(pi*Rational(2, 7)) - I*sin(pi*Rational(2, 7)), cos(pi*Rational(2, 7)) + I*sin(pi*Rational(2, 7)), ] assert roots_cyclotomic(cyclotomic_poly(8, x, polys=True)) == [ -sqrt(2)/2 - I*sqrt(2)/2, -sqrt(2)/2 + I*sqrt(2)/2, sqrt(2)/2 - I*sqrt(2)/2, sqrt(2)/2 + I*sqrt(2)/2, ] assert roots_cyclotomic(cyclotomic_poly(12, x, polys=True)) == [ -sqrt(3)/2 - I/2, -sqrt(3)/2 + I/2, sqrt(3)/2 - I/2, sqrt(3)/2 + I/2, ] assert roots_cyclotomic( cyclotomic_poly(1, x, polys=True), factor=True) == [1] assert roots_cyclotomic( cyclotomic_poly(2, x, polys=True), factor=True) == [-1] assert roots_cyclotomic(cyclotomic_poly(3, x, polys=True), factor=True) == \ [-root(-1, 3), -1 + root(-1, 3)] assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True), factor=True) == \ [-I, I] assert roots_cyclotomic(cyclotomic_poly(5, x, polys=True), factor=True) == \ [-root(-1, 5), -root(-1, 5)**3, root(-1, 5)**2, -1 - root(-1, 5)**2 + root(-1, 5) + root(-1, 5)**3] assert roots_cyclotomic(cyclotomic_poly(6, x, polys=True), factor=True) == \ [1 - root(-1, 3), root(-1, 3)] def test_roots_binomial(): assert roots_binomial(Poly(5*x, x)) == [0] assert roots_binomial(Poly(5*x**4, x)) == [0, 0, 0, 0] assert roots_binomial(Poly(5*x + 2, x)) == [Rational(-2, 5)] A = 10**Rational(3, 4)/10 assert roots_binomial(Poly(5*x**4 + 2, x)) == \ [-A - A*I, -A + A*I, A - A*I, A + A*I] _check(roots_binomial(Poly(x**8 - 2))) a1 = Symbol('a1', nonnegative=True) b1 = Symbol('b1', nonnegative=True) r0 = roots_quadratic(Poly(a1*x**2 + b1, x)) r1 = roots_binomial(Poly(a1*x**2 + b1, x)) assert powsimp(r0[0]) == powsimp(r1[0]) assert powsimp(r0[1]) == powsimp(r1[1]) for a, b, s, n in product((1, 2), (1, 2), (-1, 1), (2, 3, 4, 5)): if a == b and a != 1: # a == b == 1 is sufficient continue p = Poly(a*x**n + s*b) ans = roots_binomial(p) assert ans == _nsort(ans) # issue 8813 assert roots(Poly(2*x**3 - 16*y**3, x)) == { 2*y*(Rational(-1, 2) - sqrt(3)*I/2): 1, 2*y: 1, 2*y*(Rational(-1, 2) + sqrt(3)*I/2): 1} def test_roots_preprocessing(): f = a*y*x**2 + y - b coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1 assert poly == Poly(a*y*x**2 + y - b, x) f = c**3*x**3 + c**2*x**2 + c*x + a coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1/c assert poly == Poly(x**3 + x**2 + x + a, x) f = c**3*x**3 + c**2*x**2 + a coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1/c assert poly == Poly(x**3 + x**2 + a, x) f = c**3*x**3 + c*x + a coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1/c assert poly == Poly(x**3 + x + a, x) f = c**3*x**3 + a coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1/c assert poly == Poly(x**3 + a, x) E, F, J, L = symbols("E,F,J,L") f = -21601054687500000000*E**8*J**8/L**16 + \ 508232812500000000*F*x*E**7*J**7/L**14 - \ 4269543750000000*E**6*F**2*J**6*x**2/L**12 + \ 16194716250000*E**5*F**3*J**5*x**3/L**10 - \ 27633173750*E**4*F**4*J**4*x**4/L**8 + \ 14840215*E**3*F**5*J**3*x**5/L**6 + \ 54794*E**2*F**6*J**2*x**6/(5*L**4) - \ 1153*E*J*F**7*x**7/(80*L**2) + \ 633*F**8*x**8/160000 coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 20*E*J/(F*L**2) assert poly == 633*x**8 - 115300*x**7 + 4383520*x**6 + 296804300*x**5 - 27633173750*x**4 + \ 809735812500*x**3 - 10673859375000*x**2 + 63529101562500*x - 135006591796875 f = Poly(-y**2 + x**2*exp(x), y, domain=ZZ[x, exp(x)]) g = Poly(-y**2 + exp(x), y, domain=ZZ[exp(x)]) assert preprocess_roots(f) == (x, g) def test_roots0(): assert roots(1, x) == {} assert roots(x, x) == {S.Zero: 1} assert roots(x**9, x) == {S.Zero: 9} assert roots(((x - 2)*(x + 3)*(x - 4)).expand(), x) == {-S(3): 1, S(2): 1, S(4): 1} assert roots(2*x + 1, x) == {Rational(-1, 2): 1} assert roots((2*x + 1)**2, x) == {Rational(-1, 2): 2} assert roots((2*x + 1)**5, x) == {Rational(-1, 2): 5} assert roots((2*x + 1)**10, x) == {Rational(-1, 2): 10} assert roots(x**4 - 1, x) == {I: 1, S.One: 1, -S.One: 1, -I: 1} assert roots((x**4 - 1)**2, x) == {I: 2, S.One: 2, -S.One: 2, -I: 2} assert roots(((2*x - 3)**2).expand(), x) == {Rational( 3, 2): 2} assert roots(((2*x + 3)**2).expand(), x) == {Rational(-3, 2): 2} assert roots(((2*x - 3)**3).expand(), x) == {Rational( 3, 2): 3} assert roots(((2*x + 3)**3).expand(), x) == {Rational(-3, 2): 3} assert roots(((2*x - 3)**5).expand(), x) == {Rational( 3, 2): 5} assert roots(((2*x + 3)**5).expand(), x) == {Rational(-3, 2): 5} assert roots(((a*x - b)**5).expand(), x) == { b/a: 5} assert roots(((a*x + b)**5).expand(), x) == {-b/a: 5} assert roots(x**2 + (-a - 1)*x + a, x) == {a: 1, S.One: 1} assert roots(x**4 - 2*x**2 + 1, x) == {S.One: 2, S.NegativeOne: 2} assert roots(x**6 - 4*x**4 + 4*x**3 - x**2, x) == \ {S.One: 2, -1 - sqrt(2): 1, S.Zero: 2, -1 + sqrt(2): 1} assert roots(x**8 - 1, x) == { sqrt(2)/2 + I*sqrt(2)/2: 1, sqrt(2)/2 - I*sqrt(2)/2: 1, -sqrt(2)/2 + I*sqrt(2)/2: 1, -sqrt(2)/2 - I*sqrt(2)/2: 1, S.One: 1, -S.One: 1, I: 1, -I: 1 } f = -2016*x**2 - 5616*x**3 - 2056*x**4 + 3324*x**5 + 2176*x**6 - \ 224*x**7 - 384*x**8 - 64*x**9 assert roots(f) == {S.Zero: 2, -S(2): 2, S(2): 1, Rational(-7, 2): 1, Rational(-3, 2): 1, Rational(-1, 2): 1, Rational(3, 2): 1} assert roots((a + b + c)*x - (a + b + c + d), x) == {(a + b + c + d)/(a + b + c): 1} assert roots(x**3 + x**2 - x + 1, x, cubics=False) == {} assert roots(((x - 2)*( x + 3)*(x - 4)).expand(), x, cubics=False) == {-S(3): 1, S(2): 1, S(4): 1} assert roots(((x - 2)*(x + 3)*(x - 4)*(x - 5)).expand(), x, cubics=False) == \ {-S(3): 1, S(2): 1, S(4): 1, S(5): 1} assert roots(x**3 + 2*x**2 + 4*x + 8, x) == {-S(2): 1, -2*I: 1, 2*I: 1} assert roots(x**3 + 2*x**2 + 4*x + 8, x, cubics=True) == \ {-2*I: 1, 2*I: 1, -S(2): 1} assert roots((x**2 - x)*(x**3 + 2*x**2 + 4*x + 8), x ) == \ {S.One: 1, S.Zero: 1, -S(2): 1, -2*I: 1, 2*I: 1} r1_2, r1_3 = S.Half, Rational(1, 3) x0 = (3*sqrt(33) + 19)**r1_3 x1 = 4/x0/3 x2 = x0/3 x3 = sqrt(3)*I/2 x4 = x3 - r1_2 x5 = -x3 - r1_2 assert roots(x**3 + x**2 - x + 1, x, cubics=True) == { -x1 - x2 - r1_3: 1, -x1/x4 - x2*x4 - r1_3: 1, -x1/x5 - x2*x5 - r1_3: 1, } f = (x**2 + 2*x + 3).subs(x, 2*x**2 + 3*x).subs(x, 5*x - 4) r13_20, r1_20 = [ Rational(*r) for r in ((13, 20), (1, 20)) ] s2 = sqrt(2) assert roots(f, x) == { r13_20 + r1_20*sqrt(1 - 8*I*s2): 1, r13_20 - r1_20*sqrt(1 - 8*I*s2): 1, r13_20 + r1_20*sqrt(1 + 8*I*s2): 1, r13_20 - r1_20*sqrt(1 + 8*I*s2): 1, } f = x**4 + x**3 + x**2 + x + 1 r1_4, r1_8, r5_8 = [ Rational(*r) for r in ((1, 4), (1, 8), (5, 8)) ] assert roots(f, x) == { -r1_4 + r1_4*5**r1_2 + I*(r5_8 + r1_8*5**r1_2)**r1_2: 1, -r1_4 + r1_4*5**r1_2 - I*(r5_8 + r1_8*5**r1_2)**r1_2: 1, -r1_4 - r1_4*5**r1_2 + I*(r5_8 - r1_8*5**r1_2)**r1_2: 1, -r1_4 - r1_4*5**r1_2 - I*(r5_8 - r1_8*5**r1_2)**r1_2: 1, } f = z**3 + (-2 - y)*z**2 + (1 + 2*y - 2*x**2)*z - y + 2*x**2 assert roots(f, z) == { S.One: 1, S.Half + S.Half*y + S.Half*sqrt(1 - 2*y + y**2 + 8*x**2): 1, S.Half + S.Half*y - S.Half*sqrt(1 - 2*y + y**2 + 8*x**2): 1, } assert roots(a*b*c*x**3 + 2*x**2 + 4*x + 8, x, cubics=False) == {} assert roots(a*b*c*x**3 + 2*x**2 + 4*x + 8, x, cubics=True) != {} assert roots(x**4 - 1, x, filter='Z') == {S.One: 1, -S.One: 1} assert roots(x**4 - 1, x, filter='I') == {I: 1, -I: 1} assert roots((x - 1)*(x + 1), x) == {S.One: 1, -S.One: 1} assert roots( (x - 1)*(x + 1), x, predicate=lambda r: r.is_positive) == {S.One: 1} assert roots(x**4 - 1, x, filter='Z', multiple=True) == [-S.One, S.One] assert roots(x**4 - 1, x, filter='I', multiple=True) == [I, -I] ar, br = symbols('a, b', real=True) p = x**2*(ar-br)**2 + 2*x*(br-ar) + 1 assert roots(p, x, filter='R') == {1/(ar - br): 2} assert roots(x**3, x, multiple=True) == [S.Zero, S.Zero, S.Zero] assert roots(1234, x, multiple=True) == [] f = x**6 - x**5 + x**4 - x**3 + x**2 - x + 1 assert roots(f) == { -I*sin(pi/7) + cos(pi/7): 1, -I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 1, -I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 1, I*sin(pi/7) + cos(pi/7): 1, I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 1, I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 1, } g = ((x**2 + 1)*f**2).expand() assert roots(g) == { -I*sin(pi/7) + cos(pi/7): 2, -I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 2, -I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 2, I*sin(pi/7) + cos(pi/7): 2, I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 2, I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 2, -I: 1, I: 1, } r = roots(x**3 + 40*x + 64) real_root = [rx for rx in r if rx.is_real][0] cr = 108 + 6*sqrt(1074) assert real_root == -2*root(cr, 3)/3 + 20/root(cr, 3) eq = Poly((7 + 5*sqrt(2))*x**3 + (-6 - 4*sqrt(2))*x**2 + (-sqrt(2) - 1)*x + 2, x, domain='EX') assert roots(eq) == {-1 + sqrt(2): 1, -2 + 2*sqrt(2): 1, -sqrt(2) + 1: 1} eq = Poly(41*x**5 + 29*sqrt(2)*x**5 - 153*x**4 - 108*sqrt(2)*x**4 + 175*x**3 + 125*sqrt(2)*x**3 - 45*x**2 - 30*sqrt(2)*x**2 - 26*sqrt(2)*x - 26*x + 24, x, domain='EX') assert roots(eq) == {-sqrt(2) + 1: 1, -2 + 2*sqrt(2): 1, -1 + sqrt(2): 1, -4 + 4*sqrt(2): 1, -3 + 3*sqrt(2): 1} eq = Poly(x**3 - 2*x**2 + 6*sqrt(2)*x**2 - 8*sqrt(2)*x + 23*x - 14 + 14*sqrt(2), x, domain='EX') assert roots(eq) == {-2*sqrt(2) + 2: 1, -2*sqrt(2) + 1: 1, -2*sqrt(2) - 1: 1} assert roots(Poly((x + sqrt(2))**3 - 7, x, domain='EX')) == \ {-sqrt(2) + root(7, 3)*(-S.Half - sqrt(3)*I/2): 1, -sqrt(2) + root(7, 3)*(-S.Half + sqrt(3)*I/2): 1, -sqrt(2) + root(7, 3): 1} def test_roots_slow(): """Just test that calculating these roots does not hang. """ a, b, c, d, x = symbols("a,b,c,d,x") f1 = x**2*c + (a/b) + x*c*d - a f2 = x**2*(a + b*(c - d)*a) + x*a*b*c/(b*d - d) + (a*d - c/d) assert list(roots(f1, x).values()) == [1, 1] assert list(roots(f2, x).values()) == [1, 1] (zz, yy, xx, zy, zx, yx, k) = symbols("zz,yy,xx,zy,zx,yx,k") e1 = (zz - k)*(yy - k)*(xx - k) + zy*yx*zx + zx - zy - yx e2 = (zz - k)*yx*yx + zx*(yy - k)*zx + zy*zy*(xx - k) assert list(roots(e1 - e2, k).values()) == [1, 1, 1] f = x**3 + 2*x**2 + 8 R = list(roots(f).keys()) assert not any(i for i in [f.subs(x, ri).n(chop=True) for ri in R]) def test_roots_inexact(): R1 = roots(x**2 + x + 1, x, multiple=True) R2 = roots(x**2 + x + 1.0, x, multiple=True) for r1, r2 in zip(R1, R2): assert abs(r1 - r2) < 1e-12 f = x**4 + 3.0*sqrt(2.0)*x**3 - (78.0 + 24.0*sqrt(3.0))*x**2 \ + 144.0*(2*sqrt(3.0) + 9.0) R1 = roots(f, multiple=True) R2 = (-12.7530479110482, -3.85012393732929, 4.89897948556636, 7.46155167569183) for r1, r2 in zip(R1, R2): assert abs(r1 - r2) < 1e-10 def test_roots_preprocessed(): E, F, J, L = symbols("E,F,J,L") f = -21601054687500000000*E**8*J**8/L**16 + \ 508232812500000000*F*x*E**7*J**7/L**14 - \ 4269543750000000*E**6*F**2*J**6*x**2/L**12 + \ 16194716250000*E**5*F**3*J**5*x**3/L**10 - \ 27633173750*E**4*F**4*J**4*x**4/L**8 + \ 14840215*E**3*F**5*J**3*x**5/L**6 + \ 54794*E**2*F**6*J**2*x**6/(5*L**4) - \ 1153*E*J*F**7*x**7/(80*L**2) + \ 633*F**8*x**8/160000 assert roots(f, x) == {} R1 = roots(f.evalf(), x, multiple=True) R2 = [-1304.88375606366, 97.1168816800648, 186.946430171876, 245.526792947065, 503.441004174773, 791.549343830097, 1273.16678129348, 1850.10650616851] w = Wild('w') p = w*E*J/(F*L**2) assert len(R1) == len(R2) for r1, r2 in zip(R1, R2): match = r1.match(p) assert match is not None and abs(match[w] - r2) < 1e-10 def test_roots_strict(): assert roots(x**2 - 2*x + 1, strict=False) == {1: 2} assert roots(x**2 - 2*x + 1, strict=True) == {1: 2} assert roots(x**6 - 2*x**5 - x**2 + 3*x - 2, strict=False) == {2: 1} raises(UnsolvableFactorError, lambda: roots(x**6 - 2*x**5 - x**2 + 3*x - 2, strict=True)) def test_roots_mixed(): f = -1936 - 5056*x - 7592*x**2 + 2704*x**3 - 49*x**4 _re, _im = intervals(f, all=True) _nroots = nroots(f) _sroots = roots(f, multiple=True) _re = [ Interval(a, b) for (a, b), _ in _re ] _im = [ Interval(re(a), re(b))*Interval(im(a), im(b)) for (a, b), _ in _im ] _intervals = _re + _im _sroots = [ r.evalf() for r in _sroots ] _nroots = sorted(_nroots, key=lambda x: x.sort_key()) _sroots = sorted(_sroots, key=lambda x: x.sort_key()) for _roots in (_nroots, _sroots): for i, r in zip(_intervals, _roots): if r.is_real: assert r in i else: assert (re(r), im(r)) in i def test_root_factors(): assert root_factors(Poly(1, x)) == [Poly(1, x)] assert root_factors(Poly(x, x)) == [Poly(x, x)] assert root_factors(x**2 - 1, x) == [x + 1, x - 1] assert root_factors(x**2 - y, x) == [x - sqrt(y), x + sqrt(y)] assert root_factors((x**4 - 1)**2) == \ [x + 1, x + 1, x - 1, x - 1, x - I, x - I, x + I, x + I] assert root_factors(Poly(x**4 - 1, x), filter='Z') == \ [Poly(x + 1, x), Poly(x - 1, x), Poly(x**2 + 1, x)] assert root_factors(8*x**2 + 12*x**4 + 6*x**6 + x**8, x, filter='Q') == \ [x, x, x**6 + 6*x**4 + 12*x**2 + 8] @slow def test_nroots1(): n = 64 p = legendre_poly(n, x, polys=True) raises(mpmath.mp.NoConvergence, lambda: p.nroots(n=3, maxsteps=5)) roots = p.nroots(n=3) # The order of roots matters. They are ordered from smallest to the # largest. assert [str(r) for r in roots] == \ ['-0.999', '-0.996', '-0.991', '-0.983', '-0.973', '-0.961', '-0.946', '-0.930', '-0.911', '-0.889', '-0.866', '-0.841', '-0.813', '-0.784', '-0.753', '-0.720', '-0.685', '-0.649', '-0.611', '-0.572', '-0.531', '-0.489', '-0.446', '-0.402', '-0.357', '-0.311', '-0.265', '-0.217', '-0.170', '-0.121', '-0.0730', '-0.0243', '0.0243', '0.0730', '0.121', '0.170', '0.217', '0.265', '0.311', '0.357', '0.402', '0.446', '0.489', '0.531', '0.572', '0.611', '0.649', '0.685', '0.720', '0.753', '0.784', '0.813', '0.841', '0.866', '0.889', '0.911', '0.930', '0.946', '0.961', '0.973', '0.983', '0.991', '0.996', '0.999'] def test_nroots2(): p = Poly(x**5 + 3*x + 1, x) roots = p.nroots(n=3) # The order of roots matters. The roots are ordered by their real # components (if they agree, then by their imaginary components), # with real roots appearing first. assert [str(r) for r in roots] == \ ['-0.332', '-0.839 - 0.944*I', '-0.839 + 0.944*I', '1.01 - 0.937*I', '1.01 + 0.937*I'] roots = p.nroots(n=5) assert [str(r) for r in roots] == \ ['-0.33199', '-0.83907 - 0.94385*I', '-0.83907 + 0.94385*I', '1.0051 - 0.93726*I', '1.0051 + 0.93726*I'] def test_roots_composite(): assert len(roots(Poly(y**3 + y**2*sqrt(x) + y + x, y, composite=True))) == 3 def test_issue_19113(): eq = cos(x)**3 - cos(x) + 1 raises(PolynomialError, lambda: roots(eq)) def test_issue_17454(): assert roots([1, -3*(-4 - 4*I)**2/8 + 12*I, 0], multiple=True) == [0, 0] def test_issue_20913(): assert Poly(x + 9671406556917067856609794, x).real_roots() == [-9671406556917067856609794] assert Poly(x**3 + 4, x).real_roots() == [-2**(S(2)/3)] def test_issue_22768(): e = Rational(1, 3) r = (-1/a)**e*(a + 1)**(5*e) assert roots(Poly(a*x**3 + (a + 1)**5, x)) == { r: 1, -r*(1 + sqrt(3)*I)/2: 1, r*(-1 + sqrt(3)*I)/2: 1}
c0fc1354e94436428eee90d2914d0fb62dcdb38d52378326908ca86f1f741e99
from sympy.testing.pytest import raises, XFAIL from sympy.external import import_module from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.function import (Derivative, Function) from sympy.core.mul import Mul from sympy.core.numbers import (E, oo) from sympy.core.power import Pow from sympy.core.relational import (GreaterThan, LessThan, StrictGreaterThan, StrictLessThan, Unequality) from sympy.core.symbol import Symbol from sympy.functions.combinatorial.factorials import (binomial, factorial) from sympy.functions.elementary.complexes import (Abs, conjugate) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.integers import (ceiling, floor) from sympy.functions.elementary.miscellaneous import (root, sqrt) from sympy.functions.elementary.trigonometric import (asin, cos, csc, sec, sin, tan) from sympy.integrals.integrals import Integral from sympy.series.limits import Limit from sympy.core.relational import Eq, Ne, Lt, Le, Gt, Ge from sympy.physics.quantum.state import Bra, Ket from sympy.abc import x, y, z, a, b, c, t, k, n antlr4 = import_module("antlr4") # disable tests if antlr4-python3-runtime is not present if not antlr4: disabled = True theta = Symbol('theta') f = Function('f') # shorthand definitions def _Add(a, b): return Add(a, b, evaluate=False) def _Mul(a, b): return Mul(a, b, evaluate=False) def _Pow(a, b): return Pow(a, b, evaluate=False) def _Sqrt(a): return sqrt(a, evaluate=False) def _Conjugate(a): return conjugate(a, evaluate=False) def _Abs(a): return Abs(a, evaluate=False) def _factorial(a): return factorial(a, evaluate=False) def _exp(a): return exp(a, evaluate=False) def _log(a, b): return log(a, b, evaluate=False) def _binomial(n, k): return binomial(n, k, evaluate=False) def test_import(): from sympy.parsing.latex._build_latex_antlr import ( build_parser, check_antlr_version, dir_latex_antlr ) # XXX: It would be better to come up with a test for these... del build_parser, check_antlr_version, dir_latex_antlr # These LaTeX strings should parse to the corresponding SymPy expression GOOD_PAIRS = [ (r"0", 0), (r"1", 1), (r"-3.14", -3.14), (r"(-7.13)(1.5)", _Mul(-7.13, 1.5)), (r"x", x), (r"2x", 2*x), (r"x^2", x**2), (r"x^\frac{1}{2}", _Pow(x, _Pow(2, -1))), (r"x^{3 + 1}", x**_Add(3, 1)), (r"-c", -c), (r"a \cdot b", a * b), (r"a / b", a / b), (r"a \div b", a / b), (r"a + b", a + b), (r"a + b - a", _Add(a+b, -a)), (r"a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)), (r"(x + y) z", _Mul(_Add(x, y), z)), (r"a'b+ab'", _Add(_Mul(Symbol("a'"), b), _Mul(a, Symbol("b'")))), (r"y''_1", Symbol("y_{1}''")), (r"y_1''", Symbol("y_{1}''")), (r"\left(x + y\right) z", _Mul(_Add(x, y), z)), (r"\left( x + y\right ) z", _Mul(_Add(x, y), z)), (r"\left( x + y\right ) z", _Mul(_Add(x, y), z)), (r"\left[x + y\right] z", _Mul(_Add(x, y), z)), (r"\left\{x + y\right\} z", _Mul(_Add(x, y), z)), (r"1+1", _Add(1, 1)), (r"0+1", _Add(0, 1)), (r"1*2", _Mul(1, 2)), (r"0*1", _Mul(0, 1)), (r"1 \times 2 ", _Mul(1, 2)), (r"x = y", Eq(x, y)), (r"x \neq y", Ne(x, y)), (r"x < y", Lt(x, y)), (r"x > y", Gt(x, y)), (r"x \leq y", Le(x, y)), (r"x \geq y", Ge(x, y)), (r"x \le y", Le(x, y)), (r"x \ge y", Ge(x, y)), (r"\lfloor x \rfloor", floor(x)), (r"\lceil x \rceil", ceiling(x)), (r"\langle x |", Bra('x')), (r"| x \rangle", Ket('x')), (r"\sin \theta", sin(theta)), (r"\sin(\theta)", sin(theta)), (r"\sin^{-1} a", asin(a)), (r"\sin a \cos b", _Mul(sin(a), cos(b))), (r"\sin \cos \theta", sin(cos(theta))), (r"\sin(\cos \theta)", sin(cos(theta))), (r"\frac{a}{b}", a / b), (r"\dfrac{a}{b}", a / b), (r"\tfrac{a}{b}", a / b), (r"\frac12", _Pow(2, -1)), (r"\frac12y", _Mul(_Pow(2, -1), y)), (r"\frac1234", _Mul(_Pow(2, -1), 34)), (r"\frac2{3}", _Mul(2, _Pow(3, -1))), (r"\frac{\sin{x}}2", _Mul(sin(x), _Pow(2, -1))), (r"\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))), (r"\frac{7}{3}", _Mul(7, _Pow(3, -1))), (r"(\csc x)(\sec y)", csc(x)*sec(y)), (r"\lim_{x \to 3} a", Limit(a, x, 3)), (r"\lim_{x \rightarrow 3} a", Limit(a, x, 3)), (r"\lim_{x \Rightarrow 3} a", Limit(a, x, 3)), (r"\lim_{x \longrightarrow 3} a", Limit(a, x, 3)), (r"\lim_{x \Longrightarrow 3} a", Limit(a, x, 3)), (r"\lim_{x \to 3^{+}} a", Limit(a, x, 3, dir='+')), (r"\lim_{x \to 3^{-}} a", Limit(a, x, 3, dir='-')), (r"\lim_{x \to 3^+} a", Limit(a, x, 3, dir='+')), (r"\lim_{x \to 3^-} a", Limit(a, x, 3, dir='-')), (r"\infty", oo), (r"\lim_{x \to \infty} \frac{1}{x}", Limit(_Pow(x, -1), x, oo)), (r"\frac{d}{dx} x", Derivative(x, x)), (r"\frac{d}{dt} x", Derivative(x, t)), (r"f(x)", f(x)), (r"f(x, y)", f(x, y)), (r"f(x, y, z)", f(x, y, z)), (r"f'_1(x)", Function("f_{1}'")(x)), (r"f_{1}''(x+y)", Function("f_{1}''")(x+y)), (r"\frac{d f(x)}{dx}", Derivative(f(x), x)), (r"\frac{d\theta(x)}{dx}", Derivative(Function('theta')(x), x)), (r"x \neq y", Unequality(x, y)), (r"|x|", _Abs(x)), (r"||x||", _Abs(Abs(x))), (r"|x||y|", _Abs(x)*_Abs(y)), (r"||x||y||", _Abs(_Abs(x)*_Abs(y))), (r"\pi^{|xy|}", Symbol('pi')**_Abs(x*y)), (r"\int x dx", Integral(x, x)), (r"\int x d\theta", Integral(x, theta)), (r"\int (x^2 - y)dx", Integral(x**2 - y, x)), (r"\int x + a dx", Integral(_Add(x, a), x)), (r"\int da", Integral(1, a)), (r"\int_0^7 dx", Integral(1, (x, 0, 7))), (r"\int\limits_{0}^{1} x dx", Integral(x, (x, 0, 1))), (r"\int_a^b x dx", Integral(x, (x, a, b))), (r"\int^b_a x dx", Integral(x, (x, a, b))), (r"\int_{a}^b x dx", Integral(x, (x, a, b))), (r"\int^{b}_a x dx", Integral(x, (x, a, b))), (r"\int_{a}^{b} x dx", Integral(x, (x, a, b))), (r"\int^{b}_{a} x dx", Integral(x, (x, a, b))), (r"\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))), (r"\int (x+a)", Integral(_Add(x, a), x)), (r"\int a + b + c dx", Integral(_Add(_Add(a, b), c), x)), (r"\int \frac{dz}{z}", Integral(Pow(z, -1), z)), (r"\int \frac{3 dz}{z}", Integral(3*Pow(z, -1), z)), (r"\int \frac{1}{x} dx", Integral(Pow(x, -1), x)), (r"\int \frac{1}{a} + \frac{1}{b} dx", Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)), (r"\int \frac{3 \cdot d\theta}{\theta}", Integral(3*_Pow(theta, -1), theta)), (r"\int \frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)), (r"x_0", Symbol('x_{0}')), (r"x_{1}", Symbol('x_{1}')), (r"x_a", Symbol('x_{a}')), (r"x_{b}", Symbol('x_{b}')), (r"h_\theta", Symbol('h_{theta}')), (r"h_{\theta}", Symbol('h_{theta}')), (r"h_{\theta}(x_0, x_1)", Function('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}'))), (r"x!", _factorial(x)), (r"100!", _factorial(100)), (r"\theta!", _factorial(theta)), (r"(x + 1)!", _factorial(_Add(x, 1))), (r"(x!)!", _factorial(_factorial(x))), (r"x!!!", _factorial(_factorial(_factorial(x)))), (r"5!7!", _Mul(_factorial(5), _factorial(7))), (r"\sqrt{x}", sqrt(x)), (r"\sqrt{x + b}", sqrt(_Add(x, b))), (r"\sqrt[3]{\sin x}", root(sin(x), 3)), (r"\sqrt[y]{\sin x}", root(sin(x), y)), (r"\sqrt[\theta]{\sin x}", root(sin(x), theta)), (r"\sqrt{\frac{12}{6}}", _Sqrt(_Mul(12, _Pow(6, -1)))), (r"\overline{z}", _Conjugate(z)), (r"\overline{\overline{z}}", _Conjugate(_Conjugate(z))), (r"\overline{x + y}", _Conjugate(_Add(x, y))), (r"\overline{x} + \overline{y}", _Conjugate(x) + _Conjugate(y)), (r"x < y", StrictLessThan(x, y)), (r"x \leq y", LessThan(x, y)), (r"x > y", StrictGreaterThan(x, y)), (r"x \geq y", GreaterThan(x, y)), (r"\mathit{x}", Symbol('x')), (r"\mathit{test}", Symbol('test')), (r"\mathit{TEST}", Symbol('TEST')), (r"\mathit{HELLO world}", Symbol('HELLO world')), (r"\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))), (r"\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))), (r"\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))), (r"\sum^3_{k = 1} c", Sum(c, (k, 1, 3))), (r"\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))), (r"\sum_{n = 0}^{\infty} \frac{1}{n!}", Sum(_Pow(_factorial(n), -1), (n, 0, oo))), (r"\prod_{a = b}^{c} x", Product(x, (a, b, c))), (r"\prod_{a = b}^c x", Product(x, (a, b, c))), (r"\prod^{c}_{a = b} x", Product(x, (a, b, c))), (r"\prod^c_{a = b} x", Product(x, (a, b, c))), (r"\exp x", _exp(x)), (r"\exp(x)", _exp(x)), (r"\lg x", _log(x, 10)), (r"\ln x", _log(x, E)), (r"\ln xy", _log(x*y, E)), (r"\log x", _log(x, E)), (r"\log xy", _log(x*y, E)), (r"\log_{2} x", _log(x, 2)), (r"\log_{a} x", _log(x, a)), (r"\log_{11} x", _log(x, 11)), (r"\log_{a^2} x", _log(x, _Pow(a, 2))), (r"[x]", x), (r"[a + b]", _Add(a, b)), (r"\frac{d}{dx} [ \tan x ]", Derivative(tan(x), x)), (r"\binom{n}{k}", _binomial(n, k)), (r"\tbinom{n}{k}", _binomial(n, k)), (r"\dbinom{n}{k}", _binomial(n, k)), (r"\binom{n}{0}", _binomial(n, 0)), (r"x^\binom{n}{k}", _Pow(x, _binomial(n, k))), (r"a \, b", _Mul(a, b)), (r"a \thinspace b", _Mul(a, b)), (r"a \: b", _Mul(a, b)), (r"a \medspace b", _Mul(a, b)), (r"a \; b", _Mul(a, b)), (r"a \thickspace b", _Mul(a, b)), (r"a \quad b", _Mul(a, b)), (r"a \qquad b", _Mul(a, b)), (r"a \! b", _Mul(a, b)), (r"a \negthinspace b", _Mul(a, b)), (r"a \negmedspace b", _Mul(a, b)), (r"a \negthickspace b", _Mul(a, b)), (r"\int x \, dx", Integral(x, x)), (r"\log_2 x", _log(x, 2)), (r"\log_a x", _log(x, a)), (r"5^0 - 4^0", _Add(_Pow(5, 0), _Mul(-1, _Pow(4, 0)))), (r"3x - 1", _Add(_Mul(3, x), -1)) ] def test_parseable(): from sympy.parsing.latex import parse_latex for latex_str, sympy_expr in GOOD_PAIRS: assert parse_latex(latex_str) == sympy_expr, latex_str # These bad LaTeX strings should raise a LaTeXParsingError when parsed BAD_STRINGS = [ r"(", r")", r"\frac{d}{dx}", r"(\frac{d}{dx})", r"\sqrt{}", r"\sqrt", r"\overline{}", r"\overline", r"{", r"}", r"\mathit{x + y}", r"\mathit{21}", r"\frac{2}{}", r"\frac{}{2}", r"\int", r"!", r"!0", r"_", r"^", r"|", r"||x|", r"()", r"((((((((((((((((()))))))))))))))))", r"-", r"\frac{d}{dx} + \frac{d}{dt}", r"f(x,,y)", r"f(x,y,", r"\sin^x", r"\cos^2", r"@", r"#", r"$", r"%", r"&", r"*", r"" "\\", r"~", r"\frac{(2 + x}{1 - x)}", ] def test_not_parseable(): from sympy.parsing.latex import parse_latex, LaTeXParsingError for latex_str in BAD_STRINGS: with raises(LaTeXParsingError): parse_latex(latex_str) # At time of migration from latex2sympy, should fail but doesn't FAILING_BAD_STRINGS = [ r"\cos 1 \cos", r"f(,", r"f()", r"a \div \div b", r"a \cdot \cdot b", r"a // b", r"a +", r"1.1.1", r"1 +", r"a / b /", ] @XFAIL def test_failing_not_parseable(): from sympy.parsing.latex import parse_latex, LaTeXParsingError for latex_str in FAILING_BAD_STRINGS: with raises(LaTeXParsingError): parse_latex(latex_str)
99af5833e0ad8b884c8636729b944c19a7acc5a5a48baa76f5044e278a12b381
from sympy import sin, Function, symbols, Dummy, Lambda, cos from sympy.parsing.mathematica import parse_mathematica, MathematicaParser from sympy.core.sympify import sympify from sympy.abc import n, w, x, y, z from sympy.testing.pytest import raises def test_mathematica(): d = { '- 6x': '-6*x', 'Sin[x]^2': 'sin(x)**2', '2(x-1)': '2*(x-1)', '3y+8': '3*y+8', 'ArcSin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x', 'x+y': 'x+y', '355/113': '355/113', '2.718281828': '2.718281828', 'Cos(1/2 * Ο€)': 'Cos(Ο€/2)', 'Sin[12]': 'sin(12)', 'Exp[Log[4]]': 'exp(log(4))', '(x+1)(x+3)': '(x+1)*(x+3)', 'Cos[ArcCos[3.6]]': 'cos(acos(3.6))', 'Cos[x]==Sin[y]': 'Eq(cos(x), sin(y))', '2*Sin[x+y]': '2*sin(x+y)', 'Sin[x]+Cos[y]': 'sin(x)+cos(y)', 'Sin[Cos[x]]': 'sin(cos(x))', '2*Sqrt[x+y]': '2*sqrt(x+y)', # Test case from the issue 4259 '+Sqrt[2]': 'sqrt(2)', '-Sqrt[2]': '-sqrt(2)', '-1/Sqrt[2]': '-1/sqrt(2)', '-(1/Sqrt[3])': '-(1/sqrt(3))', '1/(2*Sqrt[5])': '1/(2*sqrt(5))', 'Mod[5,3]': 'Mod(5,3)', '-Mod[5,3]': '-Mod(5,3)', '(x+1)y': '(x+1)*y', 'x(y+1)': 'x*(y+1)', 'Sin[x]Cos[y]': 'sin(x)*cos(y)', 'Sin[x]^2Cos[y]^2': 'sin(x)**2*cos(y)**2', 'Cos[x]^2(1 - Cos[y]^2)': 'cos(x)**2*(1-cos(y)**2)', 'x y': 'x*y', 'x y': 'x*y', '2 x': '2*x', 'x 8': 'x*8', '2 8': '2*8', '4.x': '4.*x', '4. 3': '4.*3', '4. 3.': '4.*3.', '1 2 3': '1*2*3', ' - 2 * Sqrt[ 2 3 * ( 1 + 5 ) ] ': '-2*sqrt(2*3*(1+5))', 'Log[2,4]': 'log(4,2)', 'Log[Log[2,4],4]': 'log(4,log(4,2))', 'Exp[Sqrt[2]^2Log[2, 8]]': 'exp(sqrt(2)**2*log(8,2))', 'ArcSin[Cos[0]]': 'asin(cos(0))', 'Log2[16]': 'log(16,2)', 'Max[1,-2,3,-4]': 'Max(1,-2,3,-4)', 'Min[1,-2,3]': 'Min(1,-2,3)', 'Exp[I Pi/2]': 'exp(I*pi/2)', 'ArcTan[x,y]': 'atan2(y,x)', 'Pochhammer[x,y]': 'rf(x,y)', 'ExpIntegralEi[x]': 'Ei(x)', 'SinIntegral[x]': 'Si(x)', 'CosIntegral[x]': 'Ci(x)', 'AiryAi[x]': 'airyai(x)', 'AiryAiPrime[5]': 'airyaiprime(5)', 'AiryBi[x]': 'airybi(x)', 'AiryBiPrime[7]': 'airybiprime(7)', 'LogIntegral[4]': ' li(4)', 'PrimePi[7]': 'primepi(7)', 'Prime[5]': 'prime(5)', 'PrimeQ[5]': 'isprime(5)' } for e in d: assert parse_mathematica(e) == sympify(d[e]) # The parsed form of this expression should not evaluate the Lambda object: assert parse_mathematica("Sin[#]^2 + Cos[#]^2 &[x]") == sin(x)**2 + cos(x)**2 d1, d2, d3 = symbols("d1:4", cls=Dummy) assert parse_mathematica("Sin[#] + Cos[#3] &").dummy_eq(Lambda((d1, d2, d3), sin(d1) + cos(d3))) assert parse_mathematica("Sin[#^2] &").dummy_eq(Lambda(d1, sin(d1**2))) assert parse_mathematica("Function[x, x^3]") == Lambda(x, x**3) assert parse_mathematica("Function[{x, y}, x^2 + y^2]") == Lambda((x, y), x**2 + y**2) def test_parser_mathematica_tokenizer(): parser = MathematicaParser() chain = lambda expr: parser._from_tokens_to_fullformlist(parser._from_mathematica_to_tokens(expr)) # Basic patterns assert chain("x") == "x" assert chain("42") == "42" assert chain(".2") == ".2" assert chain("+x") == "x" assert chain("-1") == "-1" assert chain("- 3") == "-3" assert chain("Ξ±") == "Ξ±" assert chain("+Sin[x]") == ["Sin", "x"] assert chain("-Sin[x]") == ["Times", "-1", ["Sin", "x"]] assert chain("x(a+1)") == ["Times", "x", ["Plus", "a", "1"]] assert chain("(x)") == "x" assert chain("(+x)") == "x" assert chain("-a") == ["Times", "-1", "a"] assert chain("(-x)") == ["Times", "-1", "x"] assert chain("(x + y)") == ["Plus", "x", "y"] assert chain("3 + 4") == ["Plus", "3", "4"] assert chain("a - 3") == ["Plus", "a", "-3"] assert chain("a - b") == ["Plus", "a", ["Times", "-1", "b"]] assert chain("7 * 8") == ["Times", "7", "8"] assert chain("a + b*c") == ["Plus", "a", ["Times", "b", "c"]] assert chain("a + b* c* d + 2 * e") == ["Plus", "a", ["Times", "b", "c", "d"], ["Times", "2", "e"]] assert chain("a / b") == ["Times", "a", ["Power", "b", "-1"]] # Missing asterisk (*) patterns: assert chain("x y") == ["Times", "x", "y"] assert chain("3 4") == ["Times", "3", "4"] assert chain("a[b] c") == ["Times", ["a", "b"], "c"] assert chain("(x) (y)") == ["Times", "x", "y"] assert chain("3 (a)") == ["Times", "3", "a"] assert chain("(a) b") == ["Times", "a", "b"] assert chain("4.2") == "4.2" assert chain("4 2") == ["Times", "4", "2"] assert chain("4 2") == ["Times", "4", "2"] assert chain("3 . 4") == ["Dot", "3", "4"] assert chain("4. 2") == ["Times", "4.", "2"] assert chain("x.y") == ["Dot", "x", "y"] assert chain("4.y") == ["Times", "4.", "y"] assert chain("4 .y") == ["Dot", "4", "y"] assert chain("x.4") == ["Times", "x", ".4"] assert chain("x0.3") == ["Times", "x0", ".3"] assert chain("x. 4") == ["Dot", "x", "4"] # Comments assert chain("a (* +b *) + c") == ["Plus", "a", "c"] assert chain("a (* + b *) + (**)c (* +d *) + e") == ["Plus", "a", "c", "e"] assert chain("""a + (* + b *) c + (* d *) e """) == ["Plus", "a", "c", "e"] # Operators couples + and -, * and / are mutually associative: # (i.e. expression gets flattened when mixing these operators) assert chain("a*b/c") == ["Times", "a", "b", ["Power", "c", "-1"]] assert chain("a/b*c") == ["Times", "a", ["Power", "b", "-1"], "c"] assert chain("a+b-c") == ["Plus", "a", "b", ["Times", "-1", "c"]] assert chain("a-b+c") == ["Plus", "a", ["Times", "-1", "b"], "c"] assert chain("-a + b -c ") == ["Plus", ["Times", "-1", "a"], "b", ["Times", "-1", "c"]] assert chain("a/b/c*d") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"], "d"] assert chain("a/b/c") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"]] assert chain("a-b-c") == ["Plus", "a", ["Times", "-1", "b"], ["Times", "-1", "c"]] assert chain("1/a") == ["Times", "1", ["Power", "a", "-1"]] assert chain("1/a/b") == ["Times", "1", ["Power", "a", "-1"], ["Power", "b", "-1"]] assert chain("-1/a*b") == ["Times", "-1", ["Power", "a", "-1"], "b"] # Enclosures of various kinds, i.e. ( ) [ ] [[ ]] { } assert chain("(a + b) + c") == ["Plus", ["Plus", "a", "b"], "c"] assert chain(" a + (b + c) + d ") == ["Plus", "a", ["Plus", "b", "c"], "d"] assert chain("a * (b + c)") == ["Times", "a", ["Plus", "b", "c"]] assert chain("a b (c d)") == ["Times", "a", "b", ["Times", "c", "d"]] assert chain("{a, b, 2, c}") == ["List", "a", "b", "2", "c"] assert chain("{a, {b, c}}") == ["List", "a", ["List", "b", "c"]] assert chain("{{a}}") == ["List", ["List", "a"]] assert chain("a[b, c]") == ["a", "b", "c"] assert chain("a[[b, c]]") == ["Part", "a", "b", "c"] assert chain("a[b[c]]") == ["a", ["b", "c"]] assert chain("a[[b, c[[d, {e,f}]]]]") == ["Part", "a", "b", ["Part", "c", "d", ["List", "e", "f"]]] assert chain("a[b[[c,d]]]") == ["a", ["Part", "b", "c", "d"]] assert chain("a[[b[c]]]") == ["Part", "a", ["b", "c"]] assert chain("a[[b[[c]]]]") == ["Part", "a", ["Part", "b", "c"]] assert chain("a[[b[c[[d]]]]]") == ["Part", "a", ["b", ["Part", "c", "d"]]] assert chain("a[b[[c[d]]]]") == ["a", ["Part", "b", ["c", "d"]]] assert chain("x[[a+1, b+2, c+3]]") == ["Part", "x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] assert chain("x[a+1, b+2, c+3]") == ["x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] assert chain("{a+1, b+2, c+3}") == ["List", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] # Flat operator: assert chain("a*b*c*d*e") == ["Times", "a", "b", "c", "d", "e"] assert chain("a +b + c+ d+e") == ["Plus", "a", "b", "c", "d", "e"] # Right priority operator: assert chain("a^b") == ["Power", "a", "b"] assert chain("a^b^c") == ["Power", "a", ["Power", "b", "c"]] assert chain("a^b^c^d") == ["Power", "a", ["Power", "b", ["Power", "c", "d"]]] # Left priority operator: assert chain("a/.b") == ["ReplaceAll", "a", "b"] assert chain("a/.b/.c/.d") == ["ReplaceAll", ["ReplaceAll", ["ReplaceAll", "a", "b"], "c"], "d"] assert chain("a//b") == ["a", "b"] assert chain("a//b//c") == [["a", "b"], "c"] assert chain("a//b//c//d") == [[["a", "b"], "c"], "d"] # Compound expressions assert chain("a;b") == ["CompoundExpression", "a", "b"] assert chain("a;") == ["CompoundExpression", "a", "Null"] assert chain("a;b;") == ["CompoundExpression", "a", "b", "Null"] assert chain("a[b;c]") == ["a", ["CompoundExpression", "b", "c"]] assert chain("a[b,c;d,e]") == ["a", "b", ["CompoundExpression", "c", "d"], "e"] assert chain("a[b,c;,d]") == ["a", "b", ["CompoundExpression", "c", "Null"], "d"] # New lines assert chain("a\nb\n") == ["CompoundExpression", "a", "b"] assert chain("a\n\nb\n (c \nd) \n") == ["CompoundExpression", "a", "b", ["Times", "c", "d"]] assert chain("\na; b\nc") == ["CompoundExpression", "a", "b", "c"] assert chain("a + \nb\n") == ["Plus", "a", "b"] assert chain("a\nb; c; d\n e; (f \n g); h + \n i") == ["CompoundExpression", "a", "b", "c", "d", "e", ["Times", "f", "g"], ["Plus", "h", "i"]] assert chain("\n{\na\nb; c; d\n e (f \n g); h + \n i\n\n}\n") == ["List", ["CompoundExpression", ["Times", "a", "b"], "c", ["Times", "d", "e", ["Times", "f", "g"]], ["Plus", "h", "i"]]] # Patterns assert chain("y_") == ["Pattern", "y", ["Blank"]] assert chain("y_.") == ["Optional", ["Pattern", "y", ["Blank"]]] assert chain("y__") == ["Pattern", "y", ["BlankSequence"]] assert chain("y___") == ["Pattern", "y", ["BlankNullSequence"]] assert chain("a[b_.,c_]") == ["a", ["Optional", ["Pattern", "b", ["Blank"]]], ["Pattern", "c", ["Blank"]]] assert chain("b_. c") == ["Times", ["Optional", ["Pattern", "b", ["Blank"]]], "c"] # Slots for lambda functions assert chain("#") == ["Slot", "1"] assert chain("#3") == ["Slot", "3"] assert chain("#n") == ["Slot", "n"] assert chain("##") == ["SlotSequence", "1"] assert chain("##a") == ["SlotSequence", "a"] # Lambda functions assert chain("x&") == ["Function", "x"] assert chain("#&") == ["Function", ["Slot", "1"]] assert chain("#+3&") == ["Function", ["Plus", ["Slot", "1"], "3"]] assert chain("#1 + #2&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]] assert chain("# + #&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "1"]]] assert chain("#&[x]") == [["Function", ["Slot", "1"]], "x"] assert chain("#1 + #2 & [x, y]") == [["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]], "x", "y"] assert chain("#1^2#2^3&") == ["Function", ["Times", ["Power", ["Slot", "1"], "2"], ["Power", ["Slot", "2"], "3"]]] # Strings inside Mathematica expressions: assert chain('"abc"') == ["_Str", "abc"] assert chain('"a\\"b"') == ["_Str", 'a"b'] # This expression does not make sense mathematically, it's just testing the parser: assert chain('x + "abc" ^ 3') == ["Plus", "x", ["Power", ["_Str", "abc"], "3"]] assert chain('"a (* b *) c"') == ["_Str", "a (* b *) c"] assert chain('"a" (* b *) ') == ["_Str", "a"] assert chain('"a [ b] "') == ["_Str", "a [ b] "] raises(SyntaxError, lambda: chain('"')) raises(SyntaxError, lambda: chain('"\\"')) raises(SyntaxError, lambda: chain('"abc')) raises(SyntaxError, lambda: chain('"abc\\"def')) # Invalid expressions: raises(SyntaxError, lambda: chain("(,")) raises(SyntaxError, lambda: chain("()")) raises(SyntaxError, lambda: chain("a (* b")) def test_parser_mathematica_exp_alt(): parser = MathematicaParser() convert_chain2 = lambda expr: parser._from_fullformlist_to_fullformsympy(parser._from_fullform_to_fullformlist(expr)) convert_chain3 = lambda expr: parser._from_fullformsympy_to_sympy(convert_chain2(expr)) Sin, Times, Plus, Power = symbols("Sin Times Plus Power", cls=Function) full_form1 = "Sin[Times[x, y]]" full_form2 = "Plus[Times[x, y], z]" full_form3 = "Sin[Times[x, Plus[y, z], Power[w, n]]]]" assert parser._from_fullform_to_fullformlist(full_form1) == ["Sin", ["Times", "x", "y"]] assert parser._from_fullform_to_fullformlist(full_form2) == ["Plus", ["Times", "x", "y"], "z"] assert parser._from_fullform_to_fullformlist(full_form3) == ["Sin", ["Times", "x", ["Plus", "y", "z"], ["Power", "w", "n"]]] assert convert_chain2(full_form1) == Sin(Times(x, y)) assert convert_chain2(full_form2) == Plus(Times(x, y), z) assert convert_chain2(full_form3) == Sin(Times(x, Plus(y, z), Power(w, n))) assert convert_chain3(full_form1) == sin(x*y) assert convert_chain3(full_form2) == x*y + z assert convert_chain3(full_form3) == sin(x*(y + z)*w**n)
6fd8486a5b8951dd55d97200a757ab6a4e94f9cf82c0ac832c7d5491842ebca1
from importlib.metadata import version from sympy.external import import_module autolevparser = import_module('sympy.parsing.autolev._antlr.autolevparser', import_kwargs={'fromlist': ['AutolevParser']}) autolevlexer = import_module('sympy.parsing.autolev._antlr.autolevlexer', import_kwargs={'fromlist': ['AutolevLexer']}) autolevlistener = import_module('sympy.parsing.autolev._antlr.autolevlistener', import_kwargs={'fromlist': ['AutolevListener']}) AutolevParser = getattr(autolevparser, 'AutolevParser', None) AutolevLexer = getattr(autolevlexer, 'AutolevLexer', None) AutolevListener = getattr(autolevlistener, 'AutolevListener', None) def parse_autolev(autolev_code, include_numeric): antlr4 = import_module('antlr4') if not antlr4 or not version('antlr4-python3-runtime').startswith('4.11'): raise ImportError("Autolev parsing requires the antlr4 Python package," " provided by pip (antlr4-python3-runtime)" " conda (antlr-python-runtime), version 4.11") try: l = autolev_code.readlines() input_stream = antlr4.InputStream("".join(l)) except Exception: input_stream = antlr4.InputStream(autolev_code) if AutolevListener: from ._listener_autolev_antlr import MyListener lexer = AutolevLexer(input_stream) token_stream = antlr4.CommonTokenStream(lexer) parser = AutolevParser(token_stream) tree = parser.prog() my_listener = MyListener(include_numeric) walker = antlr4.ParseTreeWalker() walker.walk(my_listener, tree) return "".join(my_listener.output_code)
70626c1aefa56e7b2d6359c9b0b09e93af120cf9316875122517fed57a33917c
# Ported from latex2sympy by @augustt198 # https://github.com/augustt198/latex2sympy # See license in LICENSE.txt from importlib.metadata import version import sympy from sympy.external import import_module from sympy.printing.str import StrPrinter from sympy.physics.quantum.state import Bra, Ket from .errors import LaTeXParsingError LaTeXParser = LaTeXLexer = MathErrorListener = None try: LaTeXParser = import_module('sympy.parsing.latex._antlr.latexparser', import_kwargs={'fromlist': ['LaTeXParser']}).LaTeXParser LaTeXLexer = import_module('sympy.parsing.latex._antlr.latexlexer', import_kwargs={'fromlist': ['LaTeXLexer']}).LaTeXLexer except Exception: pass ErrorListener = import_module('antlr4.error.ErrorListener', warn_not_installed=True, import_kwargs={'fromlist': ['ErrorListener']} ) if ErrorListener: class MathErrorListener(ErrorListener.ErrorListener): # type: ignore def __init__(self, src): super(ErrorListener.ErrorListener, self).__init__() self.src = src def syntaxError(self, recog, symbol, line, col, msg, e): fmt = "%s\n%s\n%s" marker = "~" * col + "^" if msg.startswith("missing"): err = fmt % (msg, self.src, marker) elif msg.startswith("no viable"): err = fmt % ("I expected something else here", self.src, marker) elif msg.startswith("mismatched"): names = LaTeXParser.literalNames expected = [ names[i] for i in e.getExpectedTokens() if i < len(names) ] if len(expected) < 10: expected = " ".join(expected) err = (fmt % ("I expected one of these: " + expected, self.src, marker)) else: err = (fmt % ("I expected something else here", self.src, marker)) else: err = fmt % ("I don't understand this", self.src, marker) raise LaTeXParsingError(err) def parse_latex(sympy): antlr4 = import_module('antlr4') if None in [antlr4, MathErrorListener] or \ not version('antlr4-python3-runtime').startswith('4.11'): raise ImportError("LaTeX parsing requires the antlr4 Python package," " provided by pip (antlr4-python3-runtime) or" " conda (antlr-python-runtime), version 4.11") matherror = MathErrorListener(sympy) stream = antlr4.InputStream(sympy) lex = LaTeXLexer(stream) lex.removeErrorListeners() lex.addErrorListener(matherror) tokens = antlr4.CommonTokenStream(lex) parser = LaTeXParser(tokens) # remove default console error listener parser.removeErrorListeners() parser.addErrorListener(matherror) relation = parser.math().relation() expr = convert_relation(relation) return expr def convert_relation(rel): if rel.expr(): return convert_expr(rel.expr()) lh = convert_relation(rel.relation(0)) rh = convert_relation(rel.relation(1)) if rel.LT(): return sympy.StrictLessThan(lh, rh) elif rel.LTE(): return sympy.LessThan(lh, rh) elif rel.GT(): return sympy.StrictGreaterThan(lh, rh) elif rel.GTE(): return sympy.GreaterThan(lh, rh) elif rel.EQUAL(): return sympy.Eq(lh, rh) elif rel.NEQ(): return sympy.Ne(lh, rh) def convert_expr(expr): return convert_add(expr.additive()) def convert_add(add): if add.ADD(): lh = convert_add(add.additive(0)) rh = convert_add(add.additive(1)) return sympy.Add(lh, rh, evaluate=False) elif add.SUB(): lh = convert_add(add.additive(0)) rh = convert_add(add.additive(1)) if hasattr(rh, "is_Atom") and rh.is_Atom: return sympy.Add(lh, -1 * rh, evaluate=False) return sympy.Add(lh, sympy.Mul(-1, rh, evaluate=False), evaluate=False) else: return convert_mp(add.mp()) def convert_mp(mp): if hasattr(mp, 'mp'): mp_left = mp.mp(0) mp_right = mp.mp(1) else: mp_left = mp.mp_nofunc(0) mp_right = mp.mp_nofunc(1) if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) return sympy.Mul(lh, rh, evaluate=False) elif mp.DIV() or mp.CMD_DIV() or mp.COLON(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False) else: if hasattr(mp, 'unary'): return convert_unary(mp.unary()) else: return convert_unary(mp.unary_nofunc()) def convert_unary(unary): if hasattr(unary, 'unary'): nested_unary = unary.unary() else: nested_unary = unary.unary_nofunc() if hasattr(unary, 'postfix_nofunc'): first = unary.postfix() tail = unary.postfix_nofunc() postfix = [first] + tail else: postfix = unary.postfix() if unary.ADD(): return convert_unary(nested_unary) elif unary.SUB(): numabs = convert_unary(nested_unary) # Use Integer(-n) instead of Mul(-1, n) return -numabs elif postfix: return convert_postfix_list(postfix) def convert_postfix_list(arr, i=0): if i >= len(arr): raise LaTeXParsingError("Index out of bounds") res = convert_postfix(arr[i]) if isinstance(res, sympy.Expr): if i == len(arr) - 1: return res # nothing to multiply by else: if i > 0: left = convert_postfix(arr[i - 1]) right = convert_postfix(arr[i + 1]) if isinstance(left, sympy.Expr) and isinstance( right, sympy.Expr): left_syms = convert_postfix(arr[i - 1]).atoms(sympy.Symbol) right_syms = convert_postfix(arr[i + 1]).atoms( sympy.Symbol) # if the left and right sides contain no variables and the # symbol in between is 'x', treat as multiplication. if not (left_syms or right_syms) and str(res) == 'x': return convert_postfix_list(arr, i + 1) # multiply by next return sympy.Mul( res, convert_postfix_list(arr, i + 1), evaluate=False) else: # must be derivative wrt = res[0] if i == len(arr) - 1: raise LaTeXParsingError("Expected expression for derivative") else: expr = convert_postfix_list(arr, i + 1) return sympy.Derivative(expr, wrt) def do_subs(expr, at): if at.expr(): at_expr = convert_expr(at.expr()) syms = at_expr.atoms(sympy.Symbol) if len(syms) == 0: return expr elif len(syms) > 0: sym = next(iter(syms)) return expr.subs(sym, at_expr) elif at.equality(): lh = convert_expr(at.equality().expr(0)) rh = convert_expr(at.equality().expr(1)) return expr.subs(lh, rh) def convert_postfix(postfix): if hasattr(postfix, 'exp'): exp_nested = postfix.exp() else: exp_nested = postfix.exp_nofunc() exp = convert_exp(exp_nested) for op in postfix.postfix_op(): if op.BANG(): if isinstance(exp, list): raise LaTeXParsingError("Cannot apply postfix to derivative") exp = sympy.factorial(exp, evaluate=False) elif op.eval_at(): ev = op.eval_at() at_b = None at_a = None if ev.eval_at_sup(): at_b = do_subs(exp, ev.eval_at_sup()) if ev.eval_at_sub(): at_a = do_subs(exp, ev.eval_at_sub()) if at_b is not None and at_a is not None: exp = sympy.Add(at_b, -1 * at_a, evaluate=False) elif at_b is not None: exp = at_b elif at_a is not None: exp = at_a return exp def convert_exp(exp): if hasattr(exp, 'exp'): exp_nested = exp.exp() else: exp_nested = exp.exp_nofunc() if exp_nested: base = convert_exp(exp_nested) if isinstance(base, list): raise LaTeXParsingError("Cannot raise derivative to power") if exp.atom(): exponent = convert_atom(exp.atom()) elif exp.expr(): exponent = convert_expr(exp.expr()) return sympy.Pow(base, exponent, evaluate=False) else: if hasattr(exp, 'comp'): return convert_comp(exp.comp()) else: return convert_comp(exp.comp_nofunc()) def convert_comp(comp): if comp.group(): return convert_expr(comp.group().expr()) elif comp.abs_group(): return sympy.Abs(convert_expr(comp.abs_group().expr()), evaluate=False) elif comp.atom(): return convert_atom(comp.atom()) elif comp.floor(): return convert_floor(comp.floor()) elif comp.ceil(): return convert_ceil(comp.ceil()) elif comp.func(): return convert_func(comp.func()) def convert_atom(atom): if atom.LETTER(): sname = atom.LETTER().getText() if atom.subexpr(): if atom.subexpr().expr(): # subscript is expr subscript = convert_expr(atom.subexpr().expr()) else: # subscript is atom subscript = convert_atom(atom.subexpr().atom()) sname += '_{' + StrPrinter().doprint(subscript) + '}' if atom.SINGLE_QUOTES(): sname += atom.SINGLE_QUOTES().getText() # put after subscript for easy identify return sympy.Symbol(sname) elif atom.SYMBOL(): s = atom.SYMBOL().getText()[1:] if s == "infty": return sympy.oo else: if atom.subexpr(): subscript = None if atom.subexpr().expr(): # subscript is expr subscript = convert_expr(atom.subexpr().expr()) else: # subscript is atom subscript = convert_atom(atom.subexpr().atom()) subscriptName = StrPrinter().doprint(subscript) s += '_{' + subscriptName + '}' return sympy.Symbol(s) elif atom.number(): s = atom.number().getText().replace(",", "") return sympy.Number(s) elif atom.DIFFERENTIAL(): var = get_differential_var(atom.DIFFERENTIAL()) return sympy.Symbol('d' + var.name) elif atom.mathit(): text = rule2text(atom.mathit().mathit_text()) return sympy.Symbol(text) elif atom.frac(): return convert_frac(atom.frac()) elif atom.binom(): return convert_binom(atom.binom()) elif atom.bra(): val = convert_expr(atom.bra().expr()) return Bra(val) elif atom.ket(): val = convert_expr(atom.ket().expr()) return Ket(val) def rule2text(ctx): stream = ctx.start.getInputStream() # starting index of starting token startIdx = ctx.start.start # stopping index of stopping token stopIdx = ctx.stop.stop return stream.getText(startIdx, stopIdx) def convert_frac(frac): diff_op = False partial_op = False if frac.lower and frac.upper: lower_itv = frac.lower.getSourceInterval() lower_itv_len = lower_itv[1] - lower_itv[0] + 1 if (frac.lower.start == frac.lower.stop and frac.lower.start.type == LaTeXLexer.DIFFERENTIAL): wrt = get_differential_var_str(frac.lower.start.text) diff_op = True elif (lower_itv_len == 2 and frac.lower.start.type == LaTeXLexer.SYMBOL and frac.lower.start.text == '\\partial' and (frac.lower.stop.type == LaTeXLexer.LETTER or frac.lower.stop.type == LaTeXLexer.SYMBOL)): partial_op = True wrt = frac.lower.stop.text if frac.lower.stop.type == LaTeXLexer.SYMBOL: wrt = wrt[1:] if diff_op or partial_op: wrt = sympy.Symbol(wrt) if (diff_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == LaTeXLexer.LETTER and frac.upper.start.text == 'd'): return [wrt] elif (partial_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == LaTeXLexer.SYMBOL and frac.upper.start.text == '\\partial'): return [wrt] upper_text = rule2text(frac.upper) expr_top = None if diff_op and upper_text.startswith('d'): expr_top = parse_latex(upper_text[1:]) elif partial_op and frac.upper.start.text == '\\partial': expr_top = parse_latex(upper_text[len('\\partial'):]) if expr_top: return sympy.Derivative(expr_top, wrt) if frac.upper: expr_top = convert_expr(frac.upper) else: expr_top = sympy.Number(frac.upperd.text) if frac.lower: expr_bot = convert_expr(frac.lower) else: expr_bot = sympy.Number(frac.lowerd.text) inverse_denom = sympy.Pow(expr_bot, -1, evaluate=False) if expr_top == 1: return inverse_denom else: return sympy.Mul(expr_top, inverse_denom, evaluate=False) def convert_binom(binom): expr_n = convert_expr(binom.n) expr_k = convert_expr(binom.k) return sympy.binomial(expr_n, expr_k, evaluate=False) def convert_floor(floor): val = convert_expr(floor.val) return sympy.floor(val, evaluate=False) def convert_ceil(ceil): val = convert_expr(ceil.val) return sympy.ceiling(val, evaluate=False) def convert_func(func): if func.func_normal(): if func.L_PAREN(): # function called with parenthesis arg = convert_func_arg(func.func_arg()) else: arg = convert_func_arg(func.func_arg_noparens()) name = func.func_normal().start.text[1:] # change arc<trig> -> a<trig> if name in [ "arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot" ]: name = "a" + name[3:] expr = getattr(sympy.functions, name)(arg, evaluate=False) if name in ["arsinh", "arcosh", "artanh"]: name = "a" + name[2:] expr = getattr(sympy.functions, name)(arg, evaluate=False) if name == "exp": expr = sympy.exp(arg, evaluate=False) if name in ("log", "lg", "ln"): if func.subexpr(): if func.subexpr().expr(): base = convert_expr(func.subexpr().expr()) else: base = convert_atom(func.subexpr().atom()) elif name == "lg": # ISO 80000-2:2019 base = 10 elif name in ("ln", "log"): # SymPy's latex printer prints ln as log by default base = sympy.E expr = sympy.log(arg, base, evaluate=False) func_pow = None should_pow = True if func.supexpr(): if func.supexpr().expr(): func_pow = convert_expr(func.supexpr().expr()) else: func_pow = convert_atom(func.supexpr().atom()) if name in [ "sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh", "tanh" ]: if func_pow == -1: name = "a" + name should_pow = False expr = getattr(sympy.functions, name)(arg, evaluate=False) if func_pow and should_pow: expr = sympy.Pow(expr, func_pow, evaluate=False) return expr elif func.LETTER() or func.SYMBOL(): if func.LETTER(): fname = func.LETTER().getText() elif func.SYMBOL(): fname = func.SYMBOL().getText()[1:] fname = str(fname) # can't be unicode if func.subexpr(): if func.subexpr().expr(): # subscript is expr subscript = convert_expr(func.subexpr().expr()) else: # subscript is atom subscript = convert_atom(func.subexpr().atom()) subscriptName = StrPrinter().doprint(subscript) fname += '_{' + subscriptName + '}' if func.SINGLE_QUOTES(): fname += func.SINGLE_QUOTES().getText() input_args = func.args() output_args = [] while input_args.args(): # handle multiple arguments to function output_args.append(convert_expr(input_args.expr())) input_args = input_args.args() output_args.append(convert_expr(input_args.expr())) return sympy.Function(fname)(*output_args) elif func.FUNC_INT(): return handle_integral(func) elif func.FUNC_SQRT(): expr = convert_expr(func.base) if func.root: r = convert_expr(func.root) return sympy.root(expr, r, evaluate=False) else: return sympy.sqrt(expr, evaluate=False) elif func.FUNC_OVERLINE(): expr = convert_expr(func.base) return sympy.conjugate(expr, evaluate=False) elif func.FUNC_SUM(): return handle_sum_or_prod(func, "summation") elif func.FUNC_PROD(): return handle_sum_or_prod(func, "product") elif func.FUNC_LIM(): return handle_limit(func) def convert_func_arg(arg): if hasattr(arg, 'expr'): return convert_expr(arg.expr()) else: return convert_mp(arg.mp_nofunc()) def handle_integral(func): if func.additive(): integrand = convert_add(func.additive()) elif func.frac(): integrand = convert_frac(func.frac()) else: integrand = 1 int_var = None if func.DIFFERENTIAL(): int_var = get_differential_var(func.DIFFERENTIAL()) else: for sym in integrand.atoms(sympy.Symbol): s = str(sym) if len(s) > 1 and s[0] == 'd': if s[1] == '\\': int_var = sympy.Symbol(s[2:]) else: int_var = sympy.Symbol(s[1:]) int_sym = sym if int_var: integrand = integrand.subs(int_sym, 1) else: # Assume dx by default int_var = sympy.Symbol('x') if func.subexpr(): if func.subexpr().atom(): lower = convert_atom(func.subexpr().atom()) else: lower = convert_expr(func.subexpr().expr()) if func.supexpr().atom(): upper = convert_atom(func.supexpr().atom()) else: upper = convert_expr(func.supexpr().expr()) return sympy.Integral(integrand, (int_var, lower, upper)) else: return sympy.Integral(integrand, int_var) def handle_sum_or_prod(func, name): val = convert_mp(func.mp()) iter_var = convert_expr(func.subeq().equality().expr(0)) start = convert_expr(func.subeq().equality().expr(1)) if func.supexpr().expr(): # ^{expr} end = convert_expr(func.supexpr().expr()) else: # ^atom end = convert_atom(func.supexpr().atom()) if name == "summation": return sympy.Sum(val, (iter_var, start, end)) elif name == "product": return sympy.Product(val, (iter_var, start, end)) def handle_limit(func): sub = func.limit_sub() if sub.LETTER(): var = sympy.Symbol(sub.LETTER().getText()) elif sub.SYMBOL(): var = sympy.Symbol(sub.SYMBOL().getText()[1:]) else: var = sympy.Symbol('x') if sub.SUB(): direction = "-" else: direction = "+" approaching = convert_expr(sub.expr()) content = convert_mp(func.mp()) return sympy.Limit(content, var, approaching, direction) def get_differential_var(d): text = get_differential_var_str(d.getText()) return sympy.Symbol(text) def get_differential_var_str(text): for i in range(1, len(text)): c = text[i] if not (c == " " or c == "\r" or c == "\n" or c == "\t"): idx = i break text = text[idx:] if text[0] == "\\": text = text[1:] return text
2bb1c5ffee5d532008bf5ffb1a48539b1a9209a9c4842a73246f1f6b20040774
# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND *** # # Generated with antlr4 # antlr4 is licensed under the BSD-3-Clause License # https://github.com/antlr/antlr4/blob/master/LICENSE.txt from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): return [ 4,0,49,393,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5, 2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2, 13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7, 19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2, 26,7,26,2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7, 32,2,33,7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2, 39,7,39,2,40,7,40,2,41,7,41,2,42,7,42,2,43,7,43,2,44,7,44,2,45,7, 45,2,46,7,46,2,47,7,47,2,48,7,48,2,49,7,49,2,50,7,50,1,0,1,0,1,1, 1,1,1,2,1,2,1,3,1,3,1,3,1,4,1,4,1,4,1,5,1,5,1,5,1,6,1,6,1,6,1,7, 1,7,1,7,1,8,1,8,1,8,1,9,1,9,1,10,1,10,1,11,1,11,1,12,1,12,1,13,1, 13,1,14,1,14,1,15,1,15,1,16,1,16,1,17,1,17,1,18,1,18,1,19,1,19,1, 20,1,20,1,21,1,21,1,21,1,22,1,22,1,22,1,22,1,23,1,23,1,24,1,24,1, 25,1,25,1,26,1,26,1,26,1,26,1,26,1,27,1,27,1,27,1,27,1,27,1,27,1, 27,1,27,1,28,1,28,1,28,1,28,1,28,1,28,3,28,184,8,28,1,29,1,29,1, 29,1,29,1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,30,1,31,1,31,1,31,1, 31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,32,1,32,1,32,1,32,1,32,1, 32,1,32,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,34,1, 34,1,34,1,34,1,34,1,34,3,34,232,8,34,1,35,1,35,1,35,1,35,1,35,1, 35,3,35,240,8,35,1,36,1,36,1,36,1,36,1,36,1,36,1,36,1,36,1,36,3, 36,251,8,36,1,37,1,37,1,37,1,37,1,37,1,37,3,37,259,8,37,1,38,1,38, 1,38,1,38,1,38,1,38,1,38,1,38,1,38,3,38,270,8,38,1,39,1,39,1,39, 1,39,1,39,1,39,1,39,1,39,1,39,1,39,3,39,282,8,39,1,40,1,40,1,40, 1,40,1,40,1,40,1,40,1,40,1,40,1,40,1,41,1,41,1,41,1,41,1,41,1,41, 1,41,1,41,1,41,3,41,303,8,41,1,42,1,42,1,42,1,42,1,42,1,42,1,42, 1,42,1,42,1,42,1,42,1,42,1,42,1,42,1,42,3,42,320,8,42,1,43,5,43, 323,8,43,10,43,12,43,326,9,43,1,44,1,44,1,45,4,45,331,8,45,11,45, 12,45,332,1,46,4,46,336,8,46,11,46,12,46,337,1,46,1,46,5,46,342, 8,46,10,46,12,46,345,9,46,1,46,1,46,4,46,349,8,46,11,46,12,46,350, 3,46,353,8,46,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,3,47, 364,8,47,1,48,1,48,5,48,368,8,48,10,48,12,48,371,9,48,1,48,3,48, 374,8,48,1,48,1,48,1,48,1,48,1,49,1,49,5,49,382,8,49,10,49,12,49, 385,9,49,1,50,4,50,388,8,50,11,50,12,50,389,1,50,1,50,1,369,0,51, 1,1,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13, 27,14,29,15,31,16,33,17,35,18,37,19,39,20,41,21,43,22,45,23,47,24, 49,25,51,26,53,27,55,28,57,29,59,30,61,31,63,32,65,33,67,34,69,35, 71,36,73,37,75,38,77,39,79,40,81,41,83,42,85,43,87,0,89,0,91,44, 93,45,95,46,97,47,99,48,101,49,1,0,24,2,0,77,77,109,109,2,0,65,65, 97,97,2,0,83,83,115,115,2,0,73,73,105,105,2,0,78,78,110,110,2,0, 69,69,101,101,2,0,82,82,114,114,2,0,84,84,116,116,2,0,80,80,112, 112,2,0,85,85,117,117,2,0,79,79,111,111,2,0,86,86,118,118,2,0,89, 89,121,121,2,0,67,67,99,99,2,0,68,68,100,100,2,0,87,87,119,119,2, 0,70,70,102,102,2,0,66,66,98,98,2,0,76,76,108,108,2,0,71,71,103, 103,1,0,48,57,2,0,65,90,97,122,4,0,48,57,65,90,95,95,97,122,4,0, 9,10,13,13,32,32,38,38,410,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0, 7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,17, 1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0,27, 1,0,0,0,0,29,1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,0,35,1,0,0,0,0,37, 1,0,0,0,0,39,1,0,0,0,0,41,1,0,0,0,0,43,1,0,0,0,0,45,1,0,0,0,0,47, 1,0,0,0,0,49,1,0,0,0,0,51,1,0,0,0,0,53,1,0,0,0,0,55,1,0,0,0,0,57, 1,0,0,0,0,59,1,0,0,0,0,61,1,0,0,0,0,63,1,0,0,0,0,65,1,0,0,0,0,67, 1,0,0,0,0,69,1,0,0,0,0,71,1,0,0,0,0,73,1,0,0,0,0,75,1,0,0,0,0,77, 1,0,0,0,0,79,1,0,0,0,0,81,1,0,0,0,0,83,1,0,0,0,0,85,1,0,0,0,0,91, 1,0,0,0,0,93,1,0,0,0,0,95,1,0,0,0,0,97,1,0,0,0,0,99,1,0,0,0,0,101, 1,0,0,0,1,103,1,0,0,0,3,105,1,0,0,0,5,107,1,0,0,0,7,109,1,0,0,0, 9,112,1,0,0,0,11,115,1,0,0,0,13,118,1,0,0,0,15,121,1,0,0,0,17,124, 1,0,0,0,19,127,1,0,0,0,21,129,1,0,0,0,23,131,1,0,0,0,25,133,1,0, 0,0,27,135,1,0,0,0,29,137,1,0,0,0,31,139,1,0,0,0,33,141,1,0,0,0, 35,143,1,0,0,0,37,145,1,0,0,0,39,147,1,0,0,0,41,149,1,0,0,0,43,151, 1,0,0,0,45,154,1,0,0,0,47,158,1,0,0,0,49,160,1,0,0,0,51,162,1,0, 0,0,53,164,1,0,0,0,55,169,1,0,0,0,57,177,1,0,0,0,59,185,1,0,0,0, 61,192,1,0,0,0,63,197,1,0,0,0,65,208,1,0,0,0,67,215,1,0,0,0,69,225, 1,0,0,0,71,233,1,0,0,0,73,241,1,0,0,0,75,252,1,0,0,0,77,260,1,0, 0,0,79,271,1,0,0,0,81,283,1,0,0,0,83,293,1,0,0,0,85,304,1,0,0,0, 87,324,1,0,0,0,89,327,1,0,0,0,91,330,1,0,0,0,93,352,1,0,0,0,95,363, 1,0,0,0,97,365,1,0,0,0,99,379,1,0,0,0,101,387,1,0,0,0,103,104,5, 91,0,0,104,2,1,0,0,0,105,106,5,93,0,0,106,4,1,0,0,0,107,108,5,61, 0,0,108,6,1,0,0,0,109,110,5,43,0,0,110,111,5,61,0,0,111,8,1,0,0, 0,112,113,5,45,0,0,113,114,5,61,0,0,114,10,1,0,0,0,115,116,5,58, 0,0,116,117,5,61,0,0,117,12,1,0,0,0,118,119,5,42,0,0,119,120,5,61, 0,0,120,14,1,0,0,0,121,122,5,47,0,0,122,123,5,61,0,0,123,16,1,0, 0,0,124,125,5,94,0,0,125,126,5,61,0,0,126,18,1,0,0,0,127,128,5,44, 0,0,128,20,1,0,0,0,129,130,5,39,0,0,130,22,1,0,0,0,131,132,5,40, 0,0,132,24,1,0,0,0,133,134,5,41,0,0,134,26,1,0,0,0,135,136,5,123, 0,0,136,28,1,0,0,0,137,138,5,125,0,0,138,30,1,0,0,0,139,140,5,58, 0,0,140,32,1,0,0,0,141,142,5,43,0,0,142,34,1,0,0,0,143,144,5,45, 0,0,144,36,1,0,0,0,145,146,5,59,0,0,146,38,1,0,0,0,147,148,5,46, 0,0,148,40,1,0,0,0,149,150,5,62,0,0,150,42,1,0,0,0,151,152,5,48, 0,0,152,153,5,62,0,0,153,44,1,0,0,0,154,155,5,49,0,0,155,156,5,62, 0,0,156,157,5,62,0,0,157,46,1,0,0,0,158,159,5,94,0,0,159,48,1,0, 0,0,160,161,5,42,0,0,161,50,1,0,0,0,162,163,5,47,0,0,163,52,1,0, 0,0,164,165,7,0,0,0,165,166,7,1,0,0,166,167,7,2,0,0,167,168,7,2, 0,0,168,54,1,0,0,0,169,170,7,3,0,0,170,171,7,4,0,0,171,172,7,5,0, 0,172,173,7,6,0,0,173,174,7,7,0,0,174,175,7,3,0,0,175,176,7,1,0, 0,176,56,1,0,0,0,177,178,7,3,0,0,178,179,7,4,0,0,179,180,7,8,0,0, 180,181,7,9,0,0,181,183,7,7,0,0,182,184,7,2,0,0,183,182,1,0,0,0, 183,184,1,0,0,0,184,58,1,0,0,0,185,186,7,10,0,0,186,187,7,9,0,0, 187,188,7,7,0,0,188,189,7,8,0,0,189,190,7,9,0,0,190,191,7,7,0,0, 191,60,1,0,0,0,192,193,7,2,0,0,193,194,7,1,0,0,194,195,7,11,0,0, 195,196,7,5,0,0,196,62,1,0,0,0,197,198,7,9,0,0,198,199,7,4,0,0,199, 200,7,3,0,0,200,201,7,7,0,0,201,202,7,2,0,0,202,203,7,12,0,0,203, 204,7,2,0,0,204,205,7,7,0,0,205,206,7,5,0,0,206,207,7,0,0,0,207, 64,1,0,0,0,208,209,7,5,0,0,209,210,7,4,0,0,210,211,7,13,0,0,211, 212,7,10,0,0,212,213,7,14,0,0,213,214,7,5,0,0,214,66,1,0,0,0,215, 216,7,4,0,0,216,217,7,5,0,0,217,218,7,15,0,0,218,219,7,7,0,0,219, 220,7,10,0,0,220,221,7,4,0,0,221,222,7,3,0,0,222,223,7,1,0,0,223, 224,7,4,0,0,224,68,1,0,0,0,225,226,7,16,0,0,226,227,7,6,0,0,227, 228,7,1,0,0,228,229,7,0,0,0,229,231,7,5,0,0,230,232,7,2,0,0,231, 230,1,0,0,0,231,232,1,0,0,0,232,70,1,0,0,0,233,234,7,17,0,0,234, 235,7,10,0,0,235,236,7,14,0,0,236,237,7,3,0,0,237,239,7,5,0,0,238, 240,7,2,0,0,239,238,1,0,0,0,239,240,1,0,0,0,240,72,1,0,0,0,241,242, 7,8,0,0,242,243,7,1,0,0,243,244,7,6,0,0,244,245,7,7,0,0,245,246, 7,3,0,0,246,247,7,13,0,0,247,248,7,18,0,0,248,250,7,5,0,0,249,251, 7,2,0,0,250,249,1,0,0,0,250,251,1,0,0,0,251,74,1,0,0,0,252,253,7, 8,0,0,253,254,7,10,0,0,254,255,7,3,0,0,255,256,7,4,0,0,256,258,7, 7,0,0,257,259,7,2,0,0,258,257,1,0,0,0,258,259,1,0,0,0,259,76,1,0, 0,0,260,261,7,13,0,0,261,262,7,10,0,0,262,263,7,4,0,0,263,264,7, 2,0,0,264,265,7,7,0,0,265,266,7,1,0,0,266,267,7,4,0,0,267,269,7, 7,0,0,268,270,7,2,0,0,269,268,1,0,0,0,269,270,1,0,0,0,270,78,1,0, 0,0,271,272,7,2,0,0,272,273,7,8,0,0,273,274,7,5,0,0,274,275,7,13, 0,0,275,276,7,3,0,0,276,277,7,16,0,0,277,278,7,3,0,0,278,279,7,5, 0,0,279,281,7,14,0,0,280,282,7,2,0,0,281,280,1,0,0,0,281,282,1,0, 0,0,282,80,1,0,0,0,283,284,7,3,0,0,284,285,7,0,0,0,285,286,7,1,0, 0,286,287,7,19,0,0,287,288,7,3,0,0,288,289,7,4,0,0,289,290,7,1,0, 0,290,291,7,6,0,0,291,292,7,12,0,0,292,82,1,0,0,0,293,294,7,11,0, 0,294,295,7,1,0,0,295,296,7,6,0,0,296,297,7,3,0,0,297,298,7,1,0, 0,298,299,7,17,0,0,299,300,7,18,0,0,300,302,7,5,0,0,301,303,7,2, 0,0,302,301,1,0,0,0,302,303,1,0,0,0,303,84,1,0,0,0,304,305,7,0,0, 0,305,306,7,10,0,0,306,307,7,7,0,0,307,308,7,3,0,0,308,309,7,10, 0,0,309,310,7,4,0,0,310,311,7,11,0,0,311,312,7,1,0,0,312,313,7,6, 0,0,313,314,7,3,0,0,314,315,7,1,0,0,315,316,7,17,0,0,316,317,7,18, 0,0,317,319,7,5,0,0,318,320,7,2,0,0,319,318,1,0,0,0,319,320,1,0, 0,0,320,86,1,0,0,0,321,323,5,39,0,0,322,321,1,0,0,0,323,326,1,0, 0,0,324,322,1,0,0,0,324,325,1,0,0,0,325,88,1,0,0,0,326,324,1,0,0, 0,327,328,7,20,0,0,328,90,1,0,0,0,329,331,7,20,0,0,330,329,1,0,0, 0,331,332,1,0,0,0,332,330,1,0,0,0,332,333,1,0,0,0,333,92,1,0,0,0, 334,336,3,89,44,0,335,334,1,0,0,0,336,337,1,0,0,0,337,335,1,0,0, 0,337,338,1,0,0,0,338,339,1,0,0,0,339,343,5,46,0,0,340,342,3,89, 44,0,341,340,1,0,0,0,342,345,1,0,0,0,343,341,1,0,0,0,343,344,1,0, 0,0,344,353,1,0,0,0,345,343,1,0,0,0,346,348,5,46,0,0,347,349,3,89, 44,0,348,347,1,0,0,0,349,350,1,0,0,0,350,348,1,0,0,0,350,351,1,0, 0,0,351,353,1,0,0,0,352,335,1,0,0,0,352,346,1,0,0,0,353,94,1,0,0, 0,354,355,3,93,46,0,355,356,5,69,0,0,356,357,3,91,45,0,357,364,1, 0,0,0,358,359,3,93,46,0,359,360,5,69,0,0,360,361,5,45,0,0,361,362, 3,91,45,0,362,364,1,0,0,0,363,354,1,0,0,0,363,358,1,0,0,0,364,96, 1,0,0,0,365,369,5,37,0,0,366,368,9,0,0,0,367,366,1,0,0,0,368,371, 1,0,0,0,369,370,1,0,0,0,369,367,1,0,0,0,370,373,1,0,0,0,371,369, 1,0,0,0,372,374,5,13,0,0,373,372,1,0,0,0,373,374,1,0,0,0,374,375, 1,0,0,0,375,376,5,10,0,0,376,377,1,0,0,0,377,378,6,48,0,0,378,98, 1,0,0,0,379,383,7,21,0,0,380,382,7,22,0,0,381,380,1,0,0,0,382,385, 1,0,0,0,383,381,1,0,0,0,383,384,1,0,0,0,384,100,1,0,0,0,385,383, 1,0,0,0,386,388,7,23,0,0,387,386,1,0,0,0,388,389,1,0,0,0,389,387, 1,0,0,0,389,390,1,0,0,0,390,391,1,0,0,0,391,392,6,50,0,0,392,102, 1,0,0,0,21,0,183,231,239,250,258,269,281,302,319,324,332,337,343, 350,352,363,369,373,383,389,1,6,0,0 ] class AutolevLexer(Lexer): atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] T__0 = 1 T__1 = 2 T__2 = 3 T__3 = 4 T__4 = 5 T__5 = 6 T__6 = 7 T__7 = 8 T__8 = 9 T__9 = 10 T__10 = 11 T__11 = 12 T__12 = 13 T__13 = 14 T__14 = 15 T__15 = 16 T__16 = 17 T__17 = 18 T__18 = 19 T__19 = 20 T__20 = 21 T__21 = 22 T__22 = 23 T__23 = 24 T__24 = 25 T__25 = 26 Mass = 27 Inertia = 28 Input = 29 Output = 30 Save = 31 UnitSystem = 32 Encode = 33 Newtonian = 34 Frames = 35 Bodies = 36 Particles = 37 Points = 38 Constants = 39 Specifieds = 40 Imaginary = 41 Variables = 42 MotionVariables = 43 INT = 44 FLOAT = 45 EXP = 46 LINE_COMMENT = 47 ID = 48 WS = 49 channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ] modeNames = [ "DEFAULT_MODE" ] literalNames = [ "<INVALID>", "'['", "']'", "'='", "'+='", "'-='", "':='", "'*='", "'/='", "'^='", "','", "'''", "'('", "')'", "'{'", "'}'", "':'", "'+'", "'-'", "';'", "'.'", "'>'", "'0>'", "'1>>'", "'^'", "'*'", "'/'" ] symbolicNames = [ "<INVALID>", "Mass", "Inertia", "Input", "Output", "Save", "UnitSystem", "Encode", "Newtonian", "Frames", "Bodies", "Particles", "Points", "Constants", "Specifieds", "Imaginary", "Variables", "MotionVariables", "INT", "FLOAT", "EXP", "LINE_COMMENT", "ID", "WS" ] ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "T__8", "T__9", "T__10", "T__11", "T__12", "T__13", "T__14", "T__15", "T__16", "T__17", "T__18", "T__19", "T__20", "T__21", "T__22", "T__23", "T__24", "T__25", "Mass", "Inertia", "Input", "Output", "Save", "UnitSystem", "Encode", "Newtonian", "Frames", "Bodies", "Particles", "Points", "Constants", "Specifieds", "Imaginary", "Variables", "MotionVariables", "DIFF", "DIGIT", "INT", "FLOAT", "EXP", "LINE_COMMENT", "ID", "WS" ] grammarFileName = "Autolev.g4" def __init__(self, input=None, output:TextIO = sys.stdout): super().__init__(input, output) self.checkVersion("4.11.1") self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) self._actions = None self._predicates = None
059609ec892ead19a6e384b9d29629ffd2470a34fc7ebd70e477a4b0010f8ed8
# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND *** # # Generated with antlr4 # antlr4 is licensed under the BSD-3-Clause License # https://github.com/antlr/antlr4/blob/master/LICENSE.txt from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): return [ 4,1,49,431,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7, 6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,13,7,13, 2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,19,2,20, 7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,26,7,26, 2,27,7,27,1,0,4,0,58,8,0,11,0,12,0,59,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,3,1,69,8,1,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2, 3,2,84,8,2,1,2,1,2,1,2,3,2,89,8,2,1,3,1,3,1,4,1,4,1,4,5,4,96,8,4, 10,4,12,4,99,9,4,1,5,4,5,102,8,5,11,5,12,5,103,1,6,1,6,1,6,1,6,1, 6,5,6,111,8,6,10,6,12,6,114,9,6,3,6,116,8,6,1,6,1,6,1,6,1,6,1,6, 1,6,5,6,124,8,6,10,6,12,6,127,9,6,3,6,129,8,6,1,6,3,6,132,8,6,1, 7,1,7,1,7,1,7,5,7,138,8,7,10,7,12,7,141,9,7,1,8,1,8,1,8,1,8,1,8, 1,8,1,8,1,8,1,8,1,8,5,8,153,8,8,10,8,12,8,156,9,8,1,8,1,8,5,8,160, 8,8,10,8,12,8,163,9,8,3,8,165,8,8,1,9,1,9,1,9,1,9,1,9,1,9,3,9,173, 8,9,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1,9,5,9,183,8,9,10,9,12,9,186,9, 9,1,9,3,9,189,8,9,1,9,1,9,1,9,3,9,194,8,9,1,9,3,9,197,8,9,1,9,5, 9,200,8,9,10,9,12,9,203,9,9,1,9,1,9,3,9,207,8,9,1,10,1,10,1,10,1, 10,1,10,1,10,1,10,1,10,5,10,217,8,10,10,10,12,10,220,9,10,1,10,1, 10,1,11,1,11,1,11,1,11,5,11,228,8,11,10,11,12,11,231,9,11,1,12,1, 12,1,12,1,12,1,13,1,13,1,13,1,13,1,13,3,13,242,8,13,1,13,1,13,4, 13,246,8,13,11,13,12,13,247,1,14,1,14,1,14,1,14,5,14,254,8,14,10, 14,12,14,257,9,14,1,14,1,14,1,15,1,15,1,15,1,15,3,15,265,8,15,1, 15,1,15,3,15,269,8,15,1,16,1,16,1,16,1,16,1,16,3,16,276,8,16,1,17, 1,17,3,17,280,8,17,1,18,1,18,1,18,1,18,5,18,286,8,18,10,18,12,18, 289,9,18,1,19,1,19,1,19,1,19,5,19,295,8,19,10,19,12,19,298,9,19, 1,20,1,20,3,20,302,8,20,1,21,1,21,1,21,1,21,3,21,308,8,21,1,22,1, 22,1,22,1,22,5,22,314,8,22,10,22,12,22,317,9,22,1,23,1,23,3,23,321, 8,23,1,24,1,24,1,24,1,24,1,24,1,24,5,24,329,8,24,10,24,12,24,332, 9,24,1,24,1,24,3,24,336,8,24,1,24,1,24,1,24,1,24,1,25,1,25,1,25, 1,25,1,25,1,25,1,25,1,25,5,25,350,8,25,10,25,12,25,353,9,25,3,25, 355,8,25,1,26,1,26,4,26,359,8,26,11,26,12,26,360,1,26,1,26,3,26, 365,8,26,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,5,27,375,8,27,10, 27,12,27,378,9,27,1,27,1,27,1,27,1,27,1,27,1,27,5,27,386,8,27,10, 27,12,27,389,9,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,3, 27,400,8,27,1,27,1,27,5,27,404,8,27,10,27,12,27,407,9,27,3,27,409, 8,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27, 1,27,1,27,1,27,5,27,426,8,27,10,27,12,27,429,9,27,1,27,0,1,54,28, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44, 46,48,50,52,54,0,7,1,0,3,9,1,0,27,28,1,0,17,18,2,0,10,10,19,19,1, 0,44,45,2,0,44,46,48,48,1,0,25,26,483,0,57,1,0,0,0,2,68,1,0,0,0, 4,88,1,0,0,0,6,90,1,0,0,0,8,92,1,0,0,0,10,101,1,0,0,0,12,131,1,0, 0,0,14,133,1,0,0,0,16,164,1,0,0,0,18,166,1,0,0,0,20,208,1,0,0,0, 22,223,1,0,0,0,24,232,1,0,0,0,26,236,1,0,0,0,28,249,1,0,0,0,30,268, 1,0,0,0,32,275,1,0,0,0,34,277,1,0,0,0,36,281,1,0,0,0,38,290,1,0, 0,0,40,299,1,0,0,0,42,303,1,0,0,0,44,309,1,0,0,0,46,318,1,0,0,0, 48,322,1,0,0,0,50,354,1,0,0,0,52,364,1,0,0,0,54,408,1,0,0,0,56,58, 3,2,1,0,57,56,1,0,0,0,58,59,1,0,0,0,59,57,1,0,0,0,59,60,1,0,0,0, 60,1,1,0,0,0,61,69,3,14,7,0,62,69,3,12,6,0,63,69,3,32,16,0,64,69, 3,22,11,0,65,69,3,26,13,0,66,69,3,4,2,0,67,69,3,34,17,0,68,61,1, 0,0,0,68,62,1,0,0,0,68,63,1,0,0,0,68,64,1,0,0,0,68,65,1,0,0,0,68, 66,1,0,0,0,68,67,1,0,0,0,69,3,1,0,0,0,70,71,3,52,26,0,71,72,3,6, 3,0,72,73,3,54,27,0,73,89,1,0,0,0,74,75,5,48,0,0,75,76,5,1,0,0,76, 77,3,8,4,0,77,78,5,2,0,0,78,79,3,6,3,0,79,80,3,54,27,0,80,89,1,0, 0,0,81,83,5,48,0,0,82,84,3,10,5,0,83,82,1,0,0,0,83,84,1,0,0,0,84, 85,1,0,0,0,85,86,3,6,3,0,86,87,3,54,27,0,87,89,1,0,0,0,88,70,1,0, 0,0,88,74,1,0,0,0,88,81,1,0,0,0,89,5,1,0,0,0,90,91,7,0,0,0,91,7, 1,0,0,0,92,97,3,54,27,0,93,94,5,10,0,0,94,96,3,54,27,0,95,93,1,0, 0,0,96,99,1,0,0,0,97,95,1,0,0,0,97,98,1,0,0,0,98,9,1,0,0,0,99,97, 1,0,0,0,100,102,5,11,0,0,101,100,1,0,0,0,102,103,1,0,0,0,103,101, 1,0,0,0,103,104,1,0,0,0,104,11,1,0,0,0,105,106,5,48,0,0,106,115, 5,12,0,0,107,112,3,54,27,0,108,109,5,10,0,0,109,111,3,54,27,0,110, 108,1,0,0,0,111,114,1,0,0,0,112,110,1,0,0,0,112,113,1,0,0,0,113, 116,1,0,0,0,114,112,1,0,0,0,115,107,1,0,0,0,115,116,1,0,0,0,116, 117,1,0,0,0,117,132,5,13,0,0,118,119,7,1,0,0,119,128,5,12,0,0,120, 125,5,48,0,0,121,122,5,10,0,0,122,124,5,48,0,0,123,121,1,0,0,0,124, 127,1,0,0,0,125,123,1,0,0,0,125,126,1,0,0,0,126,129,1,0,0,0,127, 125,1,0,0,0,128,120,1,0,0,0,128,129,1,0,0,0,129,130,1,0,0,0,130, 132,5,13,0,0,131,105,1,0,0,0,131,118,1,0,0,0,132,13,1,0,0,0,133, 134,3,16,8,0,134,139,3,18,9,0,135,136,5,10,0,0,136,138,3,18,9,0, 137,135,1,0,0,0,138,141,1,0,0,0,139,137,1,0,0,0,139,140,1,0,0,0, 140,15,1,0,0,0,141,139,1,0,0,0,142,165,5,34,0,0,143,165,5,35,0,0, 144,165,5,36,0,0,145,165,5,37,0,0,146,165,5,38,0,0,147,165,5,39, 0,0,148,165,5,40,0,0,149,165,5,41,0,0,150,154,5,42,0,0,151,153,5, 11,0,0,152,151,1,0,0,0,153,156,1,0,0,0,154,152,1,0,0,0,154,155,1, 0,0,0,155,165,1,0,0,0,156,154,1,0,0,0,157,161,5,43,0,0,158,160,5, 11,0,0,159,158,1,0,0,0,160,163,1,0,0,0,161,159,1,0,0,0,161,162,1, 0,0,0,162,165,1,0,0,0,163,161,1,0,0,0,164,142,1,0,0,0,164,143,1, 0,0,0,164,144,1,0,0,0,164,145,1,0,0,0,164,146,1,0,0,0,164,147,1, 0,0,0,164,148,1,0,0,0,164,149,1,0,0,0,164,150,1,0,0,0,164,157,1, 0,0,0,165,17,1,0,0,0,166,172,5,48,0,0,167,168,5,14,0,0,168,169,5, 44,0,0,169,170,5,10,0,0,170,171,5,44,0,0,171,173,5,15,0,0,172,167, 1,0,0,0,172,173,1,0,0,0,173,188,1,0,0,0,174,175,5,14,0,0,175,176, 5,44,0,0,176,177,5,16,0,0,177,184,5,44,0,0,178,179,5,10,0,0,179, 180,5,44,0,0,180,181,5,16,0,0,181,183,5,44,0,0,182,178,1,0,0,0,183, 186,1,0,0,0,184,182,1,0,0,0,184,185,1,0,0,0,185,187,1,0,0,0,186, 184,1,0,0,0,187,189,5,15,0,0,188,174,1,0,0,0,188,189,1,0,0,0,189, 193,1,0,0,0,190,191,5,14,0,0,191,192,5,44,0,0,192,194,5,15,0,0,193, 190,1,0,0,0,193,194,1,0,0,0,194,196,1,0,0,0,195,197,7,2,0,0,196, 195,1,0,0,0,196,197,1,0,0,0,197,201,1,0,0,0,198,200,5,11,0,0,199, 198,1,0,0,0,200,203,1,0,0,0,201,199,1,0,0,0,201,202,1,0,0,0,202, 206,1,0,0,0,203,201,1,0,0,0,204,205,5,3,0,0,205,207,3,54,27,0,206, 204,1,0,0,0,206,207,1,0,0,0,207,19,1,0,0,0,208,209,5,14,0,0,209, 210,5,44,0,0,210,211,5,16,0,0,211,218,5,44,0,0,212,213,5,10,0,0, 213,214,5,44,0,0,214,215,5,16,0,0,215,217,5,44,0,0,216,212,1,0,0, 0,217,220,1,0,0,0,218,216,1,0,0,0,218,219,1,0,0,0,219,221,1,0,0, 0,220,218,1,0,0,0,221,222,5,15,0,0,222,21,1,0,0,0,223,224,5,27,0, 0,224,229,3,24,12,0,225,226,5,10,0,0,226,228,3,24,12,0,227,225,1, 0,0,0,228,231,1,0,0,0,229,227,1,0,0,0,229,230,1,0,0,0,230,23,1,0, 0,0,231,229,1,0,0,0,232,233,5,48,0,0,233,234,5,3,0,0,234,235,3,54, 27,0,235,25,1,0,0,0,236,237,5,28,0,0,237,241,5,48,0,0,238,239,5, 12,0,0,239,240,5,48,0,0,240,242,5,13,0,0,241,238,1,0,0,0,241,242, 1,0,0,0,242,245,1,0,0,0,243,244,5,10,0,0,244,246,3,54,27,0,245,243, 1,0,0,0,246,247,1,0,0,0,247,245,1,0,0,0,247,248,1,0,0,0,248,27,1, 0,0,0,249,250,5,1,0,0,250,255,3,54,27,0,251,252,7,3,0,0,252,254, 3,54,27,0,253,251,1,0,0,0,254,257,1,0,0,0,255,253,1,0,0,0,255,256, 1,0,0,0,256,258,1,0,0,0,257,255,1,0,0,0,258,259,5,2,0,0,259,29,1, 0,0,0,260,261,5,48,0,0,261,262,5,48,0,0,262,264,5,3,0,0,263,265, 7,4,0,0,264,263,1,0,0,0,264,265,1,0,0,0,265,269,1,0,0,0,266,269, 5,45,0,0,267,269,5,44,0,0,268,260,1,0,0,0,268,266,1,0,0,0,268,267, 1,0,0,0,269,31,1,0,0,0,270,276,3,36,18,0,271,276,3,38,19,0,272,276, 3,44,22,0,273,276,3,48,24,0,274,276,3,50,25,0,275,270,1,0,0,0,275, 271,1,0,0,0,275,272,1,0,0,0,275,273,1,0,0,0,275,274,1,0,0,0,276, 33,1,0,0,0,277,279,5,48,0,0,278,280,7,5,0,0,279,278,1,0,0,0,279, 280,1,0,0,0,280,35,1,0,0,0,281,282,5,32,0,0,282,287,5,48,0,0,283, 284,5,10,0,0,284,286,5,48,0,0,285,283,1,0,0,0,286,289,1,0,0,0,287, 285,1,0,0,0,287,288,1,0,0,0,288,37,1,0,0,0,289,287,1,0,0,0,290,291, 5,29,0,0,291,296,3,42,21,0,292,293,5,10,0,0,293,295,3,42,21,0,294, 292,1,0,0,0,295,298,1,0,0,0,296,294,1,0,0,0,296,297,1,0,0,0,297, 39,1,0,0,0,298,296,1,0,0,0,299,301,5,48,0,0,300,302,3,10,5,0,301, 300,1,0,0,0,301,302,1,0,0,0,302,41,1,0,0,0,303,304,3,40,20,0,304, 305,5,3,0,0,305,307,3,54,27,0,306,308,3,54,27,0,307,306,1,0,0,0, 307,308,1,0,0,0,308,43,1,0,0,0,309,310,5,30,0,0,310,315,3,46,23, 0,311,312,5,10,0,0,312,314,3,46,23,0,313,311,1,0,0,0,314,317,1,0, 0,0,315,313,1,0,0,0,315,316,1,0,0,0,316,45,1,0,0,0,317,315,1,0,0, 0,318,320,3,54,27,0,319,321,3,54,27,0,320,319,1,0,0,0,320,321,1, 0,0,0,321,47,1,0,0,0,322,323,5,48,0,0,323,335,3,12,6,0,324,325,5, 1,0,0,325,330,3,30,15,0,326,327,5,10,0,0,327,329,3,30,15,0,328,326, 1,0,0,0,329,332,1,0,0,0,330,328,1,0,0,0,330,331,1,0,0,0,331,333, 1,0,0,0,332,330,1,0,0,0,333,334,5,2,0,0,334,336,1,0,0,0,335,324, 1,0,0,0,335,336,1,0,0,0,336,337,1,0,0,0,337,338,5,48,0,0,338,339, 5,20,0,0,339,340,5,48,0,0,340,49,1,0,0,0,341,342,5,31,0,0,342,343, 5,48,0,0,343,344,5,20,0,0,344,355,5,48,0,0,345,346,5,33,0,0,346, 351,5,48,0,0,347,348,5,10,0,0,348,350,5,48,0,0,349,347,1,0,0,0,350, 353,1,0,0,0,351,349,1,0,0,0,351,352,1,0,0,0,352,355,1,0,0,0,353, 351,1,0,0,0,354,341,1,0,0,0,354,345,1,0,0,0,355,51,1,0,0,0,356,358, 5,48,0,0,357,359,5,21,0,0,358,357,1,0,0,0,359,360,1,0,0,0,360,358, 1,0,0,0,360,361,1,0,0,0,361,365,1,0,0,0,362,365,5,22,0,0,363,365, 5,23,0,0,364,356,1,0,0,0,364,362,1,0,0,0,364,363,1,0,0,0,365,53, 1,0,0,0,366,367,6,27,-1,0,367,409,5,46,0,0,368,369,5,18,0,0,369, 409,3,54,27,12,370,409,5,45,0,0,371,409,5,44,0,0,372,376,5,48,0, 0,373,375,5,11,0,0,374,373,1,0,0,0,375,378,1,0,0,0,376,374,1,0,0, 0,376,377,1,0,0,0,377,409,1,0,0,0,378,376,1,0,0,0,379,409,3,52,26, 0,380,381,5,48,0,0,381,382,5,1,0,0,382,387,3,54,27,0,383,384,5,10, 0,0,384,386,3,54,27,0,385,383,1,0,0,0,386,389,1,0,0,0,387,385,1, 0,0,0,387,388,1,0,0,0,388,390,1,0,0,0,389,387,1,0,0,0,390,391,5, 2,0,0,391,409,1,0,0,0,392,409,3,12,6,0,393,409,3,28,14,0,394,395, 5,12,0,0,395,396,3,54,27,0,396,397,5,13,0,0,397,409,1,0,0,0,398, 400,5,48,0,0,399,398,1,0,0,0,399,400,1,0,0,0,400,401,1,0,0,0,401, 405,3,20,10,0,402,404,5,11,0,0,403,402,1,0,0,0,404,407,1,0,0,0,405, 403,1,0,0,0,405,406,1,0,0,0,406,409,1,0,0,0,407,405,1,0,0,0,408, 366,1,0,0,0,408,368,1,0,0,0,408,370,1,0,0,0,408,371,1,0,0,0,408, 372,1,0,0,0,408,379,1,0,0,0,408,380,1,0,0,0,408,392,1,0,0,0,408, 393,1,0,0,0,408,394,1,0,0,0,408,399,1,0,0,0,409,427,1,0,0,0,410, 411,10,16,0,0,411,412,5,24,0,0,412,426,3,54,27,17,413,414,10,15, 0,0,414,415,7,6,0,0,415,426,3,54,27,16,416,417,10,14,0,0,417,418, 7,2,0,0,418,426,3,54,27,15,419,420,10,3,0,0,420,421,5,3,0,0,421, 426,3,54,27,4,422,423,10,2,0,0,423,424,5,16,0,0,424,426,3,54,27, 3,425,410,1,0,0,0,425,413,1,0,0,0,425,416,1,0,0,0,425,419,1,0,0, 0,425,422,1,0,0,0,426,429,1,0,0,0,427,425,1,0,0,0,427,428,1,0,0, 0,428,55,1,0,0,0,429,427,1,0,0,0,50,59,68,83,88,97,103,112,115,125, 128,131,139,154,161,164,172,184,188,193,196,201,206,218,229,241, 247,255,264,268,275,279,287,296,301,307,315,320,330,335,351,354, 360,364,376,387,399,405,408,425,427 ] class AutolevParser ( Parser ): grammarFileName = "Autolev.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] sharedContextCache = PredictionContextCache() literalNames = [ "<INVALID>", "'['", "']'", "'='", "'+='", "'-='", "':='", "'*='", "'/='", "'^='", "','", "'''", "'('", "')'", "'{'", "'}'", "':'", "'+'", "'-'", "';'", "'.'", "'>'", "'0>'", "'1>>'", "'^'", "'*'", "'/'" ] symbolicNames = [ "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "Mass", "Inertia", "Input", "Output", "Save", "UnitSystem", "Encode", "Newtonian", "Frames", "Bodies", "Particles", "Points", "Constants", "Specifieds", "Imaginary", "Variables", "MotionVariables", "INT", "FLOAT", "EXP", "LINE_COMMENT", "ID", "WS" ] RULE_prog = 0 RULE_stat = 1 RULE_assignment = 2 RULE_equals = 3 RULE_index = 4 RULE_diff = 5 RULE_functionCall = 6 RULE_varDecl = 7 RULE_varType = 8 RULE_varDecl2 = 9 RULE_ranges = 10 RULE_massDecl = 11 RULE_massDecl2 = 12 RULE_inertiaDecl = 13 RULE_matrix = 14 RULE_matrixInOutput = 15 RULE_codeCommands = 16 RULE_settings = 17 RULE_units = 18 RULE_inputs = 19 RULE_id_diff = 20 RULE_inputs2 = 21 RULE_outputs = 22 RULE_outputs2 = 23 RULE_codegen = 24 RULE_commands = 25 RULE_vec = 26 RULE_expr = 27 ruleNames = [ "prog", "stat", "assignment", "equals", "index", "diff", "functionCall", "varDecl", "varType", "varDecl2", "ranges", "massDecl", "massDecl2", "inertiaDecl", "matrix", "matrixInOutput", "codeCommands", "settings", "units", "inputs", "id_diff", "inputs2", "outputs", "outputs2", "codegen", "commands", "vec", "expr" ] EOF = Token.EOF T__0=1 T__1=2 T__2=3 T__3=4 T__4=5 T__5=6 T__6=7 T__7=8 T__8=9 T__9=10 T__10=11 T__11=12 T__12=13 T__13=14 T__14=15 T__15=16 T__16=17 T__17=18 T__18=19 T__19=20 T__20=21 T__21=22 T__22=23 T__23=24 T__24=25 T__25=26 Mass=27 Inertia=28 Input=29 Output=30 Save=31 UnitSystem=32 Encode=33 Newtonian=34 Frames=35 Bodies=36 Particles=37 Points=38 Constants=39 Specifieds=40 Imaginary=41 Variables=42 MotionVariables=43 INT=44 FLOAT=45 EXP=46 LINE_COMMENT=47 ID=48 WS=49 def __init__(self, input:TokenStream, output:TextIO = sys.stdout): super().__init__(input, output) self.checkVersion("4.11.1") self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) self._predicates = None class ProgContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def stat(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.StatContext) else: return self.getTypedRuleContext(AutolevParser.StatContext,i) def getRuleIndex(self): return AutolevParser.RULE_prog def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterProg" ): listener.enterProg(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitProg" ): listener.exitProg(self) def prog(self): localctx = AutolevParser.ProgContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_prog) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 57 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 56 self.stat() self.state = 59 self._errHandler.sync(self) _la = self._input.LA(1) if not (((_la) & ~0x3f) == 0 and ((1 << _la) & 299067041120256) != 0): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class StatContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def varDecl(self): return self.getTypedRuleContext(AutolevParser.VarDeclContext,0) def functionCall(self): return self.getTypedRuleContext(AutolevParser.FunctionCallContext,0) def codeCommands(self): return self.getTypedRuleContext(AutolevParser.CodeCommandsContext,0) def massDecl(self): return self.getTypedRuleContext(AutolevParser.MassDeclContext,0) def inertiaDecl(self): return self.getTypedRuleContext(AutolevParser.InertiaDeclContext,0) def assignment(self): return self.getTypedRuleContext(AutolevParser.AssignmentContext,0) def settings(self): return self.getTypedRuleContext(AutolevParser.SettingsContext,0) def getRuleIndex(self): return AutolevParser.RULE_stat def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterStat" ): listener.enterStat(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitStat" ): listener.exitStat(self) def stat(self): localctx = AutolevParser.StatContext(self, self._ctx, self.state) self.enterRule(localctx, 2, self.RULE_stat) try: self.state = 68 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,1,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 61 self.varDecl() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 62 self.functionCall() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 63 self.codeCommands() pass elif la_ == 4: self.enterOuterAlt(localctx, 4) self.state = 64 self.massDecl() pass elif la_ == 5: self.enterOuterAlt(localctx, 5) self.state = 65 self.inertiaDecl() pass elif la_ == 6: self.enterOuterAlt(localctx, 6) self.state = 66 self.assignment() pass elif la_ == 7: self.enterOuterAlt(localctx, 7) self.state = 67 self.settings() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AssignmentContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return AutolevParser.RULE_assignment def copyFrom(self, ctx:ParserRuleContext): super().copyFrom(ctx) class VecAssignContext(AssignmentContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.AssignmentContext super().__init__(parser) self.copyFrom(ctx) def vec(self): return self.getTypedRuleContext(AutolevParser.VecContext,0) def equals(self): return self.getTypedRuleContext(AutolevParser.EqualsContext,0) def expr(self): return self.getTypedRuleContext(AutolevParser.ExprContext,0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterVecAssign" ): listener.enterVecAssign(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitVecAssign" ): listener.exitVecAssign(self) class RegularAssignContext(AssignmentContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.AssignmentContext super().__init__(parser) self.copyFrom(ctx) def ID(self): return self.getToken(AutolevParser.ID, 0) def equals(self): return self.getTypedRuleContext(AutolevParser.EqualsContext,0) def expr(self): return self.getTypedRuleContext(AutolevParser.ExprContext,0) def diff(self): return self.getTypedRuleContext(AutolevParser.DiffContext,0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterRegularAssign" ): listener.enterRegularAssign(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitRegularAssign" ): listener.exitRegularAssign(self) class IndexAssignContext(AssignmentContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.AssignmentContext super().__init__(parser) self.copyFrom(ctx) def ID(self): return self.getToken(AutolevParser.ID, 0) def index(self): return self.getTypedRuleContext(AutolevParser.IndexContext,0) def equals(self): return self.getTypedRuleContext(AutolevParser.EqualsContext,0) def expr(self): return self.getTypedRuleContext(AutolevParser.ExprContext,0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterIndexAssign" ): listener.enterIndexAssign(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitIndexAssign" ): listener.exitIndexAssign(self) def assignment(self): localctx = AutolevParser.AssignmentContext(self, self._ctx, self.state) self.enterRule(localctx, 4, self.RULE_assignment) self._la = 0 # Token type try: self.state = 88 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,3,self._ctx) if la_ == 1: localctx = AutolevParser.VecAssignContext(self, localctx) self.enterOuterAlt(localctx, 1) self.state = 70 self.vec() self.state = 71 self.equals() self.state = 72 self.expr(0) pass elif la_ == 2: localctx = AutolevParser.IndexAssignContext(self, localctx) self.enterOuterAlt(localctx, 2) self.state = 74 self.match(AutolevParser.ID) self.state = 75 self.match(AutolevParser.T__0) self.state = 76 self.index() self.state = 77 self.match(AutolevParser.T__1) self.state = 78 self.equals() self.state = 79 self.expr(0) pass elif la_ == 3: localctx = AutolevParser.RegularAssignContext(self, localctx) self.enterOuterAlt(localctx, 3) self.state = 81 self.match(AutolevParser.ID) self.state = 83 self._errHandler.sync(self) _la = self._input.LA(1) if _la==11: self.state = 82 self.diff() self.state = 85 self.equals() self.state = 86 self.expr(0) pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class EqualsContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return AutolevParser.RULE_equals def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterEquals" ): listener.enterEquals(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitEquals" ): listener.exitEquals(self) def equals(self): localctx = AutolevParser.EqualsContext(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_equals) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 90 _la = self._input.LA(1) if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 1016) != 0): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class IndexContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.ExprContext) else: return self.getTypedRuleContext(AutolevParser.ExprContext,i) def getRuleIndex(self): return AutolevParser.RULE_index def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterIndex" ): listener.enterIndex(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitIndex" ): listener.exitIndex(self) def index(self): localctx = AutolevParser.IndexContext(self, self._ctx, self.state) self.enterRule(localctx, 8, self.RULE_index) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 92 self.expr(0) self.state = 97 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 93 self.match(AutolevParser.T__9) self.state = 94 self.expr(0) self.state = 99 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class DiffContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return AutolevParser.RULE_diff def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterDiff" ): listener.enterDiff(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitDiff" ): listener.exitDiff(self) def diff(self): localctx = AutolevParser.DiffContext(self, self._ctx, self.state) self.enterRule(localctx, 10, self.RULE_diff) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 101 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 100 self.match(AutolevParser.T__10) self.state = 103 self._errHandler.sync(self) _la = self._input.LA(1) if not (_la==11): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FunctionCallContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self, i:int=None): if i is None: return self.getTokens(AutolevParser.ID) else: return self.getToken(AutolevParser.ID, i) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.ExprContext) else: return self.getTypedRuleContext(AutolevParser.ExprContext,i) def Mass(self): return self.getToken(AutolevParser.Mass, 0) def Inertia(self): return self.getToken(AutolevParser.Inertia, 0) def getRuleIndex(self): return AutolevParser.RULE_functionCall def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterFunctionCall" ): listener.enterFunctionCall(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitFunctionCall" ): listener.exitFunctionCall(self) def functionCall(self): localctx = AutolevParser.FunctionCallContext(self, self._ctx, self.state) self.enterRule(localctx, 12, self.RULE_functionCall) self._la = 0 # Token type try: self.state = 131 self._errHandler.sync(self) token = self._input.LA(1) if token in [48]: self.enterOuterAlt(localctx, 1) self.state = 105 self.match(AutolevParser.ID) self.state = 106 self.match(AutolevParser.T__11) self.state = 115 self._errHandler.sync(self) _la = self._input.LA(1) if ((_la) & ~0x3f) == 0 and ((1 << _la) & 404620694540290) != 0: self.state = 107 self.expr(0) self.state = 112 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 108 self.match(AutolevParser.T__9) self.state = 109 self.expr(0) self.state = 114 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 117 self.match(AutolevParser.T__12) pass elif token in [27, 28]: self.enterOuterAlt(localctx, 2) self.state = 118 _la = self._input.LA(1) if not(_la==27 or _la==28): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 119 self.match(AutolevParser.T__11) self.state = 128 self._errHandler.sync(self) _la = self._input.LA(1) if _la==48: self.state = 120 self.match(AutolevParser.ID) self.state = 125 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 121 self.match(AutolevParser.T__9) self.state = 122 self.match(AutolevParser.ID) self.state = 127 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 130 self.match(AutolevParser.T__12) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class VarDeclContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def varType(self): return self.getTypedRuleContext(AutolevParser.VarTypeContext,0) def varDecl2(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.VarDecl2Context) else: return self.getTypedRuleContext(AutolevParser.VarDecl2Context,i) def getRuleIndex(self): return AutolevParser.RULE_varDecl def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterVarDecl" ): listener.enterVarDecl(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitVarDecl" ): listener.exitVarDecl(self) def varDecl(self): localctx = AutolevParser.VarDeclContext(self, self._ctx, self.state) self.enterRule(localctx, 14, self.RULE_varDecl) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 133 self.varType() self.state = 134 self.varDecl2() self.state = 139 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 135 self.match(AutolevParser.T__9) self.state = 136 self.varDecl2() self.state = 141 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class VarTypeContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def Newtonian(self): return self.getToken(AutolevParser.Newtonian, 0) def Frames(self): return self.getToken(AutolevParser.Frames, 0) def Bodies(self): return self.getToken(AutolevParser.Bodies, 0) def Particles(self): return self.getToken(AutolevParser.Particles, 0) def Points(self): return self.getToken(AutolevParser.Points, 0) def Constants(self): return self.getToken(AutolevParser.Constants, 0) def Specifieds(self): return self.getToken(AutolevParser.Specifieds, 0) def Imaginary(self): return self.getToken(AutolevParser.Imaginary, 0) def Variables(self): return self.getToken(AutolevParser.Variables, 0) def MotionVariables(self): return self.getToken(AutolevParser.MotionVariables, 0) def getRuleIndex(self): return AutolevParser.RULE_varType def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterVarType" ): listener.enterVarType(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitVarType" ): listener.exitVarType(self) def varType(self): localctx = AutolevParser.VarTypeContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_varType) self._la = 0 # Token type try: self.state = 164 self._errHandler.sync(self) token = self._input.LA(1) if token in [34]: self.enterOuterAlt(localctx, 1) self.state = 142 self.match(AutolevParser.Newtonian) pass elif token in [35]: self.enterOuterAlt(localctx, 2) self.state = 143 self.match(AutolevParser.Frames) pass elif token in [36]: self.enterOuterAlt(localctx, 3) self.state = 144 self.match(AutolevParser.Bodies) pass elif token in [37]: self.enterOuterAlt(localctx, 4) self.state = 145 self.match(AutolevParser.Particles) pass elif token in [38]: self.enterOuterAlt(localctx, 5) self.state = 146 self.match(AutolevParser.Points) pass elif token in [39]: self.enterOuterAlt(localctx, 6) self.state = 147 self.match(AutolevParser.Constants) pass elif token in [40]: self.enterOuterAlt(localctx, 7) self.state = 148 self.match(AutolevParser.Specifieds) pass elif token in [41]: self.enterOuterAlt(localctx, 8) self.state = 149 self.match(AutolevParser.Imaginary) pass elif token in [42]: self.enterOuterAlt(localctx, 9) self.state = 150 self.match(AutolevParser.Variables) self.state = 154 self._errHandler.sync(self) _la = self._input.LA(1) while _la==11: self.state = 151 self.match(AutolevParser.T__10) self.state = 156 self._errHandler.sync(self) _la = self._input.LA(1) pass elif token in [43]: self.enterOuterAlt(localctx, 10) self.state = 157 self.match(AutolevParser.MotionVariables) self.state = 161 self._errHandler.sync(self) _la = self._input.LA(1) while _la==11: self.state = 158 self.match(AutolevParser.T__10) self.state = 163 self._errHandler.sync(self) _la = self._input.LA(1) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class VarDecl2Context(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(AutolevParser.ID, 0) def INT(self, i:int=None): if i is None: return self.getTokens(AutolevParser.INT) else: return self.getToken(AutolevParser.INT, i) def expr(self): return self.getTypedRuleContext(AutolevParser.ExprContext,0) def getRuleIndex(self): return AutolevParser.RULE_varDecl2 def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterVarDecl2" ): listener.enterVarDecl2(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitVarDecl2" ): listener.exitVarDecl2(self) def varDecl2(self): localctx = AutolevParser.VarDecl2Context(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_varDecl2) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 166 self.match(AutolevParser.ID) self.state = 172 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,15,self._ctx) if la_ == 1: self.state = 167 self.match(AutolevParser.T__13) self.state = 168 self.match(AutolevParser.INT) self.state = 169 self.match(AutolevParser.T__9) self.state = 170 self.match(AutolevParser.INT) self.state = 171 self.match(AutolevParser.T__14) self.state = 188 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,17,self._ctx) if la_ == 1: self.state = 174 self.match(AutolevParser.T__13) self.state = 175 self.match(AutolevParser.INT) self.state = 176 self.match(AutolevParser.T__15) self.state = 177 self.match(AutolevParser.INT) self.state = 184 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 178 self.match(AutolevParser.T__9) self.state = 179 self.match(AutolevParser.INT) self.state = 180 self.match(AutolevParser.T__15) self.state = 181 self.match(AutolevParser.INT) self.state = 186 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 187 self.match(AutolevParser.T__14) self.state = 193 self._errHandler.sync(self) _la = self._input.LA(1) if _la==14: self.state = 190 self.match(AutolevParser.T__13) self.state = 191 self.match(AutolevParser.INT) self.state = 192 self.match(AutolevParser.T__14) self.state = 196 self._errHandler.sync(self) _la = self._input.LA(1) if _la==17 or _la==18: self.state = 195 _la = self._input.LA(1) if not(_la==17 or _la==18): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 201 self._errHandler.sync(self) _la = self._input.LA(1) while _la==11: self.state = 198 self.match(AutolevParser.T__10) self.state = 203 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 206 self._errHandler.sync(self) _la = self._input.LA(1) if _la==3: self.state = 204 self.match(AutolevParser.T__2) self.state = 205 self.expr(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class RangesContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def INT(self, i:int=None): if i is None: return self.getTokens(AutolevParser.INT) else: return self.getToken(AutolevParser.INT, i) def getRuleIndex(self): return AutolevParser.RULE_ranges def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterRanges" ): listener.enterRanges(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitRanges" ): listener.exitRanges(self) def ranges(self): localctx = AutolevParser.RangesContext(self, self._ctx, self.state) self.enterRule(localctx, 20, self.RULE_ranges) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 208 self.match(AutolevParser.T__13) self.state = 209 self.match(AutolevParser.INT) self.state = 210 self.match(AutolevParser.T__15) self.state = 211 self.match(AutolevParser.INT) self.state = 218 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 212 self.match(AutolevParser.T__9) self.state = 213 self.match(AutolevParser.INT) self.state = 214 self.match(AutolevParser.T__15) self.state = 215 self.match(AutolevParser.INT) self.state = 220 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 221 self.match(AutolevParser.T__14) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MassDeclContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def Mass(self): return self.getToken(AutolevParser.Mass, 0) def massDecl2(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.MassDecl2Context) else: return self.getTypedRuleContext(AutolevParser.MassDecl2Context,i) def getRuleIndex(self): return AutolevParser.RULE_massDecl def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterMassDecl" ): listener.enterMassDecl(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitMassDecl" ): listener.exitMassDecl(self) def massDecl(self): localctx = AutolevParser.MassDeclContext(self, self._ctx, self.state) self.enterRule(localctx, 22, self.RULE_massDecl) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 223 self.match(AutolevParser.Mass) self.state = 224 self.massDecl2() self.state = 229 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 225 self.match(AutolevParser.T__9) self.state = 226 self.massDecl2() self.state = 231 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MassDecl2Context(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(AutolevParser.ID, 0) def expr(self): return self.getTypedRuleContext(AutolevParser.ExprContext,0) def getRuleIndex(self): return AutolevParser.RULE_massDecl2 def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterMassDecl2" ): listener.enterMassDecl2(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitMassDecl2" ): listener.exitMassDecl2(self) def massDecl2(self): localctx = AutolevParser.MassDecl2Context(self, self._ctx, self.state) self.enterRule(localctx, 24, self.RULE_massDecl2) try: self.enterOuterAlt(localctx, 1) self.state = 232 self.match(AutolevParser.ID) self.state = 233 self.match(AutolevParser.T__2) self.state = 234 self.expr(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class InertiaDeclContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def Inertia(self): return self.getToken(AutolevParser.Inertia, 0) def ID(self, i:int=None): if i is None: return self.getTokens(AutolevParser.ID) else: return self.getToken(AutolevParser.ID, i) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.ExprContext) else: return self.getTypedRuleContext(AutolevParser.ExprContext,i) def getRuleIndex(self): return AutolevParser.RULE_inertiaDecl def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterInertiaDecl" ): listener.enterInertiaDecl(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitInertiaDecl" ): listener.exitInertiaDecl(self) def inertiaDecl(self): localctx = AutolevParser.InertiaDeclContext(self, self._ctx, self.state) self.enterRule(localctx, 26, self.RULE_inertiaDecl) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 236 self.match(AutolevParser.Inertia) self.state = 237 self.match(AutolevParser.ID) self.state = 241 self._errHandler.sync(self) _la = self._input.LA(1) if _la==12: self.state = 238 self.match(AutolevParser.T__11) self.state = 239 self.match(AutolevParser.ID) self.state = 240 self.match(AutolevParser.T__12) self.state = 245 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 243 self.match(AutolevParser.T__9) self.state = 244 self.expr(0) self.state = 247 self._errHandler.sync(self) _la = self._input.LA(1) if not (_la==10): break except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MatrixContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.ExprContext) else: return self.getTypedRuleContext(AutolevParser.ExprContext,i) def getRuleIndex(self): return AutolevParser.RULE_matrix def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterMatrix" ): listener.enterMatrix(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitMatrix" ): listener.exitMatrix(self) def matrix(self): localctx = AutolevParser.MatrixContext(self, self._ctx, self.state) self.enterRule(localctx, 28, self.RULE_matrix) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 249 self.match(AutolevParser.T__0) self.state = 250 self.expr(0) self.state = 255 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10 or _la==19: self.state = 251 _la = self._input.LA(1) if not(_la==10 or _la==19): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 252 self.expr(0) self.state = 257 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 258 self.match(AutolevParser.T__1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MatrixInOutputContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self, i:int=None): if i is None: return self.getTokens(AutolevParser.ID) else: return self.getToken(AutolevParser.ID, i) def FLOAT(self): return self.getToken(AutolevParser.FLOAT, 0) def INT(self): return self.getToken(AutolevParser.INT, 0) def getRuleIndex(self): return AutolevParser.RULE_matrixInOutput def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterMatrixInOutput" ): listener.enterMatrixInOutput(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitMatrixInOutput" ): listener.exitMatrixInOutput(self) def matrixInOutput(self): localctx = AutolevParser.MatrixInOutputContext(self, self._ctx, self.state) self.enterRule(localctx, 30, self.RULE_matrixInOutput) self._la = 0 # Token type try: self.state = 268 self._errHandler.sync(self) token = self._input.LA(1) if token in [48]: self.enterOuterAlt(localctx, 1) self.state = 260 self.match(AutolevParser.ID) self.state = 261 self.match(AutolevParser.ID) self.state = 262 self.match(AutolevParser.T__2) self.state = 264 self._errHandler.sync(self) _la = self._input.LA(1) if _la==44 or _la==45: self.state = 263 _la = self._input.LA(1) if not(_la==44 or _la==45): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() pass elif token in [45]: self.enterOuterAlt(localctx, 2) self.state = 266 self.match(AutolevParser.FLOAT) pass elif token in [44]: self.enterOuterAlt(localctx, 3) self.state = 267 self.match(AutolevParser.INT) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CodeCommandsContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def units(self): return self.getTypedRuleContext(AutolevParser.UnitsContext,0) def inputs(self): return self.getTypedRuleContext(AutolevParser.InputsContext,0) def outputs(self): return self.getTypedRuleContext(AutolevParser.OutputsContext,0) def codegen(self): return self.getTypedRuleContext(AutolevParser.CodegenContext,0) def commands(self): return self.getTypedRuleContext(AutolevParser.CommandsContext,0) def getRuleIndex(self): return AutolevParser.RULE_codeCommands def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterCodeCommands" ): listener.enterCodeCommands(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitCodeCommands" ): listener.exitCodeCommands(self) def codeCommands(self): localctx = AutolevParser.CodeCommandsContext(self, self._ctx, self.state) self.enterRule(localctx, 32, self.RULE_codeCommands) try: self.state = 275 self._errHandler.sync(self) token = self._input.LA(1) if token in [32]: self.enterOuterAlt(localctx, 1) self.state = 270 self.units() pass elif token in [29]: self.enterOuterAlt(localctx, 2) self.state = 271 self.inputs() pass elif token in [30]: self.enterOuterAlt(localctx, 3) self.state = 272 self.outputs() pass elif token in [48]: self.enterOuterAlt(localctx, 4) self.state = 273 self.codegen() pass elif token in [31, 33]: self.enterOuterAlt(localctx, 5) self.state = 274 self.commands() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SettingsContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self, i:int=None): if i is None: return self.getTokens(AutolevParser.ID) else: return self.getToken(AutolevParser.ID, i) def EXP(self): return self.getToken(AutolevParser.EXP, 0) def FLOAT(self): return self.getToken(AutolevParser.FLOAT, 0) def INT(self): return self.getToken(AutolevParser.INT, 0) def getRuleIndex(self): return AutolevParser.RULE_settings def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterSettings" ): listener.enterSettings(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitSettings" ): listener.exitSettings(self) def settings(self): localctx = AutolevParser.SettingsContext(self, self._ctx, self.state) self.enterRule(localctx, 34, self.RULE_settings) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 277 self.match(AutolevParser.ID) self.state = 279 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,30,self._ctx) if la_ == 1: self.state = 278 _la = self._input.LA(1) if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 404620279021568) != 0): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class UnitsContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def UnitSystem(self): return self.getToken(AutolevParser.UnitSystem, 0) def ID(self, i:int=None): if i is None: return self.getTokens(AutolevParser.ID) else: return self.getToken(AutolevParser.ID, i) def getRuleIndex(self): return AutolevParser.RULE_units def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterUnits" ): listener.enterUnits(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitUnits" ): listener.exitUnits(self) def units(self): localctx = AutolevParser.UnitsContext(self, self._ctx, self.state) self.enterRule(localctx, 36, self.RULE_units) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 281 self.match(AutolevParser.UnitSystem) self.state = 282 self.match(AutolevParser.ID) self.state = 287 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 283 self.match(AutolevParser.T__9) self.state = 284 self.match(AutolevParser.ID) self.state = 289 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class InputsContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def Input(self): return self.getToken(AutolevParser.Input, 0) def inputs2(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.Inputs2Context) else: return self.getTypedRuleContext(AutolevParser.Inputs2Context,i) def getRuleIndex(self): return AutolevParser.RULE_inputs def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterInputs" ): listener.enterInputs(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitInputs" ): listener.exitInputs(self) def inputs(self): localctx = AutolevParser.InputsContext(self, self._ctx, self.state) self.enterRule(localctx, 38, self.RULE_inputs) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 290 self.match(AutolevParser.Input) self.state = 291 self.inputs2() self.state = 296 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 292 self.match(AutolevParser.T__9) self.state = 293 self.inputs2() self.state = 298 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Id_diffContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(AutolevParser.ID, 0) def diff(self): return self.getTypedRuleContext(AutolevParser.DiffContext,0) def getRuleIndex(self): return AutolevParser.RULE_id_diff def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterId_diff" ): listener.enterId_diff(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitId_diff" ): listener.exitId_diff(self) def id_diff(self): localctx = AutolevParser.Id_diffContext(self, self._ctx, self.state) self.enterRule(localctx, 40, self.RULE_id_diff) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 299 self.match(AutolevParser.ID) self.state = 301 self._errHandler.sync(self) _la = self._input.LA(1) if _la==11: self.state = 300 self.diff() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Inputs2Context(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def id_diff(self): return self.getTypedRuleContext(AutolevParser.Id_diffContext,0) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.ExprContext) else: return self.getTypedRuleContext(AutolevParser.ExprContext,i) def getRuleIndex(self): return AutolevParser.RULE_inputs2 def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterInputs2" ): listener.enterInputs2(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitInputs2" ): listener.exitInputs2(self) def inputs2(self): localctx = AutolevParser.Inputs2Context(self, self._ctx, self.state) self.enterRule(localctx, 42, self.RULE_inputs2) try: self.enterOuterAlt(localctx, 1) self.state = 303 self.id_diff() self.state = 304 self.match(AutolevParser.T__2) self.state = 305 self.expr(0) self.state = 307 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,34,self._ctx) if la_ == 1: self.state = 306 self.expr(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class OutputsContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def Output(self): return self.getToken(AutolevParser.Output, 0) def outputs2(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.Outputs2Context) else: return self.getTypedRuleContext(AutolevParser.Outputs2Context,i) def getRuleIndex(self): return AutolevParser.RULE_outputs def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterOutputs" ): listener.enterOutputs(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitOutputs" ): listener.exitOutputs(self) def outputs(self): localctx = AutolevParser.OutputsContext(self, self._ctx, self.state) self.enterRule(localctx, 44, self.RULE_outputs) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 309 self.match(AutolevParser.Output) self.state = 310 self.outputs2() self.state = 315 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 311 self.match(AutolevParser.T__9) self.state = 312 self.outputs2() self.state = 317 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Outputs2Context(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.ExprContext) else: return self.getTypedRuleContext(AutolevParser.ExprContext,i) def getRuleIndex(self): return AutolevParser.RULE_outputs2 def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterOutputs2" ): listener.enterOutputs2(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitOutputs2" ): listener.exitOutputs2(self) def outputs2(self): localctx = AutolevParser.Outputs2Context(self, self._ctx, self.state) self.enterRule(localctx, 46, self.RULE_outputs2) try: self.enterOuterAlt(localctx, 1) self.state = 318 self.expr(0) self.state = 320 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,36,self._ctx) if la_ == 1: self.state = 319 self.expr(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CodegenContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self, i:int=None): if i is None: return self.getTokens(AutolevParser.ID) else: return self.getToken(AutolevParser.ID, i) def functionCall(self): return self.getTypedRuleContext(AutolevParser.FunctionCallContext,0) def matrixInOutput(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.MatrixInOutputContext) else: return self.getTypedRuleContext(AutolevParser.MatrixInOutputContext,i) def getRuleIndex(self): return AutolevParser.RULE_codegen def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterCodegen" ): listener.enterCodegen(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitCodegen" ): listener.exitCodegen(self) def codegen(self): localctx = AutolevParser.CodegenContext(self, self._ctx, self.state) self.enterRule(localctx, 48, self.RULE_codegen) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 322 self.match(AutolevParser.ID) self.state = 323 self.functionCall() self.state = 335 self._errHandler.sync(self) _la = self._input.LA(1) if _la==1: self.state = 324 self.match(AutolevParser.T__0) self.state = 325 self.matrixInOutput() self.state = 330 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 326 self.match(AutolevParser.T__9) self.state = 327 self.matrixInOutput() self.state = 332 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 333 self.match(AutolevParser.T__1) self.state = 337 self.match(AutolevParser.ID) self.state = 338 self.match(AutolevParser.T__19) self.state = 339 self.match(AutolevParser.ID) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CommandsContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def Save(self): return self.getToken(AutolevParser.Save, 0) def ID(self, i:int=None): if i is None: return self.getTokens(AutolevParser.ID) else: return self.getToken(AutolevParser.ID, i) def Encode(self): return self.getToken(AutolevParser.Encode, 0) def getRuleIndex(self): return AutolevParser.RULE_commands def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterCommands" ): listener.enterCommands(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitCommands" ): listener.exitCommands(self) def commands(self): localctx = AutolevParser.CommandsContext(self, self._ctx, self.state) self.enterRule(localctx, 50, self.RULE_commands) self._la = 0 # Token type try: self.state = 354 self._errHandler.sync(self) token = self._input.LA(1) if token in [31]: self.enterOuterAlt(localctx, 1) self.state = 341 self.match(AutolevParser.Save) self.state = 342 self.match(AutolevParser.ID) self.state = 343 self.match(AutolevParser.T__19) self.state = 344 self.match(AutolevParser.ID) pass elif token in [33]: self.enterOuterAlt(localctx, 2) self.state = 345 self.match(AutolevParser.Encode) self.state = 346 self.match(AutolevParser.ID) self.state = 351 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 347 self.match(AutolevParser.T__9) self.state = 348 self.match(AutolevParser.ID) self.state = 353 self._errHandler.sync(self) _la = self._input.LA(1) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class VecContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def ID(self): return self.getToken(AutolevParser.ID, 0) def getRuleIndex(self): return AutolevParser.RULE_vec def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterVec" ): listener.enterVec(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitVec" ): listener.exitVec(self) def vec(self): localctx = AutolevParser.VecContext(self, self._ctx, self.state) self.enterRule(localctx, 52, self.RULE_vec) try: self.state = 364 self._errHandler.sync(self) token = self._input.LA(1) if token in [48]: self.enterOuterAlt(localctx, 1) self.state = 356 self.match(AutolevParser.ID) self.state = 358 self._errHandler.sync(self) _alt = 1 while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt == 1: self.state = 357 self.match(AutolevParser.T__20) else: raise NoViableAltException(self) self.state = 360 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,41,self._ctx) pass elif token in [22]: self.enterOuterAlt(localctx, 2) self.state = 362 self.match(AutolevParser.T__21) pass elif token in [23]: self.enterOuterAlt(localctx, 3) self.state = 363 self.match(AutolevParser.T__22) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExprContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return AutolevParser.RULE_expr def copyFrom(self, ctx:ParserRuleContext): super().copyFrom(ctx) class ParensContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self): return self.getTypedRuleContext(AutolevParser.ExprContext,0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterParens" ): listener.enterParens(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitParens" ): listener.exitParens(self) class VectorOrDyadicContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def vec(self): return self.getTypedRuleContext(AutolevParser.VecContext,0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterVectorOrDyadic" ): listener.enterVectorOrDyadic(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitVectorOrDyadic" ): listener.exitVectorOrDyadic(self) class ExponentContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.ExprContext) else: return self.getTypedRuleContext(AutolevParser.ExprContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterExponent" ): listener.enterExponent(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitExponent" ): listener.exitExponent(self) class MulDivContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.ExprContext) else: return self.getTypedRuleContext(AutolevParser.ExprContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterMulDiv" ): listener.enterMulDiv(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitMulDiv" ): listener.exitMulDiv(self) class AddSubContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.ExprContext) else: return self.getTypedRuleContext(AutolevParser.ExprContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterAddSub" ): listener.enterAddSub(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitAddSub" ): listener.exitAddSub(self) class FloatContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def FLOAT(self): return self.getToken(AutolevParser.FLOAT, 0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterFloat" ): listener.enterFloat(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitFloat" ): listener.exitFloat(self) class IntContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def INT(self): return self.getToken(AutolevParser.INT, 0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterInt" ): listener.enterInt(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitInt" ): listener.exitInt(self) class IdEqualsExprContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.ExprContext) else: return self.getTypedRuleContext(AutolevParser.ExprContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterIdEqualsExpr" ): listener.enterIdEqualsExpr(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitIdEqualsExpr" ): listener.exitIdEqualsExpr(self) class NegativeOneContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self): return self.getTypedRuleContext(AutolevParser.ExprContext,0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterNegativeOne" ): listener.enterNegativeOne(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitNegativeOne" ): listener.exitNegativeOne(self) class FunctionContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def functionCall(self): return self.getTypedRuleContext(AutolevParser.FunctionCallContext,0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterFunction" ): listener.enterFunction(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitFunction" ): listener.exitFunction(self) class RangessContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def ranges(self): return self.getTypedRuleContext(AutolevParser.RangesContext,0) def ID(self): return self.getToken(AutolevParser.ID, 0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterRangess" ): listener.enterRangess(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitRangess" ): listener.exitRangess(self) class ColonContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.ExprContext) else: return self.getTypedRuleContext(AutolevParser.ExprContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterColon" ): listener.enterColon(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitColon" ): listener.exitColon(self) class IdContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def ID(self): return self.getToken(AutolevParser.ID, 0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterId" ): listener.enterId(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitId" ): listener.exitId(self) class ExpContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def EXP(self): return self.getToken(AutolevParser.EXP, 0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterExp" ): listener.enterExp(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitExp" ): listener.exitExp(self) class MatricesContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def matrix(self): return self.getTypedRuleContext(AutolevParser.MatrixContext,0) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterMatrices" ): listener.enterMatrices(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitMatrices" ): listener.exitMatrices(self) class IndexingContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def ID(self): return self.getToken(AutolevParser.ID, 0) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(AutolevParser.ExprContext) else: return self.getTypedRuleContext(AutolevParser.ExprContext,i) def enterRule(self, listener:ParseTreeListener): if hasattr( listener, "enterIndexing" ): listener.enterIndexing(self) def exitRule(self, listener:ParseTreeListener): if hasattr( listener, "exitIndexing" ): listener.exitIndexing(self) def expr(self, _p:int=0): _parentctx = self._ctx _parentState = self.state localctx = AutolevParser.ExprContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 54 self.enterRecursionRule(localctx, 54, self.RULE_expr, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 408 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,47,self._ctx) if la_ == 1: localctx = AutolevParser.ExpContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 367 self.match(AutolevParser.EXP) pass elif la_ == 2: localctx = AutolevParser.NegativeOneContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 368 self.match(AutolevParser.T__17) self.state = 369 self.expr(12) pass elif la_ == 3: localctx = AutolevParser.FloatContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 370 self.match(AutolevParser.FLOAT) pass elif la_ == 4: localctx = AutolevParser.IntContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 371 self.match(AutolevParser.INT) pass elif la_ == 5: localctx = AutolevParser.IdContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 372 self.match(AutolevParser.ID) self.state = 376 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,43,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 373 self.match(AutolevParser.T__10) self.state = 378 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,43,self._ctx) pass elif la_ == 6: localctx = AutolevParser.VectorOrDyadicContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 379 self.vec() pass elif la_ == 7: localctx = AutolevParser.IndexingContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 380 self.match(AutolevParser.ID) self.state = 381 self.match(AutolevParser.T__0) self.state = 382 self.expr(0) self.state = 387 self._errHandler.sync(self) _la = self._input.LA(1) while _la==10: self.state = 383 self.match(AutolevParser.T__9) self.state = 384 self.expr(0) self.state = 389 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 390 self.match(AutolevParser.T__1) pass elif la_ == 8: localctx = AutolevParser.FunctionContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 392 self.functionCall() pass elif la_ == 9: localctx = AutolevParser.MatricesContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 393 self.matrix() pass elif la_ == 10: localctx = AutolevParser.ParensContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 394 self.match(AutolevParser.T__11) self.state = 395 self.expr(0) self.state = 396 self.match(AutolevParser.T__12) pass elif la_ == 11: localctx = AutolevParser.RangessContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 399 self._errHandler.sync(self) _la = self._input.LA(1) if _la==48: self.state = 398 self.match(AutolevParser.ID) self.state = 401 self.ranges() self.state = 405 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,46,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 402 self.match(AutolevParser.T__10) self.state = 407 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,46,self._ctx) pass self._ctx.stop = self._input.LT(-1) self.state = 427 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,49,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx self.state = 425 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,48,self._ctx) if la_ == 1: localctx = AutolevParser.ExponentContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 410 if not self.precpred(self._ctx, 16): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 16)") self.state = 411 self.match(AutolevParser.T__23) self.state = 412 self.expr(17) pass elif la_ == 2: localctx = AutolevParser.MulDivContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 413 if not self.precpred(self._ctx, 15): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 15)") self.state = 414 _la = self._input.LA(1) if not(_la==25 or _la==26): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 415 self.expr(16) pass elif la_ == 3: localctx = AutolevParser.AddSubContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 416 if not self.precpred(self._ctx, 14): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 14)") self.state = 417 _la = self._input.LA(1) if not(_la==17 or _la==18): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 418 self.expr(15) pass elif la_ == 4: localctx = AutolevParser.IdEqualsExprContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 419 if not self.precpred(self._ctx, 3): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 3)") self.state = 420 self.match(AutolevParser.T__2) self.state = 421 self.expr(4) pass elif la_ == 5: localctx = AutolevParser.ColonContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 422 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 423 self.match(AutolevParser.T__15) self.state = 424 self.expr(3) pass self.state = 429 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,49,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int): if self._predicates == None: self._predicates = dict() self._predicates[27] = self.expr_sempred pred = self._predicates.get(ruleIndex, None) if pred is None: raise Exception("No predicate with index:" + str(ruleIndex)) else: return pred(localctx, predIndex) def expr_sempred(self, localctx:ExprContext, predIndex:int): if predIndex == 0: return self.precpred(self._ctx, 16) if predIndex == 1: return self.precpred(self._ctx, 15) if predIndex == 2: return self.precpred(self._ctx, 14) if predIndex == 3: return self.precpred(self._ctx, 3) if predIndex == 4: return self.precpred(self._ctx, 2)
6358666355462f9153492953a13450c9d3e7c9a2cb372d660d25b1efa1da6303
# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND *** # # Generated from ../LaTeX.g4, derived from latex2sympy # latex2sympy is licensed under the MIT license # https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt # # Generated with antlr4 # antlr4 is licensed under the BSD-3-Clause License # https://github.com/antlr/antlr4/blob/master/LICENSE.txt from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): return [ 4,0,91,911,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5, 2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2, 13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7, 19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2, 26,7,26,2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7, 32,2,33,7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2, 39,7,39,2,40,7,40,2,41,7,41,2,42,7,42,2,43,7,43,2,44,7,44,2,45,7, 45,2,46,7,46,2,47,7,47,2,48,7,48,2,49,7,49,2,50,7,50,2,51,7,51,2, 52,7,52,2,53,7,53,2,54,7,54,2,55,7,55,2,56,7,56,2,57,7,57,2,58,7, 58,2,59,7,59,2,60,7,60,2,61,7,61,2,62,7,62,2,63,7,63,2,64,7,64,2, 65,7,65,2,66,7,66,2,67,7,67,2,68,7,68,2,69,7,69,2,70,7,70,2,71,7, 71,2,72,7,72,2,73,7,73,2,74,7,74,2,75,7,75,2,76,7,76,2,77,7,77,2, 78,7,78,2,79,7,79,2,80,7,80,2,81,7,81,2,82,7,82,2,83,7,83,2,84,7, 84,2,85,7,85,2,86,7,86,2,87,7,87,2,88,7,88,2,89,7,89,2,90,7,90,2, 91,7,91,1,0,1,0,1,1,1,1,1,2,4,2,191,8,2,11,2,12,2,192,1,2,1,2,1, 3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,3,3,209,8,3,1,3,1, 3,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,3,4,224,8,4,1,4,1, 4,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,3,5,241,8, 5,1,5,1,5,1,6,1,6,1,6,1,6,1,6,1,6,1,6,1,6,1,7,1,7,1,7,1,7,1,7,1, 7,1,7,1,7,1,7,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1, 8,1,8,1,8,3,8,277,8,8,1,8,1,8,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1, 9,1,9,1,9,1,9,1,9,1,9,1,9,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10, 1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,11,1,11,1,11,1,11, 1,11,1,11,1,11,1,11,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,12, 1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13, 1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13, 1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13, 1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,3,13, 381,8,13,1,13,1,13,1,14,1,14,1,15,1,15,1,16,1,16,1,17,1,17,1,18, 1,18,1,19,1,19,1,20,1,20,1,21,1,21,1,22,1,22,1,22,1,23,1,23,1,23, 1,24,1,24,1,25,1,25,1,26,1,26,1,27,1,27,1,27,1,27,1,27,1,27,1,27, 1,27,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,29,1,29,1,29,1,29,1,29, 1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,30,1,30,1,30,1,30,1,31,1,31, 1,31,1,31,1,31,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32, 1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32, 1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32, 1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32, 1,32,1,32,1,32,1,32,1,32,1,32,3,32,504,8,32,1,33,1,33,1,33,1,33, 1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,3,33,521, 8,33,1,34,1,34,1,34,1,34,1,34,1,35,1,35,1,35,1,35,1,35,1,35,1,36, 1,36,1,36,1,36,1,36,1,37,1,37,1,37,1,37,1,37,1,38,1,38,1,38,1,38, 1,39,1,39,1,39,1,39,1,40,1,40,1,40,1,40,1,40,1,41,1,41,1,41,1,41, 1,41,1,42,1,42,1,42,1,42,1,42,1,43,1,43,1,43,1,43,1,43,1,44,1,44, 1,44,1,44,1,44,1,45,1,45,1,45,1,45,1,45,1,46,1,46,1,46,1,46,1,46, 1,46,1,46,1,46,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,48,1,48, 1,48,1,48,1,48,1,48,1,48,1,48,1,49,1,49,1,49,1,49,1,49,1,49,1,49, 1,49,1,50,1,50,1,50,1,50,1,50,1,50,1,50,1,50,1,51,1,51,1,51,1,51, 1,51,1,51,1,51,1,51,1,52,1,52,1,52,1,52,1,52,1,52,1,53,1,53,1,53, 1,53,1,53,1,53,1,54,1,54,1,54,1,54,1,54,1,54,1,55,1,55,1,55,1,55, 1,55,1,55,1,55,1,55,1,56,1,56,1,56,1,56,1,56,1,56,1,56,1,56,1,57, 1,57,1,57,1,57,1,57,1,57,1,57,1,57,1,58,1,58,1,58,1,58,1,58,1,58, 1,58,1,58,1,59,1,59,1,59,1,59,1,59,1,59,1,59,1,59,1,60,1,60,1,60, 1,60,1,60,1,60,1,60,1,61,1,61,1,61,1,61,1,61,1,61,1,61,1,62,1,62, 1,62,1,62,1,62,1,62,1,63,1,63,1,63,1,63,1,63,1,63,1,63,1,63,1,63, 1,63,1,64,1,64,1,64,1,64,1,64,1,64,1,64,1,65,1,65,1,65,1,65,1,65, 1,65,1,66,1,66,1,66,1,66,1,66,1,67,1,67,1,67,1,67,1,67,1,67,1,67, 1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,3,67,753,8,67, 1,68,1,68,1,68,1,68,1,68,1,68,1,68,1,69,1,69,1,69,1,69,1,69,1,69, 1,69,1,69,1,70,1,70,1,70,1,70,1,70,1,70,1,70,1,70,1,71,1,71,1,71, 1,71,1,71,1,71,1,71,1,71,1,72,1,72,1,73,1,73,1,74,1,74,1,75,1,75, 1,76,1,76,5,76,796,8,76,10,76,12,76,799,9,76,1,76,1,76,1,76,4,76, 804,8,76,11,76,12,76,805,3,76,808,8,76,1,77,1,77,1,78,1,78,1,79, 1,79,5,79,816,8,79,10,79,12,79,819,9,79,3,79,821,8,79,1,79,1,79, 1,79,5,79,826,8,79,10,79,12,79,829,9,79,1,79,3,79,832,8,79,3,79, 834,8,79,1,80,1,80,1,80,1,80,1,80,1,81,1,81,1,82,1,82,1,82,1,82, 1,82,1,82,1,82,1,82,1,82,3,82,852,8,82,1,83,1,83,1,83,1,83,1,83, 1,83,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,85,1,85, 1,86,1,86,1,86,1,86,1,86,1,86,1,86,1,86,1,86,3,86,881,8,86,1,87, 1,87,1,87,1,87,1,87,1,87,1,88,1,88,1,88,1,88,1,88,1,88,1,88,1,88, 1,88,1,88,1,89,1,89,1,90,4,90,902,8,90,11,90,12,90,903,1,91,1,91, 4,91,908,8,91,11,91,12,91,909,3,797,817,827,0,92,1,1,3,2,5,3,7,4, 9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,27,14,29,15,31,16, 33,17,35,18,37,19,39,20,41,21,43,22,45,23,47,24,49,25,51,26,53,27, 55,28,57,29,59,30,61,31,63,32,65,33,67,34,69,35,71,36,73,37,75,38, 77,39,79,40,81,41,83,42,85,43,87,44,89,45,91,46,93,47,95,48,97,49, 99,50,101,51,103,52,105,53,107,54,109,55,111,56,113,57,115,58,117, 59,119,60,121,61,123,62,125,63,127,64,129,65,131,66,133,67,135,68, 137,69,139,70,141,71,143,72,145,73,147,74,149,75,151,0,153,76,155, 77,157,78,159,79,161,80,163,81,165,82,167,83,169,84,171,85,173,86, 175,87,177,88,179,89,181,90,183,91,1,0,3,3,0,9,10,13,13,32,32,2, 0,65,90,97,122,1,0,48,57,949,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0, 0,7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0, 17,1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0, 27,1,0,0,0,0,29,1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,0,35,1,0,0,0,0, 37,1,0,0,0,0,39,1,0,0,0,0,41,1,0,0,0,0,43,1,0,0,0,0,45,1,0,0,0,0, 47,1,0,0,0,0,49,1,0,0,0,0,51,1,0,0,0,0,53,1,0,0,0,0,55,1,0,0,0,0, 57,1,0,0,0,0,59,1,0,0,0,0,61,1,0,0,0,0,63,1,0,0,0,0,65,1,0,0,0,0, 67,1,0,0,0,0,69,1,0,0,0,0,71,1,0,0,0,0,73,1,0,0,0,0,75,1,0,0,0,0, 77,1,0,0,0,0,79,1,0,0,0,0,81,1,0,0,0,0,83,1,0,0,0,0,85,1,0,0,0,0, 87,1,0,0,0,0,89,1,0,0,0,0,91,1,0,0,0,0,93,1,0,0,0,0,95,1,0,0,0,0, 97,1,0,0,0,0,99,1,0,0,0,0,101,1,0,0,0,0,103,1,0,0,0,0,105,1,0,0, 0,0,107,1,0,0,0,0,109,1,0,0,0,0,111,1,0,0,0,0,113,1,0,0,0,0,115, 1,0,0,0,0,117,1,0,0,0,0,119,1,0,0,0,0,121,1,0,0,0,0,123,1,0,0,0, 0,125,1,0,0,0,0,127,1,0,0,0,0,129,1,0,0,0,0,131,1,0,0,0,0,133,1, 0,0,0,0,135,1,0,0,0,0,137,1,0,0,0,0,139,1,0,0,0,0,141,1,0,0,0,0, 143,1,0,0,0,0,145,1,0,0,0,0,147,1,0,0,0,0,149,1,0,0,0,0,153,1,0, 0,0,0,155,1,0,0,0,0,157,1,0,0,0,0,159,1,0,0,0,0,161,1,0,0,0,0,163, 1,0,0,0,0,165,1,0,0,0,0,167,1,0,0,0,0,169,1,0,0,0,0,171,1,0,0,0, 0,173,1,0,0,0,0,175,1,0,0,0,0,177,1,0,0,0,0,179,1,0,0,0,0,181,1, 0,0,0,0,183,1,0,0,0,1,185,1,0,0,0,3,187,1,0,0,0,5,190,1,0,0,0,7, 208,1,0,0,0,9,223,1,0,0,0,11,240,1,0,0,0,13,244,1,0,0,0,15,252,1, 0,0,0,17,276,1,0,0,0,19,280,1,0,0,0,21,295,1,0,0,0,23,312,1,0,0, 0,25,320,1,0,0,0,27,380,1,0,0,0,29,384,1,0,0,0,31,386,1,0,0,0,33, 388,1,0,0,0,35,390,1,0,0,0,37,392,1,0,0,0,39,394,1,0,0,0,41,396, 1,0,0,0,43,398,1,0,0,0,45,400,1,0,0,0,47,403,1,0,0,0,49,406,1,0, 0,0,51,408,1,0,0,0,53,410,1,0,0,0,55,412,1,0,0,0,57,420,1,0,0,0, 59,427,1,0,0,0,61,435,1,0,0,0,63,443,1,0,0,0,65,503,1,0,0,0,67,520, 1,0,0,0,69,522,1,0,0,0,71,527,1,0,0,0,73,533,1,0,0,0,75,538,1,0, 0,0,77,543,1,0,0,0,79,547,1,0,0,0,81,551,1,0,0,0,83,556,1,0,0,0, 85,561,1,0,0,0,87,566,1,0,0,0,89,571,1,0,0,0,91,576,1,0,0,0,93,581, 1,0,0,0,95,589,1,0,0,0,97,597,1,0,0,0,99,605,1,0,0,0,101,613,1,0, 0,0,103,621,1,0,0,0,105,629,1,0,0,0,107,635,1,0,0,0,109,641,1,0, 0,0,111,647,1,0,0,0,113,655,1,0,0,0,115,663,1,0,0,0,117,671,1,0, 0,0,119,679,1,0,0,0,121,687,1,0,0,0,123,694,1,0,0,0,125,701,1,0, 0,0,127,707,1,0,0,0,129,717,1,0,0,0,131,724,1,0,0,0,133,730,1,0, 0,0,135,752,1,0,0,0,137,754,1,0,0,0,139,761,1,0,0,0,141,769,1,0, 0,0,143,777,1,0,0,0,145,785,1,0,0,0,147,787,1,0,0,0,149,789,1,0, 0,0,151,791,1,0,0,0,153,793,1,0,0,0,155,809,1,0,0,0,157,811,1,0, 0,0,159,833,1,0,0,0,161,835,1,0,0,0,163,840,1,0,0,0,165,851,1,0, 0,0,167,853,1,0,0,0,169,859,1,0,0,0,171,869,1,0,0,0,173,880,1,0, 0,0,175,882,1,0,0,0,177,888,1,0,0,0,179,898,1,0,0,0,181,901,1,0, 0,0,183,905,1,0,0,0,185,186,5,44,0,0,186,2,1,0,0,0,187,188,5,46, 0,0,188,4,1,0,0,0,189,191,7,0,0,0,190,189,1,0,0,0,191,192,1,0,0, 0,192,190,1,0,0,0,192,193,1,0,0,0,193,194,1,0,0,0,194,195,6,2,0, 0,195,6,1,0,0,0,196,197,5,92,0,0,197,209,5,44,0,0,198,199,5,92,0, 0,199,200,5,116,0,0,200,201,5,104,0,0,201,202,5,105,0,0,202,203, 5,110,0,0,203,204,5,115,0,0,204,205,5,112,0,0,205,206,5,97,0,0,206, 207,5,99,0,0,207,209,5,101,0,0,208,196,1,0,0,0,208,198,1,0,0,0,209, 210,1,0,0,0,210,211,6,3,0,0,211,8,1,0,0,0,212,213,5,92,0,0,213,224, 5,58,0,0,214,215,5,92,0,0,215,216,5,109,0,0,216,217,5,101,0,0,217, 218,5,100,0,0,218,219,5,115,0,0,219,220,5,112,0,0,220,221,5,97,0, 0,221,222,5,99,0,0,222,224,5,101,0,0,223,212,1,0,0,0,223,214,1,0, 0,0,224,225,1,0,0,0,225,226,6,4,0,0,226,10,1,0,0,0,227,228,5,92, 0,0,228,241,5,59,0,0,229,230,5,92,0,0,230,231,5,116,0,0,231,232, 5,104,0,0,232,233,5,105,0,0,233,234,5,99,0,0,234,235,5,107,0,0,235, 236,5,115,0,0,236,237,5,112,0,0,237,238,5,97,0,0,238,239,5,99,0, 0,239,241,5,101,0,0,240,227,1,0,0,0,240,229,1,0,0,0,241,242,1,0, 0,0,242,243,6,5,0,0,243,12,1,0,0,0,244,245,5,92,0,0,245,246,5,113, 0,0,246,247,5,117,0,0,247,248,5,97,0,0,248,249,5,100,0,0,249,250, 1,0,0,0,250,251,6,6,0,0,251,14,1,0,0,0,252,253,5,92,0,0,253,254, 5,113,0,0,254,255,5,113,0,0,255,256,5,117,0,0,256,257,5,97,0,0,257, 258,5,100,0,0,258,259,1,0,0,0,259,260,6,7,0,0,260,16,1,0,0,0,261, 262,5,92,0,0,262,277,5,33,0,0,263,264,5,92,0,0,264,265,5,110,0,0, 265,266,5,101,0,0,266,267,5,103,0,0,267,268,5,116,0,0,268,269,5, 104,0,0,269,270,5,105,0,0,270,271,5,110,0,0,271,272,5,115,0,0,272, 273,5,112,0,0,273,274,5,97,0,0,274,275,5,99,0,0,275,277,5,101,0, 0,276,261,1,0,0,0,276,263,1,0,0,0,277,278,1,0,0,0,278,279,6,8,0, 0,279,18,1,0,0,0,280,281,5,92,0,0,281,282,5,110,0,0,282,283,5,101, 0,0,283,284,5,103,0,0,284,285,5,109,0,0,285,286,5,101,0,0,286,287, 5,100,0,0,287,288,5,115,0,0,288,289,5,112,0,0,289,290,5,97,0,0,290, 291,5,99,0,0,291,292,5,101,0,0,292,293,1,0,0,0,293,294,6,9,0,0,294, 20,1,0,0,0,295,296,5,92,0,0,296,297,5,110,0,0,297,298,5,101,0,0, 298,299,5,103,0,0,299,300,5,116,0,0,300,301,5,104,0,0,301,302,5, 105,0,0,302,303,5,99,0,0,303,304,5,107,0,0,304,305,5,115,0,0,305, 306,5,112,0,0,306,307,5,97,0,0,307,308,5,99,0,0,308,309,5,101,0, 0,309,310,1,0,0,0,310,311,6,10,0,0,311,22,1,0,0,0,312,313,5,92,0, 0,313,314,5,108,0,0,314,315,5,101,0,0,315,316,5,102,0,0,316,317, 5,116,0,0,317,318,1,0,0,0,318,319,6,11,0,0,319,24,1,0,0,0,320,321, 5,92,0,0,321,322,5,114,0,0,322,323,5,105,0,0,323,324,5,103,0,0,324, 325,5,104,0,0,325,326,5,116,0,0,326,327,1,0,0,0,327,328,6,12,0,0, 328,26,1,0,0,0,329,330,5,92,0,0,330,331,5,118,0,0,331,332,5,114, 0,0,332,333,5,117,0,0,333,334,5,108,0,0,334,381,5,101,0,0,335,336, 5,92,0,0,336,337,5,118,0,0,337,338,5,99,0,0,338,339,5,101,0,0,339, 340,5,110,0,0,340,341,5,116,0,0,341,342,5,101,0,0,342,381,5,114, 0,0,343,344,5,92,0,0,344,345,5,118,0,0,345,346,5,98,0,0,346,347, 5,111,0,0,347,381,5,120,0,0,348,349,5,92,0,0,349,350,5,118,0,0,350, 351,5,115,0,0,351,352,5,107,0,0,352,353,5,105,0,0,353,381,5,112, 0,0,354,355,5,92,0,0,355,356,5,118,0,0,356,357,5,115,0,0,357,358, 5,112,0,0,358,359,5,97,0,0,359,360,5,99,0,0,360,381,5,101,0,0,361, 362,5,92,0,0,362,363,5,104,0,0,363,364,5,102,0,0,364,365,5,105,0, 0,365,381,5,108,0,0,366,367,5,92,0,0,367,381,5,42,0,0,368,369,5, 92,0,0,369,381,5,45,0,0,370,371,5,92,0,0,371,381,5,46,0,0,372,373, 5,92,0,0,373,381,5,47,0,0,374,375,5,92,0,0,375,381,5,34,0,0,376, 377,5,92,0,0,377,381,5,40,0,0,378,379,5,92,0,0,379,381,5,61,0,0, 380,329,1,0,0,0,380,335,1,0,0,0,380,343,1,0,0,0,380,348,1,0,0,0, 380,354,1,0,0,0,380,361,1,0,0,0,380,366,1,0,0,0,380,368,1,0,0,0, 380,370,1,0,0,0,380,372,1,0,0,0,380,374,1,0,0,0,380,376,1,0,0,0, 380,378,1,0,0,0,381,382,1,0,0,0,382,383,6,13,0,0,383,28,1,0,0,0, 384,385,5,43,0,0,385,30,1,0,0,0,386,387,5,45,0,0,387,32,1,0,0,0, 388,389,5,42,0,0,389,34,1,0,0,0,390,391,5,47,0,0,391,36,1,0,0,0, 392,393,5,40,0,0,393,38,1,0,0,0,394,395,5,41,0,0,395,40,1,0,0,0, 396,397,5,123,0,0,397,42,1,0,0,0,398,399,5,125,0,0,399,44,1,0,0, 0,400,401,5,92,0,0,401,402,5,123,0,0,402,46,1,0,0,0,403,404,5,92, 0,0,404,405,5,125,0,0,405,48,1,0,0,0,406,407,5,91,0,0,407,50,1,0, 0,0,408,409,5,93,0,0,409,52,1,0,0,0,410,411,5,124,0,0,411,54,1,0, 0,0,412,413,5,92,0,0,413,414,5,114,0,0,414,415,5,105,0,0,415,416, 5,103,0,0,416,417,5,104,0,0,417,418,5,116,0,0,418,419,5,124,0,0, 419,56,1,0,0,0,420,421,5,92,0,0,421,422,5,108,0,0,422,423,5,101, 0,0,423,424,5,102,0,0,424,425,5,116,0,0,425,426,5,124,0,0,426,58, 1,0,0,0,427,428,5,92,0,0,428,429,5,108,0,0,429,430,5,97,0,0,430, 431,5,110,0,0,431,432,5,103,0,0,432,433,5,108,0,0,433,434,5,101, 0,0,434,60,1,0,0,0,435,436,5,92,0,0,436,437,5,114,0,0,437,438,5, 97,0,0,438,439,5,110,0,0,439,440,5,103,0,0,440,441,5,108,0,0,441, 442,5,101,0,0,442,62,1,0,0,0,443,444,5,92,0,0,444,445,5,108,0,0, 445,446,5,105,0,0,446,447,5,109,0,0,447,64,1,0,0,0,448,449,5,92, 0,0,449,450,5,116,0,0,450,504,5,111,0,0,451,452,5,92,0,0,452,453, 5,114,0,0,453,454,5,105,0,0,454,455,5,103,0,0,455,456,5,104,0,0, 456,457,5,116,0,0,457,458,5,97,0,0,458,459,5,114,0,0,459,460,5,114, 0,0,460,461,5,111,0,0,461,504,5,119,0,0,462,463,5,92,0,0,463,464, 5,82,0,0,464,465,5,105,0,0,465,466,5,103,0,0,466,467,5,104,0,0,467, 468,5,116,0,0,468,469,5,97,0,0,469,470,5,114,0,0,470,471,5,114,0, 0,471,472,5,111,0,0,472,504,5,119,0,0,473,474,5,92,0,0,474,475,5, 108,0,0,475,476,5,111,0,0,476,477,5,110,0,0,477,478,5,103,0,0,478, 479,5,114,0,0,479,480,5,105,0,0,480,481,5,103,0,0,481,482,5,104, 0,0,482,483,5,116,0,0,483,484,5,97,0,0,484,485,5,114,0,0,485,486, 5,114,0,0,486,487,5,111,0,0,487,504,5,119,0,0,488,489,5,92,0,0,489, 490,5,76,0,0,490,491,5,111,0,0,491,492,5,110,0,0,492,493,5,103,0, 0,493,494,5,114,0,0,494,495,5,105,0,0,495,496,5,103,0,0,496,497, 5,104,0,0,497,498,5,116,0,0,498,499,5,97,0,0,499,500,5,114,0,0,500, 501,5,114,0,0,501,502,5,111,0,0,502,504,5,119,0,0,503,448,1,0,0, 0,503,451,1,0,0,0,503,462,1,0,0,0,503,473,1,0,0,0,503,488,1,0,0, 0,504,66,1,0,0,0,505,506,5,92,0,0,506,507,5,105,0,0,507,508,5,110, 0,0,508,521,5,116,0,0,509,510,5,92,0,0,510,511,5,105,0,0,511,512, 5,110,0,0,512,513,5,116,0,0,513,514,5,92,0,0,514,515,5,108,0,0,515, 516,5,105,0,0,516,517,5,109,0,0,517,518,5,105,0,0,518,519,5,116, 0,0,519,521,5,115,0,0,520,505,1,0,0,0,520,509,1,0,0,0,521,68,1,0, 0,0,522,523,5,92,0,0,523,524,5,115,0,0,524,525,5,117,0,0,525,526, 5,109,0,0,526,70,1,0,0,0,527,528,5,92,0,0,528,529,5,112,0,0,529, 530,5,114,0,0,530,531,5,111,0,0,531,532,5,100,0,0,532,72,1,0,0,0, 533,534,5,92,0,0,534,535,5,101,0,0,535,536,5,120,0,0,536,537,5,112, 0,0,537,74,1,0,0,0,538,539,5,92,0,0,539,540,5,108,0,0,540,541,5, 111,0,0,541,542,5,103,0,0,542,76,1,0,0,0,543,544,5,92,0,0,544,545, 5,108,0,0,545,546,5,103,0,0,546,78,1,0,0,0,547,548,5,92,0,0,548, 549,5,108,0,0,549,550,5,110,0,0,550,80,1,0,0,0,551,552,5,92,0,0, 552,553,5,115,0,0,553,554,5,105,0,0,554,555,5,110,0,0,555,82,1,0, 0,0,556,557,5,92,0,0,557,558,5,99,0,0,558,559,5,111,0,0,559,560, 5,115,0,0,560,84,1,0,0,0,561,562,5,92,0,0,562,563,5,116,0,0,563, 564,5,97,0,0,564,565,5,110,0,0,565,86,1,0,0,0,566,567,5,92,0,0,567, 568,5,99,0,0,568,569,5,115,0,0,569,570,5,99,0,0,570,88,1,0,0,0,571, 572,5,92,0,0,572,573,5,115,0,0,573,574,5,101,0,0,574,575,5,99,0, 0,575,90,1,0,0,0,576,577,5,92,0,0,577,578,5,99,0,0,578,579,5,111, 0,0,579,580,5,116,0,0,580,92,1,0,0,0,581,582,5,92,0,0,582,583,5, 97,0,0,583,584,5,114,0,0,584,585,5,99,0,0,585,586,5,115,0,0,586, 587,5,105,0,0,587,588,5,110,0,0,588,94,1,0,0,0,589,590,5,92,0,0, 590,591,5,97,0,0,591,592,5,114,0,0,592,593,5,99,0,0,593,594,5,99, 0,0,594,595,5,111,0,0,595,596,5,115,0,0,596,96,1,0,0,0,597,598,5, 92,0,0,598,599,5,97,0,0,599,600,5,114,0,0,600,601,5,99,0,0,601,602, 5,116,0,0,602,603,5,97,0,0,603,604,5,110,0,0,604,98,1,0,0,0,605, 606,5,92,0,0,606,607,5,97,0,0,607,608,5,114,0,0,608,609,5,99,0,0, 609,610,5,99,0,0,610,611,5,115,0,0,611,612,5,99,0,0,612,100,1,0, 0,0,613,614,5,92,0,0,614,615,5,97,0,0,615,616,5,114,0,0,616,617, 5,99,0,0,617,618,5,115,0,0,618,619,5,101,0,0,619,620,5,99,0,0,620, 102,1,0,0,0,621,622,5,92,0,0,622,623,5,97,0,0,623,624,5,114,0,0, 624,625,5,99,0,0,625,626,5,99,0,0,626,627,5,111,0,0,627,628,5,116, 0,0,628,104,1,0,0,0,629,630,5,92,0,0,630,631,5,115,0,0,631,632,5, 105,0,0,632,633,5,110,0,0,633,634,5,104,0,0,634,106,1,0,0,0,635, 636,5,92,0,0,636,637,5,99,0,0,637,638,5,111,0,0,638,639,5,115,0, 0,639,640,5,104,0,0,640,108,1,0,0,0,641,642,5,92,0,0,642,643,5,116, 0,0,643,644,5,97,0,0,644,645,5,110,0,0,645,646,5,104,0,0,646,110, 1,0,0,0,647,648,5,92,0,0,648,649,5,97,0,0,649,650,5,114,0,0,650, 651,5,115,0,0,651,652,5,105,0,0,652,653,5,110,0,0,653,654,5,104, 0,0,654,112,1,0,0,0,655,656,5,92,0,0,656,657,5,97,0,0,657,658,5, 114,0,0,658,659,5,99,0,0,659,660,5,111,0,0,660,661,5,115,0,0,661, 662,5,104,0,0,662,114,1,0,0,0,663,664,5,92,0,0,664,665,5,97,0,0, 665,666,5,114,0,0,666,667,5,116,0,0,667,668,5,97,0,0,668,669,5,110, 0,0,669,670,5,104,0,0,670,116,1,0,0,0,671,672,5,92,0,0,672,673,5, 108,0,0,673,674,5,102,0,0,674,675,5,108,0,0,675,676,5,111,0,0,676, 677,5,111,0,0,677,678,5,114,0,0,678,118,1,0,0,0,679,680,5,92,0,0, 680,681,5,114,0,0,681,682,5,102,0,0,682,683,5,108,0,0,683,684,5, 111,0,0,684,685,5,111,0,0,685,686,5,114,0,0,686,120,1,0,0,0,687, 688,5,92,0,0,688,689,5,108,0,0,689,690,5,99,0,0,690,691,5,101,0, 0,691,692,5,105,0,0,692,693,5,108,0,0,693,122,1,0,0,0,694,695,5, 92,0,0,695,696,5,114,0,0,696,697,5,99,0,0,697,698,5,101,0,0,698, 699,5,105,0,0,699,700,5,108,0,0,700,124,1,0,0,0,701,702,5,92,0,0, 702,703,5,115,0,0,703,704,5,113,0,0,704,705,5,114,0,0,705,706,5, 116,0,0,706,126,1,0,0,0,707,708,5,92,0,0,708,709,5,111,0,0,709,710, 5,118,0,0,710,711,5,101,0,0,711,712,5,114,0,0,712,713,5,108,0,0, 713,714,5,105,0,0,714,715,5,110,0,0,715,716,5,101,0,0,716,128,1, 0,0,0,717,718,5,92,0,0,718,719,5,116,0,0,719,720,5,105,0,0,720,721, 5,109,0,0,721,722,5,101,0,0,722,723,5,115,0,0,723,130,1,0,0,0,724, 725,5,92,0,0,725,726,5,99,0,0,726,727,5,100,0,0,727,728,5,111,0, 0,728,729,5,116,0,0,729,132,1,0,0,0,730,731,5,92,0,0,731,732,5,100, 0,0,732,733,5,105,0,0,733,734,5,118,0,0,734,134,1,0,0,0,735,736, 5,92,0,0,736,737,5,102,0,0,737,738,5,114,0,0,738,739,5,97,0,0,739, 753,5,99,0,0,740,741,5,92,0,0,741,742,5,100,0,0,742,743,5,102,0, 0,743,744,5,114,0,0,744,745,5,97,0,0,745,753,5,99,0,0,746,747,5, 92,0,0,747,748,5,116,0,0,748,749,5,102,0,0,749,750,5,114,0,0,750, 751,5,97,0,0,751,753,5,99,0,0,752,735,1,0,0,0,752,740,1,0,0,0,752, 746,1,0,0,0,753,136,1,0,0,0,754,755,5,92,0,0,755,756,5,98,0,0,756, 757,5,105,0,0,757,758,5,110,0,0,758,759,5,111,0,0,759,760,5,109, 0,0,760,138,1,0,0,0,761,762,5,92,0,0,762,763,5,100,0,0,763,764,5, 98,0,0,764,765,5,105,0,0,765,766,5,110,0,0,766,767,5,111,0,0,767, 768,5,109,0,0,768,140,1,0,0,0,769,770,5,92,0,0,770,771,5,116,0,0, 771,772,5,98,0,0,772,773,5,105,0,0,773,774,5,110,0,0,774,775,5,111, 0,0,775,776,5,109,0,0,776,142,1,0,0,0,777,778,5,92,0,0,778,779,5, 109,0,0,779,780,5,97,0,0,780,781,5,116,0,0,781,782,5,104,0,0,782, 783,5,105,0,0,783,784,5,116,0,0,784,144,1,0,0,0,785,786,5,95,0,0, 786,146,1,0,0,0,787,788,5,94,0,0,788,148,1,0,0,0,789,790,5,58,0, 0,790,150,1,0,0,0,791,792,7,0,0,0,792,152,1,0,0,0,793,797,5,100, 0,0,794,796,3,151,75,0,795,794,1,0,0,0,796,799,1,0,0,0,797,798,1, 0,0,0,797,795,1,0,0,0,798,807,1,0,0,0,799,797,1,0,0,0,800,808,7, 1,0,0,801,803,5,92,0,0,802,804,7,1,0,0,803,802,1,0,0,0,804,805,1, 0,0,0,805,803,1,0,0,0,805,806,1,0,0,0,806,808,1,0,0,0,807,800,1, 0,0,0,807,801,1,0,0,0,808,154,1,0,0,0,809,810,7,1,0,0,810,156,1, 0,0,0,811,812,7,2,0,0,812,158,1,0,0,0,813,817,5,38,0,0,814,816,3, 151,75,0,815,814,1,0,0,0,816,819,1,0,0,0,817,818,1,0,0,0,817,815, 1,0,0,0,818,821,1,0,0,0,819,817,1,0,0,0,820,813,1,0,0,0,820,821, 1,0,0,0,821,822,1,0,0,0,822,834,5,61,0,0,823,831,5,61,0,0,824,826, 3,151,75,0,825,824,1,0,0,0,826,829,1,0,0,0,827,828,1,0,0,0,827,825, 1,0,0,0,828,830,1,0,0,0,829,827,1,0,0,0,830,832,5,38,0,0,831,827, 1,0,0,0,831,832,1,0,0,0,832,834,1,0,0,0,833,820,1,0,0,0,833,823, 1,0,0,0,834,160,1,0,0,0,835,836,5,92,0,0,836,837,5,110,0,0,837,838, 5,101,0,0,838,839,5,113,0,0,839,162,1,0,0,0,840,841,5,60,0,0,841, 164,1,0,0,0,842,843,5,92,0,0,843,844,5,108,0,0,844,845,5,101,0,0, 845,852,5,113,0,0,846,847,5,92,0,0,847,848,5,108,0,0,848,852,5,101, 0,0,849,852,3,167,83,0,850,852,3,169,84,0,851,842,1,0,0,0,851,846, 1,0,0,0,851,849,1,0,0,0,851,850,1,0,0,0,852,166,1,0,0,0,853,854, 5,92,0,0,854,855,5,108,0,0,855,856,5,101,0,0,856,857,5,113,0,0,857, 858,5,113,0,0,858,168,1,0,0,0,859,860,5,92,0,0,860,861,5,108,0,0, 861,862,5,101,0,0,862,863,5,113,0,0,863,864,5,115,0,0,864,865,5, 108,0,0,865,866,5,97,0,0,866,867,5,110,0,0,867,868,5,116,0,0,868, 170,1,0,0,0,869,870,5,62,0,0,870,172,1,0,0,0,871,872,5,92,0,0,872, 873,5,103,0,0,873,874,5,101,0,0,874,881,5,113,0,0,875,876,5,92,0, 0,876,877,5,103,0,0,877,881,5,101,0,0,878,881,3,175,87,0,879,881, 3,177,88,0,880,871,1,0,0,0,880,875,1,0,0,0,880,878,1,0,0,0,880,879, 1,0,0,0,881,174,1,0,0,0,882,883,5,92,0,0,883,884,5,103,0,0,884,885, 5,101,0,0,885,886,5,113,0,0,886,887,5,113,0,0,887,176,1,0,0,0,888, 889,5,92,0,0,889,890,5,103,0,0,890,891,5,101,0,0,891,892,5,113,0, 0,892,893,5,115,0,0,893,894,5,108,0,0,894,895,5,97,0,0,895,896,5, 110,0,0,896,897,5,116,0,0,897,178,1,0,0,0,898,899,5,33,0,0,899,180, 1,0,0,0,900,902,5,39,0,0,901,900,1,0,0,0,902,903,1,0,0,0,903,901, 1,0,0,0,903,904,1,0,0,0,904,182,1,0,0,0,905,907,5,92,0,0,906,908, 7,1,0,0,907,906,1,0,0,0,908,909,1,0,0,0,909,907,1,0,0,0,909,910, 1,0,0,0,910,184,1,0,0,0,22,0,192,208,223,240,276,380,503,520,752, 797,805,807,817,820,827,831,833,851,880,903,909,1,6,0,0 ] class LaTeXLexer(Lexer): atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] T__0 = 1 T__1 = 2 WS = 3 THINSPACE = 4 MEDSPACE = 5 THICKSPACE = 6 QUAD = 7 QQUAD = 8 NEGTHINSPACE = 9 NEGMEDSPACE = 10 NEGTHICKSPACE = 11 CMD_LEFT = 12 CMD_RIGHT = 13 IGNORE = 14 ADD = 15 SUB = 16 MUL = 17 DIV = 18 L_PAREN = 19 R_PAREN = 20 L_BRACE = 21 R_BRACE = 22 L_BRACE_LITERAL = 23 R_BRACE_LITERAL = 24 L_BRACKET = 25 R_BRACKET = 26 BAR = 27 R_BAR = 28 L_BAR = 29 L_ANGLE = 30 R_ANGLE = 31 FUNC_LIM = 32 LIM_APPROACH_SYM = 33 FUNC_INT = 34 FUNC_SUM = 35 FUNC_PROD = 36 FUNC_EXP = 37 FUNC_LOG = 38 FUNC_LG = 39 FUNC_LN = 40 FUNC_SIN = 41 FUNC_COS = 42 FUNC_TAN = 43 FUNC_CSC = 44 FUNC_SEC = 45 FUNC_COT = 46 FUNC_ARCSIN = 47 FUNC_ARCCOS = 48 FUNC_ARCTAN = 49 FUNC_ARCCSC = 50 FUNC_ARCSEC = 51 FUNC_ARCCOT = 52 FUNC_SINH = 53 FUNC_COSH = 54 FUNC_TANH = 55 FUNC_ARSINH = 56 FUNC_ARCOSH = 57 FUNC_ARTANH = 58 L_FLOOR = 59 R_FLOOR = 60 L_CEIL = 61 R_CEIL = 62 FUNC_SQRT = 63 FUNC_OVERLINE = 64 CMD_TIMES = 65 CMD_CDOT = 66 CMD_DIV = 67 CMD_FRAC = 68 CMD_BINOM = 69 CMD_DBINOM = 70 CMD_TBINOM = 71 CMD_MATHIT = 72 UNDERSCORE = 73 CARET = 74 COLON = 75 DIFFERENTIAL = 76 LETTER = 77 DIGIT = 78 EQUAL = 79 NEQ = 80 LT = 81 LTE = 82 LTE_Q = 83 LTE_S = 84 GT = 85 GTE = 86 GTE_Q = 87 GTE_S = 88 BANG = 89 SINGLE_QUOTES = 90 SYMBOL = 91 channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ] modeNames = [ "DEFAULT_MODE" ] literalNames = [ "<INVALID>", "','", "'.'", "'\\quad'", "'\\qquad'", "'\\negmedspace'", "'\\negthickspace'", "'\\left'", "'\\right'", "'+'", "'-'", "'*'", "'/'", "'('", "')'", "'{'", "'}'", "'\\{'", "'\\}'", "'['", "']'", "'|'", "'\\right|'", "'\\left|'", "'\\langle'", "'\\rangle'", "'\\lim'", "'\\sum'", "'\\prod'", "'\\exp'", "'\\log'", "'\\lg'", "'\\ln'", "'\\sin'", "'\\cos'", "'\\tan'", "'\\csc'", "'\\sec'", "'\\cot'", "'\\arcsin'", "'\\arccos'", "'\\arctan'", "'\\arccsc'", "'\\arcsec'", "'\\arccot'", "'\\sinh'", "'\\cosh'", "'\\tanh'", "'\\arsinh'", "'\\arcosh'", "'\\artanh'", "'\\lfloor'", "'\\rfloor'", "'\\lceil'", "'\\rceil'", "'\\sqrt'", "'\\overline'", "'\\times'", "'\\cdot'", "'\\div'", "'\\binom'", "'\\dbinom'", "'\\tbinom'", "'\\mathit'", "'_'", "'^'", "':'", "'\\neq'", "'<'", "'\\leqq'", "'\\leqslant'", "'>'", "'\\geqq'", "'\\geqslant'", "'!'" ] symbolicNames = [ "<INVALID>", "WS", "THINSPACE", "MEDSPACE", "THICKSPACE", "QUAD", "QQUAD", "NEGTHINSPACE", "NEGMEDSPACE", "NEGTHICKSPACE", "CMD_LEFT", "CMD_RIGHT", "IGNORE", "ADD", "SUB", "MUL", "DIV", "L_PAREN", "R_PAREN", "L_BRACE", "R_BRACE", "L_BRACE_LITERAL", "R_BRACE_LITERAL", "L_BRACKET", "R_BRACKET", "BAR", "R_BAR", "L_BAR", "L_ANGLE", "R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM", "FUNC_INT", "FUNC_SUM", "FUNC_PROD", "FUNC_EXP", "FUNC_LOG", "FUNC_LG", "FUNC_LN", "FUNC_SIN", "FUNC_COS", "FUNC_TAN", "FUNC_CSC", "FUNC_SEC", "FUNC_COT", "FUNC_ARCSIN", "FUNC_ARCCOS", "FUNC_ARCTAN", "FUNC_ARCCSC", "FUNC_ARCSEC", "FUNC_ARCCOT", "FUNC_SINH", "FUNC_COSH", "FUNC_TANH", "FUNC_ARSINH", "FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR", "R_FLOOR", "L_CEIL", "R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE", "CMD_TIMES", "CMD_CDOT", "CMD_DIV", "CMD_FRAC", "CMD_BINOM", "CMD_DBINOM", "CMD_TBINOM", "CMD_MATHIT", "UNDERSCORE", "CARET", "COLON", "DIFFERENTIAL", "LETTER", "DIGIT", "EQUAL", "NEQ", "LT", "LTE", "LTE_Q", "LTE_S", "GT", "GTE", "GTE_Q", "GTE_S", "BANG", "SINGLE_QUOTES", "SYMBOL" ] ruleNames = [ "T__0", "T__1", "WS", "THINSPACE", "MEDSPACE", "THICKSPACE", "QUAD", "QQUAD", "NEGTHINSPACE", "NEGMEDSPACE", "NEGTHICKSPACE", "CMD_LEFT", "CMD_RIGHT", "IGNORE", "ADD", "SUB", "MUL", "DIV", "L_PAREN", "R_PAREN", "L_BRACE", "R_BRACE", "L_BRACE_LITERAL", "R_BRACE_LITERAL", "L_BRACKET", "R_BRACKET", "BAR", "R_BAR", "L_BAR", "L_ANGLE", "R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM", "FUNC_INT", "FUNC_SUM", "FUNC_PROD", "FUNC_EXP", "FUNC_LOG", "FUNC_LG", "FUNC_LN", "FUNC_SIN", "FUNC_COS", "FUNC_TAN", "FUNC_CSC", "FUNC_SEC", "FUNC_COT", "FUNC_ARCSIN", "FUNC_ARCCOS", "FUNC_ARCTAN", "FUNC_ARCCSC", "FUNC_ARCSEC", "FUNC_ARCCOT", "FUNC_SINH", "FUNC_COSH", "FUNC_TANH", "FUNC_ARSINH", "FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR", "R_FLOOR", "L_CEIL", "R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE", "CMD_TIMES", "CMD_CDOT", "CMD_DIV", "CMD_FRAC", "CMD_BINOM", "CMD_DBINOM", "CMD_TBINOM", "CMD_MATHIT", "UNDERSCORE", "CARET", "COLON", "WS_CHAR", "DIFFERENTIAL", "LETTER", "DIGIT", "EQUAL", "NEQ", "LT", "LTE", "LTE_Q", "LTE_S", "GT", "GTE", "GTE_Q", "GTE_S", "BANG", "SINGLE_QUOTES", "SYMBOL" ] grammarFileName = "LaTeX.g4" def __init__(self, input=None, output:TextIO = sys.stdout): super().__init__(input, output) self.checkVersion("4.11.1") self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) self._actions = None self._predicates = None
66fa27a6f4d2def2d2395a5ab3cf0cdc27cd9d484f503b0208f3e4e300585061
# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND *** # # Generated from ../LaTeX.g4, derived from latex2sympy # latex2sympy is licensed under the MIT license # https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt # # Generated with antlr4 # antlr4 is licensed under the BSD-3-Clause License # https://github.com/antlr/antlr4/blob/master/LICENSE.txt from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): return [ 4,1,91,522,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7, 6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,13,7,13, 2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,19,2,20, 7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,26,7,26, 2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7,32,2,33, 7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2,39,7,39, 2,40,7,40,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,5,1,91,8,1,10,1,12,1,94, 9,1,1,2,1,2,1,2,1,2,1,3,1,3,1,4,1,4,1,4,1,4,1,4,1,4,5,4,108,8,4, 10,4,12,4,111,9,4,1,5,1,5,1,5,1,5,1,5,1,5,5,5,119,8,5,10,5,12,5, 122,9,5,1,6,1,6,1,6,1,6,1,6,1,6,5,6,130,8,6,10,6,12,6,133,9,6,1, 7,1,7,1,7,4,7,138,8,7,11,7,12,7,139,3,7,142,8,7,1,8,1,8,1,8,1,8, 5,8,148,8,8,10,8,12,8,151,9,8,3,8,153,8,8,1,9,1,9,5,9,157,8,9,10, 9,12,9,160,9,9,1,10,1,10,5,10,164,8,10,10,10,12,10,167,9,10,1,11, 1,11,3,11,171,8,11,1,12,1,12,1,12,1,12,1,12,1,12,3,12,179,8,12,1, 13,1,13,1,13,1,13,3,13,185,8,13,1,13,1,13,1,14,1,14,1,14,1,14,3, 14,193,8,14,1,14,1,14,1,15,1,15,1,15,1,15,1,15,1,15,1,15,1,15,1, 15,1,15,3,15,207,8,15,1,15,3,15,210,8,15,5,15,212,8,15,10,15,12, 15,215,9,15,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,3, 16,227,8,16,1,16,3,16,230,8,16,5,16,232,8,16,10,16,12,16,235,9,16, 1,17,1,17,1,17,1,17,1,17,1,17,3,17,243,8,17,1,18,1,18,1,18,1,18, 1,18,3,18,250,8,18,1,19,1,19,1,19,1,19,1,19,1,19,1,19,1,19,1,19, 1,19,1,19,1,19,1,19,1,19,1,19,1,19,3,19,268,8,19,1,20,1,20,1,20, 1,20,1,21,4,21,275,8,21,11,21,12,21,276,1,21,1,21,1,21,1,21,5,21, 283,8,21,10,21,12,21,286,9,21,1,21,1,21,4,21,290,8,21,11,21,12,21, 291,3,21,294,8,21,1,22,1,22,3,22,298,8,22,1,22,3,22,301,8,22,1,22, 3,22,304,8,22,1,22,3,22,307,8,22,3,22,309,8,22,1,22,1,22,1,22,1, 22,1,22,1,22,1,22,3,22,318,8,22,1,23,1,23,1,23,1,23,1,24,1,24,1, 24,1,24,1,25,1,25,1,25,1,25,1,25,1,26,5,26,334,8,26,10,26,12,26, 337,9,26,1,27,1,27,1,27,1,27,1,27,1,27,3,27,345,8,27,1,27,1,27,1, 27,1,27,1,27,3,27,352,8,27,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1, 28,1,29,1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,31,1,31,1,32,1,32,3, 32,374,8,32,1,32,3,32,377,8,32,1,32,3,32,380,8,32,1,32,3,32,383, 8,32,3,32,385,8,32,1,32,1,32,1,32,1,32,1,32,3,32,392,8,32,1,32,1, 32,3,32,396,8,32,1,32,3,32,399,8,32,1,32,3,32,402,8,32,1,32,3,32, 405,8,32,3,32,407,8,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1, 32,1,32,1,32,3,32,420,8,32,1,32,3,32,423,8,32,1,32,1,32,1,32,3,32, 428,8,32,1,32,1,32,1,32,1,32,1,32,3,32,435,8,32,1,32,1,32,1,32,1, 32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,3, 32,453,8,32,1,32,1,32,1,32,1,32,1,32,1,32,3,32,461,8,32,1,33,1,33, 1,33,1,33,1,33,3,33,468,8,33,1,34,1,34,1,34,1,34,1,34,1,34,1,34, 1,34,1,34,1,34,1,34,3,34,481,8,34,3,34,483,8,34,1,34,1,34,1,35,1, 35,1,35,1,35,1,35,3,35,492,8,35,1,36,1,36,1,37,1,37,1,37,1,37,1, 37,1,37,3,37,502,8,37,1,38,1,38,1,38,1,38,1,38,1,38,3,38,510,8,38, 1,39,1,39,1,39,1,39,1,39,1,40,1,40,1,40,1,40,1,40,1,40,0,6,2,8,10, 12,30,32,41,0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36, 38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80, 0,9,2,0,79,82,85,86,1,0,15,16,3,0,17,18,65,67,75,75,2,0,77,77,91, 91,1,0,27,28,2,0,27,27,29,29,1,0,69,71,1,0,37,58,1,0,35,36,563,0, 82,1,0,0,0,2,84,1,0,0,0,4,95,1,0,0,0,6,99,1,0,0,0,8,101,1,0,0,0, 10,112,1,0,0,0,12,123,1,0,0,0,14,141,1,0,0,0,16,152,1,0,0,0,18,154, 1,0,0,0,20,161,1,0,0,0,22,170,1,0,0,0,24,172,1,0,0,0,26,180,1,0, 0,0,28,188,1,0,0,0,30,196,1,0,0,0,32,216,1,0,0,0,34,242,1,0,0,0, 36,249,1,0,0,0,38,267,1,0,0,0,40,269,1,0,0,0,42,274,1,0,0,0,44,317, 1,0,0,0,46,319,1,0,0,0,48,323,1,0,0,0,50,327,1,0,0,0,52,335,1,0, 0,0,54,338,1,0,0,0,56,353,1,0,0,0,58,361,1,0,0,0,60,365,1,0,0,0, 62,369,1,0,0,0,64,460,1,0,0,0,66,467,1,0,0,0,68,469,1,0,0,0,70,491, 1,0,0,0,72,493,1,0,0,0,74,495,1,0,0,0,76,503,1,0,0,0,78,511,1,0, 0,0,80,516,1,0,0,0,82,83,3,2,1,0,83,1,1,0,0,0,84,85,6,1,-1,0,85, 86,3,6,3,0,86,92,1,0,0,0,87,88,10,2,0,0,88,89,7,0,0,0,89,91,3,2, 1,3,90,87,1,0,0,0,91,94,1,0,0,0,92,90,1,0,0,0,92,93,1,0,0,0,93,3, 1,0,0,0,94,92,1,0,0,0,95,96,3,6,3,0,96,97,5,79,0,0,97,98,3,6,3,0, 98,5,1,0,0,0,99,100,3,8,4,0,100,7,1,0,0,0,101,102,6,4,-1,0,102,103, 3,10,5,0,103,109,1,0,0,0,104,105,10,2,0,0,105,106,7,1,0,0,106,108, 3,8,4,3,107,104,1,0,0,0,108,111,1,0,0,0,109,107,1,0,0,0,109,110, 1,0,0,0,110,9,1,0,0,0,111,109,1,0,0,0,112,113,6,5,-1,0,113,114,3, 14,7,0,114,120,1,0,0,0,115,116,10,2,0,0,116,117,7,2,0,0,117,119, 3,10,5,3,118,115,1,0,0,0,119,122,1,0,0,0,120,118,1,0,0,0,120,121, 1,0,0,0,121,11,1,0,0,0,122,120,1,0,0,0,123,124,6,6,-1,0,124,125, 3,16,8,0,125,131,1,0,0,0,126,127,10,2,0,0,127,128,7,2,0,0,128,130, 3,12,6,3,129,126,1,0,0,0,130,133,1,0,0,0,131,129,1,0,0,0,131,132, 1,0,0,0,132,13,1,0,0,0,133,131,1,0,0,0,134,135,7,1,0,0,135,142,3, 14,7,0,136,138,3,18,9,0,137,136,1,0,0,0,138,139,1,0,0,0,139,137, 1,0,0,0,139,140,1,0,0,0,140,142,1,0,0,0,141,134,1,0,0,0,141,137, 1,0,0,0,142,15,1,0,0,0,143,144,7,1,0,0,144,153,3,16,8,0,145,149, 3,18,9,0,146,148,3,20,10,0,147,146,1,0,0,0,148,151,1,0,0,0,149,147, 1,0,0,0,149,150,1,0,0,0,150,153,1,0,0,0,151,149,1,0,0,0,152,143, 1,0,0,0,152,145,1,0,0,0,153,17,1,0,0,0,154,158,3,30,15,0,155,157, 3,22,11,0,156,155,1,0,0,0,157,160,1,0,0,0,158,156,1,0,0,0,158,159, 1,0,0,0,159,19,1,0,0,0,160,158,1,0,0,0,161,165,3,32,16,0,162,164, 3,22,11,0,163,162,1,0,0,0,164,167,1,0,0,0,165,163,1,0,0,0,165,166, 1,0,0,0,166,21,1,0,0,0,167,165,1,0,0,0,168,171,5,89,0,0,169,171, 3,24,12,0,170,168,1,0,0,0,170,169,1,0,0,0,171,23,1,0,0,0,172,178, 5,27,0,0,173,179,3,28,14,0,174,179,3,26,13,0,175,176,3,28,14,0,176, 177,3,26,13,0,177,179,1,0,0,0,178,173,1,0,0,0,178,174,1,0,0,0,178, 175,1,0,0,0,179,25,1,0,0,0,180,181,5,73,0,0,181,184,5,21,0,0,182, 185,3,6,3,0,183,185,3,4,2,0,184,182,1,0,0,0,184,183,1,0,0,0,185, 186,1,0,0,0,186,187,5,22,0,0,187,27,1,0,0,0,188,189,5,74,0,0,189, 192,5,21,0,0,190,193,3,6,3,0,191,193,3,4,2,0,192,190,1,0,0,0,192, 191,1,0,0,0,193,194,1,0,0,0,194,195,5,22,0,0,195,29,1,0,0,0,196, 197,6,15,-1,0,197,198,3,34,17,0,198,213,1,0,0,0,199,200,10,2,0,0, 200,206,5,74,0,0,201,207,3,44,22,0,202,203,5,21,0,0,203,204,3,6, 3,0,204,205,5,22,0,0,205,207,1,0,0,0,206,201,1,0,0,0,206,202,1,0, 0,0,207,209,1,0,0,0,208,210,3,74,37,0,209,208,1,0,0,0,209,210,1, 0,0,0,210,212,1,0,0,0,211,199,1,0,0,0,212,215,1,0,0,0,213,211,1, 0,0,0,213,214,1,0,0,0,214,31,1,0,0,0,215,213,1,0,0,0,216,217,6,16, -1,0,217,218,3,36,18,0,218,233,1,0,0,0,219,220,10,2,0,0,220,226, 5,74,0,0,221,227,3,44,22,0,222,223,5,21,0,0,223,224,3,6,3,0,224, 225,5,22,0,0,225,227,1,0,0,0,226,221,1,0,0,0,226,222,1,0,0,0,227, 229,1,0,0,0,228,230,3,74,37,0,229,228,1,0,0,0,229,230,1,0,0,0,230, 232,1,0,0,0,231,219,1,0,0,0,232,235,1,0,0,0,233,231,1,0,0,0,233, 234,1,0,0,0,234,33,1,0,0,0,235,233,1,0,0,0,236,243,3,38,19,0,237, 243,3,40,20,0,238,243,3,64,32,0,239,243,3,44,22,0,240,243,3,58,29, 0,241,243,3,60,30,0,242,236,1,0,0,0,242,237,1,0,0,0,242,238,1,0, 0,0,242,239,1,0,0,0,242,240,1,0,0,0,242,241,1,0,0,0,243,35,1,0,0, 0,244,250,3,38,19,0,245,250,3,40,20,0,246,250,3,44,22,0,247,250, 3,58,29,0,248,250,3,60,30,0,249,244,1,0,0,0,249,245,1,0,0,0,249, 246,1,0,0,0,249,247,1,0,0,0,249,248,1,0,0,0,250,37,1,0,0,0,251,252, 5,19,0,0,252,253,3,6,3,0,253,254,5,20,0,0,254,268,1,0,0,0,255,256, 5,25,0,0,256,257,3,6,3,0,257,258,5,26,0,0,258,268,1,0,0,0,259,260, 5,21,0,0,260,261,3,6,3,0,261,262,5,22,0,0,262,268,1,0,0,0,263,264, 5,23,0,0,264,265,3,6,3,0,265,266,5,24,0,0,266,268,1,0,0,0,267,251, 1,0,0,0,267,255,1,0,0,0,267,259,1,0,0,0,267,263,1,0,0,0,268,39,1, 0,0,0,269,270,5,27,0,0,270,271,3,6,3,0,271,272,5,27,0,0,272,41,1, 0,0,0,273,275,5,78,0,0,274,273,1,0,0,0,275,276,1,0,0,0,276,274,1, 0,0,0,276,277,1,0,0,0,277,284,1,0,0,0,278,279,5,1,0,0,279,280,5, 78,0,0,280,281,5,78,0,0,281,283,5,78,0,0,282,278,1,0,0,0,283,286, 1,0,0,0,284,282,1,0,0,0,284,285,1,0,0,0,285,293,1,0,0,0,286,284, 1,0,0,0,287,289,5,2,0,0,288,290,5,78,0,0,289,288,1,0,0,0,290,291, 1,0,0,0,291,289,1,0,0,0,291,292,1,0,0,0,292,294,1,0,0,0,293,287, 1,0,0,0,293,294,1,0,0,0,294,43,1,0,0,0,295,308,7,3,0,0,296,298,3, 74,37,0,297,296,1,0,0,0,297,298,1,0,0,0,298,300,1,0,0,0,299,301, 5,90,0,0,300,299,1,0,0,0,300,301,1,0,0,0,301,309,1,0,0,0,302,304, 5,90,0,0,303,302,1,0,0,0,303,304,1,0,0,0,304,306,1,0,0,0,305,307, 3,74,37,0,306,305,1,0,0,0,306,307,1,0,0,0,307,309,1,0,0,0,308,297, 1,0,0,0,308,303,1,0,0,0,309,318,1,0,0,0,310,318,3,42,21,0,311,318, 5,76,0,0,312,318,3,50,25,0,313,318,3,54,27,0,314,318,3,56,28,0,315, 318,3,46,23,0,316,318,3,48,24,0,317,295,1,0,0,0,317,310,1,0,0,0, 317,311,1,0,0,0,317,312,1,0,0,0,317,313,1,0,0,0,317,314,1,0,0,0, 317,315,1,0,0,0,317,316,1,0,0,0,318,45,1,0,0,0,319,320,5,30,0,0, 320,321,3,6,3,0,321,322,7,4,0,0,322,47,1,0,0,0,323,324,7,5,0,0,324, 325,3,6,3,0,325,326,5,31,0,0,326,49,1,0,0,0,327,328,5,72,0,0,328, 329,5,21,0,0,329,330,3,52,26,0,330,331,5,22,0,0,331,51,1,0,0,0,332, 334,5,77,0,0,333,332,1,0,0,0,334,337,1,0,0,0,335,333,1,0,0,0,335, 336,1,0,0,0,336,53,1,0,0,0,337,335,1,0,0,0,338,344,5,68,0,0,339, 345,5,78,0,0,340,341,5,21,0,0,341,342,3,6,3,0,342,343,5,22,0,0,343, 345,1,0,0,0,344,339,1,0,0,0,344,340,1,0,0,0,345,351,1,0,0,0,346, 352,5,78,0,0,347,348,5,21,0,0,348,349,3,6,3,0,349,350,5,22,0,0,350, 352,1,0,0,0,351,346,1,0,0,0,351,347,1,0,0,0,352,55,1,0,0,0,353,354, 7,6,0,0,354,355,5,21,0,0,355,356,3,6,3,0,356,357,5,22,0,0,357,358, 5,21,0,0,358,359,3,6,3,0,359,360,5,22,0,0,360,57,1,0,0,0,361,362, 5,59,0,0,362,363,3,6,3,0,363,364,5,60,0,0,364,59,1,0,0,0,365,366, 5,61,0,0,366,367,3,6,3,0,367,368,5,62,0,0,368,61,1,0,0,0,369,370, 7,7,0,0,370,63,1,0,0,0,371,384,3,62,31,0,372,374,3,74,37,0,373,372, 1,0,0,0,373,374,1,0,0,0,374,376,1,0,0,0,375,377,3,76,38,0,376,375, 1,0,0,0,376,377,1,0,0,0,377,385,1,0,0,0,378,380,3,76,38,0,379,378, 1,0,0,0,379,380,1,0,0,0,380,382,1,0,0,0,381,383,3,74,37,0,382,381, 1,0,0,0,382,383,1,0,0,0,383,385,1,0,0,0,384,373,1,0,0,0,384,379, 1,0,0,0,385,391,1,0,0,0,386,387,5,19,0,0,387,388,3,70,35,0,388,389, 5,20,0,0,389,392,1,0,0,0,390,392,3,72,36,0,391,386,1,0,0,0,391,390, 1,0,0,0,392,461,1,0,0,0,393,406,7,3,0,0,394,396,3,74,37,0,395,394, 1,0,0,0,395,396,1,0,0,0,396,398,1,0,0,0,397,399,5,90,0,0,398,397, 1,0,0,0,398,399,1,0,0,0,399,407,1,0,0,0,400,402,5,90,0,0,401,400, 1,0,0,0,401,402,1,0,0,0,402,404,1,0,0,0,403,405,3,74,37,0,404,403, 1,0,0,0,404,405,1,0,0,0,405,407,1,0,0,0,406,395,1,0,0,0,406,401, 1,0,0,0,407,408,1,0,0,0,408,409,5,19,0,0,409,410,3,66,33,0,410,411, 5,20,0,0,411,461,1,0,0,0,412,419,5,34,0,0,413,414,3,74,37,0,414, 415,3,76,38,0,415,420,1,0,0,0,416,417,3,76,38,0,417,418,3,74,37, 0,418,420,1,0,0,0,419,413,1,0,0,0,419,416,1,0,0,0,419,420,1,0,0, 0,420,427,1,0,0,0,421,423,3,8,4,0,422,421,1,0,0,0,422,423,1,0,0, 0,423,424,1,0,0,0,424,428,5,76,0,0,425,428,3,54,27,0,426,428,3,8, 4,0,427,422,1,0,0,0,427,425,1,0,0,0,427,426,1,0,0,0,428,461,1,0, 0,0,429,434,5,63,0,0,430,431,5,25,0,0,431,432,3,6,3,0,432,433,5, 26,0,0,433,435,1,0,0,0,434,430,1,0,0,0,434,435,1,0,0,0,435,436,1, 0,0,0,436,437,5,21,0,0,437,438,3,6,3,0,438,439,5,22,0,0,439,461, 1,0,0,0,440,441,5,64,0,0,441,442,5,21,0,0,442,443,3,6,3,0,443,444, 5,22,0,0,444,461,1,0,0,0,445,452,7,8,0,0,446,447,3,78,39,0,447,448, 3,76,38,0,448,453,1,0,0,0,449,450,3,76,38,0,450,451,3,78,39,0,451, 453,1,0,0,0,452,446,1,0,0,0,452,449,1,0,0,0,453,454,1,0,0,0,454, 455,3,10,5,0,455,461,1,0,0,0,456,457,5,32,0,0,457,458,3,68,34,0, 458,459,3,10,5,0,459,461,1,0,0,0,460,371,1,0,0,0,460,393,1,0,0,0, 460,412,1,0,0,0,460,429,1,0,0,0,460,440,1,0,0,0,460,445,1,0,0,0, 460,456,1,0,0,0,461,65,1,0,0,0,462,463,3,6,3,0,463,464,5,1,0,0,464, 465,3,66,33,0,465,468,1,0,0,0,466,468,3,6,3,0,467,462,1,0,0,0,467, 466,1,0,0,0,468,67,1,0,0,0,469,470,5,73,0,0,470,471,5,21,0,0,471, 472,7,3,0,0,472,473,5,33,0,0,473,482,3,6,3,0,474,480,5,74,0,0,475, 476,5,21,0,0,476,477,7,1,0,0,477,481,5,22,0,0,478,481,5,15,0,0,479, 481,5,16,0,0,480,475,1,0,0,0,480,478,1,0,0,0,480,479,1,0,0,0,481, 483,1,0,0,0,482,474,1,0,0,0,482,483,1,0,0,0,483,484,1,0,0,0,484, 485,5,22,0,0,485,69,1,0,0,0,486,492,3,6,3,0,487,488,3,6,3,0,488, 489,5,1,0,0,489,490,3,70,35,0,490,492,1,0,0,0,491,486,1,0,0,0,491, 487,1,0,0,0,492,71,1,0,0,0,493,494,3,12,6,0,494,73,1,0,0,0,495,501, 5,73,0,0,496,502,3,44,22,0,497,498,5,21,0,0,498,499,3,6,3,0,499, 500,5,22,0,0,500,502,1,0,0,0,501,496,1,0,0,0,501,497,1,0,0,0,502, 75,1,0,0,0,503,509,5,74,0,0,504,510,3,44,22,0,505,506,5,21,0,0,506, 507,3,6,3,0,507,508,5,22,0,0,508,510,1,0,0,0,509,504,1,0,0,0,509, 505,1,0,0,0,510,77,1,0,0,0,511,512,5,73,0,0,512,513,5,21,0,0,513, 514,3,4,2,0,514,515,5,22,0,0,515,79,1,0,0,0,516,517,5,73,0,0,517, 518,5,21,0,0,518,519,3,4,2,0,519,520,5,22,0,0,520,81,1,0,0,0,59, 92,109,120,131,139,141,149,152,158,165,170,178,184,192,206,209,213, 226,229,233,242,249,267,276,284,291,293,297,300,303,306,308,317, 335,344,351,373,376,379,382,384,391,395,398,401,404,406,419,422, 427,434,452,460,467,480,482,491,501,509 ] class LaTeXParser ( Parser ): grammarFileName = "LaTeX.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] sharedContextCache = PredictionContextCache() literalNames = [ "<INVALID>", "','", "'.'", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "'\\quad'", "'\\qquad'", "<INVALID>", "'\\negmedspace'", "'\\negthickspace'", "'\\left'", "'\\right'", "<INVALID>", "'+'", "'-'", "'*'", "'/'", "'('", "')'", "'{'", "'}'", "'\\{'", "'\\}'", "'['", "']'", "'|'", "'\\right|'", "'\\left|'", "'\\langle'", "'\\rangle'", "'\\lim'", "<INVALID>", "<INVALID>", "'\\sum'", "'\\prod'", "'\\exp'", "'\\log'", "'\\lg'", "'\\ln'", "'\\sin'", "'\\cos'", "'\\tan'", "'\\csc'", "'\\sec'", "'\\cot'", "'\\arcsin'", "'\\arccos'", "'\\arctan'", "'\\arccsc'", "'\\arcsec'", "'\\arccot'", "'\\sinh'", "'\\cosh'", "'\\tanh'", "'\\arsinh'", "'\\arcosh'", "'\\artanh'", "'\\lfloor'", "'\\rfloor'", "'\\lceil'", "'\\rceil'", "'\\sqrt'", "'\\overline'", "'\\times'", "'\\cdot'", "'\\div'", "<INVALID>", "'\\binom'", "'\\dbinom'", "'\\tbinom'", "'\\mathit'", "'_'", "'^'", "':'", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "'\\neq'", "'<'", "<INVALID>", "'\\leqq'", "'\\leqslant'", "'>'", "<INVALID>", "'\\geqq'", "'\\geqslant'", "'!'" ] symbolicNames = [ "<INVALID>", "<INVALID>", "<INVALID>", "WS", "THINSPACE", "MEDSPACE", "THICKSPACE", "QUAD", "QQUAD", "NEGTHINSPACE", "NEGMEDSPACE", "NEGTHICKSPACE", "CMD_LEFT", "CMD_RIGHT", "IGNORE", "ADD", "SUB", "MUL", "DIV", "L_PAREN", "R_PAREN", "L_BRACE", "R_BRACE", "L_BRACE_LITERAL", "R_BRACE_LITERAL", "L_BRACKET", "R_BRACKET", "BAR", "R_BAR", "L_BAR", "L_ANGLE", "R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM", "FUNC_INT", "FUNC_SUM", "FUNC_PROD", "FUNC_EXP", "FUNC_LOG", "FUNC_LG", "FUNC_LN", "FUNC_SIN", "FUNC_COS", "FUNC_TAN", "FUNC_CSC", "FUNC_SEC", "FUNC_COT", "FUNC_ARCSIN", "FUNC_ARCCOS", "FUNC_ARCTAN", "FUNC_ARCCSC", "FUNC_ARCSEC", "FUNC_ARCCOT", "FUNC_SINH", "FUNC_COSH", "FUNC_TANH", "FUNC_ARSINH", "FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR", "R_FLOOR", "L_CEIL", "R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE", "CMD_TIMES", "CMD_CDOT", "CMD_DIV", "CMD_FRAC", "CMD_BINOM", "CMD_DBINOM", "CMD_TBINOM", "CMD_MATHIT", "UNDERSCORE", "CARET", "COLON", "DIFFERENTIAL", "LETTER", "DIGIT", "EQUAL", "NEQ", "LT", "LTE", "LTE_Q", "LTE_S", "GT", "GTE", "GTE_Q", "GTE_S", "BANG", "SINGLE_QUOTES", "SYMBOL" ] RULE_math = 0 RULE_relation = 1 RULE_equality = 2 RULE_expr = 3 RULE_additive = 4 RULE_mp = 5 RULE_mp_nofunc = 6 RULE_unary = 7 RULE_unary_nofunc = 8 RULE_postfix = 9 RULE_postfix_nofunc = 10 RULE_postfix_op = 11 RULE_eval_at = 12 RULE_eval_at_sub = 13 RULE_eval_at_sup = 14 RULE_exp = 15 RULE_exp_nofunc = 16 RULE_comp = 17 RULE_comp_nofunc = 18 RULE_group = 19 RULE_abs_group = 20 RULE_number = 21 RULE_atom = 22 RULE_bra = 23 RULE_ket = 24 RULE_mathit = 25 RULE_mathit_text = 26 RULE_frac = 27 RULE_binom = 28 RULE_floor = 29 RULE_ceil = 30 RULE_func_normal = 31 RULE_func = 32 RULE_args = 33 RULE_limit_sub = 34 RULE_func_arg = 35 RULE_func_arg_noparens = 36 RULE_subexpr = 37 RULE_supexpr = 38 RULE_subeq = 39 RULE_supeq = 40 ruleNames = [ "math", "relation", "equality", "expr", "additive", "mp", "mp_nofunc", "unary", "unary_nofunc", "postfix", "postfix_nofunc", "postfix_op", "eval_at", "eval_at_sub", "eval_at_sup", "exp", "exp_nofunc", "comp", "comp_nofunc", "group", "abs_group", "number", "atom", "bra", "ket", "mathit", "mathit_text", "frac", "binom", "floor", "ceil", "func_normal", "func", "args", "limit_sub", "func_arg", "func_arg_noparens", "subexpr", "supexpr", "subeq", "supeq" ] EOF = Token.EOF T__0=1 T__1=2 WS=3 THINSPACE=4 MEDSPACE=5 THICKSPACE=6 QUAD=7 QQUAD=8 NEGTHINSPACE=9 NEGMEDSPACE=10 NEGTHICKSPACE=11 CMD_LEFT=12 CMD_RIGHT=13 IGNORE=14 ADD=15 SUB=16 MUL=17 DIV=18 L_PAREN=19 R_PAREN=20 L_BRACE=21 R_BRACE=22 L_BRACE_LITERAL=23 R_BRACE_LITERAL=24 L_BRACKET=25 R_BRACKET=26 BAR=27 R_BAR=28 L_BAR=29 L_ANGLE=30 R_ANGLE=31 FUNC_LIM=32 LIM_APPROACH_SYM=33 FUNC_INT=34 FUNC_SUM=35 FUNC_PROD=36 FUNC_EXP=37 FUNC_LOG=38 FUNC_LG=39 FUNC_LN=40 FUNC_SIN=41 FUNC_COS=42 FUNC_TAN=43 FUNC_CSC=44 FUNC_SEC=45 FUNC_COT=46 FUNC_ARCSIN=47 FUNC_ARCCOS=48 FUNC_ARCTAN=49 FUNC_ARCCSC=50 FUNC_ARCSEC=51 FUNC_ARCCOT=52 FUNC_SINH=53 FUNC_COSH=54 FUNC_TANH=55 FUNC_ARSINH=56 FUNC_ARCOSH=57 FUNC_ARTANH=58 L_FLOOR=59 R_FLOOR=60 L_CEIL=61 R_CEIL=62 FUNC_SQRT=63 FUNC_OVERLINE=64 CMD_TIMES=65 CMD_CDOT=66 CMD_DIV=67 CMD_FRAC=68 CMD_BINOM=69 CMD_DBINOM=70 CMD_TBINOM=71 CMD_MATHIT=72 UNDERSCORE=73 CARET=74 COLON=75 DIFFERENTIAL=76 LETTER=77 DIGIT=78 EQUAL=79 NEQ=80 LT=81 LTE=82 LTE_Q=83 LTE_S=84 GT=85 GTE=86 GTE_Q=87 GTE_S=88 BANG=89 SINGLE_QUOTES=90 SYMBOL=91 def __init__(self, input:TokenStream, output:TextIO = sys.stdout): super().__init__(input, output) self.checkVersion("4.11.1") self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) self._predicates = None class MathContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def relation(self): return self.getTypedRuleContext(LaTeXParser.RelationContext,0) def getRuleIndex(self): return LaTeXParser.RULE_math def math(self): localctx = LaTeXParser.MathContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_math) try: self.enterOuterAlt(localctx, 1) self.state = 82 self.relation(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class RelationContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def relation(self, i:int=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.RelationContext) else: return self.getTypedRuleContext(LaTeXParser.RelationContext,i) def EQUAL(self): return self.getToken(LaTeXParser.EQUAL, 0) def LT(self): return self.getToken(LaTeXParser.LT, 0) def LTE(self): return self.getToken(LaTeXParser.LTE, 0) def GT(self): return self.getToken(LaTeXParser.GT, 0) def GTE(self): return self.getToken(LaTeXParser.GTE, 0) def NEQ(self): return self.getToken(LaTeXParser.NEQ, 0) def getRuleIndex(self): return LaTeXParser.RULE_relation def relation(self, _p:int=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.RelationContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 2 self.enterRecursionRule(localctx, 2, self.RULE_relation, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 85 self.expr() self._ctx.stop = self._input.LT(-1) self.state = 92 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,0,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.RelationContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_relation) self.state = 87 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 88 _la = self._input.LA(1) if not((((_la - 79)) & ~0x3f) == 0 and ((1 << (_la - 79)) & 207) != 0): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 89 self.relation(3) self.state = 94 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,0,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class EqualityContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def EQUAL(self): return self.getToken(LaTeXParser.EQUAL, 0) def getRuleIndex(self): return LaTeXParser.RULE_equality def equality(self): localctx = LaTeXParser.EqualityContext(self, self._ctx, self.state) self.enterRule(localctx, 4, self.RULE_equality) try: self.enterOuterAlt(localctx, 1) self.state = 95 self.expr() self.state = 96 self.match(LaTeXParser.EQUAL) self.state = 97 self.expr() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExprContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def additive(self): return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0) def getRuleIndex(self): return LaTeXParser.RULE_expr def expr(self): localctx = LaTeXParser.ExprContext(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_expr) try: self.enterOuterAlt(localctx, 1) self.state = 99 self.additive(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AdditiveContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def mp(self): return self.getTypedRuleContext(LaTeXParser.MpContext,0) def additive(self, i:int=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.AdditiveContext) else: return self.getTypedRuleContext(LaTeXParser.AdditiveContext,i) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def getRuleIndex(self): return LaTeXParser.RULE_additive def additive(self, _p:int=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.AdditiveContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 8 self.enterRecursionRule(localctx, 8, self.RULE_additive, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 102 self.mp(0) self._ctx.stop = self._input.LT(-1) self.state = 109 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,1,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.AdditiveContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_additive) self.state = 104 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 105 _la = self._input.LA(1) if not(_la==15 or _la==16): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 106 self.additive(3) self.state = 111 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,1,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class MpContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def unary(self): return self.getTypedRuleContext(LaTeXParser.UnaryContext,0) def mp(self, i:int=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.MpContext) else: return self.getTypedRuleContext(LaTeXParser.MpContext,i) def MUL(self): return self.getToken(LaTeXParser.MUL, 0) def CMD_TIMES(self): return self.getToken(LaTeXParser.CMD_TIMES, 0) def CMD_CDOT(self): return self.getToken(LaTeXParser.CMD_CDOT, 0) def DIV(self): return self.getToken(LaTeXParser.DIV, 0) def CMD_DIV(self): return self.getToken(LaTeXParser.CMD_DIV, 0) def COLON(self): return self.getToken(LaTeXParser.COLON, 0) def getRuleIndex(self): return LaTeXParser.RULE_mp def mp(self, _p:int=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.MpContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 10 self.enterRecursionRule(localctx, 10, self.RULE_mp, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 113 self.unary() self._ctx.stop = self._input.LT(-1) self.state = 120 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,2,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.MpContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_mp) self.state = 115 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 116 _la = self._input.LA(1) if not((((_la - 17)) & ~0x3f) == 0 and ((1 << (_la - 17)) & 290200700988686339) != 0): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 117 self.mp(3) self.state = 122 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,2,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class Mp_nofuncContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def unary_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0) def mp_nofunc(self, i:int=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Mp_nofuncContext) else: return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,i) def MUL(self): return self.getToken(LaTeXParser.MUL, 0) def CMD_TIMES(self): return self.getToken(LaTeXParser.CMD_TIMES, 0) def CMD_CDOT(self): return self.getToken(LaTeXParser.CMD_CDOT, 0) def DIV(self): return self.getToken(LaTeXParser.DIV, 0) def CMD_DIV(self): return self.getToken(LaTeXParser.CMD_DIV, 0) def COLON(self): return self.getToken(LaTeXParser.COLON, 0) def getRuleIndex(self): return LaTeXParser.RULE_mp_nofunc def mp_nofunc(self, _p:int=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.Mp_nofuncContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 12 self.enterRecursionRule(localctx, 12, self.RULE_mp_nofunc, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 124 self.unary_nofunc() self._ctx.stop = self._input.LT(-1) self.state = 131 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,3,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.Mp_nofuncContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_mp_nofunc) self.state = 126 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 127 _la = self._input.LA(1) if not((((_la - 17)) & ~0x3f) == 0 and ((1 << (_la - 17)) & 290200700988686339) != 0): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 128 self.mp_nofunc(3) self.state = 133 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,3,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class UnaryContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def unary(self): return self.getTypedRuleContext(LaTeXParser.UnaryContext,0) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def postfix(self, i:int=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.PostfixContext) else: return self.getTypedRuleContext(LaTeXParser.PostfixContext,i) def getRuleIndex(self): return LaTeXParser.RULE_unary def unary(self): localctx = LaTeXParser.UnaryContext(self, self._ctx, self.state) self.enterRule(localctx, 14, self.RULE_unary) self._la = 0 # Token type try: self.state = 141 self._errHandler.sync(self) token = self._input.LA(1) if token in [15, 16]: self.enterOuterAlt(localctx, 1) self.state = 134 _la = self._input.LA(1) if not(_la==15 or _la==16): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 135 self.unary() pass elif token in [19, 21, 23, 25, 27, 29, 30, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 63, 64, 68, 69, 70, 71, 72, 76, 77, 78, 91]: self.enterOuterAlt(localctx, 2) self.state = 137 self._errHandler.sync(self) _alt = 1 while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt == 1: self.state = 136 self.postfix() else: raise NoViableAltException(self) self.state = 139 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,4,self._ctx) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Unary_nofuncContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def unary_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def postfix(self): return self.getTypedRuleContext(LaTeXParser.PostfixContext,0) def postfix_nofunc(self, i:int=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Postfix_nofuncContext) else: return self.getTypedRuleContext(LaTeXParser.Postfix_nofuncContext,i) def getRuleIndex(self): return LaTeXParser.RULE_unary_nofunc def unary_nofunc(self): localctx = LaTeXParser.Unary_nofuncContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_unary_nofunc) self._la = 0 # Token type try: self.state = 152 self._errHandler.sync(self) token = self._input.LA(1) if token in [15, 16]: self.enterOuterAlt(localctx, 1) self.state = 143 _la = self._input.LA(1) if not(_la==15 or _la==16): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 144 self.unary_nofunc() pass elif token in [19, 21, 23, 25, 27, 29, 30, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 63, 64, 68, 69, 70, 71, 72, 76, 77, 78, 91]: self.enterOuterAlt(localctx, 2) self.state = 145 self.postfix() self.state = 149 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,6,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 146 self.postfix_nofunc() self.state = 151 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,6,self._ctx) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class PostfixContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def exp(self): return self.getTypedRuleContext(LaTeXParser.ExpContext,0) def postfix_op(self, i:int=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext) else: return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i) def getRuleIndex(self): return LaTeXParser.RULE_postfix def postfix(self): localctx = LaTeXParser.PostfixContext(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_postfix) try: self.enterOuterAlt(localctx, 1) self.state = 154 self.exp(0) self.state = 158 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,8,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 155 self.postfix_op() self.state = 160 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,8,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Postfix_nofuncContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def exp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0) def postfix_op(self, i:int=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext) else: return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i) def getRuleIndex(self): return LaTeXParser.RULE_postfix_nofunc def postfix_nofunc(self): localctx = LaTeXParser.Postfix_nofuncContext(self, self._ctx, self.state) self.enterRule(localctx, 20, self.RULE_postfix_nofunc) try: self.enterOuterAlt(localctx, 1) self.state = 161 self.exp_nofunc(0) self.state = 165 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,9,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 162 self.postfix_op() self.state = 167 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,9,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Postfix_opContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def BANG(self): return self.getToken(LaTeXParser.BANG, 0) def eval_at(self): return self.getTypedRuleContext(LaTeXParser.Eval_atContext,0) def getRuleIndex(self): return LaTeXParser.RULE_postfix_op def postfix_op(self): localctx = LaTeXParser.Postfix_opContext(self, self._ctx, self.state) self.enterRule(localctx, 22, self.RULE_postfix_op) try: self.state = 170 self._errHandler.sync(self) token = self._input.LA(1) if token in [89]: self.enterOuterAlt(localctx, 1) self.state = 168 self.match(LaTeXParser.BANG) pass elif token in [27]: self.enterOuterAlt(localctx, 2) self.state = 169 self.eval_at() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Eval_atContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def BAR(self): return self.getToken(LaTeXParser.BAR, 0) def eval_at_sup(self): return self.getTypedRuleContext(LaTeXParser.Eval_at_supContext,0) def eval_at_sub(self): return self.getTypedRuleContext(LaTeXParser.Eval_at_subContext,0) def getRuleIndex(self): return LaTeXParser.RULE_eval_at def eval_at(self): localctx = LaTeXParser.Eval_atContext(self, self._ctx, self.state) self.enterRule(localctx, 24, self.RULE_eval_at) try: self.enterOuterAlt(localctx, 1) self.state = 172 self.match(LaTeXParser.BAR) self.state = 178 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,11,self._ctx) if la_ == 1: self.state = 173 self.eval_at_sup() pass elif la_ == 2: self.state = 174 self.eval_at_sub() pass elif la_ == 3: self.state = 175 self.eval_at_sup() self.state = 176 self.eval_at_sub() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Eval_at_subContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def getRuleIndex(self): return LaTeXParser.RULE_eval_at_sub def eval_at_sub(self): localctx = LaTeXParser.Eval_at_subContext(self, self._ctx, self.state) self.enterRule(localctx, 26, self.RULE_eval_at_sub) try: self.enterOuterAlt(localctx, 1) self.state = 180 self.match(LaTeXParser.UNDERSCORE) self.state = 181 self.match(LaTeXParser.L_BRACE) self.state = 184 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,12,self._ctx) if la_ == 1: self.state = 182 self.expr() pass elif la_ == 2: self.state = 183 self.equality() pass self.state = 186 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Eval_at_supContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def getRuleIndex(self): return LaTeXParser.RULE_eval_at_sup def eval_at_sup(self): localctx = LaTeXParser.Eval_at_supContext(self, self._ctx, self.state) self.enterRule(localctx, 28, self.RULE_eval_at_sup) try: self.enterOuterAlt(localctx, 1) self.state = 188 self.match(LaTeXParser.CARET) self.state = 189 self.match(LaTeXParser.L_BRACE) self.state = 192 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,13,self._ctx) if la_ == 1: self.state = 190 self.expr() pass elif la_ == 2: self.state = 191 self.equality() pass self.state = 194 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExpContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def comp(self): return self.getTypedRuleContext(LaTeXParser.CompContext,0) def exp(self): return self.getTypedRuleContext(LaTeXParser.ExpContext,0) def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_exp def exp(self, _p:int=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.ExpContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 30 self.enterRecursionRule(localctx, 30, self.RULE_exp, _p) try: self.enterOuterAlt(localctx, 1) self.state = 197 self.comp() self._ctx.stop = self._input.LT(-1) self.state = 213 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,16,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.ExpContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_exp) self.state = 199 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 200 self.match(LaTeXParser.CARET) self.state = 206 self._errHandler.sync(self) token = self._input.LA(1) if token in [27, 29, 30, 68, 69, 70, 71, 72, 76, 77, 78, 91]: self.state = 201 self.atom() pass elif token in [21]: self.state = 202 self.match(LaTeXParser.L_BRACE) self.state = 203 self.expr() self.state = 204 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) self.state = 209 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,15,self._ctx) if la_ == 1: self.state = 208 self.subexpr() self.state = 215 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,16,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class Exp_nofuncContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def comp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Comp_nofuncContext,0) def exp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0) def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_exp_nofunc def exp_nofunc(self, _p:int=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.Exp_nofuncContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 32 self.enterRecursionRule(localctx, 32, self.RULE_exp_nofunc, _p) try: self.enterOuterAlt(localctx, 1) self.state = 217 self.comp_nofunc() self._ctx.stop = self._input.LT(-1) self.state = 233 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,19,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.Exp_nofuncContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_exp_nofunc) self.state = 219 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 220 self.match(LaTeXParser.CARET) self.state = 226 self._errHandler.sync(self) token = self._input.LA(1) if token in [27, 29, 30, 68, 69, 70, 71, 72, 76, 77, 78, 91]: self.state = 221 self.atom() pass elif token in [21]: self.state = 222 self.match(LaTeXParser.L_BRACE) self.state = 223 self.expr() self.state = 224 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) self.state = 229 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,18,self._ctx) if la_ == 1: self.state = 228 self.subexpr() self.state = 235 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,19,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class CompContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def group(self): return self.getTypedRuleContext(LaTeXParser.GroupContext,0) def abs_group(self): return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0) def func(self): return self.getTypedRuleContext(LaTeXParser.FuncContext,0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def floor(self): return self.getTypedRuleContext(LaTeXParser.FloorContext,0) def ceil(self): return self.getTypedRuleContext(LaTeXParser.CeilContext,0) def getRuleIndex(self): return LaTeXParser.RULE_comp def comp(self): localctx = LaTeXParser.CompContext(self, self._ctx, self.state) self.enterRule(localctx, 34, self.RULE_comp) try: self.state = 242 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,20,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 236 self.group() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 237 self.abs_group() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 238 self.func() pass elif la_ == 4: self.enterOuterAlt(localctx, 4) self.state = 239 self.atom() pass elif la_ == 5: self.enterOuterAlt(localctx, 5) self.state = 240 self.floor() pass elif la_ == 6: self.enterOuterAlt(localctx, 6) self.state = 241 self.ceil() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Comp_nofuncContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def group(self): return self.getTypedRuleContext(LaTeXParser.GroupContext,0) def abs_group(self): return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def floor(self): return self.getTypedRuleContext(LaTeXParser.FloorContext,0) def ceil(self): return self.getTypedRuleContext(LaTeXParser.CeilContext,0) def getRuleIndex(self): return LaTeXParser.RULE_comp_nofunc def comp_nofunc(self): localctx = LaTeXParser.Comp_nofuncContext(self, self._ctx, self.state) self.enterRule(localctx, 36, self.RULE_comp_nofunc) try: self.state = 249 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,21,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 244 self.group() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 245 self.abs_group() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 246 self.atom() pass elif la_ == 4: self.enterOuterAlt(localctx, 4) self.state = 247 self.floor() pass elif la_ == 5: self.enterOuterAlt(localctx, 5) self.state = 248 self.ceil() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class GroupContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def L_PAREN(self): return self.getToken(LaTeXParser.L_PAREN, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_PAREN(self): return self.getToken(LaTeXParser.R_PAREN, 0) def L_BRACKET(self): return self.getToken(LaTeXParser.L_BRACKET, 0) def R_BRACKET(self): return self.getToken(LaTeXParser.R_BRACKET, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def L_BRACE_LITERAL(self): return self.getToken(LaTeXParser.L_BRACE_LITERAL, 0) def R_BRACE_LITERAL(self): return self.getToken(LaTeXParser.R_BRACE_LITERAL, 0) def getRuleIndex(self): return LaTeXParser.RULE_group def group(self): localctx = LaTeXParser.GroupContext(self, self._ctx, self.state) self.enterRule(localctx, 38, self.RULE_group) try: self.state = 267 self._errHandler.sync(self) token = self._input.LA(1) if token in [19]: self.enterOuterAlt(localctx, 1) self.state = 251 self.match(LaTeXParser.L_PAREN) self.state = 252 self.expr() self.state = 253 self.match(LaTeXParser.R_PAREN) pass elif token in [25]: self.enterOuterAlt(localctx, 2) self.state = 255 self.match(LaTeXParser.L_BRACKET) self.state = 256 self.expr() self.state = 257 self.match(LaTeXParser.R_BRACKET) pass elif token in [21]: self.enterOuterAlt(localctx, 3) self.state = 259 self.match(LaTeXParser.L_BRACE) self.state = 260 self.expr() self.state = 261 self.match(LaTeXParser.R_BRACE) pass elif token in [23]: self.enterOuterAlt(localctx, 4) self.state = 263 self.match(LaTeXParser.L_BRACE_LITERAL) self.state = 264 self.expr() self.state = 265 self.match(LaTeXParser.R_BRACE_LITERAL) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Abs_groupContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def BAR(self, i:int=None): if i is None: return self.getTokens(LaTeXParser.BAR) else: return self.getToken(LaTeXParser.BAR, i) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_abs_group def abs_group(self): localctx = LaTeXParser.Abs_groupContext(self, self._ctx, self.state) self.enterRule(localctx, 40, self.RULE_abs_group) try: self.enterOuterAlt(localctx, 1) self.state = 269 self.match(LaTeXParser.BAR) self.state = 270 self.expr() self.state = 271 self.match(LaTeXParser.BAR) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class NumberContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def DIGIT(self, i:int=None): if i is None: return self.getTokens(LaTeXParser.DIGIT) else: return self.getToken(LaTeXParser.DIGIT, i) def getRuleIndex(self): return LaTeXParser.RULE_number def number(self): localctx = LaTeXParser.NumberContext(self, self._ctx, self.state) self.enterRule(localctx, 42, self.RULE_number) try: self.enterOuterAlt(localctx, 1) self.state = 274 self._errHandler.sync(self) _alt = 1 while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt == 1: self.state = 273 self.match(LaTeXParser.DIGIT) else: raise NoViableAltException(self) self.state = 276 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,23,self._ctx) self.state = 284 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,24,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 278 self.match(LaTeXParser.T__0) self.state = 279 self.match(LaTeXParser.DIGIT) self.state = 280 self.match(LaTeXParser.DIGIT) self.state = 281 self.match(LaTeXParser.DIGIT) self.state = 286 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,24,self._ctx) self.state = 293 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,26,self._ctx) if la_ == 1: self.state = 287 self.match(LaTeXParser.T__1) self.state = 289 self._errHandler.sync(self) _alt = 1 while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt == 1: self.state = 288 self.match(LaTeXParser.DIGIT) else: raise NoViableAltException(self) self.state = 291 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,25,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AtomContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def LETTER(self): return self.getToken(LaTeXParser.LETTER, 0) def SYMBOL(self): return self.getToken(LaTeXParser.SYMBOL, 0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def SINGLE_QUOTES(self): return self.getToken(LaTeXParser.SINGLE_QUOTES, 0) def number(self): return self.getTypedRuleContext(LaTeXParser.NumberContext,0) def DIFFERENTIAL(self): return self.getToken(LaTeXParser.DIFFERENTIAL, 0) def mathit(self): return self.getTypedRuleContext(LaTeXParser.MathitContext,0) def frac(self): return self.getTypedRuleContext(LaTeXParser.FracContext,0) def binom(self): return self.getTypedRuleContext(LaTeXParser.BinomContext,0) def bra(self): return self.getTypedRuleContext(LaTeXParser.BraContext,0) def ket(self): return self.getTypedRuleContext(LaTeXParser.KetContext,0) def getRuleIndex(self): return LaTeXParser.RULE_atom def atom(self): localctx = LaTeXParser.AtomContext(self, self._ctx, self.state) self.enterRule(localctx, 44, self.RULE_atom) self._la = 0 # Token type try: self.state = 317 self._errHandler.sync(self) token = self._input.LA(1) if token in [77, 91]: self.enterOuterAlt(localctx, 1) self.state = 295 _la = self._input.LA(1) if not(_la==77 or _la==91): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 308 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,31,self._ctx) if la_ == 1: self.state = 297 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,27,self._ctx) if la_ == 1: self.state = 296 self.subexpr() self.state = 300 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,28,self._ctx) if la_ == 1: self.state = 299 self.match(LaTeXParser.SINGLE_QUOTES) pass elif la_ == 2: self.state = 303 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,29,self._ctx) if la_ == 1: self.state = 302 self.match(LaTeXParser.SINGLE_QUOTES) self.state = 306 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,30,self._ctx) if la_ == 1: self.state = 305 self.subexpr() pass pass elif token in [78]: self.enterOuterAlt(localctx, 2) self.state = 310 self.number() pass elif token in [76]: self.enterOuterAlt(localctx, 3) self.state = 311 self.match(LaTeXParser.DIFFERENTIAL) pass elif token in [72]: self.enterOuterAlt(localctx, 4) self.state = 312 self.mathit() pass elif token in [68]: self.enterOuterAlt(localctx, 5) self.state = 313 self.frac() pass elif token in [69, 70, 71]: self.enterOuterAlt(localctx, 6) self.state = 314 self.binom() pass elif token in [30]: self.enterOuterAlt(localctx, 7) self.state = 315 self.bra() pass elif token in [27, 29]: self.enterOuterAlt(localctx, 8) self.state = 316 self.ket() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BraContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def L_ANGLE(self): return self.getToken(LaTeXParser.L_ANGLE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BAR(self): return self.getToken(LaTeXParser.R_BAR, 0) def BAR(self): return self.getToken(LaTeXParser.BAR, 0) def getRuleIndex(self): return LaTeXParser.RULE_bra def bra(self): localctx = LaTeXParser.BraContext(self, self._ctx, self.state) self.enterRule(localctx, 46, self.RULE_bra) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 319 self.match(LaTeXParser.L_ANGLE) self.state = 320 self.expr() self.state = 321 _la = self._input.LA(1) if not(_la==27 or _la==28): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class KetContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_ANGLE(self): return self.getToken(LaTeXParser.R_ANGLE, 0) def L_BAR(self): return self.getToken(LaTeXParser.L_BAR, 0) def BAR(self): return self.getToken(LaTeXParser.BAR, 0) def getRuleIndex(self): return LaTeXParser.RULE_ket def ket(self): localctx = LaTeXParser.KetContext(self, self._ctx, self.state) self.enterRule(localctx, 48, self.RULE_ket) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 323 _la = self._input.LA(1) if not(_la==27 or _la==29): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 324 self.expr() self.state = 325 self.match(LaTeXParser.R_ANGLE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MathitContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def CMD_MATHIT(self): return self.getToken(LaTeXParser.CMD_MATHIT, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def mathit_text(self): return self.getTypedRuleContext(LaTeXParser.Mathit_textContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_mathit def mathit(self): localctx = LaTeXParser.MathitContext(self, self._ctx, self.state) self.enterRule(localctx, 50, self.RULE_mathit) try: self.enterOuterAlt(localctx, 1) self.state = 327 self.match(LaTeXParser.CMD_MATHIT) self.state = 328 self.match(LaTeXParser.L_BRACE) self.state = 329 self.mathit_text() self.state = 330 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Mathit_textContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def LETTER(self, i:int=None): if i is None: return self.getTokens(LaTeXParser.LETTER) else: return self.getToken(LaTeXParser.LETTER, i) def getRuleIndex(self): return LaTeXParser.RULE_mathit_text def mathit_text(self): localctx = LaTeXParser.Mathit_textContext(self, self._ctx, self.state) self.enterRule(localctx, 52, self.RULE_mathit_text) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 335 self._errHandler.sync(self) _la = self._input.LA(1) while _la==77: self.state = 332 self.match(LaTeXParser.LETTER) self.state = 337 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FracContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser self.upperd = None # Token self.upper = None # ExprContext self.lowerd = None # Token self.lower = None # ExprContext def CMD_FRAC(self): return self.getToken(LaTeXParser.CMD_FRAC, 0) def L_BRACE(self, i:int=None): if i is None: return self.getTokens(LaTeXParser.L_BRACE) else: return self.getToken(LaTeXParser.L_BRACE, i) def R_BRACE(self, i:int=None): if i is None: return self.getTokens(LaTeXParser.R_BRACE) else: return self.getToken(LaTeXParser.R_BRACE, i) def DIGIT(self, i:int=None): if i is None: return self.getTokens(LaTeXParser.DIGIT) else: return self.getToken(LaTeXParser.DIGIT, i) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def getRuleIndex(self): return LaTeXParser.RULE_frac def frac(self): localctx = LaTeXParser.FracContext(self, self._ctx, self.state) self.enterRule(localctx, 54, self.RULE_frac) try: self.enterOuterAlt(localctx, 1) self.state = 338 self.match(LaTeXParser.CMD_FRAC) self.state = 344 self._errHandler.sync(self) token = self._input.LA(1) if token in [78]: self.state = 339 localctx.upperd = self.match(LaTeXParser.DIGIT) pass elif token in [21]: self.state = 340 self.match(LaTeXParser.L_BRACE) self.state = 341 localctx.upper = self.expr() self.state = 342 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) self.state = 351 self._errHandler.sync(self) token = self._input.LA(1) if token in [78]: self.state = 346 localctx.lowerd = self.match(LaTeXParser.DIGIT) pass elif token in [21]: self.state = 347 self.match(LaTeXParser.L_BRACE) self.state = 348 localctx.lower = self.expr() self.state = 349 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BinomContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser self.n = None # ExprContext self.k = None # ExprContext def L_BRACE(self, i:int=None): if i is None: return self.getTokens(LaTeXParser.L_BRACE) else: return self.getToken(LaTeXParser.L_BRACE, i) def R_BRACE(self, i:int=None): if i is None: return self.getTokens(LaTeXParser.R_BRACE) else: return self.getToken(LaTeXParser.R_BRACE, i) def CMD_BINOM(self): return self.getToken(LaTeXParser.CMD_BINOM, 0) def CMD_DBINOM(self): return self.getToken(LaTeXParser.CMD_DBINOM, 0) def CMD_TBINOM(self): return self.getToken(LaTeXParser.CMD_TBINOM, 0) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def getRuleIndex(self): return LaTeXParser.RULE_binom def binom(self): localctx = LaTeXParser.BinomContext(self, self._ctx, self.state) self.enterRule(localctx, 56, self.RULE_binom) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 353 _la = self._input.LA(1) if not((((_la - 69)) & ~0x3f) == 0 and ((1 << (_la - 69)) & 7) != 0): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 354 self.match(LaTeXParser.L_BRACE) self.state = 355 localctx.n = self.expr() self.state = 356 self.match(LaTeXParser.R_BRACE) self.state = 357 self.match(LaTeXParser.L_BRACE) self.state = 358 localctx.k = self.expr() self.state = 359 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FloorContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser self.val = None # ExprContext def L_FLOOR(self): return self.getToken(LaTeXParser.L_FLOOR, 0) def R_FLOOR(self): return self.getToken(LaTeXParser.R_FLOOR, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_floor def floor(self): localctx = LaTeXParser.FloorContext(self, self._ctx, self.state) self.enterRule(localctx, 58, self.RULE_floor) try: self.enterOuterAlt(localctx, 1) self.state = 361 self.match(LaTeXParser.L_FLOOR) self.state = 362 localctx.val = self.expr() self.state = 363 self.match(LaTeXParser.R_FLOOR) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CeilContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser self.val = None # ExprContext def L_CEIL(self): return self.getToken(LaTeXParser.L_CEIL, 0) def R_CEIL(self): return self.getToken(LaTeXParser.R_CEIL, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_ceil def ceil(self): localctx = LaTeXParser.CeilContext(self, self._ctx, self.state) self.enterRule(localctx, 60, self.RULE_ceil) try: self.enterOuterAlt(localctx, 1) self.state = 365 self.match(LaTeXParser.L_CEIL) self.state = 366 localctx.val = self.expr() self.state = 367 self.match(LaTeXParser.R_CEIL) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Func_normalContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def FUNC_EXP(self): return self.getToken(LaTeXParser.FUNC_EXP, 0) def FUNC_LOG(self): return self.getToken(LaTeXParser.FUNC_LOG, 0) def FUNC_LG(self): return self.getToken(LaTeXParser.FUNC_LG, 0) def FUNC_LN(self): return self.getToken(LaTeXParser.FUNC_LN, 0) def FUNC_SIN(self): return self.getToken(LaTeXParser.FUNC_SIN, 0) def FUNC_COS(self): return self.getToken(LaTeXParser.FUNC_COS, 0) def FUNC_TAN(self): return self.getToken(LaTeXParser.FUNC_TAN, 0) def FUNC_CSC(self): return self.getToken(LaTeXParser.FUNC_CSC, 0) def FUNC_SEC(self): return self.getToken(LaTeXParser.FUNC_SEC, 0) def FUNC_COT(self): return self.getToken(LaTeXParser.FUNC_COT, 0) def FUNC_ARCSIN(self): return self.getToken(LaTeXParser.FUNC_ARCSIN, 0) def FUNC_ARCCOS(self): return self.getToken(LaTeXParser.FUNC_ARCCOS, 0) def FUNC_ARCTAN(self): return self.getToken(LaTeXParser.FUNC_ARCTAN, 0) def FUNC_ARCCSC(self): return self.getToken(LaTeXParser.FUNC_ARCCSC, 0) def FUNC_ARCSEC(self): return self.getToken(LaTeXParser.FUNC_ARCSEC, 0) def FUNC_ARCCOT(self): return self.getToken(LaTeXParser.FUNC_ARCCOT, 0) def FUNC_SINH(self): return self.getToken(LaTeXParser.FUNC_SINH, 0) def FUNC_COSH(self): return self.getToken(LaTeXParser.FUNC_COSH, 0) def FUNC_TANH(self): return self.getToken(LaTeXParser.FUNC_TANH, 0) def FUNC_ARSINH(self): return self.getToken(LaTeXParser.FUNC_ARSINH, 0) def FUNC_ARCOSH(self): return self.getToken(LaTeXParser.FUNC_ARCOSH, 0) def FUNC_ARTANH(self): return self.getToken(LaTeXParser.FUNC_ARTANH, 0) def getRuleIndex(self): return LaTeXParser.RULE_func_normal def func_normal(self): localctx = LaTeXParser.Func_normalContext(self, self._ctx, self.state) self.enterRule(localctx, 62, self.RULE_func_normal) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 369 _la = self._input.LA(1) if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 576460614864470016) != 0): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FuncContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser self.root = None # ExprContext self.base = None # ExprContext def func_normal(self): return self.getTypedRuleContext(LaTeXParser.Func_normalContext,0) def L_PAREN(self): return self.getToken(LaTeXParser.L_PAREN, 0) def func_arg(self): return self.getTypedRuleContext(LaTeXParser.Func_argContext,0) def R_PAREN(self): return self.getToken(LaTeXParser.R_PAREN, 0) def func_arg_noparens(self): return self.getTypedRuleContext(LaTeXParser.Func_arg_noparensContext,0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def supexpr(self): return self.getTypedRuleContext(LaTeXParser.SupexprContext,0) def args(self): return self.getTypedRuleContext(LaTeXParser.ArgsContext,0) def LETTER(self): return self.getToken(LaTeXParser.LETTER, 0) def SYMBOL(self): return self.getToken(LaTeXParser.SYMBOL, 0) def SINGLE_QUOTES(self): return self.getToken(LaTeXParser.SINGLE_QUOTES, 0) def FUNC_INT(self): return self.getToken(LaTeXParser.FUNC_INT, 0) def DIFFERENTIAL(self): return self.getToken(LaTeXParser.DIFFERENTIAL, 0) def frac(self): return self.getTypedRuleContext(LaTeXParser.FracContext,0) def additive(self): return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0) def FUNC_SQRT(self): return self.getToken(LaTeXParser.FUNC_SQRT, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def L_BRACKET(self): return self.getToken(LaTeXParser.L_BRACKET, 0) def R_BRACKET(self): return self.getToken(LaTeXParser.R_BRACKET, 0) def FUNC_OVERLINE(self): return self.getToken(LaTeXParser.FUNC_OVERLINE, 0) def mp(self): return self.getTypedRuleContext(LaTeXParser.MpContext,0) def FUNC_SUM(self): return self.getToken(LaTeXParser.FUNC_SUM, 0) def FUNC_PROD(self): return self.getToken(LaTeXParser.FUNC_PROD, 0) def subeq(self): return self.getTypedRuleContext(LaTeXParser.SubeqContext,0) def FUNC_LIM(self): return self.getToken(LaTeXParser.FUNC_LIM, 0) def limit_sub(self): return self.getTypedRuleContext(LaTeXParser.Limit_subContext,0) def getRuleIndex(self): return LaTeXParser.RULE_func def func(self): localctx = LaTeXParser.FuncContext(self, self._ctx, self.state) self.enterRule(localctx, 64, self.RULE_func) self._la = 0 # Token type try: self.state = 460 self._errHandler.sync(self) token = self._input.LA(1) if token in [37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58]: self.enterOuterAlt(localctx, 1) self.state = 371 self.func_normal() self.state = 384 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,40,self._ctx) if la_ == 1: self.state = 373 self._errHandler.sync(self) _la = self._input.LA(1) if _la==73: self.state = 372 self.subexpr() self.state = 376 self._errHandler.sync(self) _la = self._input.LA(1) if _la==74: self.state = 375 self.supexpr() pass elif la_ == 2: self.state = 379 self._errHandler.sync(self) _la = self._input.LA(1) if _la==74: self.state = 378 self.supexpr() self.state = 382 self._errHandler.sync(self) _la = self._input.LA(1) if _la==73: self.state = 381 self.subexpr() pass self.state = 391 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,41,self._ctx) if la_ == 1: self.state = 386 self.match(LaTeXParser.L_PAREN) self.state = 387 self.func_arg() self.state = 388 self.match(LaTeXParser.R_PAREN) pass elif la_ == 2: self.state = 390 self.func_arg_noparens() pass pass elif token in [77, 91]: self.enterOuterAlt(localctx, 2) self.state = 393 _la = self._input.LA(1) if not(_la==77 or _la==91): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 406 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,46,self._ctx) if la_ == 1: self.state = 395 self._errHandler.sync(self) _la = self._input.LA(1) if _la==73: self.state = 394 self.subexpr() self.state = 398 self._errHandler.sync(self) _la = self._input.LA(1) if _la==90: self.state = 397 self.match(LaTeXParser.SINGLE_QUOTES) pass elif la_ == 2: self.state = 401 self._errHandler.sync(self) _la = self._input.LA(1) if _la==90: self.state = 400 self.match(LaTeXParser.SINGLE_QUOTES) self.state = 404 self._errHandler.sync(self) _la = self._input.LA(1) if _la==73: self.state = 403 self.subexpr() pass self.state = 408 self.match(LaTeXParser.L_PAREN) self.state = 409 self.args() self.state = 410 self.match(LaTeXParser.R_PAREN) pass elif token in [34]: self.enterOuterAlt(localctx, 3) self.state = 412 self.match(LaTeXParser.FUNC_INT) self.state = 419 self._errHandler.sync(self) token = self._input.LA(1) if token in [73]: self.state = 413 self.subexpr() self.state = 414 self.supexpr() pass elif token in [74]: self.state = 416 self.supexpr() self.state = 417 self.subexpr() pass elif token in [15, 16, 19, 21, 23, 25, 27, 29, 30, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 63, 64, 68, 69, 70, 71, 72, 76, 77, 78, 91]: pass else: pass self.state = 427 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,49,self._ctx) if la_ == 1: self.state = 422 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,48,self._ctx) if la_ == 1: self.state = 421 self.additive(0) self.state = 424 self.match(LaTeXParser.DIFFERENTIAL) pass elif la_ == 2: self.state = 425 self.frac() pass elif la_ == 3: self.state = 426 self.additive(0) pass pass elif token in [63]: self.enterOuterAlt(localctx, 4) self.state = 429 self.match(LaTeXParser.FUNC_SQRT) self.state = 434 self._errHandler.sync(self) _la = self._input.LA(1) if _la==25: self.state = 430 self.match(LaTeXParser.L_BRACKET) self.state = 431 localctx.root = self.expr() self.state = 432 self.match(LaTeXParser.R_BRACKET) self.state = 436 self.match(LaTeXParser.L_BRACE) self.state = 437 localctx.base = self.expr() self.state = 438 self.match(LaTeXParser.R_BRACE) pass elif token in [64]: self.enterOuterAlt(localctx, 5) self.state = 440 self.match(LaTeXParser.FUNC_OVERLINE) self.state = 441 self.match(LaTeXParser.L_BRACE) self.state = 442 localctx.base = self.expr() self.state = 443 self.match(LaTeXParser.R_BRACE) pass elif token in [35, 36]: self.enterOuterAlt(localctx, 6) self.state = 445 _la = self._input.LA(1) if not(_la==35 or _la==36): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 452 self._errHandler.sync(self) token = self._input.LA(1) if token in [73]: self.state = 446 self.subeq() self.state = 447 self.supexpr() pass elif token in [74]: self.state = 449 self.supexpr() self.state = 450 self.subeq() pass else: raise NoViableAltException(self) self.state = 454 self.mp(0) pass elif token in [32]: self.enterOuterAlt(localctx, 7) self.state = 456 self.match(LaTeXParser.FUNC_LIM) self.state = 457 self.limit_sub() self.state = 458 self.mp(0) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ArgsContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def args(self): return self.getTypedRuleContext(LaTeXParser.ArgsContext,0) def getRuleIndex(self): return LaTeXParser.RULE_args def args(self): localctx = LaTeXParser.ArgsContext(self, self._ctx, self.state) self.enterRule(localctx, 66, self.RULE_args) try: self.state = 467 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,53,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 462 self.expr() self.state = 463 self.match(LaTeXParser.T__0) self.state = 464 self.args() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 466 self.expr() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Limit_subContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self, i:int=None): if i is None: return self.getTokens(LaTeXParser.L_BRACE) else: return self.getToken(LaTeXParser.L_BRACE, i) def LIM_APPROACH_SYM(self): return self.getToken(LaTeXParser.LIM_APPROACH_SYM, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self, i:int=None): if i is None: return self.getTokens(LaTeXParser.R_BRACE) else: return self.getToken(LaTeXParser.R_BRACE, i) def LETTER(self): return self.getToken(LaTeXParser.LETTER, 0) def SYMBOL(self): return self.getToken(LaTeXParser.SYMBOL, 0) def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def getRuleIndex(self): return LaTeXParser.RULE_limit_sub def limit_sub(self): localctx = LaTeXParser.Limit_subContext(self, self._ctx, self.state) self.enterRule(localctx, 68, self.RULE_limit_sub) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 469 self.match(LaTeXParser.UNDERSCORE) self.state = 470 self.match(LaTeXParser.L_BRACE) self.state = 471 _la = self._input.LA(1) if not(_la==77 or _la==91): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 472 self.match(LaTeXParser.LIM_APPROACH_SYM) self.state = 473 self.expr() self.state = 482 self._errHandler.sync(self) _la = self._input.LA(1) if _la==74: self.state = 474 self.match(LaTeXParser.CARET) self.state = 480 self._errHandler.sync(self) token = self._input.LA(1) if token in [21]: self.state = 475 self.match(LaTeXParser.L_BRACE) self.state = 476 _la = self._input.LA(1) if not(_la==15 or _la==16): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 477 self.match(LaTeXParser.R_BRACE) pass elif token in [15]: self.state = 478 self.match(LaTeXParser.ADD) pass elif token in [16]: self.state = 479 self.match(LaTeXParser.SUB) pass else: raise NoViableAltException(self) self.state = 484 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Func_argContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def func_arg(self): return self.getTypedRuleContext(LaTeXParser.Func_argContext,0) def getRuleIndex(self): return LaTeXParser.RULE_func_arg def func_arg(self): localctx = LaTeXParser.Func_argContext(self, self._ctx, self.state) self.enterRule(localctx, 70, self.RULE_func_arg) try: self.state = 491 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,56,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 486 self.expr() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 487 self.expr() self.state = 488 self.match(LaTeXParser.T__0) self.state = 489 self.func_arg() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Func_arg_noparensContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def mp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,0) def getRuleIndex(self): return LaTeXParser.RULE_func_arg_noparens def func_arg_noparens(self): localctx = LaTeXParser.Func_arg_noparensContext(self, self._ctx, self.state) self.enterRule(localctx, 72, self.RULE_func_arg_noparens) try: self.enterOuterAlt(localctx, 1) self.state = 493 self.mp_nofunc(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SubexprContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_subexpr def subexpr(self): localctx = LaTeXParser.SubexprContext(self, self._ctx, self.state) self.enterRule(localctx, 74, self.RULE_subexpr) try: self.enterOuterAlt(localctx, 1) self.state = 495 self.match(LaTeXParser.UNDERSCORE) self.state = 501 self._errHandler.sync(self) token = self._input.LA(1) if token in [27, 29, 30, 68, 69, 70, 71, 72, 76, 77, 78, 91]: self.state = 496 self.atom() pass elif token in [21]: self.state = 497 self.match(LaTeXParser.L_BRACE) self.state = 498 self.expr() self.state = 499 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SupexprContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_supexpr def supexpr(self): localctx = LaTeXParser.SupexprContext(self, self._ctx, self.state) self.enterRule(localctx, 76, self.RULE_supexpr) try: self.enterOuterAlt(localctx, 1) self.state = 503 self.match(LaTeXParser.CARET) self.state = 509 self._errHandler.sync(self) token = self._input.LA(1) if token in [27, 29, 30, 68, 69, 70, 71, 72, 76, 77, 78, 91]: self.state = 504 self.atom() pass elif token in [21]: self.state = 505 self.match(LaTeXParser.L_BRACE) self.state = 506 self.expr() self.state = 507 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SubeqContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_subeq def subeq(self): localctx = LaTeXParser.SubeqContext(self, self._ctx, self.state) self.enterRule(localctx, 78, self.RULE_subeq) try: self.enterOuterAlt(localctx, 1) self.state = 511 self.match(LaTeXParser.UNDERSCORE) self.state = 512 self.match(LaTeXParser.L_BRACE) self.state = 513 self.equality() self.state = 514 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SupeqContext(ParserRuleContext): __slots__ = 'parser' def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_supeq def supeq(self): localctx = LaTeXParser.SupeqContext(self, self._ctx, self.state) self.enterRule(localctx, 80, self.RULE_supeq) try: self.enterOuterAlt(localctx, 1) self.state = 516 self.match(LaTeXParser.UNDERSCORE) self.state = 517 self.match(LaTeXParser.L_BRACE) self.state = 518 self.equality() self.state = 519 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int): if self._predicates == None: self._predicates = dict() self._predicates[1] = self.relation_sempred self._predicates[4] = self.additive_sempred self._predicates[5] = self.mp_sempred self._predicates[6] = self.mp_nofunc_sempred self._predicates[15] = self.exp_sempred self._predicates[16] = self.exp_nofunc_sempred pred = self._predicates.get(ruleIndex, None) if pred is None: raise Exception("No predicate with index:" + str(ruleIndex)) else: return pred(localctx, predIndex) def relation_sempred(self, localctx:RelationContext, predIndex:int): if predIndex == 0: return self.precpred(self._ctx, 2) def additive_sempred(self, localctx:AdditiveContext, predIndex:int): if predIndex == 1: return self.precpred(self._ctx, 2) def mp_sempred(self, localctx:MpContext, predIndex:int): if predIndex == 2: return self.precpred(self._ctx, 2) def mp_nofunc_sempred(self, localctx:Mp_nofuncContext, predIndex:int): if predIndex == 3: return self.precpred(self._ctx, 2) def exp_sempred(self, localctx:ExpContext, predIndex:int): if predIndex == 4: return self.precpred(self._ctx, 2) def exp_nofunc_sempred(self, localctx:Exp_nofuncContext, predIndex:int): if predIndex == 5: return self.precpred(self._ctx, 2)
b81a72db4dfb4f56c2c59b22168200cc742bbb6622d8e9bc3c50ed742ab935ab
"""Abstract tensor product.""" from sympy.core.add import Add from sympy.core.expr import Expr from sympy.core.mul import Mul from sympy.core.power import Pow from sympy.core.sympify import sympify from sympy.matrices.dense import MutableDenseMatrix as Matrix from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.state import Ket, Bra from sympy.physics.quantum.matrixutils import ( numpy_ndarray, scipy_sparse_matrix, matrix_tensor_product ) from sympy.physics.quantum.trace import Tr __all__ = [ 'TensorProduct', 'tensor_product_simp' ] #----------------------------------------------------------------------------- # Tensor product #----------------------------------------------------------------------------- _combined_printing = False def combined_tensor_printing(combined): """Set flag controlling whether tensor products of states should be printed as a combined bra/ket or as an explicit tensor product of different bra/kets. This is a global setting for all TensorProduct class instances. Parameters ---------- combine : bool When true, tensor product states are combined into one ket/bra, and when false explicit tensor product notation is used between each ket/bra. """ global _combined_printing _combined_printing = combined class TensorProduct(Expr): """The tensor product of two or more arguments. For matrices, this uses ``matrix_tensor_product`` to compute the Kronecker or tensor product matrix. For other objects a symbolic ``TensorProduct`` instance is returned. The tensor product is a non-commutative multiplication that is used primarily with operators and states in quantum mechanics. Currently, the tensor product distinguishes between commutative and non-commutative arguments. Commutative arguments are assumed to be scalars and are pulled out in front of the ``TensorProduct``. Non-commutative arguments remain in the resulting ``TensorProduct``. Parameters ========== args : tuple A sequence of the objects to take the tensor product of. Examples ======== Start with a simple tensor product of SymPy matrices:: >>> from sympy import Matrix >>> from sympy.physics.quantum import TensorProduct >>> m1 = Matrix([[1,2],[3,4]]) >>> m2 = Matrix([[1,0],[0,1]]) >>> TensorProduct(m1, m2) Matrix([ [1, 0, 2, 0], [0, 1, 0, 2], [3, 0, 4, 0], [0, 3, 0, 4]]) >>> TensorProduct(m2, m1) Matrix([ [1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 1, 2], [0, 0, 3, 4]]) We can also construct tensor products of non-commutative symbols: >>> from sympy import Symbol >>> A = Symbol('A',commutative=False) >>> B = Symbol('B',commutative=False) >>> tp = TensorProduct(A, B) >>> tp AxB We can take the dagger of a tensor product (note the order does NOT reverse like the dagger of a normal product): >>> from sympy.physics.quantum import Dagger >>> Dagger(tp) Dagger(A)xDagger(B) Expand can be used to distribute a tensor product across addition: >>> C = Symbol('C',commutative=False) >>> tp = TensorProduct(A+B,C) >>> tp (A + B)xC >>> tp.expand(tensorproduct=True) AxC + BxC """ is_commutative = False def __new__(cls, *args): if isinstance(args[0], (Matrix, numpy_ndarray, scipy_sparse_matrix)): return matrix_tensor_product(*args) c_part, new_args = cls.flatten(sympify(args)) c_part = Mul(*c_part) if len(new_args) == 0: return c_part elif len(new_args) == 1: return c_part * new_args[0] else: tp = Expr.__new__(cls, *new_args) return c_part * tp @classmethod def flatten(cls, args): # TODO: disallow nested TensorProducts. c_part = [] nc_parts = [] for arg in args: cp, ncp = arg.args_cnc() c_part.extend(list(cp)) nc_parts.append(Mul._from_args(ncp)) return c_part, nc_parts def _eval_adjoint(self): return TensorProduct(*[Dagger(i) for i in self.args]) def _eval_rewrite(self, rule, args, **hints): return TensorProduct(*args).expand(tensorproduct=True) def _sympystr(self, printer, *args): length = len(self.args) s = '' for i in range(length): if isinstance(self.args[i], (Add, Pow, Mul)): s = s + '(' s = s + printer._print(self.args[i]) if isinstance(self.args[i], (Add, Pow, Mul)): s = s + ')' if i != length - 1: s = s + 'x' return s def _pretty(self, printer, *args): if (_combined_printing and (all(isinstance(arg, Ket) for arg in self.args) or all(isinstance(arg, Bra) for arg in self.args))): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print('', *args) length_i = len(self.args[i].args) for j in range(length_i): part_pform = printer._print(self.args[i].args[j], *args) next_pform = prettyForm(*next_pform.right(part_pform)) if j != length_i - 1: next_pform = prettyForm(*next_pform.right(', ')) if len(self.args[i].args) > 1: next_pform = prettyForm( *next_pform.parens(left='{', right='}')) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: pform = prettyForm(*pform.right(',' + ' ')) pform = prettyForm(*pform.left(self.args[0].lbracket)) pform = prettyForm(*pform.right(self.args[0].rbracket)) return pform length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (Add, Mul)): next_pform = prettyForm( *next_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right('\N{N-ARY CIRCLED TIMES OPERATOR}' + ' ')) else: pform = prettyForm(*pform.right('x' + ' ')) return pform def _latex(self, printer, *args): if (_combined_printing and (all(isinstance(arg, Ket) for arg in self.args) or all(isinstance(arg, Bra) for arg in self.args))): def _label_wrap(label, nlabels): return label if nlabels == 1 else r"\left\{%s\right\}" % label s = r", ".join([_label_wrap(arg._print_label_latex(printer, *args), len(arg.args)) for arg in self.args]) return r"{%s%s%s}" % (self.args[0].lbracket_latex, s, self.args[0].rbracket_latex) length = len(self.args) s = '' for i in range(length): if isinstance(self.args[i], (Add, Mul)): s = s + '\\left(' # The extra {} brackets are needed to get matplotlib's latex # rendered to render this properly. s = s + '{' + printer._print(self.args[i], *args) + '}' if isinstance(self.args[i], (Add, Mul)): s = s + '\\right)' if i != length - 1: s = s + '\\otimes ' return s def doit(self, **hints): return TensorProduct(*[item.doit(**hints) for item in self.args]) def _eval_expand_tensorproduct(self, **hints): """Distribute TensorProducts across addition.""" args = self.args add_args = [] for i in range(len(args)): if isinstance(args[i], Add): for aa in args[i].args: tp = TensorProduct(*args[:i] + (aa,) + args[i + 1:]) c_part, nc_part = tp.args_cnc() # Check for TensorProduct object: is the one object in nc_part, if any: # (Note: any other object type to be expanded must be added here) if len(nc_part) == 1 and isinstance(nc_part[0], TensorProduct): nc_part = (nc_part[0]._eval_expand_tensorproduct(), ) add_args.append(Mul(*c_part)*Mul(*nc_part)) break if add_args: return Add(*add_args) else: return self def _eval_trace(self, **kwargs): indices = kwargs.get('indices', None) exp = tensor_product_simp(self) if indices is None or len(indices) == 0: return Mul(*[Tr(arg).doit() for arg in exp.args]) else: return Mul(*[Tr(value).doit() if idx in indices else value for idx, value in enumerate(exp.args)]) def tensor_product_simp_Mul(e): """Simplify a Mul with TensorProducts. Current the main use of this is to simplify a ``Mul`` of ``TensorProduct``s to a ``TensorProduct`` of ``Muls``. It currently only works for relatively simple cases where the initial ``Mul`` only has scalars and raw ``TensorProduct``s, not ``Add``, ``Pow``, ``Commutator``s of ``TensorProduct``s. Parameters ========== e : Expr A ``Mul`` of ``TensorProduct``s to be simplified. Returns ======= e : Expr A ``TensorProduct`` of ``Mul``s. Examples ======== This is an example of the type of simplification that this function performs:: >>> from sympy.physics.quantum.tensorproduct import \ tensor_product_simp_Mul, TensorProduct >>> from sympy import Symbol >>> A = Symbol('A',commutative=False) >>> B = Symbol('B',commutative=False) >>> C = Symbol('C',commutative=False) >>> D = Symbol('D',commutative=False) >>> e = TensorProduct(A,B)*TensorProduct(C,D) >>> e AxB*CxD >>> tensor_product_simp_Mul(e) (A*C)x(B*D) """ # TODO: This won't work with Muls that have other composites of # TensorProducts, like an Add, Commutator, etc. # TODO: This only works for the equivalent of single Qbit gates. if not isinstance(e, Mul): return e c_part, nc_part = e.args_cnc() n_nc = len(nc_part) if n_nc == 0: return e elif n_nc == 1: if isinstance(nc_part[0], Pow): return Mul(*c_part) * tensor_product_simp_Pow(nc_part[0]) return e elif e.has(TensorProduct): current = nc_part[0] if not isinstance(current, TensorProduct): if isinstance(current, Pow): if isinstance(current.base, TensorProduct): current = tensor_product_simp_Pow(current) else: raise TypeError('TensorProduct expected, got: %r' % current) n_terms = len(current.args) new_args = list(current.args) for next in nc_part[1:]: # TODO: check the hilbert spaces of next and current here. if isinstance(next, TensorProduct): if n_terms != len(next.args): raise QuantumError( 'TensorProducts of different lengths: %r and %r' % (current, next) ) for i in range(len(new_args)): new_args[i] = new_args[i] * next.args[i] else: if isinstance(next, Pow): if isinstance(next.base, TensorProduct): new_tp = tensor_product_simp_Pow(next) for i in range(len(new_args)): new_args[i] = new_args[i] * new_tp.args[i] else: raise TypeError('TensorProduct expected, got: %r' % next) else: raise TypeError('TensorProduct expected, got: %r' % next) current = next return Mul(*c_part) * TensorProduct(*new_args) elif e.has(Pow): new_args = [ tensor_product_simp_Pow(nc) for nc in nc_part ] return tensor_product_simp_Mul(Mul(*c_part) * TensorProduct(*new_args)) else: return e def tensor_product_simp_Pow(e): """Evaluates ``Pow`` expressions whose base is ``TensorProduct``""" if not isinstance(e, Pow): return e if isinstance(e.base, TensorProduct): return TensorProduct(*[ b**e.exp for b in e.base.args]) else: return e def tensor_product_simp(e, **hints): """Try to simplify and combine TensorProducts. In general this will try to pull expressions inside of ``TensorProducts``. It currently only works for relatively simple cases where the products have only scalars, raw ``TensorProducts``, not ``Add``, ``Pow``, ``Commutators`` of ``TensorProducts``. It is best to see what it does by showing examples. Examples ======== >>> from sympy.physics.quantum import tensor_product_simp >>> from sympy.physics.quantum import TensorProduct >>> from sympy import Symbol >>> A = Symbol('A',commutative=False) >>> B = Symbol('B',commutative=False) >>> C = Symbol('C',commutative=False) >>> D = Symbol('D',commutative=False) First see what happens to products of tensor products: >>> e = TensorProduct(A,B)*TensorProduct(C,D) >>> e AxB*CxD >>> tensor_product_simp(e) (A*C)x(B*D) This is the core logic of this function, and it works inside, powers, sums, commutators and anticommutators as well: >>> tensor_product_simp(e**2) (A*C)x(B*D)**2 """ if isinstance(e, Add): return Add(*[tensor_product_simp(arg) for arg in e.args]) elif isinstance(e, Pow): if isinstance(e.base, TensorProduct): return tensor_product_simp_Pow(e) else: return tensor_product_simp(e.base) ** e.exp elif isinstance(e, Mul): return tensor_product_simp_Mul(e) elif isinstance(e, Commutator): return Commutator(*[tensor_product_simp(arg) for arg in e.args]) elif isinstance(e, AntiCommutator): return AntiCommutator(*[tensor_product_simp(arg) for arg in e.args]) else: return e
acbbae77bbde026280d0e44fda881a9f8332746013674a9a458fa59de8d51314
"""Dirac notation for states.""" from sympy.core.cache import cacheit from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.function import Function from sympy.core.numbers import oo from sympy.core.singleton import S from sympy.functions.elementary.complexes import conjugate from sympy.functions.elementary.miscellaneous import sqrt from sympy.integrals.integrals import integrate from sympy.printing.pretty.stringpict import stringPict from sympy.physics.quantum.qexpr import QExpr, dispatch_method __all__ = [ 'KetBase', 'BraBase', 'StateBase', 'State', 'Ket', 'Bra', 'TimeDepState', 'TimeDepBra', 'TimeDepKet', 'OrthogonalKet', 'OrthogonalBra', 'OrthogonalState', 'Wavefunction' ] #----------------------------------------------------------------------------- # States, bras and kets. #----------------------------------------------------------------------------- # ASCII brackets _lbracket = "<" _rbracket = ">" _straight_bracket = "|" # Unicode brackets # MATHEMATICAL ANGLE BRACKETS _lbracket_ucode = "\N{MATHEMATICAL LEFT ANGLE BRACKET}" _rbracket_ucode = "\N{MATHEMATICAL RIGHT ANGLE BRACKET}" # LIGHT VERTICAL BAR _straight_bracket_ucode = "\N{LIGHT VERTICAL BAR}" # Other options for unicode printing of <, > and | for Dirac notation. # LEFT-POINTING ANGLE BRACKET # _lbracket = "\u2329" # _rbracket = "\u232A" # LEFT ANGLE BRACKET # _lbracket = "\u3008" # _rbracket = "\u3009" # VERTICAL LINE # _straight_bracket = "\u007C" class StateBase(QExpr): """Abstract base class for general abstract states in quantum mechanics. All other state classes defined will need to inherit from this class. It carries the basic structure for all other states such as dual, _eval_adjoint and label. This is an abstract base class and you should not instantiate it directly, instead use State. """ @classmethod def _operators_to_state(self, ops, **options): """ Returns the eigenstate instance for the passed operators. This method should be overridden in subclasses. It will handle being passed either an Operator instance or set of Operator instances. It should return the corresponding state INSTANCE or simply raise a NotImplementedError. See cartesian.py for an example. """ raise NotImplementedError("Cannot map operators to states in this class. Method not implemented!") def _state_to_operators(self, op_classes, **options): """ Returns the operators which this state instance is an eigenstate of. This method should be overridden in subclasses. It will be called on state instances and be passed the operator classes that we wish to make into instances. The state instance will then transform the classes appropriately, or raise a NotImplementedError if it cannot return operator instances. See cartesian.py for examples, """ raise NotImplementedError( "Cannot map this state to operators. Method not implemented!") @property def operators(self): """Return the operator(s) that this state is an eigenstate of""" from .operatorset import state_to_operators # import internally to avoid circular import errors return state_to_operators(self) def _enumerate_state(self, num_states, **options): raise NotImplementedError("Cannot enumerate this state!") def _represent_default_basis(self, **options): return self._represent(basis=self.operators) #------------------------------------------------------------------------- # Dagger/dual #------------------------------------------------------------------------- @property def dual(self): """Return the dual state of this one.""" return self.dual_class()._new_rawargs(self.hilbert_space, *self.args) @classmethod def dual_class(self): """Return the class used to construct the dual.""" raise NotImplementedError( 'dual_class must be implemented in a subclass' ) def _eval_adjoint(self): """Compute the dagger of this state using the dual.""" return self.dual #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- def _pretty_brackets(self, height, use_unicode=True): # Return pretty printed brackets for the state # Ideally, this could be done by pform.parens but it does not support the angled < and > # Setup for unicode vs ascii if use_unicode: lbracket, rbracket = getattr(self, 'lbracket_ucode', ""), getattr(self, 'rbracket_ucode', "") slash, bslash, vert = '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT}', \ '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT}', \ '\N{BOX DRAWINGS LIGHT VERTICAL}' else: lbracket, rbracket = getattr(self, 'lbracket', ""), getattr(self, 'rbracket', "") slash, bslash, vert = '/', '\\', '|' # If height is 1, just return brackets if height == 1: return stringPict(lbracket), stringPict(rbracket) # Make height even height += (height % 2) brackets = [] for bracket in lbracket, rbracket: # Create left bracket if bracket in {_lbracket, _lbracket_ucode}: bracket_args = [ ' ' * (height//2 - i - 1) + slash for i in range(height // 2)] bracket_args.extend( [' ' * i + bslash for i in range(height // 2)]) # Create right bracket elif bracket in {_rbracket, _rbracket_ucode}: bracket_args = [ ' ' * i + bslash for i in range(height // 2)] bracket_args.extend([ ' ' * ( height//2 - i - 1) + slash for i in range(height // 2)]) # Create straight bracket elif bracket in {_straight_bracket, _straight_bracket_ucode}: bracket_args = [vert] * height else: raise ValueError(bracket) brackets.append( stringPict('\n'.join(bracket_args), baseline=height//2)) return brackets def _sympystr(self, printer, *args): contents = self._print_contents(printer, *args) return '%s%s%s' % (getattr(self, 'lbracket', ""), contents, getattr(self, 'rbracket', "")) def _pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm # Get brackets pform = self._print_contents_pretty(printer, *args) lbracket, rbracket = self._pretty_brackets( pform.height(), printer._use_unicode) # Put together state pform = prettyForm(*pform.left(lbracket)) pform = prettyForm(*pform.right(rbracket)) return pform def _latex(self, printer, *args): contents = self._print_contents_latex(printer, *args) # The extra {} brackets are needed to get matplotlib's latex # rendered to render this properly. return '{%s%s%s}' % (getattr(self, 'lbracket_latex', ""), contents, getattr(self, 'rbracket_latex', "")) class KetBase(StateBase): """Base class for Kets. This class defines the dual property and the brackets for printing. This is an abstract base class and you should not instantiate it directly, instead use Ket. """ lbracket = _straight_bracket rbracket = _rbracket lbracket_ucode = _straight_bracket_ucode rbracket_ucode = _rbracket_ucode lbracket_latex = r'\left|' rbracket_latex = r'\right\rangle ' @classmethod def default_args(self): return ("psi",) @classmethod def dual_class(self): return BraBase def __mul__(self, other): """KetBase*other""" from sympy.physics.quantum.operator import OuterProduct if isinstance(other, BraBase): return OuterProduct(self, other) else: return Expr.__mul__(self, other) def __rmul__(self, other): """other*KetBase""" from sympy.physics.quantum.innerproduct import InnerProduct if isinstance(other, BraBase): return InnerProduct(other, self) else: return Expr.__rmul__(self, other) #------------------------------------------------------------------------- # _eval_* methods #------------------------------------------------------------------------- def _eval_innerproduct(self, bra, **hints): """Evaluate the inner product between this ket and a bra. This is called to compute <bra|ket>, where the ket is ``self``. This method will dispatch to sub-methods having the format:: ``def _eval_innerproduct_BraClass(self, **hints):`` Subclasses should define these methods (one for each BraClass) to teach the ket how to take inner products with bras. """ return dispatch_method(self, '_eval_innerproduct', bra, **hints) def _apply_from_right_to(self, op, **options): """Apply an Operator to this Ket as Operator*Ket This method will dispatch to methods having the format:: ``def _apply_from_right_to_OperatorName(op, **options):`` Subclasses should define these methods (one for each OperatorName) to teach the Ket how to implement OperatorName*Ket Parameters ========== op : Operator The Operator that is acting on the Ket as op*Ket options : dict A dict of key/value pairs that control how the operator is applied to the Ket. """ return dispatch_method(self, '_apply_from_right_to', op, **options) class BraBase(StateBase): """Base class for Bras. This class defines the dual property and the brackets for printing. This is an abstract base class and you should not instantiate it directly, instead use Bra. """ lbracket = _lbracket rbracket = _straight_bracket lbracket_ucode = _lbracket_ucode rbracket_ucode = _straight_bracket_ucode lbracket_latex = r'\left\langle ' rbracket_latex = r'\right|' @classmethod def _operators_to_state(self, ops, **options): state = self.dual_class()._operators_to_state(ops, **options) return state.dual def _state_to_operators(self, op_classes, **options): return self.dual._state_to_operators(op_classes, **options) def _enumerate_state(self, num_states, **options): dual_states = self.dual._enumerate_state(num_states, **options) return [x.dual for x in dual_states] @classmethod def default_args(self): return self.dual_class().default_args() @classmethod def dual_class(self): return KetBase def __mul__(self, other): """BraBase*other""" from sympy.physics.quantum.innerproduct import InnerProduct if isinstance(other, KetBase): return InnerProduct(self, other) else: return Expr.__mul__(self, other) def __rmul__(self, other): """other*BraBase""" from sympy.physics.quantum.operator import OuterProduct if isinstance(other, KetBase): return OuterProduct(other, self) else: return Expr.__rmul__(self, other) def _represent(self, **options): """A default represent that uses the Ket's version.""" from sympy.physics.quantum.dagger import Dagger return Dagger(self.dual._represent(**options)) class State(StateBase): """General abstract quantum state used as a base class for Ket and Bra.""" pass class Ket(State, KetBase): """A general time-independent Ket in quantum mechanics. Inherits from State and KetBase. This class should be used as the base class for all physical, time-independent Kets in a system. This class and its subclasses will be the main classes that users will use for expressing Kets in Dirac notation [1]_. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time. Examples ======== Create a simple Ket and looking at its properties:: >>> from sympy.physics.quantum import Ket >>> from sympy import symbols, I >>> k = Ket('psi') >>> k |psi> >>> k.hilbert_space H >>> k.is_commutative False >>> k.label (psi,) Ket's know about their associated bra:: >>> k.dual <psi| >>> k.dual_class() <class 'sympy.physics.quantum.state.Bra'> Take a linear combination of two kets:: >>> k0 = Ket(0) >>> k1 = Ket(1) >>> 2*I*k0 - 4*k1 2*I*|0> - 4*|1> Compound labels are passed as tuples:: >>> n, m = symbols('n,m') >>> k = Ket(n,m) >>> k |nm> References ========== .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation """ @classmethod def dual_class(self): return Bra class Bra(State, BraBase): """A general time-independent Bra in quantum mechanics. Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This class and its subclasses will be the main classes that users will use for expressing Bras in Dirac notation. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time. Examples ======== Create a simple Bra and look at its properties:: >>> from sympy.physics.quantum import Bra >>> from sympy import symbols, I >>> b = Bra('psi') >>> b <psi| >>> b.hilbert_space H >>> b.is_commutative False Bra's know about their dual Ket's:: >>> b.dual |psi> >>> b.dual_class() <class 'sympy.physics.quantum.state.Ket'> Like Kets, Bras can have compound labels and be manipulated in a similar manner:: >>> n, m = symbols('n,m') >>> b = Bra(n,m) - I*Bra(m,n) >>> b -I*<mn| + <nm| Symbols in a Bra can be substituted using ``.subs``:: >>> b.subs(n,m) <mm| - I*<mm| References ========== .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation """ @classmethod def dual_class(self): return Ket #----------------------------------------------------------------------------- # Time dependent states, bras and kets. #----------------------------------------------------------------------------- class TimeDepState(StateBase): """Base class for a general time-dependent quantum state. This class is used as a base class for any time-dependent state. The main difference between this class and the time-independent state is that this class takes a second argument that is the time in addition to the usual label argument. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time as the final argument. """ #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def default_args(self): return ("psi", "t") #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def label(self): """The label of the state.""" return self.args[:-1] @property def time(self): """The time of the state.""" return self.args[-1] #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- def _print_time(self, printer, *args): return printer._print(self.time, *args) _print_time_repr = _print_time _print_time_latex = _print_time def _print_time_pretty(self, printer, *args): pform = printer._print(self.time, *args) return pform def _print_contents(self, printer, *args): label = self._print_label(printer, *args) time = self._print_time(printer, *args) return '%s;%s' % (label, time) def _print_label_repr(self, printer, *args): label = self._print_sequence(self.label, ',', printer, *args) time = self._print_time_repr(printer, *args) return '%s,%s' % (label, time) def _print_contents_pretty(self, printer, *args): label = self._print_label_pretty(printer, *args) time = self._print_time_pretty(printer, *args) return printer._print_seq((label, time), delimiter=';') def _print_contents_latex(self, printer, *args): label = self._print_sequence( self.label, self._label_separator, printer, *args) time = self._print_time_latex(printer, *args) return '%s;%s' % (label, time) class TimeDepKet(TimeDepState, KetBase): """General time-dependent Ket in quantum mechanics. This inherits from ``TimeDepState`` and ``KetBase`` and is the main class that should be used for Kets that vary with time. Its dual is a ``TimeDepBra``. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time as the final argument. Examples ======== Create a TimeDepKet and look at its attributes:: >>> from sympy.physics.quantum import TimeDepKet >>> k = TimeDepKet('psi', 't') >>> k |psi;t> >>> k.time t >>> k.label (psi,) >>> k.hilbert_space H TimeDepKets know about their dual bra:: >>> k.dual <psi;t| >>> k.dual_class() <class 'sympy.physics.quantum.state.TimeDepBra'> """ @classmethod def dual_class(self): return TimeDepBra class TimeDepBra(TimeDepState, BraBase): """General time-dependent Bra in quantum mechanics. This inherits from TimeDepState and BraBase and is the main class that should be used for Bras that vary with time. Its dual is a TimeDepBra. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time as the final argument. Examples ======== >>> from sympy.physics.quantum import TimeDepBra >>> b = TimeDepBra('psi', 't') >>> b <psi;t| >>> b.time t >>> b.label (psi,) >>> b.hilbert_space H >>> b.dual |psi;t> """ @classmethod def dual_class(self): return TimeDepKet class OrthogonalState(State, StateBase): """General abstract quantum state used as a base class for Ket and Bra.""" pass class OrthogonalKet(OrthogonalState, KetBase): """Orthogonal Ket in quantum mechanics. The inner product of two states with different labels will give zero, states with the same label will give one. >>> from sympy.physics.quantum import OrthogonalBra, OrthogonalKet >>> from sympy.abc import m, n >>> (OrthogonalBra(n)*OrthogonalKet(n)).doit() 1 >>> (OrthogonalBra(n)*OrthogonalKet(n+1)).doit() 0 >>> (OrthogonalBra(n)*OrthogonalKet(m)).doit() <n|m> """ @classmethod def dual_class(self): return OrthogonalBra def _eval_innerproduct(self, bra, **hints): if len(self.args) != len(bra.args): raise ValueError('Cannot multiply a ket that has a different number of labels.') for arg, bra_arg in zip(self.args, bra.args): diff = arg - bra_arg diff = diff.expand() is_zero = diff.is_zero if is_zero is False: return 0 if is_zero is None: return None return 1 class OrthogonalBra(OrthogonalState, BraBase): """Orthogonal Bra in quantum mechanics. """ @classmethod def dual_class(self): return OrthogonalKet class Wavefunction(Function): """Class for representations in continuous bases This class takes an expression and coordinates in its constructor. It can be used to easily calculate normalizations and probabilities. Parameters ========== expr : Expr The expression representing the functional form of the w.f. coords : Symbol or tuple The coordinates to be integrated over, and their bounds Examples ======== Particle in a box, specifying bounds in the more primitive way of using Piecewise: >>> from sympy import Symbol, Piecewise, pi, N >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x = Symbol('x', real=True) >>> n = 1 >>> L = 1 >>> g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True)) >>> f = Wavefunction(g, x) >>> f.norm 1 >>> f.is_normalized True >>> p = f.prob() >>> p(0) 0 >>> p(L) 0 >>> p(0.5) 2 >>> p(0.85*L) 2*sin(0.85*pi)**2 >>> N(p(0.85*L)) 0.412214747707527 Additionally, you can specify the bounds of the function and the indices in a more compact way: >>> from sympy import symbols, pi, diff >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sqrt(2/L)*sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.norm 1 >>> f(L+1) 0 >>> f(L-1) sqrt(2)*sin(pi*n*(L - 1)/L)/sqrt(L) >>> f(-1) 0 >>> f(0.85) sqrt(2)*sin(0.85*pi*n/L)/sqrt(L) >>> f(0.85, n=1, L=1) sqrt(2)*sin(0.85*pi) >>> f.is_commutative False All arguments are automatically sympified, so you can define the variables as strings rather than symbols: >>> expr = x**2 >>> f = Wavefunction(expr, 'x') >>> type(f.variables[0]) <class 'sympy.core.symbol.Symbol'> Derivatives of Wavefunctions will return Wavefunctions: >>> diff(f, x) Wavefunction(2*x, x) """ #Any passed tuples for coordinates and their bounds need to be #converted to Tuples before Function's constructor is called, to #avoid errors from calling is_Float in the constructor def __new__(cls, *args, **options): new_args = [None for i in args] ct = 0 for arg in args: if isinstance(arg, tuple): new_args[ct] = Tuple(*arg) else: new_args[ct] = arg ct += 1 return super().__new__(cls, *new_args, **options) def __call__(self, *args, **options): var = self.variables if len(args) != len(var): raise NotImplementedError( "Incorrect number of arguments to function!") ct = 0 #If the passed value is outside the specified bounds, return 0 for v in var: lower, upper = self.limits[v] #Do the comparison to limits only if the passed symbol is actually #a symbol present in the limits; #Had problems with a comparison of x > L if isinstance(args[ct], Expr) and \ not (lower in args[ct].free_symbols or upper in args[ct].free_symbols): continue if (args[ct] < lower) == True or (args[ct] > upper) == True: return S.Zero ct += 1 expr = self.expr #Allows user to make a call like f(2, 4, m=1, n=1) for symbol in list(expr.free_symbols): if str(symbol) in options.keys(): val = options[str(symbol)] expr = expr.subs(symbol, val) return expr.subs(zip(var, args)) def _eval_derivative(self, symbol): expr = self.expr deriv = expr._eval_derivative(symbol) return Wavefunction(deriv, *self.args[1:]) def _eval_conjugate(self): return Wavefunction(conjugate(self.expr), *self.args[1:]) def _eval_transpose(self): return self @property def free_symbols(self): return self.expr.free_symbols @property def is_commutative(self): """ Override Function's is_commutative so that order is preserved in represented expressions """ return False @classmethod def eval(self, *args): return None @property def variables(self): """ Return the coordinates which the wavefunction depends on Examples ======== >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy import symbols >>> x,y = symbols('x,y') >>> f = Wavefunction(x*y, x, y) >>> f.variables (x, y) >>> g = Wavefunction(x*y, x) >>> g.variables (x,) """ var = [g[0] if isinstance(g, Tuple) else g for g in self._args[1:]] return tuple(var) @property def limits(self): """ Return the limits of the coordinates which the w.f. depends on If no limits are specified, defaults to ``(-oo, oo)``. Examples ======== >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy import symbols >>> x, y = symbols('x, y') >>> f = Wavefunction(x**2, (x, 0, 1)) >>> f.limits {x: (0, 1)} >>> f = Wavefunction(x**2, x) >>> f.limits {x: (-oo, oo)} >>> f = Wavefunction(x**2 + y**2, x, (y, -1, 2)) >>> f.limits {x: (-oo, oo), y: (-1, 2)} """ limits = [(g[1], g[2]) if isinstance(g, Tuple) else (-oo, oo) for g in self._args[1:]] return dict(zip(self.variables, tuple(limits))) @property def expr(self): """ Return the expression which is the functional form of the Wavefunction Examples ======== >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy import symbols >>> x, y = symbols('x, y') >>> f = Wavefunction(x**2, x) >>> f.expr x**2 """ return self._args[0] @property def is_normalized(self): """ Returns true if the Wavefunction is properly normalized Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sqrt(2/L)*sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.is_normalized True """ return (self.norm == 1.0) @property # type: ignore @cacheit def norm(self): """ Return the normalization of the specified functional form. This function integrates over the coordinates of the Wavefunction, with the bounds specified. Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sqrt(2/L)*sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.norm 1 >>> g = sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.norm sqrt(2)*sqrt(L)/2 """ exp = self.expr*conjugate(self.expr) var = self.variables limits = self.limits for v in var: curr_limits = limits[v] exp = integrate(exp, (v, curr_limits[0], curr_limits[1])) return sqrt(exp) def normalize(self): """ Return a normalized version of the Wavefunction Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sin >>> from sympy.physics.quantum.state import Wavefunction >>> x = symbols('x', real=True) >>> L = symbols('L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.normalize() Wavefunction(sqrt(2)*sin(pi*n*x/L)/sqrt(L), (x, 0, L)) """ const = self.norm if const is oo: raise NotImplementedError("The function is not normalizable!") else: return Wavefunction((const)**(-1)*self.expr, *self.args[1:]) def prob(self): r""" Return the absolute magnitude of the w.f., `|\psi(x)|^2` Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', real=True) >>> n = symbols('n', integer=True) >>> g = sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.prob() Wavefunction(sin(pi*n*x/L)**2, x) """ return Wavefunction(self.expr*conjugate(self.expr), *self.variables)
b51fe908761c4afa4e77b7e8e59ed6e58609630c20d03e1cf4890eda7d7d1206
"""An implementation of gates that act on qubits. Gates are unitary operators that act on the space of qubits. Medium Term Todo: * Optimize Gate._apply_operators_Qubit to remove the creation of many intermediate Qubit objects. * Add commutation relationships to all operators and use this in gate_sort. * Fix gate_sort and gate_simp. * Get multi-target UGates plotting properly. * Get UGate to work with either sympy/numpy matrices and output either format. This should also use the matrix slots. """ from itertools import chain import random from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.mul import Mul from sympy.core.numbers import (I, Integer) from sympy.core.power import Pow from sympy.core.numbers import Number from sympy.core.singleton import S as _S from sympy.core.sorting import default_sort_key from sympy.core.sympify import _sympify from sympy.functions.elementary.miscellaneous import sqrt from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.operator import (UnitaryOperator, Operator, HermitianOperator) from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye from sympy.physics.quantum.matrixcache import matrix_cache from sympy.matrices.matrices import MatrixBase from sympy.utilities.iterables import is_sequence __all__ = [ 'Gate', 'CGate', 'UGate', 'OneQubitGate', 'TwoQubitGate', 'IdentityGate', 'HadamardGate', 'XGate', 'YGate', 'ZGate', 'TGate', 'PhaseGate', 'SwapGate', 'CNotGate', # Aliased gate names 'CNOT', 'SWAP', 'H', 'X', 'Y', 'Z', 'T', 'S', 'Phase', 'normalized', 'gate_sort', 'gate_simp', 'random_circuit', 'CPHASE', 'CGateS', ] #----------------------------------------------------------------------------- # Gate Super-Classes #----------------------------------------------------------------------------- _normalized = True def _max(*args, **kwargs): if "key" not in kwargs: kwargs["key"] = default_sort_key return max(*args, **kwargs) def _min(*args, **kwargs): if "key" not in kwargs: kwargs["key"] = default_sort_key return min(*args, **kwargs) def normalized(normalize): r"""Set flag controlling normalization of Hadamard gates by `1/\sqrt{2}`. This is a global setting that can be used to simplify the look of various expressions, by leaving off the leading `1/\sqrt{2}` of the Hadamard gate. Parameters ---------- normalize : bool Should the Hadamard gate include the `1/\sqrt{2}` normalization factor? When True, the Hadamard gate will have the `1/\sqrt{2}`. When False, the Hadamard gate will not have this factor. """ global _normalized _normalized = normalize def _validate_targets_controls(tandc): tandc = list(tandc) # Check for integers for bit in tandc: if not bit.is_Integer and not bit.is_Symbol: raise TypeError('Integer expected, got: %r' % tandc[bit]) # Detect duplicates if len(set(tandc)) != len(tandc): raise QuantumError( 'Target/control qubits in a gate cannot be duplicated' ) class Gate(UnitaryOperator): """Non-controlled unitary gate operator that acts on qubits. This is a general abstract gate that needs to be subclassed to do anything useful. Parameters ---------- label : tuple, int A list of the target qubits (as ints) that the gate will apply to. Examples ======== """ _label_separator = ',' gate_name = 'G' gate_name_latex = 'G' #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): args = Tuple(*UnitaryOperator._eval_args(args)) _validate_targets_controls(args) return args @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def nqubits(self): """The total number of qubits this gate acts on. For controlled gate subclasses this includes both target and control qubits, so that, for examples the CNOT gate acts on 2 qubits. """ return len(self.targets) @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(self.targets) + 1 @property def targets(self): """A tuple of target qubits.""" return self.label @property def gate_name_plot(self): return r'$%s$' % self.gate_name_latex #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): """The matrix represenation of the target part of the gate. Parameters ---------- format : str The format string ('sympy','numpy', etc.) """ raise NotImplementedError( 'get_target_matrix is not implemented in Gate.') #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_IntQubit(self, qubits, **options): """Redirect an apply from IntQubit to Qubit""" return self._apply_operator_Qubit(qubits, **options) def _apply_operator_Qubit(self, qubits, **options): """Apply this gate to a Qubit.""" # Check number of qubits this gate acts on. if qubits.nqubits < self.min_qubits: raise QuantumError( 'Gate needs a minimum of %r qubits to act on, got: %r' % (self.min_qubits, qubits.nqubits) ) # If the controls are not met, just return if isinstance(self, CGate): if not self.eval_controls(qubits): return qubits targets = self.targets target_matrix = self.get_target_matrix(format='sympy') # Find which column of the target matrix this applies to. column_index = 0 n = 1 for target in targets: column_index += n*qubits[target] n = n << 1 column = target_matrix[:, int(column_index)] # Now apply each column element to the qubit. result = 0 for index in range(column.rows): # TODO: This can be optimized to reduce the number of Qubit # creations. We should simply manipulate the raw list of qubit # values and then build the new Qubit object once. # Make a copy of the incoming qubits. new_qubit = qubits.__class__(*qubits.args) # Flip the bits that need to be flipped. for bit, target in enumerate(targets): if new_qubit[target] != (index >> bit) & 1: new_qubit = new_qubit.flip(target) # The value in that row and column times the flipped-bit qubit # is the result for that part. result += column[index]*new_qubit return result #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): format = options.get('format', 'sympy') nqubits = options.get('nqubits', 0) if nqubits == 0: raise QuantumError( 'The number of qubits must be given as nqubits.') # Make sure we have enough qubits for the gate. if nqubits < self.min_qubits: raise QuantumError( 'The number of qubits %r is too small for the gate.' % nqubits ) target_matrix = self.get_target_matrix(format) targets = self.targets if isinstance(self, CGate): controls = self.controls else: controls = [] m = represent_zbasis( controls, targets, target_matrix, nqubits, format ) return m #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _sympystr(self, printer, *args): label = self._print_label(printer, *args) return '%s(%s)' % (self.gate_name, label) def _pretty(self, printer, *args): a = stringPict(self.gate_name) b = self._print_label_pretty(printer, *args) return self._print_subscript_pretty(a, b) def _latex(self, printer, *args): label = self._print_label(printer, *args) return '%s_{%s}' % (self.gate_name_latex, label) def plot_gate(self, axes, gate_idx, gate_grid, wire_grid): raise NotImplementedError('plot_gate is not implemented.') class CGate(Gate): """A general unitary gate with control qubits. A general control gate applies a target gate to a set of targets if all of the control qubits have a particular values (set by ``CGate.control_value``). Parameters ---------- label : tuple The label in this case has the form (controls, gate), where controls is a tuple/list of control qubits (as ints) and gate is a ``Gate`` instance that is the target operator. Examples ======== """ gate_name = 'C' gate_name_latex = 'C' # The values this class controls for. control_value = _S.One simplify_cgate = False #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): # _eval_args has the right logic for the controls argument. controls = args[0] gate = args[1] if not is_sequence(controls): controls = (controls,) controls = UnitaryOperator._eval_args(controls) _validate_targets_controls(chain(controls, gate.targets)) return (Tuple(*controls), gate) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def nqubits(self): """The total number of qubits this gate acts on. For controlled gate subclasses this includes both target and control qubits, so that, for examples the CNOT gate acts on 2 qubits. """ return len(self.targets) + len(self.controls) @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(_max(self.controls), _max(self.targets)) + 1 @property def targets(self): """A tuple of target qubits.""" return self.gate.targets @property def controls(self): """A tuple of control qubits.""" return tuple(self.label[0]) @property def gate(self): """The non-controlled gate that will be applied to the targets.""" return self.label[1] #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): return self.gate.get_target_matrix(format) def eval_controls(self, qubit): """Return True/False to indicate if the controls are satisfied.""" return all(qubit[bit] == self.control_value for bit in self.controls) def decompose(self, **options): """Decompose the controlled gate into CNOT and single qubits gates.""" if len(self.controls) == 1: c = self.controls[0] t = self.gate.targets[0] if isinstance(self.gate, YGate): g1 = PhaseGate(t) g2 = CNotGate(c, t) g3 = PhaseGate(t) g4 = ZGate(t) return g1*g2*g3*g4 if isinstance(self.gate, ZGate): g1 = HadamardGate(t) g2 = CNotGate(c, t) g3 = HadamardGate(t) return g1*g2*g3 else: return self #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _print_label(self, printer, *args): controls = self._print_sequence(self.controls, ',', printer, *args) gate = printer._print(self.gate, *args) return '(%s),%s' % (controls, gate) def _pretty(self, printer, *args): controls = self._print_sequence_pretty( self.controls, ',', printer, *args) gate = printer._print(self.gate) gate_name = stringPict(self.gate_name) first = self._print_subscript_pretty(gate_name, controls) gate = self._print_parens_pretty(gate) final = prettyForm(*first.right(gate)) return final def _latex(self, printer, *args): controls = self._print_sequence(self.controls, ',', printer, *args) gate = printer._print(self.gate, *args) return r'%s_{%s}{\left(%s\right)}' % \ (self.gate_name_latex, controls, gate) def plot_gate(self, circ_plot, gate_idx): """ Plot the controlled gate. If *simplify_cgate* is true, simplify C-X and C-Z gates into their more familiar forms. """ min_wire = int(_min(chain(self.controls, self.targets))) max_wire = int(_max(chain(self.controls, self.targets))) circ_plot.control_line(gate_idx, min_wire, max_wire) for c in self.controls: circ_plot.control_point(gate_idx, int(c)) if self.simplify_cgate: if self.gate.gate_name == 'X': self.gate.plot_gate_plus(circ_plot, gate_idx) elif self.gate.gate_name == 'Z': circ_plot.control_point(gate_idx, self.targets[0]) else: self.gate.plot_gate(circ_plot, gate_idx) else: self.gate.plot_gate(circ_plot, gate_idx) #------------------------------------------------------------------------- # Miscellaneous #------------------------------------------------------------------------- def _eval_dagger(self): if isinstance(self.gate, HermitianOperator): return self else: return Gate._eval_dagger(self) def _eval_inverse(self): if isinstance(self.gate, HermitianOperator): return self else: return Gate._eval_inverse(self) def _eval_power(self, exp): if isinstance(self.gate, HermitianOperator): if exp == -1: return Gate._eval_power(self, exp) elif abs(exp) % 2 == 0: return self*(Gate._eval_inverse(self)) else: return self else: return Gate._eval_power(self, exp) class CGateS(CGate): """Version of CGate that allows gate simplifications. I.e. cnot looks like an oplus, cphase has dots, etc. """ simplify_cgate=True class UGate(Gate): """General gate specified by a set of targets and a target matrix. Parameters ---------- label : tuple A tuple of the form (targets, U), where targets is a tuple of the target qubits and U is a unitary matrix with dimension of len(targets). """ gate_name = 'U' gate_name_latex = 'U' #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): targets = args[0] if not is_sequence(targets): targets = (targets,) targets = Gate._eval_args(targets) _validate_targets_controls(targets) mat = args[1] if not isinstance(mat, MatrixBase): raise TypeError('Matrix expected, got: %r' % mat) #make sure this matrix is of a Basic type mat = _sympify(mat) dim = 2**len(targets) if not all(dim == shape for shape in mat.shape): raise IndexError( 'Number of targets must match the matrix size: %r %r' % (targets, mat) ) return (targets, mat) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args[0]) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def targets(self): """A tuple of target qubits.""" return tuple(self.label[0]) #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): """The matrix rep. of the target part of the gate. Parameters ---------- format : str The format string ('sympy','numpy', etc.) """ return self.label[1] #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _pretty(self, printer, *args): targets = self._print_sequence_pretty( self.targets, ',', printer, *args) gate_name = stringPict(self.gate_name) return self._print_subscript_pretty(gate_name, targets) def _latex(self, printer, *args): targets = self._print_sequence(self.targets, ',', printer, *args) return r'%s_{%s}' % (self.gate_name_latex, targets) def plot_gate(self, circ_plot, gate_idx): circ_plot.one_qubit_box( self.gate_name_plot, gate_idx, int(self.targets[0]) ) class OneQubitGate(Gate): """A single qubit unitary gate base class.""" nqubits = _S.One def plot_gate(self, circ_plot, gate_idx): circ_plot.one_qubit_box( self.gate_name_plot, gate_idx, int(self.targets[0]) ) def _eval_commutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return _S.Zero return Operator._eval_commutator(self, other, **hints) def _eval_anticommutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(2)*self*other return Operator._eval_anticommutator(self, other, **hints) class TwoQubitGate(Gate): """A two qubit unitary gate base class.""" nqubits = Integer(2) #----------------------------------------------------------------------------- # Single Qubit Gates #----------------------------------------------------------------------------- class IdentityGate(OneQubitGate): """The single qubit identity gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = '1' gate_name_latex = '1' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('eye2', format) def _eval_commutator(self, other, **hints): return _S.Zero def _eval_anticommutator(self, other, **hints): return Integer(2)*other class HadamardGate(HermitianOperator, OneQubitGate): """The single qubit Hadamard gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== >>> from sympy import sqrt >>> from sympy.physics.quantum.qubit import Qubit >>> from sympy.physics.quantum.gate import HadamardGate >>> from sympy.physics.quantum.qapply import qapply >>> qapply(HadamardGate(0)*Qubit('1')) sqrt(2)*|0>/2 - sqrt(2)*|1>/2 >>> # Hadamard on bell state, applied on 2 qubits. >>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11')) >>> qapply(HadamardGate(0)*HadamardGate(1)*psi) sqrt(2)*|00>/2 + sqrt(2)*|11>/2 """ gate_name = 'H' gate_name_latex = 'H' def get_target_matrix(self, format='sympy'): if _normalized: return matrix_cache.get_matrix('H', format) else: return matrix_cache.get_matrix('Hsqrt2', format) def _eval_commutator_XGate(self, other, **hints): return I*sqrt(2)*YGate(self.targets[0]) def _eval_commutator_YGate(self, other, **hints): return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0])) def _eval_commutator_ZGate(self, other, **hints): return -I*sqrt(2)*YGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return sqrt(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return _S.Zero def _eval_anticommutator_ZGate(self, other, **hints): return sqrt(2)*IdentityGate(self.targets[0]) class XGate(HermitianOperator, OneQubitGate): """The single qubit X, or NOT, gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'X' gate_name_latex = 'X' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('X', format) def plot_gate(self, circ_plot, gate_idx): OneQubitGate.plot_gate(self,circ_plot,gate_idx) def plot_gate_plus(self, circ_plot, gate_idx): circ_plot.not_point( gate_idx, int(self.label[0]) ) def _eval_commutator_YGate(self, other, **hints): return Integer(2)*I*ZGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return _S.Zero def _eval_anticommutator_ZGate(self, other, **hints): return _S.Zero class YGate(HermitianOperator, OneQubitGate): """The single qubit Y gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'Y' gate_name_latex = 'Y' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Y', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(2)*I*XGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_ZGate(self, other, **hints): return _S.Zero class ZGate(HermitianOperator, OneQubitGate): """The single qubit Z gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'Z' gate_name_latex = 'Z' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Z', format) def _eval_commutator_XGate(self, other, **hints): return Integer(2)*I*YGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return _S.Zero class PhaseGate(OneQubitGate): """The single qubit phase, or S, gate. This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and does nothing if the state is ``|0>``. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'S' gate_name_latex = 'S' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('S', format) def _eval_commutator_ZGate(self, other, **hints): return _S.Zero def _eval_commutator_TGate(self, other, **hints): return _S.Zero class TGate(OneQubitGate): """The single qubit pi/8 gate. This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and does nothing if the state is ``|0>``. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'T' gate_name_latex = 'T' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('T', format) def _eval_commutator_ZGate(self, other, **hints): return _S.Zero def _eval_commutator_PhaseGate(self, other, **hints): return _S.Zero # Aliases for gate names. H = HadamardGate X = XGate Y = YGate Z = ZGate T = TGate Phase = S = PhaseGate #----------------------------------------------------------------------------- # 2 Qubit Gates #----------------------------------------------------------------------------- class CNotGate(HermitianOperator, CGate, TwoQubitGate): """Two qubit controlled-NOT. This gate performs the NOT or X gate on the target qubit if the control qubits all have the value 1. Parameters ---------- label : tuple A tuple of the form (control, target). Examples ======== >>> from sympy.physics.quantum.gate import CNOT >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import Qubit >>> c = CNOT(1,0) >>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left |11> """ gate_name = 'CNOT' gate_name_latex = r'\text{CNOT}' simplify_cgate = True #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): args = Gate._eval_args(args) return args @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(self.label) + 1 @property def targets(self): """A tuple of target qubits.""" return (self.label[1],) @property def controls(self): """A tuple of control qubits.""" return (self.label[0],) @property def gate(self): """The non-controlled gate that will be applied to the targets.""" return XGate(self.label[1]) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- # The default printing of Gate works better than those of CGate, so we # go around the overridden methods in CGate. def _print_label(self, printer, *args): return Gate._print_label(self, printer, *args) def _pretty(self, printer, *args): return Gate._pretty(self, printer, *args) def _latex(self, printer, *args): return Gate._latex(self, printer, *args) #------------------------------------------------------------------------- # Commutator/AntiCommutator #------------------------------------------------------------------------- def _eval_commutator_ZGate(self, other, **hints): """[CNOT(i, j), Z(i)] == 0.""" if self.controls[0] == other.targets[0]: return _S.Zero else: raise NotImplementedError('Commutator not implemented: %r' % other) def _eval_commutator_TGate(self, other, **hints): """[CNOT(i, j), T(i)] == 0.""" return self._eval_commutator_ZGate(other, **hints) def _eval_commutator_PhaseGate(self, other, **hints): """[CNOT(i, j), S(i)] == 0.""" return self._eval_commutator_ZGate(other, **hints) def _eval_commutator_XGate(self, other, **hints): """[CNOT(i, j), X(j)] == 0.""" if self.targets[0] == other.targets[0]: return _S.Zero else: raise NotImplementedError('Commutator not implemented: %r' % other) def _eval_commutator_CNotGate(self, other, **hints): """[CNOT(i, j), CNOT(i,k)] == 0.""" if self.controls[0] == other.controls[0]: return _S.Zero else: raise NotImplementedError('Commutator not implemented: %r' % other) class SwapGate(TwoQubitGate): """Two qubit SWAP gate. This gate swap the values of the two qubits. Parameters ---------- label : tuple A tuple of the form (target1, target2). Examples ======== """ gate_name = 'SWAP' gate_name_latex = r'\text{SWAP}' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('SWAP', format) def decompose(self, **options): """Decompose the SWAP gate into CNOT gates.""" i, j = self.targets[0], self.targets[1] g1 = CNotGate(i, j) g2 = CNotGate(j, i) return g1*g2*g1 def plot_gate(self, circ_plot, gate_idx): min_wire = int(_min(self.targets)) max_wire = int(_max(self.targets)) circ_plot.control_line(gate_idx, min_wire, max_wire) circ_plot.swap_point(gate_idx, min_wire) circ_plot.swap_point(gate_idx, max_wire) def _represent_ZGate(self, basis, **options): """Represent the SWAP gate in the computational basis. The following representation is used to compute this: SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0| """ format = options.get('format', 'sympy') targets = [int(t) for t in self.targets] min_target = _min(targets) max_target = _max(targets) nqubits = options.get('nqubits', self.min_qubits) op01 = matrix_cache.get_matrix('op01', format) op10 = matrix_cache.get_matrix('op10', format) op11 = matrix_cache.get_matrix('op11', format) op00 = matrix_cache.get_matrix('op00', format) eye2 = matrix_cache.get_matrix('eye2', format) result = None for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)): product = nqubits*[eye2] product[nqubits - min_target - 1] = i product[nqubits - max_target - 1] = j new_result = matrix_tensor_product(*product) if result is None: result = new_result else: result = result + new_result return result # Aliases for gate names. CNOT = CNotGate SWAP = SwapGate def CPHASE(a,b): return CGateS((a,),Z(b)) #----------------------------------------------------------------------------- # Represent #----------------------------------------------------------------------------- def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'): """Represent a gate with controls, targets and target_matrix. This function does the low-level work of representing gates as matrices in the standard computational basis (ZGate). Currently, we support two main cases: 1. One target qubit and no control qubits. 2. One target qubits and multiple control qubits. For the base of multiple controls, we use the following expression [1]: 1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2}) Parameters ---------- controls : list, tuple A sequence of control qubits. targets : list, tuple A sequence of target qubits. target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse The matrix form of the transformation to be performed on the target qubits. The format of this matrix must match that passed into the `format` argument. nqubits : int The total number of qubits used for the representation. format : str The format of the final matrix ('sympy', 'numpy', 'scipy.sparse'). Examples ======== References ---------- [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html. """ controls = [int(x) for x in controls] targets = [int(x) for x in targets] nqubits = int(nqubits) # This checks for the format as well. op11 = matrix_cache.get_matrix('op11', format) eye2 = matrix_cache.get_matrix('eye2', format) # Plain single qubit case if len(controls) == 0 and len(targets) == 1: product = [] bit = targets[0] # Fill product with [I1,Gate,I2] such that the unitaries, # I, cause the gate to be applied to the correct Qubit if bit != nqubits - 1: product.append(matrix_eye(2**(nqubits - bit - 1), format=format)) product.append(target_matrix) if bit != 0: product.append(matrix_eye(2**bit, format=format)) return matrix_tensor_product(*product) # Single target, multiple controls. elif len(targets) == 1 and len(controls) >= 1: target = targets[0] # Build the non-trivial part. product2 = [] for i in range(nqubits): product2.append(matrix_eye(2, format=format)) for control in controls: product2[nqubits - 1 - control] = op11 product2[nqubits - 1 - target] = target_matrix - eye2 return matrix_eye(2**nqubits, format=format) + \ matrix_tensor_product(*product2) # Multi-target, multi-control is not yet implemented. else: raise NotImplementedError( 'The representation of multi-target, multi-control gates ' 'is not implemented.' ) #----------------------------------------------------------------------------- # Gate manipulation functions. #----------------------------------------------------------------------------- def gate_simp(circuit): """Simplifies gates symbolically It first sorts gates using gate_sort. It then applies basic simplification rules to the circuit, e.g., XGate**2 = Identity """ # Bubble sort out gates that commute. circuit = gate_sort(circuit) # Do simplifications by subing a simplification into the first element # which can be simplified. We recursively call gate_simp with new circuit # as input more simplifications exist. if isinstance(circuit, Add): return sum(gate_simp(t) for t in circuit.args) elif isinstance(circuit, Mul): circuit_args = circuit.args elif isinstance(circuit, Pow): b, e = circuit.as_base_exp() circuit_args = (gate_simp(b)**e,) else: return circuit # Iterate through each element in circuit, simplify if possible. for i in range(len(circuit_args)): # H,X,Y or Z squared is 1. # T**2 = S, S**2 = Z if isinstance(circuit_args[i], Pow): if isinstance(circuit_args[i].base, (HadamardGate, XGate, YGate, ZGate)) \ and isinstance(circuit_args[i].exp, Number): # Build a new circuit taking replacing the # H,X,Y,Z squared with one. newargs = (circuit_args[:i] + (circuit_args[i].base**(circuit_args[i].exp % 2),) + circuit_args[i + 1:]) # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break elif isinstance(circuit_args[i].base, PhaseGate): # Build a new circuit taking old circuit but splicing # in simplification. newargs = circuit_args[:i] # Replace PhaseGate**2 with ZGate. newargs = newargs + (ZGate(circuit_args[i].base.args[0])** (Integer(circuit_args[i].exp/2)), circuit_args[i].base** (circuit_args[i].exp % 2)) # Append the last elements. newargs = newargs + circuit_args[i + 1:] # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break elif isinstance(circuit_args[i].base, TGate): # Build a new circuit taking all the old elements. newargs = circuit_args[:i] # Put an Phasegate in place of any TGate**2. newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])** Integer(circuit_args[i].exp/2), circuit_args[i].base** (circuit_args[i].exp % 2)) # Append the last elements. newargs = newargs + circuit_args[i + 1:] # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break return circuit def gate_sort(circuit): """Sorts the gates while keeping track of commutation relations This function uses a bubble sort to rearrange the order of gate application. Keeps track of Quantum computations special commutation relations (e.g. things that apply to the same Qubit do not commute with each other) circuit is the Mul of gates that are to be sorted. """ # Make sure we have an Add or Mul. if isinstance(circuit, Add): return sum(gate_sort(t) for t in circuit.args) if isinstance(circuit, Pow): return gate_sort(circuit.base)**circuit.exp elif isinstance(circuit, Gate): return circuit if not isinstance(circuit, Mul): return circuit changes = True while changes: changes = False circ_array = circuit.args for i in range(len(circ_array) - 1): # Go through each element and switch ones that are in wrong order if isinstance(circ_array[i], (Gate, Pow)) and \ isinstance(circ_array[i + 1], (Gate, Pow)): # If we have a Pow object, look at only the base first_base, first_exp = circ_array[i].as_base_exp() second_base, second_exp = circ_array[i + 1].as_base_exp() # Use SymPy's hash based sorting. This is not mathematical # sorting, but is rather based on comparing hashes of objects. # See Basic.compare for details. if first_base.compare(second_base) > 0: if Commutator(first_base, second_base).doit() == 0: new_args = (circuit.args[:i] + (circuit.args[i + 1],) + (circuit.args[i],) + circuit.args[i + 2:]) circuit = Mul(*new_args) changes = True break if AntiCommutator(first_base, second_base).doit() == 0: new_args = (circuit.args[:i] + (circuit.args[i + 1],) + (circuit.args[i],) + circuit.args[i + 2:]) sign = _S.NegativeOne**(first_exp*second_exp) circuit = sign*Mul(*new_args) changes = True break return circuit #----------------------------------------------------------------------------- # Utility functions #----------------------------------------------------------------------------- def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)): """Return a random circuit of ngates and nqubits. This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP) gates. Parameters ---------- ngates : int The number of gates in the circuit. nqubits : int The number of qubits in the circuit. gate_space : tuple A tuple of the gate classes that will be used in the circuit. Repeating gate classes multiple times in this tuple will increase the frequency they appear in the random circuit. """ qubit_space = range(nqubits) result = [] for i in range(ngates): g = random.choice(gate_space) if g == CNotGate or g == SwapGate: qubits = random.sample(qubit_space, 2) g = g(*qubits) else: qubit = random.choice(qubit_space) g = g(qubit) result.append(g) return Mul(*result) def zx_basis_transform(self, format='sympy'): """Transformation matrix from Z to X basis.""" return matrix_cache.get_matrix('ZX', format) def zy_basis_transform(self, format='sympy'): """Transformation matrix from Z to Y basis.""" return matrix_cache.get_matrix('ZY', format)
f6e9a54a99baa4aa29947ee14511dbbb0be4bdd33df00f4618d67ac9e3497ffa
"""Fermionic quantum operators.""" from sympy.core.numbers import Integer from sympy.core.singleton import S from sympy.physics.quantum import Operator from sympy.physics.quantum import HilbertSpace, Ket, Bra from sympy.functions.special.tensor_functions import KroneckerDelta __all__ = [ 'FermionOp', 'FermionFockKet', 'FermionFockBra' ] class FermionOp(Operator): """A fermionic operator that satisfies {c, Dagger(c)} == 1. Parameters ========== name : str A string that labels the fermionic mode. annihilation : bool A bool that indicates if the fermionic operator is an annihilation (True, default value) or creation operator (False) Examples ======== >>> from sympy.physics.quantum import Dagger, AntiCommutator >>> from sympy.physics.quantum.fermion import FermionOp >>> c = FermionOp("c") >>> AntiCommutator(c, Dagger(c)).doit() 1 """ @property def name(self): return self.args[0] @property def is_annihilation(self): return bool(self.args[1]) @classmethod def default_args(self): return ("c", True) def __new__(cls, *args, **hints): if not len(args) in [1, 2]: raise ValueError('1 or 2 parameters expected, got %s' % args) if len(args) == 1: args = (args[0], S.One) if len(args) == 2: args = (args[0], Integer(args[1])) return Operator.__new__(cls, *args) def _eval_commutator_FermionOp(self, other, **hints): if 'independent' in hints and hints['independent']: # [c, d] = 0 return S.Zero return None def _eval_anticommutator_FermionOp(self, other, **hints): if self.name == other.name: # {a^\dagger, a} = 1 if not self.is_annihilation and other.is_annihilation: return S.One elif 'independent' in hints and hints['independent']: # {c, d} = 2 * c * d, because [c, d] = 0 for independent operators return 2 * self * other return None def _eval_anticommutator_BosonOp(self, other, **hints): # because fermions and bosons commute return 2 * self * other def _eval_commutator_BosonOp(self, other, **hints): return S.Zero def _eval_adjoint(self): return FermionOp(str(self.name), not self.is_annihilation) def _print_contents_latex(self, printer, *args): if self.is_annihilation: return r'{%s}' % str(self.name) else: return r'{{%s}^\dagger}' % str(self.name) def _print_contents(self, printer, *args): if self.is_annihilation: return r'%s' % str(self.name) else: return r'Dagger(%s)' % str(self.name) def _print_contents_pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) if self.is_annihilation: return pform else: return pform**prettyForm('\N{DAGGER}') class FermionFockKet(Ket): """Fock state ket for a fermionic mode. Parameters ========== n : Number The Fock state number. """ def __new__(cls, n): if n not in (0, 1): raise ValueError("n must be 0 or 1") return Ket.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return FermionFockBra @classmethod def _eval_hilbert_space(cls, label): return HilbertSpace() def _eval_innerproduct_FermionFockBra(self, bra, **hints): return KroneckerDelta(self.n, bra.n) def _apply_from_right_to_FermionOp(self, op, **options): if op.is_annihilation: if self.n == 1: return FermionFockKet(0) else: return S.Zero else: if self.n == 0: return FermionFockKet(1) else: return S.Zero class FermionFockBra(Bra): """Fock state bra for a fermionic mode. Parameters ========== n : Number The Fock state number. """ def __new__(cls, n): if n not in (0, 1): raise ValueError("n must be 0 or 1") return Bra.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return FermionFockKet
7041fc75c3d7ba7a209c0a5cebd63a4d2251319eb73f6d0da3ab41db1187ca74
"""Bosonic quantum operators.""" from sympy.core.mul import Mul from sympy.core.numbers import Integer from sympy.core.singleton import S from sympy.functions.elementary.complexes import conjugate from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.physics.quantum import Operator from sympy.physics.quantum import HilbertSpace, FockSpace, Ket, Bra, IdentityOperator from sympy.functions.special.tensor_functions import KroneckerDelta __all__ = [ 'BosonOp', 'BosonFockKet', 'BosonFockBra', 'BosonCoherentKet', 'BosonCoherentBra' ] class BosonOp(Operator): """A bosonic operator that satisfies [a, Dagger(a)] == 1. Parameters ========== name : str A string that labels the bosonic mode. annihilation : bool A bool that indicates if the bosonic operator is an annihilation (True, default value) or creation operator (False) Examples ======== >>> from sympy.physics.quantum import Dagger, Commutator >>> from sympy.physics.quantum.boson import BosonOp >>> a = BosonOp("a") >>> Commutator(a, Dagger(a)).doit() 1 """ @property def name(self): return self.args[0] @property def is_annihilation(self): return bool(self.args[1]) @classmethod def default_args(self): return ("a", True) def __new__(cls, *args, **hints): if not len(args) in [1, 2]: raise ValueError('1 or 2 parameters expected, got %s' % args) if len(args) == 1: args = (args[0], S.One) if len(args) == 2: args = (args[0], Integer(args[1])) return Operator.__new__(cls, *args) def _eval_commutator_BosonOp(self, other, **hints): if self.name == other.name: # [a^\dagger, a] = -1 if not self.is_annihilation and other.is_annihilation: return S.NegativeOne elif 'independent' in hints and hints['independent']: # [a, b] = 0 return S.Zero return None def _eval_commutator_FermionOp(self, other, **hints): return S.Zero def _eval_anticommutator_BosonOp(self, other, **hints): if 'independent' in hints and hints['independent']: # {a, b} = 2 * a * b, because [a, b] = 0 return 2 * self * other return None def _eval_adjoint(self): return BosonOp(str(self.name), not self.is_annihilation) def __mul__(self, other): if other == IdentityOperator(2): return self if isinstance(other, Mul): args1 = tuple(arg for arg in other.args if arg.is_commutative) args2 = tuple(arg for arg in other.args if not arg.is_commutative) x = self for y in args2: x = x * y return Mul(*args1) * x return Mul(self, other) def _print_contents_latex(self, printer, *args): if self.is_annihilation: return r'{%s}' % str(self.name) else: return r'{{%s}^\dagger}' % str(self.name) def _print_contents(self, printer, *args): if self.is_annihilation: return r'%s' % str(self.name) else: return r'Dagger(%s)' % str(self.name) def _print_contents_pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) if self.is_annihilation: return pform else: return pform**prettyForm('\N{DAGGER}') class BosonFockKet(Ket): """Fock state ket for a bosonic mode. Parameters ========== n : Number The Fock state number. """ def __new__(cls, n): return Ket.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return BosonFockBra @classmethod def _eval_hilbert_space(cls, label): return FockSpace() def _eval_innerproduct_BosonFockBra(self, bra, **hints): return KroneckerDelta(self.n, bra.n) def _apply_from_right_to_BosonOp(self, op, **options): if op.is_annihilation: return sqrt(self.n) * BosonFockKet(self.n - 1) else: return sqrt(self.n + 1) * BosonFockKet(self.n + 1) class BosonFockBra(Bra): """Fock state bra for a bosonic mode. Parameters ========== n : Number The Fock state number. """ def __new__(cls, n): return Bra.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return BosonFockKet @classmethod def _eval_hilbert_space(cls, label): return FockSpace() class BosonCoherentKet(Ket): """Coherent state ket for a bosonic mode. Parameters ========== alpha : Number, Symbol The complex amplitude of the coherent state. """ def __new__(cls, alpha): return Ket.__new__(cls, alpha) @property def alpha(self): return self.label[0] @classmethod def dual_class(self): return BosonCoherentBra @classmethod def _eval_hilbert_space(cls, label): return HilbertSpace() def _eval_innerproduct_BosonCoherentBra(self, bra, **hints): if self.alpha == bra.alpha: return S.One else: return exp(-(abs(self.alpha)**2 + abs(bra.alpha)**2 - 2 * conjugate(bra.alpha) * self.alpha)/2) def _apply_from_right_to_BosonOp(self, op, **options): if op.is_annihilation: return self.alpha * self else: return None class BosonCoherentBra(Bra): """Coherent state bra for a bosonic mode. Parameters ========== alpha : Number, Symbol The complex amplitude of the coherent state. """ def __new__(cls, alpha): return Bra.__new__(cls, alpha) @property def alpha(self): return self.label[0] @classmethod def dual_class(self): return BosonCoherentKet def _apply_operator_BosonOp(self, op, **options): if not op.is_annihilation: return self.alpha * self else: return None
973c561475eac4a5918982bdf500a8f73b951bd7955e207cbc5c9aed3beb5714
"""Pauli operators and states""" from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.numbers import I from sympy.core.power import Pow from sympy.core.singleton import S from sympy.functions.elementary.exponential import exp from sympy.physics.quantum import Operator, Ket, Bra from sympy.physics.quantum import ComplexSpace from sympy.matrices import Matrix from sympy.functions.special.tensor_functions import KroneckerDelta __all__ = [ 'SigmaX', 'SigmaY', 'SigmaZ', 'SigmaMinus', 'SigmaPlus', 'SigmaZKet', 'SigmaZBra', 'qsimplify_pauli' ] class SigmaOpBase(Operator): """Pauli sigma operator, base class""" @property def name(self): return self.args[0] @property def use_name(self): return bool(self.args[0]) is not False @classmethod def default_args(self): return (False,) def __new__(cls, *args, **hints): return Operator.__new__(cls, *args, **hints) def _eval_commutator_BosonOp(self, other, **hints): return S.Zero class SigmaX(SigmaOpBase): """Pauli sigma x operator Parameters ========== name : str An optional string that labels the operator. Pauli operators with different names commute. Examples ======== >>> from sympy.physics.quantum import represent >>> from sympy.physics.quantum.pauli import SigmaX >>> sx = SigmaX() >>> sx SigmaX() >>> represent(sx) Matrix([ [0, 1], [1, 0]]) """ def __new__(cls, *args, **hints): return SigmaOpBase.__new__(cls, *args, **hints) def _eval_commutator_SigmaY(self, other, **hints): if self.name != other.name: return S.Zero else: return 2 * I * SigmaZ(self.name) def _eval_commutator_SigmaZ(self, other, **hints): if self.name != other.name: return S.Zero else: return - 2 * I * SigmaY(self.name) def _eval_commutator_BosonOp(self, other, **hints): return S.Zero def _eval_anticommutator_SigmaY(self, other, **hints): return S.Zero def _eval_anticommutator_SigmaZ(self, other, **hints): return S.Zero def _eval_adjoint(self): return self def _print_contents_latex(self, printer, *args): if self.use_name: return r'{\sigma_x^{(%s)}}' % str(self.name) else: return r'{\sigma_x}' def _print_contents(self, printer, *args): return 'SigmaX()' def _eval_power(self, e): if e.is_Integer and e.is_positive: return SigmaX(self.name).__pow__(int(e) % 2) def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[0, 1], [1, 0]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.') class SigmaY(SigmaOpBase): """Pauli sigma y operator Parameters ========== name : str An optional string that labels the operator. Pauli operators with different names commute. Examples ======== >>> from sympy.physics.quantum import represent >>> from sympy.physics.quantum.pauli import SigmaY >>> sy = SigmaY() >>> sy SigmaY() >>> represent(sy) Matrix([ [0, -I], [I, 0]]) """ def __new__(cls, *args, **hints): return SigmaOpBase.__new__(cls, *args) def _eval_commutator_SigmaZ(self, other, **hints): if self.name != other.name: return S.Zero else: return 2 * I * SigmaX(self.name) def _eval_commutator_SigmaX(self, other, **hints): if self.name != other.name: return S.Zero else: return - 2 * I * SigmaZ(self.name) def _eval_anticommutator_SigmaX(self, other, **hints): return S.Zero def _eval_anticommutator_SigmaZ(self, other, **hints): return S.Zero def _eval_adjoint(self): return self def _print_contents_latex(self, printer, *args): if self.use_name: return r'{\sigma_y^{(%s)}}' % str(self.name) else: return r'{\sigma_y}' def _print_contents(self, printer, *args): return 'SigmaY()' def _eval_power(self, e): if e.is_Integer and e.is_positive: return SigmaY(self.name).__pow__(int(e) % 2) def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[0, -I], [I, 0]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.') class SigmaZ(SigmaOpBase): """Pauli sigma z operator Parameters ========== name : str An optional string that labels the operator. Pauli operators with different names commute. Examples ======== >>> from sympy.physics.quantum import represent >>> from sympy.physics.quantum.pauli import SigmaZ >>> sz = SigmaZ() >>> sz ** 3 SigmaZ() >>> represent(sz) Matrix([ [1, 0], [0, -1]]) """ def __new__(cls, *args, **hints): return SigmaOpBase.__new__(cls, *args) def _eval_commutator_SigmaX(self, other, **hints): if self.name != other.name: return S.Zero else: return 2 * I * SigmaY(self.name) def _eval_commutator_SigmaY(self, other, **hints): if self.name != other.name: return S.Zero else: return - 2 * I * SigmaX(self.name) def _eval_anticommutator_SigmaX(self, other, **hints): return S.Zero def _eval_anticommutator_SigmaY(self, other, **hints): return S.Zero def _eval_adjoint(self): return self def _print_contents_latex(self, printer, *args): if self.use_name: return r'{\sigma_z^{(%s)}}' % str(self.name) else: return r'{\sigma_z}' def _print_contents(self, printer, *args): return 'SigmaZ()' def _eval_power(self, e): if e.is_Integer and e.is_positive: return SigmaZ(self.name).__pow__(int(e) % 2) def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[1, 0], [0, -1]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.') class SigmaMinus(SigmaOpBase): """Pauli sigma minus operator Parameters ========== name : str An optional string that labels the operator. Pauli operators with different names commute. Examples ======== >>> from sympy.physics.quantum import represent, Dagger >>> from sympy.physics.quantum.pauli import SigmaMinus >>> sm = SigmaMinus() >>> sm SigmaMinus() >>> Dagger(sm) SigmaPlus() >>> represent(sm) Matrix([ [0, 0], [1, 0]]) """ def __new__(cls, *args, **hints): return SigmaOpBase.__new__(cls, *args) def _eval_commutator_SigmaX(self, other, **hints): if self.name != other.name: return S.Zero else: return -SigmaZ(self.name) def _eval_commutator_SigmaY(self, other, **hints): if self.name != other.name: return S.Zero else: return I * SigmaZ(self.name) def _eval_commutator_SigmaZ(self, other, **hints): return 2 * self def _eval_commutator_SigmaMinus(self, other, **hints): return SigmaZ(self.name) def _eval_anticommutator_SigmaZ(self, other, **hints): return S.Zero def _eval_anticommutator_SigmaX(self, other, **hints): return S.One def _eval_anticommutator_SigmaY(self, other, **hints): return I * S.NegativeOne def _eval_anticommutator_SigmaPlus(self, other, **hints): return S.One def _eval_adjoint(self): return SigmaPlus(self.name) def _eval_power(self, e): if e.is_Integer and e.is_positive: return S.Zero def _print_contents_latex(self, printer, *args): if self.use_name: return r'{\sigma_-^{(%s)}}' % str(self.name) else: return r'{\sigma_-}' def _print_contents(self, printer, *args): return 'SigmaMinus()' def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[0, 0], [1, 0]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.') class SigmaPlus(SigmaOpBase): """Pauli sigma plus operator Parameters ========== name : str An optional string that labels the operator. Pauli operators with different names commute. Examples ======== >>> from sympy.physics.quantum import represent, Dagger >>> from sympy.physics.quantum.pauli import SigmaPlus >>> sp = SigmaPlus() >>> sp SigmaPlus() >>> Dagger(sp) SigmaMinus() >>> represent(sp) Matrix([ [0, 1], [0, 0]]) """ def __new__(cls, *args, **hints): return SigmaOpBase.__new__(cls, *args) def _eval_commutator_SigmaX(self, other, **hints): if self.name != other.name: return S.Zero else: return SigmaZ(self.name) def _eval_commutator_SigmaY(self, other, **hints): if self.name != other.name: return S.Zero else: return I * SigmaZ(self.name) def _eval_commutator_SigmaZ(self, other, **hints): if self.name != other.name: return S.Zero else: return -2 * self def _eval_commutator_SigmaMinus(self, other, **hints): return SigmaZ(self.name) def _eval_anticommutator_SigmaZ(self, other, **hints): return S.Zero def _eval_anticommutator_SigmaX(self, other, **hints): return S.One def _eval_anticommutator_SigmaY(self, other, **hints): return I def _eval_anticommutator_SigmaMinus(self, other, **hints): return S.One def _eval_adjoint(self): return SigmaMinus(self.name) def _eval_mul(self, other): return self * other def _eval_power(self, e): if e.is_Integer and e.is_positive: return S.Zero def _print_contents_latex(self, printer, *args): if self.use_name: return r'{\sigma_+^{(%s)}}' % str(self.name) else: return r'{\sigma_+}' def _print_contents(self, printer, *args): return 'SigmaPlus()' def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[0, 1], [0, 0]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.') class SigmaZKet(Ket): """Ket for a two-level system quantum system. Parameters ========== n : Number The state number (0 or 1). """ def __new__(cls, n): if n not in (0, 1): raise ValueError("n must be 0 or 1") return Ket.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return SigmaZBra @classmethod def _eval_hilbert_space(cls, label): return ComplexSpace(2) def _eval_innerproduct_SigmaZBra(self, bra, **hints): return KroneckerDelta(self.n, bra.n) def _apply_from_right_to_SigmaZ(self, op, **options): if self.n == 0: return self else: return S.NegativeOne * self def _apply_from_right_to_SigmaX(self, op, **options): return SigmaZKet(1) if self.n == 0 else SigmaZKet(0) def _apply_from_right_to_SigmaY(self, op, **options): return I * SigmaZKet(1) if self.n == 0 else (-I) * SigmaZKet(0) def _apply_from_right_to_SigmaMinus(self, op, **options): if self.n == 0: return SigmaZKet(1) else: return S.Zero def _apply_from_right_to_SigmaPlus(self, op, **options): if self.n == 0: return S.Zero else: return SigmaZKet(0) def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[1], [0]]) if self.n == 0 else Matrix([[0], [1]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.') class SigmaZBra(Bra): """Bra for a two-level quantum system. Parameters ========== n : Number The state number (0 or 1). """ def __new__(cls, n): if n not in (0, 1): raise ValueError("n must be 0 or 1") return Bra.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return SigmaZKet def _qsimplify_pauli_product(a, b): """ Internal helper function for simplifying products of Pauli operators. """ if not (isinstance(a, SigmaOpBase) and isinstance(b, SigmaOpBase)): return Mul(a, b) if a.name != b.name: # Pauli matrices with different labels commute; sort by name if a.name < b.name: return Mul(a, b) else: return Mul(b, a) elif isinstance(a, SigmaX): if isinstance(b, SigmaX): return S.One if isinstance(b, SigmaY): return I * SigmaZ(a.name) if isinstance(b, SigmaZ): return - I * SigmaY(a.name) if isinstance(b, SigmaMinus): return (S.Half + SigmaZ(a.name)/2) if isinstance(b, SigmaPlus): return (S.Half - SigmaZ(a.name)/2) elif isinstance(a, SigmaY): if isinstance(b, SigmaX): return - I * SigmaZ(a.name) if isinstance(b, SigmaY): return S.One if isinstance(b, SigmaZ): return I * SigmaX(a.name) if isinstance(b, SigmaMinus): return -I * (S.One + SigmaZ(a.name))/2 if isinstance(b, SigmaPlus): return I * (S.One - SigmaZ(a.name))/2 elif isinstance(a, SigmaZ): if isinstance(b, SigmaX): return I * SigmaY(a.name) if isinstance(b, SigmaY): return - I * SigmaX(a.name) if isinstance(b, SigmaZ): return S.One if isinstance(b, SigmaMinus): return - SigmaMinus(a.name) if isinstance(b, SigmaPlus): return SigmaPlus(a.name) elif isinstance(a, SigmaMinus): if isinstance(b, SigmaX): return (S.One - SigmaZ(a.name))/2 if isinstance(b, SigmaY): return - I * (S.One - SigmaZ(a.name))/2 if isinstance(b, SigmaZ): # (SigmaX(a.name) - I * SigmaY(a.name))/2 return SigmaMinus(b.name) if isinstance(b, SigmaMinus): return S.Zero if isinstance(b, SigmaPlus): return S.Half - SigmaZ(a.name)/2 elif isinstance(a, SigmaPlus): if isinstance(b, SigmaX): return (S.One + SigmaZ(a.name))/2 if isinstance(b, SigmaY): return I * (S.One + SigmaZ(a.name))/2 if isinstance(b, SigmaZ): #-(SigmaX(a.name) + I * SigmaY(a.name))/2 return -SigmaPlus(a.name) if isinstance(b, SigmaMinus): return (S.One + SigmaZ(a.name))/2 if isinstance(b, SigmaPlus): return S.Zero else: return a * b def qsimplify_pauli(e): """ Simplify an expression that includes products of pauli operators. Parameters ========== e : expression An expression that contains products of Pauli operators that is to be simplified. Examples ======== >>> from sympy.physics.quantum.pauli import SigmaX, SigmaY >>> from sympy.physics.quantum.pauli import qsimplify_pauli >>> sx, sy = SigmaX(), SigmaY() >>> sx * sy SigmaX()*SigmaY() >>> qsimplify_pauli(sx * sy) I*SigmaZ() """ if isinstance(e, Operator): return e if isinstance(e, (Add, Pow, exp)): t = type(e) return t(*(qsimplify_pauli(arg) for arg in e.args)) if isinstance(e, Mul): c, nc = e.args_cnc() nc_s = [] while nc: curr = nc.pop(0) while (len(nc) and isinstance(curr, SigmaOpBase) and isinstance(nc[0], SigmaOpBase) and curr.name == nc[0].name): x = nc.pop(0) y = _qsimplify_pauli_product(curr, x) c1, nc1 = y.args_cnc() curr = Mul(*nc1) c = c + c1 nc_s.append(curr) return Mul(*c) * Mul(*nc_s) return e
13a847d30ee93076973a2c53dc55a4701266e7a6288bc07ddf079d81c1f75d06
"""Logic for applying operators to states. Todo: * Sometimes the final result needs to be expanded, we should do this by hand. """ from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.sympify import sympify from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.innerproduct import InnerProduct from sympy.physics.quantum.operator import OuterProduct, Operator from sympy.physics.quantum.state import State, KetBase, BraBase, Wavefunction from sympy.physics.quantum.tensorproduct import TensorProduct __all__ = [ 'qapply' ] #----------------------------------------------------------------------------- # Main code #----------------------------------------------------------------------------- def qapply(e, **options): """Apply operators to states in a quantum expression. Parameters ========== e : Expr The expression containing operators and states. This expression tree will be walked to find operators acting on states symbolically. options : dict A dict of key/value pairs that determine how the operator actions are carried out. The following options are valid: * ``dagger``: try to apply Dagger operators to the left (default: False). * ``ip_doit``: call ``.doit()`` in inner products when they are encountered (default: True). Returns ======= e : Expr The original expression, but with the operators applied to states. Examples ======== >>> from sympy.physics.quantum import qapply, Ket, Bra >>> b = Bra('b') >>> k = Ket('k') >>> A = k * b >>> A |k><b| >>> qapply(A * b.dual / (b * b.dual)) |k> >>> qapply(k.dual * A / (k.dual * k), dagger=True) <b| >>> qapply(k.dual * A / (k.dual * k)) <k|*|k><b|/<k|k> """ from sympy.physics.quantum.density import Density dagger = options.get('dagger', False) if e == 0: return S.Zero # This may be a bit aggressive but ensures that everything gets expanded # to its simplest form before trying to apply operators. This includes # things like (A+B+C)*|a> and A*(|a>+|b>) and all Commutators and # TensorProducts. The only problem with this is that if we can't apply # all the Operators, we have just expanded everything. # TODO: don't expand the scalars in front of each Mul. e = e.expand(commutator=True, tensorproduct=True) # If we just have a raw ket, return it. if isinstance(e, KetBase): return e # We have an Add(a, b, c, ...) and compute # Add(qapply(a), qapply(b), ...) elif isinstance(e, Add): result = 0 for arg in e.args: result += qapply(arg, **options) return result.expand() # For a Density operator call qapply on its state elif isinstance(e, Density): new_args = [(qapply(state, **options), prob) for (state, prob) in e.args] return Density(*new_args) # For a raw TensorProduct, call qapply on its args. elif isinstance(e, TensorProduct): return TensorProduct(*[qapply(t, **options) for t in e.args]) # For a Pow, call qapply on its base. elif isinstance(e, Pow): return qapply(e.base, **options)**e.exp # We have a Mul where there might be actual operators to apply to kets. elif isinstance(e, Mul): c_part, nc_part = e.args_cnc() c_mul = Mul(*c_part) nc_mul = Mul(*nc_part) if isinstance(nc_mul, Mul): result = c_mul*qapply_Mul(nc_mul, **options) else: result = c_mul*qapply(nc_mul, **options) if result == e and dagger: return Dagger(qapply_Mul(Dagger(e), **options)) else: return result # In all other cases (State, Operator, Pow, Commutator, InnerProduct, # OuterProduct) we won't ever have operators to apply to kets. else: return e def qapply_Mul(e, **options): ip_doit = options.get('ip_doit', True) args = list(e.args) # If we only have 0 or 1 args, we have nothing to do and return. if len(args) <= 1 or not isinstance(e, Mul): return e rhs = args.pop() lhs = args.pop() # Make sure we have two non-commutative objects before proceeding. if (not isinstance(rhs, Wavefunction) and sympify(rhs).is_commutative) or \ (not isinstance(lhs, Wavefunction) and sympify(lhs).is_commutative): return e # For a Pow with an integer exponent, apply one of them and reduce the # exponent by one. if isinstance(lhs, Pow) and lhs.exp.is_Integer: args.append(lhs.base**(lhs.exp - 1)) lhs = lhs.base # Pull OuterProduct apart if isinstance(lhs, OuterProduct): args.append(lhs.ket) lhs = lhs.bra # Call .doit() on Commutator/AntiCommutator. if isinstance(lhs, (Commutator, AntiCommutator)): comm = lhs.doit() if isinstance(comm, Add): return qapply( e.func(*(args + [comm.args[0], rhs])) + e.func(*(args + [comm.args[1], rhs])), **options ) else: return qapply(e.func(*args)*comm*rhs, **options) # Apply tensor products of operators to states if isinstance(lhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in lhs.args) and \ isinstance(rhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in rhs.args) and \ len(lhs.args) == len(rhs.args): result = TensorProduct(*[qapply(lhs.args[n]*rhs.args[n], **options) for n in range(len(lhs.args))]).expand(tensorproduct=True) return qapply_Mul(e.func(*args), **options)*result # Now try to actually apply the operator and build an inner product. try: result = lhs._apply_operator(rhs, **options) except (NotImplementedError, AttributeError): try: result = rhs._apply_from_right_to(lhs, **options) except (NotImplementedError, AttributeError): if isinstance(lhs, BraBase) and isinstance(rhs, KetBase): result = InnerProduct(lhs, rhs) if ip_doit: result = result.doit() else: result = None # TODO: I may need to expand before returning the final result. if result == 0: return S.Zero elif result is None: if len(args) == 0: # We had two args to begin with so args=[]. return e else: return qapply_Mul(e.func(*(args + [lhs])), **options)*rhs elif isinstance(result, InnerProduct): return result*qapply_Mul(e.func(*args), **options) else: # result is a scalar times a Mul, Add or TensorProduct return qapply(e.func(*args)*result, **options)
7aa41b9ac3ce66769dd1a1f7dba37f15f6595adcece0822f6ee8307e42e51ed4
from sympy.core.backend import Symbol from sympy.physics.vector import Point, Vector, ReferenceFrame, Dyadic from sympy.physics.mechanics import RigidBody, Particle, inertia __all__ = ['Body'] # XXX: We use type:ignore because the classes RigidBody and Particle have # inconsistent parallel axis methods that take different numbers of arguments. class Body(RigidBody, Particle): # type: ignore """ Body is a common representation of either a RigidBody or a Particle SymPy object depending on what is passed in during initialization. If a mass is passed in and central_inertia is left as None, the Particle object is created. Otherwise a RigidBody object will be created. Explanation =========== The attributes that Body possesses will be the same as a Particle instance or a Rigid Body instance depending on which was created. Additional attributes are listed below. Attributes ========== name : string The body's name masscenter : Point The point which represents the center of mass of the rigid body frame : ReferenceFrame The reference frame which the body is fixed in mass : Sympifyable The body's mass inertia : (Dyadic, Point) The body's inertia around its center of mass. This attribute is specific to the rigid body form of Body and is left undefined for the Particle form loads : iterable This list contains information on the different loads acting on the Body. Forces are listed as a (point, vector) tuple and torques are listed as (reference frame, vector) tuples. Parameters ========== name : String Defines the name of the body. It is used as the base for defining body specific properties. masscenter : Point, optional A point that represents the center of mass of the body or particle. If no point is given, a point is generated. mass : Sympifyable, optional A Sympifyable object which represents the mass of the body. If no mass is passed, one is generated. frame : ReferenceFrame, optional The ReferenceFrame that represents the reference frame of the body. If no frame is given, a frame is generated. central_inertia : Dyadic, optional Central inertia dyadic of the body. If none is passed while creating RigidBody, a default inertia is generated. Examples ======== Default behaviour. This results in the creation of a RigidBody object for which the mass, mass center, frame and inertia attributes are given default values. :: >>> from sympy.physics.mechanics import Body >>> body = Body('name_of_body') This next example demonstrates the code required to specify all of the values of the Body object. Note this will also create a RigidBody version of the Body object. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import ReferenceFrame, Point, inertia >>> from sympy.physics.mechanics import Body >>> mass = Symbol('mass') >>> masscenter = Point('masscenter') >>> frame = ReferenceFrame('frame') >>> ixx = Symbol('ixx') >>> body_inertia = inertia(frame, ixx, 0, 0) >>> body = Body('name_of_body', masscenter, mass, frame, body_inertia) The minimal code required to create a Particle version of the Body object involves simply passing in a name and a mass. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import Body >>> mass = Symbol('mass') >>> body = Body('name_of_body', mass=mass) The Particle version of the Body object can also receive a masscenter point and a reference frame, just not an inertia. """ def __init__(self, name, masscenter=None, mass=None, frame=None, central_inertia=None): self.name = name self._loads = [] if frame is None: frame = ReferenceFrame(name + '_frame') if masscenter is None: masscenter = Point(name + '_masscenter') if central_inertia is None and mass is None: ixx = Symbol(name + '_ixx') iyy = Symbol(name + '_iyy') izz = Symbol(name + '_izz') izx = Symbol(name + '_izx') ixy = Symbol(name + '_ixy') iyz = Symbol(name + '_iyz') _inertia = (inertia(frame, ixx, iyy, izz, ixy, iyz, izx), masscenter) else: _inertia = (central_inertia, masscenter) if mass is None: _mass = Symbol(name + '_mass') else: _mass = mass masscenter.set_vel(frame, 0) # If user passes masscenter and mass then a particle is created # otherwise a rigidbody. As a result a body may or may not have inertia. if central_inertia is None and mass is not None: self.frame = frame self.masscenter = masscenter Particle.__init__(self, name, masscenter, _mass) self._central_inertia = Dyadic(0) else: RigidBody.__init__(self, name, masscenter, frame, _mass, _inertia) @property def loads(self): return self._loads @property def x(self): """The basis Vector for the Body, in the x direction.""" return self.frame.x @property def y(self): """The basis Vector for the Body, in the y direction.""" return self.frame.y @property def z(self): """The basis Vector for the Body, in the z direction.""" return self.frame.z @property def inertia(self): """The body's inertia about a point; stored as (Dyadic, Point).""" if self.is_rigidbody: return RigidBody.inertia.fget(self) return (self.central_inertia, self.masscenter) @inertia.setter def inertia(self, I): RigidBody.inertia.fset(self, I) @property def is_rigidbody(self): if hasattr(self, '_inertia'): return True return False def kinetic_energy(self, frame): """Kinetic energy of the body. Parameters ========== frame : ReferenceFrame or Body The Body's angular velocity and the velocity of it's mass center are typically defined with respect to an inertial frame but any relevant frame in which the velocities are known can be supplied. Examples ======== >>> from sympy.physics.mechanics import Body, ReferenceFrame, Point >>> from sympy import symbols >>> m, v, r, omega = symbols('m v r omega') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> P = Body('P', masscenter=O, mass=m) >>> P.masscenter.set_vel(N, v * N.y) >>> P.kinetic_energy(N) m*v**2/2 >>> N = ReferenceFrame('N') >>> b = ReferenceFrame('b') >>> b.set_ang_vel(N, omega * b.x) >>> P = Point('P') >>> P.set_vel(N, v * N.x) >>> B = Body('B', masscenter=P, frame=b) >>> B.kinetic_energy(N) B_ixx*omega**2/2 + B_mass*v**2/2 See Also ======== sympy.physics.mechanics : Particle, RigidBody """ if isinstance(frame, Body): frame = Body.frame if self.is_rigidbody: return RigidBody(self.name, self.masscenter, self.frame, self.mass, (self.central_inertia, self.masscenter)).kinetic_energy(frame) return Particle(self.name, self.masscenter, self.mass).kinetic_energy(frame) def apply_force(self, force, point=None, reaction_body=None, reaction_point=None): """Add force to the body(s). Explanation =========== Applies the force on self or equal and oppposite forces on self and other body if both are given on the desried point on the bodies. The force applied on other body is taken opposite of self, i.e, -force. Parameters ========== force: Vector The force to be applied. point: Point, optional The point on self on which force is applied. By default self's masscenter. reaction_body: Body, optional Second body on which equal and opposite force is to be applied. reaction_point : Point, optional The point on other body on which equal and opposite force is applied. By default masscenter of other body. Example ======= >>> from sympy import symbols >>> from sympy.physics.mechanics import Body, Point, dynamicsymbols >>> m, g = symbols('m g') >>> B = Body('B') >>> force1 = m*g*B.z >>> B.apply_force(force1) #Applying force on B's masscenter >>> B.loads [(B_masscenter, g*m*B_frame.z)] We can also remove some part of force from any point on the body by adding the opposite force to the body on that point. >>> f1, f2 = dynamicsymbols('f1 f2') >>> P = Point('P') #Considering point P on body B >>> B.apply_force(f1*B.x + f2*B.y, P) >>> B.loads [(B_masscenter, g*m*B_frame.z), (P, f1(t)*B_frame.x + f2(t)*B_frame.y)] Let's remove f1 from point P on body B. >>> B.apply_force(-f1*B.x, P) >>> B.loads [(B_masscenter, g*m*B_frame.z), (P, f2(t)*B_frame.y)] To further demonstrate the use of ``apply_force`` attribute, consider two bodies connected through a spring. >>> from sympy.physics.mechanics import Body, dynamicsymbols >>> N = Body('N') #Newtonion Frame >>> x = dynamicsymbols('x') >>> B1 = Body('B1') >>> B2 = Body('B2') >>> spring_force = x*N.x Now let's apply equal and opposite spring force to the bodies. >>> P1 = Point('P1') >>> P2 = Point('P2') >>> B1.apply_force(spring_force, point=P1, reaction_body=B2, reaction_point=P2) We can check the loads(forces) applied to bodies now. >>> B1.loads [(P1, x(t)*N_frame.x)] >>> B2.loads [(P2, - x(t)*N_frame.x)] Notes ===== If a new force is applied to a body on a point which already has some force applied on it, then the new force is added to the already applied force on that point. """ if not isinstance(point, Point): if point is None: point = self.masscenter # masscenter else: raise TypeError("Force must be applied to a point on the body.") if not isinstance(force, Vector): raise TypeError("Force must be a vector.") if reaction_body is not None: reaction_body.apply_force(-force, point=reaction_point) for load in self._loads: if point in load: force += load[1] self._loads.remove(load) break self._loads.append((point, force)) def apply_torque(self, torque, reaction_body=None): """Add torque to the body(s). Explanation =========== Applies the torque on self or equal and oppposite torquess on self and other body if both are given. The torque applied on other body is taken opposite of self, i.e, -torque. Parameters ========== torque: Vector The torque to be applied. reaction_body: Body, optional Second body on which equal and opposite torque is to be applied. Example ======= >>> from sympy import symbols >>> from sympy.physics.mechanics import Body, dynamicsymbols >>> t = symbols('t') >>> B = Body('B') >>> torque1 = t*B.z >>> B.apply_torque(torque1) >>> B.loads [(B_frame, t*B_frame.z)] We can also remove some part of torque from the body by adding the opposite torque to the body. >>> t1, t2 = dynamicsymbols('t1 t2') >>> B.apply_torque(t1*B.x + t2*B.y) >>> B.loads [(B_frame, t1(t)*B_frame.x + t2(t)*B_frame.y + t*B_frame.z)] Let's remove t1 from Body B. >>> B.apply_torque(-t1*B.x) >>> B.loads [(B_frame, t2(t)*B_frame.y + t*B_frame.z)] To further demonstrate the use, let us consider two bodies such that a torque `T` is acting on one body, and `-T` on the other. >>> from sympy.physics.mechanics import Body, dynamicsymbols >>> N = Body('N') #Newtonion frame >>> B1 = Body('B1') >>> B2 = Body('B2') >>> v = dynamicsymbols('v') >>> T = v*N.y #Torque Now let's apply equal and opposite torque to the bodies. >>> B1.apply_torque(T, B2) We can check the loads (torques) applied to bodies now. >>> B1.loads [(B1_frame, v(t)*N_frame.y)] >>> B2.loads [(B2_frame, - v(t)*N_frame.y)] Notes ===== If a new torque is applied on body which already has some torque applied on it, then the new torque is added to the previous torque about the body's frame. """ if not isinstance(torque, Vector): raise TypeError("A Vector must be supplied to add torque.") if reaction_body is not None: reaction_body.apply_torque(-torque) for load in self._loads: if self.frame in load: torque += load[1] self._loads.remove(load) break self._loads.append((self.frame, torque)) def clear_loads(self): """ Clears the Body's loads list. Example ======= >>> from sympy.physics.mechanics import Body >>> B = Body('B') >>> force = B.x + B.y >>> B.apply_force(force) >>> B.loads [(B_masscenter, B_frame.x + B_frame.y)] >>> B.clear_loads() >>> B.loads [] """ self._loads = [] def remove_load(self, about=None): """ Remove load about a point or frame. Parameters ========== about : Point or ReferenceFrame, optional The point about which force is applied, and is to be removed. If about is None, then the torque about self's frame is removed. Example ======= >>> from sympy.physics.mechanics import Body, Point >>> B = Body('B') >>> P = Point('P') >>> f1 = B.x >>> f2 = B.y >>> B.apply_force(f1) >>> B.apply_force(f2, P) >>> B.loads [(B_masscenter, B_frame.x), (P, B_frame.y)] >>> B.remove_load(P) >>> B.loads [(B_masscenter, B_frame.x)] """ if about is not None: if not isinstance(about, Point): raise TypeError('Load is applied about Point or ReferenceFrame.') else: about = self.frame for load in self._loads: if about in load: self._loads.remove(load) break def masscenter_vel(self, body): """ Returns the velocity of the mass center with respect to the provided rigid body or reference frame. Parameters ========== body: Body or ReferenceFrame The rigid body or reference frame to calculate the velocity in. Example ======= >>> from sympy.physics.mechanics import Body >>> A = Body('A') >>> B = Body('B') >>> A.masscenter.set_vel(B.frame, 5*B.frame.x) >>> A.masscenter_vel(B) 5*B_frame.x >>> A.masscenter_vel(B.frame) 5*B_frame.x """ if isinstance(body, ReferenceFrame): frame=body elif isinstance(body, Body): frame = body.frame return self.masscenter.vel(frame) def ang_vel_in(self, body): """ Returns this body's angular velocity with respect to the provided rigid body or reference frame. Parameters ========== body: Body or ReferenceFrame The rigid body or reference frame to calculate the angular velocity in. Example ======= >>> from sympy.physics.mechanics import Body, ReferenceFrame >>> A = Body('A') >>> N = ReferenceFrame('N') >>> B = Body('B', frame=N) >>> A.frame.set_ang_vel(N, 5*N.x) >>> A.ang_vel_in(B) 5*N.x >>> A.ang_vel_in(N) 5*N.x """ if isinstance(body, ReferenceFrame): frame=body elif isinstance(body, Body): frame = body.frame return self.frame.ang_vel_in(frame) def dcm(self, body): """ Returns the direction cosine matrix of this body relative to the provided rigid body or reference frame. Parameters ========== body: Body or ReferenceFrame The rigid body or reference frame to calculate the dcm. Example ======= >>> from sympy.physics.mechanics import Body >>> A = Body('A') >>> B = Body('B') >>> A.frame.orient_axis(B.frame, B.frame.x, 5) >>> A.dcm(B) Matrix([ [1, 0, 0], [0, cos(5), sin(5)], [0, -sin(5), cos(5)]]) >>> A.dcm(B.frame) Matrix([ [1, 0, 0], [0, cos(5), sin(5)], [0, -sin(5), cos(5)]]) """ if isinstance(body, ReferenceFrame): frame=body elif isinstance(body, Body): frame = body.frame return self.frame.dcm(frame) def parallel_axis(self, point, frame=None): """Returns the inertia dyadic of the body with respect to another point. Parameters ========== point : sympy.physics.vector.Point The point to express the inertia dyadic about. frame : sympy.physics.vector.ReferenceFrame The reference frame used to construct the dyadic. Returns ======= inertia : sympy.physics.vector.Dyadic The inertia dyadic of the rigid body expressed about the provided point. Example ======= >>> from sympy.physics.mechanics import Body >>> A = Body('A') >>> P = A.masscenter.locatenew('point', 3 * A.x + 5 * A.y) >>> A.parallel_axis(P).to_matrix(A.frame) Matrix([ [A_ixx + 25*A_mass, A_ixy - 15*A_mass, A_izx], [A_ixy - 15*A_mass, A_iyy + 9*A_mass, A_iyz], [ A_izx, A_iyz, A_izz + 34*A_mass]]) """ if self.is_rigidbody: return RigidBody.parallel_axis(self, point, frame) return Particle.parallel_axis(self, point, frame)
e7b5c73ce645df2dbe74b72b7f01021208c5b615187909dc99fb7719960ac8e6
__all__ = [ 'vector', 'CoordinateSym', 'ReferenceFrame', 'Dyadic', 'Vector', 'Point', 'cross', 'dot', 'express', 'time_derivative', 'outer', 'kinematic_equations', 'get_motion_params', 'partial_velocity', 'dynamicsymbols', 'vprint', 'vsstrrepr', 'vsprint', 'vpprint', 'vlatex', 'init_vprinting', 'curl', 'divergence', 'gradient', 'is_conservative', 'is_solenoidal', 'scalar_potential', 'scalar_potential_difference', 'KanesMethod', 'RigidBody', 'inertia', 'inertia_of_point_mass', 'linear_momentum', 'angular_momentum', 'kinetic_energy', 'potential_energy', 'Lagrangian', 'mechanics_printing', 'mprint', 'msprint', 'mpprint', 'mlatex', 'msubs', 'find_dynamicsymbols', 'Particle', 'LagrangesMethod', 'Linearizer', 'Body', 'SymbolicSystem', 'PinJoint', 'PrismaticJoint', 'CylindricalJoint', 'PlanarJoint', 'SphericalJoint', 'WeldJoint', 'JointsMethod' ] from sympy.physics import vector from sympy.physics.vector import (CoordinateSym, ReferenceFrame, Dyadic, Vector, Point, cross, dot, express, time_derivative, outer, kinematic_equations, get_motion_params, partial_velocity, dynamicsymbols, vprint, vsstrrepr, vsprint, vpprint, vlatex, init_vprinting, curl, divergence, gradient, is_conservative, is_solenoidal, scalar_potential, scalar_potential_difference) from .kane import KanesMethod from .rigidbody import RigidBody from .functions import (inertia, inertia_of_point_mass, linear_momentum, angular_momentum, kinetic_energy, potential_energy, Lagrangian, mechanics_printing, mprint, msprint, mpprint, mlatex, msubs, find_dynamicsymbols) from .particle import Particle from .lagrange import LagrangesMethod from .linearize import Linearizer from .body import Body from .system import SymbolicSystem from .jointsmethod import JointsMethod from .joint import (PinJoint, PrismaticJoint, CylindricalJoint, PlanarJoint, SphericalJoint, WeldJoint)
2fe8a644de33042b455da8e3c90e3eda978c50bab2b026d5114abaf49a506e00
from sympy.core.backend import zeros, Matrix, diff, eye from sympy.core.sorting import default_sort_key from sympy.physics.vector import (ReferenceFrame, dynamicsymbols, partial_velocity) from sympy.physics.mechanics.method import _Methods from sympy.physics.mechanics.particle import Particle from sympy.physics.mechanics.rigidbody import RigidBody from sympy.physics.mechanics.functions import ( msubs, find_dynamicsymbols, _f_list_parser, _validate_coordinates) from sympy.physics.mechanics.linearize import Linearizer from sympy.utilities.iterables import iterable __all__ = ['KanesMethod'] class KanesMethod(_Methods): r"""Kane's method object. Explanation =========== This object is used to do the "book-keeping" as you go through and form equations of motion in the way Kane presents in: Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill The attributes are for equations in the form [M] udot = forcing. Attributes ========== q, u : Matrix Matrices of the generalized coordinates and speeds bodies : iterable Iterable of Point and RigidBody objects in the system. loads : iterable Iterable of (Point, vector) or (ReferenceFrame, vector) tuples describing the forces on the system. auxiliary_eqs : Matrix If applicable, the set of auxiliary Kane's equations used to solve for non-contributing forces. mass_matrix : Matrix The system's dynamics mass matrix: [k_d; k_dnh] forcing : Matrix The system's dynamics forcing vector: -[f_d; f_dnh] mass_matrix_kin : Matrix The "mass matrix" for kinematic differential equations: k_kqdot forcing_kin : Matrix The forcing vector for kinematic differential equations: -(k_ku*u + f_k) mass_matrix_full : Matrix The "mass matrix" for the u's and q's with dynamics and kinematics forcing_full : Matrix The "forcing vector" for the u's and q's with dynamics and kinematics explicit_kinematics : bool Boolean whether the mass matrices and forcing vectors should use the explicit form (default) or implicit form for kinematics. See the notes for more details. Notes ===== The mass matrices and forcing vectors related to kinematic equations are given in the explicit form by default. In other words, the kinematic mass matrix is $\mathbf{k_{k\dot{q}}} = \mathbf{I}$. In order to get the implicit form of those matrices/vectors, you can set the ``explicit_kinematics`` attribute to ``False``. So $\mathbf{k_{k\dot{q}}}$ is not necessarily an identity matrix. This can provide more compact equations for non-simple kinematics (see #22626). Examples ======== This is a simple example for a one degree of freedom translational spring-mass-damper. In this example, we first need to do the kinematics. This involves creating generalized speeds and coordinates and their derivatives. Then we create a point and set its velocity in a frame. >>> from sympy import symbols >>> from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame >>> from sympy.physics.mechanics import Point, Particle, KanesMethod >>> q, u = dynamicsymbols('q u') >>> qd, ud = dynamicsymbols('q u', 1) >>> m, c, k = symbols('m c k') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, u * N.x) Next we need to arrange/store information in the way that KanesMethod requires. The kinematic differential equations need to be stored in a dict. A list of forces/torques must be constructed, where each entry in the list is a (Point, Vector) or (ReferenceFrame, Vector) tuple, where the Vectors represent the Force or Torque. Next a particle needs to be created, and it needs to have a point and mass assigned to it. Finally, a list of all bodies and particles needs to be created. >>> kd = [qd - u] >>> FL = [(P, (-k * q - c * u) * N.x)] >>> pa = Particle('pa', P, m) >>> BL = [pa] Finally we can generate the equations of motion. First we create the KanesMethod object and supply an inertial frame, coordinates, generalized speeds, and the kinematic differential equations. Additional quantities such as configuration and motion constraints, dependent coordinates and speeds, and auxiliary speeds are also supplied here (see the online documentation). Next we form FR* and FR to complete: Fr + Fr* = 0. We have the equations of motion at this point. It makes sense to rearrange them though, so we calculate the mass matrix and the forcing terms, for E.o.M. in the form: [MM] udot = forcing, where MM is the mass matrix, udot is a vector of the time derivatives of the generalized speeds, and forcing is a vector representing "forcing" terms. >>> KM = KanesMethod(N, q_ind=[q], u_ind=[u], kd_eqs=kd) >>> (fr, frstar) = KM.kanes_equations(BL, FL) >>> MM = KM.mass_matrix >>> forcing = KM.forcing >>> rhs = MM.inv() * forcing >>> rhs Matrix([[(-c*u(t) - k*q(t))/m]]) >>> KM.linearize(A_and_B=True)[0] Matrix([ [ 0, 1], [-k/m, -c/m]]) Please look at the documentation pages for more information on how to perform linearization and how to deal with dependent coordinates & speeds, and how do deal with bringing non-contributing forces into evidence. """ def __init__(self, frame, q_ind, u_ind, kd_eqs=None, q_dependent=None, configuration_constraints=None, u_dependent=None, velocity_constraints=None, acceleration_constraints=None, u_auxiliary=None, bodies=None, forcelist=None, explicit_kinematics=True): """Please read the online documentation. """ if not q_ind: q_ind = [dynamicsymbols('dummy_q')] kd_eqs = [dynamicsymbols('dummy_kd')] if not isinstance(frame, ReferenceFrame): raise TypeError('An inertial ReferenceFrame must be supplied') self._inertial = frame self._fr = None self._frstar = None self._forcelist = forcelist self._bodylist = bodies self.explicit_kinematics = explicit_kinematics self._initialize_vectors(q_ind, q_dependent, u_ind, u_dependent, u_auxiliary) _validate_coordinates(self.q, self.u) self._initialize_kindiffeq_matrices(kd_eqs) self._initialize_constraint_matrices(configuration_constraints, velocity_constraints, acceleration_constraints) def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux): """Initialize the coordinate and speed vectors.""" none_handler = lambda x: Matrix(x) if x else Matrix() # Initialize generalized coordinates q_dep = none_handler(q_dep) if not iterable(q_ind): raise TypeError('Generalized coordinates must be an iterable.') if not iterable(q_dep): raise TypeError('Dependent coordinates must be an iterable.') q_ind = Matrix(q_ind) self._qdep = q_dep self._q = Matrix([q_ind, q_dep]) self._qdot = self.q.diff(dynamicsymbols._t) # Initialize generalized speeds u_dep = none_handler(u_dep) if not iterable(u_ind): raise TypeError('Generalized speeds must be an iterable.') if not iterable(u_dep): raise TypeError('Dependent speeds must be an iterable.') u_ind = Matrix(u_ind) self._udep = u_dep self._u = Matrix([u_ind, u_dep]) self._udot = self.u.diff(dynamicsymbols._t) self._uaux = none_handler(u_aux) def _initialize_constraint_matrices(self, config, vel, acc): """Initializes constraint matrices.""" # Define vector dimensions o = len(self.u) m = len(self._udep) p = o - m none_handler = lambda x: Matrix(x) if x else Matrix() # Initialize configuration constraints config = none_handler(config) if len(self._qdep) != len(config): raise ValueError('There must be an equal number of dependent ' 'coordinates and configuration constraints.') self._f_h = none_handler(config) # Initialize velocity and acceleration constraints vel = none_handler(vel) acc = none_handler(acc) if len(vel) != m: raise ValueError('There must be an equal number of dependent ' 'speeds and velocity constraints.') if acc and (len(acc) != m): raise ValueError('There must be an equal number of dependent ' 'speeds and acceleration constraints.') if vel: u_zero = {i: 0 for i in self.u} udot_zero = {i: 0 for i in self._udot} # When calling kanes_equations, another class instance will be # created if auxiliary u's are present. In this case, the # computation of kinetic differential equation matrices will be # skipped as this was computed during the original KanesMethod # object, and the qd_u_map will not be available. if self._qdot_u_map is not None: vel = msubs(vel, self._qdot_u_map) self._f_nh = msubs(vel, u_zero) self._k_nh = (vel - self._f_nh).jacobian(self.u) # If no acceleration constraints given, calculate them. if not acc: _f_dnh = (self._k_nh.diff(dynamicsymbols._t) * self.u + self._f_nh.diff(dynamicsymbols._t)) if self._qdot_u_map is not None: _f_dnh = msubs(_f_dnh, self._qdot_u_map) self._f_dnh = _f_dnh self._k_dnh = self._k_nh else: if self._qdot_u_map is not None: acc = msubs(acc, self._qdot_u_map) self._f_dnh = msubs(acc, udot_zero) self._k_dnh = (acc - self._f_dnh).jacobian(self._udot) # Form of non-holonomic constraints is B*u + C = 0. # We partition B into independent and dependent columns: # Ars is then -B_dep.inv() * B_ind, and it relates dependent speeds # to independent speeds as: udep = Ars*uind, neglecting the C term. B_ind = self._k_nh[:, :p] B_dep = self._k_nh[:, p:o] self._Ars = -B_dep.LUsolve(B_ind) else: self._f_nh = Matrix() self._k_nh = Matrix() self._f_dnh = Matrix() self._k_dnh = Matrix() self._Ars = Matrix() def _initialize_kindiffeq_matrices(self, kdeqs): """Initialize the kinematic differential equation matrices. Parameters ========== kdeqs : sequence of sympy expressions Kinematic differential equations in the form of f(u,q',q,t) where f() = 0. The equations have to be linear in the generalized coordinates and generalized speeds. """ if kdeqs: if len(self.q) != len(kdeqs): raise ValueError('There must be an equal number of kinematic ' 'differential equations and coordinates.') u = self.u qdot = self._qdot kdeqs = Matrix(kdeqs) u_zero = {ui: 0 for ui in u} uaux_zero = {uai: 0 for uai in self._uaux} qdot_zero = {qdi: 0 for qdi in qdot} # Extract the linear coefficient matrices as per the following # equation: # # k_ku(q,t)*u(t) + k_kqdot(q,t)*q'(t) + f_k(q,t) = 0 # k_ku = kdeqs.jacobian(u) k_kqdot = kdeqs.jacobian(qdot) f_k = kdeqs.xreplace(u_zero).xreplace(qdot_zero) # The kinematic differential equations should be linear in both q' # and u, so check for u and q' in the components. dy_syms = find_dynamicsymbols(k_ku.row_join(k_kqdot).row_join(f_k)) nonlin_vars = [vari for vari in u[:] + qdot[:] if vari in dy_syms] if nonlin_vars: msg = ('The provided kinematic differential equations are ' 'nonlinear in {}. They must be linear in the ' 'generalized speeds and derivatives of the generalized ' 'coordinates.') raise ValueError(msg.format(nonlin_vars)) self._f_k_implicit = f_k.xreplace(uaux_zero) self._k_ku_implicit = k_ku.xreplace(uaux_zero) self._k_kqdot_implicit = k_kqdot # Solve for q'(t) such that the coefficient matrices are now in # this form: # # k_kqdot^-1*k_ku*u(t) + I*q'(t) + k_kqdot^-1*f_k = 0 # # NOTE : Solving the kinematic differential equations here is not # necessary and prevents the equations from being provided in fully # implicit form. f_k_explicit = k_kqdot.LUsolve(f_k) k_ku_explicit = k_kqdot.LUsolve(k_ku) self._qdot_u_map = dict(zip(qdot, -(k_ku_explicit*u + f_k_explicit))) self._f_k = f_k_explicit.xreplace(uaux_zero) self._k_ku = k_ku_explicit.xreplace(uaux_zero) self._k_kqdot = eye(len(qdot)) else: self._qdot_u_map = None self._f_k_implicit = self._f_k = Matrix() self._k_ku_implicit = self._k_ku = Matrix() self._k_kqdot_implicit = self._k_kqdot = Matrix() def _form_fr(self, fl): """Form the generalized active force.""" if fl is not None and (len(fl) == 0 or not iterable(fl)): raise ValueError('Force pairs must be supplied in an ' 'non-empty iterable or None.') N = self._inertial # pull out relevant velocities for constructing partial velocities vel_list, f_list = _f_list_parser(fl, N) vel_list = [msubs(i, self._qdot_u_map) for i in vel_list] f_list = [msubs(i, self._qdot_u_map) for i in f_list] # Fill Fr with dot product of partial velocities and forces o = len(self.u) b = len(f_list) FR = zeros(o, 1) partials = partial_velocity(vel_list, self.u, N) for i in range(o): FR[i] = sum(partials[j][i] & f_list[j] for j in range(b)) # In case there are dependent speeds if self._udep: p = o - len(self._udep) FRtilde = FR[:p, 0] FRold = FR[p:o, 0] FRtilde += self._Ars.T * FRold FR = FRtilde self._forcelist = fl self._fr = FR return FR def _form_frstar(self, bl): """Form the generalized inertia force.""" if not iterable(bl): raise TypeError('Bodies must be supplied in an iterable.') t = dynamicsymbols._t N = self._inertial # Dicts setting things to zero udot_zero = {i: 0 for i in self._udot} uaux_zero = {i: 0 for i in self._uaux} uauxdot = [diff(i, t) for i in self._uaux] uauxdot_zero = {i: 0 for i in uauxdot} # Dictionary of q' and q'' to u and u' q_ddot_u_map = {k.diff(t): v.diff(t) for (k, v) in self._qdot_u_map.items()} q_ddot_u_map.update(self._qdot_u_map) # Fill up the list of partials: format is a list with num elements # equal to number of entries in body list. Each of these elements is a # list - either of length 1 for the translational components of # particles or of length 2 for the translational and rotational # components of rigid bodies. The inner most list is the list of # partial velocities. def get_partial_velocity(body): if isinstance(body, RigidBody): vlist = [body.masscenter.vel(N), body.frame.ang_vel_in(N)] elif isinstance(body, Particle): vlist = [body.point.vel(N),] else: raise TypeError('The body list may only contain either ' 'RigidBody or Particle as list elements.') v = [msubs(vel, self._qdot_u_map) for vel in vlist] return partial_velocity(v, self.u, N) partials = [get_partial_velocity(body) for body in bl] # Compute fr_star in two components: # fr_star = -(MM*u' + nonMM) o = len(self.u) MM = zeros(o, o) nonMM = zeros(o, 1) zero_uaux = lambda expr: msubs(expr, uaux_zero) zero_udot_uaux = lambda expr: msubs(msubs(expr, udot_zero), uaux_zero) for i, body in enumerate(bl): if isinstance(body, RigidBody): M = zero_uaux(body.mass) I = zero_uaux(body.central_inertia) vel = zero_uaux(body.masscenter.vel(N)) omega = zero_uaux(body.frame.ang_vel_in(N)) acc = zero_udot_uaux(body.masscenter.acc(N)) inertial_force = (M.diff(t) * vel + M * acc) inertial_torque = zero_uaux((I.dt(body.frame) & omega) + msubs(I & body.frame.ang_acc_in(N), udot_zero) + (omega ^ (I & omega))) for j in range(o): tmp_vel = zero_uaux(partials[i][0][j]) tmp_ang = zero_uaux(I & partials[i][1][j]) for k in range(o): # translational MM[j, k] += M * (tmp_vel & partials[i][0][k]) # rotational MM[j, k] += (tmp_ang & partials[i][1][k]) nonMM[j] += inertial_force & partials[i][0][j] nonMM[j] += inertial_torque & partials[i][1][j] else: M = zero_uaux(body.mass) vel = zero_uaux(body.point.vel(N)) acc = zero_udot_uaux(body.point.acc(N)) inertial_force = (M.diff(t) * vel + M * acc) for j in range(o): temp = zero_uaux(partials[i][0][j]) for k in range(o): MM[j, k] += M * (temp & partials[i][0][k]) nonMM[j] += inertial_force & partials[i][0][j] # Compose fr_star out of MM and nonMM MM = zero_uaux(msubs(MM, q_ddot_u_map)) nonMM = msubs(msubs(nonMM, q_ddot_u_map), udot_zero, uauxdot_zero, uaux_zero) fr_star = -(MM * msubs(Matrix(self._udot), uauxdot_zero) + nonMM) # If there are dependent speeds, we need to find fr_star_tilde if self._udep: p = o - len(self._udep) fr_star_ind = fr_star[:p, 0] fr_star_dep = fr_star[p:o, 0] fr_star = fr_star_ind + (self._Ars.T * fr_star_dep) # Apply the same to MM MMi = MM[:p, :] MMd = MM[p:o, :] MM = MMi + (self._Ars.T * MMd) self._bodylist = bl self._frstar = fr_star self._k_d = MM self._f_d = -msubs(self._fr + self._frstar, udot_zero) return fr_star def to_linearizer(self): """Returns an instance of the Linearizer class, initiated from the data in the KanesMethod class. This may be more desirable than using the linearize class method, as the Linearizer object will allow more efficient recalculation (i.e. about varying operating points).""" if (self._fr is None) or (self._frstar is None): raise ValueError('Need to compute Fr, Fr* first.') # Get required equation components. The Kane's method class breaks # these into pieces. Need to reassemble f_c = self._f_h if self._f_nh and self._k_nh: f_v = self._f_nh + self._k_nh*Matrix(self.u) else: f_v = Matrix() if self._f_dnh and self._k_dnh: f_a = self._f_dnh + self._k_dnh*Matrix(self._udot) else: f_a = Matrix() # Dicts to sub to zero, for splitting up expressions u_zero = {i: 0 for i in self.u} ud_zero = {i: 0 for i in self._udot} qd_zero = {i: 0 for i in self._qdot} qd_u_zero = {i: 0 for i in Matrix([self._qdot, self.u])} # Break the kinematic differential eqs apart into f_0 and f_1 f_0 = msubs(self._f_k, u_zero) + self._k_kqdot*Matrix(self._qdot) f_1 = msubs(self._f_k, qd_zero) + self._k_ku*Matrix(self.u) # Break the dynamic differential eqs into f_2 and f_3 f_2 = msubs(self._frstar, qd_u_zero) f_3 = msubs(self._frstar, ud_zero) + self._fr f_4 = zeros(len(f_2), 1) # Get the required vector components q = self.q u = self.u if self._qdep: q_i = q[:-len(self._qdep)] else: q_i = q q_d = self._qdep if self._udep: u_i = u[:-len(self._udep)] else: u_i = u u_d = self._udep # Form dictionary to set auxiliary speeds & their derivatives to 0. uaux = self._uaux uauxdot = uaux.diff(dynamicsymbols._t) uaux_zero = {i: 0 for i in Matrix([uaux, uauxdot])} # Checking for dynamic symbols outside the dynamic differential # equations; throws error if there is. sym_list = set(Matrix([q, self._qdot, u, self._udot, uaux, uauxdot])) if any(find_dynamicsymbols(i, sym_list) for i in [self._k_kqdot, self._k_ku, self._f_k, self._k_dnh, self._f_dnh, self._k_d]): raise ValueError('Cannot have dynamicsymbols outside dynamic \ forcing vector.') # Find all other dynamic symbols, forming the forcing vector r. # Sort r to make it canonical. r = list(find_dynamicsymbols(msubs(self._f_d, uaux_zero), sym_list)) r.sort(key=default_sort_key) # Check for any derivatives of variables in r that are also found in r. for i in r: if diff(i, dynamicsymbols._t) in r: raise ValueError('Cannot have derivatives of specified \ quantities when linearizing forcing terms.') return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i, q_d, u_i, u_d, r) # TODO : Remove `new_method` after 1.1 has been released. def linearize(self, *, new_method=None, **kwargs): """ Linearize the equations of motion about a symbolic operating point. Explanation =========== If kwarg A_and_B is False (default), returns M, A, B, r for the linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r. If kwarg A_and_B is True, returns A, B, r for the linearized form dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. Values may then be substituted in to these matrices, and the state space form found as A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat. In both cases, r is found as all dynamicsymbols in the equations of motion that are not part of q, u, q', or u'. They are sorted in canonical form. The operating points may be also entered using the ``op_point`` kwarg. This takes a dictionary of {symbol: value}, or a an iterable of such dictionaries. The values may be numeric or symbolic. The more values you can specify beforehand, the faster this computation will run. For more documentation, please see the ``Linearizer`` class.""" linearizer = self.to_linearizer() result = linearizer.linearize(**kwargs) return result + (linearizer.r,) def kanes_equations(self, bodies=None, loads=None): """ Method to form Kane's equations, Fr + Fr* = 0. Explanation =========== Returns (Fr, Fr*). In the case where auxiliary generalized speeds are present (say, s auxiliary speeds, o generalized speeds, and m motion constraints) the length of the returned vectors will be o - m + s in length. The first o - m equations will be the constrained Kane's equations, then the s auxiliary Kane's equations. These auxiliary equations can be accessed with the auxiliary_eqs property. Parameters ========== bodies : iterable An iterable of all RigidBody's and Particle's in the system. A system must have at least one body. loads : iterable Takes in an iterable of (Particle, Vector) or (ReferenceFrame, Vector) tuples which represent the force at a point or torque on a frame. Must be either a non-empty iterable of tuples or None which corresponds to a system with no constraints. """ if bodies is None: bodies = self.bodies if loads is None and self._forcelist is not None: loads = self._forcelist if loads == []: loads = None if not self._k_kqdot: raise AttributeError('Create an instance of KanesMethod with ' 'kinematic differential equations to use this method.') fr = self._form_fr(loads) frstar = self._form_frstar(bodies) if self._uaux: if not self._udep: km = KanesMethod(self._inertial, self.q, self._uaux, u_auxiliary=self._uaux) else: km = KanesMethod(self._inertial, self.q, self._uaux, u_auxiliary=self._uaux, u_dependent=self._udep, velocity_constraints=(self._k_nh * self.u + self._f_nh), acceleration_constraints=(self._k_dnh * self._udot + self._f_dnh) ) km._qdot_u_map = self._qdot_u_map self._km = km fraux = km._form_fr(loads) frstaraux = km._form_frstar(bodies) self._aux_eq = fraux + frstaraux self._fr = fr.col_join(fraux) self._frstar = frstar.col_join(frstaraux) return (self._fr, self._frstar) def _form_eoms(self): fr, frstar = self.kanes_equations(self.bodylist, self.forcelist) return fr + frstar def rhs(self, inv_method=None): """Returns the system's equations of motion in first order form. The output is the right hand side of:: x' = |q'| =: f(q, u, r, p, t) |u'| The right hand side is what is needed by most numerical ODE integrators. Parameters ========== inv_method : str The specific sympy inverse matrix calculation method to use. For a list of valid methods, see :meth:`~sympy.matrices.matrices.MatrixBase.inv` """ rhs = zeros(len(self.q) + len(self.u), 1) kdes = self.kindiffdict() for i, q_i in enumerate(self.q): rhs[i] = kdes[q_i.diff()] if inv_method is None: rhs[len(self.q):, 0] = self.mass_matrix.LUsolve(self.forcing) else: rhs[len(self.q):, 0] = (self.mass_matrix.inv(inv_method, try_block_diag=True) * self.forcing) return rhs def kindiffdict(self): """Returns a dictionary mapping q' to u.""" if not self._qdot_u_map: raise AttributeError('Create an instance of KanesMethod with ' 'kinematic differential equations to use this method.') return self._qdot_u_map @property def auxiliary_eqs(self): """A matrix containing the auxiliary equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') if not self._uaux: raise ValueError('No auxiliary speeds have been declared.') return self._aux_eq @property def mass_matrix_kin(self): r"""The kinematic "mass matrix" $\mathbf{k_{k\dot{q}}}$ of the system.""" return self._k_kqdot if self.explicit_kinematics else self._k_kqdot_implicit @property def forcing_kin(self): """The kinematic "forcing vector" of the system.""" if self.explicit_kinematics: return -(self._k_ku * Matrix(self.u) + self._f_k) else: return -(self._k_ku_implicit * Matrix(self.u) + self._f_k_implicit) @property def mass_matrix(self): """The mass matrix of the system.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') return Matrix([self._k_d, self._k_dnh]) @property def forcing(self): """The forcing vector of the system.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') return -Matrix([self._f_d, self._f_dnh]) @property def mass_matrix_full(self): """The mass matrix of the system, augmented by the kinematic differential equations in explicit or implicit form.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') o, n = len(self.u), len(self.q) return (self.mass_matrix_kin.row_join(zeros(n, o))).col_join( zeros(o, n).row_join(self.mass_matrix)) @property def forcing_full(self): """The forcing vector of the system, augmented by the kinematic differential equations in explicit or implicit form.""" return Matrix([self.forcing_kin, self.forcing]) @property def q(self): return self._q @property def u(self): return self._u @property def bodylist(self): return self._bodylist @property def forcelist(self): return self._forcelist @property def bodies(self): return self._bodylist @property def loads(self): return self._forcelist
908965704f1b605703d5bff6264d544968da19acca63122640034203f3c02b6c
from sympy.utilities import dict_merge from sympy.utilities.iterables import iterable from sympy.physics.vector import (Dyadic, Vector, ReferenceFrame, Point, dynamicsymbols) from sympy.physics.vector.printing import (vprint, vsprint, vpprint, vlatex, init_vprinting) from sympy.physics.mechanics.particle import Particle from sympy.physics.mechanics.rigidbody import RigidBody from sympy.simplify.simplify import simplify from sympy.core.backend import (Matrix, sympify, Mul, Derivative, sin, cos, tan, AppliedUndef, S) __all__ = ['inertia', 'inertia_of_point_mass', 'linear_momentum', 'angular_momentum', 'kinetic_energy', 'potential_energy', 'Lagrangian', 'mechanics_printing', 'mprint', 'msprint', 'mpprint', 'mlatex', 'msubs', 'find_dynamicsymbols'] # These are functions that we've moved and renamed during extracting the # basic vector calculus code from the mechanics packages. mprint = vprint msprint = vsprint mpprint = vpprint mlatex = vlatex def mechanics_printing(**kwargs): """ Initializes time derivative printing for all SymPy objects in mechanics module. """ init_vprinting(**kwargs) mechanics_printing.__doc__ = init_vprinting.__doc__ def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0): """Simple way to create inertia Dyadic object. Explanation =========== If you do not know what a Dyadic is, just treat this like the inertia tensor. Then, do the easy thing and define it in a body-fixed frame. Parameters ========== frame : ReferenceFrame The frame the inertia is defined in ixx : Sympifyable the xx element in the inertia dyadic iyy : Sympifyable the yy element in the inertia dyadic izz : Sympifyable the zz element in the inertia dyadic ixy : Sympifyable the xy element in the inertia dyadic iyz : Sympifyable the yz element in the inertia dyadic izx : Sympifyable the zx element in the inertia dyadic Examples ======== >>> from sympy.physics.mechanics import ReferenceFrame, inertia >>> N = ReferenceFrame('N') >>> inertia(N, 1, 2, 3) (N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z) """ if not isinstance(frame, ReferenceFrame): raise TypeError('Need to define the inertia in a frame') ixx = sympify(ixx) ixy = sympify(ixy) iyy = sympify(iyy) iyz = sympify(iyz) izx = sympify(izx) izz = sympify(izz) ol = ixx * (frame.x | frame.x) ol += ixy * (frame.x | frame.y) ol += izx * (frame.x | frame.z) ol += ixy * (frame.y | frame.x) ol += iyy * (frame.y | frame.y) ol += iyz * (frame.y | frame.z) ol += izx * (frame.z | frame.x) ol += iyz * (frame.z | frame.y) ol += izz * (frame.z | frame.z) return ol def inertia_of_point_mass(mass, pos_vec, frame): """Inertia dyadic of a point mass relative to point O. Parameters ========== mass : Sympifyable Mass of the point mass pos_vec : Vector Position from point O to point mass frame : ReferenceFrame Reference frame to express the dyadic in Examples ======== >>> from sympy import symbols >>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass >>> N = ReferenceFrame('N') >>> r, m = symbols('r m') >>> px = r * N.x >>> inertia_of_point_mass(m, px, N) m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z) """ return mass * (((frame.x | frame.x) + (frame.y | frame.y) + (frame.z | frame.z)) * (pos_vec & pos_vec) - (pos_vec | pos_vec)) def linear_momentum(frame, *body): """Linear momentum of the system. Explanation =========== This function returns the linear momentum of a system of Particle's and/or RigidBody's. The linear momentum of a system is equal to the vector sum of the linear momentum of its constituents. Consider a system, S, comprised of a rigid body, A, and a particle, P. The linear momentum of the system, L, is equal to the vector sum of the linear momentum of the particle, L1, and the linear momentum of the rigid body, L2, i.e. L = L1 + L2 Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose linear momentum is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, linear_momentum >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = Point('Ac') >>> Ac.set_vel(N, 25 * N.y) >>> I = outer(N.x, N.x) >>> A = RigidBody('A', Ac, N, 20, (I, Ac)) >>> linear_momentum(N, A, Pa) 10*N.x + 500*N.y """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please specify a valid ReferenceFrame') else: linear_momentum_sys = Vector(0) for e in body: if isinstance(e, (RigidBody, Particle)): linear_momentum_sys += e.linear_momentum(frame) else: raise TypeError('*body must have only Particle or RigidBody') return linear_momentum_sys def angular_momentum(point, frame, *body): """Angular momentum of a system. Explanation =========== This function returns the angular momentum of a system of Particle's and/or RigidBody's. The angular momentum of such a system is equal to the vector sum of the angular momentum of its constituents. Consider a system, S, comprised of a rigid body, A, and a particle, P. The angular momentum of the system, H, is equal to the vector sum of the angular momentum of the particle, H1, and the angular momentum of the rigid body, H2, i.e. H = H1 + H2 Parameters ========== point : Point The point about which angular momentum of the system is desired. frame : ReferenceFrame The frame in which angular momentum is desired. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose angular momentum is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, angular_momentum >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> angular_momentum(O, N, Pa, A) 10*N.z """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please enter a valid ReferenceFrame') if not isinstance(point, Point): raise TypeError('Please specify a valid Point') else: angular_momentum_sys = Vector(0) for e in body: if isinstance(e, (RigidBody, Particle)): angular_momentum_sys += e.angular_momentum(point, frame) else: raise TypeError('*body must have only Particle or RigidBody') return angular_momentum_sys def kinetic_energy(frame, *body): """Kinetic energy of a multibody system. Explanation =========== This function returns the kinetic energy of a system of Particle's and/or RigidBody's. The kinetic energy of such a system is equal to the sum of the kinetic energies of its constituents. Consider a system, S, comprising a rigid body, A, and a particle, P. The kinetic energy of the system, T, is equal to the vector sum of the kinetic energy of the particle, T1, and the kinetic energy of the rigid body, T2, i.e. T = T1 + T2 Kinetic energy is a scalar. Parameters ========== frame : ReferenceFrame The frame in which the velocity or angular velocity of the body is defined. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose kinetic energy is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, kinetic_energy >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> kinetic_energy(N, Pa, A) 350 """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please enter a valid ReferenceFrame') ke_sys = S.Zero for e in body: if isinstance(e, (RigidBody, Particle)): ke_sys += e.kinetic_energy(frame) else: raise TypeError('*body must have only Particle or RigidBody') return ke_sys def potential_energy(*body): """Potential energy of a multibody system. Explanation =========== This function returns the potential energy of a system of Particle's and/or RigidBody's. The potential energy of such a system is equal to the sum of the potential energy of its constituents. Consider a system, S, comprising a rigid body, A, and a particle, P. The potential energy of the system, V, is equal to the vector sum of the potential energy of the particle, V1, and the potential energy of the rigid body, V2, i.e. V = V1 + V2 Potential energy is a scalar. Parameters ========== body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose potential energy is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, potential_energy >>> from sympy import symbols >>> M, m, g, h = symbols('M m g h') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> Pa = Particle('Pa', P, m) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> a = ReferenceFrame('a') >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, M, (I, Ac)) >>> Pa.potential_energy = m * g * h >>> A.potential_energy = M * g * h >>> potential_energy(Pa, A) M*g*h + g*h*m """ pe_sys = S.Zero for e in body: if isinstance(e, (RigidBody, Particle)): pe_sys += e.potential_energy else: raise TypeError('*body must have only Particle or RigidBody') return pe_sys def gravity(acceleration, *bodies): """ Returns a list of gravity forces given the acceleration due to gravity and any number of particles or rigidbodies. Example ======= >>> from sympy.physics.mechanics import ReferenceFrame, Point, Particle, outer, RigidBody >>> from sympy.physics.mechanics.functions import gravity >>> from sympy import symbols >>> N = ReferenceFrame('N') >>> m, M, g = symbols('m M g') >>> F1, F2 = symbols('F1 F2') >>> po = Point('po') >>> pa = Particle('pa', po, m) >>> A = ReferenceFrame('A') >>> P = Point('P') >>> I = outer(A.x, A.x) >>> B = RigidBody('B', P, A, M, (I, P)) >>> forceList = [(po, F1), (P, F2)] >>> forceList.extend(gravity(g*N.y, pa, B)) >>> forceList [(po, F1), (P, F2), (po, g*m*N.y), (P, M*g*N.y)] """ gravity_force = [] if not bodies: raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.") for e in bodies: point = getattr(e, 'masscenter', None) if point is None: point = e.point gravity_force.append((point, e.mass*acceleration)) return gravity_force def center_of_mass(point, *bodies): """ Returns the position vector from the given point to the center of mass of the given bodies(particles or rigidbodies). Example ======= >>> from sympy import symbols, S >>> from sympy.physics.vector import Point >>> from sympy.physics.mechanics import Particle, ReferenceFrame, RigidBody, outer >>> from sympy.physics.mechanics.functions import center_of_mass >>> a = ReferenceFrame('a') >>> m = symbols('m', real=True) >>> p1 = Particle('p1', Point('p1_pt'), S(1)) >>> p2 = Particle('p2', Point('p2_pt'), S(2)) >>> p3 = Particle('p3', Point('p3_pt'), S(3)) >>> p4 = Particle('p4', Point('p4_pt'), m) >>> b_f = ReferenceFrame('b_f') >>> b_cm = Point('b_cm') >>> mb = symbols('mb') >>> b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm)) >>> p2.point.set_pos(p1.point, a.x) >>> p3.point.set_pos(p1.point, a.x + a.y) >>> p4.point.set_pos(p1.point, a.y) >>> b.masscenter.set_pos(p1.point, a.y + a.z) >>> point_o=Point('o') >>> point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b)) >>> expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z >>> point_o.pos_from(p1.point) 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z """ if not bodies: raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.") total_mass = 0 vec = Vector(0) for i in bodies: total_mass += i.mass masscenter = getattr(i, 'masscenter', None) if masscenter is None: masscenter = i.point vec += i.mass*masscenter.pos_from(point) return vec/total_mass def Lagrangian(frame, *body): """Lagrangian of a multibody system. Explanation =========== This function returns the Lagrangian of a system of Particle's and/or RigidBody's. The Lagrangian of such a system is equal to the difference between the kinetic energies and potential energies of its constituents. If T and V are the kinetic and potential energies of a system then it's Lagrangian, L, is defined as L = T - V The Lagrangian is a scalar. Parameters ========== frame : ReferenceFrame The frame in which the velocity or angular velocity of the body is defined to determine the kinetic energy. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose Lagrangian is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, Lagrangian >>> from sympy import symbols >>> M, m, g, h = symbols('M m g h') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> Pa.potential_energy = m * g * h >>> A.potential_energy = M * g * h >>> Lagrangian(N, Pa, A) -M*g*h - g*h*m + 350 """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please supply a valid ReferenceFrame') for e in body: if not isinstance(e, (RigidBody, Particle)): raise TypeError('*body must have only Particle or RigidBody') return kinetic_energy(frame, *body) - potential_energy(*body) def find_dynamicsymbols(expression, exclude=None, reference_frame=None): """Find all dynamicsymbols in expression. Explanation =========== If the optional ``exclude`` kwarg is used, only dynamicsymbols not in the iterable ``exclude`` are returned. If we intend to apply this function on a vector, the optional ``reference_frame`` is also used to inform about the corresponding frame with respect to which the dynamic symbols of the given vector is to be determined. Parameters ========== expression : SymPy expression exclude : iterable of dynamicsymbols, optional reference_frame : ReferenceFrame, optional The frame with respect to which the dynamic symbols of the given vector is to be determined. Examples ======== >>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols >>> from sympy.physics.mechanics import ReferenceFrame >>> x, y = dynamicsymbols('x, y') >>> expr = x + x.diff()*y >>> find_dynamicsymbols(expr) {x(t), y(t), Derivative(x(t), t)} >>> find_dynamicsymbols(expr, exclude=[x, y]) {Derivative(x(t), t)} >>> a, b, c = dynamicsymbols('a, b, c') >>> A = ReferenceFrame('A') >>> v = a * A.x + b * A.y + c * A.z >>> find_dynamicsymbols(v, reference_frame=A) {a(t), b(t), c(t)} """ t_set = {dynamicsymbols._t} if exclude: if iterable(exclude): exclude_set = set(exclude) else: raise TypeError("exclude kwarg must be iterable") else: exclude_set = set() if isinstance(expression, Vector): if reference_frame is None: raise ValueError("You must provide reference_frame when passing a " "vector expression, got %s." % reference_frame) else: expression = expression.to_matrix(reference_frame) return {i for i in expression.atoms(AppliedUndef, Derivative) if i.free_symbols == t_set} - exclude_set def msubs(expr, *sub_dicts, smart=False, **kwargs): """A custom subs for use on expressions derived in physics.mechanics. Traverses the expression tree once, performing the subs found in sub_dicts. Terms inside ``Derivative`` expressions are ignored: Examples ======== >>> from sympy.physics.mechanics import dynamicsymbols, msubs >>> x = dynamicsymbols('x') >>> msubs(x.diff() + x, {x: 1}) Derivative(x(t), t) + 1 Note that sub_dicts can be a single dictionary, or several dictionaries: >>> x, y, z = dynamicsymbols('x, y, z') >>> sub1 = {x: 1, y: 2} >>> sub2 = {z: 3, x.diff(): 4} >>> msubs(x.diff() + x + y + z, sub1, sub2) 10 If smart=True (default False), also checks for conditions that may result in ``nan``, but if simplified would yield a valid expression. For example: >>> from sympy import sin, tan >>> (sin(x)/tan(x)).subs(x, 0) nan >>> msubs(sin(x)/tan(x), {x: 0}, smart=True) 1 It does this by first replacing all ``tan`` with ``sin/cos``. Then each node is traversed. If the node is a fraction, subs is first evaluated on the denominator. If this results in 0, simplification of the entire fraction is attempted. Using this selective simplification, only subexpressions that result in 1/0 are targeted, resulting in faster performance. """ sub_dict = dict_merge(*sub_dicts) if smart: func = _smart_subs elif hasattr(expr, 'msubs'): return expr.msubs(sub_dict) else: func = lambda expr, sub_dict: _crawl(expr, _sub_func, sub_dict) if isinstance(expr, (Matrix, Vector, Dyadic)): return expr.applyfunc(lambda x: func(x, sub_dict)) else: return func(expr, sub_dict) def _crawl(expr, func, *args, **kwargs): """Crawl the expression tree, and apply func to every node.""" val = func(expr, *args, **kwargs) if val is not None: return val new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args) return expr.func(*new_args) def _sub_func(expr, sub_dict): """Perform direct matching substitution, ignoring derivatives.""" if expr in sub_dict: return sub_dict[expr] elif not expr.args or expr.is_Derivative: return expr def _tan_repl_func(expr): """Replace tan with sin/cos.""" if isinstance(expr, tan): return sin(*expr.args) / cos(*expr.args) elif not expr.args or expr.is_Derivative: return expr def _smart_subs(expr, sub_dict): """Performs subs, checking for conditions that may result in `nan` or `oo`, and attempts to simplify them out. The expression tree is traversed twice, and the following steps are performed on each expression node: - First traverse: Replace all `tan` with `sin/cos`. - Second traverse: If node is a fraction, check if the denominator evaluates to 0. If so, attempt to simplify it out. Then if node is in sub_dict, sub in the corresponding value. """ expr = _crawl(expr, _tan_repl_func) def _recurser(expr, sub_dict): # Decompose the expression into num, den num, den = _fraction_decomp(expr) if den != 1: # If there is a non trivial denominator, we need to handle it denom_subbed = _recurser(den, sub_dict) if denom_subbed.evalf() == 0: # If denom is 0 after this, attempt to simplify the bad expr expr = simplify(expr) else: # Expression won't result in nan, find numerator num_subbed = _recurser(num, sub_dict) return num_subbed / denom_subbed # We have to crawl the tree manually, because `expr` may have been # modified in the simplify step. First, perform subs as normal: val = _sub_func(expr, sub_dict) if val is not None: return val new_args = (_recurser(arg, sub_dict) for arg in expr.args) return expr.func(*new_args) return _recurser(expr, sub_dict) def _fraction_decomp(expr): """Return num, den such that expr = num/den.""" if not isinstance(expr, Mul): return expr, 1 num = [] den = [] for a in expr.args: if a.is_Pow and a.args[1] < 0: den.append(1 / a) else: num.append(a) if not den: return expr, 1 num = Mul(*num) den = Mul(*den) return num, den def _f_list_parser(fl, ref_frame): """Parses the provided forcelist composed of items of the form (obj, force). Returns a tuple containing: vel_list: The velocity (ang_vel for Frames, vel for Points) in the provided reference frame. f_list: The forces. Used internally in the KanesMethod and LagrangesMethod classes. """ def flist_iter(): for pair in fl: obj, force = pair if isinstance(obj, ReferenceFrame): yield obj.ang_vel_in(ref_frame), force elif isinstance(obj, Point): yield obj.vel(ref_frame), force else: raise TypeError('First entry in each forcelist pair must ' 'be a point or frame.') if not fl: vel_list, f_list = (), () else: unzip = lambda l: list(zip(*l)) if l[0] else [(), ()] vel_list, f_list = unzip(list(flist_iter())) return vel_list, f_list def _validate_coordinates(coordinates=None, speeds=None, check_duplicates=True, is_dynamicsymbols=True): # Convert input to iterables if coordinates is None: coordinates = [] elif not iterable(coordinates): coordinates = [coordinates] if speeds is None: speeds = [] elif not iterable(speeds): speeds = [speeds] if check_duplicates: # Check for duplicates if len(coordinates) != len(set(coordinates)): raise ValueError('Duplicate generalized coordinates found, all ' 'generalized coordinates should be unique.') if len(speeds) != len(set(speeds)): raise ValueError('Duplicate generalized speeds found, all ' 'generalized speeds should be unique.') if is_dynamicsymbols: # Check whether all coordinates are dynamicsymbols for coordinate in coordinates: if not isinstance(coordinate, (AppliedUndef, Derivative)): raise ValueError(f'Generalized coordinate "{coordinate}" is not' f' a dynamicsymbol.') for speed in speeds: if not isinstance(speed, (AppliedUndef, Derivative)): raise ValueError(f'Generalized speed "{speed}" is not a ' f'dynamicsymbol.')
304c47c72971eb12a98ce49d185e8c18280fbf93ee9b33b1ff08587871a84eaa
# coding=utf-8 from abc import ABC, abstractmethod from sympy.core.backend import pi, AppliedUndef, Derivative, Matrix from sympy.physics.mechanics.body import Body from sympy.physics.mechanics.functions import _validate_coordinates from sympy.physics.vector import (Vector, dynamicsymbols, cross, Point, ReferenceFrame) from sympy.utilities.iterables import iterable from sympy.utilities.exceptions import sympy_deprecation_warning __all__ = ['Joint', 'PinJoint', 'PrismaticJoint', 'CylindricalJoint', 'PlanarJoint', 'SphericalJoint', 'WeldJoint'] class Joint(ABC): """Abstract base class for all specific joints. Explanation =========== A joint subtracts degrees of freedom from a body. This is the base class for all specific joints and holds all common methods acting as an interface for all joints. Custom joint can be created by inheriting Joint class and defining all abstract functions. The abstract methods are: - ``_generate_coordinates`` - ``_generate_speeds`` - ``_orient_frames`` - ``_set_angular_velocity`` - ``_set_linear_velocity`` Parameters ========== name : string A unique name for the joint. parent : Body The parent body of joint. child : Body The child body of joint. coordinates : iterable of dynamicsymbols, optional Generalized coordinates of the joint. speeds : iterable of dynamicsymbols, optional Generalized speeds of joint. parent_point : Point or Vector, optional Attachment point where the joint is fixed to the parent body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the parent's mass center. child_point : Point or Vector, optional Attachment point where the joint is fixed to the child body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the child's mass center. parent_axis : Vector, optional .. deprecated:: 1.12 Axis fixed in the parent body which aligns with an axis fixed in the child body. The default is the x axis of parent's reference frame. For more information on this deprecation, see :ref:`deprecated-mechanics-joint-axis`. child_axis : Vector, optional .. deprecated:: 1.12 Axis fixed in the child body which aligns with an axis fixed in the parent body. The default is the x axis of child's reference frame. For more information on this deprecation, see :ref:`deprecated-mechanics-joint-axis`. parent_interframe : ReferenceFrame, optional Intermediate frame of the parent body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the parent's own frame. child_interframe : ReferenceFrame, optional Intermediate frame of the child body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the child's own frame. parent_joint_pos : Point or Vector, optional .. deprecated:: 1.12 This argument is replaced by parent_point and will be removed in a future version. See :ref:`deprecated-mechanics-joint-pos` for more information. child_joint_pos : Point or Vector, optional .. deprecated:: 1.12 This argument is replaced by child_point and will be removed in a future version. See :ref:`deprecated-mechanics-joint-pos` for more information. Attributes ========== name : string The joint's name. parent : Body The joint's parent body. child : Body The joint's child body. coordinates : Matrix Matrix of the joint's generalized coordinates. speeds : Matrix Matrix of the joint's generalized speeds. parent_point : Point Attachment point where the joint is fixed to the parent body. child_point : Point Attachment point where the joint is fixed to the child body. parent_axis : Vector The axis fixed in the parent frame that represents the joint. child_axis : Vector The axis fixed in the child frame that represents the joint. parent_interframe : ReferenceFrame Intermediate frame of the parent body with respect to which the joint transformation is formulated. child_interframe : ReferenceFrame Intermediate frame of the child body with respect to which the joint transformation is formulated. kdes : Matrix Kinematical differential equations of the joint. Notes ===== When providing a vector as the intermediate frame, a new intermediate frame is created which aligns its X axis with the provided vector. This is done with a single fixed rotation about a rotation axis. This rotation axis is determined by taking the cross product of the ``body.x`` axis with the provided vector. In the case where the provided vector is in the ``-body.x`` direction, the rotation is done about the ``body.y`` axis. """ def __init__(self, name, parent, child, coordinates=None, speeds=None, parent_point=None, child_point=None, parent_axis=None, child_axis=None, parent_interframe=None, child_interframe=None, parent_joint_pos=None, child_joint_pos=None): if not isinstance(name, str): raise TypeError('Supply a valid name.') self._name = name if not isinstance(parent, Body): raise TypeError('Parent must be an instance of Body.') self._parent = parent if not isinstance(child, Body): raise TypeError('Parent must be an instance of Body.') self._child = child self._coordinates = self._generate_coordinates(coordinates) self._speeds = self._generate_speeds(speeds) _validate_coordinates(self.coordinates, self.speeds) self._kdes = self._generate_kdes() self._parent_axis = self._axis(parent_axis, parent.frame) self._child_axis = self._axis(child_axis, child.frame) if parent_joint_pos is not None or child_joint_pos is not None: sympy_deprecation_warning( """ The parent_joint_pos and child_joint_pos arguments for the Joint classes are deprecated. Instead use parent_point and child_point. """, deprecated_since_version="1.12", active_deprecations_target="deprecated-mechanics-joint-pos", stacklevel=4 ) if parent_point is None: parent_point = parent_joint_pos if child_point is None: child_point = child_joint_pos self._parent_point = self._locate_joint_pos(parent, parent_point) self._child_point = self._locate_joint_pos(child, child_point) if parent_axis is not None or child_axis is not None: sympy_deprecation_warning( """ The parent_axis and child_axis arguments for the Joint classes are deprecated. Instead use parent_interframe, child_interframe. """, deprecated_since_version="1.12", active_deprecations_target="deprecated-mechanics-joint-axis", stacklevel=4 ) if parent_interframe is None: parent_interframe = parent_axis if child_interframe is None: child_interframe = child_axis self._parent_interframe = self._locate_joint_frame(parent, parent_interframe) self._child_interframe = self._locate_joint_frame(child, child_interframe) self._orient_frames() self._set_angular_velocity() self._set_linear_velocity() def __str__(self): return self.name def __repr__(self): return self.__str__() @property def name(self): """Name of the joint.""" return self._name @property def parent(self): """Parent body of Joint.""" return self._parent @property def child(self): """Child body of Joint.""" return self._child @property def coordinates(self): """Matrix of the joint's generalized coordinates.""" return self._coordinates @property def speeds(self): """Matrix of the joint's generalized speeds.""" return self._speeds @property def kdes(self): """Kinematical differential equations of the joint.""" return self._kdes @property def parent_axis(self): """The axis of parent frame.""" # Will be removed with `deprecated-mechanics-joint-axis` return self._parent_axis @property def child_axis(self): """The axis of child frame.""" # Will be removed with `deprecated-mechanics-joint-axis` return self._child_axis @property def parent_point(self): """Attachment point where the joint is fixed to the parent body.""" return self._parent_point @property def child_point(self): """Attachment point where the joint is fixed to the child body.""" return self._child_point @property def parent_interframe(self): return self._parent_interframe @property def child_interframe(self): return self._child_interframe @abstractmethod def _generate_coordinates(self, coordinates): """Generate Matrix of the joint's generalized coordinates.""" pass @abstractmethod def _generate_speeds(self, speeds): """Generate Matrix of the joint's generalized speeds.""" pass @abstractmethod def _orient_frames(self): """Orient frames as per the joint.""" pass @abstractmethod def _set_angular_velocity(self): """Set angular velocity of the joint related frames.""" pass @abstractmethod def _set_linear_velocity(self): """Set velocity of related points to the joint.""" pass @staticmethod def _to_vector(matrix, frame): """Converts a matrix to a vector in the given frame.""" return Vector([(matrix, frame)]) @staticmethod def _axis(ax, *frames): """Check whether an axis is fixed in one of the frames.""" if ax is None: ax = frames[0].x return ax if not isinstance(ax, Vector): raise TypeError("Axis must be a Vector.") ref_frame = None # Find a body in which the axis can be expressed for frame in frames: try: ax.to_matrix(frame) except ValueError: pass else: ref_frame = frame break if ref_frame is None: raise ValueError("Axis cannot be expressed in one of the body's " "frames.") if not ax.dt(ref_frame) == 0: raise ValueError('Axis cannot be time-varying when viewed from the ' 'associated body.') return ax @staticmethod def _choose_rotation_axis(frame, axis): components = axis.to_matrix(frame) x, y, z = components[0], components[1], components[2] if x != 0: if y != 0: if z != 0: return cross(axis, frame.x) if z != 0: return frame.y return frame.z else: if y != 0: return frame.x return frame.y @staticmethod def _create_aligned_interframe(frame, align_axis, frame_axis=None, frame_name=None): """ Returns an intermediate frame, where the ``frame_axis`` defined in ``frame`` is aligned with ``axis``. By default this means that the X axis will be aligned with ``axis``. Parameters ========== frame : Body or ReferenceFrame The body or reference frame with respect to which the intermediate frame is oriented. align_axis : Vector The vector with respect to which the intermediate frame will be aligned. frame_axis : Vector The vector of the frame which should get aligned with ``axis``. The default is the X axis of the frame. frame_name : string Name of the to be created intermediate frame. The default adds "_int_frame" to the name of ``frame``. Example ======= An intermediate frame, where the X axis of the parent becomes aligned with ``parent.y + parent.z`` can be created as follows: >>> from sympy.physics.mechanics.joint import Joint >>> from sympy.physics.mechanics import Body >>> parent = Body('parent') >>> parent_interframe = Joint._create_aligned_interframe( ... parent, parent.y + parent.z) >>> parent_interframe parent_int_frame >>> parent.dcm(parent_interframe) Matrix([ [ 0, -sqrt(2)/2, -sqrt(2)/2], [sqrt(2)/2, 1/2, -1/2], [sqrt(2)/2, -1/2, 1/2]]) >>> (parent.y + parent.z).express(parent_interframe) sqrt(2)*parent_int_frame.x Notes ===== The direction cosine matrix between the given frame and intermediate frame is formed using a simple rotation about an axis that is normal to both ``align_axis`` and ``frame_axis``. In general, the normal axis is formed by crossing the ``frame_axis`` with the ``align_axis``. The exception is if the axes are parallel with opposite directions, in which case the rotation vector is chosen using the rules in the following table with the vectors expressed in the given frame: .. list-table:: :header-rows: 1 * - ``align_axis`` - ``frame_axis`` - ``rotation_axis`` * - ``-x`` - ``x`` - ``z`` * - ``-y`` - ``y`` - ``x`` * - ``-z`` - ``z`` - ``y`` * - ``-x-y`` - ``x+y`` - ``z`` * - ``-y-z`` - ``y+z`` - ``x`` * - ``-x-z`` - ``x+z`` - ``y`` * - ``-x-y-z`` - ``x+y+z`` - ``(x+y+z) Γ— x`` """ if isinstance(frame, Body): frame = frame.frame if frame_axis is None: frame_axis = frame.x if frame_name is None: if frame.name[-6:] == '_frame': frame_name = f'{frame.name[:-6]}_int_frame' else: frame_name = f'{frame.name}_int_frame' angle = frame_axis.angle_between(align_axis) rotation_axis = cross(frame_axis, align_axis) if rotation_axis == Vector(0) and angle == 0: return frame if angle == pi: rotation_axis = Joint._choose_rotation_axis(frame, align_axis) int_frame = ReferenceFrame(frame_name) int_frame.orient_axis(frame, rotation_axis, angle) int_frame.set_ang_vel(frame, 0 * rotation_axis) return int_frame def _generate_kdes(self): """Generate kinematical differential equations.""" kdes = [] t = dynamicsymbols._t for i in range(len(self.coordinates)): kdes.append(-self.coordinates[i].diff(t) + self.speeds[i]) return Matrix(kdes) def _locate_joint_pos(self, body, joint_pos): """Returns the attachment point of a body.""" if joint_pos is None: return body.masscenter if not isinstance(joint_pos, (Point, Vector)): raise TypeError('Attachment point must be a Point or Vector.') if isinstance(joint_pos, Vector): point_name = f'{self.name}_{body.name}_joint' joint_pos = body.masscenter.locatenew(point_name, joint_pos) if not joint_pos.pos_from(body.masscenter).dt(body.frame) == 0: raise ValueError('Attachment point must be fixed to the associated ' 'body.') return joint_pos def _locate_joint_frame(self, body, interframe): """Returns the attachment frame of a body.""" if interframe is None: return body.frame if isinstance(interframe, Vector): interframe = Joint._create_aligned_interframe( body, interframe, frame_name=f'{self.name}_{body.name}_int_frame') elif not isinstance(interframe, ReferenceFrame): raise TypeError('Interframe must be a ReferenceFrame.') if not interframe.ang_vel_in(body.frame) == 0: raise ValueError(f'Interframe {interframe} is not fixed to body ' f'{body}.') body.masscenter.set_vel(interframe, 0) # Fixate interframe to body return interframe def _fill_coordinate_list(self, coordinates, n_coords, label='q', offset=0, number_single=False): """Helper method for _generate_coordinates and _generate_speeds. Parameters ========== coordinates : iterable Iterable of coordinates or speeds that have been provided. n_coords : Integer Number of coordinates that should be returned. label : String, optional Coordinate type either 'q' (coordinates) or 'u' (speeds). The Default is 'q'. offset : Integer Count offset when creating new dynamicsymbols. The default is 0. number_single : Boolean Boolean whether if n_coords == 1, number should still be used. The default is False. """ def create_symbol(number): if n_coords == 1 and not number_single: return dynamicsymbols(f'{label}_{self.name}') return dynamicsymbols(f'{label}{number}_{self.name}') name = 'generalized coordinate' if label == 'q' else 'generalized speed' generated_coordinates = [] if coordinates is None: coordinates = [] elif not iterable(coordinates): coordinates = [coordinates] if not (len(coordinates) == 0 or len(coordinates) == n_coords): raise ValueError(f'Expected {n_coords} {name}s, instead got ' f'{len(coordinates)} {name}s.') # Supports more iterables, also Matrix for i, coord in enumerate(coordinates): if coord is None: generated_coordinates.append(create_symbol(i + offset)) elif isinstance(coord, (AppliedUndef, Derivative)): generated_coordinates.append(coord) else: raise TypeError(f'The {name} {coord} should have been a ' f'dynamicsymbol.') for i in range(len(coordinates) + offset, n_coords + offset): generated_coordinates.append(create_symbol(i)) return Matrix(generated_coordinates) class PinJoint(Joint): """Pin (Revolute) Joint. .. image:: PinJoint.svg Explanation =========== A pin joint is defined such that the joint rotation axis is fixed in both the child and parent and the location of the joint is relative to the mass center of each body. The child rotates an angle, ΞΈ, from the parent about the rotation axis and has a simple angular speed, Ο‰, relative to the parent. The direction cosine matrix between the child interframe and parent interframe is formed using a simple rotation about the joint axis. The page on the joints framework gives a more detailed explanation of the intermediate frames. Parameters ========== name : string A unique name for the joint. parent : Body The parent body of joint. child : Body The child body of joint. coordinates : dynamicsymbol, optional Generalized coordinates of the joint. speeds : dynamicsymbol, optional Generalized speeds of joint. parent_point : Point or Vector, optional Attachment point where the joint is fixed to the parent body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the parent's mass center. child_point : Point or Vector, optional Attachment point where the joint is fixed to the child body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the child's mass center. parent_axis : Vector, optional .. deprecated:: 1.12 Axis fixed in the parent body which aligns with an axis fixed in the child body. The default is the x axis of parent's reference frame. For more information on this deprecation, see :ref:`deprecated-mechanics-joint-axis`. child_axis : Vector, optional .. deprecated:: 1.12 Axis fixed in the child body which aligns with an axis fixed in the parent body. The default is the x axis of child's reference frame. For more information on this deprecation, see :ref:`deprecated-mechanics-joint-axis`. parent_interframe : ReferenceFrame, optional Intermediate frame of the parent body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the parent's own frame. child_interframe : ReferenceFrame, optional Intermediate frame of the child body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the child's own frame. joint_axis : Vector The axis about which the rotation occurs. Note that the components of this axis are the same in the parent_interframe and child_interframe. parent_joint_pos : Point or Vector, optional .. deprecated:: 1.12 This argument is replaced by parent_point and will be removed in a future version. See :ref:`deprecated-mechanics-joint-pos` for more information. child_joint_pos : Point or Vector, optional .. deprecated:: 1.12 This argument is replaced by child_point and will be removed in a future version. See :ref:`deprecated-mechanics-joint-pos` for more information. Attributes ========== name : string The joint's name. parent : Body The joint's parent body. child : Body The joint's child body. coordinates : Matrix Matrix of the joint's generalized coordinates. The default value is ``dynamicsymbols(f'q_{joint.name}')``. speeds : Matrix Matrix of the joint's generalized speeds. The default value is ``dynamicsymbols(f'u_{joint.name}')``. parent_point : Point Attachment point where the joint is fixed to the parent body. child_point : Point Attachment point where the joint is fixed to the child body. parent_axis : Vector The axis fixed in the parent frame that represents the joint. child_axis : Vector The axis fixed in the child frame that represents the joint. parent_interframe : ReferenceFrame Intermediate frame of the parent body with respect to which the joint transformation is formulated. child_interframe : ReferenceFrame Intermediate frame of the child body with respect to which the joint transformation is formulated. joint_axis : Vector The axis about which the rotation occurs. Note that the components of this axis are the same in the parent_interframe and child_interframe. kdes : Matrix Kinematical differential equations of the joint. Examples ========= A single pin joint is created from two bodies and has the following basic attributes: >>> from sympy.physics.mechanics import Body, PinJoint >>> parent = Body('P') >>> parent P >>> child = Body('C') >>> child C >>> joint = PinJoint('PC', parent, child) >>> joint PinJoint: PC parent: P child: C >>> joint.name 'PC' >>> joint.parent P >>> joint.child C >>> joint.parent_point P_masscenter >>> joint.child_point C_masscenter >>> joint.parent_axis P_frame.x >>> joint.child_axis C_frame.x >>> joint.coordinates Matrix([[q_PC(t)]]) >>> joint.speeds Matrix([[u_PC(t)]]) >>> joint.child.frame.ang_vel_in(joint.parent.frame) u_PC(t)*P_frame.x >>> joint.child.frame.dcm(joint.parent.frame) Matrix([ [1, 0, 0], [0, cos(q_PC(t)), sin(q_PC(t))], [0, -sin(q_PC(t)), cos(q_PC(t))]]) >>> joint.child_point.pos_from(joint.parent_point) 0 To further demonstrate the use of the pin joint, the kinematics of simple double pendulum that rotates about the Z axis of each connected body can be created as follows. >>> from sympy import symbols, trigsimp >>> from sympy.physics.mechanics import Body, PinJoint >>> l1, l2 = symbols('l1 l2') First create bodies to represent the fixed ceiling and one to represent each pendulum bob. >>> ceiling = Body('C') >>> upper_bob = Body('U') >>> lower_bob = Body('L') The first joint will connect the upper bob to the ceiling by a distance of ``l1`` and the joint axis will be about the Z axis for each body. >>> ceiling_joint = PinJoint('P1', ceiling, upper_bob, ... child_point=-l1*upper_bob.frame.x, ... joint_axis=ceiling.frame.z) The second joint will connect the lower bob to the upper bob by a distance of ``l2`` and the joint axis will also be about the Z axis for each body. >>> pendulum_joint = PinJoint('P2', upper_bob, lower_bob, ... child_point=-l2*lower_bob.frame.x, ... joint_axis=upper_bob.frame.z) Once the joints are established the kinematics of the connected bodies can be accessed. First the direction cosine matrices of pendulum link relative to the ceiling are found: >>> upper_bob.frame.dcm(ceiling.frame) Matrix([ [ cos(q_P1(t)), sin(q_P1(t)), 0], [-sin(q_P1(t)), cos(q_P1(t)), 0], [ 0, 0, 1]]) >>> trigsimp(lower_bob.frame.dcm(ceiling.frame)) Matrix([ [ cos(q_P1(t) + q_P2(t)), sin(q_P1(t) + q_P2(t)), 0], [-sin(q_P1(t) + q_P2(t)), cos(q_P1(t) + q_P2(t)), 0], [ 0, 0, 1]]) The position of the lower bob's masscenter is found with: >>> lower_bob.masscenter.pos_from(ceiling.masscenter) l1*U_frame.x + l2*L_frame.x The angular velocities of the two pendulum links can be computed with respect to the ceiling. >>> upper_bob.frame.ang_vel_in(ceiling.frame) u_P1(t)*C_frame.z >>> lower_bob.frame.ang_vel_in(ceiling.frame) u_P1(t)*C_frame.z + u_P2(t)*U_frame.z And finally, the linear velocities of the two pendulum bobs can be computed with respect to the ceiling. >>> upper_bob.masscenter.vel(ceiling.frame) l1*u_P1(t)*U_frame.y >>> lower_bob.masscenter.vel(ceiling.frame) l1*u_P1(t)*U_frame.y + l2*(u_P1(t) + u_P2(t))*L_frame.y """ def __init__(self, name, parent, child, coordinates=None, speeds=None, parent_point=None, child_point=None, parent_axis=None, child_axis=None, parent_interframe=None, child_interframe=None, joint_axis=None, parent_joint_pos=None, child_joint_pos=None): self._joint_axis = joint_axis super().__init__(name, parent, child, coordinates, speeds, parent_point, child_point, parent_axis, child_axis, parent_interframe, child_interframe, parent_joint_pos, child_joint_pos) def __str__(self): return (f'PinJoint: {self.name} parent: {self.parent} ' f'child: {self.child}') @property def joint_axis(self): """Axis about which the child rotates with respect to the parent.""" return self._joint_axis def _generate_coordinates(self, coordinate): return self._fill_coordinate_list(coordinate, 1, 'q') def _generate_speeds(self, speed): return self._fill_coordinate_list(speed, 1, 'u') def _orient_frames(self): self._joint_axis = self._axis(self.joint_axis, self.parent_interframe) self.child_interframe.orient_axis( self.parent_interframe, self.joint_axis, self.coordinates[0]) def _set_angular_velocity(self): self.child_interframe.set_ang_vel(self.parent_interframe, self.speeds[ 0] * self.joint_axis.normalize()) def _set_linear_velocity(self): self.child_point.set_pos(self.parent_point, 0) self.parent_point.set_vel(self.parent.frame, 0) self.child_point.set_vel(self.child.frame, 0) self.child.masscenter.v2pt_theory(self.parent_point, self.parent.frame, self.child.frame) class PrismaticJoint(Joint): """Prismatic (Sliding) Joint. .. image:: PrismaticJoint.svg Explanation =========== It is defined such that the child body translates with respect to the parent body along the body-fixed joint axis. The location of the joint is defined by two points, one in each body, which coincide when the generalized coordinate is zero. The direction cosine matrix between the parent_interframe and child_interframe is the identity matrix. Therefore, the direction cosine matrix between the parent and child frames is fully defined by the definition of the intermediate frames. The page on the joints framework gives a more detailed explanation of the intermediate frames. Parameters ========== name : string A unique name for the joint. parent : Body The parent body of joint. child : Body The child body of joint. coordinates : dynamicsymbol, optional Generalized coordinates of the joint. The default value is ``dynamicsymbols(f'q_{joint.name}')``. speeds : dynamicsymbol, optional Generalized speeds of joint. The default value is ``dynamicsymbols(f'u_{joint.name}')``. parent_point : Point or Vector, optional Attachment point where the joint is fixed to the parent body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the parent's mass center. child_point : Point or Vector, optional Attachment point where the joint is fixed to the child body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the child's mass center. parent_axis : Vector, optional .. deprecated:: 1.12 Axis fixed in the parent body which aligns with an axis fixed in the child body. The default is the x axis of parent's reference frame. For more information on this deprecation, see :ref:`deprecated-mechanics-joint-axis`. child_axis : Vector, optional .. deprecated:: 1.12 Axis fixed in the child body which aligns with an axis fixed in the parent body. The default is the x axis of child's reference frame. For more information on this deprecation, see :ref:`deprecated-mechanics-joint-axis`. parent_interframe : ReferenceFrame, optional Intermediate frame of the parent body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the parent's own frame. child_interframe : ReferenceFrame, optional Intermediate frame of the child body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the child's own frame. joint_axis : Vector The axis along which the translation occurs. Note that the components of this axis are the same in the parent_interframe and child_interframe. parent_joint_pos : Point or Vector, optional .. deprecated:: 1.12 This argument is replaced by parent_point and will be removed in a future version. See :ref:`deprecated-mechanics-joint-pos` for more information. child_joint_pos : Point or Vector, optional .. deprecated:: 1.12 This argument is replaced by child_point and will be removed in a future version. See :ref:`deprecated-mechanics-joint-pos` for more information. Attributes ========== name : string The joint's name. parent : Body The joint's parent body. child : Body The joint's child body. coordinates : Matrix Matrix of the joint's generalized coordinates. speeds : Matrix Matrix of the joint's generalized speeds. parent_point : Point Attachment point where the joint is fixed to the parent body. child_point : Point Attachment point where the joint is fixed to the child body. parent_axis : Vector The axis fixed in the parent frame that represents the joint. child_axis : Vector The axis fixed in the child frame that represents the joint. parent_interframe : ReferenceFrame Intermediate frame of the parent body with respect to which the joint transformation is formulated. child_interframe : ReferenceFrame Intermediate frame of the child body with respect to which the joint transformation is formulated. kdes : Matrix Kinematical differential equations of the joint. Examples ========= A single prismatic joint is created from two bodies and has the following basic attributes: >>> from sympy.physics.mechanics import Body, PrismaticJoint >>> parent = Body('P') >>> parent P >>> child = Body('C') >>> child C >>> joint = PrismaticJoint('PC', parent, child) >>> joint PrismaticJoint: PC parent: P child: C >>> joint.name 'PC' >>> joint.parent P >>> joint.child C >>> joint.parent_point P_masscenter >>> joint.child_point C_masscenter >>> joint.parent_axis P_frame.x >>> joint.child_axis C_frame.x >>> joint.coordinates Matrix([[q_PC(t)]]) >>> joint.speeds Matrix([[u_PC(t)]]) >>> joint.child.frame.ang_vel_in(joint.parent.frame) 0 >>> joint.child.frame.dcm(joint.parent.frame) Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> joint.child_point.pos_from(joint.parent_point) q_PC(t)*P_frame.x To further demonstrate the use of the prismatic joint, the kinematics of two masses sliding, one moving relative to a fixed body and the other relative to the moving body. about the X axis of each connected body can be created as follows. >>> from sympy.physics.mechanics import PrismaticJoint, Body First create bodies to represent the fixed ceiling and one to represent a particle. >>> wall = Body('W') >>> Part1 = Body('P1') >>> Part2 = Body('P2') The first joint will connect the particle to the ceiling and the joint axis will be about the X axis for each body. >>> J1 = PrismaticJoint('J1', wall, Part1) The second joint will connect the second particle to the first particle and the joint axis will also be about the X axis for each body. >>> J2 = PrismaticJoint('J2', Part1, Part2) Once the joint is established the kinematics of the connected bodies can be accessed. First the direction cosine matrices of Part relative to the ceiling are found: >>> Part1.dcm(wall) Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> Part2.dcm(wall) Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) The position of the particles' masscenter is found with: >>> Part1.masscenter.pos_from(wall.masscenter) q_J1(t)*W_frame.x >>> Part2.masscenter.pos_from(wall.masscenter) q_J1(t)*W_frame.x + q_J2(t)*P1_frame.x The angular velocities of the two particle links can be computed with respect to the ceiling. >>> Part1.ang_vel_in(wall) 0 >>> Part2.ang_vel_in(wall) 0 And finally, the linear velocities of the two particles can be computed with respect to the ceiling. >>> Part1.masscenter_vel(wall) u_J1(t)*W_frame.x >>> Part2.masscenter.vel(wall.frame) u_J1(t)*W_frame.x + Derivative(q_J2(t), t)*P1_frame.x """ def __init__(self, name, parent, child, coordinates=None, speeds=None, parent_point=None, child_point=None, parent_axis=None, child_axis=None, parent_interframe=None, child_interframe=None, joint_axis=None, parent_joint_pos=None, child_joint_pos=None): self._joint_axis = joint_axis super().__init__(name, parent, child, coordinates, speeds, parent_point, child_point, parent_axis, child_axis, parent_interframe, child_interframe, parent_joint_pos, child_joint_pos) def __str__(self): return (f'PrismaticJoint: {self.name} parent: {self.parent} ' f'child: {self.child}') @property def joint_axis(self): """Axis along which the child translates with respect to the parent.""" return self._joint_axis def _generate_coordinates(self, coordinate): return self._fill_coordinate_list(coordinate, 1, 'q') def _generate_speeds(self, speed): return self._fill_coordinate_list(speed, 1, 'u') def _orient_frames(self): self._joint_axis = self._axis(self.joint_axis, self.parent_interframe) self.child_interframe.orient_axis( self.parent_interframe, self.joint_axis, 0) def _set_angular_velocity(self): self.child_interframe.set_ang_vel(self.parent_interframe, 0) def _set_linear_velocity(self): axis = self.joint_axis.normalize() self.child_point.set_pos(self.parent_point, self.coordinates[0] * axis) self.parent_point.set_vel(self.parent.frame, 0) self.child_point.set_vel(self.child.frame, 0) self.child_point.set_vel(self.parent.frame, self.speeds[0] * axis) self.child.masscenter.set_vel(self.parent.frame, self.speeds[0] * axis) class CylindricalJoint(Joint): """Cylindrical Joint. .. image:: CylindricalJoint.svg :align: center :width: 600 Explanation =========== A cylindrical joint is defined such that the child body both rotates about and translates along the body-fixed joint axis with respect to the parent body. The joint axis is both the rotation axis and translation axis. The location of the joint is defined by two points, one in each body, which coincide when the generalized coordinate corresponding to the translation is zero. The direction cosine matrix between the child interframe and parent interframe is formed using a simple rotation about the joint axis. The page on the joints framework gives a more detailed explanation of the intermediate frames. Parameters ========== name : string A unique name for the joint. parent : Body The parent body of joint. child : Body The child body of joint. rotation_coordinate : dynamicsymbol, optional Generalized coordinate corresponding to the rotation angle. The default value is ``dynamicsymbols(f'q0_{joint.name}')``. translation_coordinate : dynamicsymbol, optional Generalized coordinate corresponding to the translation distance. The default value is ``dynamicsymbols(f'q1_{joint.name}')``. rotation_speed : dynamicsymbol, optional Generalized speed corresponding to the angular velocity. The default value is ``dynamicsymbols(f'u0_{joint.name}')``. translation_speed : dynamicsymbol, optional Generalized speed corresponding to the translation velocity. The default value is ``dynamicsymbols(f'u1_{joint.name}')``. parent_point : Point or Vector, optional Attachment point where the joint is fixed to the parent body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the parent's mass center. child_point : Point or Vector, optional Attachment point where the joint is fixed to the child body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the child's mass center. parent_interframe : ReferenceFrame, optional Intermediate frame of the parent body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the parent's own frame. child_interframe : ReferenceFrame, optional Intermediate frame of the child body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the child's own frame. joint_axis : Vector, optional The rotation as well as translation axis. Note that the components of this axis are the same in the parent_interframe and child_interframe. Attributes ========== name : string The joint's name. parent : Body The joint's parent body. child : Body The joint's child body. rotation_coordinate : dynamicsymbol Generalized coordinate corresponding to the rotation angle. translation_coordinate : dynamicsymbol Generalized coordinate corresponding to the translation distance. rotation_speed : dynamicsymbol Generalized speed corresponding to the angular velocity. translation_speed : dynamicsymbol Generalized speed corresponding to the translation velocity. coordinates : Matrix Matrix of the joint's generalized coordinates. speeds : Matrix Matrix of the joint's generalized speeds. parent_point : Point Attachment point where the joint is fixed to the parent body. child_point : Point Attachment point where the joint is fixed to the child body. parent_interframe : ReferenceFrame Intermediate frame of the parent body with respect to which the joint transformation is formulated. child_interframe : ReferenceFrame Intermediate frame of the child body with respect to which the joint transformation is formulated. kdes : Matrix Kinematical differential equations of the joint. joint_axis : Vector The axis of rotation and translation. Examples ========= A single cylindrical joint is created between two bodies and has the following basic attributes: >>> from sympy.physics.mechanics import Body, CylindricalJoint >>> parent = Body('P') >>> parent P >>> child = Body('C') >>> child C >>> joint = CylindricalJoint('PC', parent, child) >>> joint CylindricalJoint: PC parent: P child: C >>> joint.name 'PC' >>> joint.parent P >>> joint.child C >>> joint.parent_point P_masscenter >>> joint.child_point C_masscenter >>> joint.parent_axis P_frame.x >>> joint.child_axis C_frame.x >>> joint.coordinates Matrix([ [q0_PC(t)], [q1_PC(t)]]) >>> joint.speeds Matrix([ [u0_PC(t)], [u1_PC(t)]]) >>> joint.child.frame.ang_vel_in(joint.parent.frame) u0_PC(t)*P_frame.x >>> joint.child.frame.dcm(joint.parent.frame) Matrix([ [1, 0, 0], [0, cos(q0_PC(t)), sin(q0_PC(t))], [0, -sin(q0_PC(t)), cos(q0_PC(t))]]) >>> joint.child_point.pos_from(joint.parent_point) q1_PC(t)*P_frame.x >>> child.masscenter.vel(parent.frame) u1_PC(t)*P_frame.x To further demonstrate the use of the cylindrical joint, the kinematics of two cylindral joints perpendicular to each other can be created as follows. >>> from sympy import symbols >>> from sympy.physics.mechanics import Body, CylindricalJoint >>> r, l, w = symbols('r l w') First create bodies to represent the fixed floor with a fixed pole on it. The second body represents a freely moving tube around that pole. The third body represents a solid flag freely translating along and rotating around the Y axis of the tube. >>> floor = Body('floor') >>> tube = Body('tube') >>> flag = Body('flag') The first joint will connect the first tube to the floor with it translating along and rotating around the Z axis of both bodies. >>> floor_joint = CylindricalJoint('C1', floor, tube, joint_axis=floor.z) The second joint will connect the tube perpendicular to the flag along the Y axis of both the tube and the flag, with the joint located at a distance ``r`` from the tube's center of mass and a combination of the distances ``l`` and ``w`` from the flag's center of mass. >>> flag_joint = CylindricalJoint('C2', tube, flag, ... parent_point=r * tube.y, ... child_point=-w * flag.y + l * flag.z, ... joint_axis=tube.y) Once the joints are established the kinematics of the connected bodies can be accessed. First the direction cosine matrices of both the body and the flag relative to the floor are found: >>> tube.dcm(floor) Matrix([ [ cos(q0_C1(t)), sin(q0_C1(t)), 0], [-sin(q0_C1(t)), cos(q0_C1(t)), 0], [ 0, 0, 1]]) >>> flag.dcm(floor) Matrix([ [cos(q0_C1(t))*cos(q0_C2(t)), sin(q0_C1(t))*cos(q0_C2(t)), -sin(q0_C2(t))], [ -sin(q0_C1(t)), cos(q0_C1(t)), 0], [sin(q0_C2(t))*cos(q0_C1(t)), sin(q0_C1(t))*sin(q0_C2(t)), cos(q0_C2(t))]]) The position of the flag's center of mass is found with: >>> flag.masscenter.pos_from(floor.masscenter) q1_C1(t)*floor_frame.z + (r + q1_C2(t))*tube_frame.y + w*flag_frame.y - l*flag_frame.z The angular velocities of the two tubes can be computed with respect to the floor. >>> tube.ang_vel_in(floor) u0_C1(t)*floor_frame.z >>> flag.ang_vel_in(floor) u0_C1(t)*floor_frame.z + u0_C2(t)*tube_frame.y Finally, the linear velocities of the two tube centers of mass can be computed with respect to the floor, while expressed in the tube's frame. >>> tube.masscenter.vel(floor.frame).to_matrix(tube.frame) Matrix([ [ 0], [ 0], [u1_C1(t)]]) >>> flag.masscenter.vel(floor.frame).to_matrix(tube.frame).simplify() Matrix([ [-l*u0_C2(t)*cos(q0_C2(t)) - r*u0_C1(t) - w*u0_C1(t) - q1_C2(t)*u0_C1(t)], [ -l*u0_C1(t)*sin(q0_C2(t)) + Derivative(q1_C2(t), t)], [ l*u0_C2(t)*sin(q0_C2(t)) + u1_C1(t)]]) """ def __init__(self, name, parent, child, rotation_coordinate=None, translation_coordinate=None, rotation_speed=None, translation_speed=None, parent_point=None, child_point=None, parent_interframe=None, child_interframe=None, joint_axis=None): self._joint_axis = joint_axis coordinates = (rotation_coordinate, translation_coordinate) speeds = (rotation_speed, translation_speed) super().__init__(name, parent, child, coordinates, speeds, parent_point, child_point, parent_interframe=parent_interframe, child_interframe=child_interframe) def __str__(self): return (f'CylindricalJoint: {self.name} parent: {self.parent} ' f'child: {self.child}') @property def joint_axis(self): """Axis about and along which the rotation and translation occurs.""" return self._joint_axis @property def rotation_coordinate(self): """Generalized coordinate corresponding to the rotation angle.""" return self.coordinates[0] @property def translation_coordinate(self): """Generalized coordinate corresponding to the translation distance.""" return self.coordinates[1] @property def rotation_speed(self): """Generalized speed corresponding to the angular velocity.""" return self.speeds[0] @property def translation_speed(self): """Generalized speed corresponding to the translation velocity.""" return self.speeds[1] def _generate_coordinates(self, coordinates): return self._fill_coordinate_list(coordinates, 2, 'q') def _generate_speeds(self, speeds): return self._fill_coordinate_list(speeds, 2, 'u') def _orient_frames(self): self._joint_axis = self._axis(self.joint_axis, self.parent_interframe) self.child_interframe.orient_axis( self.parent_interframe, self.joint_axis, self.rotation_coordinate) def _set_angular_velocity(self): self.child_interframe.set_ang_vel( self.parent_interframe, self.rotation_speed * self.joint_axis.normalize()) def _set_linear_velocity(self): self.child_point.set_pos( self.parent_point, self.translation_coordinate * self.joint_axis.normalize()) self.parent_point.set_vel(self.parent.frame, 0) self.child_point.set_vel(self.child.frame, 0) self.child_point.set_vel( self.parent.frame, self.translation_speed * self.joint_axis.normalize()) self.child.masscenter.v2pt_theory(self.child_point, self.parent.frame, self.child_interframe) class PlanarJoint(Joint): """Planar Joint. .. image:: PlanarJoint.svg :align: center :width: 800 Explanation =========== A planar joint is defined such that the child body translates over a fixed plane of the parent body as well as rotate about the rotation axis, which is perpendicular to that plane. The origin of this plane is the ``parent_point`` and the plane is spanned by two nonparallel planar vectors. The location of the ``child_point`` is based on the planar vectors ($\\vec{v}_1$, $\\vec{v}_2$) and generalized coordinates ($q_1$, $q_2$), i.e. $\\vec{r} = q_1 \\hat{v}_1 + q_2 \\hat{v}_2$. The direction cosine matrix between the ``child_interframe`` and ``parent_interframe`` is formed using a simple rotation ($q_0$) about the rotation axis. In order to simplify the definition of the ``PlanarJoint``, the ``rotation_axis`` and ``planar_vectors`` are set to be the unit vectors of the ``parent_interframe`` according to the table below. This ensures that you can only define these vectors by creating a separate frame and supplying that as the interframe. If you however would only like to supply the normals of the plane with respect to the parent and child bodies, then you can also supply those to the ``parent_interframe`` and ``child_interframe`` arguments. An example of both of these cases is in the examples section below and the page on the joints framework provides a more detailed explanation of the intermediate frames. .. list-table:: * - ``rotation_axis`` - ``parent_interframe.x`` * - ``planar_vectors[0]`` - ``parent_interframe.y`` * - ``planar_vectors[1]`` - ``parent_interframe.z`` Parameters ========== name : string A unique name for the joint. parent : Body The parent body of joint. child : Body The child body of joint. rotation_coordinate : dynamicsymbol, optional Generalized coordinate corresponding to the rotation angle. The default value is ``dynamicsymbols(f'q0_{joint.name}')``. planar_coordinates : iterable of dynamicsymbols, optional Two generalized coordinates used for the planar translation. The default value is ``dynamicsymbols(f'q1_{joint.name} q2_{joint.name}')``. rotation_speed : dynamicsymbol, optional Generalized speed corresponding to the angular velocity. The default value is ``dynamicsymbols(f'u0_{joint.name}')``. planar_speeds : dynamicsymbols, optional Two generalized speeds used for the planar translation velocity. The default value is ``dynamicsymbols(f'u1_{joint.name} u2_{joint.name}')``. parent_point : Point or Vector, optional Attachment point where the joint is fixed to the parent body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the parent's mass center. child_point : Point or Vector, optional Attachment point where the joint is fixed to the child body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the child's mass center. parent_interframe : ReferenceFrame, optional Intermediate frame of the parent body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the parent's own frame. child_interframe : ReferenceFrame, optional Intermediate frame of the child body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the child's own frame. Attributes ========== name : string The joint's name. parent : Body The joint's parent body. child : Body The joint's child body. rotation_coordinate : dynamicsymbol Generalized coordinate corresponding to the rotation angle. planar_coordinates : Matrix Two generalized coordinates used for the planar translation. rotation_speed : dynamicsymbol Generalized speed corresponding to the angular velocity. planar_speeds : Matrix Two generalized speeds used for the planar translation velocity. coordinates : Matrix Matrix of the joint's generalized coordinates. speeds : Matrix Matrix of the joint's generalized speeds. parent_point : Point Attachment point where the joint is fixed to the parent body. child_point : Point Attachment point where the joint is fixed to the child body. parent_interframe : ReferenceFrame Intermediate frame of the parent body with respect to which the joint transformation is formulated. child_interframe : ReferenceFrame Intermediate frame of the child body with respect to which the joint transformation is formulated. kdes : Matrix Kinematical differential equations of the joint. rotation_axis : Vector The axis about which the rotation occurs. planar_vectors : list The vectors that describe the planar translation directions. Examples ========= A single planar joint is created between two bodies and has the following basic attributes: >>> from sympy.physics.mechanics import Body, PlanarJoint >>> parent = Body('P') >>> parent P >>> child = Body('C') >>> child C >>> joint = PlanarJoint('PC', parent, child) >>> joint PlanarJoint: PC parent: P child: C >>> joint.name 'PC' >>> joint.parent P >>> joint.child C >>> joint.parent_point P_masscenter >>> joint.child_point C_masscenter >>> joint.rotation_axis P_frame.x >>> joint.planar_vectors [P_frame.y, P_frame.z] >>> joint.rotation_coordinate q0_PC(t) >>> joint.planar_coordinates Matrix([ [q1_PC(t)], [q2_PC(t)]]) >>> joint.coordinates Matrix([ [q0_PC(t)], [q1_PC(t)], [q2_PC(t)]]) >>> joint.rotation_speed u0_PC(t) >>> joint.planar_speeds Matrix([ [u1_PC(t)], [u2_PC(t)]]) >>> joint.speeds Matrix([ [u0_PC(t)], [u1_PC(t)], [u2_PC(t)]]) >>> joint.child.frame.ang_vel_in(joint.parent.frame) u0_PC(t)*P_frame.x >>> joint.child.frame.dcm(joint.parent.frame) Matrix([ [1, 0, 0], [0, cos(q0_PC(t)), sin(q0_PC(t))], [0, -sin(q0_PC(t)), cos(q0_PC(t))]]) >>> joint.child_point.pos_from(joint.parent_point) q1_PC(t)*P_frame.y + q2_PC(t)*P_frame.z >>> child.masscenter.vel(parent.frame) u1_PC(t)*P_frame.y + u2_PC(t)*P_frame.z To further demonstrate the use of the planar joint, the kinematics of a block sliding on a slope, can be created as follows. >>> from sympy import symbols >>> from sympy.physics.mechanics import PlanarJoint, Body, ReferenceFrame >>> a, d, h = symbols('a d h') First create bodies to represent the slope and the block. >>> ground = Body('G') >>> block = Body('B') To define the slope you can either define the plane by specifying the ``planar_vectors`` or/and the ``rotation_axis``. However it is advisable to create a rotated intermediate frame, so that the ``parent_vectors`` and ``rotation_axis`` will be the unit vectors of this intermediate frame. >>> slope = ReferenceFrame('A') >>> slope.orient_axis(ground.frame, ground.y, a) The planar joint can be created using these bodies and intermediate frame. We can specify the origin of the slope to be ``d`` above the slope's center of mass and the block's center of mass to be a distance ``h`` above the slope's surface. Note that we can specify the normal of the plane using the rotation axis argument. >>> joint = PlanarJoint('PC', ground, block, parent_point=d * ground.x, ... child_point=-h * block.x, parent_interframe=slope) Once the joint is established the kinematics of the bodies can be accessed. First the ``rotation_axis``, which is normal to the plane and the ``plane_vectors``, can be found. >>> joint.rotation_axis A.x >>> joint.planar_vectors [A.y, A.z] The direction cosine matrix of the block with respect to the ground can be found with: >>> block.dcm(ground) Matrix([ [ cos(a), 0, -sin(a)], [sin(a)*sin(q0_PC(t)), cos(q0_PC(t)), sin(q0_PC(t))*cos(a)], [sin(a)*cos(q0_PC(t)), -sin(q0_PC(t)), cos(a)*cos(q0_PC(t))]]) The angular velocity of the block can be computed with respect to the ground. >>> block.ang_vel_in(ground) u0_PC(t)*A.x The position of the block's center of mass can be found with: >>> block.masscenter.pos_from(ground.masscenter) d*G_frame.x + h*B_frame.x + q1_PC(t)*A.y + q2_PC(t)*A.z Finally, the linear velocity of the block's center of mass can be computed with respect to the ground. >>> block.masscenter.vel(ground.frame) u1_PC(t)*A.y + u2_PC(t)*A.z In some cases it could be your preference to only define the normals of the plane with respect to both bodies. This can most easily be done by supplying vectors to the ``interframe`` arguments. What will happen in this case is that an interframe will be created with its ``x`` axis aligned with the provided vector. For a further explanation of how this is done see the notes of the ``Joint`` class. In the code below, the above example (with the block on the slope) is recreated by supplying vectors to the interframe arguments. Note that the previously described option is however more computationally efficient, because the algorithm now has to compute the rotation angle between the provided vector and the 'x' axis. >>> from sympy import symbols, cos, sin >>> from sympy.physics.mechanics import PlanarJoint, Body >>> a, d, h = symbols('a d h') >>> ground = Body('G') >>> block = Body('B') >>> joint = PlanarJoint( ... 'PC', ground, block, parent_point=d * ground.x, ... child_point=-h * block.x, child_interframe=block.x, ... parent_interframe=cos(a) * ground.x + sin(a) * ground.z) >>> block.dcm(ground).simplify() Matrix([ [ cos(a), 0, sin(a)], [-sin(a)*sin(q0_PC(t)), cos(q0_PC(t)), sin(q0_PC(t))*cos(a)], [-sin(a)*cos(q0_PC(t)), -sin(q0_PC(t)), cos(a)*cos(q0_PC(t))]]) """ def __init__(self, name, parent, child, rotation_coordinate=None, planar_coordinates=None, rotation_speed=None, planar_speeds=None, parent_point=None, child_point=None, parent_interframe=None, child_interframe=None): # A ready to merge implementation of setting the planar_vectors and # rotation_axis was added and removed in PR #24046 coordinates = (rotation_coordinate, planar_coordinates) speeds = (rotation_speed, planar_speeds) super().__init__(name, parent, child, coordinates, speeds, parent_point, child_point, parent_interframe=parent_interframe, child_interframe=child_interframe) def __str__(self): return (f'PlanarJoint: {self.name} parent: {self.parent} ' f'child: {self.child}') @property def rotation_coordinate(self): """Generalized coordinate corresponding to the rotation angle.""" return self.coordinates[0] @property def planar_coordinates(self): """Two generalized coordinates used for the planar translation.""" return self.coordinates[1:, 0] @property def rotation_speed(self): """Generalized speed corresponding to the angular velocity.""" return self.speeds[0] @property def planar_speeds(self): """Two generalized speeds used for the planar translation velocity.""" return self.speeds[1:, 0] @property def rotation_axis(self): """The axis about which the rotation occurs.""" return self.parent_interframe.x @property def planar_vectors(self): """The vectors that describe the planar translation directions.""" return [self.parent_interframe.y, self.parent_interframe.z] def _generate_coordinates(self, coordinates): rotation_speed = self._fill_coordinate_list(coordinates[0], 1, 'q', number_single=True) planar_speeds = self._fill_coordinate_list(coordinates[1], 2, 'q', 1) return rotation_speed.col_join(planar_speeds) def _generate_speeds(self, speeds): rotation_speed = self._fill_coordinate_list(speeds[0], 1, 'u', number_single=True) planar_speeds = self._fill_coordinate_list(speeds[1], 2, 'u', 1) return rotation_speed.col_join(planar_speeds) def _orient_frames(self): self.child_interframe.orient_axis( self.parent_interframe, self.rotation_axis, self.rotation_coordinate) def _set_angular_velocity(self): self.child_interframe.set_ang_vel( self.parent_interframe, self.rotation_speed * self.rotation_axis) def _set_linear_velocity(self): self.child_point.set_pos( self.parent_point, self.planar_coordinates[0] * self.planar_vectors[0] + self.planar_coordinates[1] * self.planar_vectors[1]) self.parent_point.set_vel(self.parent_interframe, 0) self.child_point.set_vel(self.child_interframe, 0) self.child_point.set_vel( self.parent.frame, self.planar_speeds[0] * self.planar_vectors[0] + self.planar_speeds[1] * self.planar_vectors[1]) self.child.masscenter.v2pt_theory(self.child_point, self.parent.frame, self.child.frame) class SphericalJoint(Joint): """Spherical (Ball-and-Socket) Joint. .. image:: SphericalJoint.svg :align: center :width: 600 Explanation =========== A spherical joint is defined such that the child body is free to rotate in any direction, without allowing a translation of the ``child_point``. As can also be seen in the image, the ``parent_point`` and ``child_point`` are fixed on top of each other, i.e. the ``joint_point``. This rotation is defined using the :func:`parent_interframe.orient(child_interframe, rot_type, amounts, rot_order) <sympy.physics.vector.frame.ReferenceFrame.orient>` method. The default rotation consists of three relative rotations, i.e. body-fixed rotations. Based on the direction cosine matrix following from these rotations, the angular velocity is computed based on the generalized coordinates and generalized speeds. Parameters ========== name : string A unique name for the joint. parent : Body The parent body of joint. child : Body The child body of joint. coordinates: iterable of dynamicsymbols, optional Generalized coordinates of the joint. speeds : iterable of dynamicsymbols, optional Generalized speeds of joint. parent_point : Point or Vector, optional Attachment point where the joint is fixed to the parent body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the parent's mass center. child_point : Point or Vector, optional Attachment point where the joint is fixed to the child body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the child's mass center. parent_interframe : ReferenceFrame, optional Intermediate frame of the parent body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the parent's own frame. child_interframe : ReferenceFrame, optional Intermediate frame of the child body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the child's own frame. rot_type : str, optional The method used to generate the direction cosine matrix. Supported methods are: - ``'Body'``: three successive rotations about new intermediate axes, also called "Euler and Tait-Bryan angles" - ``'Space'``: three successive rotations about the parent frames' unit vectors The default method is ``'Body'``. amounts : Expressions defining the rotation angles or direction cosine matrix. These must match the ``rot_type``. See examples below for details. The input types are: - ``'Body'``: 3-tuple of expressions, symbols, or functions - ``'Space'``: 3-tuple of expressions, symbols, or functions The default amounts are the given ``coordinates``. rot_order : str or int, optional If applicable, the order of the successive of rotations. The string ``'123'`` and integer ``123`` are equivalent, for example. Required for ``'Body'`` and ``'Space'``. The default value is ``123``. Attributes ========== name : string The joint's name. parent : Body The joint's parent body. child : Body The joint's child body. coordinates : Matrix Matrix of the joint's generalized coordinates. speeds : Matrix Matrix of the joint's generalized speeds. parent_point : Point Attachment point where the joint is fixed to the parent body. child_point : Point Attachment point where the joint is fixed to the child body. parent_interframe : ReferenceFrame Intermediate frame of the parent body with respect to which the joint transformation is formulated. child_interframe : ReferenceFrame Intermediate frame of the child body with respect to which the joint transformation is formulated. kdes : Matrix Kinematical differential equations of the joint. Examples ========= A single spherical joint is created from two bodies and has the following basic attributes: >>> from sympy.physics.mechanics import Body, SphericalJoint >>> parent = Body('P') >>> parent P >>> child = Body('C') >>> child C >>> joint = SphericalJoint('PC', parent, child) >>> joint SphericalJoint: PC parent: P child: C >>> joint.name 'PC' >>> joint.parent P >>> joint.child C >>> joint.parent_point P_masscenter >>> joint.child_point C_masscenter >>> joint.parent_interframe P_frame >>> joint.child_interframe C_frame >>> joint.coordinates Matrix([ [q0_PC(t)], [q1_PC(t)], [q2_PC(t)]]) >>> joint.speeds Matrix([ [u0_PC(t)], [u1_PC(t)], [u2_PC(t)]]) >>> child.frame.ang_vel_in(parent.frame).to_matrix(child.frame) Matrix([ [ u0_PC(t)*cos(q1_PC(t))*cos(q2_PC(t)) + u1_PC(t)*sin(q2_PC(t))], [-u0_PC(t)*sin(q2_PC(t))*cos(q1_PC(t)) + u1_PC(t)*cos(q2_PC(t))], [ u0_PC(t)*sin(q1_PC(t)) + u2_PC(t)]]) >>> child.frame.x.to_matrix(parent.frame) Matrix([ [ cos(q1_PC(t))*cos(q2_PC(t))], [sin(q0_PC(t))*sin(q1_PC(t))*cos(q2_PC(t)) + sin(q2_PC(t))*cos(q0_PC(t))], [sin(q0_PC(t))*sin(q2_PC(t)) - sin(q1_PC(t))*cos(q0_PC(t))*cos(q2_PC(t))]]) >>> joint.child_point.pos_from(joint.parent_point) 0 To further demonstrate the use of the spherical joint, the kinematics of a spherical joint with a ZXZ rotation can be created as follows. >>> from sympy import symbols >>> from sympy.physics.mechanics import Body, SphericalJoint >>> l1 = symbols('l1') First create bodies to represent the fixed floor and a pendulum bob. >>> floor = Body('F') >>> bob = Body('B') The joint will connect the bob to the floor, with the joint located at a distance of ``l1`` from the child's center of mass and the rotation set to a body-fixed ZXZ rotation. >>> joint = SphericalJoint('S', floor, bob, child_point=l1 * bob.y, ... rot_type='body', rot_order='ZXZ') Now that the joint is established, the kinematics of the connected body can be accessed. The position of the bob's masscenter is found with: >>> bob.masscenter.pos_from(floor.masscenter) - l1*B_frame.y The angular velocities of the pendulum link can be computed with respect to the floor. >>> bob.frame.ang_vel_in(floor.frame).to_matrix( ... floor.frame).simplify() Matrix([ [u1_S(t)*cos(q0_S(t)) + u2_S(t)*sin(q0_S(t))*sin(q1_S(t))], [u1_S(t)*sin(q0_S(t)) - u2_S(t)*sin(q1_S(t))*cos(q0_S(t))], [ u0_S(t) + u2_S(t)*cos(q1_S(t))]]) Finally, the linear velocity of the bob's center of mass can be computed. >>> bob.masscenter.vel(floor.frame).to_matrix(bob.frame) Matrix([ [ l1*(u0_S(t)*cos(q1_S(t)) + u2_S(t))], [ 0], [-l1*(u0_S(t)*sin(q1_S(t))*sin(q2_S(t)) + u1_S(t)*cos(q2_S(t)))]]) """ def __init__(self, name, parent, child, coordinates=None, speeds=None, parent_point=None, child_point=None, parent_interframe=None, child_interframe=None, rot_type='BODY', amounts=None, rot_order=123): self._rot_type = rot_type self._amounts = amounts self._rot_order = rot_order super().__init__(name, parent, child, coordinates, speeds, parent_point, child_point, parent_interframe=parent_interframe, child_interframe=child_interframe) def __str__(self): return (f'SphericalJoint: {self.name} parent: {self.parent} ' f'child: {self.child}') def _generate_coordinates(self, coordinates): return self._fill_coordinate_list(coordinates, 3, 'q') def _generate_speeds(self, speeds): return self._fill_coordinate_list(speeds, len(self.coordinates), 'u') def _orient_frames(self): supported_rot_types = ('BODY', 'SPACE') if self._rot_type.upper() not in supported_rot_types: raise NotImplementedError( f'Rotation type "{self._rot_type}" is not implemented. ' f'Implemented rotation types are: {supported_rot_types}') amounts = self.coordinates if self._amounts is None else self._amounts self.child_interframe.orient(self.parent_interframe, self._rot_type, amounts, self._rot_order) def _set_angular_velocity(self): t = dynamicsymbols._t vel = self.child_interframe.ang_vel_in(self.parent_interframe).xreplace( {q.diff(t): u for q, u in zip(self.coordinates, self.speeds)} ) self.child_interframe.set_ang_vel(self.parent_interframe, vel) def _set_linear_velocity(self): self.child_point.set_pos(self.parent_point, 0) self.parent_point.set_vel(self.parent.frame, 0) self.child_point.set_vel(self.child.frame, 0) self.child.masscenter.v2pt_theory(self.parent_point, self.parent.frame, self.child.frame) class WeldJoint(Joint): """Weld Joint. .. image:: WeldJoint.svg :align: center :width: 500 Explanation =========== A weld joint is defined such that there is no relative motion between the child and parent bodies. The direction cosine matrix between the attachment frame (``parent_interframe`` and ``child_interframe``) is the identity matrix and the attachment points (``parent_point`` and ``child_point``) are coincident. The page on the joints framework gives a more detailed explanation of the intermediate frames. Parameters ========== name : string A unique name for the joint. parent : Body The parent body of joint. child : Body The child body of joint. parent_point : Point or Vector, optional Attachment point where the joint is fixed to the parent body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the parent's mass center. child_point : Point or Vector, optional Attachment point where the joint is fixed to the child body. If a vector is provided, then the attachment point is computed by adding the vector to the body's mass center. The default value is the child's mass center. parent_interframe : ReferenceFrame, optional Intermediate frame of the parent body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the parent's own frame. child_interframe : ReferenceFrame, optional Intermediate frame of the child body with respect to which the joint transformation is formulated. If a Vector is provided then an interframe is created which aligns its X axis with the given vector. The default value is the child's own frame. Attributes ========== name : string The joint's name. parent : Body The joint's parent body. child : Body The joint's child body. coordinates : Matrix Matrix of the joint's generalized coordinates. The default value is ``dynamicsymbols(f'q_{joint.name}')``. speeds : Matrix Matrix of the joint's generalized speeds. The default value is ``dynamicsymbols(f'u_{joint.name}')``. parent_point : Point Attachment point where the joint is fixed to the parent body. child_point : Point Attachment point where the joint is fixed to the child body. parent_interframe : ReferenceFrame Intermediate frame of the parent body with respect to which the joint transformation is formulated. child_interframe : ReferenceFrame Intermediate frame of the child body with respect to which the joint transformation is formulated. kdes : Matrix Kinematical differential equations of the joint. Examples ========= A single weld joint is created from two bodies and has the following basic attributes: >>> from sympy.physics.mechanics import Body, WeldJoint >>> parent = Body('P') >>> parent P >>> child = Body('C') >>> child C >>> joint = WeldJoint('PC', parent, child) >>> joint WeldJoint: PC parent: P child: C >>> joint.name 'PC' >>> joint.parent P >>> joint.child C >>> joint.parent_point P_masscenter >>> joint.child_point C_masscenter >>> joint.coordinates Matrix(0, 0, []) >>> joint.speeds Matrix(0, 0, []) >>> joint.child.frame.ang_vel_in(joint.parent.frame) 0 >>> joint.child.frame.dcm(joint.parent.frame) Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> joint.child_point.pos_from(joint.parent_point) 0 To further demonstrate the use of the weld joint, two relatively-fixed bodies rotated by a quarter turn about the Y axis can be created as follows: >>> from sympy import symbols, pi >>> from sympy.physics.mechanics import ReferenceFrame, Body, WeldJoint >>> l1, l2 = symbols('l1 l2') First create the bodies to represent the parent and rotated child body. >>> parent = Body('P') >>> child = Body('C') Next the intermediate frame specifying the fixed rotation with respect to the parent can be created. >>> rotated_frame = ReferenceFrame('Pr') >>> rotated_frame.orient_axis(parent.frame, parent.y, pi / 2) The weld between the parent body and child body is located at a distance ``l1`` from the parent's center of mass in the X direction and ``l2`` from the child's center of mass in the child's negative X direction. >>> weld = WeldJoint('weld', parent, child, parent_point=l1 * parent.x, ... child_point=-l2 * child.x, ... parent_interframe=rotated_frame) Now that the joint has been established, the kinematics of the bodies can be accessed. The direction cosine matrix of the child body with respect to the parent can be found: >>> child.dcm(parent) Matrix([ [0, 0, -1], [0, 1, 0], [1, 0, 0]]) As can also been seen from the direction cosine matrix, the parent X axis is aligned with the child's Z axis: >>> parent.x == child.z True The position of the child's center of mass with respect to the parent's center of mass can be found with: >>> child.masscenter.pos_from(parent.masscenter) l1*P_frame.x + l2*C_frame.x The angular velocity of the child with respect to the parent is 0 as one would expect. >>> child.ang_vel_in(parent) 0 """ def __init__(self, name, parent, child, parent_point=None, child_point=None, parent_interframe=None, child_interframe=None): super().__init__(name, parent, child, [], [], parent_point, child_point, parent_interframe=parent_interframe, child_interframe=child_interframe) self._kdes = Matrix(1, 0, []).T # Removes stackability problems #10770 def __str__(self): return (f'WeldJoint: {self.name} parent: {self.parent} ' f'child: {self.child}') def _generate_coordinates(self, coordinate): return Matrix() def _generate_speeds(self, speed): return Matrix() def _orient_frames(self): self.child_interframe.orient_axis(self.parent_interframe, self.parent_interframe.x, 0) def _set_angular_velocity(self): self.child_interframe.set_ang_vel(self.parent_interframe, 0) def _set_linear_velocity(self): self.child_point.set_pos(self.parent_point, 0) self.parent_point.set_vel(self.parent.frame, 0) self.child_point.set_vel(self.child.frame, 0) self.child.masscenter.set_vel(self.parent.frame, 0)
fc1336ab67ae0718958fee4e54c3a4bb3bbd0f4d7630fe400ba2e73843706d7d
from sympy.core.backend import diff, zeros, Matrix, eye, sympify from sympy.core.sorting import default_sort_key from sympy.physics.vector import dynamicsymbols, ReferenceFrame from sympy.physics.mechanics.method import _Methods from sympy.physics.mechanics.functions import ( find_dynamicsymbols, msubs, _f_list_parser, _validate_coordinates) from sympy.physics.mechanics.linearize import Linearizer from sympy.utilities.iterables import iterable __all__ = ['LagrangesMethod'] class LagrangesMethod(_Methods): """Lagrange's method object. Explanation =========== This object generates the equations of motion in a two step procedure. The first step involves the initialization of LagrangesMethod by supplying the Lagrangian and the generalized coordinates, at the bare minimum. If there are any constraint equations, they can be supplied as keyword arguments. The Lagrange multipliers are automatically generated and are equal in number to the constraint equations. Similarly any non-conservative forces can be supplied in an iterable (as described below and also shown in the example) along with a ReferenceFrame. This is also discussed further in the __init__ method. Attributes ========== q, u : Matrix Matrices of the generalized coordinates and speeds loads : iterable Iterable of (Point, vector) or (ReferenceFrame, vector) tuples describing the forces on the system. bodies : iterable Iterable containing the rigid bodies and particles of the system. mass_matrix : Matrix The system's mass matrix forcing : Matrix The system's forcing vector mass_matrix_full : Matrix The "mass matrix" for the qdot's, qdoubledot's, and the lagrange multipliers (lam) forcing_full : Matrix The forcing vector for the qdot's, qdoubledot's and lagrange multipliers (lam) Examples ======== This is a simple example for a one degree of freedom translational spring-mass-damper. In this example, we first need to do the kinematics. This involves creating generalized coordinates and their derivatives. Then we create a point and set its velocity in a frame. >>> from sympy.physics.mechanics import LagrangesMethod, Lagrangian >>> from sympy.physics.mechanics import ReferenceFrame, Particle, Point >>> from sympy.physics.mechanics import dynamicsymbols >>> from sympy import symbols >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> m, k, b = symbols('m k b') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, qd * N.x) We need to then prepare the information as required by LagrangesMethod to generate equations of motion. First we create the Particle, which has a point attached to it. Following this the lagrangian is created from the kinetic and potential energies. Then, an iterable of nonconservative forces/torques must be constructed, where each item is a (Point, Vector) or (ReferenceFrame, Vector) tuple, with the Vectors representing the nonconservative forces or torques. >>> Pa = Particle('Pa', P, m) >>> Pa.potential_energy = k * q**2 / 2.0 >>> L = Lagrangian(N, Pa) >>> fl = [(P, -b * qd * N.x)] Finally we can generate the equations of motion. First we create the LagrangesMethod object. To do this one must supply the Lagrangian, and the generalized coordinates. The constraint equations, the forcelist, and the inertial frame may also be provided, if relevant. Next we generate Lagrange's equations of motion, such that: Lagrange's equations of motion = 0. We have the equations of motion at this point. >>> l = LagrangesMethod(L, [q], forcelist = fl, frame = N) >>> print(l.form_lagranges_equations()) Matrix([[b*Derivative(q(t), t) + 1.0*k*q(t) + m*Derivative(q(t), (t, 2))]]) We can also solve for the states using the 'rhs' method. >>> print(l.rhs()) Matrix([[Derivative(q(t), t)], [(-b*Derivative(q(t), t) - 1.0*k*q(t))/m]]) Please refer to the docstrings on each method for more details. """ def __init__(self, Lagrangian, qs, forcelist=None, bodies=None, frame=None, hol_coneqs=None, nonhol_coneqs=None): """Supply the following for the initialization of LagrangesMethod. Lagrangian : Sympifyable qs : array_like The generalized coordinates hol_coneqs : array_like, optional The holonomic constraint equations nonhol_coneqs : array_like, optional The nonholonomic constraint equations forcelist : iterable, optional Takes an iterable of (Point, Vector) or (ReferenceFrame, Vector) tuples which represent the force at a point or torque on a frame. This feature is primarily to account for the nonconservative forces and/or moments. bodies : iterable, optional Takes an iterable containing the rigid bodies and particles of the system. frame : ReferenceFrame, optional Supply the inertial frame. This is used to determine the generalized forces due to non-conservative forces. """ self._L = Matrix([sympify(Lagrangian)]) self.eom = None self._m_cd = Matrix() # Mass Matrix of differentiated coneqs self._m_d = Matrix() # Mass Matrix of dynamic equations self._f_cd = Matrix() # Forcing part of the diff coneqs self._f_d = Matrix() # Forcing part of the dynamic equations self.lam_coeffs = Matrix() # The coeffecients of the multipliers forcelist = forcelist if forcelist else [] if not iterable(forcelist): raise TypeError('Force pairs must be supplied in an iterable.') self._forcelist = forcelist if frame and not isinstance(frame, ReferenceFrame): raise TypeError('frame must be a valid ReferenceFrame') self._bodies = bodies self.inertial = frame self.lam_vec = Matrix() self._term1 = Matrix() self._term2 = Matrix() self._term3 = Matrix() self._term4 = Matrix() # Creating the qs, qdots and qdoubledots if not iterable(qs): raise TypeError('Generalized coordinates must be an iterable') self._q = Matrix(qs) self._qdots = self.q.diff(dynamicsymbols._t) self._qdoubledots = self._qdots.diff(dynamicsymbols._t) _validate_coordinates(self.q) mat_build = lambda x: Matrix(x) if x else Matrix() hol_coneqs = mat_build(hol_coneqs) nonhol_coneqs = mat_build(nonhol_coneqs) self.coneqs = Matrix([hol_coneqs.diff(dynamicsymbols._t), nonhol_coneqs]) self._hol_coneqs = hol_coneqs def form_lagranges_equations(self): """Method to form Lagrange's equations of motion. Returns a vector of equations of motion using Lagrange's equations of the second kind. """ qds = self._qdots qdd_zero = {i: 0 for i in self._qdoubledots} n = len(self.q) # Internally we represent the EOM as four terms: # EOM = term1 - term2 - term3 - term4 = 0 # First term self._term1 = self._L.jacobian(qds) self._term1 = self._term1.diff(dynamicsymbols._t).T # Second term self._term2 = self._L.jacobian(self.q).T # Third term if self.coneqs: coneqs = self.coneqs m = len(coneqs) # Creating the multipliers self.lam_vec = Matrix(dynamicsymbols('lam1:' + str(m + 1))) self.lam_coeffs = -coneqs.jacobian(qds) self._term3 = self.lam_coeffs.T * self.lam_vec # Extracting the coeffecients of the qdds from the diff coneqs diffconeqs = coneqs.diff(dynamicsymbols._t) self._m_cd = diffconeqs.jacobian(self._qdoubledots) # The remaining terms i.e. the 'forcing' terms in diff coneqs self._f_cd = -diffconeqs.subs(qdd_zero) else: self._term3 = zeros(n, 1) # Fourth term if self.forcelist: N = self.inertial self._term4 = zeros(n, 1) for i, qd in enumerate(qds): flist = zip(*_f_list_parser(self.forcelist, N)) self._term4[i] = sum(v.diff(qd, N) & f for (v, f) in flist) else: self._term4 = zeros(n, 1) # Form the dynamic mass and forcing matrices without_lam = self._term1 - self._term2 - self._term4 self._m_d = without_lam.jacobian(self._qdoubledots) self._f_d = -without_lam.subs(qdd_zero) # Form the EOM self.eom = without_lam - self._term3 return self.eom def _form_eoms(self): return self.form_lagranges_equations() @property def mass_matrix(self): """Returns the mass matrix, which is augmented by the Lagrange multipliers, if necessary. Explanation =========== If the system is described by 'n' generalized coordinates and there are no constraint equations then an n X n matrix is returned. If there are 'n' generalized coordinates and 'm' constraint equations have been supplied during initialization then an n X (n+m) matrix is returned. The (n + m - 1)th and (n + m)th columns contain the coefficients of the Lagrange multipliers. """ if self.eom is None: raise ValueError('Need to compute the equations of motion first') if self.coneqs: return (self._m_d).row_join(self.lam_coeffs.T) else: return self._m_d @property def mass_matrix_full(self): """Augments the coefficients of qdots to the mass_matrix.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') n = len(self.q) m = len(self.coneqs) row1 = eye(n).row_join(zeros(n, n + m)) row2 = zeros(n, n).row_join(self.mass_matrix) if self.coneqs: row3 = zeros(m, n).row_join(self._m_cd).row_join(zeros(m, m)) return row1.col_join(row2).col_join(row3) else: return row1.col_join(row2) @property def forcing(self): """Returns the forcing vector from 'lagranges_equations' method.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') return self._f_d @property def forcing_full(self): """Augments qdots to the forcing vector above.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') if self.coneqs: return self._qdots.col_join(self.forcing).col_join(self._f_cd) else: return self._qdots.col_join(self.forcing) def to_linearizer(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None): """Returns an instance of the Linearizer class, initiated from the data in the LagrangesMethod class. This may be more desirable than using the linearize class method, as the Linearizer object will allow more efficient recalculation (i.e. about varying operating points). Parameters ========== q_ind, qd_ind : array_like, optional The independent generalized coordinates and speeds. q_dep, qd_dep : array_like, optional The dependent generalized coordinates and speeds. """ # Compose vectors t = dynamicsymbols._t q = self.q u = self._qdots ud = u.diff(t) # Get vector of lagrange multipliers lams = self.lam_vec mat_build = lambda x: Matrix(x) if x else Matrix() q_i = mat_build(q_ind) q_d = mat_build(q_dep) u_i = mat_build(qd_ind) u_d = mat_build(qd_dep) # Compose general form equations f_c = self._hol_coneqs f_v = self.coneqs f_a = f_v.diff(t) f_0 = u f_1 = -u f_2 = self._term1 f_3 = -(self._term2 + self._term4) f_4 = -self._term3 # Check that there are an appropriate number of independent and # dependent coordinates if len(q_d) != len(f_c) or len(u_d) != len(f_v): raise ValueError(("Must supply {:} dependent coordinates, and " + "{:} dependent speeds").format(len(f_c), len(f_v))) if set(Matrix([q_i, q_d])) != set(q): raise ValueError("Must partition q into q_ind and q_dep, with " + "no extra or missing symbols.") if set(Matrix([u_i, u_d])) != set(u): raise ValueError("Must partition qd into qd_ind and qd_dep, " + "with no extra or missing symbols.") # Find all other dynamic symbols, forming the forcing vector r. # Sort r to make it canonical. insyms = set(Matrix([q, u, ud, lams])) r = list(find_dynamicsymbols(f_3, insyms)) r.sort(key=default_sort_key) # Check for any derivatives of variables in r that are also found in r. for i in r: if diff(i, dynamicsymbols._t) in r: raise ValueError('Cannot have derivatives of specified \ quantities when linearizing forcing terms.') return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i, q_d, u_i, u_d, r, lams) def linearize(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None, **kwargs): """Linearize the equations of motion about a symbolic operating point. Explanation =========== If kwarg A_and_B is False (default), returns M, A, B, r for the linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r. If kwarg A_and_B is True, returns A, B, r for the linearized form dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. Values may then be substituted in to these matrices, and the state space form found as A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat. In both cases, r is found as all dynamicsymbols in the equations of motion that are not part of q, u, q', or u'. They are sorted in canonical form. The operating points may be also entered using the ``op_point`` kwarg. This takes a dictionary of {symbol: value}, or a an iterable of such dictionaries. The values may be numeric or symbolic. The more values you can specify beforehand, the faster this computation will run. For more documentation, please see the ``Linearizer`` class.""" linearizer = self.to_linearizer(q_ind, qd_ind, q_dep, qd_dep) result = linearizer.linearize(**kwargs) return result + (linearizer.r,) def solve_multipliers(self, op_point=None, sol_type='dict'): """Solves for the values of the lagrange multipliers symbolically at the specified operating point. Parameters ========== op_point : dict or iterable of dicts, optional Point at which to solve at. The operating point is specified as a dictionary or iterable of dictionaries of {symbol: value}. The value may be numeric or symbolic itself. sol_type : str, optional Solution return type. Valid options are: - 'dict': A dict of {symbol : value} (default) - 'Matrix': An ordered column matrix of the solution """ # Determine number of multipliers k = len(self.lam_vec) if k == 0: raise ValueError("System has no lagrange multipliers to solve for.") # Compose dict of operating conditions if isinstance(op_point, dict): op_point_dict = op_point elif iterable(op_point): op_point_dict = {} for op in op_point: op_point_dict.update(op) elif op_point is None: op_point_dict = {} else: raise TypeError("op_point must be either a dictionary or an " "iterable of dictionaries.") # Compose the system to be solved mass_matrix = self.mass_matrix.col_join(-self.lam_coeffs.row_join( zeros(k, k))) force_matrix = self.forcing.col_join(self._f_cd) # Sub in the operating point mass_matrix = msubs(mass_matrix, op_point_dict) force_matrix = msubs(force_matrix, op_point_dict) # Solve for the multipliers sol_list = mass_matrix.LUsolve(-force_matrix)[-k:] if sol_type == 'dict': return dict(zip(self.lam_vec, sol_list)) elif sol_type == 'Matrix': return Matrix(sol_list) else: raise ValueError("Unknown sol_type {:}.".format(sol_type)) def rhs(self, inv_method=None, **kwargs): """Returns equations that can be solved numerically. Parameters ========== inv_method : str The specific sympy inverse matrix calculation method to use. For a list of valid methods, see :meth:`~sympy.matrices.matrices.MatrixBase.inv` """ if inv_method is None: self._rhs = self.mass_matrix_full.LUsolve(self.forcing_full) else: self._rhs = (self.mass_matrix_full.inv(inv_method, try_block_diag=True) * self.forcing_full) return self._rhs @property def q(self): return self._q @property def u(self): return self._qdots @property def bodies(self): return self._bodies @property def forcelist(self): return self._forcelist @property def loads(self): return self._forcelist
fc8ce616d7227f673f01a4166dc3ac848eca7bbfca5229c6bc756f135c853bfb
""" Unit system for physical quantities; include definition of constants. """ from typing import Dict as tDict, Set as tSet from sympy.core.add import Add from sympy.core.function import (Derivative, Function) from sympy.core.mul import Mul from sympy.core.power import Pow from sympy.core.singleton import S from sympy.physics.units.dimensions import _QuantityMapper from sympy.physics.units.quantities import Quantity from .dimensions import Dimension class UnitSystem(_QuantityMapper): """ UnitSystem represents a coherent set of units. A unit system is basically a dimension system with notions of scales. Many of the methods are defined in the same way. It is much better if all base units have a symbol. """ _unit_systems = {} # type: tDict[str, UnitSystem] def __init__(self, base_units, units=(), name="", descr="", dimension_system=None, derived_units: tDict[Dimension, Quantity]={}): UnitSystem._unit_systems[name] = self self.name = name self.descr = descr self._base_units = base_units self._dimension_system = dimension_system self._units = tuple(set(base_units) | set(units)) self._base_units = tuple(base_units) self._derived_units = derived_units super().__init__() def __str__(self): """ Return the name of the system. If it does not exist, then it makes a list of symbols (or names) of the base dimensions. """ if self.name != "": return self.name else: return "UnitSystem((%s))" % ", ".join( str(d) for d in self._base_units) def __repr__(self): return '<UnitSystem: %s>' % repr(self._base_units) def extend(self, base, units=(), name="", description="", dimension_system=None, derived_units: tDict[Dimension, Quantity]={}): """Extend the current system into a new one. Take the base and normal units of the current system to merge them to the base and normal units given in argument. If not provided, name and description are overridden by empty strings. """ base = self._base_units + tuple(base) units = self._units + tuple(units) return UnitSystem(base, units, name, description, dimension_system, {**self._derived_units, **derived_units}) def get_dimension_system(self): return self._dimension_system def get_quantity_dimension(self, unit): qdm = self.get_dimension_system()._quantity_dimension_map if unit in qdm: return qdm[unit] return super().get_quantity_dimension(unit) def get_quantity_scale_factor(self, unit): qsfm = self.get_dimension_system()._quantity_scale_factors if unit in qsfm: return qsfm[unit] return super().get_quantity_scale_factor(unit) @staticmethod def get_unit_system(unit_system): if isinstance(unit_system, UnitSystem): return unit_system if unit_system not in UnitSystem._unit_systems: raise ValueError( "Unit system is not supported. Currently" "supported unit systems are {}".format( ", ".join(sorted(UnitSystem._unit_systems)) ) ) return UnitSystem._unit_systems[unit_system] @staticmethod def get_default_unit_system(): return UnitSystem._unit_systems["SI"] @property def dim(self): """ Give the dimension of the system. That is return the number of units forming the basis. """ return len(self._base_units) @property def is_consistent(self): """ Check if the underlying dimension system is consistent. """ # test is performed in DimensionSystem return self.get_dimension_system().is_consistent @property def derived_units(self) -> tDict[Dimension, Quantity]: return self._derived_units def get_dimensional_expr(self, expr): from sympy.physics.units import Quantity if isinstance(expr, Mul): return Mul(*[self.get_dimensional_expr(i) for i in expr.args]) elif isinstance(expr, Pow): return self.get_dimensional_expr(expr.base) ** expr.exp elif isinstance(expr, Add): return self.get_dimensional_expr(expr.args[0]) elif isinstance(expr, Derivative): dim = self.get_dimensional_expr(expr.expr) for independent, count in expr.variable_count: dim /= self.get_dimensional_expr(independent)**count return dim elif isinstance(expr, Function): args = [self.get_dimensional_expr(arg) for arg in expr.args] if all(i == 1 for i in args): return S.One return expr.func(*args) elif isinstance(expr, Quantity): return self.get_quantity_dimension(expr).name return S.One def _collect_factor_and_dimension(self, expr): """ Return tuple with scale factor expression and dimension expression. """ from sympy.physics.units import Quantity if isinstance(expr, Quantity): return expr.scale_factor, expr.dimension elif isinstance(expr, Mul): factor = 1 dimension = Dimension(1) for arg in expr.args: arg_factor, arg_dim = self._collect_factor_and_dimension(arg) factor *= arg_factor dimension *= arg_dim return factor, dimension elif isinstance(expr, Pow): factor, dim = self._collect_factor_and_dimension(expr.base) exp_factor, exp_dim = self._collect_factor_and_dimension(expr.exp) if self.get_dimension_system().is_dimensionless(exp_dim): exp_dim = 1 return factor ** exp_factor, dim ** (exp_factor * exp_dim) elif isinstance(expr, Add): factor, dim = self._collect_factor_and_dimension(expr.args[0]) for addend in expr.args[1:]: addend_factor, addend_dim = \ self._collect_factor_and_dimension(addend) if dim != addend_dim: raise ValueError( 'Dimension of "{}" is {}, ' 'but it should be {}'.format( addend, addend_dim, dim)) factor += addend_factor return factor, dim elif isinstance(expr, Derivative): factor, dim = self._collect_factor_and_dimension(expr.args[0]) for independent, count in expr.variable_count: ifactor, idim = self._collect_factor_and_dimension(independent) factor /= ifactor**count dim /= idim**count return factor, dim elif isinstance(expr, Function): fds = [self._collect_factor_and_dimension(arg) for arg in expr.args] dims = [Dimension(1) if self.get_dimension_system().is_dimensionless(d[1]) else d[1] for d in fds] return (expr.func(*(f[0] for f in fds)), *dims) elif isinstance(expr, Dimension): return S.One, expr else: return expr, Dimension(1) def get_units_non_prefixed(self) -> tSet[Quantity]: """ Return the units of the system that do not have a prefix. """ return set(filter(lambda u: not u.is_prefixed and not u.is_physical_constant, self._units))
dc54624be408f84699f5b877c50610505642f0e0e0872e98e743a9b26a972d04
from sympy.core.backend import (diff, expand, sin, cos, sympify, eye, zeros, ImmutableMatrix as Matrix, MatrixBase) from sympy.core.symbol import Symbol from sympy.simplify.trigsimp import trigsimp from sympy.physics.vector.vector import Vector, _check_vector from sympy.utilities.misc import translate from warnings import warn __all__ = ['CoordinateSym', 'ReferenceFrame'] class CoordinateSym(Symbol): """ A coordinate symbol/base scalar associated wrt a Reference Frame. Ideally, users should not instantiate this class. Instances of this class must only be accessed through the corresponding frame as 'frame[index]'. CoordinateSyms having the same frame and index parameters are equal (even though they may be instantiated separately). Parameters ========== name : string The display name of the CoordinateSym frame : ReferenceFrame The reference frame this base scalar belongs to index : 0, 1 or 2 The index of the dimension denoted by this coordinate variable Examples ======== >>> from sympy.physics.vector import ReferenceFrame, CoordinateSym >>> A = ReferenceFrame('A') >>> A[1] A_y >>> type(A[0]) <class 'sympy.physics.vector.frame.CoordinateSym'> >>> a_y = CoordinateSym('a_y', A, 1) >>> a_y == A[1] True """ def __new__(cls, name, frame, index): # We can't use the cached Symbol.__new__ because this class depends on # frame and index, which are not passed to Symbol.__xnew__. assumptions = {} super()._sanitize(assumptions, cls) obj = super().__xnew__(cls, name, **assumptions) _check_frame(frame) if index not in range(0, 3): raise ValueError("Invalid index specified") obj._id = (frame, index) return obj @property def frame(self): return self._id[0] def __eq__(self, other): # Check if the other object is a CoordinateSym of the same frame and # same index if isinstance(other, CoordinateSym): if other._id == self._id: return True return False def __ne__(self, other): return not self == other def __hash__(self): return tuple((self._id[0].__hash__(), self._id[1])).__hash__() class ReferenceFrame: """A reference frame in classical mechanics. ReferenceFrame is a class used to represent a reference frame in classical mechanics. It has a standard basis of three unit vectors in the frame's x, y, and z directions. It also can have a rotation relative to a parent frame; this rotation is defined by a direction cosine matrix relating this frame's basis vectors to the parent frame's basis vectors. It can also have an angular velocity vector, defined in another frame. """ _count = 0 def __init__(self, name, indices=None, latexs=None, variables=None): """ReferenceFrame initialization method. A ReferenceFrame has a set of orthonormal basis vectors, along with orientations relative to other ReferenceFrames and angular velocities relative to other ReferenceFrames. Parameters ========== indices : tuple of str Enables the reference frame's basis unit vectors to be accessed by Python's square bracket indexing notation using the provided three indice strings and alters the printing of the unit vectors to reflect this choice. latexs : tuple of str Alters the LaTeX printing of the reference frame's basis unit vectors to the provided three valid LaTeX strings. Examples ======== >>> from sympy.physics.vector import ReferenceFrame, vlatex >>> N = ReferenceFrame('N') >>> N.x N.x >>> O = ReferenceFrame('O', indices=('1', '2', '3')) >>> O.x O['1'] >>> O['1'] O['1'] >>> P = ReferenceFrame('P', latexs=('A1', 'A2', 'A3')) >>> vlatex(P.x) 'A1' ``symbols()`` can be used to create multiple Reference Frames in one step, for example: >>> from sympy.physics.vector import ReferenceFrame >>> from sympy import symbols >>> A, B, C = symbols('A B C', cls=ReferenceFrame) >>> D, E = symbols('D E', cls=ReferenceFrame, indices=('1', '2', '3')) >>> A[0] A_x >>> D.x D['1'] >>> E.y E['2'] >>> type(A) == type(D) True """ if not isinstance(name, str): raise TypeError('Need to supply a valid name') # The if statements below are for custom printing of basis-vectors for # each frame. # First case, when custom indices are supplied if indices is not None: if not isinstance(indices, (tuple, list)): raise TypeError('Supply the indices as a list') if len(indices) != 3: raise ValueError('Supply 3 indices') for i in indices: if not isinstance(i, str): raise TypeError('Indices must be strings') self.str_vecs = [(name + '[\'' + indices[0] + '\']'), (name + '[\'' + indices[1] + '\']'), (name + '[\'' + indices[2] + '\']')] self.pretty_vecs = [(name.lower() + "_" + indices[0]), (name.lower() + "_" + indices[1]), (name.lower() + "_" + indices[2])] self.latex_vecs = [(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(), indices[0])), (r"\mathbf{\hat{%s}_{%s}}" % (name.lower(), indices[1])), (r"\mathbf{\hat{%s}_{%s}}" % (name.lower(), indices[2]))] self.indices = indices # Second case, when no custom indices are supplied else: self.str_vecs = [(name + '.x'), (name + '.y'), (name + '.z')] self.pretty_vecs = [name.lower() + "_x", name.lower() + "_y", name.lower() + "_z"] self.latex_vecs = [(r"\mathbf{\hat{%s}_x}" % name.lower()), (r"\mathbf{\hat{%s}_y}" % name.lower()), (r"\mathbf{\hat{%s}_z}" % name.lower())] self.indices = ['x', 'y', 'z'] # Different step, for custom latex basis vectors if latexs is not None: if not isinstance(latexs, (tuple, list)): raise TypeError('Supply the indices as a list') if len(latexs) != 3: raise ValueError('Supply 3 indices') for i in latexs: if not isinstance(i, str): raise TypeError('Latex entries must be strings') self.latex_vecs = latexs self.name = name self._var_dict = {} # The _dcm_dict dictionary will only store the dcms of adjacent # parent-child relationships. The _dcm_cache dictionary will store # calculated dcm along with all content of _dcm_dict for faster # retrieval of dcms. self._dcm_dict = {} self._dcm_cache = {} self._ang_vel_dict = {} self._ang_acc_dict = {} self._dlist = [self._dcm_dict, self._ang_vel_dict, self._ang_acc_dict] self._cur = 0 self._x = Vector([(Matrix([1, 0, 0]), self)]) self._y = Vector([(Matrix([0, 1, 0]), self)]) self._z = Vector([(Matrix([0, 0, 1]), self)]) # Associate coordinate symbols wrt this frame if variables is not None: if not isinstance(variables, (tuple, list)): raise TypeError('Supply the variable names as a list/tuple') if len(variables) != 3: raise ValueError('Supply 3 variable names') for i in variables: if not isinstance(i, str): raise TypeError('Variable names must be strings') else: variables = [name + '_x', name + '_y', name + '_z'] self.varlist = (CoordinateSym(variables[0], self, 0), CoordinateSym(variables[1], self, 1), CoordinateSym(variables[2], self, 2)) ReferenceFrame._count += 1 self.index = ReferenceFrame._count def __getitem__(self, ind): """ Returns basis vector for the provided index, if the index is a string. If the index is a number, returns the coordinate variable correspon- -ding to that index. """ if not isinstance(ind, str): if ind < 3: return self.varlist[ind] else: raise ValueError("Invalid index provided") if self.indices[0] == ind: return self.x if self.indices[1] == ind: return self.y if self.indices[2] == ind: return self.z else: raise ValueError('Not a defined index') def __iter__(self): return iter([self.x, self.y, self.z]) def __str__(self): """Returns the name of the frame. """ return self.name __repr__ = __str__ def _dict_list(self, other, num): """Returns an inclusive list of reference frames that connect this reference frame to the provided reference frame. Parameters ========== other : ReferenceFrame The other reference frame to look for a connecting relationship to. num : integer ``0``, ``1``, and ``2`` will look for orientation, angular velocity, and angular acceleration relationships between the two frames, respectively. Returns ======= list Inclusive list of reference frames that connect this reference frame to the other reference frame. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> A = ReferenceFrame('A') >>> B = ReferenceFrame('B') >>> C = ReferenceFrame('C') >>> D = ReferenceFrame('D') >>> B.orient_axis(A, A.x, 1.0) >>> C.orient_axis(B, B.x, 1.0) >>> D.orient_axis(C, C.x, 1.0) >>> D._dict_list(A, 0) [D, C, B, A] Raises ====== ValueError When no path is found between the two reference frames or ``num`` is an incorrect value. """ connect_type = {0: 'orientation', 1: 'angular velocity', 2: 'angular acceleration'} if num not in connect_type.keys(): raise ValueError('Valid values for num are 0, 1, or 2.') possible_connecting_paths = [[self]] oldlist = [[]] while possible_connecting_paths != oldlist: oldlist = possible_connecting_paths[:] # make a copy for frame_list in possible_connecting_paths: frames_adjacent_to_last = frame_list[-1]._dlist[num].keys() for adjacent_frame in frames_adjacent_to_last: if adjacent_frame not in frame_list: connecting_path = frame_list + [adjacent_frame] if connecting_path not in possible_connecting_paths: possible_connecting_paths.append(connecting_path) for connecting_path in oldlist: if connecting_path[-1] != other: possible_connecting_paths.remove(connecting_path) possible_connecting_paths.sort(key=len) if len(possible_connecting_paths) != 0: return possible_connecting_paths[0] # selects the shortest path msg = 'No connecting {} path found between {} and {}.' raise ValueError(msg.format(connect_type[num], self.name, other.name)) def _w_diff_dcm(self, otherframe): """Angular velocity from time differentiating the DCM. """ from sympy.physics.vector.functions import dynamicsymbols dcm2diff = otherframe.dcm(self) diffed = dcm2diff.diff(dynamicsymbols._t) angvelmat = diffed * dcm2diff.T w1 = trigsimp(expand(angvelmat[7]), recursive=True) w2 = trigsimp(expand(angvelmat[2]), recursive=True) w3 = trigsimp(expand(angvelmat[3]), recursive=True) return Vector([(Matrix([w1, w2, w3]), otherframe)]) def variable_map(self, otherframe): """ Returns a dictionary which expresses the coordinate variables of this frame in terms of the variables of otherframe. If Vector.simp is True, returns a simplified version of the mapped values. Else, returns them without simplification. Simplification of the expressions may take time. Parameters ========== otherframe : ReferenceFrame The other frame to map the variables to Examples ======== >>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols >>> A = ReferenceFrame('A') >>> q = dynamicsymbols('q') >>> B = A.orientnew('B', 'Axis', [q, A.z]) >>> A.variable_map(B) {A_x: B_x*cos(q(t)) - B_y*sin(q(t)), A_y: B_x*sin(q(t)) + B_y*cos(q(t)), A_z: B_z} """ _check_frame(otherframe) if (otherframe, Vector.simp) in self._var_dict: return self._var_dict[(otherframe, Vector.simp)] else: vars_matrix = self.dcm(otherframe) * Matrix(otherframe.varlist) mapping = {} for i, x in enumerate(self): if Vector.simp: mapping[self.varlist[i]] = trigsimp(vars_matrix[i], method='fu') else: mapping[self.varlist[i]] = vars_matrix[i] self._var_dict[(otherframe, Vector.simp)] = mapping return mapping def ang_acc_in(self, otherframe): """Returns the angular acceleration Vector of the ReferenceFrame. Effectively returns the Vector: ``N_alpha_B`` which represent the angular acceleration of B in N, where B is self, and N is otherframe. Parameters ========== otherframe : ReferenceFrame The ReferenceFrame which the angular acceleration is returned in. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> V = 10 * N.x >>> A.set_ang_acc(N, V) >>> A.ang_acc_in(N) 10*N.x """ _check_frame(otherframe) if otherframe in self._ang_acc_dict: return self._ang_acc_dict[otherframe] else: return self.ang_vel_in(otherframe).dt(otherframe) def ang_vel_in(self, otherframe): """Returns the angular velocity Vector of the ReferenceFrame. Effectively returns the Vector: ^N omega ^B which represent the angular velocity of B in N, where B is self, and N is otherframe. Parameters ========== otherframe : ReferenceFrame The ReferenceFrame which the angular velocity is returned in. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> V = 10 * N.x >>> A.set_ang_vel(N, V) >>> A.ang_vel_in(N) 10*N.x """ _check_frame(otherframe) flist = self._dict_list(otherframe, 1) outvec = Vector(0) for i in range(len(flist) - 1): outvec += flist[i]._ang_vel_dict[flist[i + 1]] return outvec def dcm(self, otherframe): r"""Returns the direction cosine matrix of this reference frame relative to the provided reference frame. The returned matrix can be used to express the orthogonal unit vectors of this frame in terms of the orthogonal unit vectors of ``otherframe``. Parameters ========== otherframe : ReferenceFrame The reference frame which the direction cosine matrix of this frame is formed relative to. Examples ======== The following example rotates the reference frame A relative to N by a simple rotation and then calculates the direction cosine matrix of N relative to A. >>> from sympy import symbols, sin, cos >>> from sympy.physics.vector import ReferenceFrame >>> q1 = symbols('q1') >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> A.orient_axis(N, q1, N.x) >>> N.dcm(A) Matrix([ [1, 0, 0], [0, cos(q1), -sin(q1)], [0, sin(q1), cos(q1)]]) The second row of the above direction cosine matrix represents the ``N.y`` unit vector in N expressed in A. Like so: >>> Ny = 0*A.x + cos(q1)*A.y - sin(q1)*A.z Thus, expressing ``N.y`` in A should return the same result: >>> N.y.express(A) cos(q1)*A.y - sin(q1)*A.z Notes ===== It is important to know what form of the direction cosine matrix is returned. If ``B.dcm(A)`` is called, it means the "direction cosine matrix of B rotated relative to A". This is the matrix :math:`{}^B\mathbf{C}^A` shown in the following relationship: .. math:: \begin{bmatrix} \hat{\mathbf{b}}_1 \\ \hat{\mathbf{b}}_2 \\ \hat{\mathbf{b}}_3 \end{bmatrix} = {}^B\mathbf{C}^A \begin{bmatrix} \hat{\mathbf{a}}_1 \\ \hat{\mathbf{a}}_2 \\ \hat{\mathbf{a}}_3 \end{bmatrix}. :math:`{}^B\mathbf{C}^A` is the matrix that expresses the B unit vectors in terms of the A unit vectors. """ _check_frame(otherframe) # Check if the dcm wrt that frame has already been calculated if otherframe in self._dcm_cache: return self._dcm_cache[otherframe] flist = self._dict_list(otherframe, 0) outdcm = eye(3) for i in range(len(flist) - 1): outdcm = outdcm * flist[i]._dcm_dict[flist[i + 1]] # After calculation, store the dcm in dcm cache for faster future # retrieval self._dcm_cache[otherframe] = outdcm otherframe._dcm_cache[self] = outdcm.T return outdcm def _dcm(self, parent, parent_orient): # If parent.oreint(self) is already defined,then # update the _dcm_dict of parent while over write # all content of self._dcm_dict and self._dcm_cache # with new dcm relation. # Else update _dcm_cache and _dcm_dict of both # self and parent. frames = self._dcm_cache.keys() dcm_dict_del = [] dcm_cache_del = [] if parent in frames: for frame in frames: if frame in self._dcm_dict: dcm_dict_del += [frame] dcm_cache_del += [frame] # Reset the _dcm_cache of this frame, and remove it from the # _dcm_caches of the frames it is linked to. Also remove it from # the _dcm_dict of its parent for frame in dcm_dict_del: del frame._dcm_dict[self] for frame in dcm_cache_del: del frame._dcm_cache[self] # Reset the _dcm_dict self._dcm_dict = self._dlist[0] = {} # Reset the _dcm_cache self._dcm_cache = {} else: # Check for loops and raise warning accordingly. visited = [] queue = list(frames) cont = True # Flag to control queue loop. while queue and cont: node = queue.pop(0) if node not in visited: visited.append(node) neighbors = node._dcm_dict.keys() for neighbor in neighbors: if neighbor == parent: warn('Loops are defined among the orientation of ' 'frames. This is likely not desired and may ' 'cause errors in your calculations.') cont = False break queue.append(neighbor) # Add the dcm relationship to _dcm_dict self._dcm_dict.update({parent: parent_orient.T}) parent._dcm_dict.update({self: parent_orient}) # Update the dcm cache self._dcm_cache.update({parent: parent_orient.T}) parent._dcm_cache.update({self: parent_orient}) def orient_axis(self, parent, axis, angle): """Sets the orientation of this reference frame with respect to a parent reference frame by rotating through an angle about an axis fixed in the parent reference frame. Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. axis : Vector Vector fixed in the parent frame about about which this frame is rotated. It need not be a unit vector and the rotation follows the right hand rule. angle : sympifiable Angle in radians by which it the frame is to be rotated. Warns ====== UserWarning If the orientation creates a kinematic loop. Examples ======== Setup variables for the examples: >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame >>> q1 = symbols('q1') >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B.orient_axis(N, N.x, q1) The ``orient_axis()`` method generates a direction cosine matrix and its transpose which defines the orientation of B relative to N and vice versa. Once orient is called, ``dcm()`` outputs the appropriate direction cosine matrix: >>> B.dcm(N) Matrix([ [1, 0, 0], [0, cos(q1), sin(q1)], [0, -sin(q1), cos(q1)]]) >>> N.dcm(B) Matrix([ [1, 0, 0], [0, cos(q1), -sin(q1)], [0, sin(q1), cos(q1)]]) The following two lines show that the sense of the rotation can be defined by negating the vector direction or the angle. Both lines produce the same result. >>> B.orient_axis(N, -N.x, q1) >>> B.orient_axis(N, N.x, -q1) """ from sympy.physics.vector.functions import dynamicsymbols _check_frame(parent) if not isinstance(axis, Vector) and isinstance(angle, Vector): axis, angle = angle, axis axis = _check_vector(axis) theta = sympify(angle) if not axis.dt(parent) == 0: raise ValueError('Axis cannot be time-varying.') unit_axis = axis.express(parent).normalize() unit_col = unit_axis.args[0][0] parent_orient_axis = ( (eye(3) - unit_col * unit_col.T) * cos(theta) + Matrix([[0, -unit_col[2], unit_col[1]], [unit_col[2], 0, -unit_col[0]], [-unit_col[1], unit_col[0], 0]]) * sin(theta) + unit_col * unit_col.T) self._dcm(parent, parent_orient_axis) thetad = (theta).diff(dynamicsymbols._t) wvec = thetad*axis.express(parent).normalize() self._ang_vel_dict.update({parent: wvec}) parent._ang_vel_dict.update({self: -wvec}) self._var_dict = {} def orient_explicit(self, parent, dcm): """Sets the orientation of this reference frame relative to a parent reference frame by explicitly setting the direction cosine matrix. Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. dcm : Matrix, shape(3, 3) Direction cosine matrix that specifies the relative rotation between the two reference frames. Warns ====== UserWarning If the orientation creates a kinematic loop. Examples ======== Setup variables for the examples: >>> from sympy import symbols, Matrix, sin, cos >>> from sympy.physics.vector import ReferenceFrame >>> q1 = symbols('q1') >>> A = ReferenceFrame('A') >>> B = ReferenceFrame('B') >>> N = ReferenceFrame('N') A simple rotation of ``A`` relative to ``N`` about ``N.x`` is defined by the following direction cosine matrix: >>> dcm = Matrix([[1, 0, 0], ... [0, cos(q1), -sin(q1)], ... [0, sin(q1), cos(q1)]]) >>> A.orient_explicit(N, dcm) >>> A.dcm(N) Matrix([ [1, 0, 0], [0, cos(q1), sin(q1)], [0, -sin(q1), cos(q1)]]) This is equivalent to using ``orient_axis()``: >>> B.orient_axis(N, N.x, q1) >>> B.dcm(N) Matrix([ [1, 0, 0], [0, cos(q1), sin(q1)], [0, -sin(q1), cos(q1)]]) **Note carefully that** ``N.dcm(B)`` **(the transpose) would be passed into** ``orient_explicit()`` **for** ``A.dcm(N)`` **to match** ``B.dcm(N)``: >>> A.orient_explicit(N, N.dcm(B)) >>> A.dcm(N) Matrix([ [1, 0, 0], [0, cos(q1), sin(q1)], [0, -sin(q1), cos(q1)]]) """ _check_frame(parent) # amounts must be a Matrix type object # (e.g. sympy.matrices.dense.MutableDenseMatrix). if not isinstance(dcm, MatrixBase): raise TypeError("Amounts must be a SymPy Matrix type object.") parent_orient_dcm = dcm self._dcm(parent, parent_orient_dcm) wvec = self._w_diff_dcm(parent) self._ang_vel_dict.update({parent: wvec}) parent._ang_vel_dict.update({self: -wvec}) self._var_dict = {} def _rot(self, axis, angle): """DCM for simple axis 1,2,or 3 rotations.""" if axis == 1: return Matrix([[1, 0, 0], [0, cos(angle), -sin(angle)], [0, sin(angle), cos(angle)]]) elif axis == 2: return Matrix([[cos(angle), 0, sin(angle)], [0, 1, 0], [-sin(angle), 0, cos(angle)]]) elif axis == 3: return Matrix([[cos(angle), -sin(angle), 0], [sin(angle), cos(angle), 0], [0, 0, 1]]) def _parse_consecutive_rotations(self, angles, rotation_order): """Helper for orient_body_fixed and orient_space_fixed. Parameters ========== angles : 3-tuple of sympifiable Three angles in radians used for the successive rotations. rotation_order : 3 character string or 3 digit integer Order of the rotations. The order can be specified by the strings ``'XZX'``, ``'131'``, or the integer ``131``. There are 12 unique valid rotation orders. Returns ======= amounts : list List of sympifiables corresponding to the rotation angles. rot_order : list List of integers corresponding to the axis of rotation. rot_matrices : list List of DCM around the given axis with corresponding magnitude. """ amounts = list(angles) for i, v in enumerate(amounts): if not isinstance(v, Vector): amounts[i] = sympify(v) approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131', '212', '232', '313', '323', '') # make sure XYZ => 123 rot_order = translate(str(rotation_order), 'XYZxyz', '123123') if rot_order not in approved_orders: raise TypeError('The rotation order is not a valid order.') rot_order = [int(r) for r in rot_order] if not (len(amounts) == 3 & len(rot_order) == 3): raise TypeError('Body orientation takes 3 values & 3 orders') rot_matrices = [self._rot(order, amount) for (order, amount) in zip(rot_order, amounts)] return amounts, rot_order, rot_matrices def orient_body_fixed(self, parent, angles, rotation_order): """Rotates this reference frame relative to the parent reference frame by right hand rotating through three successive body fixed simple axis rotations. Each subsequent axis of rotation is about the "body fixed" unit vectors of a new intermediate reference frame. This type of rotation is also referred to rotating through the `Euler and Tait-Bryan Angles`_. .. _Euler and Tait-Bryan Angles: https://en.wikipedia.org/wiki/Euler_angles The computed angular velocity in this method is by default expressed in the child's frame, so it is most preferable to use ``u1 * child.x + u2 * child.y + u3 * child.z`` as generalized speeds. Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. angles : 3-tuple of sympifiable Three angles in radians used for the successive rotations. rotation_order : 3 character string or 3 digit integer Order of the rotations about each intermediate reference frames' unit vectors. The Euler rotation about the X, Z', X'' axes can be specified by the strings ``'XZX'``, ``'131'``, or the integer ``131``. There are 12 unique valid rotation orders (6 Euler and 6 Tait-Bryan): zxz, xyx, yzy, zyz, xzx, yxy, xyz, yzx, zxy, xzy, zyx, and yxz. Warns ====== UserWarning If the orientation creates a kinematic loop. Examples ======== Setup variables for the examples: >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame >>> q1, q2, q3 = symbols('q1, q2, q3') >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B1 = ReferenceFrame('B1') >>> B2 = ReferenceFrame('B2') >>> B3 = ReferenceFrame('B3') For example, a classic Euler Angle rotation can be done by: >>> B.orient_body_fixed(N, (q1, q2, q3), 'XYX') >>> B.dcm(N) Matrix([ [ cos(q2), sin(q1)*sin(q2), -sin(q2)*cos(q1)], [sin(q2)*sin(q3), -sin(q1)*sin(q3)*cos(q2) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q3)*cos(q1)*cos(q2)], [sin(q2)*cos(q3), -sin(q1)*cos(q2)*cos(q3) - sin(q3)*cos(q1), -sin(q1)*sin(q3) + cos(q1)*cos(q2)*cos(q3)]]) This rotates reference frame B relative to reference frame N through ``q1`` about ``N.x``, then rotates B again through ``q2`` about ``B.y``, and finally through ``q3`` about ``B.x``. It is equivalent to three successive ``orient_axis()`` calls: >>> B1.orient_axis(N, N.x, q1) >>> B2.orient_axis(B1, B1.y, q2) >>> B3.orient_axis(B2, B2.x, q3) >>> B3.dcm(N) Matrix([ [ cos(q2), sin(q1)*sin(q2), -sin(q2)*cos(q1)], [sin(q2)*sin(q3), -sin(q1)*sin(q3)*cos(q2) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q3)*cos(q1)*cos(q2)], [sin(q2)*cos(q3), -sin(q1)*cos(q2)*cos(q3) - sin(q3)*cos(q1), -sin(q1)*sin(q3) + cos(q1)*cos(q2)*cos(q3)]]) Acceptable rotation orders are of length 3, expressed in as a string ``'XYZ'`` or ``'123'`` or integer ``123``. Rotations about an axis twice in a row are prohibited. >>> B.orient_body_fixed(N, (q1, q2, 0), 'ZXZ') >>> B.orient_body_fixed(N, (q1, q2, 0), '121') >>> B.orient_body_fixed(N, (q1, q2, q3), 123) """ from sympy.physics.vector.functions import dynamicsymbols _check_frame(parent) amounts, rot_order, rot_matrices = self._parse_consecutive_rotations( angles, rotation_order) self._dcm(parent, rot_matrices[0] * rot_matrices[1] * rot_matrices[2]) rot_vecs = [zeros(3, 1) for _ in range(3)] for i, order in enumerate(rot_order): rot_vecs[i][order - 1] = amounts[i].diff(dynamicsymbols._t) u1, u2, u3 = rot_vecs[2] + rot_matrices[2].T * ( rot_vecs[1] + rot_matrices[1].T * rot_vecs[0]) wvec = u1 * self.x + u2 * self.y + u3 * self.z # There is a double - self._ang_vel_dict.update({parent: wvec}) parent._ang_vel_dict.update({self: -wvec}) self._var_dict = {} def orient_space_fixed(self, parent, angles, rotation_order): """Rotates this reference frame relative to the parent reference frame by right hand rotating through three successive space fixed simple axis rotations. Each subsequent axis of rotation is about the "space fixed" unit vectors of the parent reference frame. The computed angular velocity in this method is by default expressed in the child's frame, so it is most preferable to use ``u1 * child.x + u2 * child.y + u3 * child.z`` as generalized speeds. Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. angles : 3-tuple of sympifiable Three angles in radians used for the successive rotations. rotation_order : 3 character string or 3 digit integer Order of the rotations about the parent reference frame's unit vectors. The order can be specified by the strings ``'XZX'``, ``'131'``, or the integer ``131``. There are 12 unique valid rotation orders. Warns ====== UserWarning If the orientation creates a kinematic loop. Examples ======== Setup variables for the examples: >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame >>> q1, q2, q3 = symbols('q1, q2, q3') >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B1 = ReferenceFrame('B1') >>> B2 = ReferenceFrame('B2') >>> B3 = ReferenceFrame('B3') >>> B.orient_space_fixed(N, (q1, q2, q3), '312') >>> B.dcm(N) Matrix([ [ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1)], [-sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3)], [ sin(q3)*cos(q2), -sin(q2), cos(q2)*cos(q3)]]) is equivalent to: >>> B1.orient_axis(N, N.z, q1) >>> B2.orient_axis(B1, N.x, q2) >>> B3.orient_axis(B2, N.y, q3) >>> B3.dcm(N).simplify() Matrix([ [ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1)], [-sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3)], [ sin(q3)*cos(q2), -sin(q2), cos(q2)*cos(q3)]]) It is worth noting that space-fixed and body-fixed rotations are related by the order of the rotations, i.e. the reverse order of body fixed will give space fixed and vice versa. >>> B.orient_space_fixed(N, (q1, q2, q3), '231') >>> B.dcm(N) Matrix([ [cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), -sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)], [ -sin(q2), cos(q2)*cos(q3), sin(q3)*cos(q2)], [sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3)]]) >>> B.orient_body_fixed(N, (q3, q2, q1), '132') >>> B.dcm(N) Matrix([ [cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), -sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)], [ -sin(q2), cos(q2)*cos(q3), sin(q3)*cos(q2)], [sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3)]]) """ from sympy.physics.vector.functions import dynamicsymbols _check_frame(parent) amounts, rot_order, rot_matrices = self._parse_consecutive_rotations( angles, rotation_order) self._dcm(parent, rot_matrices[2] * rot_matrices[1] * rot_matrices[0]) rot_vecs = [zeros(3, 1) for _ in range(3)] for i, order in enumerate(rot_order): rot_vecs[i][order - 1] = amounts[i].diff(dynamicsymbols._t) u1, u2, u3 = rot_vecs[0] + rot_matrices[0].T * ( rot_vecs[1] + rot_matrices[1].T * rot_vecs[2]) wvec = u1 * self.x + u2 * self.y + u3 * self.z # There is a double - self._ang_vel_dict.update({parent: wvec}) parent._ang_vel_dict.update({self: -wvec}) self._var_dict = {} def orient_quaternion(self, parent, numbers): """Sets the orientation of this reference frame relative to a parent reference frame via an orientation quaternion. An orientation quaternion is defined as a finite rotation a unit vector, ``(lambda_x, lambda_y, lambda_z)``, by an angle ``theta``. The orientation quaternion is described by four parameters: - ``q0 = cos(theta/2)`` - ``q1 = lambda_x*sin(theta/2)`` - ``q2 = lambda_y*sin(theta/2)`` - ``q3 = lambda_z*sin(theta/2)`` See `Quaternions and Spatial Rotation <https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation>`_ on Wikipedia for more information. Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. numbers : 4-tuple of sympifiable The four quaternion scalar numbers as defined above: ``q0``, ``q1``, ``q2``, ``q3``. Warns ====== UserWarning If the orientation creates a kinematic loop. Examples ======== Setup variables for the examples: >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame >>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3') >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') Set the orientation: >>> B.orient_quaternion(N, (q0, q1, q2, q3)) >>> B.dcm(N) Matrix([ [q0**2 + q1**2 - q2**2 - q3**2, 2*q0*q3 + 2*q1*q2, -2*q0*q2 + 2*q1*q3], [ -2*q0*q3 + 2*q1*q2, q0**2 - q1**2 + q2**2 - q3**2, 2*q0*q1 + 2*q2*q3], [ 2*q0*q2 + 2*q1*q3, -2*q0*q1 + 2*q2*q3, q0**2 - q1**2 - q2**2 + q3**2]]) """ from sympy.physics.vector.functions import dynamicsymbols _check_frame(parent) numbers = list(numbers) for i, v in enumerate(numbers): if not isinstance(v, Vector): numbers[i] = sympify(v) if not (isinstance(numbers, (list, tuple)) & (len(numbers) == 4)): raise TypeError('Amounts are a list or tuple of length 4') q0, q1, q2, q3 = numbers parent_orient_quaternion = ( Matrix([[q0**2 + q1**2 - q2**2 - q3**2, 2 * (q1 * q2 - q0 * q3), 2 * (q0 * q2 + q1 * q3)], [2 * (q1 * q2 + q0 * q3), q0**2 - q1**2 + q2**2 - q3**2, 2 * (q2 * q3 - q0 * q1)], [2 * (q1 * q3 - q0 * q2), 2 * (q0 * q1 + q2 * q3), q0**2 - q1**2 - q2**2 + q3**2]])) self._dcm(parent, parent_orient_quaternion) t = dynamicsymbols._t q0, q1, q2, q3 = numbers q0d = diff(q0, t) q1d = diff(q1, t) q2d = diff(q2, t) q3d = diff(q3, t) w1 = 2 * (q1d * q0 + q2d * q3 - q3d * q2 - q0d * q1) w2 = 2 * (q2d * q0 + q3d * q1 - q1d * q3 - q0d * q2) w3 = 2 * (q3d * q0 + q1d * q2 - q2d * q1 - q0d * q3) wvec = Vector([(Matrix([w1, w2, w3]), self)]) self._ang_vel_dict.update({parent: wvec}) parent._ang_vel_dict.update({self: -wvec}) self._var_dict = {} def orient(self, parent, rot_type, amounts, rot_order=''): """Sets the orientation of this reference frame relative to another (parent) reference frame. .. note:: It is now recommended to use the ``.orient_axis, .orient_body_fixed, .orient_space_fixed, .orient_quaternion`` methods for the different rotation types. Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. rot_type : str The method used to generate the direction cosine matrix. Supported methods are: - ``'Axis'``: simple rotations about a single common axis - ``'DCM'``: for setting the direction cosine matrix directly - ``'Body'``: three successive rotations about new intermediate axes, also called "Euler and Tait-Bryan angles" - ``'Space'``: three successive rotations about the parent frames' unit vectors - ``'Quaternion'``: rotations defined by four parameters which result in a singularity free direction cosine matrix amounts : Expressions defining the rotation angles or direction cosine matrix. These must match the ``rot_type``. See examples below for details. The input types are: - ``'Axis'``: 2-tuple (expr/sym/func, Vector) - ``'DCM'``: Matrix, shape(3,3) - ``'Body'``: 3-tuple of expressions, symbols, or functions - ``'Space'``: 3-tuple of expressions, symbols, or functions - ``'Quaternion'``: 4-tuple of expressions, symbols, or functions rot_order : str or int, optional If applicable, the order of the successive of rotations. The string ``'123'`` and integer ``123`` are equivalent, for example. Required for ``'Body'`` and ``'Space'``. Warns ====== UserWarning If the orientation creates a kinematic loop. """ _check_frame(parent) approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131', '212', '232', '313', '323', '') rot_order = translate(str(rot_order), 'XYZxyz', '123123') rot_type = rot_type.upper() if rot_order not in approved_orders: raise TypeError('The supplied order is not an approved type') if rot_type == 'AXIS': self.orient_axis(parent, amounts[1], amounts[0]) elif rot_type == 'DCM': self.orient_explicit(parent, amounts) elif rot_type == 'BODY': self.orient_body_fixed(parent, amounts, rot_order) elif rot_type == 'SPACE': self.orient_space_fixed(parent, amounts, rot_order) elif rot_type == 'QUATERNION': self.orient_quaternion(parent, amounts) else: raise NotImplementedError('That is not an implemented rotation') def orientnew(self, newname, rot_type, amounts, rot_order='', variables=None, indices=None, latexs=None): r"""Returns a new reference frame oriented with respect to this reference frame. See ``ReferenceFrame.orient()`` for detailed examples of how to orient reference frames. Parameters ========== newname : str Name for the new reference frame. rot_type : str The method used to generate the direction cosine matrix. Supported methods are: - ``'Axis'``: simple rotations about a single common axis - ``'DCM'``: for setting the direction cosine matrix directly - ``'Body'``: three successive rotations about new intermediate axes, also called "Euler and Tait-Bryan angles" - ``'Space'``: three successive rotations about the parent frames' unit vectors - ``'Quaternion'``: rotations defined by four parameters which result in a singularity free direction cosine matrix amounts : Expressions defining the rotation angles or direction cosine matrix. These must match the ``rot_type``. See examples below for details. The input types are: - ``'Axis'``: 2-tuple (expr/sym/func, Vector) - ``'DCM'``: Matrix, shape(3,3) - ``'Body'``: 3-tuple of expressions, symbols, or functions - ``'Space'``: 3-tuple of expressions, symbols, or functions - ``'Quaternion'``: 4-tuple of expressions, symbols, or functions rot_order : str or int, optional If applicable, the order of the successive of rotations. The string ``'123'`` and integer ``123`` are equivalent, for example. Required for ``'Body'`` and ``'Space'``. indices : tuple of str Enables the reference frame's basis unit vectors to be accessed by Python's square bracket indexing notation using the provided three indice strings and alters the printing of the unit vectors to reflect this choice. latexs : tuple of str Alters the LaTeX printing of the reference frame's basis unit vectors to the provided three valid LaTeX strings. Examples ======== >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame, vlatex >>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3') >>> N = ReferenceFrame('N') Create a new reference frame A rotated relative to N through a simple rotation. >>> A = N.orientnew('A', 'Axis', (q0, N.x)) Create a new reference frame B rotated relative to N through body-fixed rotations. >>> B = N.orientnew('B', 'Body', (q1, q2, q3), '123') Create a new reference frame C rotated relative to N through a simple rotation with unique indices and LaTeX printing. >>> C = N.orientnew('C', 'Axis', (q0, N.x), indices=('1', '2', '3'), ... latexs=(r'\hat{\mathbf{c}}_1',r'\hat{\mathbf{c}}_2', ... r'\hat{\mathbf{c}}_3')) >>> C['1'] C['1'] >>> print(vlatex(C['1'])) \hat{\mathbf{c}}_1 """ newframe = self.__class__(newname, variables=variables, indices=indices, latexs=latexs) approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131', '212', '232', '313', '323', '') rot_order = translate(str(rot_order), 'XYZxyz', '123123') rot_type = rot_type.upper() if rot_order not in approved_orders: raise TypeError('The supplied order is not an approved type') if rot_type == 'AXIS': newframe.orient_axis(self, amounts[1], amounts[0]) elif rot_type == 'DCM': newframe.orient_explicit(self, amounts) elif rot_type == 'BODY': newframe.orient_body_fixed(self, amounts, rot_order) elif rot_type == 'SPACE': newframe.orient_space_fixed(self, amounts, rot_order) elif rot_type == 'QUATERNION': newframe.orient_quaternion(self, amounts) else: raise NotImplementedError('That is not an implemented rotation') return newframe def set_ang_acc(self, otherframe, value): """Define the angular acceleration Vector in a ReferenceFrame. Defines the angular acceleration of this ReferenceFrame, in another. Angular acceleration can be defined with respect to multiple different ReferenceFrames. Care must be taken to not create loops which are inconsistent. Parameters ========== otherframe : ReferenceFrame A ReferenceFrame to define the angular acceleration in value : Vector The Vector representing angular acceleration Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> V = 10 * N.x >>> A.set_ang_acc(N, V) >>> A.ang_acc_in(N) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) _check_frame(otherframe) self._ang_acc_dict.update({otherframe: value}) otherframe._ang_acc_dict.update({self: -value}) def set_ang_vel(self, otherframe, value): """Define the angular velocity vector in a ReferenceFrame. Defines the angular velocity of this ReferenceFrame, in another. Angular velocity can be defined with respect to multiple different ReferenceFrames. Care must be taken to not create loops which are inconsistent. Parameters ========== otherframe : ReferenceFrame A ReferenceFrame to define the angular velocity in value : Vector The Vector representing angular velocity Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> V = 10 * N.x >>> A.set_ang_vel(N, V) >>> A.ang_vel_in(N) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) _check_frame(otherframe) self._ang_vel_dict.update({otherframe: value}) otherframe._ang_vel_dict.update({self: -value}) @property def x(self): """The basis Vector for the ReferenceFrame, in the x direction. """ return self._x @property def y(self): """The basis Vector for the ReferenceFrame, in the y direction. """ return self._y @property def z(self): """The basis Vector for the ReferenceFrame, in the z direction. """ return self._z def partial_velocity(self, frame, *gen_speeds): """Returns the partial angular velocities of this frame in the given frame with respect to one or more provided generalized speeds. Parameters ========== frame : ReferenceFrame The frame with which the angular velocity is defined in. gen_speeds : functions of time The generalized speeds. Returns ======= partial_velocities : tuple of Vector The partial angular velocity vectors corresponding to the provided generalized speeds. Examples ======== >>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> u1, u2 = dynamicsymbols('u1, u2') >>> A.set_ang_vel(N, u1 * A.x + u2 * N.y) >>> A.partial_velocity(N, u1) A.x >>> A.partial_velocity(N, u1, u2) (A.x, N.y) """ partials = [self.ang_vel_in(frame).diff(speed, frame, var_in_dcm=False) for speed in gen_speeds] if len(partials) == 1: return partials[0] else: return tuple(partials) def _check_frame(other): from .vector import VectorTypeError if not isinstance(other, ReferenceFrame): raise VectorTypeError(other, ReferenceFrame('A'))
988ad988e5577ad1ad2a42f197c2e569fd99f5ca167a77fa24aac2961e16f325
#!/usr/bin/env python # -*- coding: utf-8 -*- """ The module implements routines to model the polarization of optical fields and can be used to calculate the effects of polarization optical elements on the fields. - Jones vectors. - Stokes vectors. - Jones matrices. - Mueller matrices. Examples ======== We calculate a generic Jones vector: >>> from sympy import symbols, pprint, zeros, simplify >>> from sympy.physics.optics.polarization import (jones_vector, stokes_vector, ... half_wave_retarder, polarizing_beam_splitter, jones_2_stokes) >>> psi, chi, p, I0 = symbols("psi, chi, p, I0", real=True) >>> x0 = jones_vector(psi, chi) >>> pprint(x0, use_unicode=True) ⎑-β…ˆβ‹…sin(Ο‡)β‹…sin(ψ) + cos(Ο‡)β‹…cos(ψ)⎀ ⎒ βŽ₯ βŽ£β…ˆβ‹…sin(Ο‡)β‹…cos(ψ) + sin(ψ)β‹…cos(Ο‡) ⎦ And the more general Stokes vector: >>> s0 = stokes_vector(psi, chi, p, I0) >>> pprint(s0, use_unicode=True) ⎑ Iβ‚€ ⎀ ⎒ βŽ₯ ⎒Iβ‚€β‹…pβ‹…cos(2β‹…Ο‡)β‹…cos(2β‹…Οˆ)βŽ₯ ⎒ βŽ₯ ⎒Iβ‚€β‹…pβ‹…sin(2β‹…Οˆ)β‹…cos(2β‹…Ο‡)βŽ₯ ⎒ βŽ₯ ⎣ Iβ‚€β‹…pβ‹…sin(2β‹…Ο‡) ⎦ We calculate how the Jones vector is modified by a half-wave plate: >>> alpha = symbols("alpha", real=True) >>> HWP = half_wave_retarder(alpha) >>> x1 = simplify(HWP*x0) We calculate the very common operation of passing a beam through a half-wave plate and then through a polarizing beam-splitter. We do this by putting this Jones vector as the first entry of a two-Jones-vector state that is transformed by a 4x4 Jones matrix modelling the polarizing beam-splitter to get the transmitted and reflected Jones vectors: >>> PBS = polarizing_beam_splitter() >>> X1 = zeros(4, 1) >>> X1[:2, :] = x1 >>> X2 = PBS*X1 >>> transmitted_port = X2[:2, :] >>> reflected_port = X2[2:, :] This allows us to calculate how the power in both ports depends on the initial polarization: >>> transmitted_power = jones_2_stokes(transmitted_port)[0] >>> reflected_power = jones_2_stokes(reflected_port)[0] >>> print(transmitted_power) cos(-2*alpha + chi + psi)**2/2 + cos(2*alpha + chi - psi)**2/2 >>> print(reflected_power) sin(-2*alpha + chi + psi)**2/2 + sin(2*alpha + chi - psi)**2/2 Please see the description of the individual functions for further details and examples. References ========== .. [1] https://en.wikipedia.org/wiki/Jones_calculus .. [2] https://en.wikipedia.org/wiki/Mueller_calculus .. [3] https://en.wikipedia.org/wiki/Stokes_parameters """ from sympy.core.numbers import (I, pi) from sympy.functions.elementary.complexes import (Abs, im, re) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.matrices.dense import Matrix from sympy.simplify.simplify import simplify from sympy.physics.quantum import TensorProduct def jones_vector(psi, chi): """A Jones vector corresponding to a polarization ellipse with `psi` tilt, and `chi` circularity. Parameters ========== psi : numeric type or SymPy Symbol The tilt of the polarization relative to the `x` axis. chi : numeric type or SymPy Symbol The angle adjacent to the mayor axis of the polarization ellipse. Returns ======= Matrix : A Jones vector. Examples ======== The axes on the PoincarΓ© sphere. >>> from sympy import pprint, symbols, pi >>> from sympy.physics.optics.polarization import jones_vector >>> psi, chi = symbols("psi, chi", real=True) A general Jones vector. >>> pprint(jones_vector(psi, chi), use_unicode=True) ⎑-β…ˆβ‹…sin(Ο‡)β‹…sin(ψ) + cos(Ο‡)β‹…cos(ψ)⎀ ⎒ βŽ₯ βŽ£β…ˆβ‹…sin(Ο‡)β‹…cos(ψ) + sin(ψ)β‹…cos(Ο‡) ⎦ Horizontal polarization. >>> pprint(jones_vector(0, 0), use_unicode=True) ⎑1⎀ ⎒ βŽ₯ ⎣0⎦ Vertical polarization. >>> pprint(jones_vector(pi/2, 0), use_unicode=True) ⎑0⎀ ⎒ βŽ₯ ⎣1⎦ Diagonal polarization. >>> pprint(jones_vector(pi/4, 0), use_unicode=True) ⎑√2⎀ βŽ’β”€β”€βŽ₯ ⎒2 βŽ₯ ⎒ βŽ₯ ⎒√2βŽ₯ βŽ’β”€β”€βŽ₯ ⎣2 ⎦ Anti-diagonal polarization. >>> pprint(jones_vector(-pi/4, 0), use_unicode=True) ⎑ √2 ⎀ ⎒ ── βŽ₯ ⎒ 2 βŽ₯ ⎒ βŽ₯ ⎒-√2 βŽ₯ βŽ’β”€β”€β”€β”€βŽ₯ ⎣ 2 ⎦ Right-hand circular polarization. >>> pprint(jones_vector(0, pi/4), use_unicode=True) ⎑ √2 ⎀ ⎒ ── βŽ₯ ⎒ 2 βŽ₯ ⎒ βŽ₯ ⎒√2β‹…β…ˆβŽ₯ βŽ’β”€β”€β”€β”€βŽ₯ ⎣ 2 ⎦ Left-hand circular polarization. >>> pprint(jones_vector(0, -pi/4), use_unicode=True) ⎑ √2 ⎀ ⎒ ── βŽ₯ ⎒ 2 βŽ₯ ⎒ βŽ₯ ⎒-√2β‹…β…ˆ βŽ₯ βŽ’β”€β”€β”€β”€β”€β”€βŽ₯ ⎣ 2 ⎦ """ return Matrix([-I*sin(chi)*sin(psi) + cos(chi)*cos(psi), I*sin(chi)*cos(psi) + sin(psi)*cos(chi)]) def stokes_vector(psi, chi, p=1, I=1): """A Stokes vector corresponding to a polarization ellipse with ``psi`` tilt, and ``chi`` circularity. Parameters ========== psi : numeric type or SymPy Symbol The tilt of the polarization relative to the ``x`` axis. chi : numeric type or SymPy Symbol The angle adjacent to the mayor axis of the polarization ellipse. p : numeric type or SymPy Symbol The degree of polarization. I : numeric type or SymPy Symbol The intensity of the field. Returns ======= Matrix : A Stokes vector. Examples ======== The axes on the PoincarΓ© sphere. >>> from sympy import pprint, symbols, pi >>> from sympy.physics.optics.polarization import stokes_vector >>> psi, chi, p, I = symbols("psi, chi, p, I", real=True) >>> pprint(stokes_vector(psi, chi, p, I), use_unicode=True) ⎑ I ⎀ ⎒ βŽ₯ ⎒Iβ‹…pβ‹…cos(2β‹…Ο‡)β‹…cos(2β‹…Οˆ)βŽ₯ ⎒ βŽ₯ ⎒Iβ‹…pβ‹…sin(2β‹…Οˆ)β‹…cos(2β‹…Ο‡)βŽ₯ ⎒ βŽ₯ ⎣ Iβ‹…pβ‹…sin(2β‹…Ο‡) ⎦ Horizontal polarization >>> pprint(stokes_vector(0, 0), use_unicode=True) ⎑1⎀ ⎒ βŽ₯ ⎒1βŽ₯ ⎒ βŽ₯ ⎒0βŽ₯ ⎒ βŽ₯ ⎣0⎦ Vertical polarization >>> pprint(stokes_vector(pi/2, 0), use_unicode=True) ⎑1 ⎀ ⎒ βŽ₯ ⎒-1βŽ₯ ⎒ βŽ₯ ⎒0 βŽ₯ ⎒ βŽ₯ ⎣0 ⎦ Diagonal polarization >>> pprint(stokes_vector(pi/4, 0), use_unicode=True) ⎑1⎀ ⎒ βŽ₯ ⎒0βŽ₯ ⎒ βŽ₯ ⎒1βŽ₯ ⎒ βŽ₯ ⎣0⎦ Anti-diagonal polarization >>> pprint(stokes_vector(-pi/4, 0), use_unicode=True) ⎑1 ⎀ ⎒ βŽ₯ ⎒0 βŽ₯ ⎒ βŽ₯ ⎒-1βŽ₯ ⎒ βŽ₯ ⎣0 ⎦ Right-hand circular polarization >>> pprint(stokes_vector(0, pi/4), use_unicode=True) ⎑1⎀ ⎒ βŽ₯ ⎒0βŽ₯ ⎒ βŽ₯ ⎒0βŽ₯ ⎒ βŽ₯ ⎣1⎦ Left-hand circular polarization >>> pprint(stokes_vector(0, -pi/4), use_unicode=True) ⎑1 ⎀ ⎒ βŽ₯ ⎒0 βŽ₯ ⎒ βŽ₯ ⎒0 βŽ₯ ⎒ βŽ₯ ⎣-1⎦ Unpolarized light >>> pprint(stokes_vector(0, 0, 0), use_unicode=True) ⎑1⎀ ⎒ βŽ₯ ⎒0βŽ₯ ⎒ βŽ₯ ⎒0βŽ₯ ⎒ βŽ₯ ⎣0⎦ """ S0 = I S1 = I*p*cos(2*psi)*cos(2*chi) S2 = I*p*sin(2*psi)*cos(2*chi) S3 = I*p*sin(2*chi) return Matrix([S0, S1, S2, S3]) def jones_2_stokes(e): """Return the Stokes vector for a Jones vector ``e``. Parameters ========== e : SymPy Matrix A Jones vector. Returns ======= SymPy Matrix A Jones vector. Examples ======== The axes on the PoincarΓ© sphere. >>> from sympy import pprint, pi >>> from sympy.physics.optics.polarization import jones_vector >>> from sympy.physics.optics.polarization import jones_2_stokes >>> H = jones_vector(0, 0) >>> V = jones_vector(pi/2, 0) >>> D = jones_vector(pi/4, 0) >>> A = jones_vector(-pi/4, 0) >>> R = jones_vector(0, pi/4) >>> L = jones_vector(0, -pi/4) >>> pprint([jones_2_stokes(e) for e in [H, V, D, A, R, L]], ... use_unicode=True) ⎑⎑1⎀ ⎑1 ⎀ ⎑1⎀ ⎑1 ⎀ ⎑1⎀ ⎑1 ⎀⎀ ⎒⎒ βŽ₯ ⎒ βŽ₯ ⎒ βŽ₯ ⎒ βŽ₯ ⎒ βŽ₯ ⎒ βŽ₯βŽ₯ ⎒⎒1βŽ₯ ⎒-1βŽ₯ ⎒0βŽ₯ ⎒0 βŽ₯ ⎒0βŽ₯ ⎒0 βŽ₯βŽ₯ ⎒⎒ βŽ₯, ⎒ βŽ₯, ⎒ βŽ₯, ⎒ βŽ₯, ⎒ βŽ₯, ⎒ βŽ₯βŽ₯ ⎒⎒0βŽ₯ ⎒0 βŽ₯ ⎒1βŽ₯ ⎒-1βŽ₯ ⎒0βŽ₯ ⎒0 βŽ₯βŽ₯ ⎒⎒ βŽ₯ ⎒ βŽ₯ ⎒ βŽ₯ ⎒ βŽ₯ ⎒ βŽ₯ ⎒ βŽ₯βŽ₯ ⎣⎣0⎦ ⎣0 ⎦ ⎣0⎦ ⎣0 ⎦ ⎣1⎦ ⎣-1⎦⎦ """ ex, ey = e return Matrix([Abs(ex)**2 + Abs(ey)**2, Abs(ex)**2 - Abs(ey)**2, 2*re(ex*ey.conjugate()), -2*im(ex*ey.conjugate())]) def linear_polarizer(theta=0): """A linear polarizer Jones matrix with transmission axis at an angle ``theta``. Parameters ========== theta : numeric type or SymPy Symbol The angle of the transmission axis relative to the horizontal plane. Returns ======= SymPy Matrix A Jones matrix representing the polarizer. Examples ======== A generic polarizer. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import linear_polarizer >>> theta = symbols("theta", real=True) >>> J = linear_polarizer(theta) >>> pprint(J, use_unicode=True) ⎑ 2 ⎀ ⎒ cos (ΞΈ) sin(ΞΈ)β‹…cos(ΞΈ)βŽ₯ ⎒ βŽ₯ ⎒ 2 βŽ₯ ⎣sin(ΞΈ)β‹…cos(ΞΈ) sin (ΞΈ) ⎦ """ M = Matrix([[cos(theta)**2, sin(theta)*cos(theta)], [sin(theta)*cos(theta), sin(theta)**2]]) return M def phase_retarder(theta=0, delta=0): """A phase retarder Jones matrix with retardance ``delta`` at angle ``theta``. Parameters ========== theta : numeric type or SymPy Symbol The angle of the fast axis relative to the horizontal plane. delta : numeric type or SymPy Symbol The phase difference between the fast and slow axes of the transmitted light. Returns ======= SymPy Matrix : A Jones matrix representing the retarder. Examples ======== A generic retarder. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import phase_retarder >>> theta, delta = symbols("theta, delta", real=True) >>> R = phase_retarder(theta, delta) >>> pprint(R, use_unicode=True) ⎑ -β…ˆβ‹…Ξ΄ -β…ˆβ‹…Ξ΄ ⎀ ⎒ ───── ───── βŽ₯ βŽ’βŽ› β…ˆβ‹…Ξ΄ 2 2 ⎞ 2 βŽ› β…ˆβ‹…Ξ΄βŽž 2 βŽ₯ βŽ’βŽβ„― β‹…sin (ΞΈ) + cos (ΞΈ)βŽ β‹…β„― ⎝1 - β„― βŽ β‹…β„― β‹…sin(ΞΈ)β‹…cos(ΞΈ)βŽ₯ ⎒ βŽ₯ ⎒ -β…ˆβ‹…Ξ΄ -β…ˆβ‹…Ξ΄ βŽ₯ ⎒ ───── ─────βŽ₯ βŽ’βŽ› β…ˆβ‹…Ξ΄βŽž 2 βŽ› β…ˆβ‹…Ξ΄ 2 2 ⎞ 2 βŽ₯ ⎣⎝1 - β„― βŽ β‹…β„― β‹…sin(ΞΈ)β‹…cos(ΞΈ) βŽβ„― β‹…cos (ΞΈ) + sin (ΞΈ)βŽ β‹…β„― ⎦ """ R = Matrix([[cos(theta)**2 + exp(I*delta)*sin(theta)**2, (1-exp(I*delta))*cos(theta)*sin(theta)], [(1-exp(I*delta))*cos(theta)*sin(theta), sin(theta)**2 + exp(I*delta)*cos(theta)**2]]) return R*exp(-I*delta/2) def half_wave_retarder(theta): """A half-wave retarder Jones matrix at angle ``theta``. Parameters ========== theta : numeric type or SymPy Symbol The angle of the fast axis relative to the horizontal plane. Returns ======= SymPy Matrix A Jones matrix representing the retarder. Examples ======== A generic half-wave plate. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import half_wave_retarder >>> theta= symbols("theta", real=True) >>> HWP = half_wave_retarder(theta) >>> pprint(HWP, use_unicode=True) ⎑ βŽ› 2 2 ⎞ ⎀ ⎒-β…ˆβ‹…βŽ- sin (ΞΈ) + cos (ΞΈ)⎠ -2β‹…β…ˆβ‹…sin(ΞΈ)β‹…cos(ΞΈ) βŽ₯ ⎒ βŽ₯ ⎒ βŽ› 2 2 ⎞βŽ₯ ⎣ -2β‹…β…ˆβ‹…sin(ΞΈ)β‹…cos(ΞΈ) -β…ˆβ‹…βŽsin (ΞΈ) - cos (ΞΈ)⎠⎦ """ return phase_retarder(theta, pi) def quarter_wave_retarder(theta): """A quarter-wave retarder Jones matrix at angle ``theta``. Parameters ========== theta : numeric type or SymPy Symbol The angle of the fast axis relative to the horizontal plane. Returns ======= SymPy Matrix A Jones matrix representing the retarder. Examples ======== A generic quarter-wave plate. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import quarter_wave_retarder >>> theta= symbols("theta", real=True) >>> QWP = quarter_wave_retarder(theta) >>> pprint(QWP, use_unicode=True) ⎑ -β…ˆβ‹…Ο€ -β…ˆβ‹…Ο€ ⎀ ⎒ ───── ───── βŽ₯ βŽ’βŽ› 2 2 ⎞ 4 4 βŽ₯ βŽ’βŽβ…ˆβ‹…sin (ΞΈ) + cos (ΞΈ)βŽ β‹…β„― (1 - β…ˆ)β‹…β„― β‹…sin(ΞΈ)β‹…cos(ΞΈ)βŽ₯ ⎒ βŽ₯ ⎒ -β…ˆβ‹…Ο€ -β…ˆβ‹…Ο€ βŽ₯ ⎒ ───── ─────βŽ₯ ⎒ 4 βŽ› 2 2 ⎞ 4 βŽ₯ ⎣(1 - β…ˆ)β‹…β„― β‹…sin(ΞΈ)β‹…cos(ΞΈ) ⎝sin (ΞΈ) + β…ˆβ‹…cos (ΞΈ)βŽ β‹…β„― ⎦ """ return phase_retarder(theta, pi/2) def transmissive_filter(T): """An attenuator Jones matrix with transmittance ``T``. Parameters ========== T : numeric type or SymPy Symbol The transmittance of the attenuator. Returns ======= SymPy Matrix A Jones matrix representing the filter. Examples ======== A generic filter. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import transmissive_filter >>> T = symbols("T", real=True) >>> NDF = transmissive_filter(T) >>> pprint(NDF, use_unicode=True) ⎑√T 0 ⎀ ⎒ βŽ₯ ⎣0 √T⎦ """ return Matrix([[sqrt(T), 0], [0, sqrt(T)]]) def reflective_filter(R): """A reflective filter Jones matrix with reflectance ``R``. Parameters ========== R : numeric type or SymPy Symbol The reflectance of the filter. Returns ======= SymPy Matrix A Jones matrix representing the filter. Examples ======== A generic filter. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import reflective_filter >>> R = symbols("R", real=True) >>> pprint(reflective_filter(R), use_unicode=True) ⎑√R 0 ⎀ ⎒ βŽ₯ ⎣0 -√R⎦ """ return Matrix([[sqrt(R), 0], [0, -sqrt(R)]]) def mueller_matrix(J): """The Mueller matrix corresponding to Jones matrix `J`. Parameters ========== J : SymPy Matrix A Jones matrix. Returns ======= SymPy Matrix The corresponding Mueller matrix. Examples ======== Generic optical components. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import (mueller_matrix, ... linear_polarizer, half_wave_retarder, quarter_wave_retarder) >>> theta = symbols("theta", real=True) A linear_polarizer >>> pprint(mueller_matrix(linear_polarizer(theta)), use_unicode=True) ⎑ cos(2β‹…ΞΈ) sin(2β‹…ΞΈ) ⎀ ⎒ 1/2 ──────── ──────── 0βŽ₯ ⎒ 2 2 βŽ₯ ⎒ βŽ₯ ⎒cos(2β‹…ΞΈ) cos(4β‹…ΞΈ) 1 sin(4β‹…ΞΈ) βŽ₯ βŽ’β”€β”€β”€β”€β”€β”€β”€β”€ ──────── + ─ ──────── 0βŽ₯ ⎒ 2 4 4 4 βŽ₯ ⎒ βŽ₯ ⎒sin(2β‹…ΞΈ) sin(4β‹…ΞΈ) 1 cos(4β‹…ΞΈ) βŽ₯ βŽ’β”€β”€β”€β”€β”€β”€β”€β”€ ──────── ─ - ──────── 0βŽ₯ ⎒ 2 4 4 4 βŽ₯ ⎒ βŽ₯ ⎣ 0 0 0 0⎦ A half-wave plate >>> pprint(mueller_matrix(half_wave_retarder(theta)), use_unicode=True) ⎑1 0 0 0 ⎀ ⎒ βŽ₯ ⎒ 4 2 βŽ₯ ⎒0 8β‹…sin (ΞΈ) - 8β‹…sin (ΞΈ) + 1 sin(4β‹…ΞΈ) 0 βŽ₯ ⎒ βŽ₯ ⎒ 4 2 βŽ₯ ⎒0 sin(4β‹…ΞΈ) - 8β‹…sin (ΞΈ) + 8β‹…sin (ΞΈ) - 1 0 βŽ₯ ⎒ βŽ₯ ⎣0 0 0 -1⎦ A quarter-wave plate >>> pprint(mueller_matrix(quarter_wave_retarder(theta)), use_unicode=True) ⎑1 0 0 0 ⎀ ⎒ βŽ₯ ⎒ cos(4β‹…ΞΈ) 1 sin(4β‹…ΞΈ) βŽ₯ ⎒0 ──────── + ─ ──────── -sin(2β‹…ΞΈ)βŽ₯ ⎒ 2 2 2 βŽ₯ ⎒ βŽ₯ ⎒ sin(4β‹…ΞΈ) 1 cos(4β‹…ΞΈ) βŽ₯ ⎒0 ──────── ─ - ──────── cos(2β‹…ΞΈ) βŽ₯ ⎒ 2 2 2 βŽ₯ ⎒ βŽ₯ ⎣0 sin(2β‹…ΞΈ) -cos(2β‹…ΞΈ) 0 ⎦ """ A = Matrix([[1, 0, 0, 1], [1, 0, 0, -1], [0, 1, 1, 0], [0, -I, I, 0]]) return simplify(A*TensorProduct(J, J.conjugate())*A.inv()) def polarizing_beam_splitter(Tp=1, Rs=1, Ts=0, Rp=0, phia=0, phib=0): r"""A polarizing beam splitter Jones matrix at angle `theta`. Parameters ========== J : SymPy Matrix A Jones matrix. Tp : numeric type or SymPy Symbol The transmissivity of the P-polarized component. Rs : numeric type or SymPy Symbol The reflectivity of the S-polarized component. Ts : numeric type or SymPy Symbol The transmissivity of the S-polarized component. Rp : numeric type or SymPy Symbol The reflectivity of the P-polarized component. phia : numeric type or SymPy Symbol The phase difference between transmitted and reflected component for output mode a. phib : numeric type or SymPy Symbol The phase difference between transmitted and reflected component for output mode b. Returns ======= SymPy Matrix A 4x4 matrix representing the PBS. This matrix acts on a 4x1 vector whose first two entries are the Jones vector on one of the PBS ports, and the last two entries the Jones vector on the other port. Examples ======== Generic polarizing beam-splitter. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import polarizing_beam_splitter >>> Ts, Rs, Tp, Rp = symbols(r"Ts, Rs, Tp, Rp", positive=True) >>> phia, phib = symbols("phi_a, phi_b", real=True) >>> PBS = polarizing_beam_splitter(Tp, Rs, Ts, Rp, phia, phib) >>> pprint(PBS, use_unicode=False) [ ____ ____ ] [ \/ Tp 0 I*\/ Rp 0 ] [ ] [ ____ ____ I*phi_a] [ 0 \/ Ts 0 -I*\/ Rs *e ] [ ] [ ____ ____ ] [I*\/ Rp 0 \/ Tp 0 ] [ ] [ ____ I*phi_b ____ ] [ 0 -I*\/ Rs *e 0 \/ Ts ] """ PBS = Matrix([[sqrt(Tp), 0, I*sqrt(Rp), 0], [0, sqrt(Ts), 0, -I*sqrt(Rs)*exp(I*phia)], [I*sqrt(Rp), 0, sqrt(Tp), 0], [0, -I*sqrt(Rs)*exp(I*phib), 0, sqrt(Ts)]]) return PBS