code
stringlengths
17
6.64M
def eulers_method(f, x0, y0, h, x1, algorithm='table'): '\n This implements Euler\'s method for finding numerically the\n solution of the 1st order ODE `y\' = f(x,y)`, `y(a)=c`. The ``x``\n column of the table increments from `x_0` to `x_1` by `h` (so\n `(x_1-x_0)/h` must be an integer). In the ``y`` column, the new\n `y`-value equals the old `y`-value plus the corresponding entry in the\n last column.\n\n .. NOTE::\n\n This function is for pedagogical purposes only.\n\n EXAMPLES::\n\n sage: from sage.calculus.desolvers import eulers_method\n sage: x,y = PolynomialRing(QQ,2,"xy").gens()\n sage: eulers_method(5*x+y-5,0,1,1/2,1)\n x y h*f(x,y)\n 0 1 -2\n 1/2 -1 -7/4\n 1 -11/4 -11/8\n\n ::\n\n sage: x,y = PolynomialRing(QQ,2,"xy").gens()\n sage: eulers_method(5*x+y-5,0,1,1/2,1,algorithm="none")\n [[0, 1], [1/2, -1], [1, -11/4], [3/2, -33/8]]\n\n ::\n\n sage: RR = RealField(sci_not=0, prec=4, rnd=\'RNDU\')\n sage: x,y = PolynomialRing(RR,2,"xy").gens()\n sage: eulers_method(5*x+y-5,0,1,1/2,1,algorithm="None")\n [[0, 1], [1/2, -1.0], [1, -2.7], [3/2, -4.0]]\n\n ::\n\n sage: RR = RealField(sci_not=0, prec=4, rnd=\'RNDU\')\n sage: x,y=PolynomialRing(RR,2,"xy").gens()\n sage: eulers_method(5*x+y-5,0,1,1/2,1)\n x y h*f(x,y)\n 0 1 -2.0\n 1/2 -1.0 -1.7\n 1 -2.7 -1.3\n\n ::\n\n sage: x,y=PolynomialRing(QQ,2,"xy").gens()\n sage: eulers_method(5*x+y-5,1,1,1/3,2)\n x y h*f(x,y)\n 1 1 1/3\n 4/3 4/3 1\n 5/3 7/3 17/9\n 2 38/9 83/27\n\n ::\n\n sage: eulers_method(5*x+y-5,0,1,1/2,1,algorithm="none")\n [[0, 1], [1/2, -1], [1, -11/4], [3/2, -33/8]]\n\n ::\n\n sage: pts = eulers_method(5*x+y-5,0,1,1/2,1,algorithm="none")\n sage: P1 = list_plot(pts) # needs sage.plot\n sage: P2 = line(pts) # needs sage.plot\n sage: (P1 + P2).show() # needs sage.plot\n\n AUTHORS:\n\n - David Joyner\n ' if (algorithm == 'table'): print(('%10s %20s %25s' % ('x', 'y', 'h*f(x,y)'))) n = int(((1.0 * (x1 - x0)) / h)) x00 = x0 y00 = y0 soln = [[x00, y00]] for i in range((n + 1)): if (algorithm == 'table'): print(('%10r %20r %20r' % (x00, y00, (h * f(x00, y00))))) y00 = (y00 + (h * f(x00, y00))) x00 = (x00 + h) soln.append([x00, y00]) if (algorithm != 'table'): return soln
def eulers_method_2x2(f, g, t0, x0, y0, h, t1, algorithm='table'): '\n This implements Euler\'s method for finding numerically the\n solution of the 1st order system of two ODEs\n\n .. MATH::\n\n \\begin{aligned}\n x\' &= f(t, x, y), x(t_0)=x_0 \\\\\n y\' &= g(t, x, y), y(t_0)=y_0.\n \\end{aligned}\n\n The ``t`` column of the table increments from `t_0` to `t_1` by `h`\n (so `\\frac{t_1-t_0}{h}` must be an integer). In the ``x`` column,\n the new `x`-value equals the old `x`-value plus the corresponding\n entry in the next (third) column. In the ``y`` column, the new\n `y`-value equals the old `y`-value plus the corresponding entry in the\n next (last) column.\n\n .. NOTE::\n\n This function is for pedagogical purposes only.\n\n EXAMPLES::\n\n sage: from sage.calculus.desolvers import eulers_method_2x2\n sage: t, x, y = PolynomialRing(QQ,3,"txy").gens()\n sage: f = x+y+t; g = x-y\n sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1,algorithm="none")\n [[0, 0, 0], [1/3, 0, 0], [2/3, 1/9, 0], [1, 10/27, 1/27], [4/3, 68/81, 4/27]]\n\n ::\n\n sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1)\n t x h*f(t,x,y) y h*g(t,x,y)\n 0 0 0 0 0\n 1/3 0 1/9 0 0\n 2/3 1/9 7/27 0 1/27\n 1 10/27 38/81 1/27 1/9\n\n ::\n\n sage: RR = RealField(sci_not=0, prec=4, rnd=\'RNDU\')\n sage: t,x,y=PolynomialRing(RR,3,"txy").gens()\n sage: f = x+y+t; g = x-y\n sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1)\n t x h*f(t,x,y) y h*g(t,x,y)\n 0 0 0.00 0 0.00\n 1/3 0.00 0.13 0.00 0.00\n 2/3 0.13 0.29 0.00 0.043\n 1 0.41 0.57 0.043 0.15\n\n To numerically approximate `y(1)`, where `(1+t^2)y\'\'+y\'-y=0`,\n `y(0)=1`, `y\'(0)=-1`, using 4 steps of Euler\'s method, first\n convert to a system: `y_1\' = y_2`, `y_1(0)=1`; `y_2\' =\n \\frac{y_1-y_2}{1+t^2}`, `y_2(0)=-1`.::\n\n sage: RR = RealField(sci_not=0, prec=4, rnd=\'RNDU\')\n sage: t, x, y=PolynomialRing(RR,3,"txy").gens()\n sage: f = y; g = (x-y)/(1+t^2)\n sage: eulers_method_2x2(f,g, 0, 1, -1, 1/4, 1)\n t x h*f(t,x,y) y h*g(t,x,y)\n 0 1 -0.25 -1 0.50\n 1/4 0.75 -0.12 -0.50 0.29\n 1/2 0.63 -0.054 -0.21 0.19\n 3/4 0.63 -0.0078 -0.031 0.11\n 1 0.63 0.020 0.079 0.071\n\n To numerically approximate `y(1)`, where `y\'\'+ty\'+y=0`, `y(0)=1`, `y\'(0)=0`::\n\n sage: t,x,y=PolynomialRing(RR,3,"txy").gens()\n sage: f = y; g = -x-y*t\n sage: eulers_method_2x2(f,g, 0, 1, 0, 1/4, 1)\n t x h*f(t,x,y) y h*g(t,x,y)\n 0 1 0.00 0 -0.25\n 1/4 1.0 -0.062 -0.25 -0.23\n 1/2 0.94 -0.11 -0.46 -0.17\n 3/4 0.88 -0.15 -0.62 -0.10\n 1 0.75 -0.17 -0.68 -0.015\n\n AUTHORS:\n\n - David Joyner\n ' if (algorithm == 'table'): print(('%10s %20s %25s %20s %20s' % ('t', 'x', 'h*f(t,x,y)', 'y', 'h*g(t,x,y)'))) n = int(((1.0 * (t1 - t0)) / h)) t00 = t0 x00 = x0 y00 = y0 soln = [[t00, x00, y00]] for i in range((n + 1)): if (algorithm == 'table'): print(('%10r %20r %25r %20r %20r' % (t00, x00, (h * f(t00, x00, y00)), y00, (h * g(t00, x00, y00))))) x01 = (x00 + (h * f(t00, x00, y00))) y00 = (y00 + (h * g(t00, x00, y00))) x00 = x01 t00 = (t00 + h) soln.append([t00, x00, y00]) if (algorithm != 'table'): return soln
def eulers_method_2x2_plot(f, g, t0, x0, y0, h, t1): "\n Plot solution of ODE.\n\n This plots the solution in the rectangle with sides ``(xrange[0],xrange[1])`` and\n ``(yrange[0],yrange[1])``, and plots using Euler's method the\n numerical solution of the 1st order ODEs `x' = f(t,x,y)`,\n `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`.\n\n .. NOTE::\n\n This function is for pedagogical purposes only.\n\n EXAMPLES:\n\n The following example plots the solution to\n `\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) =\n 0`. Type ``P[0].show()`` to plot the solution,\n ``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and\n `(t,\\theta'(t))`::\n\n sage: from sage.calculus.desolvers import eulers_method_2x2_plot\n sage: f = lambda z : z[2]; g = lambda z : -sin(z[1])\n sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) # needs sage.plot\n " from sage.plot.line import line n = int(((1.0 * (t1 - t0)) / h)) t00 = t0 x00 = x0 y00 = y0 soln = [[t00, x00, y00]] for i in range((n + 1)): x01 = (x00 + (h * f([t00, x00, y00]))) y00 = (y00 + (h * g([t00, x00, y00]))) x00 = x01 t00 = (t00 + h) soln.append([t00, x00, y00]) Q1 = line([[x[0], x[1]] for x in soln], rgbcolor=(0.25, 0.125, 0.75)) Q2 = line([[x[0], x[2]] for x in soln], rgbcolor=(0.5, 0.125, 0.25)) return [Q1, Q2]
def desolve_rk4_determine_bounds(ics, end_points=None): '\n Used to determine bounds for numerical integration.\n\n - If ``end_points`` is None, the interval for integration is from ``ics[0]``\n to ``ics[0]+10``\n\n - If ``end_points`` is ``a`` or ``[a]``, the interval for integration is from ``min(ics[0],a)``\n to ``max(ics[0],a)``\n\n - If ``end_points`` is ``[a,b]``, the interval for integration is from ``min(ics[0],a)``\n to ``max(ics[0],b)``\n\n EXAMPLES::\n\n sage: from sage.calculus.desolvers import desolve_rk4_determine_bounds\n sage: desolve_rk4_determine_bounds([0,2],1)\n (0, 1)\n\n ::\n\n sage: desolve_rk4_determine_bounds([0,2])\n (0, 10)\n\n ::\n\n sage: desolve_rk4_determine_bounds([0,2],[-2])\n (-2, 0)\n\n ::\n\n sage: desolve_rk4_determine_bounds([0,2],[-2,4])\n (-2, 4)\n\n ' if (end_points is None): return (ics[0], (ics[0] + 10)) if (not isinstance(end_points, list)): end_points = [end_points] if (len(end_points) == 1): return (min(ics[0], end_points[0]), max(ics[0], end_points[0])) else: return (min(ics[0], end_points[0]), max(ics[0], end_points[1]))
def desolve_rk4(de, dvar, ics=None, ivar=None, end_points=None, step=0.1, output='list', **kwds): "\n Solve numerically one first-order ordinary differential\n equation.\n\n INPUT:\n\n Input is similar to ``desolve`` command. The differential equation can be\n written in a form close to the ``plot_slope_field`` or ``desolve`` command.\n\n - Variant 1 (function in two variables)\n\n - ``de`` - right hand side, i.e. the function `f(x,y)` from ODE `y'=f(x,y)`\n\n - ``dvar`` - dependent variable (symbolic variable declared by var)\n\n - Variant 2 (symbolic equation)\n\n - ``de`` - equation, including term with ``diff(y,x)``\n\n - ``dvar`` - dependent variable (declared as function of independent variable)\n\n - Other parameters\n\n - ``ivar`` - should be specified, if there are more variables or if the equation is autonomous\n\n - ``ics`` - initial conditions in the form ``[x0,y0]``\n\n - ``end_points`` - the end points of the interval\n\n - if ``end_points`` is a or [a], we integrate between ``min(ics[0],a)`` and ``max(ics[0],a)``\n - if ``end_points`` is None, we use ``end_points=ics[0]+10``\n\n - if end_points is [a,b] we integrate between ``min(ics[0], a)`` and ``max(ics[0], b)``\n\n - ``step`` - (optional, default:0.1) the length of the step (positive number)\n\n - ``output`` - (optional, default: ``'list'``) one of ``'list'``,\n ``'plot'``, ``'slope_field'`` (graph of the solution with slope field)\n\n OUTPUT:\n\n Return a list of points, or plot produced by ``list_plot``,\n optionally with slope field.\n\n .. SEEALSO::\n\n :func:`ode_solver`.\n\n EXAMPLES::\n\n sage: from sage.calculus.desolvers import desolve_rk4\n\n Variant 2 for input - more common in numerics::\n\n sage: x,y = var('x,y')\n sage: desolve_rk4(x*y*(2-y),y,ics=[0,1],end_points=1,step=0.5)\n [[0, 1], [0.5, 1.12419127424558], [1.0, 1.46159016228882...]]\n\n Variant 1 for input - we can pass ODE in the form used by\n desolve function In this example we integrate backwards, since\n ``end_points < ics[0]``::\n\n sage: y = function('y')(x)\n sage: desolve_rk4(diff(y,x)+y*(y-1) == x-2,y,ics=[1,1],step=0.5, end_points=0)\n [[0.0, 8.904257108962112], [0.5, 1.90932794536153...], [1, 1]]\n\n Here we show how to plot simple pictures. For more advanced\n applications use list_plot instead. To see the resulting picture\n use ``show(P)`` in Sage notebook. ::\n\n sage: x,y = var('x,y')\n sage: P=desolve_rk4(y*(2-y),y,ics=[0,.1],ivar=x,output='slope_field',end_points=[-4,6],thickness=3)\n\n ALGORITHM:\n\n 4th order Runge-Kutta method. Wrapper for command ``rk`` in\n Maxima's dynamics package. Perhaps could be faster by using\n fast_float instead.\n\n AUTHORS:\n\n - Robert Marik (10-2009)\n " if (ics is None): raise ValueError('No initial conditions, specify with ics=[x0,y0].') if (output not in ['list', 'plot', 'slope_field']): raise ValueError("Option output should be 'list', 'plot' or 'slope_field'.") if (ivar is None): ivars = de.variables() ivars = [t for t in ivars if (t != dvar)] if (len(ivars) != 1): raise ValueError('Unable to determine independent variable, please specify.') ivar = ivars[0] step = abs(step) def desolve_rk4_inner(de, dvar): de0 = de._maxima_() maxima("load('dynamics)") (lower_bound, upper_bound) = desolve_rk4_determine_bounds(ics, end_points) (sol_1, sol_2) = ([], []) if (lower_bound < ics[0]): cmd = ('rk(%s,%s,%s,[%s,%s,%s,%s]) ' % (de0.str(), ('_SAGE_VAR_' + str(dvar)), str(ics[1]), ('_SAGE_VAR_' + str(ivar)), str(ics[0]), lower_bound, (- step))) sol_1 = maxima(cmd).sage() sol_1.pop(0) sol_1.reverse() if (upper_bound > ics[0]): cmd = ('rk(%s,%s,%s,[%s,%s,%s,%s]) ' % (de0.str(), ('_SAGE_VAR_' + str(dvar)), str(ics[1]), ('_SAGE_VAR_' + str(ivar)), str(ics[0]), upper_bound, step)) sol_2 = maxima(cmd).sage() sol_2.pop(0) sol = sol_1 sol.extend([[ics[0], ics[1]]]) sol.extend(sol_2) if (output == 'list'): return sol from sage.plot.plot import list_plot from sage.plot.plot_field import plot_slope_field R = list_plot(sol, plotjoined=True, **kwds) if (output == 'plot'): return R if (output == 'slope_field'): XMIN = sol[0][0] YMIN = sol[0][1] XMAX = XMIN YMAX = YMIN for (s, t) in sol: if (s > XMAX): XMAX = s if (s < XMIN): XMIN = s if (t > YMAX): YMAX = t if (t < YMIN): YMIN = t return (plot_slope_field(de, (ivar, XMIN, XMAX), (dvar, YMIN, YMAX)) + R) if (not (isinstance(dvar, Expression) and dvar.is_symbol())): from sage.symbolic.ring import SR from sage.calculus.all import diff from sage.symbolic.relation import solve if (isinstance(de, Expression) and de.is_relational()): de = (de.lhs() - de.rhs()) de = solve(de, diff(dvar, ivar), solution_dict=True) if (len(de) != 1): raise NotImplementedError('Sorry, cannot find explicit formula for right-hand side of the ODE.') with SR.temp_var() as dummy_dvar: return desolve_rk4_inner(de[0][diff(dvar, ivar)].subs({dvar: dummy_dvar}), dummy_dvar) else: return desolve_rk4_inner(de, dvar)
def desolve_system_rk4(des, vars, ics=None, ivar=None, end_points=None, step=0.1): "\n Solve numerically a system of first-order ordinary differential\n equations using the 4th order Runge-Kutta method. Wrapper for\n Maxima command ``rk``.\n\n INPUT:\n\n input is similar to desolve_system and desolve_rk4 commands\n\n - ``des`` - right hand sides of the system\n\n - ``vars`` - dependent variables\n\n - ``ivar`` - (optional) should be specified, if there are more variables or\n if the equation is autonomous and the independent variable is\n missing\n\n - ``ics`` - initial conditions in the form ``[x0,y01,y02,y03,....]``\n\n - ``end_points`` - the end points of the interval\n\n - if ``end_points`` is a or [a], we integrate on between ``min(ics[0], a)`` and ``max(ics[0], a)``\n - if ``end_points`` is None, we use ``end_points=ics[0]+10``\n\n - if ``end_points`` is [a,b] we integrate on between ``min(ics[0], a)`` and ``max(ics[0], b)``\n\n - ``step`` -- (optional, default: 0.1) the length of the step\n\n OUTPUT:\n\n Return a list of points.\n\n .. SEEALSO::\n\n :func:`ode_solver`.\n\n EXAMPLES::\n\n sage: from sage.calculus.desolvers import desolve_system_rk4\n\n Lotka Volterra system::\n\n sage: from sage.calculus.desolvers import desolve_system_rk4\n sage: x,y,t = var('x y t')\n sage: P = desolve_system_rk4([x*(1-y),-y*(1-x)], [x,y], ics=[0,0.5,2],\n ....: ivar=t, end_points=20)\n sage: Q = [[i,j] for i,j,k in P]\n sage: LP = list_plot(Q) # needs sage.plot\n\n sage: Q = [[j,k] for i,j,k in P]\n sage: LP = list_plot(Q) # needs sage.plot\n\n ALGORITHM:\n\n 4th order Runge-Kutta method. Wrapper for command ``rk`` in Maxima's\n dynamics package. Perhaps could be faster by using ``fast_float``\n instead.\n\n AUTHOR:\n\n - Robert Marik (10-2009)\n " if (ics is None): raise ValueError('No initial conditions, specify with ics=[x0,y01,y02,...].') ivars = set([]) for de in des: ivars = ivars.union(set(de.variables())) if (ivar is None): ivars = (ivars - set(vars)) if (len(ivars) != 1): raise ValueError('Unable to determine independent variable, please specify.') ivar = list(ivars)[0] dess = [de._maxima_().str() for de in des] desstr = (('[' + ','.join(dess)) + ']') varss = [varsi._maxima_().str() for varsi in vars] varstr = (('[' + ','.join(varss)) + ']') x0 = ics[0] icss = [ics[i]._maxima_().str() for i in range(1, len(ics))] icstr = (('[' + ','.join(icss)) + ']') step = abs(step) maxima("load('dynamics)") (lower_bound, upper_bound) = desolve_rk4_determine_bounds(ics, end_points) (sol_1, sol_2) = ([], []) if (lower_bound < ics[0]): cmd = ('rk(%s,%s,%s,[%s,%s,%s,%s]) ' % (desstr, varstr, icstr, ('_SAGE_VAR_' + str(ivar)), str(x0), lower_bound, (- step))) sol_1 = maxima(cmd).sage() sol_1.pop(0) sol_1.reverse() if (upper_bound > ics[0]): cmd = ('rk(%s,%s,%s,[%s,%s,%s,%s]) ' % (desstr, varstr, icstr, ('_SAGE_VAR_' + str(ivar)), str(x0), upper_bound, step)) sol_2 = maxima(cmd).sage() sol_2.pop(0) sol = sol_1 sol.append(ics) sol.extend(sol_2) return sol
def desolve_odeint(des, ics, times, dvars, ivar=None, compute_jac=False, args=(), rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12, mxords=5, printmessg=0): "\n Solve numerically a system of first-order ordinary differential equations\n using ``odeint`` from scipy.integrate module.\n\n INPUT:\n\n - ``des`` -- right hand sides of the system\n\n - ``ics`` -- initial conditions\n\n - ``times`` -- a sequence of time points in which the solution must be found\n\n - ``dvars`` -- dependent variables. ATTENTION: the order must be the same as\n in ``des``, that means: ``d(dvars[i])/dt=des[i]``\n\n - ``ivar`` -- independent variable, optional.\n\n - ``compute_jac`` -- boolean. If True, the Jacobian of ``des`` is computed and\n used during the integration of stiff systems. Default value is False.\n\n Other Parameters (taken from the documentation of odeint function from `scipy.integrate module.\n <https://docs.scipy.org/doc/scipy/reference/integrate.html#module-scipy.integrate>`_)\n\n - ``rtol``, ``atol`` : float\n The input parameters ``rtol`` and ``atol`` determine the error\n control performed by the solver. The solver will control the\n vector, `e`, of estimated local errors in `y`, according to an\n inequality of the form:\n\n max-norm of (e / ewt) <= 1\n\n where ewt is a vector of positive error weights computed as:\n\n ewt = rtol * abs(y) + atol\n\n ``rtol`` and ``atol`` can be either vectors the same length as `y` or scalars.\n\n - ``tcrit`` : array\n Vector of critical points (e.g. singularities) where integration\n care should be taken.\n\n - ``h0`` : float, (0: solver-determined)\n The step size to be attempted on the first step.\n\n - ``hmax`` : float, (0: solver-determined)\n The maximum absolute step size allowed.\n\n - ``hmin`` : float, (0: solver-determined)\n The minimum absolute step size allowed.\n\n - ``ixpr`` : boolean.\n Whether to generate extra printing at method switches.\n\n - ``mxstep`` : integer, (0: solver-determined)\n Maximum number of (internally defined) steps allowed for each\n integration point in t.\n\n - ``mxhnil`` : integer, (0: solver-determined)\n Maximum number of messages printed.\n\n - ``mxordn`` : integer, (0: solver-determined)\n Maximum order to be allowed for the nonstiff (Adams) method.\n\n - ``mxords`` : integer, (0: solver-determined)\n Maximum order to be allowed for the stiff (BDF) method.\n\n OUTPUT:\n\n Return a list with the solution of the system at each time in ``times``.\n\n EXAMPLES:\n\n Lotka Volterra Equations::\n\n sage: from sage.calculus.desolvers import desolve_odeint\n sage: x,y = var('x,y')\n sage: f = [x*(1-y), -y*(1-x)]\n sage: sol = desolve_odeint(f, [0.5,2], srange(0,10,0.1), [x,y]) # needs scipy\n sage: p = line(zip(sol[:,0],sol[:,1])) # needs scipy sage.plot\n sage: p.show() # needs scipy sage.plot\n\n Lorenz Equations::\n\n sage: x,y,z = var('x,y,z')\n sage: # Next we define the parameters\n sage: sigma = 10\n sage: rho = 28\n sage: beta = 8/3\n sage: # The Lorenz equations\n sage: lorenz = [sigma*(y-x),x*(rho-z)-y,x*y-beta*z]\n sage: # Time and initial conditions\n sage: times = srange(0,50.05,0.05)\n sage: ics = [0,1,1]\n sage: sol = desolve_odeint(lorenz, ics, times, [x,y,z], # needs scipy\n ....: rtol=1e-13, atol=1e-14)\n\n One-dimensional stiff system::\n\n sage: y = var('y')\n sage: epsilon = 0.01\n sage: f = y^2*(1-y)\n sage: ic = epsilon\n sage: t = srange(0,2/epsilon,1)\n sage: sol = desolve_odeint(f, ic, t, y, # needs scipy\n ....: rtol=1e-9, atol=1e-10, compute_jac=True)\n sage: p = points(zip(t,sol[:,0])) # needs scipy sage.plot\n sage: p.show() # needs scipy sage.plot\n\n Another stiff system with some optional parameters with no\n default value::\n\n sage: y1,y2,y3 = var('y1,y2,y3')\n sage: f1 = 77.27*(y2+y1*(1-8.375*1e-6*y1-y2))\n sage: f2 = 1/77.27*(y3-(1+y1)*y2)\n sage: f3 = 0.16*(y1-y3)\n sage: f = [f1,f2,f3]\n sage: ci = [0.2,0.4,0.7]\n sage: t = srange(0,10,0.01)\n sage: v = [y1,y2,y3]\n sage: sol = desolve_odeint(f, ci, t, v, rtol=1e-3, atol=1e-4, # needs scipy\n ....: h0=0.1, hmax=1, hmin=1e-4, mxstep=1000, mxords=17)\n\n AUTHOR:\n\n - Oriol Castejon (05-2010)\n " from scipy.integrate import odeint from sage.ext.fast_eval import fast_float from sage.calculus.functions import jacobian def desolve_odeint_inner(ivar): if (len(dvars) == 1): assert (len(des) == 1) dvar = dvars[0] de = des[0] func = fast_float(de, dvar, ivar) if (not compute_jac): Dfun = None else: J = diff(de, dvar) J = fast_float(J, dvar, ivar) def Dfun(y, t): return [J(y.item(), t)] else: desc = [] variabs = dvars[:] variabs.append(ivar) for de in des: desc.append(fast_float(de, *variabs)) def func(y, t): v = list(y[:]) v.append(t) return [dec(*v) for dec in desc] if (not compute_jac): Dfun = None else: J = jacobian(des, dvars) J = [list(v) for v in J] J = fast_float(J, *variabs) def Dfun(y, t): v = list(y[:]) v.append(t) return [[element(*v) for element in row] for row in J] return odeint(func, ics, times, args=args, Dfun=Dfun, rtol=rtol, atol=atol, tcrit=tcrit, h0=h0, hmax=hmax, hmin=hmin, ixpr=ixpr, mxstep=mxstep, mxhnil=mxhnil, mxordn=mxordn, mxords=mxords, printmessg=printmessg) if (isinstance(dvars, Expression) and dvars.is_symbol()): dvars = [dvars] if (not isinstance(des, (list, tuple))): des = [des] if (ivar is None): all_vars = set().union(*[de.variables() for de in des]) ivars = (all_vars - set(dvars)) if (len(ivars) == 1): return desolve_odeint_inner(next(iter(ivars))) elif (not ivars): from sage.symbolic.ring import SR with SR.temp_var() as ivar: return desolve_odeint_inner(ivar) else: raise ValueError('Unable to determine independent variable, please specify.') return desolve_odeint_inner(ivar)
def desolve_mintides(f, ics, initial, final, delta, tolrel=1e-16, tolabs=1e-16): "\n Solve numerically a system of first order differential equations using the\n taylor series integrator implemented in mintides.\n\n INPUT:\n\n - ``f`` -- symbolic function. Its first argument will be the independent\n variable. Its output should be de derivatives of the dependent variables.\n\n - ``ics`` -- a list or tuple with the initial conditions.\n\n - ``initial`` -- the starting value for the independent variable.\n\n - ``final`` -- the final value for the independent value.\n\n - ``delta`` -- the size of the steps in the output.\n\n - ``tolrel`` -- the relative tolerance for the method.\n\n - ``tolabs`` -- the absolute tolerance for the method.\n\n\n OUTPUT:\n\n - A list with the positions of the IVP.\n\n\n EXAMPLES:\n\n We integrate a periodic orbit of the Kepler problem along 50 periods::\n\n sage: var('t,x,y,X,Y')\n (t, x, y, X, Y)\n sage: f(t,x,y,X,Y)=[X, Y, -x/(x^2+y^2)^(3/2), -y/(x^2+y^2)^(3/2)]\n sage: ics = [0.8, 0, 0, 1.22474487139159]\n sage: t = 100*pi\n sage: sol = desolve_mintides(f, ics, 0, t, t, 1e-12, 1e-12) # optional -tides\n sage: sol # optional -tides # abs tol 1e-5\n [[0.000000000000000,\n 0.800000000000000,\n 0.000000000000000,\n 0.000000000000000,\n 1.22474487139159],\n [314.159265358979,\n 0.800000000028622,\n -5.91973525754241e-9,\n 7.56887091890590e-9,\n 1.22474487136329]]\n\n\n ALGORITHM:\n\n Uses TIDES.\n\n REFERENCES:\n\n - A. Abad, R. Barrio, F. Blesa, M. Rodriguez. Algorithm 924. *ACM\n Transactions on Mathematical Software* , *39* (1), 1-28.\n\n - A. Abad, R. Barrio, F. Blesa, M. Rodriguez.\n `TIDES tutorial: Integrating ODEs by using the Taylor Series Method.\n <http://www.unizar.es/acz/05Publicaciones/Monografias/MonografiasPublicadas/Monografia36/IndMonogr36.htm>`_\n " import subprocess if subprocess.call('command -v gcc', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE): raise RuntimeError('Unable to run because gcc cannot be found') from sage.interfaces.tides import genfiles_mintides from sage.misc.temporary_file import tmp_dir tempdir = tmp_dir() intfile = os.path.join(tempdir, 'integrator.c') drfile = os.path.join(tempdir, 'driver.c') fileoutput = os.path.join(tempdir, 'output') runmefile = os.path.join(tempdir, 'runme') genfiles_mintides(intfile, drfile, f, [N(_) for _ in ics], N(initial), N(final), N(delta), N(tolrel), N(tolabs), fileoutput) subprocess.check_call((((((((('gcc -o ' + runmefile) + ' ') + os.path.join(tempdir, '*.c ')) + os.path.join('$SAGE_LOCAL', 'lib', 'libTIDES.a')) + ' $LDFLAGS ') + os.path.join('-L$SAGE_LOCAL', 'lib ')) + ' -lm -O2 ') + os.path.join('-I$SAGE_LOCAL', 'include ')), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) subprocess.check_call(os.path.join(tempdir, 'runme'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) with open(fileoutput) as outfile: res = outfile.readlines() for i in range(len(res)): res[i] = [RealField()(_) for _ in res[i].split(' ') if (len(_) > 2)] shutil.rmtree(tempdir) return res
def desolve_tides_mpfr(f, ics, initial, final, delta, tolrel=1e-16, tolabs=1e-16, digits=50): "\n Solve numerically a system of first order differential equations using the\n taylor series integrator in arbitrary precision implemented in tides.\n\n INPUT:\n\n - ``f`` -- symbolic function. Its first argument will be the independent\n variable. Its output should be de derivatives of the dependent variables.\n\n - ``ics`` -- a list or tuple with the initial conditions.\n\n - ``initial`` -- the starting value for the independent variable.\n\n - ``final`` -- the final value for the independent value.\n\n - ``delta`` -- the size of the steps in the output.\n\n - ``tolrel`` -- the relative tolerance for the method.\n\n - ``tolabs`` -- the absolute tolerance for the method.\n\n - ``digits`` -- the digits of precision used in the computation.\n\n\n OUTPUT:\n\n - A list with the positions of the IVP.\n\n\n EXAMPLES:\n\n We integrate the Lorenz equations with Saltzman values for the parameters\n along 10 periodic orbits with 100 digits of precision::\n\n sage: var('t,x,y,z')\n (t, x, y, z)\n sage: s = 10\n sage: r = 28\n sage: b = 8/3\n sage: f(t,x,y,z)= [s*(y-x),x*(r-z)-y,x*y-b*z]\n sage: x0 = -13.7636106821342005250144010543616538641008648540923684535378642921202827747268115852940239346395038284\n sage: y0 = -19.5787519424517955388380414460095588661142400534276438649791334295426354746147526415973165506704676171\n sage: z0 = 27\n sage: T = 15.586522107161747275678702092126960705284805489972439358895215783190198756258880854355851082660142374\n sage: sol = desolve_tides_mpfr(f, [x0, y0, z0], 0, T, T, 1e-100, 1e-100, 100) # optional - tides\n sage: sol # optional -tides # abs tol 1e-50\n [[0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,\n -13.7636106821342005250144010543616538641008648540923684535378642921202827747268115852940239346395038,\n -19.5787519424517955388380414460095588661142400534276438649791334295426354746147526415973165506704676,\n 27.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000],\n [15.5865221071617472756787020921269607052848054899724393588952157831901987562588808543558510826601424,\n -13.7636106821342005250144010543616538641008648540923684535378642921202827747268115852940239346315658,\n -19.5787519424517955388380414460095588661142400534276438649791334295426354746147526415973165506778440,\n 26.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999636628]]\n\n\n ALGORITHM:\n\n Uses TIDES.\n\n\n .. WARNING::\n\n This requires the package tides.\n\n REFERENCES:\n\n - [ABBR2011]_\n - [ABBR2012]_\n " import subprocess if subprocess.call('command -v gcc', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE): raise RuntimeError('Unable to run because gcc cannot be found') from sage.interfaces.tides import genfiles_mpfr from sage.functions.other import ceil from sage.functions.log import log from sage.misc.temporary_file import tmp_dir tempdir = tmp_dir() intfile = os.path.join(tempdir, 'integrator.c') drfile = os.path.join(tempdir, 'driver.c') fileoutput = os.path.join(tempdir, 'output') runmefile = os.path.join(tempdir, 'runme') genfiles_mpfr(intfile, drfile, f, ics, initial, final, delta, [], [], digits, tolrel, tolabs, fileoutput) subprocess.check_call((((((((('gcc -o ' + runmefile) + ' ') + os.path.join(tempdir, '*.c ')) + os.path.join('$SAGE_LOCAL', 'lib', 'libTIDES.a')) + ' $LDFLAGS ') + os.path.join('-L$SAGE_LOCAL', 'lib ')) + '-lmpfr -lgmp -lm -O2 -w ') + os.path.join('-I$SAGE_LOCAL', 'include ')), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) subprocess.check_call(os.path.join(tempdir, 'runme'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) with open(fileoutput) as outfile: res = outfile.readlines() for i in range(len(res)): res[i] = [RealField(ceil((digits * log(10, 2))))(piece) for piece in res[i].split(' ') if (len(piece) > 2)] shutil.rmtree(tempdir) return res
def simplify(f, algorithm='maxima', **kwds): '\n Simplify the expression `f`.\n\n See the documentation of the\n :meth:`~sage.symbolic.expression.Expression.simplify` method of symbolic\n expressions for details on options.\n\n EXAMPLES:\n\n We simplify the expression `i + x - x`::\n\n sage: f = I + x - x; simplify(f)\n I\n\n In fact, printing `f` yields the same thing - i.e., the\n simplified form.\n\n Some simplifications are algorithm-specific::\n\n sage: x, t = var("x, t")\n sage: ex = 1/2*I*x + 1/2*I*sqrt(x^2 - 1) + 1/2/(I*x + I*sqrt(x^2 - 1))\n sage: simplify(ex)\n 1/2*I*x + 1/2*I*sqrt(x^2 - 1) + 1/(2*I*x + 2*I*sqrt(x^2 - 1))\n sage: simplify(ex, algorithm="giac")\n I*sqrt(x^2 - 1)\n ' try: return f.simplify(algorithm=algorithm, **kwds) except (TypeError, AttributeError): pass try: return f.simplify() except AttributeError: return f
def derivative(f, *args, **kwds): "\n The derivative of `f`.\n\n Repeated differentiation is supported by the syntax given in the\n examples below.\n\n ALIAS: diff\n\n EXAMPLES: We differentiate a callable symbolic function::\n\n sage: f(x,y) = x*y + sin(x^2) + e^(-x)\n sage: f\n (x, y) |--> x*y + e^(-x) + sin(x^2)\n sage: derivative(f, x)\n (x, y) |--> 2*x*cos(x^2) + y - e^(-x)\n sage: derivative(f, y)\n (x, y) |--> x\n\n We differentiate a polynomial::\n\n sage: t = polygen(QQ, 't')\n sage: f = (1-t)^5; f\n -t^5 + 5*t^4 - 10*t^3 + 10*t^2 - 5*t + 1\n sage: derivative(f)\n -5*t^4 + 20*t^3 - 30*t^2 + 20*t - 5\n sage: derivative(f, t)\n -5*t^4 + 20*t^3 - 30*t^2 + 20*t - 5\n sage: derivative(f, t, t)\n -20*t^3 + 60*t^2 - 60*t + 20\n sage: derivative(f, t, 2)\n -20*t^3 + 60*t^2 - 60*t + 20\n sage: derivative(f, 2)\n -20*t^3 + 60*t^2 - 60*t + 20\n\n We differentiate a symbolic expression::\n\n sage: var('a x')\n (a, x)\n sage: f = exp(sin(a - x^2))/x\n sage: derivative(f, x)\n -2*cos(-x^2 + a)*e^(sin(-x^2 + a)) - e^(sin(-x^2 + a))/x^2\n sage: derivative(f, a)\n cos(-x^2 + a)*e^(sin(-x^2 + a))/x\n\n Syntax for repeated differentiation::\n\n sage: R.<u, v> = PolynomialRing(QQ)\n sage: f = u^4*v^5\n sage: derivative(f, u)\n 4*u^3*v^5\n sage: f.derivative(u) # can always use method notation too\n 4*u^3*v^5\n\n ::\n\n sage: derivative(f, u, u)\n 12*u^2*v^5\n sage: derivative(f, u, u, u)\n 24*u*v^5\n sage: derivative(f, u, 3)\n 24*u*v^5\n\n ::\n\n sage: derivative(f, u, v)\n 20*u^3*v^4\n sage: derivative(f, u, 2, v)\n 60*u^2*v^4\n sage: derivative(f, u, v, 2)\n 80*u^3*v^3\n sage: derivative(f, [u, v, v])\n 80*u^3*v^3\n\n We differentiate a scalar field on a manifold::\n\n sage: M = Manifold(2, 'M')\n sage: X.<x,y> = M.chart()\n sage: f = M.scalar_field(x^2*y, name='f')\n sage: derivative(f)\n 1-form df on the 2-dimensional differentiable manifold M\n sage: derivative(f).display()\n df = 2*x*y dx + x^2 dy\n\n We differentiate a differentiable form, getting its exterior derivative::\n\n sage: a = M.one_form(-y, x, name='a'); a.display()\n a = -y dx + x dy\n sage: derivative(a)\n 2-form da on the 2-dimensional differentiable manifold M\n sage: derivative(a).display()\n da = 2 dx∧dy\n\n " try: return f.derivative(*args, **kwds) except AttributeError: pass if (not isinstance(f, Expression)): from sage.symbolic.ring import SR f = SR(f) return f.derivative(*args, **kwds)
def integral(f, *args, **kwds): '\n The integral of `f`.\n\n EXAMPLES::\n\n sage: integral(sin(x), x)\n -cos(x)\n sage: integral(sin(x)^2, x, pi, 123*pi/2)\n 121/4*pi\n sage: integral( sin(x), x, 0, pi)\n 2\n\n We integrate a symbolic function::\n\n sage: f(x,y,z) = x*y/z + sin(z)\n sage: integral(f, z)\n (x, y, z) |--> x*y*log(z) - cos(z)\n\n ::\n\n sage: var(\'a,b\')\n (a, b)\n sage: assume(b-a>0)\n sage: integral( sin(x), x, a, b)\n cos(a) - cos(b)\n sage: forget()\n\n ::\n\n sage: integral(x/(x^3-1), x)\n 1/3*sqrt(3)*arctan(1/3*sqrt(3)*(2*x + 1)) - 1/6*log(x^2 + x + 1) + 1/3*log(x - 1)\n\n ::\n\n sage: integral( exp(-x^2), x )\n 1/2*sqrt(pi)*erf(x)\n\n We define the Gaussian, plot and integrate it numerically and\n symbolically::\n\n sage: f(x) = 1/(sqrt(2*pi)) * e^(-x^2/2)\n sage: P = plot(f, -4, 4, hue=0.8, thickness=2)\n sage: P.show(ymin=0, ymax=0.4)\n sage: numerical_integral(f, -4, 4) # random output\n (0.99993665751633376, 1.1101527003413533e-14)\n sage: integrate(f, x)\n x |--> 1/2*erf(1/2*sqrt(2)*x)\n\n You can have Sage calculate multiple integrals. For example,\n consider the function `exp(y^2)` on the region between the\n lines `x=y`, `x=1`, and `y=0`. We find the\n value of the integral on this region using the command::\n\n sage: area = integral(integral(exp(y^2),x,0,y),y,0,1); area\n 1/2*e - 1/2\n sage: float(area)\n 0.859140914229522...\n\n We compute the line integral of `\\sin(x)` along the arc of\n the curve `x=y^4` from `(1,-1)` to\n `(1,1)`::\n\n sage: t = var(\'t\')\n sage: (x,y) = (t^4,t)\n sage: (dx,dy) = (diff(x,t), diff(y,t))\n sage: integral(sin(x)*dx, t,-1, 1)\n 0\n sage: restore(\'x,y\') # restore the symbolic variables x and y\n\n Sage is now (:trac:`27958`) able to compute the following integral::\n\n sage: integral(exp(-x^2)*log(x), x) # long time\n 1/2*sqrt(pi)*erf(x)*log(x) - x*hypergeometric((1/2, 1/2), (3/2, 3/2), -x^2)\n\n and its value::\n\n sage: integral( exp(-x^2)*ln(x), x, 0, oo)\n -1/4*sqrt(pi)*(euler_gamma + 2*log(2))\n\n This definite integral is easy::\n\n sage: integral( ln(x)/x, x, 1, 2)\n 1/2*log(2)^2\n\n Sage cannot do this elliptic integral (yet)::\n\n sage: integral(1/sqrt(2*t^4 - 3*t^2 - 2), t, 2, 3)\n integrate(1/(sqrt(2*t^2 + 1)*sqrt(t^2 - 2)), t, 2, 3)\n\n A double integral::\n\n sage: y = var(\'y\')\n sage: integral(integral(x*y^2, x, 0, y), y, -2, 2)\n 32/5\n\n This illustrates using assumptions::\n\n sage: integral(abs(x), x, 0, 5)\n 25/2\n sage: a = var("a")\n sage: integral(abs(x), x, 0, a)\n 1/2*a*abs(a)\n sage: integral(abs(x)*x, x, 0, a)\n Traceback (most recent call last):\n ...\n ValueError: Computation failed since Maxima requested additional\n constraints; using the \'assume\' command before evaluation\n *may* help (example of legal syntax is \'assume(a>0)\',\n see `assume?` for more details)\n Is a positive, negative or zero?\n sage: assume(a>0)\n sage: integral(abs(x)*x, x, 0, a)\n 1/3*a^3\n sage: forget() # forget the assumptions.\n\n We integrate and differentiate a huge mess::\n\n sage: f = (x^2-1+3*(1+x^2)^(1/3))/(1+x^2)^(2/3)*x/(x^2+2)^2\n sage: g = integral(f, x)\n sage: h = f - diff(g, x)\n\n ::\n\n sage: [float(h(x=i)) for i in range(5)] #random\n\n [0.0,\n -1.1102230246251565e-16,\n -5.5511151231257827e-17,\n -5.5511151231257827e-17,\n -6.9388939039072284e-17]\n sage: h.factor()\n 0\n sage: bool(h == 0)\n True\n ' try: return f.integral(*args, **kwds) except AttributeError: pass if (not isinstance(f, Expression)): from sage.symbolic.ring import SR f = SR(f) return f.integral(*args, **kwds)
def limit(f, dir=None, taylor=False, **argv): "\n Return the limit as the variable `v` approaches `a`\n from the given direction.\n\n ::\n\n limit(expr, x = a)\n limit(expr, x = a, dir='above')\n\n\n INPUT:\n\n - ``dir`` - (default: None); dir may have the value\n 'plus' (or 'above') for a limit from above, 'minus' (or 'below')\n for a limit from below, or may be omitted (implying a two-sided\n limit is to be computed).\n\n - ``taylor`` - (default: False); if True, use Taylor\n series, which allows more limits to be computed (but may also\n crash in some obscure cases due to bugs in Maxima).\n\n - ``\\*\\*argv`` - 1 named parameter\n\n ALIAS: You can also use lim instead of limit.\n\n EXAMPLES::\n\n sage: limit(sin(x)/x, x=0)\n 1\n sage: limit(exp(x), x=oo)\n +Infinity\n sage: lim(exp(x), x=-oo)\n 0\n sage: lim(1/x, x=0)\n Infinity\n sage: limit(sqrt(x^2+x+1)+x, taylor=True, x=-oo)\n -1/2\n sage: limit((tan(sin(x)) - sin(tan(x)))/x^7, taylor=True, x=0)\n 1/30\n\n Sage does not know how to do this limit (which is 0), so it returns\n it unevaluated::\n\n sage: lim(exp(x^2)*(1-erf(x)), x=infinity)\n -limit((erf(x) - 1)*e^(x^2), x, +Infinity)\n " if (not isinstance(f, Expression)): from sage.symbolic.ring import SR f = SR(f) return f.limit(dir=dir, taylor=taylor, **argv)
def taylor(f, *args): "\n Expands self in a truncated Taylor or Laurent series in the\n variable `v` around the point `a`, containing terms\n through `(x - a)^n`. Functions in more variables are also\n supported.\n\n INPUT:\n\n - ``*args`` - the following notation is supported\n\n - ``x, a, n`` - variable, point, degree\n\n - ``(x, a), (y, b), ..., n`` - variables with points, degree of polynomial\n\n EXAMPLES::\n\n sage: var('x,k,n')\n (x, k, n)\n sage: taylor (sqrt (1 - k^2*sin(x)^2), x, 0, 6)\n -1/720*(45*k^6 - 60*k^4 + 16*k^2)*x^6 - 1/24*(3*k^4 - 4*k^2)*x^4 - 1/2*k^2*x^2 + 1\n\n ::\n\n sage: taylor ((x + 1)^n, x, 0, 4)\n 1/24*(n^4 - 6*n^3 + 11*n^2 - 6*n)*x^4 + 1/6*(n^3 - 3*n^2 + 2*n)*x^3 + 1/2*(n^2 - n)*x^2 + n*x + 1\n\n ::\n\n sage: taylor ((x + 1)^n, x, 0, 4)\n 1/24*(n^4 - 6*n^3 + 11*n^2 - 6*n)*x^4 + 1/6*(n^3 - 3*n^2 + 2*n)*x^3 + 1/2*(n^2 - n)*x^2 + n*x + 1\n\n Taylor polynomial in two variables::\n\n sage: x,y=var('x y'); taylor(x*y^3,(x,1),(y,-1),4)\n (x - 1)*(y + 1)^3 - 3*(x - 1)*(y + 1)^2 + (y + 1)^3 + 3*(x - 1)*(y + 1) - 3*(y + 1)^2 - x + 3*y + 3\n " if (not isinstance(f, Expression)): from sage.symbolic.ring import SR f = SR(f) return f.taylor(*args)
def expand(x, *args, **kwds): '\n EXAMPLES::\n\n sage: a = (x-1)*(x^2 - 1); a\n (x^2 - 1)*(x - 1)\n sage: expand(a)\n x^3 - x^2 - x + 1\n\n You can also use expand on polynomial, integer, and other\n factorizations::\n\n sage: x = polygen(ZZ)\n sage: F = factor(x^12 - 1); F\n (x - 1) * (x + 1) * (x^2 - x + 1) * (x^2 + 1) * (x^2 + x + 1) * (x^4 - x^2 + 1)\n sage: expand(F)\n x^12 - 1\n sage: F.expand()\n x^12 - 1\n sage: F = factor(2007); F\n 3^2 * 223\n sage: expand(F)\n 2007\n\n Note: If you want to compute the expanded form of a polynomial\n arithmetic operation quickly and the coefficients of the polynomial\n all lie in some ring, e.g., the integers, it is vastly faster to\n create a polynomial ring and do the arithmetic there.\n\n ::\n\n sage: x = polygen(ZZ) # polynomial over a given base ring.\n sage: f = sum(x^n for n in range(5))\n sage: f*f # much faster, even if the degree is huge\n x^8 + 2*x^7 + 3*x^6 + 4*x^5 + 5*x^4 + 4*x^3 + 3*x^2 + 2*x + 1\n\n TESTS::\n\n sage: t1 = (sqrt(3)-3)*(sqrt(3)+1)/6\n sage: tt1 = -1/sqrt(3)\n sage: t2 = sqrt(3)/6\n sage: float(t1)\n -0.577350269189625...\n sage: float(tt1)\n -0.577350269189625...\n sage: float(t2)\n 0.28867513459481287\n sage: float(expand(t1 + t2))\n -0.288675134594812...\n sage: float(expand(tt1 + t2))\n -0.288675134594812...\n ' try: return x.expand(*args, **kwds) except AttributeError: return x
def wronskian(*args): "\n Return the Wronskian of the provided functions, differentiating with\n respect to the given variable.\n\n If no variable is provided, diff(f) is called for each function f.\n\n wronskian(f1,...,fn, x) returns the Wronskian of f1,...,fn, with\n derivatives taken with respect to x.\n\n wronskian(f1,...,fn) returns the Wronskian of f1,...,fn where\n k'th derivatives are computed by doing ``.derivative(k)`` on each\n function.\n\n The Wronskian of a list of functions is a determinant of derivatives.\n The nth row (starting from 0) is a list of the nth derivatives of the\n given functions.\n\n For two functions::\n\n | f g |\n W(f, g) = det| | = f*g' - g*f'.\n | f' g' |\n\n EXAMPLES::\n\n sage: wronskian(e^x, x^2)\n -x^2*e^x + 2*x*e^x\n\n sage: x,y = var('x, y')\n sage: wronskian(x*y, log(x), x)\n -y*log(x) + y\n\n If your functions are in a list, you can use `*' to turn them into\n arguments to :func:`wronskian`::\n\n sage: wronskian(*[x^k for k in range(1, 5)])\n 12*x^4\n\n If you want to use 'x' as one of the functions in the Wronskian,\n you can't put it last or it will be interpreted as the variable\n with respect to which we differentiate. There are several ways to\n get around this.\n\n Two-by-two Wronskian of sin(x) and e^x::\n\n sage: wronskian(sin(x), e^x, x)\n -cos(x)*e^x + e^x*sin(x)\n\n Or don't put x last::\n\n sage: wronskian(x, sin(x), e^x)\n (cos(x)*e^x + e^x*sin(x))*x - 2*e^x*sin(x)\n\n Example where one of the functions is constant::\n\n sage: wronskian(1, e^(-x), e^(2*x))\n -6*e^x\n\n REFERENCES:\n\n - :wikipedia:`Wronskian`\n - http://planetmath.org/encyclopedia/WronskianDeterminant.html\n\n AUTHORS:\n\n - Dan Drake (2008-03-12)\n " if (not args): raise TypeError('wronskian() takes at least one argument (0 given)') elif (len(args) == 1): return args[0] else: if (isinstance(args[(- 1)], Expression) and args[(- 1)].is_symbol()): v = args[(- 1)] fs = args[0:(- 1)] def row(n): return [diff(f, v, n) for f in fs] else: fs = args def row(n): return [diff(f, n) for f in fs] return matrix([row(r) for r in range(len(fs))]).determinant()
def jacobian(functions, variables): '\n Return the Jacobian matrix, which is the matrix of partial\n derivatives in which the i,j entry of the Jacobian matrix is the\n partial derivative diff(functions[i], variables[j]).\n\n EXAMPLES::\n\n sage: x,y = var(\'x,y\')\n sage: g=x^2-2*x*y\n sage: jacobian(g, (x,y))\n [2*x - 2*y -2*x]\n\n The Jacobian of the Jacobian should give us the "second derivative", which is the Hessian matrix::\n\n sage: jacobian(jacobian(g, (x,y)), (x,y))\n [ 2 -2]\n [-2 0]\n sage: g.hessian()\n [ 2 -2]\n [-2 0]\n\n sage: f=(x^3*sin(y), cos(x)*sin(y), exp(x))\n sage: jacobian(f, (x,y))\n [ 3*x^2*sin(y) x^3*cos(y)]\n [-sin(x)*sin(y) cos(x)*cos(y)]\n [ e^x 0]\n sage: jacobian(f, (y,x))\n [ x^3*cos(y) 3*x^2*sin(y)]\n [ cos(x)*cos(y) -sin(x)*sin(y)]\n [ 0 e^x]\n ' if (is_Matrix(functions) and ((functions.nrows() == 1) or (functions.ncols() == 1))): functions = functions.list() elif (not (isinstance(functions, (tuple, list)) or is_Vector(functions))): functions = [functions] if ((not isinstance(variables, (tuple, list))) and (not is_Vector(variables))): variables = [variables] return matrix([[diff(f, v) for v in variables] for f in functions])
class IndexedSequence(SageObject): '\n An indexed sequence.\n\n INPUT:\n\n - ``L`` -- A list\n\n - ``index_object`` must be a Sage object with an ``__iter__`` method\n containing the same number of elements as ``self``, which is a\n list of elements taken from a field.\n ' def __init__(self, L, index_object): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: J = list(range(10))\n sage: A = [1/10 for j in J]\n sage: s = IndexedSequence(A,J)\n sage: s\n Indexed sequence: [1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10]\n indexed by [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n sage: s.dict()\n {0: 1/10,\n 1: 1/10,\n 2: 1/10,\n 3: 1/10,\n 4: 1/10,\n 5: 1/10,\n 6: 1/10,\n 7: 1/10,\n 8: 1/10,\n 9: 1/10}\n sage: s.list()\n [1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10]\n sage: s.index_object()\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n sage: s.base_ring()\n Rational Field\n ' try: ind = index_object.list() except AttributeError: ind = list(index_object) self._index_object = index_object self._list = Sequence(L) self._base_ring = self._list.universe() dict = {} for i in range(len(ind)): dict[ind[i]] = L[i] self._dict = dict def dict(self): '\n Return a python dict of ``self`` where the keys are elements in the\n indexing set.\n\n EXAMPLES::\n\n sage: J = list(range(10))\n sage: A = [1/10 for j in J]\n sage: s = IndexedSequence(A,J)\n sage: s.dict()\n {0: 1/10, 1: 1/10, 2: 1/10, 3: 1/10, 4: 1/10, 5: 1/10, 6: 1/10, 7: 1/10, 8: 1/10, 9: 1/10}\n ' return self._dict def list(self): '\n Return the list of ``self``.\n\n EXAMPLES::\n\n sage: J = list(range(10))\n sage: A = [1/10 for j in J]\n sage: s = IndexedSequence(A,J)\n sage: s.list()\n [1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10, 1/10]\n ' return self._list def base_ring(self): '\n This just returns the common parent `R` of the `N` list\n elements. In some applications (say, when computing the\n discrete Fourier transform, dft), it is more accurate to think\n of the base_ring as the group ring `\\QQ(\\zeta_N)[R]`.\n\n EXAMPLES::\n\n sage: J = list(range(10))\n sage: A = [1/10 for j in J]\n sage: s = IndexedSequence(A,J)\n sage: s.base_ring()\n Rational Field\n ' return self._base_ring def index_object(self): '\n Return the indexing object.\n\n EXAMPLES::\n\n sage: J = list(range(10))\n sage: A = [1/10 for j in J]\n sage: s = IndexedSequence(A,J)\n sage: s.index_object()\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n ' return self._index_object def _repr_(self): '\n Implements print method.\n\n EXAMPLES::\n\n sage: A = [ZZ(i) for i in range(3)]\n sage: I = list(range(3))\n sage: s = IndexedSequence(A,I)\n sage: s\n Indexed sequence: [0, 1, 2]\n indexed by [0, 1, 2]\n sage: print(s)\n Indexed sequence: [0, 1, 2]\n indexed by [0, 1, 2]\n sage: I = GF(3)\n sage: A = [i^2 for i in I]\n sage: s = IndexedSequence(A,I); s\n Indexed sequence: [0, 1, 1]\n indexed by Finite Field of size 3\n ' return ((('Indexed sequence: ' + str(self.list())) + '\n indexed by ') + str(self.index_object())) def plot_histogram(self, clr=(0, 0, 1), eps=0.4): '\n Plot the histogram plot of the sequence.\n\n The sequence is assumed to be real or from a finite field,\n with a real indexing set ``I`` coercible into `\\RR`.\n\n Options are ``clr``, which is an RGB value, and ``eps``, which\n is the spacing between the bars.\n\n EXAMPLES::\n\n sage: J = list(range(3))\n sage: A = [ZZ(i^2)+1 for i in J]\n sage: s = IndexedSequence(A,J)\n sage: P = s.plot_histogram() # needs sage.plot\n sage: show(P) # not tested # needs sage.plot\n ' from sage.rings.real_mpfr import RR I = self.index_object() N = len(I) S = self.list() P = [polygon([[(RR(I[i]) - eps), 0], [(RR(I[i]) - eps), RR(S[i])], [(RR(I[i]) + eps), RR(S[i])], [(RR(I[i]) + eps), 0], [RR(I[i]), 0]], rgbcolor=clr) for i in range(N)] T = [text(str(I[i]), (RR(I[i]), (- 0.8)), fontsize=15, rgbcolor=(1, 0, 0)) for i in range(N)] return (sum(P) + sum(T)) def plot(self): '\n Plot the points of the sequence.\n\n Elements of the sequence are assumed to be real or from a\n finite field, with a real indexing set ``I = range(len(self))``.\n\n EXAMPLES::\n\n sage: I = list(range(3))\n sage: A = [ZZ(i^2)+1 for i in I]\n sage: s = IndexedSequence(A,I)\n sage: P = s.plot() # needs sage.plot\n sage: show(P) # not tested # needs sage.plot\n ' from sage.rings.real_mpfr import RR I = self.index_object() S = self.list() return line([[RR(I[i]), RR(S[i])] for i in range((len(I) - 1))]) def dft(self, chi=None): '\n A discrete Fourier transform "over `\\QQ`" using exact\n `N`-th roots of unity.\n\n EXAMPLES::\n\n sage: J = list(range(6))\n sage: A = [ZZ(1) for i in J]\n sage: s = IndexedSequence(A,J)\n sage: s.dft(lambda x: x^2) # needs sage.rings.number_field\n Indexed sequence: [6, 0, 0, 6, 0, 0]\n indexed by [0, 1, 2, 3, 4, 5]\n sage: s.dft() # needs sage.rings.number_field\n Indexed sequence: [6, 0, 0, 0, 0, 0]\n indexed by [0, 1, 2, 3, 4, 5]\n\n sage: # needs sage.groups\n sage: G = SymmetricGroup(3)\n sage: J = G.conjugacy_classes_representatives()\n sage: s = IndexedSequence([1,2,3], J) # 1,2,3 are the values of a class fcn on G\n sage: s.dft() # the "scalar-valued Fourier transform" of this class fcn\n Indexed sequence: [8, 2, 2]\n indexed by [(), (1,2), (1,2,3)]\n sage: J = AbelianGroup(2, [2,3], names=\'ab\')\n sage: s = IndexedSequence([1,2,3,4,5,6], J)\n sage: s.dft() # the precision of output is somewhat random and architecture dependent.\n Indexed sequence: [21.0000000000000,\n -2.99999999999997 - 1.73205080756885*I,\n -2.99999999999999 + 1.73205080756888*I,\n -9.00000000000000 + 0.0000000000000485744257349999*I,\n -0.00000000000000976996261670137 - 0.0000000000000159872115546022*I,\n -0.00000000000000621724893790087 - 0.0000000000000106581410364015*I]\n indexed by Multiplicative Abelian group isomorphic to C2 x C3\n sage: J = CyclicPermutationGroup(6)\n sage: s = IndexedSequence([1,2,3,4,5,6], J)\n sage: s.dft() # the precision of output is somewhat random and architecture dependent.\n Indexed sequence: [21.0000000000000,\n -2.99999999999997 - 1.73205080756885*I,\n -2.99999999999999 + 1.73205080756888*I,\n -9.00000000000000 + 0.0000000000000485744257349999*I,\n -0.00000000000000976996261670137 - 0.0000000000000159872115546022*I,\n -0.00000000000000621724893790087 - 0.0000000000000106581410364015*I]\n indexed by Cyclic group of order 6 as a permutation group\n\n sage: # needs sage.rings.number_field\n sage: p = 7; J = list(range(p)); A = [kronecker_symbol(j,p) for j in J]\n sage: s = IndexedSequence(A, J)\n sage: Fs = s.dft()\n sage: c = Fs.list()[1]; [x/c for x in Fs.list()]; s.list()\n [0, 1, 1, -1, 1, -1, -1]\n [0, 1, 1, -1, 1, -1, -1]\n\n The DFT of the values of the quadratic residue symbol is itself, up to\n a constant factor (denoted c on the last line above).\n\n .. TODO::\n\n Read the parent of the elements of S; if `\\QQ` or `\\CC` leave as\n is; if AbelianGroup, use abelian_group_dual; if some other\n implemented Group (permutation, matrix), call .characters()\n and test if the index list is the set of conjugacy classes.\n ' if (chi is None): chi = (lambda x: x) J = self.index_object() N = len(J) S = self.list() F = self.base_ring() if (J[0] not in ZZ): G = J[0].parent() if ((J[0] in ZZ) and (F.base_ring().fraction_field() == QQ)): zeta = CyclotomicField(N).gen() FT = [sum([(S[i] * chi((zeta ** (i * j)))) for i in J]) for j in J] elif (((J[0] not in ZZ) and G.is_abelian() and (F == ZZ)) or (F.is_field() and (F.base_ring() == QQ))): if isinstance(J[0], PermutationGroupElement): n = G.order() a = list(n.factor()) invs = [(x[0] ** x[1]) for x in a] G = AbelianGroup(len(a), invs) Gd = G.dual_group() FT = [sum([(S[i] * chid(G.list()[i])) for i in range(N)]) for chid in Gd] elif (((J[0] not in ZZ) and G.is_finite() and (F == ZZ)) or (F.is_field() and (F.base_ring() == QQ))): chi = G.character_table() FT = [sum([(S[i] * chi[(i, j)]) for i in range(N)]) for j in range(N)] else: raise ValueError(f'list elements must be in QQ(zeta_{N})') return IndexedSequence(FT, J) def idft(self): '\n A discrete inverse Fourier transform. Only works over `\\QQ`.\n\n EXAMPLES::\n\n sage: J = list(range(5))\n sage: A = [ZZ(1) for i in J]\n sage: s = IndexedSequence(A,J)\n sage: fs = s.dft(); fs # needs sage.rings.number_field\n Indexed sequence: [5, 0, 0, 0, 0]\n indexed by [0, 1, 2, 3, 4]\n sage: it = fs.idft(); it # needs sage.rings.number_field\n Indexed sequence: [1, 1, 1, 1, 1]\n indexed by [0, 1, 2, 3, 4]\n sage: it == s # needs sage.rings.number_field\n True\n ' F = self.base_ring() J = self.index_object() N = len(J) S = self.list() zeta = CyclotomicField(N).gen() iFT = [sum([(S[i] * (zeta ** ((- i) * j))) for i in J]) for j in J] if ((J[0] not in ZZ) or (F.base_ring().fraction_field() != QQ)): raise NotImplementedError('Sorry this type of idft is not implemented yet.') return (IndexedSequence(iFT, J) * (Integer(1) / N)) def dct(self): '\n A discrete Cosine transform.\n\n EXAMPLES::\n\n sage: J = list(range(5))\n sage: A = [exp(-2*pi*i*I/5) for i in J] # needs sage.symbolic\n sage: s = IndexedSequence(A, J) # needs sage.symbolic\n sage: s.dct() # needs sage.symbolic\n Indexed sequence: [0, 1/16*(sqrt(5) + I*sqrt(-2*sqrt(5) + 10) + ...\n indexed by [0, 1, 2, 3, 4]\n ' F = self.base_ring() try: pi = F.pi() except AttributeError: from sage.symbolic.constants import pi pi = F(pi) J = self.index_object() N = len(J) S = self.list() PI = ((2 * pi) / N) FT = [sum([(S[i] * cos(((PI * i) * j))) for i in J]) for j in J] return IndexedSequence(FT, J) def dst(self): '\n A discrete Sine transform.\n\n EXAMPLES::\n\n sage: J = list(range(5))\n sage: I = CC.0; pi = CC.pi()\n sage: A = [exp(-2*pi*i*I/5) for i in J]\n sage: s = IndexedSequence(A, J)\n\n sage: s.dst() # discrete sine\n Indexed sequence: [0.000000000000000, 1.11022302462516e-16 - 2.50000000000000*I, ...]\n indexed by [0, 1, 2, 3, 4]\n ' F = self.base_ring() try: pi = F.pi() except AttributeError: from sage.symbolic.constants import pi pi = F(pi) J = self.index_object() N = len(J) S = self.list() PI = ((2 * F(pi)) / N) FT = [sum([(S[i] * sin(((PI * i) * j))) for i in J]) for j in J] return IndexedSequence(FT, J) def convolution(self, other): '\n Convolves two sequences of the same length (automatically expands\n the shortest one by extending it by 0 if they have different lengths).\n\n If `\\{a_n\\}` and `\\{b_n\\}` are sequences indexed by `(n=0,1,...,N-1)`,\n extended by zero for all `n` in `\\ZZ`, then the convolution is\n\n .. MATH::\n\n c_j = \\sum_{i=0}^{N-1} a_i b_{j-i}.\n\n INPUT:\n\n - ``other`` -- a collection of elements of a ring with\n index set a finite abelian group (under `+`)\n\n OUTPUT:\n\n The Dirichlet convolution of ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: J = list(range(5))\n sage: A = [ZZ(1) for i in J]\n sage: B = [ZZ(1) for i in J]\n sage: s = IndexedSequence(A,J)\n sage: t = IndexedSequence(B,J)\n sage: s.convolution(t)\n [1, 2, 3, 4, 5, 4, 3, 2, 1]\n\n AUTHOR: David Joyner (2006-09)\n ' S = self.list() T = other.list() I0 = self.index_object() J0 = other.index_object() F = self.base_ring() E = other.base_ring() if (F != E): raise TypeError('IndexedSequences must have same base ring') if (I0 != J0): raise TypeError('IndexedSequences must have same index set') M = len(S) N = len(T) if (M < N): a = ([S[i] for i in range(M)] + [F(0) for i in range((2 * N))]) b = (T + [E(0) for i in range((2 * M))]) if (M > N): b = ([T[i] for i in range(N)] + [E(0) for i in range((2 * M))]) a = (S + [F(0) for i in range((2 * M))]) if (M == N): a = (S + [F(0) for i in range((2 * M))]) b = (T + [E(0) for i in range((2 * M))]) N = max(M, N) return [sum([(a[i] * b[(j - i)]) for i in range(N)]) for j in range(((2 * N) - 1))] def convolution_periodic(self, other): '\n Convolves two collections indexed by a ``range(...)`` of the same\n length (automatically expands the shortest one by extending it\n by 0 if they have different lengths).\n\n If `\\{a_n\\}` and `\\{b_n\\}` are sequences indexed by `(n=0,1,...,N-1)`,\n extended periodically for all `n` in `\\ZZ`, then the convolution is\n\n .. MATH::\n\n c_j = \\sum_{i=0}^{N-1} a_i b_{j-i}.\n\n INPUT:\n\n - ``other`` -- a sequence of elements of `\\CC`, `\\RR` or `\\GF{q}`\n\n OUTPUT:\n\n The Dirichlet convolution of ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: I = list(range(5))\n sage: A = [ZZ(1) for i in I]\n sage: B = [ZZ(1) for i in I]\n sage: s = IndexedSequence(A,I)\n sage: t = IndexedSequence(B,I)\n sage: s.convolution_periodic(t)\n [5, 5, 5, 5, 5, 5, 5, 5, 5]\n\n AUTHOR: David Joyner (2006-09)\n ' S = self.list() T = other.list() I = self.index_object() J = other.index_object() F = self.base_ring() E = other.base_ring() if (F != E): raise TypeError('IndexedSequences must have same parent') if (I != J): raise TypeError('IndexedSequences must have same index set') M = len(S) N = len(T) if (M < N): a = ([S[i] for i in range(M)] + [F(0) for i in range((N - M))]) b = other if (M > N): b = ([T[i] for i in range(N)] + [E(0) for i in range((M - N))]) a = self if (M == N): a = S b = T N = max(M, N) return [sum([(a[i] * b[((j - i) % N)]) for i in range(N)]) for j in range(((2 * N) - 1))] def __mul__(self, other): '\n Implements scalar multiplication (on the right).\n\n EXAMPLES::\n\n sage: J = list(range(5))\n sage: A = [ZZ(1) for i in J]\n sage: s = IndexedSequence(A,J)\n sage: s.base_ring()\n Integer Ring\n sage: t = s*(1/3); t; t.base_ring()\n Indexed sequence: [1/3, 1/3, 1/3, 1/3, 1/3]\n indexed by [0, 1, 2, 3, 4]\n Rational Field\n ' S = self.list() S1 = [(S[i] * other) for i in range(len(self.index_object()))] return IndexedSequence(S1, self.index_object()) def __eq__(self, other): '\n Implements boolean equals.\n\n EXAMPLES::\n\n sage: J = list(range(5))\n sage: A = [ZZ(1) for i in J]\n sage: s = IndexedSequence(A,J)\n sage: t = s*(1/3)\n sage: t*3 == s\n 1\n\n .. WARNING::\n\n ** elements are considered different if they differ\n by ``10^(-8)``, which is pretty arbitrary -- use with CAUTION!! **\n ' if (type(self) is not type(other)): return False S = self.list() T = other.list() I = self.index_object() J = other.index_object() if (I != J): return False for i in I: try: if (abs((S[i] - T[i])) > (10 ** (- 8))): return False except TypeError: pass return True def fft(self): '\n Wraps the gsl ``FastFourierTransform.forward()`` in\n :mod:`~sage.calculus.transforms.fft`.\n\n If the length is a power of 2 then this automatically uses the\n radix2 method. If the number of sample points in the input is\n a power of 2 then the wrapper for the GSL function\n ``gsl_fft_complex_radix2_forward()`` is automatically called.\n Otherwise, ``gsl_fft_complex_forward()`` is used.\n\n EXAMPLES::\n\n sage: J = list(range(5))\n sage: A = [RR(1) for i in J]\n sage: s = IndexedSequence(A,J)\n sage: t = s.fft(); t\n Indexed sequence: [5.00000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000]\n indexed by [0, 1, 2, 3, 4]\n ' from sage.rings.cc import CC I = CC.gen() J = self.index_object() N = len(J) S = self.list() a = FastFourierTransform(N) for i in range(N): a[i] = S[i] a.forward_transform() return IndexedSequence([(a[j][0] + (I * a[j][1])) for j in J], J) def ifft(self): '\n Implements the gsl ``FastFourierTransform.inverse`` in\n :mod:`~sage.calculus.transforms.fft`.\n\n If the number of sample points in the input is a power of 2\n then the wrapper for the GSL function\n ``gsl_fft_complex_radix2_inverse()`` is automatically called.\n Otherwise, ``gsl_fft_complex_inverse()`` is used.\n\n EXAMPLES::\n\n sage: J = list(range(5))\n sage: A = [RR(1) for i in J]\n sage: s = IndexedSequence(A,J)\n sage: t = s.fft(); t\n Indexed sequence: [5.00000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000]\n indexed by [0, 1, 2, 3, 4]\n sage: t.ifft()\n Indexed sequence: [1.00000000000000, 1.00000000000000, 1.00000000000000, 1.00000000000000, 1.00000000000000]\n indexed by [0, 1, 2, 3, 4]\n sage: t.ifft() == s\n 1\n ' from sage.rings.cc import CC I = CC.gen() J = self.index_object() N = len(J) S = self.list() a = FastFourierTransform(N) for i in range(N): a[i] = S[i] a.inverse_transform() return IndexedSequence([(a[j][0] + (I * a[j][1])) for j in J], J) def dwt(self, other='haar', wavelet_k=2): "\n Wraps the gsl ``WaveletTransform.forward`` in :mod:`~sage.calculus.transforms.dwt`\n (written by Joshua Kantor). Assumes the length of the sample is a\n power of 2. Uses the GSL function ``gsl_wavelet_transform_forward()``.\n\n INPUT:\n\n - ``other`` -- the name of the type of wavelet; valid choices are:\n\n * ``'daubechies'``\n * ``'daubechies_centered'``\n * ``'haar'`` (default)\n * ``'haar_centered'``\n * ``'bspline'``\n * ``'bspline_centered'``\n\n - ``wavelet_k`` -- For daubechies wavelets, ``wavelet_k`` specifies a\n daubechie wavelet with `k/2` vanishing moments.\n `k = 4,6,...,20` for `k` even are the only ones implemented.\n\n For Haar wavelets, ``wavelet_k`` must be 2.\n\n For bspline wavelets, ``wavelet_k`` equal to `103,105,202,204,\n 206,208,301,305,307,309` will give biorthogonal B-spline wavelets\n of order `(i,j)` where ``wavelet_k`` equals `100 \\cdot i + j`.\n\n The wavelet transform uses `J = \\log_2(n)` levels.\n\n EXAMPLES::\n\n sage: J = list(range(8))\n sage: A = [RR(1) for i in J]\n sage: s = IndexedSequence(A,J)\n sage: t = s.dwt()\n sage: t # slightly random output\n Indexed sequence: [2.82842712474999, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000]\n indexed by [0, 1, 2, 3, 4, 5, 6, 7]\n " from sage.rings.real_mpfr import RR J = self.index_object() N = len(J) S = self.list() if ((other == 'haar') or (other == 'haar_centered')): if (wavelet_k in [2]): a = WaveletTransform(N, other, wavelet_k) else: raise ValueError('wavelet_k must be = 2') if ((other == 'daubechies') or (other == 'daubechies_centered')): if (wavelet_k in [4, 6, 8, 10, 12, 14, 16, 18, 20]): a = WaveletTransform(N, other, wavelet_k) else: raise ValueError('wavelet_k must be in {4,6,8,10,12,14,16,18,20}') if ((other == 'bspline') or (other == 'bspline_centered')): if (wavelet_k in [103, 105, 202, 204, 206, 208, 301, 305, 307, 309]): a = WaveletTransform(N, other, 103) else: raise ValueError('wavelet_k must be in {103,105,202,204,206,208,301,305,307,309}') for i in range(N): a[i] = S[i] a.forward_transform() return IndexedSequence([RR(a[j]) for j in J], J) def idwt(self, other='haar', wavelet_k=2): '\n Implements the gsl ``WaveletTransform.backward()`` in\n :mod:`~sage.calculus.transforms.dwt`.\n\n Assumes the length of the sample is a power of 2. Uses the\n GSL function ``gsl_wavelet_transform_backward()``.\n\n INPUT:\n\n - ``other`` -- Must be one of the following:\n\n * ``"haar"``\n * ``"daubechies"``\n * ``"daubechies_centered"``\n * ``"haar_centered"``\n * ``"bspline"``\n * ``"bspline_centered"``\n\n - ``wavelet_k`` -- For daubechies wavelets, ``wavelet_k`` specifies a\n daubechie wavelet with `k/2` vanishing moments.\n `k = 4,6,...,20` for `k` even are the only ones implemented.\n\n For Haar wavelets, ``wavelet_k`` must be 2.\n\n For bspline wavelets, ``wavelet_k`` equal to `103,105,202,204,\n 206,208,301,305,307,309` will give biorthogonal B-spline wavelets\n of order `(i,j)` where ``wavelet_k`` equals `100 \\cdot i + j`.\n\n EXAMPLES::\n\n sage: J = list(range(8))\n sage: A = [RR(1) for i in J]\n sage: s = IndexedSequence(A,J)\n sage: t = s.dwt()\n sage: t # random arch dependent output\n Indexed sequence: [2.82842712474999, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000]\n indexed by [0, 1, 2, 3, 4, 5, 6, 7]\n sage: t.idwt() # random arch dependent output\n Indexed sequence: [1.00000000000000, 1.00000000000000, 1.00000000000000, 1.00000000000000, 1.00000000000000, 1.00000000000000, 1.00000000000000, 1.00000000000000]\n indexed by [0, 1, 2, 3, 4, 5, 6, 7]\n sage: t.idwt() == s\n True\n sage: J = list(range(16))\n sage: A = [RR(1) for i in J]\n sage: s = IndexedSequence(A,J)\n sage: t = s.dwt("bspline", 103)\n sage: t # random arch dependent output\n Indexed sequence: [4.00000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000, 0.000000000000000]\n indexed by [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n sage: t.idwt("bspline", 103) == s\n True\n ' from sage.rings.real_mpfr import RR J = self.index_object() N = len(J) S = self.list() k = wavelet_k if ((other == 'haar') or (other == 'haar_centered')): if (k in [2]): a = WaveletTransform(N, other, wavelet_k) else: raise ValueError('wavelet_k must be = 2') if ((other == 'daubechies') or (other == 'daubechies_centered')): if (k in [4, 6, 8, 10, 12, 14, 16, 18, 20]): a = WaveletTransform(N, other, wavelet_k) else: raise ValueError('wavelet_k must be in {4,6,8,10,12,14,16,18,20}') if ((other == 'bspline') or (other == 'bspline_centered')): if (k in [103, 105, 202, 204, 206, 208, 301, 305, 307, 309]): a = WaveletTransform(N, other, 103) else: raise ValueError('wavelet_k must be in {103,105,202,204,206,208,301,305,307,309}') for i in range(N): a[i] = S[i] a.backward_transform() return IndexedSequence([RR(a[j]) for j in J], J)
class AdditiveGroups(CategoryWithAxiom_singleton): "\n The category of additive groups.\n\n An *additive group* is a set with an internal binary operation `+` which\n is associative, admits a zero, and where every element can be negated.\n\n EXAMPLES::\n\n sage: from sage.categories.additive_groups import AdditiveGroups\n sage: from sage.categories.additive_monoids import AdditiveMonoids\n sage: AdditiveGroups()\n Category of additive groups\n sage: AdditiveGroups().super_categories()\n [Category of additive inverse additive unital additive magmas,\n Category of additive monoids]\n sage: AdditiveGroups().all_super_categories()\n [Category of additive groups,\n Category of additive inverse additive unital additive magmas,\n Category of additive monoids,\n Category of additive unital additive magmas,\n Category of additive semigroups,\n Category of additive magmas,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n sage: AdditiveGroups().axioms()\n frozenset({'AdditiveAssociative', 'AdditiveInverse', 'AdditiveUnital'})\n sage: AdditiveGroups() is AdditiveMonoids().AdditiveInverse()\n True\n\n TESTS::\n\n sage: C = AdditiveGroups()\n sage: TestSuite(C).run()\n " _base_category_class_and_axiom = (AdditiveMonoids, 'AdditiveInverse') class Algebras(AlgebrasCategory): class ParentMethods(): group = raw_getattr(Groups.Algebras.ParentMethods, 'group') class Finite(CategoryWithAxiom): class Algebras(AlgebrasCategory): extra_super_categories = raw_getattr(Groups.Finite.Algebras, 'extra_super_categories') class ParentMethods(): __init_extra__ = raw_getattr(Groups.Finite.Algebras.ParentMethods, '__init_extra__') AdditiveCommutative = LazyImport('sage.categories.commutative_additive_groups', 'CommutativeAdditiveGroups', at_startup=True)
class AdditiveMagmas(Category_singleton): '\n The category of additive magmas.\n\n An additive magma is a set endowed with a binary operation `+`.\n\n EXAMPLES::\n\n sage: AdditiveMagmas()\n Category of additive magmas\n sage: AdditiveMagmas().super_categories()\n [Category of sets]\n sage: AdditiveMagmas().all_super_categories()\n [Category of additive magmas,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n The following axioms are defined by this category::\n\n sage: AdditiveMagmas().AdditiveAssociative()\n Category of additive semigroups\n sage: AdditiveMagmas().AdditiveUnital()\n Category of additive unital additive magmas\n sage: AdditiveMagmas().AdditiveCommutative()\n Category of additive commutative additive magmas\n sage: AdditiveMagmas().AdditiveUnital().AdditiveInverse()\n Category of additive inverse additive unital additive magmas\n sage: C = AdditiveMagmas().AdditiveAssociative().AdditiveCommutative(); C\n Category of commutative additive semigroups\n sage: C.AdditiveUnital()\n Category of commutative additive monoids\n sage: C.AdditiveUnital().AdditiveInverse()\n Category of commutative additive groups\n\n TESTS::\n\n sage: C = AdditiveMagmas()\n sage: TestSuite(C).run()\n\n ' def super_categories(self): '\n EXAMPLES::\n\n sage: AdditiveMagmas().super_categories()\n [Category of sets]\n ' return [Sets()] class SubcategoryMethods(): @cached_method def AdditiveAssociative(self): "\n Return the full subcategory of the additive associative\n objects of ``self``.\n\n An :class:`additive magma <AdditiveMagmas>` `M` is\n *associative* if, for all `x,y,z \\in M`,\n\n .. MATH:: x + (y + z) = (x + y) + z\n\n .. SEEALSO:: :wikipedia:`Associative_property`\n\n EXAMPLES::\n\n sage: AdditiveMagmas().AdditiveAssociative()\n Category of additive semigroups\n\n TESTS::\n\n sage: TestSuite(AdditiveMagmas().AdditiveAssociative()).run()\n sage: Rings().AdditiveAssociative.__module__\n 'sage.categories.additive_magmas'\n " return self._with_axiom('AdditiveAssociative') @cached_method def AdditiveCommutative(self): "\n Return the full subcategory of the commutative objects of ``self``.\n\n An :class:`additive magma <AdditiveMagmas>` `M` is\n *commutative* if, for all `x,y \\in M`,\n\n .. MATH:: x + y = y + x\n\n .. SEEALSO:: :wikipedia:`Commutative_property`\n\n EXAMPLES::\n\n sage: AdditiveMagmas().AdditiveCommutative()\n Category of additive commutative additive magmas\n sage: C = AdditiveMagmas().AdditiveAssociative().AdditiveUnital()\n sage: C.AdditiveCommutative()\n Category of commutative additive monoids\n sage: C.AdditiveCommutative() is CommutativeAdditiveMonoids()\n True\n\n TESTS::\n\n sage: TestSuite(AdditiveMagmas().AdditiveCommutative()).run()\n sage: Rings().AdditiveCommutative.__module__\n 'sage.categories.additive_magmas'\n " return self._with_axiom('AdditiveCommutative') @cached_method def AdditiveUnital(self): "\n Return the subcategory of the unital objects of ``self``.\n\n An :class:`additive magma <AdditiveMagmas>` `M` is *unital*\n if it admits an element `0`, called *neutral element*,\n such that for all `x \\in M`,\n\n .. MATH:: 0 + x = x + 0 = x\n\n This element is necessarily unique, and should be provided\n as ``M.zero()``.\n\n .. SEEALSO:: :wikipedia:`Unital_magma#unital`\n\n EXAMPLES::\n\n sage: AdditiveMagmas().AdditiveUnital()\n Category of additive unital additive magmas\n sage: from sage.categories.additive_semigroups import AdditiveSemigroups\n sage: AdditiveSemigroups().AdditiveUnital()\n Category of additive monoids\n sage: CommutativeAdditiveMonoids().AdditiveUnital()\n Category of commutative additive monoids\n\n TESTS::\n\n sage: TestSuite(AdditiveMagmas().AdditiveUnital()).run()\n sage: CommutativeAdditiveSemigroups().AdditiveUnital.__module__\n 'sage.categories.additive_magmas'\n " return self._with_axiom('AdditiveUnital') AdditiveAssociative = LazyImport('sage.categories.additive_semigroups', 'AdditiveSemigroups', at_startup=True) class ParentMethods(): def summation(self, x, y): '\n Return the sum of ``x`` and ``y``.\n\n The binary addition operator of this additive magma.\n\n INPUT:\n\n - ``x``, ``y`` -- elements of this additive magma\n\n EXAMPLES::\n\n sage: S = CommutativeAdditiveSemigroups().example()\n sage: (a,b,c,d) = S.additive_semigroup_generators()\n sage: S.summation(a, b)\n a + b\n\n A parent in ``AdditiveMagmas()`` must\n either implement :meth:`.summation` in the parent class or\n ``_add_`` in the element class. By default, the addition\n method on elements ``x._add_(y)`` calls\n ``S.summation(x,y)``, and reciprocally.\n\n As a bonus effect, ``S.summation`` by itself models the\n binary function from ``S`` to ``S``::\n\n sage: bin = S.summation\n sage: bin(a,b)\n a + b\n\n Here, ``S.summation`` is just a bound method. Whenever\n possible, it is recommended to enrich ``S.summation`` with\n extra mathematical structure. Lazy attributes can come\n handy for this.\n\n .. TODO:: Add an example.\n ' return (x + y) summation_from_element_class_add = summation def __init_extra__(self): '\n TESTS::\n\n sage: S = CommutativeAdditiveSemigroups().example()\n sage: (a,b,c,d) = S.additive_semigroup_generators()\n sage: a + b # indirect doctest\n a + b\n sage: a.__class__._add_ == a.__class__._add_parent\n True\n ' if ((self.summation != self.summation_from_element_class_add) and hasattr(self, 'element_class') and hasattr(self.element_class, '_add_parent')): self.element_class._add_ = self.element_class._add_parent def addition_table(self, names='letters', elements=None): "\n Return a table describing the addition operation.\n\n .. NOTE::\n\n The order of the elements in the row and column\n headings is equal to the order given by the table's\n :meth:`~sage.matrix.operation_table.OperationTable.column_keys`\n method. The association can also be retrieved with the\n :meth:`~sage.matrix.operation_table.OperationTable.translation`\n method.\n\n INPUT:\n\n - ``names`` -- the type of names used:\n\n * ``'letters'`` - lowercase ASCII letters are used\n for a base 26 representation of the elements'\n positions in the list given by\n :meth:`~sage.matrix.operation_table.OperationTable.column_keys`,\n padded to a common width with leading 'a's.\n * ``'digits'`` - base 10 representation of the\n elements' positions in the list given by\n :meth:`~sage.matrix.operation_table.OperationTable.column_keys`,\n padded to a common width with leading zeros.\n * ``'elements'`` - the string representations\n of the elements themselves.\n * a list - a list of strings, where the length\n of the list equals the number of elements.\n\n - ``elements`` -- (default: ``None``) A list of\n elements of the additive magma, in forms that\n can be coerced into the structure, eg. their\n string representations. This may be used to\n impose an alternate ordering on the elements,\n perhaps when this is used in the context of a\n particular structure. The default is to use\n whatever ordering the ``S.list`` method returns.\n Or the ``elements`` can be a subset which is\n closed under the operation. In particular,\n this can be used when the base set is infinite.\n\n OUTPUT:\n\n The addition table as an object of the class\n :class:`~sage.matrix.operation_table.OperationTable`\n which defines several methods for manipulating and\n displaying the table. See the documentation there\n for full details to supplement the documentation\n here.\n\n EXAMPLES:\n\n All that is required is that an algebraic structure\n has an addition defined.The default is to represent\n elements as lowercase ASCII letters. ::\n\n sage: R = IntegerModRing(5)\n sage: R.addition_table() # needs sage.modules\n + a b c d e\n +----------\n a| a b c d e\n b| b c d e a\n c| c d e a b\n d| d e a b c\n e| e a b c d\n\n The ``names`` argument allows displaying the elements in\n different ways. Requesting ``elements`` will use the\n representation of the elements of the set. Requesting\n ``digits`` will include leading zeros as padding. ::\n\n sage: R = IntegerModRing(11)\n sage: P = R.addition_table(names='elements'); P # needs sage.modules\n + 0 1 2 3 4 5 6 7 8 9 10\n +---------------------------------\n 0| 0 1 2 3 4 5 6 7 8 9 10\n 1| 1 2 3 4 5 6 7 8 9 10 0\n 2| 2 3 4 5 6 7 8 9 10 0 1\n 3| 3 4 5 6 7 8 9 10 0 1 2\n 4| 4 5 6 7 8 9 10 0 1 2 3\n 5| 5 6 7 8 9 10 0 1 2 3 4\n 6| 6 7 8 9 10 0 1 2 3 4 5\n 7| 7 8 9 10 0 1 2 3 4 5 6\n 8| 8 9 10 0 1 2 3 4 5 6 7\n 9| 9 10 0 1 2 3 4 5 6 7 8\n 10| 10 0 1 2 3 4 5 6 7 8 9\n\n sage: T = R.addition_table(names='digits'); T # needs sage.modules\n + 00 01 02 03 04 05 06 07 08 09 10\n +---------------------------------\n 00| 00 01 02 03 04 05 06 07 08 09 10\n 01| 01 02 03 04 05 06 07 08 09 10 00\n 02| 02 03 04 05 06 07 08 09 10 00 01\n 03| 03 04 05 06 07 08 09 10 00 01 02\n 04| 04 05 06 07 08 09 10 00 01 02 03\n 05| 05 06 07 08 09 10 00 01 02 03 04\n 06| 06 07 08 09 10 00 01 02 03 04 05\n 07| 07 08 09 10 00 01 02 03 04 05 06\n 08| 08 09 10 00 01 02 03 04 05 06 07\n 09| 09 10 00 01 02 03 04 05 06 07 08\n 10| 10 00 01 02 03 04 05 06 07 08 09\n\n Specifying the elements in an alternative order can provide\n more insight into how the operation behaves. ::\n\n sage: S = IntegerModRing(7)\n sage: elts = [0, 3, 6, 2, 5, 1, 4]\n sage: S.addition_table(elements=elts) # needs sage.modules\n + a b c d e f g\n +--------------\n a| a b c d e f g\n b| b c d e f g a\n c| c d e f g a b\n d| d e f g a b c\n e| e f g a b c d\n f| f g a b c d e\n g| g a b c d e f\n\n The ``elements`` argument can be used to provide\n a subset of the elements of the structure. The subset\n must be closed under the operation. Elements need only\n be in a form that can be coerced into the set. The\n ``names`` argument can also be used to request that\n the elements be represented with their usual string\n representation. ::\n\n sage: T = IntegerModRing(12)\n sage: elts = [0, 3, 6, 9]\n sage: T.addition_table(names='elements', elements=elts) # needs sage.modules\n + 0 3 6 9\n +--------\n 0| 0 3 6 9\n 3| 3 6 9 0\n 6| 6 9 0 3\n 9| 9 0 3 6\n\n The table returned can be manipulated in various ways. See\n the documentation for\n :class:`~sage.matrix.operation_table.OperationTable` for more\n comprehensive documentation. ::\n\n sage: # needs sage.modules\n sage: R = IntegerModRing(3)\n sage: T = R.addition_table()\n sage: T.column_keys()\n (0, 1, 2)\n sage: sorted(T.translation().items())\n [('a', 0), ('b', 1), ('c', 2)]\n sage: T.change_names(['x', 'y', 'z'])\n sage: sorted(T.translation().items())\n [('x', 0), ('y', 1), ('z', 2)]\n sage: T\n + x y z\n +------\n x| x y z\n y| y z x\n z| z x y\n " from sage.matrix.operation_table import OperationTable import operator return OperationTable(self, operation=operator.add, names=names, elements=elements) class ElementMethods(): @abstract_method(optional=True) def _add_(self, right): '\n Return the sum of ``self`` and ``right``.\n\n INPUT:\n\n - ``self``, ``right`` -- two elements with the same parent\n\n OUTPUT:\n\n - an element of the same parent\n\n EXAMPLES::\n\n sage: F = CommutativeAdditiveSemigroups().example()\n sage: (a,b,c,d) = F.additive_semigroup_generators()\n sage: a._add_(b)\n a + b\n ' def _add_parent(self, other): '\n Return the sum of the two elements, calculated using\n the ``summation`` method of the parent.\n\n This is the default implementation of _add_ if\n ``summation`` is implemented in the parent.\n\n INPUT:\n\n - ``other`` -- an element of the parent of ``self``\n\n OUTPUT:\n\n - an element of the parent of ``self``\n\n EXAMPLES::\n\n sage: S = CommutativeAdditiveSemigroups().example()\n sage: (a,b,c,d) = S.additive_semigroup_generators()\n sage: a._add_parent(b)\n a + b\n ' return self.parent().summation(self, other) class Homsets(HomsetsCategory): def extra_super_categories(self): '\n Implement the fact that a homset between two magmas is a magma.\n\n EXAMPLES::\n\n sage: AdditiveMagmas().Homsets().extra_super_categories()\n [Category of additive magmas]\n sage: AdditiveMagmas().Homsets().super_categories()\n [Category of additive magmas, Category of homsets]\n ' return [AdditiveMagmas()] class CartesianProducts(CartesianProductsCategory): def extra_super_categories(self): '\n Implement the fact that a Cartesian product of additive magmas is\n an additive magma.\n\n EXAMPLES::\n\n sage: C = AdditiveMagmas().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of additive magmas]\n sage: C.super_categories()\n [Category of additive magmas, Category of Cartesian products of sets]\n sage: C.axioms()\n frozenset()\n ' return [AdditiveMagmas()] class ElementMethods(): def _add_(self, right): "\n EXAMPLES::\n\n sage: # needs sage.rings.finite_rings\n sage: G5 = GF(5); G8 = GF(4, 'x'); GG = G5.cartesian_product(G8)\n sage: e = GG((G5(1), G8.primitive_element())); e\n (1, x)\n sage: e + e\n (2, 0)\n sage: e = groups.misc.AdditiveCyclic(8) # needs sage.groups\n sage: x = e.cartesian_product(e)((e(1), e(2)))\n sage: x\n (1, 2)\n sage: 4 * x\n (4, 0)\n " return self.parent()._cartesian_product_of_elements(((x + y) for (x, y) in zip(self.cartesian_factors(), right.cartesian_factors()))) class Algebras(AlgebrasCategory): def extra_super_categories(self): '\n EXAMPLES::\n\n sage: AdditiveMagmas().Algebras(QQ).extra_super_categories()\n [Category of magmatic algebras with basis over Rational Field]\n\n sage: AdditiveMagmas().Algebras(QQ).super_categories()\n [Category of magmatic algebras with basis over Rational Field,\n Category of set algebras over Rational Field]\n ' from sage.categories.magmatic_algebras import MagmaticAlgebras return [MagmaticAlgebras(self.base_ring()).WithBasis()] class ParentMethods(): @cached_method def algebra_generators(self): "\n The generators of this algebra, as per\n :meth:`MagmaticAlgebras.ParentMethods.algebra_generators()\n <.magmatic_algebras.MagmaticAlgebras.ParentMethods.algebra_generators>`.\n\n They correspond to the generators of the additive semigroup.\n\n EXAMPLES::\n\n sage: S = CommutativeAdditiveSemigroups().example(); S\n An example of a commutative semigroup:\n the free commutative semigroup generated by ('a', 'b', 'c', 'd')\n sage: A = S.algebra(QQ) # needs sage.modules\n sage: A.algebra_generators() # needs sage.modules\n Family (B[a], B[b], B[c], B[d])\n\n .. TODO::\n\n This doctest does not actually test this method,\n but rather the method of the same name for\n ``AdditiveSemigroups``. Find a better doctest!\n " return self.basis().keys().additive_semigroup_generators().map(self.monomial) def product_on_basis(self, g1, g2): "\n Product, on basis elements, as per\n :meth:`MagmaticAlgebras.WithBasis.ParentMethods.product_on_basis()\n <.magmatic_algebras.MagmaticAlgebras.WithBasis.ParentMethods.product_on_basis>`.\n\n The product of two basis elements is induced by the\n addition of the corresponding elements of the group.\n\n EXAMPLES::\n\n sage: S = CommutativeAdditiveSemigroups().example(); S\n An example of a commutative semigroup:\n the free commutative semigroup generated by ('a', 'b', 'c', 'd')\n sage: A = S.algebra(QQ) # needs sage.modules\n sage: a, b, c, d = A.algebra_generators() # needs sage.modules\n sage: a * d * b # needs sage.modules\n B[a + b + d]\n\n .. TODO::\n\n This doctest does not actually test this method,\n but rather the method of the same name for\n ``AdditiveSemigroups``. Find a better doctest!\n " return self.monomial((g1 + g2)) class AdditiveCommutative(CategoryWithAxiom): class CartesianProducts(CartesianProductsCategory): def extra_super_categories(self): "\n Implement the fact that a Cartesian product of commutative\n additive magmas is a commutative additive magma.\n\n EXAMPLES::\n\n sage: C = AdditiveMagmas().AdditiveCommutative().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of additive commutative additive magmas]\n sage: C.axioms()\n frozenset({'AdditiveCommutative'})\n " return [AdditiveMagmas().AdditiveCommutative()] class Algebras(AlgebrasCategory): def extra_super_categories(self): '\n Implement the fact that the algebra of a commutative additive\n magmas is commutative.\n\n EXAMPLES::\n\n sage: C = AdditiveMagmas().AdditiveCommutative().Algebras(QQ)\n sage: C.extra_super_categories()\n [Category of commutative magmas]\n\n sage: C.super_categories()\n [Category of additive magma algebras over Rational Field,\n Category of commutative magmas]\n ' from sage.categories.magmas import Magmas return [Magmas().Commutative()] class AdditiveUnital(CategoryWithAxiom): def additional_structure(self): '\n Return whether ``self`` is a structure category.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n The category of unital additive magmas defines the zero as\n additional structure, and this zero shall be preserved by\n morphisms.\n\n EXAMPLES::\n\n sage: AdditiveMagmas().AdditiveUnital().additional_structure()\n Category of additive unital additive magmas\n ' return self class SubcategoryMethods(): @cached_method def AdditiveInverse(self): "\n Return the full subcategory of the additive inverse objects\n of ``self``.\n\n An inverse :class:`additive magma <AdditiveMagmas>` is\n a :class:`unital additive magma <AdditiveMagmas.Unital>`\n such that every element admits both an additive\n inverse on the left and on the right. Such an additive\n magma is also called an *additive loop*.\n\n .. SEEALSO::\n\n :wikipedia:`Inverse_element`, :wikipedia:`Quasigroup`\n\n EXAMPLES::\n\n sage: AdditiveMagmas().AdditiveUnital().AdditiveInverse()\n Category of additive inverse additive unital additive magmas\n sage: from sage.categories.additive_monoids import AdditiveMonoids\n sage: AdditiveMonoids().AdditiveInverse()\n Category of additive groups\n\n TESTS::\n\n sage: TestSuite(AdditiveMagmas().AdditiveUnital().AdditiveInverse()).run()\n sage: CommutativeAdditiveMonoids().AdditiveInverse.__module__\n 'sage.categories.additive_magmas'\n " return self._with_axiom('AdditiveInverse') class ParentMethods(): def _test_zero(self, **options): '\n Test that ``self.zero()`` is an element of self and\n is neutral for the addition.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted\n by :meth:`_tester`\n\n EXAMPLES:\n\n By default, this method tests only the elements returned by\n ``self.some_elements()``::\n\n sage: S = CommutativeAdditiveMonoids().example()\n sage: S._test_zero()\n\n However, the elements tested can be customized with the\n ``elements`` keyword argument::\n\n sage: (a,b,c,d) = S.additive_semigroup_generators()\n sage: S._test_zero(elements = (a, a+c))\n\n See the documentation for :class:`TestSuite` for\n more information.\n ' tester = self._tester(**options) zero = self.zero() tester.assertTrue(self.is_parent_of(zero)) for x in tester.some_elements(): tester.assertEqual((x + zero), x) if hasattr(zero, 'is_immutable'): tester.assertEqual(zero.is_immutable(), True) if hasattr(zero, 'is_mutable'): tester.assertEqual(zero.is_mutable(), False) tester.assertFalse(bool(self.zero())) @cached_method def zero(self): '\n Return the zero of this additive magma, that is the unique\n neutral element for `+`.\n\n The default implementation is to coerce ``0`` into ``self``.\n\n It is recommended to override this method because the\n coercion from the integers:\n\n - is not always meaningful (except for `0`), and\n - often uses ``self.zero()`` otherwise.\n\n EXAMPLES::\n\n sage: S = CommutativeAdditiveMonoids().example()\n sage: S.zero()\n 0\n ' return self(0) def is_empty(self): "\n Return whether this set is empty.\n\n Since this set is an additive magma it has a zero element and\n hence is not empty. This method thus always returns ``False``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: A = AdditiveAbelianGroup([3, 3])\n sage: A in AdditiveMagmas()\n True\n sage: A.is_empty()\n False\n\n sage: B = CommutativeAdditiveMonoids().example()\n sage: B.is_empty()\n False\n\n TESTS:\n\n We check that the method ``is_empty`` is inherited from this\n category in both examples above::\n\n sage: A.is_empty.__module__ # needs sage.modules\n 'sage.categories.additive_magmas'\n sage: B.is_empty.__module__\n 'sage.categories.additive_magmas'\n " return False class ElementMethods(): @abstract_method def __bool__(self): '\n Return whether ``self`` is not zero.\n\n All parents in the category ``CommutativeAdditiveMonoids()``\n should implement this method.\n\n .. note:: This is currently not useful because this method is\n overridden by ``Element``.\n\n TESTS::\n\n sage: S = CommutativeAdditiveMonoids().example()\n sage: bool(S.zero())\n False\n sage: bool(S.an_element())\n True\n ' def _test_nonzero_equal(self, **options): '\n Test that ``.__bool__()`` behave consistently\n with `` == 0``.\n\n TESTS::\n\n sage: S = CommutativeAdditiveMonoids().example()\n sage: S.zero()._test_nonzero_equal()\n sage: S.an_element()._test_nonzero_equal()\n ' tester = self._tester(**options) tester.assertEqual(bool(self), (self != self.parent().zero())) tester.assertEqual((not self), (self == self.parent().zero())) def _sub_(left, right): "\n Default implementation of difference.\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b']) # needs sage.modules\n sage: a, b = F.basis() # needs sage.modules\n sage: a - b # needs sage.modules\n B['a'] - B['b']\n\n TESTS:\n\n Check that :trac:`18275` is fixed::\n\n sage: C = GF(5).cartesian_product(GF(5))\n sage: C.one() - C.one()\n (0, 0)\n " return (left + (- right)) def __neg__(self): "\n Return the negation of ``self``, if it exists.\n\n This top-level implementation delegates the job to\n ``_neg_``, for those additive unital magmas which may\n choose to implement it instead of ``__neg__`` for\n consistency.\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b']) # needs sage.modules\n sage: a, b = F.basis() # needs sage.modules\n sage: -b # needs sage.modules\n -B['b']\n\n TESTS::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(ZZ, ['a', 'b'])\n sage: a, b = F.gens()\n sage: FF = cartesian_product((F, F))\n sage: x = cartesian_product([a, 2*a-3*b]); x\n B[(0, 'a')] + 2*B[(1, 'a')] - 3*B[(1, 'b')]\n sage: x.parent() is FF\n True\n sage: -x\n -B[(0, 'a')] - 2*B[(1, 'a')] + 3*B[(1, 'b')]\n " return self._neg_() class Homsets(HomsetsCategory): def extra_super_categories(self): '\n Implement the fact that a homset between two unital additive\n magmas is a unital additive magma.\n\n EXAMPLES::\n\n sage: AdditiveMagmas().AdditiveUnital().Homsets().extra_super_categories()\n [Category of additive unital additive magmas]\n sage: AdditiveMagmas().AdditiveUnital().Homsets().super_categories()\n [Category of additive unital additive magmas, Category of homsets]\n ' return [AdditiveMagmas().AdditiveUnital()] class ParentMethods(): @cached_method def zero(self): "\n EXAMPLES::\n\n sage: R = QQ['x']\n sage: H = Hom(ZZ, R, AdditiveMagmas().AdditiveUnital())\n sage: f = H.zero()\n sage: f\n Generic morphism:\n From: Integer Ring\n To: Univariate Polynomial Ring in x over Rational Field\n sage: f(3)\n 0\n sage: f(3) is R.zero()\n True\n\n TESTS:\n\n sage: TestSuite(f).run()\n " from sage.misc.constant_function import ConstantFunction return self(ConstantFunction(self.codomain().zero())) class AdditiveInverse(CategoryWithAxiom): class CartesianProducts(CartesianProductsCategory): def extra_super_categories(self): "\n Implement the fact that a Cartesian product of additive magmas\n with inverses is an additive magma with inverse.\n\n EXAMPLES::\n\n sage: C = AdditiveMagmas().AdditiveUnital().AdditiveInverse().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of additive inverse additive unital additive magmas]\n sage: sorted(C.axioms())\n ['AdditiveInverse', 'AdditiveUnital']\n " return [AdditiveMagmas().AdditiveUnital().AdditiveInverse()] class ElementMethods(): def _neg_(self): '\n Return the negation of ``self``.\n\n EXAMPLES::\n\n sage: x = cartesian_product((GF(7)(2), 17)); x\n (2, 17)\n sage: -x\n (5, -17)\n\n TESTS::\n\n sage: C = AdditiveMagmas().AdditiveUnital().AdditiveInverse().CartesianProducts()\n sage: x.parent() in C\n True\n ' return self.parent()._cartesian_product_of_elements([(- x) for x in self.cartesian_factors()]) class CartesianProducts(CartesianProductsCategory): def extra_super_categories(self): "\n Implement the fact that a Cartesian product of unital additive\n magmas is a unital additive magma.\n\n EXAMPLES::\n\n sage: C = AdditiveMagmas().AdditiveUnital().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of additive unital additive magmas]\n sage: C.axioms()\n frozenset({'AdditiveUnital'})\n " return [AdditiveMagmas().AdditiveUnital()] class ParentMethods(): def zero(self): "\n Returns the zero of this group\n\n EXAMPLES::\n\n sage: GF(8, 'x').cartesian_product(GF(5)).zero() # needs sage.rings.finite_rings\n (0, 0)\n " return self._cartesian_product_of_elements((_.zero() for _ in self.cartesian_factors())) class Algebras(AlgebrasCategory): def extra_super_categories(self): '\n EXAMPLES::\n\n sage: C = AdditiveMagmas().AdditiveUnital().Algebras(QQ)\n sage: C.extra_super_categories()\n [Category of unital magmas]\n\n sage: C.super_categories()\n [Category of unital algebras with basis over Rational Field,\n Category of additive magma algebras over Rational Field]\n ' from sage.categories.magmas import Magmas return [Magmas().Unital()] class ParentMethods(): @cached_method def one_basis(self): "\n Return the zero of this additive magma, which index the\n one of this algebra, as per\n :meth:`AlgebrasWithBasis.ParentMethods.one_basis()\n <sage.categories.algebras_with_basis.AlgebrasWithBasis.ParentMethods.one_basis>`.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: S = CommutativeAdditiveMonoids().example(); S\n An example of a commutative monoid:\n the free commutative monoid generated by ('a', 'b', 'c', 'd')\n sage: A = S.algebra(ZZ)\n sage: A.one_basis()\n 0\n sage: A.one()\n B[0]\n sage: A(3)\n 3*B[0]\n " return self.basis().keys().zero() class WithRealizations(WithRealizationsCategory): class ParentMethods(): def zero(self): "\n Return the zero of this unital additive magma.\n\n This default implementation returns the zero of the\n realization of ``self`` given by\n :meth:`~Sets.WithRealizations.ParentMethods.a_realization`.\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example(); A # needs sage.modules\n The subset algebra of {1, 2, 3} over Rational Field\n sage: A.zero.__module__ # needs sage.modules\n 'sage.categories.additive_magmas'\n sage: A.zero() # needs sage.modules\n 0\n\n TESTS::\n\n sage: A.zero() is A.a_realization().zero() # needs sage.modules\n True\n sage: A._test_zero() # needs sage.modules\n " return self.a_realization().zero()
class AdditiveMonoids(CategoryWithAxiom_singleton): "\n The category of additive monoids.\n\n An *additive monoid* is a unital :class:`additive semigroup\n <sage.categories.additive_semigroups.AdditiveSemigroups>`, that\n is a set endowed with a binary operation `+` which is associative\n and admits a zero (see :wikipedia:`Monoid`).\n\n EXAMPLES::\n\n sage: from sage.categories.additive_monoids import AdditiveMonoids\n sage: C = AdditiveMonoids(); C\n Category of additive monoids\n sage: C.super_categories()\n [Category of additive unital additive magmas, Category of additive semigroups]\n sage: sorted(C.axioms())\n ['AdditiveAssociative', 'AdditiveUnital']\n sage: from sage.categories.additive_semigroups import AdditiveSemigroups\n sage: C is AdditiveSemigroups().AdditiveUnital()\n True\n\n TESTS::\n\n sage: C.Algebras(QQ).is_subcategory(AlgebrasWithBasis(QQ))\n True\n sage: TestSuite(C).run()\n " _base_category_class_and_axiom = (AdditiveSemigroups, 'AdditiveUnital') AdditiveCommutative = LazyImport('sage.categories.commutative_additive_monoids', 'CommutativeAdditiveMonoids', at_startup=True) AdditiveInverse = LazyImport('sage.categories.additive_groups', 'AdditiveGroups', at_startup=True) class ParentMethods(): def sum(self, args): '\n Return the sum of the elements in ``args``, as an element\n of ``self``.\n\n INPUT:\n\n - ``args`` -- a list (or iterable) of elements of ``self``\n\n EXAMPLES::\n\n sage: S = CommutativeAdditiveMonoids().example()\n sage: (a,b,c,d) = S.additive_semigroup_generators()\n sage: S.sum((a,b,a,c,a,b))\n 3*a + 2*b + c\n sage: S.sum(())\n 0\n sage: S.sum(()).parent() == S\n True\n ' return sum(args, self.zero()) class Homsets(HomsetsCategory): def extra_super_categories(self): '\n Implement the fact that a homset between two monoids is\n associative.\n\n EXAMPLES::\n\n sage: from sage.categories.additive_monoids import AdditiveMonoids\n sage: AdditiveMonoids().Homsets().extra_super_categories()\n [Category of additive semigroups]\n sage: AdditiveMonoids().Homsets().super_categories()\n [Category of homsets of additive unital additive magmas, Category of additive monoids]\n\n .. TODO::\n\n This could be deduced from\n :meth:`AdditiveSemigroups.Homsets.extra_super_categories`.\n See comment in :meth:`Objects.SubcategoryMethods.Homsets`.\n ' return [AdditiveSemigroups()]
class AdditiveSemigroups(CategoryWithAxiom_singleton): "\n The category of additive semigroups.\n\n An *additive semigroup* is an associative :class:`additive magma\n <AdditiveMagmas>`, that is a set endowed with an operation `+`\n which is associative.\n\n EXAMPLES::\n\n sage: from sage.categories.additive_semigroups import AdditiveSemigroups\n sage: C = AdditiveSemigroups(); C\n Category of additive semigroups\n sage: C.super_categories()\n [Category of additive magmas]\n sage: C.all_super_categories()\n [Category of additive semigroups,\n Category of additive magmas,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n sage: C.axioms()\n frozenset({'AdditiveAssociative'})\n sage: C is AdditiveMagmas().AdditiveAssociative()\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\n " _base_category_class_and_axiom = (AdditiveMagmas, 'AdditiveAssociative') AdditiveCommutative = LazyImport('sage.categories.commutative_additive_semigroups', 'CommutativeAdditiveSemigroups', at_startup=True) AdditiveUnital = LazyImport('sage.categories.additive_monoids', 'AdditiveMonoids', at_startup=True) class ParentMethods(): def _test_additive_associativity(self, **options): '\n Test associativity for (not necessarily all) elements of this\n additive semigroup.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`\n\n EXAMPLES:\n\n By default, this method tests only the elements returned by\n ``self.some_elements()``::\n\n sage: S = CommutativeAdditiveSemigroups().example()\n sage: S._test_additive_associativity()\n\n However, the elements tested can be customized with the\n ``elements`` keyword argument::\n\n sage: (a,b,c,d) = S.additive_semigroup_generators()\n sage: S._test_additive_associativity(elements = (a, b+c, d))\n\n See the documentation for :class:`TestSuite` for more information.\n ' tester = self._tester(**options) S = tester.some_elements() from sage.misc.misc import some_tuples for (x, y, z) in some_tuples(S, 3, tester._max_runs): tester.assertEqual(((x + y) + z), (x + (y + z))) class Homsets(HomsetsCategory): def extra_super_categories(self): '\n Implement the fact that a homset between two semigroups is a\n semigroup.\n\n EXAMPLES::\n\n sage: from sage.categories.additive_semigroups import AdditiveSemigroups\n sage: AdditiveSemigroups().Homsets().extra_super_categories()\n [Category of additive semigroups]\n sage: AdditiveSemigroups().Homsets().super_categories()\n [Category of homsets of additive magmas, Category of additive semigroups]\n ' return [AdditiveSemigroups()] class CartesianProducts(CartesianProductsCategory): def extra_super_categories(self): "\n Implement the fact that a Cartesian product of additive semigroups\n is an additive semigroup.\n\n EXAMPLES::\n\n sage: from sage.categories.additive_semigroups import AdditiveSemigroups\n sage: C = AdditiveSemigroups().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of additive semigroups]\n sage: C.axioms()\n frozenset({'AdditiveAssociative'})\n " return [AdditiveSemigroups()] class Algebras(AlgebrasCategory): def extra_super_categories(self): '\n EXAMPLES::\n\n sage: from sage.categories.additive_semigroups import AdditiveSemigroups\n sage: AdditiveSemigroups().Algebras(QQ).extra_super_categories()\n [Category of semigroups]\n sage: CommutativeAdditiveSemigroups().Algebras(QQ).super_categories()\n [Category of additive semigroup algebras over Rational Field,\n Category of additive commutative additive magma algebras over Rational Field]\n ' from sage.categories.semigroups import Semigroups return [Semigroups()] class ParentMethods(): @cached_method def algebra_generators(self): "\n Return the generators of this algebra, as per\n :meth:`MagmaticAlgebras.ParentMethods.algebra_generators()\n <.magmatic_algebras.MagmaticAlgebras.ParentMethods.algebra_generators>`.\n\n They correspond to the generators of the additive semigroup.\n\n EXAMPLES::\n\n sage: S = CommutativeAdditiveSemigroups().example(); S\n An example of a commutative semigroup:\n the free commutative semigroup generated by ('a', 'b', 'c', 'd')\n sage: A = S.algebra(QQ) # needs sage.modules\n sage: A.algebra_generators() # needs sage.modules\n Family (B[a], B[b], B[c], B[d])\n " return self.basis().keys().additive_semigroup_generators().map(self.monomial) def product_on_basis(self, g1, g2): "\n Product, on basis elements, as per\n :meth:`MagmaticAlgebras.WithBasis.ParentMethods.product_on_basis()\n <sage.categories.magmatic_algebras.MagmaticAlgebras.WithBasis.ParentMethods.product_on_basis>`.\n\n The product of two basis elements is induced by the\n addition of the corresponding elements of the group.\n\n EXAMPLES::\n\n sage: S = CommutativeAdditiveSemigroups().example(); S\n An example of a commutative semigroup:\n the free commutative semigroup generated by ('a', 'b', 'c', 'd')\n sage: A = S.algebra(QQ) # needs sage.modules\n sage: a, b, c, d = A.algebra_generators() # needs sage.modules\n sage: b * d * c # needs sage.modules\n B[b + c + d]\n " return self.monomial((g1 + g2))
class AffineWeylGroups(Category_singleton): '\n The category of affine Weyl groups\n\n .. TODO:: add a description of this category\n\n .. SEEALSO::\n\n - :wikipedia:`Affine_weyl_group`\n - :class:`WeylGroups`, :class:`WeylGroup`\n\n EXAMPLES::\n\n sage: C = AffineWeylGroups(); C\n Category of affine Weyl groups\n sage: C.super_categories()\n [Category of infinite Weyl groups]\n\n sage: C.example()\n NotImplemented\n sage: W = WeylGroup(["A", 4, 1]); W # needs sage.combinat sage.groups\n Weyl Group of type [\'A\', 4, 1] (as a matrix group acting on the root space)\n sage: W.category() # needs sage.combinat sage.groups\n Category of irreducible affine Weyl groups\n\n TESTS::\n\n sage: TestSuite(C).run()\n ' def super_categories(self): '\n EXAMPLES::\n\n sage: AffineWeylGroups().super_categories()\n [Category of infinite Weyl groups]\n ' return [WeylGroups().Infinite()] def additional_structure(self): '\n Return ``None``.\n\n Indeed, the category of affine Weyl groups defines no\n additional structure: affine Weyl groups are a special class\n of Weyl groups.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n .. TODO:: Should this category be a :class:`CategoryWithAxiom`?\n\n EXAMPLES::\n\n sage: AffineWeylGroups().additional_structure()\n ' return None def _repr_object_names(self): '\n Return the name of the objects of this category.\n\n EXAMPLES::\n\n sage: AffineWeylGroups()\n Category of affine Weyl groups\n ' return 'affine Weyl groups' class ParentMethods(): @cached_method def special_node(self): "\n Return the distinguished special node of the underlying\n Dynkin diagram.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A', 3, 1]) # needs sage.combinat sage.groups\n sage: W.special_node() # needs sage.combinat sage.groups\n 0\n " return self.cartan_type().special_node() def affine_grassmannian_elements_of_given_length(self, k): "\n Return the affine Grassmannian elements of length `k`.\n\n This is returned as a finite enumerated set.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A', 3, 1]) # needs sage.combinat sage.groups\n sage: [x.reduced_word() # needs sage.combinat sage.groups\n ....: for x in W.affine_grassmannian_elements_of_given_length(3)]\n [[2, 1, 0], [3, 1, 0], [2, 3, 0]]\n\n .. SEEALSO::\n\n :meth:`AffineWeylGroups.ElementMethods.is_affine_grassmannian`\n " from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet_forest def select_length(pair): (u, length) = pair if (length == k): return u def succ(pair): (u, length) = pair for i in u.descents(positive=True, side='left'): u1 = u.apply_simple_reflection(i, 'left') if ((length < k) and (i == u1.first_descent(side='left')) and u1.is_affine_grassmannian()): (yield (u1, (length + 1))) return return RecursivelyEnumeratedSet_forest(((self.one(), 0),), succ, algorithm='breadth', category=FiniteEnumeratedSets(), post_process=select_length) class ElementMethods(): def is_affine_grassmannian(self): "\n Test whether ``self`` is affine Grassmannian.\n\n An element of an affine Weyl group is *affine Grassmannian*\n if any of the following equivalent properties holds:\n\n - all reduced words for ``self`` end with 0.\n - ``self`` is the identity, or 0 is its single right descent.\n - ``self`` is a minimal coset representative for W / cl W.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup(['A', 3, 1])\n sage: w = W.from_reduced_word([2,1,0])\n sage: w.is_affine_grassmannian()\n True\n sage: w = W.from_reduced_word([2,0])\n sage: w.is_affine_grassmannian()\n False\n sage: W.one().is_affine_grassmannian()\n True\n " D = self.descents() return ((not D) or (D == [self.parent().special_node()])) def affine_grassmannian_to_core(self): "\n Bijection between affine Grassmannian elements of type `A_k^{(1)}` and `(k+1)`-cores.\n\n INPUT:\n\n - ``self`` -- an affine Grassmannian element of some affine Weyl group of type `A_k^{(1)}`\n\n Recall that an element `w` of an affine Weyl group is\n affine Grassmannian if all its all reduced words end in 0, see :meth:`is_affine_grassmannian`.\n\n OUTPUT:\n\n - a `(k+1)`-core\n\n .. SEEALSO:: :meth:`affine_grassmannian_to_partition`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup(['A', 2, 1])\n sage: w = W.from_reduced_word([0,2,1,0])\n sage: la = w.affine_grassmannian_to_core(); la\n [4, 2]\n sage: type(la)\n <class 'sage.combinat.core.Cores_length_with_category.element_class'>\n sage: la.to_grassmannian() == w\n True\n\n sage: w = W.from_reduced_word([0,2,1]) # needs sage.combinat sage.groups\n sage: w.affine_grassmannian_to_core() # needs sage.combinat sage.groups\n Traceback (most recent call last):\n ...\n ValueError: this only works on type 'A' affine Grassmannian elements\n " from sage.combinat.partition import Partition from sage.combinat.core import Core if ((not self.is_affine_grassmannian()) or (not (self.parent().cartan_type().letter == 'A'))): raise ValueError("this only works on type 'A' affine Grassmannian elements") out = Partition([]) rword = self.reduced_word() kp1 = self.parent().n for i in range(len(rword)): for c in out.outside_corners(): if (((c[1] - c[0]) % kp1) == rword[((- i) - 1)]): out = out.add_cell(c[0], c[1]) return Core(out._list, kp1) def affine_grassmannian_to_partition(self): "\n Bijection between affine Grassmannian elements of type `A_k^{(1)}`\n and `k`-bounded partitions.\n\n INPUT:\n\n - ``self`` is affine Grassmannian element of the affine Weyl group of type `A_k^{(1)}` (i.e. all reduced words end in 0)\n\n OUTPUT:\n\n - `k`-bounded partition\n\n .. SEEALSO:: :meth:`affine_grassmannian_to_core`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: k = 2\n sage: W = WeylGroup(['A', k, 1])\n sage: w = W.from_reduced_word([0,2,1,0])\n sage: la = w.affine_grassmannian_to_partition(); la\n [2, 2]\n sage: la.from_kbounded_to_grassmannian(k) == w\n True\n " return self.affine_grassmannian_to_core().to_bounded_partition()
class AlgebraFunctor(CovariantFunctorialConstruction): '\n For a fixed ring, a functor sending a group/... to the\n corresponding group/... algebra.\n\n EXAMPLES::\n\n sage: from sage.categories.algebra_functor import AlgebraFunctor\n sage: F = AlgebraFunctor(QQ); F\n The algebra functorial construction\n sage: F(DihedralGroup(3))\n Algebra of Dihedral group of order 6 as a permutation group\n over Rational Field\n ' _functor_name = 'algebra' _functor_category = 'Algebras' def __init__(self, base_ring): '\n EXAMPLES::\n\n sage: from sage.categories.algebra_functor import AlgebraFunctor\n sage: F = AlgebraFunctor(QQ); F\n The algebra functorial construction\n sage: TestSuite(F).run()\n ' from sage.categories.rings import Rings assert (base_ring in Rings()) self._base_ring = base_ring def base_ring(self): '\n Return the base ring for this functor.\n\n EXAMPLES::\n\n sage: from sage.categories.algebra_functor import AlgebraFunctor\n sage: AlgebraFunctor(QQ).base_ring()\n Rational Field\n ' return self._base_ring def __call__(self, G, category=None): '\n Return the algebra of ``G``.\n\n See :ref:`sage.categories.algebra_functor` for details.\n\n INPUT:\n\n - ``G`` -- a group\n - ``category`` -- a category, or ``None``\n\n EXAMPLES::\n\n sage: from sage.categories.algebra_functor import AlgebraFunctor\n sage: F = AlgebraFunctor(QQ)\n sage: G = DihedralGroup(3)\n sage: A = F(G, category=Monoids()); A\n Algebra of Dihedral group of order 6 as a permutation group\n over Rational Field\n sage: A.category()\n Category of finite dimensional monoid algebras over Rational Field\n ' return G.algebra(self._base_ring, category=category)
class GroupAlgebraFunctor(ConstructionFunctor): '\n For a fixed group, a functor sending a commutative ring to the\n corresponding group algebra.\n\n INPUT:\n\n - ``group`` -- the group associated to each group algebra under\n consideration\n\n EXAMPLES::\n\n sage: from sage.categories.algebra_functor import GroupAlgebraFunctor\n sage: F = GroupAlgebraFunctor(KleinFourGroup()); F\n GroupAlgebraFunctor\n sage: A = F(QQ); A\n Algebra of The Klein 4 group of order 4, as a permutation group over Rational Field\n\n TESTS::\n\n sage: loads(dumps(F)) == F\n True\n sage: A is KleinFourGroup().algebra(QQ)\n True\n ' def __init__(self, group): "\n See :class:`GroupAlgebraFunctor` for full documentation.\n\n EXAMPLES::\n\n sage: from sage.categories.algebra_functor import GroupAlgebraFunctor\n sage: GroupAlgebra(SU(2, GF(4, 'a')), IntegerModRing(12)).category()\n Category of finite group algebras over Ring of integers modulo 12\n " self.__group = group from sage.categories.rings import Rings ConstructionFunctor.__init__(self, Rings(), Rings()) def group(self): '\n Return the group which is associated to this functor.\n\n EXAMPLES::\n\n sage: from sage.categories.algebra_functor import GroupAlgebraFunctor\n sage: GroupAlgebraFunctor(CyclicPermutationGroup(17)).group() == CyclicPermutationGroup(17)\n True\n ' return self.__group def _apply_functor(self, base_ring): '\n Create the group algebra with given base ring over ``self.group()``.\n\n INPUT:\n\n - ``base_ring`` -- the base ring of the group algebra\n\n OUTPUT:\n\n A group algebra.\n\n EXAMPLES::\n\n sage: from sage.categories.algebra_functor import GroupAlgebraFunctor\n sage: F = GroupAlgebraFunctor(CyclicPermutationGroup(17))\n sage: F(QQ)\n Algebra of Cyclic group of order 17 as a permutation group\n over Rational Field\n ' return self.__group.algebra(base_ring) def _apply_functor_to_morphism(self, f): '\n Lift a homomorphism of rings to the corresponding homomorphism\n of the group algebras of ``self.group()``.\n\n INPUT:\n\n - ``f`` -- a morphism of rings\n\n OUTPUT:\n\n A morphism of group algebras.\n\n EXAMPLES::\n\n sage: G = SymmetricGroup(3)\n sage: A = GroupAlgebra(G, ZZ)\n sage: h = GF(5).coerce_map_from(ZZ)\n sage: hh = A.construction()[0](h); hh\n Generic morphism:\n From: Symmetric group algebra of order 3 over Integer Ring\n To: Symmetric group algebra of order 3 over Finite Field of size 5\n\n sage: a = 2 * A.an_element(); a\n 2*() + 2*(2,3) + 6*(1,2,3) + 4*(1,3,2)\n sage: hh(a)\n 2*() + 2*(2,3) + (1,2,3) + 4*(1,3,2)\n ' from sage.categories.rings import Rings domain = self(f.domain()) codomain = self(f.codomain()) return SetMorphism(domain.Hom(codomain, category=Rings()), (lambda x: codomain.sum_of_terms(((g, f(c)) for (g, c) in x))))
class AlgebrasCategory(CovariantConstructionCategory, Category_over_base_ring): "\n An abstract base class for categories of monoid algebras,\n groups algebras, and the like.\n\n .. SEEALSO::\n\n - :meth:`Sets.ParentMethods.algebra`\n - :meth:`Sets.SubcategoryMethods.Algebras`\n - :class:`~sage.categories.covariant_functorial_construction.CovariantFunctorialConstruction`\n\n INPUT:\n\n - ``base_ring`` -- a ring\n\n EXAMPLES::\n\n sage: C = Groups().Algebras(QQ); C\n Category of group algebras over Rational Field\n sage: C = Monoids().Algebras(QQ); C\n Category of monoid algebras over Rational Field\n\n sage: C._short_name()\n 'Algebras'\n sage: latex(C) # todo: improve that\n \\mathbf{Algebras}(\\mathbf{Monoids})\n " _functor_category = 'Algebras' def _repr_object_names(self): '\n EXAMPLES::\n\n sage: Semigroups().Algebras(QQ) # indirect doctest\n Category of semigroup algebras over Rational Field\n ' return '{} algebras over {}'.format(self.base_category()._repr_object_names()[:(- 1)], self.base_ring()) @staticmethod def __classcall__(cls, category=None, R=None): '\n Make ``CatAlgebras(**)`` a shorthand for ``Cat().Algebras(**)``.\n\n EXAMPLES::\n\n sage: GradedModules(ZZ) # indirect doctest\n Category of graded modules over Integer Ring\n sage: Modules(ZZ).Graded()\n Category of graded modules over Integer Ring\n sage: Modules.Graded(ZZ)\n Category of graded modules over Integer Ring\n sage: GradedModules(ZZ) is Modules(ZZ).Graded()\n True\n\n .. SEEALSO:: :meth:`_base_category_class`\n\n .. TODO::\n\n The logic is very similar to the default implementation\n :class:`FunctorialConstructionCategory.__classcall__`;\n the only difference is whether the additional arguments\n should be passed to ``Cat`` or to the construction.\n\n Find a way to refactor this to avoid the duplication.\n ' base_category_class = cls._base_category_class[0] if isinstance(category, base_category_class): return super(FunctorialConstructionCategory, cls).__classcall__(cls, category, R) else: return cls.category_of(base_category_class(), category) class ParentMethods(): def coproduct_on_basis(self, g): '\n Return the coproduct of the element ``g`` of the basis.\n\n Each basis element ``g`` is group-like. This method is\n used to compute the coproduct of any element.\n\n EXAMPLES::\n\n sage: PF = NonDecreasingParkingFunctions(4)\n sage: A = PF.algebra(ZZ); A\n Algebra of Non-decreasing parking functions of size 4 over Integer Ring\n sage: g = PF.an_element(); g\n [1, 1, 1, 1]\n sage: A.coproduct_on_basis(g)\n B[[1, 1, 1, 1]] # B[[1, 1, 1, 1]]\n sage: a = A.an_element(); a\n 2*B[[1, 1, 1, 1]] + 2*B[[1, 1, 1, 2]] + 3*B[[1, 1, 1, 3]]\n sage: a.coproduct()\n 2*B[[1, 1, 1, 1]] # B[[1, 1, 1, 1]] +\n 2*B[[1, 1, 1, 2]] # B[[1, 1, 1, 2]] +\n 3*B[[1, 1, 1, 3]] # B[[1, 1, 1, 3]]\n ' from sage.categories.tensor import tensor g = self.term(g) return tensor([g, g])
class AlgebraIdeals(Category_ideal): "\n The category of two-sided ideals in a fixed algebra `A`.\n\n EXAMPLES::\n\n sage: AlgebraIdeals(QQ['a'])\n Category of algebra ideals in Univariate Polynomial Ring in a over Rational Field\n\n .. TODO::\n\n - Add support for non commutative rings (this is currently not\n supported by the subcategory :class:`AlgebraModules`).\n - Make ``AlgebraIdeals(R)``, return ``CommutativeAlgebraIdeals(R)``\n when ``R`` is commutative.\n - If useful, implement ``AlgebraLeftIdeals`` and\n ``AlgebraRightIdeals`` of which ``AlgebraIdeals``\n would be a subcategory.\n " def __init__(self, A): "\n EXAMPLES::\n\n sage: AlgebraIdeals(QQ['a'])\n Category of algebra ideals in Univariate Polynomial Ring in a over Rational Field\n sage: AlgebraIdeals(QQ)\n Traceback (most recent call last):\n ...\n TypeError: A (=Rational Field) must be an algebra\n\n TESTS::\n\n sage: TestSuite(AlgebraIdeals(QQ['a'])).run()\n " try: base_ring = A.base_ring() except AttributeError: raise TypeError(f'A (={A}) must be an algebra') else: if ((base_ring not in Rings()) or (A not in Algebras(base_ring.category()))): raise TypeError(f'A (={A}) must be an algebra') Category_ideal.__init__(self, A) def algebra(self): "\n EXAMPLES::\n\n sage: AlgebraIdeals(QQ['x']).algebra()\n Univariate Polynomial Ring in x over Rational Field\n " return self.ambient() def super_categories(self): "\n The category of algebra modules should be a super category of this category.\n\n However, since algebra modules are currently only available over commutative rings,\n we have to omit it if our ring is non-commutative.\n\n EXAMPLES::\n\n sage: AlgebraIdeals(QQ['x']).super_categories()\n [Category of algebra modules\n over Univariate Polynomial Ring in x over Rational Field]\n sage: C = AlgebraIdeals(FreeAlgebra(QQ, 2, 'a,b')) # needs sage.combinat sage.modules\n sage: C.super_categories() # needs sage.combinat sage.modules\n []\n\n " R = self.algebra() try: if R.is_commutative(): return [AlgebraModules(R)] except (AttributeError, NotImplementedError): pass return []
class AlgebraModules(Category_module): "\n The category of modules over a fixed algebra `A`.\n\n EXAMPLES::\n\n sage: AlgebraModules(QQ['a'])\n Category of algebra modules over Univariate Polynomial Ring in a over Rational Field\n sage: AlgebraModules(QQ['a']).super_categories()\n [Category of modules over Univariate Polynomial Ring in a over Rational Field]\n\n Note: as of now, `A` is required to be commutative, ensuring that\n the categories of left and right modules are isomorphic. Feedback\n and use cases for potential generalizations to the non commutative\n case are welcome.\n\n " def __init__(self, A): "\n EXAMPLES::\n\n sage: AlgebraModules(QQ['a'])\n Category of algebra modules over Univariate Polynomial Ring in a over Rational Field\n sage: AlgebraModules(QQ['a,b']) # todo: not implemented (QQ['a,b'] should be in Algebras(QQ))\n sage: AlgebraModules(FreeAlgebra(QQ, 2, 'a,b')) # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n TypeError: A (=Free Algebra on 2 generators (a, b) over Rational Field) must be a commutative algebra\n sage: AlgebraModules(QQ)\n Traceback (most recent call last):\n ...\n TypeError: A (=Rational Field) must be a commutative algebra\n\n TESTS::\n\n sage: TestSuite(AlgebraModules(QQ['a'])).run()\n " try: base_ring = A.base_ring() except AttributeError: raise TypeError(f'A (={A}) must be a commutative algebra') else: if ((base_ring not in CommutativeRings()) or (A not in CommutativeAlgebras(base_ring.category()))): raise TypeError(f'A (={A}) must be a commutative algebra') Category_module.__init__(self, A) @classmethod def an_instance(cls): '\n Returns an instance of this class\n\n EXAMPLES::\n\n sage: AlgebraModules.an_instance()\n Category of algebra modules over Univariate Polynomial Ring in x over Rational Field\n ' from sage.rings.rational_field import QQ return cls(QQ['x']) def algebra(self): "\n EXAMPLES::\n\n sage: AlgebraModules(QQ['x']).algebra()\n Univariate Polynomial Ring in x over Rational Field\n " return self.base_ring() def super_categories(self): "\n EXAMPLES::\n\n sage: AlgebraModules(QQ['x']).super_categories()\n [Category of modules over Univariate Polynomial Ring in x over Rational Field]\n " R = self.algebra() return [Modules(R)]
class Algebras(CategoryWithAxiom_over_base_ring): '\n The category of associative and unital algebras over a given base ring.\n\n An associative and unital algebra over a ring `R` is a module over\n `R` which is itself a ring.\n\n .. WARNING::\n\n :class:`Algebras` will be eventually be replaced by\n :class:`.magmatic_algebras.MagmaticAlgebras`\n for consistency with e.g. :wikipedia:`Algebras` which assumes\n neither associativity nor the existence of a unit (see\n :trac:`15043`).\n\n .. TODO:: Should `R` be a commutative ring?\n\n EXAMPLES::\n\n sage: Algebras(ZZ)\n Category of algebras over Integer Ring\n sage: sorted(Algebras(ZZ).super_categories(), key=str)\n [Category of associative algebras over Integer Ring,\n Category of rings,\n Category of unital algebras over Integer Ring]\n\n TESTS::\n\n sage: TestSuite(Algebras(ZZ)).run()\n ' _base_category_class_and_axiom = (AssociativeAlgebras, 'Unital') def __contains__(self, x): "\n Membership testing\n\n EXAMPLES::\n\n sage: QQ['x'] in Algebras(QQ)\n True\n\n sage: QQ^3 in Algebras(QQ) # needs sage.modules\n False\n sage: QQ['x'] in Algebras(CDF) # needs sage.rings.complex_double\n False\n " if super().__contains__(x): return True from sage.rings.ring import Algebra return (isinstance(x, Algebra) and (x.base_ring() == self.base_ring())) class SubcategoryMethods(): def Semisimple(self): '\n Return the subcategory of semisimple objects of ``self``.\n\n .. NOTE::\n\n This mimics the syntax of axioms for a smooth\n transition if ``Semisimple`` becomes one.\n\n EXAMPLES::\n\n sage: Algebras(QQ).Semisimple()\n Category of semisimple algebras over Rational Field\n sage: Algebras(QQ).WithBasis().FiniteDimensional().Semisimple()\n Category of finite dimensional semisimple algebras with basis over Rational Field\n ' from sage.categories.semisimple_algebras import SemisimpleAlgebras return (self & SemisimpleAlgebras(self.base_ring())) @cached_method def Supercommutative(self): '\n Return the full subcategory of the supercommutative objects\n of ``self``.\n\n This is shorthand for creating the corresponding super category.\n\n EXAMPLES::\n\n sage: Algebras(ZZ).Supercommutative()\n Category of supercommutative algebras over Integer Ring\n sage: Algebras(ZZ).WithBasis().Supercommutative()\n Category of supercommutative super algebras with basis over Integer Ring\n\n sage: Cat = Algebras(ZZ).Supercommutative()\n sage: Cat is Algebras(ZZ).Super().Supercommutative()\n True\n ' return self.Super().Supercommutative() Commutative = LazyImport('sage.categories.commutative_algebras', 'CommutativeAlgebras', at_startup=True) Filtered = LazyImport('sage.categories.filtered_algebras', 'FilteredAlgebras') Graded = LazyImport('sage.categories.graded_algebras', 'GradedAlgebras') Super = LazyImport('sage.categories.super_algebras', 'SuperAlgebras') WithBasis = LazyImport('sage.categories.algebras_with_basis', 'AlgebrasWithBasis', at_startup=True) Semisimple = LazyImport('sage.categories.semisimple_algebras', 'SemisimpleAlgebras') class ElementMethods(): def _div_(self, y): '\n Division by invertible elements\n\n # TODO: move in Monoids\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: C = AlgebrasWithBasis(QQ).example()\n sage: x = C(2); x\n 2*B[word: ]\n sage: y = C.algebra_generators().first(); y\n B[word: a]\n sage: y._div_(x)\n 1/2*B[word: a]\n sage: x._div_(y)\n Traceback (most recent call last):\n ...\n ValueError: cannot invert self (= B[word: a])\n ' return self.parent().product(self, (~ y)) class Quotients(QuotientsCategory): class ParentMethods(): def algebra_generators(self): "\n Return algebra generators for ``self``.\n\n This implementation retracts the algebra generators\n from the ambient algebra.\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.modules\n sage: A = FiniteDimensionalAlgebrasWithBasis(QQ).example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: S = A.semisimple_quotient()\n sage: S.algebra_generators()\n Finite family {'x': B['x'], 'y': B['y'], 'a': 0, 'b': 0}\n\n .. TODO:: this could possibly remove the elements that retract to zero.\n " return self.ambient().algebra_generators().map(self.retract) class CartesianProducts(CartesianProductsCategory): '\n The category of algebras constructed as Cartesian products of algebras\n\n This construction gives the direct product of algebras. See\n discussion on:\n\n - http://groups.google.fr/group/sage-devel/browse_thread/thread/35a72b1d0a2fc77a/348f42ae77a66d16#348f42ae77a66d16\n - :wikipedia:`Direct_product`\n ' def extra_super_categories(self): '\n A Cartesian product of algebras is endowed with a natural\n algebra structure.\n\n EXAMPLES::\n\n sage: C = Algebras(QQ).CartesianProducts()\n sage: C.extra_super_categories()\n [Category of algebras over Rational Field]\n sage: sorted(C.super_categories(), key=str)\n [Category of Cartesian products of monoids,\n Category of Cartesian products of unital algebras over Rational Field,\n Category of algebras over Rational Field]\n ' return [self.base_category()] class TensorProducts(TensorProductsCategory): @cached_method def extra_super_categories(self): '\n EXAMPLES::\n\n sage: Algebras(QQ).TensorProducts().extra_super_categories()\n [Category of algebras over Rational Field]\n sage: Algebras(QQ).TensorProducts().super_categories()\n [Category of algebras over Rational Field,\n Category of tensor products of vector spaces over Rational Field]\n\n Meaning: a tensor product of algebras is an algebra\n ' return [self.base_category()] class ParentMethods(): pass class ElementMethods(): pass class DualObjects(DualObjectsCategory): def extra_super_categories(self): '\n Return the dual category\n\n EXAMPLES:\n\n The category of algebras over the Rational Field is dual\n to the category of coalgebras over the same field::\n\n sage: C = Algebras(QQ)\n sage: C.dual()\n Category of duals of algebras over Rational Field\n sage: C.dual().extra_super_categories()\n [Category of coalgebras over Rational Field]\n\n .. WARNING::\n\n This is only correct in certain cases (finite dimension, ...).\n See :trac:`15647`.\n ' from sage.categories.coalgebras import Coalgebras return [Coalgebras(self.base_category().base_ring())]
class AlgebrasWithBasis(CategoryWithAxiom_over_base_ring): "\n The category of algebras with a distinguished basis.\n\n EXAMPLES::\n\n sage: C = AlgebrasWithBasis(QQ); C\n Category of algebras with basis over Rational Field\n sage: sorted(C.super_categories(), key=str)\n [Category of algebras over Rational Field,\n Category of unital algebras with basis over Rational Field]\n\n We construct a typical parent in this category, and do some\n computations with it::\n\n sage: A = C.example(); A # needs sage.combinat sage.modules\n An example of an algebra with basis:\n the free algebra on the generators ('a', 'b', 'c') over Rational Field\n\n sage: A.category() # needs sage.combinat sage.modules\n Category of algebras with basis over Rational Field\n\n sage: A.one_basis() # needs sage.combinat sage.modules\n word:\n sage: A.one() # needs sage.combinat sage.modules\n B[word: ]\n\n sage: A.base_ring() # needs sage.combinat sage.modules\n Rational Field\n sage: A.basis().keys() # needs sage.combinat sage.modules\n Finite words over {'a', 'b', 'c'}\n\n sage: (a,b,c) = A.algebra_generators() # needs sage.combinat sage.modules\n sage: a^3, b^2 # needs sage.combinat sage.modules\n (B[word: aaa], B[word: bb])\n sage: a * c * b # needs sage.combinat sage.modules\n B[word: acb]\n\n sage: A.product # needs sage.combinat sage.modules\n <bound method MagmaticAlgebras.WithBasis.ParentMethods._product_from_product_on_basis_multiply of\n An example of an algebra with basis:\n the free algebra on the generators ('a', 'b', 'c') over Rational Field>\n sage: A.product(a * b, b) # needs sage.combinat sage.modules\n B[word: abb]\n\n sage: TestSuite(A).run(verbose=True) # needs sage.combinat sage.modules\n running ._test_additive_associativity() . . . pass\n running ._test_an_element() . . . pass\n running ._test_associativity() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_characteristic() . . . pass\n running ._test_construction() . . . pass\n running ._test_distributivity() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_nonzero_equal() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_one() . . . pass\n running ._test_pickling() . . . pass\n running ._test_prod() . . . pass\n running ._test_some_elements() . . . pass\n running ._test_zero() . . . pass\n sage: A.__class__ # needs sage.combinat sage.modules\n <class 'sage.categories.examples.algebras_with_basis.FreeAlgebra_with_category'>\n sage: A.element_class # needs sage.combinat sage.modules\n <class 'sage.categories.examples.algebras_with_basis.FreeAlgebra_with_category.element_class'>\n\n Please see the source code of `A` (with ``A??``) for how to\n implement other algebras with basis.\n\n TESTS::\n\n sage: TestSuite(AlgebrasWithBasis(QQ)).run()\n " def example(self, alphabet=('a', 'b', 'c')): "\n Return an example of algebra with basis.\n\n EXAMPLES::\n\n sage: AlgebrasWithBasis(QQ).example() # needs sage.combinat sage.modules\n An example of an algebra with basis:\n the free algebra on the generators ('a', 'b', 'c') over Rational Field\n\n An other set of generators can be specified as optional argument::\n\n sage: AlgebrasWithBasis(QQ).example((1,2,3)) # needs sage.combinat sage.modules\n An example of an algebra with basis:\n the free algebra on the generators (1, 2, 3) over Rational Field\n " from sage.categories.examples.algebras_with_basis import Example return Example(self.base_ring(), alphabet) Filtered = LazyImport('sage.categories.filtered_algebras_with_basis', 'FilteredAlgebrasWithBasis') FiniteDimensional = LazyImport('sage.categories.finite_dimensional_algebras_with_basis', 'FiniteDimensionalAlgebrasWithBasis', at_startup=True) Graded = LazyImport('sage.categories.graded_algebras_with_basis', 'GradedAlgebrasWithBasis') Super = LazyImport('sage.categories.super_algebras_with_basis', 'SuperAlgebrasWithBasis') class ParentMethods(): one = UnitalAlgebras.WithBasis.ParentMethods.one def hochschild_complex(self, M): '\n Return the Hochschild complex of ``self`` with coefficients\n in ``M``.\n\n .. SEEALSO::\n\n :class:`~sage.homology.hochschild_complex.HochschildComplex`\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: A = algebras.DifferentialWeyl(R) # needs sage.modules\n sage: H = A.hochschild_complex(A) # needs sage.modules\n\n sage: SGA = SymmetricGroupAlgebra(QQ, 3) # needs sage.combinat sage.modules\n sage: T = SGA.trivial_representation() # needs sage.combinat sage.modules\n sage: H = SGA.hochschild_complex(T) # needs sage.combinat sage.modules\n ' from sage.homology.hochschild_complex import HochschildComplex return HochschildComplex(self, M) class ElementMethods(): def __invert__(self): "\n Return the inverse of ``self`` if ``self`` is a multiple of one,\n and one is in the basis of this algebra. Otherwise throws\n an error.\n\n Caveat: this generic implementation is not complete; there\n may be invertible elements in the algebra that can't be\n inversed this way. It is correct though for graded\n connected algebras with basis.\n\n .. WARNING::\n\n This might produce a result which does not belong to\n the parent of ``self``, yet believes to do so. For\n instance, inverting 2 times the unity will produce 1/2\n times the unity, even if 1/2 is not in the base ring.\n Handle with care.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: C = AlgebrasWithBasis(QQ).example()\n sage: x = C(2); x\n 2*B[word: ]\n sage: ~x\n 1/2*B[word: ]\n sage: a = C.algebra_generators().first(); a\n B[word: a]\n sage: ~a\n Traceback (most recent call last):\n ...\n ValueError: cannot invert self (= B[word: a])\n " mcs = self.monomial_coefficients(copy=False) one = self.parent().one_basis() if ((len(mcs) == 1) and (one in mcs)): return self.parent().term(one, (~ mcs[one])) else: raise ValueError(('cannot invert self (= %s)' % self)) class CartesianProducts(CartesianProductsCategory): '\n The category of algebras with basis, constructed as Cartesian\n products of algebras with basis.\n\n Note: this construction give the direct products of algebras with basis.\n See comment in :class:`Algebras.CartesianProducts\n <sage.categories.algebras.Algebras.CartesianProducts>`\n ' def extra_super_categories(self): '\n A Cartesian product of algebras with basis is endowed with\n a natural algebra with basis structure.\n\n EXAMPLES::\n\n sage: AlgebrasWithBasis(QQ).CartesianProducts().extra_super_categories()\n [Category of algebras with basis over Rational Field]\n sage: AlgebrasWithBasis(QQ).CartesianProducts().super_categories()\n [Category of algebras with basis over Rational Field,\n Category of Cartesian products of algebras over Rational Field,\n Category of Cartesian products of vector spaces with basis over Rational Field]\n ' return [self.base_category()] class ParentMethods(): @cached_method def one_from_cartesian_product_of_one_basis(self): "\n Return the one of this Cartesian product of algebras, as per\n ``Monoids.ParentMethods.one``\n\n It is constructed as the Cartesian product of the ones of the\n summands, using their :meth:`~AlgebrasWithBasis.ParentMethods.one_basis` methods.\n\n This implementation does not require multiplication by\n scalars nor calling cartesian_product. This might help keeping\n things as lazy as possible upon initialization.\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).example(); A # needs sage.combinat sage.modules\n An example of an algebra with basis: the free algebra\n on the generators ('a', 'b', 'c') over Rational Field\n sage: A.one_basis() # needs sage.combinat sage.modules\n word:\n\n sage: B = cartesian_product((A, A, A)) # needs sage.combinat sage.modules\n sage: B.one_from_cartesian_product_of_one_basis() # needs sage.combinat sage.modules\n B[(0, word: )] + B[(1, word: )] + B[(2, word: )]\n sage: B.one() # needs sage.combinat sage.modules\n B[(0, word: )] + B[(1, word: )] + B[(2, word: )]\n\n sage: cartesian_product([SymmetricGroupAlgebra(QQ, 3), # needs sage.combinat sage.modules\n ....: SymmetricGroupAlgebra(QQ, 4)]).one()\n B[(0, [1, 2, 3])] + B[(1, [1, 2, 3, 4])]\n " return self.sum_of_monomials(zip(self._sets_keys(), (set.one_basis() for set in self._sets))) @lazy_attribute def one(self): "\n TESTS::\n\n sage: A = AlgebrasWithBasis(QQ).example(); A # needs sage.combinat sage.modules\n An example of an algebra with basis: the free algebra\n on the generators ('a', 'b', 'c') over Rational Field\n sage: B = cartesian_product((A, A, A)) # needs sage.combinat sage.modules\n sage: B.one() # needs sage.combinat sage.modules\n B[(0, word: )] + B[(1, word: )] + B[(2, word: )]\n " if all(((hasattr(module, 'one_basis') and (module.one_basis is not NotImplemented)) for module in self._sets)): return self.one_from_cartesian_product_of_one_basis return self._one_generic _one_generic = UnitalAlgebras.CartesianProducts.ParentMethods.one class TensorProducts(TensorProductsCategory): '\n The category of algebras with basis constructed by tensor product of algebras with basis\n ' @cached_method def extra_super_categories(self): '\n EXAMPLES::\n\n sage: AlgebrasWithBasis(QQ).TensorProducts().extra_super_categories()\n [Category of algebras with basis over Rational Field]\n sage: AlgebrasWithBasis(QQ).TensorProducts().super_categories()\n [Category of algebras with basis over Rational Field,\n Category of tensor products of algebras over Rational Field,\n Category of tensor products of vector spaces with basis over Rational Field]\n ' return [self.base_category()] class ParentMethods(): '\n implements operations on tensor products of algebras with basis\n ' @cached_method def one_basis(self): "\n Returns the index of the one of this tensor product of\n algebras, as per ``AlgebrasWithBasis.ParentMethods.one_basis``\n\n It is the tuple whose operands are the indices of the\n ones of the operands, as returned by their\n :meth:`.one_basis` methods.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = AlgebrasWithBasis(QQ).example(); A\n An example of an algebra with basis: the free algebra\n on the generators ('a', 'b', 'c') over Rational Field\n sage: A.one_basis()\n word:\n sage: B = tensor((A, A, A))\n sage: B.one_basis()\n (word: , word: , word: )\n sage: B.one()\n B[word: ] # B[word: ] # B[word: ]\n " if all((hasattr(module, 'one_basis') for module in self._sets)): return tuple((module.one_basis() for module in self._sets)) else: raise NotImplementedError def product_on_basis(self, t1, t2): "\n The product of the algebra on the basis, as per\n ``AlgebrasWithBasis.ParentMethods.product_on_basis``.\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).example(); A # needs sage.combinat sage.modules\n An example of an algebra with basis: the free algebra\n on the generators ('a', 'b', 'c') over Rational Field\n sage: (a,b,c) = A.algebra_generators() # needs sage.combinat sage.modules\n\n sage: x = tensor((a, b, c)); x # needs sage.combinat sage.modules\n B[word: a] # B[word: b] # B[word: c]\n sage: y = tensor((c, b, a)); y # needs sage.combinat sage.modules\n B[word: c] # B[word: b] # B[word: a]\n sage: x * y # needs sage.combinat sage.modules\n B[word: ac] # B[word: bb] # B[word: ca]\n\n sage: x = tensor(((a + 2*b), c)); x # needs sage.combinat sage.modules\n B[word: a] # B[word: c] + 2*B[word: b] # B[word: c]\n sage: y = tensor((c, a)) + 1; y # needs sage.combinat sage.modules\n B[word: ] # B[word: ] + B[word: c] # B[word: a]\n sage: x * y # needs sage.combinat sage.modules\n B[word: a] # B[word: c] + B[word: ac] # B[word: ca]\n + 2*B[word: b] # B[word: c] + 2*B[word: bc] # B[word: ca]\n\n\n TODO: optimize this implementation!\n " return tensor(((module.monomial(x1) * module.monomial(x2)) for (module, x1, x2) in zip(self._sets, t1, t2))) class ElementMethods(): '\n Implements operations on elements of tensor products of algebras with basis\n ' pass
class AperiodicSemigroups(CategoryWithAxiom): def extra_super_categories(self): '\n Implement the fact that an aperiodic semigroup is `H`-trivial.\n\n EXAMPLES::\n\n sage: Semigroups().Aperiodic().extra_super_categories()\n [Category of h trivial semigroups]\n ' return [Semigroups().HTrivial()]
class AssociativeAlgebras(CategoryWithAxiom_over_base_ring): '\n The category of associative algebras over a given base ring.\n\n An associative algebra over a ring `R` is a module over `R` which\n is also a not necessarily unital ring.\n\n .. WARNING::\n\n Until :trac:`15043` is implemented, :class:`Algebras` is the\n category of associative unital algebras; thus, unlike the name\n suggests, :class:`AssociativeAlgebras` is not a subcategory of\n :class:`Algebras` but of\n :class:`~.magmatic_algebras.MagmaticAlgebras`.\n\n EXAMPLES::\n\n sage: from sage.categories.associative_algebras import AssociativeAlgebras\n sage: C = AssociativeAlgebras(ZZ); C\n Category of associative algebras over Integer Ring\n\n TESTS::\n\n sage: from sage.categories.magmatic_algebras import MagmaticAlgebras\n sage: C is MagmaticAlgebras(ZZ).Associative()\n True\n sage: TestSuite(C).run()\n ' _base_category_class_and_axiom = (MagmaticAlgebras, 'Associative') Unital = LazyImport('sage.categories.algebras', 'Algebras', at_startup=True)
class Bialgebras(Category_over_base_ring): '\n The category of bialgebras\n\n EXAMPLES::\n\n sage: Bialgebras(ZZ)\n Category of bialgebras over Integer Ring\n sage: Bialgebras(ZZ).super_categories()\n [Category of algebras over Integer Ring, Category of coalgebras over Integer Ring]\n\n TESTS::\n\n sage: TestSuite(Bialgebras(ZZ)).run()\n ' def super_categories(self): '\n EXAMPLES::\n\n sage: Bialgebras(QQ).super_categories()\n [Category of algebras over Rational Field, Category of coalgebras over Rational Field]\n ' R = self.base_ring() return [Algebras(R), Coalgebras(R)] def additional_structure(self): '\n Return ``None``.\n\n Indeed, the category of bialgebras defines no additional\n structure: a morphism of coalgebras and of algebras between\n two bialgebras is a bialgebra morphism.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n .. TODO:: This category should be a :class:`CategoryWithAxiom`.\n\n EXAMPLES::\n\n sage: Bialgebras(QQ).additional_structure()\n ' return None class ElementMethods(): def is_primitive(self): '\n Return whether ``self`` is a primitive element.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: s = SymmetricFunctions(QQ).schur()\n sage: s([5]).is_primitive()\n False\n sage: p = SymmetricFunctions(QQ).powersum()\n sage: p([5]).is_primitive()\n True\n ' one = self.parent().one() return (self.coproduct() == (one.tensor(self) + self.tensor(one))) def is_grouplike(self): '\n Return whether ``self`` is a grouplike element.\n\n EXAMPLES::\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.modules\n sage: s([5]).is_grouplike() # needs sage.modules\n False\n sage: s([]).is_grouplike() # needs sage.modules\n True\n ' return (self.coproduct() == self.tensor(self)) class Super(SuperModulesCategory): pass WithBasis = LazyImport('sage.categories.bialgebras_with_basis', 'BialgebrasWithBasis')
class BialgebrasWithBasis(CategoryWithAxiom_over_base_ring): '\n The category of bialgebras with a distinguished basis.\n\n EXAMPLES::\n\n sage: C = BialgebrasWithBasis(QQ); C\n Category of bialgebras with basis over Rational Field\n\n sage: sorted(C.super_categories(), key=str)\n [Category of algebras with basis over Rational Field,\n Category of bialgebras over Rational Field,\n Category of coalgebras with basis over Rational Field]\n\n TESTS::\n\n sage: TestSuite(BialgebrasWithBasis(ZZ)).run()\n ' class ParentMethods(): def convolution_product(self, *maps): '\n Return the convolution product (a map) of the given maps.\n\n Let `A` and `B` be bialgebras over a commutative ring `R`.\n Given maps `f_i : A \\to B` for `1 \\leq i < n`, define the\n convolution product\n\n .. MATH::\n\n (f_1 * f_2 * \\cdots * f_n) := \\mu^{(n-1)} \\circ (f_1 \\otimes\n f_2 \\otimes \\cdots \\otimes f_n) \\circ \\Delta^{(n-1)},\n\n where `\\Delta^{(k)} := \\bigl(\\Delta \\otimes\n \\mathrm{Id}^{\\otimes(k-1)}\\bigr) \\circ \\Delta^{(k-1)}`,\n with `\\Delta^{(1)} = \\Delta` (the ordinary coproduct in `A`) and\n `\\Delta^{(0)} = \\mathrm{Id}`; and with `\\mu^{(k)} := \\mu \\circ\n \\bigl(\\mu^{(k-1)} \\otimes \\mathrm{Id})` and `\\mu^{(1)} = \\mu`\n (the ordinary product in `B`). See [Swe1969]_.\n\n (In the literature, one finds, e.g., `\\Delta^{(2)}` for what we\n denote above as `\\Delta^{(1)}`. See [KMN2012]_.)\n\n INPUT:\n\n - ``maps`` -- any number `n \\geq 0` of linear maps `f_1, f_2,\n \\ldots, f_n` on ``self``; or a single ``list`` or ``tuple``\n of such maps\n\n OUTPUT:\n\n - the new map `f_1 * f_2 * \\cdots * f_2` representing their\n convolution product\n\n .. SEEALSO::\n\n :meth:`sage.categories.bialgebras.ElementMethods.convolution_product`\n\n AUTHORS:\n\n - Aaron Lauve - 12 June 2015 - Sage Days 65\n\n .. TODO::\n\n Remove dependency on ``modules_with_basis`` methods.\n\n EXAMPLES:\n\n We construct some maps: the identity, the antipode and\n projection onto the homogeneous component of degree 2::\n\n sage: Id = lambda x: x\n sage: Antipode = lambda x: x.antipode()\n sage: Proj2 = lambda x: x.parent().sum_of_terms([(m, c) for (m, c) in x if m.size() == 2])\n\n Compute the convolution product of the identity with itself and\n with the projection ``Proj2`` on the Hopf algebra of\n non-commutative symmetric functions::\n\n sage: # needs sage.combinat sage.modules\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon()\n sage: T = R.convolution_product([Id, Id])\n sage: [T(R(comp)) for comp in Compositions(3)]\n [4*R[1, 1, 1] + R[1, 2] + R[2, 1],\n 2*R[1, 1, 1] + 4*R[1, 2] + 2*R[2, 1] + 2*R[3],\n 2*R[1, 1, 1] + 2*R[1, 2] + 4*R[2, 1] + 2*R[3],\n R[1, 2] + R[2, 1] + 4*R[3]]\n sage: T = R.convolution_product(Proj2, Id)\n sage: [T(R([i])) for i in range(1, 5)]\n [0, R[2], R[2, 1] + R[3], R[2, 2] + R[4]]\n\n Compute the convolution product of no maps on the Hopf algebra of\n symmetric functions in non-commuting variables. This is the\n composition of the counit with the unit::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m() # needs sage.combinat sage.modules\n sage: T = m.convolution_product() # needs sage.combinat sage.modules\n sage: [T(m(lam)) # needs sage.combinat sage.modules\n ....: for lam in SetPartitions(0).list() + SetPartitions(2).list()]\n [m{}, 0, 0]\n\n Compute the convolution product of the projection ``Proj2`` with\n the identity on the Hopf algebra of symmetric functions in\n non-commuting variables::\n\n sage: T = m.convolution_product(Proj2, Id) # needs sage.combinat sage.modules\n sage: [T(m(lam)) for lam in SetPartitions(3)] # needs sage.combinat sage.modules\n [0,\n m{{1, 2}, {3}} + m{{1, 2, 3}},\n m{{1, 2}, {3}} + m{{1, 2, 3}},\n m{{1, 2}, {3}} + m{{1, 2, 3}},\n 3*m{{1}, {2}, {3}} + 3*m{{1}, {2, 3}} + 3*m{{1, 3}, {2}}]\n\n Compute the convolution product of the antipode with itself and the\n identity map on group algebra of the symmetric group::\n\n sage: # needs sage.combinat sage.groups\n sage: G = SymmetricGroup(3)\n sage: QG = GroupAlgebra(G, QQ)\n sage: x = QG.sum_of_terms(\n ....: [(p, p.number_of_peaks() + p.number_of_inversions())\n ....: for p in Permutations(3)]\n ....: ); x\n 2*[1, 3, 2] + [2, 1, 3] + 3*[2, 3, 1] + 2*[3, 1, 2] + 3*[3, 2, 1]\n sage: T = QG.convolution_product(Antipode, Antipode, Id)\n sage: T(x)\n 2*[1, 3, 2] + [2, 1, 3] + 2*[2, 3, 1] + 3*[3, 1, 2] + 3*[3, 2, 1]\n ' onbasis = (lambda x: self.term(x).convolution_product(*maps)) return self.module_morphism(on_basis=onbasis, codomain=self) class ElementMethods(): def adams_operator(self, n): '\n Compute the `n`-th convolution power of the identity morphism\n `\\mathrm{Id}` on ``self``.\n\n INPUT:\n\n - ``n`` -- a nonnegative integer\n\n OUTPUT:\n\n - the image of ``self`` under the convolution power `\\mathrm{Id}^{*n}`\n\n .. NOTE::\n\n In the literature, this is also called a Hopf power or\n Sweedler power, cf. [AL2015]_.\n\n .. SEEALSO::\n\n :meth:`sage.categories.bialgebras.ElementMethods.convolution_product`\n\n .. TODO::\n\n Remove dependency on ``modules_with_basis`` methods.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: h = SymmetricFunctions(QQ).h()\n sage: h[5].adams_operator(2)\n 2*h[3, 2] + 2*h[4, 1] + 2*h[5]\n sage: h[5].plethysm(2*h[1])\n 2*h[3, 2] + 2*h[4, 1] + 2*h[5]\n sage: h([]).adams_operator(0)\n h[]\n sage: h([]).adams_operator(1)\n h[]\n sage: h[3,2].adams_operator(0)\n 0\n sage: h[3,2].adams_operator(1)\n h[3, 2]\n\n ::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S() # needs sage.combinat sage.modules\n sage: S[4].adams_operator(5) # needs sage.combinat sage.modules\n 5*S[1, 1, 1, 1] + 10*S[1, 1, 2] + 10*S[1, 2, 1]\n + 10*S[1, 3] + 10*S[2, 1, 1] + 10*S[2, 2] + 10*S[3, 1] + 5*S[4]\n\n\n ::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m() # needs sage.combinat sage.modules\n sage: m[[1,3],[2]].adams_operator(-2) # needs sage.combinat sage.modules\n 3*m{{1}, {2, 3}} + 3*m{{1, 2}, {3}} + 6*m{{1, 2, 3}} - 2*m{{1, 3}, {2}}\n ' if (n < 0): if hasattr(self, 'antipode'): T = (lambda x: x.antipode()) n = abs(n) else: raise ValueError('antipode not defined; cannot take negative convolution powers: {} < 0'.format(n)) else: T = (lambda x: x) return self.convolution_product(([T] * n)) def convolution_product(self, *maps): '\n Return the image of ``self`` under the convolution product (map) of\n the maps.\n\n Let `A` and `B` be bialgebras over a commutative ring `R`.\n Given maps `f_i : A \\to B` for `1 \\leq i < n`, define the\n convolution product\n\n .. MATH::\n\n (f_1 * f_2 * \\cdots * f_n) := \\mu^{(n-1)} \\circ (f_1 \\otimes\n f_2 \\otimes \\cdots \\otimes f_n) \\circ \\Delta^{(n-1)},\n\n where `\\Delta^{(k)} := \\bigl(\\Delta \\otimes\n \\mathrm{Id}^{\\otimes(k-1)}\\bigr) \\circ \\Delta^{(k-1)}`,\n with `\\Delta^{(1)} = \\Delta` (the ordinary coproduct in `A`) and\n `\\Delta^{(0)} = \\mathrm{Id}`; and with `\\mu^{(k)} := \\mu \\circ\n \\bigl(\\mu^{(k-1)} \\otimes \\mathrm{Id})` and `\\mu^{(1)} = \\mu`\n (the ordinary product in `B`). See [Swe1969]_.\n\n (In the literature, one finds, e.g., `\\Delta^{(2)}` for what we\n denote above as `\\Delta^{(1)}`. See [KMN2012]_.)\n\n INPUT:\n\n - ``maps`` -- any number `n \\geq 0` of linear maps `f_1, f_2,\n \\ldots, f_n` on ``self.parent()``; or a single ``list`` or\n ``tuple`` of such maps\n\n OUTPUT:\n\n - the convolution product of ``maps`` applied to ``self``\n\n AUTHORS:\n\n - Amy Pang - 12 June 2015 - Sage Days 65\n\n .. TODO::\n\n Remove dependency on ``modules_with_basis`` methods.\n\n EXAMPLES:\n\n We compute convolution products of the identity and antipode maps\n on Schur functions::\n\n sage: Id = lambda x: x\n sage: Antipode = lambda x: x.antipode()\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: s[3].convolution_product(Id, Id) # needs sage.combinat sage.modules\n 2*s[2, 1] + 4*s[3]\n sage: s[3,2].convolution_product(Id) == s[3,2] # needs sage.combinat sage.modules\n True\n\n The method accepts multiple arguments, or a single argument\n consisting of a list of maps::\n\n sage: s[3,2].convolution_product(Id, Id) # needs sage.combinat sage.modules\n 2*s[2, 1, 1, 1] + 6*s[2, 2, 1] + 6*s[3, 1, 1] + 12*s[3, 2] + 6*s[4, 1] + 2*s[5]\n sage: s[3,2].convolution_product([Id, Id]) # needs sage.combinat sage.modules\n 2*s[2, 1, 1, 1] + 6*s[2, 2, 1] + 6*s[3, 1, 1] + 12*s[3, 2] + 6*s[4, 1] + 2*s[5]\n\n We test the defining property of the antipode morphism; namely,\n that the antipode is the inverse of the identity map in the\n convolution algebra whose identity element is the composition of\n the counit and unit::\n\n sage: (s[3,2].convolution_product() # needs sage.combinat sage.modules\n ....: == s[3,2].convolution_product(Antipode, Id)\n ....: == s[3,2].convolution_product(Id, Antipode))\n True\n\n ::\n\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi() # needs sage.combinat sage.modules\n sage: Psi[2,1].convolution_product(Id, Id, Id) # needs sage.combinat sage.modules\n 3*Psi[1, 2] + 6*Psi[2, 1]\n sage: (Psi[5,1] - Psi[1,5]).convolution_product(Id, Id, Id) # needs sage.combinat sage.modules\n -3*Psi[1, 5] + 3*Psi[5, 1]\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: G = SymmetricGroup(3)\n sage: QG = GroupAlgebra(G, QQ)\n sage: x = QG.sum_of_terms([(p, p.length())\n ....: for p in Permutations(3)]); x\n [1, 3, 2] + [2, 1, 3] + 2*[2, 3, 1] + 2*[3, 1, 2] + 3*[3, 2, 1]\n sage: x.convolution_product(Id, Id)\n 5*[1, 2, 3] + 2*[2, 3, 1] + 2*[3, 1, 2]\n sage: x.convolution_product(Id, Id, Id)\n 4*[1, 2, 3] + [1, 3, 2] + [2, 1, 3] + 3*[3, 2, 1]\n sage: x.convolution_product([Id] * 6)\n 9*[1, 2, 3]\n\n TESTS::\n\n sage: Id = lambda x: x\n sage: Antipode = lambda x: x.antipode()\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: h = SymmetricFunctions(QQ).h()\n sage: h[5].convolution_product([Id, Id])\n 2*h[3, 2] + 2*h[4, 1] + 2*h[5]\n sage: h.one().convolution_product([Id, Antipode])\n h[]\n sage: h[3,2].convolution_product([Id, Antipode])\n 0\n sage: (h.one().convolution_product([Id, Antipode])\n ....: == h.one().convolution_product())\n True\n\n ::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S() # needs sage.combinat sage.modules\n sage: S[4].convolution_product([Id] * 5) # needs sage.combinat sage.modules\n 5*S[1, 1, 1, 1] + 10*S[1, 1, 2] + 10*S[1, 2, 1] + 10*S[1, 3]\n + 10*S[2, 1, 1] + 10*S[2, 2] + 10*S[3, 1] + 5*S[4]\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m()\n sage: m[[1,3],[2]].convolution_product([Antipode, Antipode])\n 3*m{{1}, {2, 3}} + 3*m{{1, 2}, {3}} + 6*m{{1, 2, 3}} - 2*m{{1, 3}, {2}}\n sage: m[[]].convolution_product([])\n m{}\n sage: m[[1,3],[2]].convolution_product([])\n 0\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: QS = SymmetricGroupAlgebra(QQ, 5)\n sage: x = QS.sum_of_terms(zip(Permutations(5)[3:6], [1,2,3])); x\n [1, 2, 4, 5, 3] + 2*[1, 2, 5, 3, 4] + 3*[1, 2, 5, 4, 3]\n sage: x.convolution_product([Antipode, Id])\n 6*[1, 2, 3, 4, 5]\n sage: x.convolution_product(Id, Antipode, Antipode, Antipode)\n 3*[1, 2, 3, 4, 5] + [1, 2, 4, 5, 3] + 2*[1, 2, 5, 3, 4]\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: G = SymmetricGroup(3)\n sage: QG = GroupAlgebra(G, QQ)\n sage: x = QG.sum_of_terms([(p, p.length())\n ....: for p in Permutations(3)]); x\n [1, 3, 2] + [2, 1, 3] + 2*[2, 3, 1] + 2*[3, 1, 2] + 3*[3, 2, 1]\n sage: x.convolution_product(Antipode, Id)\n 9*[1, 2, 3]\n sage: x.convolution_product([Id, Antipode, Antipode, Antipode])\n 5*[1, 2, 3] + 2*[2, 3, 1] + 2*[3, 1, 2]\n\n ::\n\n sage: (s[3,2].counit().parent() # needs sage.combinat sage.modules\n ....: == s[3,2].convolution_product().parent())\n False\n ' if ((len(maps) == 1) and isinstance(maps[0], (list, tuple))): T = tuple(maps[0]) else: T = maps H = self.parent() n = len(T) if (n == 0): return (H.one() * self.counit()) if (n == 1): return T[0](self) out = tensor((H.one(), self)) HH = tensor((H, H)) for mor in T[:(- 1)]: def split_convolve(x_y): (x, y) = x_y return (((xy1, y2), (c * d)) for ((y1, y2), d) in H.term(y).coproduct() for (xy1, c) in (H.term(x) * mor(H.term(y1)))) out = HH.module_morphism(on_basis=(lambda t: HH.sum_of_terms(split_convolve(t))), codomain=HH)(out) return HH.module_morphism(on_basis=(lambda xy: (H.term(xy[0]) * T[(- 1)](H.term(xy[1])))), codomain=H)(out)
class Bimodules(CategoryWithParameters): '\n The category of `(R,S)`-bimodules\n\n For `R` and `S` rings, a `(R,S)`-bimodule `X` is a left `R`-module\n and right `S`-module such that the left and right actions commute:\n `r*(x*s) = (r*x)*s`.\n\n EXAMPLES::\n\n sage: Bimodules(QQ, ZZ)\n Category of bimodules over Rational Field on the left and Integer Ring on the right\n sage: Bimodules(QQ, ZZ).super_categories()\n [Category of left modules over Rational Field, Category of right modules over Integer Ring]\n ' def __init__(self, left_base, right_base, name=None): '\n The ``name`` parameter is ignored.\n\n EXAMPLES::\n\n sage: C = Bimodules(QQ, ZZ)\n sage: TestSuite(C).run()\n ' if (not ((left_base in Rings()) or (isinstance(left_base, Category) and left_base.is_subcategory(Rings())))): raise ValueError('the left base must be a ring or a subcategory of Rings()') if (not ((right_base in Rings()) or (isinstance(right_base, Category) and right_base.is_subcategory(Rings())))): raise ValueError('the right base must be a ring or a subcategory of Rings()') self._left_base_ring = left_base self._right_base_ring = right_base Category.__init__(self) def _make_named_class_key(self, name): "\n Return what the element/parent/... classes depend on.\n\n Since :trac:`11935`, the element and parent classes of a\n bimodule only depend on the categories of the left and right\n base ring.\n\n .. SEEALSO::\n\n - :meth:`CategoryWithParameters`\n - :meth:`CategoryWithParameters._make_named_class_key`\n\n EXAMPLES::\n\n sage: Bimodules(QQ,ZZ)._make_named_class_key('parent_class')\n (Join of Category of number fields\n and Category of quotient fields\n and Category of metric spaces,\n Join of Category of euclidean domains\n and Category of infinite enumerated sets\n and Category of metric spaces)\n\n\n sage: Bimodules(Fields(), ZZ)._make_named_class_key('element_class')\n (Category of fields,\n Join of Category of euclidean domains\n and Category of infinite enumerated sets\n and Category of metric spaces)\n\n sage: Bimodules(QQ, Rings())._make_named_class_key('element_class')\n (Join of Category of number fields\n and Category of quotient fields\n and Category of metric spaces,\n Category of rings)\n\n sage: Bimodules(Fields(), Rings())._make_named_class_key('element_class')\n (Category of fields, Category of rings)\n " return ((self._left_base_ring if isinstance(self._left_base_ring, Category) else self._left_base_ring.category()), (self._right_base_ring if isinstance(self._right_base_ring, Category) else self._right_base_ring.category())) @classmethod def an_instance(cls): '\n Return an instance of this class.\n\n EXAMPLES::\n\n sage: Bimodules.an_instance() # needs sage.rings.real_mpfr\n Category of bimodules over Rational Field on the left and Real Field with 53 bits of precision on the right\n ' from sage.rings.rational_field import QQ from sage.rings.real_mpfr import RR return cls(QQ, RR) def _repr_object_names(self): '\n EXAMPLES::\n\n sage: Bimodules(QQ, ZZ) # indirect doctest\n Category of bimodules over Rational Field on the left and Integer Ring on the right\n ' return ('bimodules over %s on the left and %s on the right' % (self._left_base_ring, self._right_base_ring)) def left_base_ring(self): '\n Return the left base ring over which elements of this category are\n defined.\n\n EXAMPLES::\n\n sage: Bimodules(QQ, ZZ).left_base_ring()\n Rational Field\n ' return self._left_base_ring def right_base_ring(self): '\n Return the right base ring over which elements of this category are\n defined.\n\n EXAMPLES::\n\n sage: Bimodules(QQ, ZZ).right_base_ring()\n Integer Ring\n ' return self._right_base_ring def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: print(Bimodules(QQ, ZZ)._latex_())\n {\\mathbf{Bimodules}}_{\\Bold{Q}, \\Bold{Z}}\n ' from sage.misc.latex import latex return '{{{0}}}_{{{1}, {2}}}'.format(Category._latex_(self), latex(self._left_base_ring), latex(self._right_base_ring)) def super_categories(self): '\n EXAMPLES::\n\n sage: Bimodules(QQ, ZZ).super_categories()\n [Category of left modules over Rational Field, Category of right modules over Integer Ring]\n ' R = self.left_base_ring() S = self.right_base_ring() return [LeftModules(R), RightModules(S)] def additional_structure(self): '\n Return ``None``.\n\n Indeed, the category of bimodules defines no additional\n structure: a left and right module morphism between two\n bimodules is a bimodule morphism.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n .. TODO:: Should this category be a :class:`CategoryWithAxiom`?\n\n EXAMPLES::\n\n sage: Bimodules(QQ, ZZ).additional_structure()\n ' return None class ParentMethods(): pass class ElementMethods(): pass
class CartesianProductFunctor(CovariantFunctorialConstruction, MultivariateConstructionFunctor): "\n The Cartesian product functor.\n\n EXAMPLES::\n\n sage: cartesian_product\n The cartesian_product functorial construction\n\n ``cartesian_product`` takes a finite collection of sets, and\n constructs the Cartesian product of those sets::\n\n sage: A = FiniteEnumeratedSet(['a','b','c'])\n sage: B = FiniteEnumeratedSet([1,2])\n sage: C = cartesian_product([A, B]); C\n The Cartesian product of ({'a', 'b', 'c'}, {1, 2})\n sage: C.an_element()\n ('a', 1)\n sage: C.list() # todo: not implemented\n [['a', 1], ['a', 2], ['b', 1], ['b', 2], ['c', 1], ['c', 2]]\n\n If those sets are endowed with more structure, say they are\n monoids (hence in the category ``Monoids()``), then the result is\n automatically endowed with its natural monoid structure::\n\n sage: M = Monoids().example()\n sage: M\n An example of a monoid: the free monoid generated by ('a', 'b', 'c', 'd')\n sage: M.rename('M')\n sage: C = cartesian_product([M, ZZ, QQ])\n sage: C\n The Cartesian product of (M, Integer Ring, Rational Field)\n sage: C.an_element()\n ('abcd', 1, 1/2)\n sage: C.an_element()^2\n ('abcdabcd', 1, 1/4)\n sage: C.category()\n Category of Cartesian products of monoids\n\n sage: Monoids().CartesianProducts()\n Category of Cartesian products of monoids\n\n The Cartesian product functor is covariant: if ``A`` is a\n subcategory of ``B``, then ``A.CartesianProducts()`` is a\n subcategory of ``B.CartesianProducts()`` (see also\n :class:`~sage.categories.covariant_functorial_construction.CovariantFunctorialConstruction`)::\n\n sage: C.categories()\n [Category of Cartesian products of monoids,\n Category of monoids,\n Category of Cartesian products of semigroups,\n Category of semigroups,\n Category of Cartesian products of unital magmas,\n Category of Cartesian products of magmas,\n Category of unital magmas,\n Category of magmas,\n Category of Cartesian products of sets,\n Category of sets, ...]\n\n [Category of Cartesian products of monoids,\n Category of monoids,\n Category of Cartesian products of semigroups,\n Category of semigroups,\n Category of Cartesian products of magmas,\n Category of unital magmas,\n Category of magmas,\n Category of Cartesian products of sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n Hence, the role of ``Monoids().CartesianProducts()`` is solely to\n provide mathematical information and algorithms which are relevant\n to Cartesian product of monoids. For example, it specifies that\n the result is again a monoid, and that its multiplicative unit is\n the Cartesian product of the units of the underlying sets::\n\n sage: C.one()\n ('', 1, 1)\n\n Those are implemented in the nested class\n :class:`Monoids.CartesianProducts\n <sage.categories.monoids.Monoids.CartesianProducts>` of\n ``Monoids(QQ)``. This nested class is itself a subclass of\n :class:`CartesianProductsCategory`.\n\n " _functor_name = 'cartesian_product' _functor_category = 'CartesianProducts' symbol = ' (+) ' def __init__(self, category=None): '\n Constructor. See :class:`CartesianProductFunctor` for details.\n\n TESTS::\n\n sage: from sage.categories.cartesian_product import CartesianProductFunctor\n sage: CartesianProductFunctor()\n The cartesian_product functorial construction\n ' CovariantFunctorialConstruction.__init__(self) self._forced_category = category from sage.categories.sets_cat import Sets if (self._forced_category is not None): codomain = self._forced_category else: codomain = Sets() MultivariateConstructionFunctor.__init__(self, Sets(), codomain) def __call__(self, args, **kwds): "\n Functorial construction application.\n\n This specializes the generic ``__call__`` from\n :class:`CovariantFunctorialConstruction` to:\n\n - handle the following plain Python containers as input:\n :class:`frozenset`, :class:`list`, :class:`set`,\n :class:`tuple`, and :class:`xrange` (Python3 ``range``).\n\n - handle the empty list of factors.\n\n See the examples below.\n\n EXAMPLES::\n\n sage: cartesian_product([[0,1], ('a','b','c')])\n The Cartesian product of ({0, 1}, {'a', 'b', 'c'})\n sage: _.category()\n Category of Cartesian products of finite enumerated sets\n\n sage: cartesian_product([set([0,1,2]), [0,1]])\n The Cartesian product of ({0, 1, 2}, {0, 1})\n sage: _.category()\n Category of Cartesian products of finite enumerated sets\n\n Check that the empty product is handled correctly::\n\n sage: C = cartesian_product([])\n sage: C\n The Cartesian product of ()\n sage: C.cardinality()\n 1\n sage: C.an_element()\n ()\n sage: C.category()\n Category of Cartesian products of sets\n\n Check that Python3 ``range`` is handled correctly::\n\n sage: C = cartesian_product([range(2), range(2)])\n sage: list(C)\n [(0, 0), (0, 1), (1, 0), (1, 1)]\n sage: C.category()\n Category of Cartesian products of finite enumerated sets\n " if any(((type(arg) in native_python_containers) for arg in args)): from sage.categories.sets_cat import Sets S = Sets() args = [S(a, enumerated_set=True) for a in args] elif (not args): if (self._forced_category is None): from sage.categories.sets_cat import Sets cat = Sets().CartesianProducts() else: cat = self._forced_category from sage.sets.cartesian_product import CartesianProduct return CartesianProduct((), cat) elif (self._forced_category is not None): return super().__call__(args, category=self._forced_category, **kwds) return super().__call__(args, **kwds) def __eq__(self, other): '\n Comparison ignores the ``category`` parameter.\n\n TESTS::\n\n sage: from sage.categories.cartesian_product import CartesianProductFunctor\n sage: cartesian_product([ZZ, ZZ]).construction()[0] == CartesianProductFunctor()\n True\n ' return isinstance(other, CartesianProductFunctor) def __ne__(self, other): '\n Comparison ignores the ``category`` parameter.\n\n TESTS::\n\n sage: from sage.categories.cartesian_product import CartesianProductFunctor\n sage: cartesian_product([ZZ, ZZ]).construction()[0] != CartesianProductFunctor()\n False\n ' return (not (self == other))
class CartesianProductsCategory(CovariantConstructionCategory): '\n An abstract base class for all ``CartesianProducts`` categories.\n\n TESTS::\n\n sage: C = Sets().CartesianProducts()\n sage: C\n Category of Cartesian products of sets\n sage: C.base_category()\n Category of sets\n sage: latex(C)\n \\mathbf{CartesianProducts}(\\mathbf{Sets})\n ' _functor_category = 'CartesianProducts' def _repr_object_names(self): '\n EXAMPLES::\n\n sage: ModulesWithBasis(QQ).CartesianProducts() # indirect doctest\n Category of Cartesian products of vector spaces with basis over Rational Field\n\n ' return ('Cartesian products of %s' % self.base_category()._repr_object_names()) def CartesianProducts(self): "\n Return the category of (finite) Cartesian products of objects\n of ``self``.\n\n By associativity of Cartesian products, this is ``self`` (a Cartesian\n product of Cartesian products of `A`'s is a Cartesian product of\n `A`'s).\n\n EXAMPLES::\n\n sage: ModulesWithBasis(QQ).CartesianProducts().CartesianProducts()\n Category of Cartesian products of vector spaces with basis over Rational Field\n " return self def base_ring(self): '\n The base ring of a Cartesian product is the base ring of the underlying category.\n\n EXAMPLES::\n\n sage: Algebras(ZZ).CartesianProducts().base_ring()\n Integer Ring\n ' return self.base_category().base_ring()
class Category(UniqueRepresentation, SageObject): '\n The base class for modeling mathematical categories, like for example:\n\n - ``Groups()``: the category of groups\n - ``EuclideanDomains()``: the category of euclidean rings\n - ``VectorSpaces(QQ)``: the category of vector spaces over the field of\n rationals\n\n See :mod:`sage.categories.primer` for an introduction to\n categories in Sage, their relevance, purpose, and usage. The\n documentation below will focus on their implementation.\n\n Technically, a category is an instance of the class\n :class:`Category` or some of its subclasses. Some categories, like\n :class:`VectorSpaces`, are parametrized: ``VectorSpaces(QQ)`` is one of\n many instances of the class :class:`VectorSpaces`. On the other\n hand, ``EuclideanDomains()`` is the single instance of the class\n :class:`EuclideanDomains`.\n\n Recall that an algebraic structure (say, the ring `\\QQ[x]`) is\n modelled in Sage by an object which is called a parent. This\n object belongs to certain categories (here ``EuclideanDomains()`` and\n ``Algebras()``). The elements of the ring are themselves objects.\n\n The class of a category (say :class:`EuclideanDomains`) can define simultaneously:\n\n - Operations on the category itself (what is its super categories?\n its category of morphisms? its dual category?).\n - Generic operations on parents in this category, like the ring `\\QQ[x]`.\n - Generic operations on elements of such parents (e. g., the\n Euclidean algorithm for computing gcds).\n - Generic operations on morphisms of this category.\n\n This is achieved as follows::\n\n sage: from sage.categories.category import Category\n sage: class EuclideanDomains(Category):\n ....: # operations on the category itself\n ....: def super_categories(self):\n ....: [Rings()]\n ....:\n ....: def dummy(self): # TODO: find some good examples\n ....: pass\n ....:\n ....: class ParentMethods: # holds the generic operations on parents\n ....: # TODO: find a good example of an operation\n ....: pass\n ....:\n ....: class ElementMethods:# holds the generic operations on elements\n ....: def gcd(x,y):\n ....: # Euclid algorithms\n ....: pass\n ....:\n ....: class MorphismMethods: # holds the generic operations on morphisms\n ....: # TODO: find a good example of an operation\n ....: pass\n ....:\n\n Note that the nested class ``ParentMethods`` is merely a container\n of operations, and does not inherit from anything. Instead, the\n hierarchy relation is defined once at the level of the categories,\n and the actual hierarchy of classes is built in parallel from all\n the ``ParentMethods`` nested classes, and stored in the attributes\n ``parent_class``. Then, a parent in a category ``C`` receives the\n appropriate operations from all the super categories by usual\n class inheritance from ``C.parent_class``.\n\n Similarly, two other hierarchies of classes, for elements and\n morphisms respectively, are built from all the ``ElementMethods``\n and ``MorphismMethods`` nested classes.\n\n EXAMPLES:\n\n We define a hierarchy of four categories ``As()``, ``Bs()``,\n ``Cs()``, ``Ds()`` with a diamond inheritance. Think for example:\n\n - ``As()``: the category of sets\n - ``Bs()``: the category of additive groups\n - ``Cs()``: the category of multiplicative monoids\n - ``Ds()``: the category of rings\n\n ::\n\n sage: from sage.categories.category import Category\n sage: from sage.misc.lazy_attribute import lazy_attribute\n sage: class As (Category):\n ....: def super_categories(self):\n ....: return []\n ....:\n ....: class ParentMethods:\n ....: def fA(self):\n ....: return "A"\n ....: f = fA\n\n sage: class Bs (Category):\n ....: def super_categories(self):\n ....: return [As()]\n ....:\n ....: class ParentMethods:\n ....: def fB(self):\n ....: return "B"\n\n sage: class Cs (Category):\n ....: def super_categories(self):\n ....: return [As()]\n ....:\n ....: class ParentMethods:\n ....: def fC(self):\n ....: return "C"\n ....: f = fC\n\n sage: class Ds (Category):\n ....: def super_categories(self):\n ....: return [Bs(),Cs()]\n ....:\n ....: class ParentMethods:\n ....: def fD(self):\n ....: return "D"\n\n Categories should always have unique representation; by :trac:`12215`,\n this means that it will be kept in cache, but only\n if there is still some strong reference to it.\n\n We check this before proceeding::\n\n sage: import gc\n sage: idAs = id(As())\n sage: _ = gc.collect()\n sage: n == id(As())\n False\n sage: a = As()\n sage: id(As()) == id(As())\n True\n sage: As().parent_class == As().parent_class\n True\n\n We construct a parent in the category ``Ds()`` (that, is an instance\n of ``Ds().parent_class``), and check that it has access to all the\n methods provided by all the categories, with the appropriate\n inheritance order::\n\n sage: D = Ds().parent_class()\n sage: [ D.fA(), D.fB(), D.fC(), D.fD() ]\n [\'A\', \'B\', \'C\', \'D\']\n sage: D.f()\n \'C\'\n\n ::\n\n sage: C = Cs().parent_class()\n sage: [ C.fA(), C.fC() ]\n [\'A\', \'C\']\n sage: C.f()\n \'C\'\n\n Here is the parallel hierarchy of classes which has been built\n automatically, together with the method resolution order (``.mro()``)::\n\n sage: As().parent_class\n <class \'__main__.As.parent_class\'>\n sage: As().parent_class.__bases__\n (<... \'object\'>,)\n sage: As().parent_class.mro()\n [<class \'__main__.As.parent_class\'>, <... \'object\'>]\n\n ::\n\n sage: Bs().parent_class\n <class \'__main__.Bs.parent_class\'>\n sage: Bs().parent_class.__bases__\n (<class \'__main__.As.parent_class\'>,)\n sage: Bs().parent_class.mro()\n [<class \'__main__.Bs.parent_class\'>, <class \'__main__.As.parent_class\'>, <... \'object\'>]\n\n ::\n\n sage: Cs().parent_class\n <class \'__main__.Cs.parent_class\'>\n sage: Cs().parent_class.__bases__\n (<class \'__main__.As.parent_class\'>,)\n sage: Cs().parent_class.__mro__\n (<class \'__main__.Cs.parent_class\'>, <class \'__main__.As.parent_class\'>, <... \'object\'>)\n\n ::\n\n sage: Ds().parent_class\n <class \'__main__.Ds.parent_class\'>\n sage: Ds().parent_class.__bases__\n (<class \'__main__.Cs.parent_class\'>, <class \'__main__.Bs.parent_class\'>)\n sage: Ds().parent_class.mro()\n [<class \'__main__.Ds.parent_class\'>, <class \'__main__.Cs.parent_class\'>,\n <class \'__main__.Bs.parent_class\'>, <class \'__main__.As.parent_class\'>, <... \'object\'>]\n\n Note that two categories in the same class need not have the\n same ``super_categories``. For example, ``Algebras(QQ)`` has\n ``VectorSpaces(QQ)`` as super category, whereas ``Algebras(ZZ)``\n only has ``Modules(ZZ)`` as super category. In particular, the\n constructed parent class and element class will differ (inheriting,\n or not, methods specific for vector spaces)::\n\n sage: Algebras(QQ).parent_class is Algebras(ZZ).parent_class\n False\n sage: issubclass(Algebras(QQ).parent_class, VectorSpaces(QQ).parent_class)\n True\n\n On the other hand, identical hierarchies of classes are,\n preferably, built only once (e.g. for categories over a base ring)::\n\n sage: Algebras(GF(5)).parent_class is Algebras(GF(7)).parent_class\n True\n sage: F = FractionField(ZZ[\'t\'])\n sage: Coalgebras(F).parent_class is Coalgebras(FractionField(F[\'x\'])).parent_class\n True\n\n We now construct a parent in the usual way::\n\n sage: class myparent(Parent):\n ....: def __init__(self):\n ....: Parent.__init__(self, category=Ds())\n ....: def g(self):\n ....: return "myparent"\n ....: class Element():\n ....: pass\n sage: D = myparent()\n sage: D.__class__\n <class \'__main__.myparent_with_category\'>\n sage: D.__class__.__bases__\n (<class \'__main__.myparent\'>, <class \'__main__.Ds.parent_class\'>)\n sage: D.__class__.mro()\n [<class \'__main__.myparent_with_category\'>,\n <class \'__main__.myparent\'>,\n <class \'sage.structure.parent.Parent\'>,\n <class \'sage.structure.category_object.CategoryObject\'>,\n <class \'sage.structure.sage_object.SageObject\'>,\n <class \'__main__.Ds.parent_class\'>,\n <class \'__main__.Cs.parent_class\'>,\n <class \'__main__.Bs.parent_class\'>,\n <class \'__main__.As.parent_class\'>,\n <... \'object\'>]\n sage: D.fA()\n \'A\'\n sage: D.fB()\n \'B\'\n sage: D.fC()\n \'C\'\n sage: D.fD()\n \'D\'\n sage: D.f()\n \'C\'\n sage: D.g()\n \'myparent\'\n\n ::\n\n sage: D.element_class\n <class \'__main__.myparent_with_category.element_class\'>\n sage: D.element_class.mro()\n [<class \'__main__.myparent_with_category.element_class\'>,\n <class ...__main__....Element...>,\n <class \'__main__.Ds.element_class\'>,\n <class \'__main__.Cs.element_class\'>,\n <class \'__main__.Bs.element_class\'>,\n <class \'__main__.As.element_class\'>,\n <... \'object\'>]\n\n\n TESTS::\n\n sage: import __main__\n sage: __main__.myparent = myparent\n sage: __main__.As = As\n sage: __main__.Bs = Bs\n sage: __main__.Cs = Cs\n sage: __main__.Ds = Ds\n sage: loads(dumps(Ds)) is Ds\n True\n sage: loads(dumps(Ds())) is Ds()\n True\n sage: loads(dumps(Ds().element_class)) is Ds().element_class\n True\n\n .. automethod:: Category._super_categories\n .. automethod:: Category._super_categories_for_classes\n .. automethod:: Category._all_super_categories\n .. automethod:: Category._all_super_categories_proper\n .. automethod:: Category._set_of_super_categories\n .. automethod:: Category._make_named_class\n .. automethod:: Category._repr_\n .. automethod:: Category._repr_object_names\n .. automethod:: Category._test_category\n .. automethod:: Category._with_axiom\n .. automethod:: Category._with_axiom_as_tuple\n .. automethod:: Category._without_axioms\n .. automethod:: Category._sort\n .. automethod:: Category._sort_uniq\n .. automethod:: Category.__classcall__\n .. automethod:: Category.__init__\n ' @staticmethod def __classcall__(cls, *args, **options): "\n Input mangling for unique representation.\n\n Let ``C = Cs(...)`` be a category. Since :trac:`12895`, the\n class of ``C`` is a dynamic subclass ``Cs_with_category`` of\n ``Cs`` in order for ``C`` to inherit code from the\n ``SubcategoryMethods`` nested classes of its super categories.\n\n The purpose of this ``__classcall__`` method is to ensure that\n reconstructing ``C`` from its class with\n ``Cs_with_category(...)`` actually calls properly ``Cs(...)``\n and gives back ``C``.\n\n .. SEEALSO:: :meth:`subcategory_class`\n\n EXAMPLES::\n\n sage: A = Algebras(QQ)\n sage: A.__class__\n <class 'sage.categories.algebras.Algebras_with_category'>\n sage: A is Algebras(QQ)\n True\n sage: A is A.__class__(QQ)\n True\n " if isinstance(cls, DynamicMetaclass): cls = cls.__base__ return super().__classcall__(cls, *args, **options) def __init__(self): "\n Initialize this category.\n\n EXAMPLES::\n\n sage: class SemiprimitiveRings(Category):\n ....: def super_categories(self):\n ....: return [Rings()]\n ....: class ParentMethods:\n ....: def jacobson_radical(self):\n ....: return self.ideal(0)\n sage: C = SemiprimitiveRings()\n sage: C\n Category of semiprimitive rings\n sage: C.__class__\n <class '__main__.SemiprimitiveRings_with_category'>\n\n .. NOTE::\n\n If the default name of the category (built from the name of\n the class) is not adequate, please implement\n :meth:`_repr_object_names` to customize it.\n " self.__class__ = dynamic_class('{}_with_category'.format(self.__class__.__name__), (self.__class__, self.subcategory_class), cache=False, reduction=None, doccls=self.__class__) @lazy_attribute def _label(self): "\n A short name of ``self``, obtained from its type.\n\n EXAMPLES::\n\n sage: Rings()._label\n 'Rings'\n\n " t = str(self.__class__.__base__) t = t[(t.rfind('.') + 1):] return t[:t.rfind("'")] def _repr_object_names(self): "\n Return the name of the objects of this category.\n\n EXAMPLES::\n\n sage: FiniteGroups()._repr_object_names()\n 'finite groups'\n sage: AlgebrasWithBasis(QQ)._repr_object_names()\n 'algebras with basis over Rational Field'\n\n TESTS::\n\n sage: Rings()\n Category of rings\n sage: Rings()._repr_object_names()\n 'rings'\n sage: PrincipalIdealDomains()._repr_object_names()\n 'principal ideal domains'\n " words = ''.join(((letter if (not letter.isupper()) else (';' + letter)) for letter in self._label)).split(';') return ' '.join(((w if (w in HALL_OF_FAME) else w.lower()) for w in words)).lstrip() def _short_name(self): "\n Return a CamelCase name for this category.\n\n EXAMPLES::\n\n sage: CoxeterGroups()._short_name()\n 'CoxeterGroups'\n\n sage: AlgebrasWithBasis(QQ)._short_name()\n 'AlgebrasWithBasis'\n\n Conventions for short names should be discussed at the level\n of Sage, and only then applied accordingly here.\n " return self._label @classmethod def an_instance(cls): '\n Return an instance of this class.\n\n EXAMPLES::\n\n sage: Rings.an_instance()\n Category of rings\n\n Parametrized categories should overload this default\n implementation to provide appropriate arguments::\n\n sage: Algebras.an_instance()\n Category of algebras over Rational Field\n sage: Bimodules.an_instance() # needs sage.rings.real_mpfr\n Category of bimodules over Rational Field on the left\n and Real Field with 53 bits of precision on the right\n sage: AlgebraIdeals.an_instance()\n Category of algebra ideals\n in Univariate Polynomial Ring in x over Rational Field\n ' return cls() def __call__(self, x, *args, **opts): '\n Construct an object in this category from the data in ``x``,\n or throw :class:`TypeError` or :class:`NotImplementedError`.\n\n If ``x`` is readily in ``self`` it is returned unchanged.\n Categories wishing to extend this minimal behavior should\n implement :meth:`._call_`.\n\n EXAMPLES::\n\n sage: Rings()(ZZ)\n Integer Ring\n ' if (x in self): return x return self._call_(x, *args, **opts) def _call_(self, x): '\n Construct an object in this category from the data in ``x``,\n or throw :class:`NotImplementedError`.\n\n EXAMPLES::\n\n sage: Semigroups()._call_(3)\n Traceback (most recent call last):\n ...\n NotImplementedError\n ' raise NotImplementedError def _repr_(self): '\n Return the print representation of this category.\n\n EXAMPLES::\n\n sage: Sets() # indirect doctest\n Category of sets\n ' return 'Category of {}'.format(self._repr_object_names()) def _latex_(self): '\n Returns the latex representation of this category.\n\n EXAMPLES::\n\n sage: latex(Sets()) # indirect doctest\n \\mathbf{Sets}\n sage: latex(CommutativeAdditiveSemigroups())\n \\mathbf{CommutativeAdditiveSemigroups}\n ' return ('\\mathbf{%s}' % self._short_name()) def _subcategory_hook_(self, category): '\n Quick subcategory check.\n\n INPUT:\n\n - ``category`` -- a category\n\n OUTPUT:\n\n - ``True``, if ``category`` is a subcategory of ``self``.\n - ``False``, if ``category`` is not a subcategory of ``self``.\n - ``Unknown``, if a quick check was not enough to determine\n whether ``category`` is a subcategory of ``self`` or not.\n\n The aim of this method is to offer a framework to add cheap\n tests for subcategories. When doing\n ``category.is_subcategory(self)`` (note the reverse order of\n ``self`` and ``category``), this method is usually called\n first. Only if it returns ``Unknown``, :meth:`is_subcategory`\n will build the list of super categories of ``category``.\n\n This method need not to handle the case where ``category`` is\n ``self``; this is the first test that is done in\n :meth:`is_subcategory`.\n\n This default implementation tests whether the parent class of\n ``category`` is a subclass of the parent class of ``self``.\n This is most of the time a complete subcategory test.\n\n .. WARNING::\n\n This test is incomplete for categories in\n :class:`CategoryWithParameters`, as introduced by\n :trac:`11935`. This method is therefore overwritten by\n :meth:`~sage.categories.category.CategoryWithParameters._subcategory_hook_`.\n\n EXAMPLES::\n\n sage: Rings()._subcategory_hook_(Rings())\n True\n ' return issubclass(category.parent_class, self.parent_class) def __contains__(self, x): '\n Membership testing\n\n Returns whether ``x`` is an object in this category, that is\n if the category of ``x`` is a subcategory of ``self``.\n\n EXAMPLES::\n\n sage: ZZ in Sets()\n True\n ' try: c = x.category() except AttributeError: return False return c.is_subcategory(self) @staticmethod def __classcontains__(cls, x): '\n Membership testing, without arguments\n\n INPUT:\n\n - ``cls`` -- a category class\n - ``x`` -- any object\n\n Returns whether ``x`` is an object of a category which is an instance\n of ``cls``.\n\n EXAMPLES:\n\n This method makes it easy to test if an object is, say, a\n vector space, without having to specify the base ring::\n\n sage: F = FreeModule(QQ, 3) # needs sage.modules\n sage: F in VectorSpaces # needs sage.modules\n True\n\n sage: F = FreeModule(ZZ, 3) # needs sage.modules\n sage: F in VectorSpaces # needs sage.modules\n False\n\n sage: F in Algebras # needs sage.modules\n False\n\n TESTS:\n\n Non category objects shall be handled properly::\n\n sage: [1,2] in Algebras\n False\n ' try: c = x.categories() except AttributeError: return False return any((isinstance(cat, cls) for cat in c)) def is_abelian(self): '\n Return whether this category is abelian.\n\n An abelian category is a category satisfying:\n\n - It has a zero object;\n - It has all pullbacks and pushouts;\n - All monomorphisms and epimorphisms are normal.\n\n Equivalently, one can define an increasing sequence of conditions:\n\n - A category is pre-additive if it is enriched over abelian groups\n (all homsets are abelian groups and composition is bilinear);\n - A pre-additive category is additive if every finite set of objects\n has a biproduct (we can form direct sums and direct products);\n - An additive category is pre-abelian if every morphism has both a\n kernel and a cokernel;\n - A pre-abelian category is abelian if every monomorphism is the\n kernel of some morphism and every epimorphism is the cokernel of\n some morphism.\n\n EXAMPLES::\n\n sage: Modules(ZZ).is_abelian()\n True\n sage: FreeModules(ZZ).is_abelian()\n False\n sage: FreeModules(QQ).is_abelian()\n True\n sage: CommutativeAdditiveGroups().is_abelian()\n True\n sage: Semigroups().is_abelian()\n Traceback (most recent call last):\n ...\n NotImplementedError: is_abelian\n ' raise NotImplementedError('is_abelian') def category_graph(self): '\n Returns the graph of all super categories of this category\n\n EXAMPLES::\n\n sage: C = Algebras(QQ)\n sage: G = C.category_graph() # needs sage.graphs\n sage: G.is_directed_acyclic() # needs sage.graphs\n True\n\n The girth of a directed acyclic graph is infinite, however,\n the girth of the underlying undirected graph is 4 in this case::\n\n sage: Graph(G).girth() # needs sage.graphs\n 4\n ' return category_graph([self]) @abstract_method def super_categories(self): '\n Return the *immediate* super categories of ``self``.\n\n OUTPUT:\n\n - a duplicate-free list of categories.\n\n Every category should implement this method.\n\n EXAMPLES::\n\n sage: Groups().super_categories()\n [Category of monoids, Category of inverse unital magmas]\n sage: Objects().super_categories()\n []\n\n .. NOTE::\n\n Since :trac:`10963`, the order of the categories in the\n result is irrelevant. For details, see\n :ref:`category-primer-category-order`.\n\n .. NOTE::\n\n Whenever speed matters, developers are advised to use the\n lazy attribute :meth:`_super_categories` instead of\n calling this method.\n ' @lazy_attribute def _all_super_categories(self): "\n All the super categories of this category, including this category.\n\n Since :trac:`11943`, the order of super categories is\n determined by Python's method resolution order C3 algorithm.\n\n .. SEEALSO:: :meth:`all_super_categories`\n\n .. note:: this attribute is likely to eventually become a tuple.\n\n .. note:: this sets :meth:`_super_categories_for_classes` as a side effect\n\n EXAMPLES::\n\n sage: C = Rings(); C\n Category of rings\n sage: C._all_super_categories\n [Category of rings, Category of rngs, Category of semirings, ...\n Category of monoids, ...\n Category of commutative additive groups, ...\n Category of sets, Category of sets with partial maps,\n Category of objects]\n " (result, bases) = C3_sorted_merge(([cat._all_super_categories for cat in self._super_categories] + [self._super_categories]), category_sort_key) if (not (sorted(result, key=category_sort_key, reverse=True) == result)): warn('Inconsistent sorting results for all super categories of {}'.format(self.__class__)) self._super_categories_for_classes = bases return ([self] + result) @lazy_attribute def _all_super_categories_proper(self): "\n All the proper super categories of this category.\n\n Since :trac:`11943`, the order of super categories is\n determined by Python's method resolution order C3 algorithm.\n\n .. SEEALSO:: :meth:`all_super_categories`\n\n .. note:: this attribute is likely to eventually become a tuple.\n\n EXAMPLES::\n\n sage: C = Rings(); C\n Category of rings\n sage: C._all_super_categories_proper\n [Category of rngs, Category of semirings, ...\n Category of monoids, ...\n Category of commutative additive groups, ...\n Category of sets, Category of sets with partial maps,\n Category of objects]\n " return self._all_super_categories[1:] @lazy_attribute def _set_of_super_categories(self): '\n The frozen set of all proper super categories of this category.\n\n .. note:: this is used for speeding up category containment tests.\n\n .. SEEALSO:: :meth:`all_super_categories`\n\n EXAMPLES::\n\n sage: sorted(Groups()._set_of_super_categories, key=str)\n [Category of inverse unital magmas,\n Category of magmas,\n Category of monoids,\n Category of objects,\n Category of semigroups,\n Category of sets,\n Category of sets with partial maps,\n Category of unital magmas]\n sage: sorted(Groups()._set_of_super_categories, key=str)\n [Category of inverse unital magmas, Category of magmas, Category of monoids,\n Category of objects, Category of semigroups, Category of sets,\n Category of sets with partial maps, Category of unital magmas]\n\n TESTS::\n\n sage: C = HopfAlgebrasWithBasis(GF(7))\n sage: C._set_of_super_categories == set(C._all_super_categories_proper)\n True\n ' return frozenset(self._all_super_categories_proper) def all_super_categories(self, proper=False): "\n Returns the list of all super categories of this category.\n\n INPUT:\n\n - ``proper`` -- a boolean (default: ``False``); whether to exclude this category.\n\n Since :trac:`11943`, the order of super categories is\n determined by Python's method resolution order C3 algorithm.\n\n .. note::\n\n Whenever speed matters, the developers are advised to use\n instead the lazy attributes :meth:`_all_super_categories`,\n :meth:`_all_super_categories_proper`, or\n :meth:`_set_of_super_categories`, as\n appropriate. Simply because lazy attributes are much\n faster than any method.\n\n EXAMPLES::\n\n sage: C = Rings(); C\n Category of rings\n sage: C.all_super_categories()\n [Category of rings, Category of rngs, Category of semirings, ...\n Category of monoids, ...\n Category of commutative additive groups, ...\n Category of sets, Category of sets with partial maps,\n Category of objects]\n\n sage: C.all_super_categories(proper = True)\n [Category of rngs, Category of semirings, ...\n Category of monoids, ...\n Category of commutative additive groups, ...\n Category of sets, Category of sets with partial maps,\n Category of objects]\n\n sage: Sets().all_super_categories()\n [Category of sets, Category of sets with partial maps, Category of objects]\n sage: Sets().all_super_categories(proper=True)\n [Category of sets with partial maps, Category of objects]\n sage: Sets().all_super_categories() is Sets()._all_super_categories\n True\n sage: Sets().all_super_categories(proper=True) is Sets()._all_super_categories_proper\n True\n\n " if proper: return self._all_super_categories_proper return self._all_super_categories @lazy_attribute def _super_categories(self): '\n The immediate super categories of this category.\n\n This lazy attribute caches the result of the mandatory method\n :meth:`super_categories` for speed. It also does some mangling\n (flattening join categories, sorting, ...).\n\n Whenever speed matters, developers are advised to use this\n lazy attribute rather than calling :meth:`super_categories`.\n\n .. NOTE::\n\n This attribute is likely to eventually become a tuple.\n When this happens, we might as well use :meth:`Category._sort`,\n if not :meth:`Category._sort_uniq`.\n\n EXAMPLES::\n\n sage: Rings()._super_categories\n [Category of rngs, Category of semirings]\n ' return sorted(_flatten_categories(self.super_categories(), JoinCategory), key=category_sort_key, reverse=True) @lazy_attribute def _super_categories_for_classes(self): '\n The super categories of this category used for building classes.\n\n This is a close variant of :meth:`_super_categories` used for\n constructing the list of the bases for :meth:`parent_class`,\n :meth:`element_class`, and friends. The purpose is ensure that\n Python will find a proper Method Resolution Order for those\n classes. For background, see :mod:`sage.misc.c3_controlled`.\n\n .. SEEALSO:: :meth:`_cmp_key`.\n\n .. NOTE::\n\n This attribute is calculated as a by-product of computing\n :meth:`_all_super_categories`.\n\n EXAMPLES::\n\n sage: Rings()._super_categories_for_classes\n [Category of rngs, Category of semirings]\n ' self._all_super_categories return self._super_categories_for_classes def additional_structure(self): "\n Return whether ``self`` defines additional structure.\n\n OUTPUT:\n\n - ``self`` if ``self`` defines additional structure and\n ``None`` otherwise. This default implementation returns\n ``self``.\n\n A category `C` *defines additional structure* if `C`-morphisms\n shall preserve more structure (e.g. operations) than that\n specified by the super categories of `C`. For example, the\n category of magmas defines additional structure, namely the\n operation `*` that shall be preserved by magma morphisms. On\n the other hand the category of rings does not define additional\n structure: a function between two rings that is both a unital\n magma morphism and a unital additive magma morphism is\n automatically a ring morphism.\n\n Formally speaking `C` *defines additional structure*, if `C`\n is *not* a full subcategory of the join of its super\n categories: the morphisms need to preserve more structure, and\n thus the homsets are smaller.\n\n By default, a category is considered as defining additional\n structure, unless it is a :ref:`category with axiom\n <category-primer-axioms>`.\n\n EXAMPLES:\n\n Here are some typical structure categories, with the\n additional structure they define::\n\n sage: Sets().additional_structure()\n Category of sets\n sage: Magmas().additional_structure() # `*`\n Category of magmas\n sage: AdditiveMagmas().additional_structure() # `+`\n Category of additive magmas\n sage: LeftModules(ZZ).additional_structure() # left multiplication by scalar\n Category of left modules over Integer Ring\n sage: Coalgebras(QQ).additional_structure() # coproduct\n Category of coalgebras over Rational Field\n sage: Crystals().additional_structure() # crystal operators\n Category of crystals\n\n On the other hand, the category of semigroups is not a\n structure category, since its operation `+` is already defined\n by the category of magmas::\n\n sage: Semigroups().additional_structure()\n\n Most :ref:`categories with axiom <category-primer-axioms>`\n don't define additional structure::\n\n sage: Sets().Finite().additional_structure()\n sage: Rings().Commutative().additional_structure()\n sage: Modules(QQ).FiniteDimensional().additional_structure()\n sage: from sage.categories.magmatic_algebras import MagmaticAlgebras\n sage: MagmaticAlgebras(QQ).Unital().additional_structure()\n\n As of Sage 6.4, the only exceptions are the category of unital\n magmas or the category of unital additive magmas (both define\n a unit which shall be preserved by morphisms)::\n\n sage: Magmas().Unital().additional_structure()\n Category of unital magmas\n sage: AdditiveMagmas().AdditiveUnital().additional_structure()\n Category of additive unital additive magmas\n\n Similarly, :ref:`functorial construction categories\n <category-primer-functorial-constructions>` don't define\n additional structure, unless the construction is actually\n defined by their base category. For example, the category of\n graded modules defines a grading which shall be preserved by\n morphisms::\n\n sage: Modules(ZZ).Graded().additional_structure()\n Category of graded modules over Integer Ring\n\n On the other hand, the category of graded algebras does not\n define additional structure; indeed an algebra morphism which\n is also a module morphism is a graded algebra morphism::\n\n sage: Algebras(ZZ).Graded().additional_structure()\n\n Similarly, morphisms are requested to preserve the structure\n given by the following constructions::\n\n sage: Sets().Quotients().additional_structure()\n Category of quotients of sets\n sage: Sets().CartesianProducts().additional_structure()\n Category of Cartesian products of sets\n sage: Modules(QQ).TensorProducts().additional_structure()\n\n This might change, as we are lacking enough data points to\n guarantee that this was the correct design decision.\n\n .. NOTE::\n\n In some cases a category defines additional structure,\n where the structure can be useful to manipulate morphisms\n but where, in most use cases, we don't want the morphisms\n to necessarily preserve it. For example, in the context of\n finite dimensional vector spaces, having a distinguished\n basis allows for representing morphisms by matrices; yet\n considering only morphisms that preserve that\n distinguished basis would be boring.\n\n In such cases, we might want to eventually have two\n categories, one where the additional structure is\n preserved, and one where it's not necessarily preserved\n (we would need to find an idiom for this).\n\n At this point, a choice is to be made each time, according\n to the main use cases. Some of those choices are yet to be\n settled. For example, should by default:\n\n - an euclidean domain morphism preserve euclidean\n division? ::\n\n sage: EuclideanDomains().additional_structure()\n Category of euclidean domains\n\n - an enumerated set morphism preserve the distinguished\n enumeration? ::\n\n sage: EnumeratedSets().additional_structure()\n\n - a module with basis morphism preserve the distinguished\n basis? ::\n\n sage: Modules(QQ).WithBasis().additional_structure()\n\n .. SEEALSO::\n\n This method together with the methods overloading it\n provide the basic data to determine, for a given category,\n the super categories that define some structure (see\n :meth:`structure`), and to test whether a category is a\n full subcategory of some other category (see\n :meth:`is_full_subcategory`). For example, the category of\n Coxeter groups is not full subcategory of the category of\n groups since morphisms need to preserve the distinguished\n generators::\n\n sage: CoxeterGroups().is_full_subcategory(Groups())\n False\n\n The support for modeling full subcategories has been\n introduced in :trac:`16340`.\n " return self @cached_method def structure(self): '\n Return the structure ``self`` is endowed with.\n\n This method returns the structure that morphisms in this\n category shall be preserving. For example, it tells that a\n ring is a set endowed with a structure of both a unital magma\n and an additive unital magma which satisfies some further\n axioms. In other words, a ring morphism is a function that\n preserves the unital magma and additive unital magma\n structure.\n\n In practice, this returns the collection of all the super\n categories of ``self`` that define some additional structure,\n as a frozen set.\n\n EXAMPLES::\n\n sage: Objects().structure()\n frozenset()\n\n sage: def structure(C):\n ....: return Category._sort(C.structure())\n\n sage: structure(Sets())\n (Category of sets, Category of sets with partial maps)\n sage: structure(Magmas())\n (Category of magmas, Category of sets, Category of sets with partial maps)\n\n In the following example, we only list the smallest structure\n categories to get a more readable output::\n\n sage: def structure(C):\n ....: return Category._sort_uniq(C.structure())\n\n sage: structure(Magmas())\n (Category of magmas,)\n sage: structure(Rings())\n (Category of unital magmas, Category of additive unital additive magmas)\n sage: structure(Fields())\n (Category of euclidean domains,)\n sage: structure(Algebras(QQ))\n (Category of unital magmas,\n Category of right modules over Rational Field,\n Category of left modules over Rational Field)\n sage: structure(HopfAlgebras(QQ).Graded().WithBasis().Connected())\n (Category of Hopf algebras over Rational Field,\n Category of graded modules over Rational Field)\n\n This method is used in :meth:`is_full_subcategory` for\n deciding whether a category is a full subcategory of some\n other category, and for documentation purposes. It is computed\n recursively from the result of :meth:`additional_structure`\n on the super categories of ``self``.\n ' result = {D for C in self.super_categories() for D in C.structure()} if (self.additional_structure() is not None): result.add(self) return frozenset(result) def is_full_subcategory(self, other): '\n Return whether ``self`` is a full subcategory of ``other``.\n\n A subcategory `B` of a category `A` is a *full subcategory* if\n any `A`-morphism between two objects of `B` is also a\n `B`-morphism (the reciprocal always holds: any `B`-morphism\n between two objects of `B` is an `A`-morphism).\n\n This is computed by testing whether ``self`` is a subcategory\n of ``other`` and whether they have the same structure, as\n determined by :meth:`structure` from the\n result of :meth:`additional_structure` on the super\n categories.\n\n .. WARNING::\n\n A positive answer is guaranteed to be mathematically\n correct. A negative answer may mean that Sage has not been\n taught enough information (or can not yet within the\n current model) to derive this information. See\n :meth:`full_super_categories` for a discussion.\n\n .. SEEALSO::\n\n - :meth:`is_subcategory`\n - :meth:`full_super_categories`\n\n EXAMPLES::\n\n sage: Magmas().Associative().is_full_subcategory(Magmas())\n True\n sage: Magmas().Unital().is_full_subcategory(Magmas())\n False\n sage: Rings().is_full_subcategory(Magmas().Unital() & AdditiveMagmas().AdditiveUnital())\n True\n\n Here are two typical examples of false negatives::\n\n sage: Groups().is_full_subcategory(Semigroups())\n False\n sage: Groups().is_full_subcategory(Semigroups()) # todo: not implemented\n True\n sage: Fields().is_full_subcategory(Rings())\n False\n sage: Fields().is_full_subcategory(Rings()) # todo: not implemented\n True\n\n .. TODO::\n\n The latter is a consequence of :class:`EuclideanDomains`\n currently being a structure category. Is this what we\n want? ::\n\n sage: EuclideanDomains().is_full_subcategory(Rings())\n False\n ' return (self.is_subcategory(other) and (len(self.structure()) == len(other.structure()))) @cached_method def full_super_categories(self): '\n Return the *immediate* full super categories of ``self``.\n\n .. SEEALSO::\n\n - :meth:`super_categories`\n - :meth:`is_full_subcategory`\n\n .. WARNING::\n\n The current implementation selects the full subcategories\n among the immediate super categories of ``self``. This\n assumes that, if `C\\subset B\\subset A` is a chain of\n categories and `C` is a full subcategory of `A`, then `C`\n is a full subcategory of `B` and `B` is a full subcategory\n of `A`.\n\n This assumption is guaranteed to hold with the current\n model and implementation of full subcategories in\n Sage. However, mathematically speaking, this is too\n restrictive. This indeed prevents the complete modelling\n of situations where any `A` morphism between elements of\n `C` automatically preserves the `B` structure. See below\n for an example.\n\n EXAMPLES:\n\n A semigroup morphism between two finite semigroups is a finite\n semigroup morphism::\n\n sage: Semigroups().Finite().full_super_categories()\n [Category of semigroups]\n\n On the other hand, a semigroup morphism between two monoids is\n not necessarily a monoid morphism (which must map the unit to\n the unit)::\n\n sage: Monoids().super_categories()\n [Category of semigroups, Category of unital magmas]\n sage: Monoids().full_super_categories()\n [Category of unital magmas]\n\n Any semigroup morphism between two groups is automatically a\n monoid morphism (in a group the unit is the unique idempotent,\n so it has to be mapped to the unit). Yet, due to the\n limitation of the model advertised above, Sage currently cannot\n be taught that the category of groups is a full subcategory of\n the category of semigroups::\n\n sage: Groups().full_super_categories() # todo: not implemented\n [Category of monoids, Category of semigroups, Category of inverse unital magmas]\n sage: Groups().full_super_categories()\n [Category of monoids, Category of inverse unital magmas]\n ' return [C for C in self.super_categories() if self.is_full_subcategory(C)] def _test_category_graph(self, **options): "\n Check that the category graph matches with Python's method resolution order\n\n .. note::\n\n By :trac:`11943`, the list of categories returned by\n :meth:`all_super_categories` is supposed to match with the\n method resolution order of the parent and element\n classes. This method checks this.\n\n .. TODO:: currently, this won't work for hom categories.\n\n EXAMPLES::\n\n sage: C = HopfAlgebrasWithBasis(QQ)\n sage: C.parent_class.mro() == [X.parent_class for X in C._all_super_categories] + [object]\n True\n sage: C.element_class.mro() == [X.element_class for X in C._all_super_categories] + [object]\n True\n sage: TestSuite(C).run() # indirect doctest\n\n " tester = self._tester(**options) tester.assertEqual(self.parent_class.mro(), ([C.parent_class for C in self._all_super_categories] + [object])) tester.assertEqual(self.element_class.mro(), ([C.element_class for C in self._all_super_categories] + [object])) def _test_category(self, **options): '\n Run generic tests on this category\n\n .. SEEALSO:: :class:`TestSuite`.\n\n EXAMPLES::\n\n sage: Sets()._test_category()\n\n Let us now write a couple broken categories::\n\n sage: class MyObjects(Category):\n ....: pass\n sage: MyObjects()._test_category()\n Traceback (most recent call last):\n ...\n NotImplementedError: <abstract method super_categories at ...>\n\n sage: class MyObjects(Category):\n ....: def super_categories(self):\n ....: return tuple()\n sage: MyObjects()._test_category()\n Traceback (most recent call last):\n ...\n AssertionError: Category of my objects.super_categories() should return a list\n\n sage: class MyObjects(Category):\n ....: def super_categories(self):\n ....: return []\n sage: MyObjects()._test_category()\n Traceback (most recent call last):\n ...\n AssertionError: Category of my objects is not a subcategory of Objects()\n ' from sage.categories.objects import Objects from sage.categories.sets_cat import Sets tester = self._tester(**options) tester.assertTrue(isinstance(self.super_categories(), list), ('%s.super_categories() should return a list' % self)) tester.assertTrue(self.is_subcategory(Objects()), ('%s is not a subcategory of Objects()' % self)) tester.assertTrue(isinstance(self.parent_class, type)) tester.assertTrue(all(((not isinstance(cat, JoinCategory)) for cat in self._super_categories))) if (not isinstance(self, JoinCategory)): tester.assertTrue(all(((self._cmp_key > cat._cmp_key) for cat in self._super_categories))) tester.assertTrue(self.is_subcategory(Category.join(self.super_categories()))) for category in self._all_super_categories_proper: if self.is_full_subcategory(category): tester.assertTrue(any((cat.is_subcategory(category) for cat in self.full_super_categories())), 'Every full super category should be a super categoryof some immediate full super category') if self.is_subcategory(Sets()): tester.assertTrue(isinstance(self.parent_class, type)) tester.assertTrue(isinstance(self.element_class, type)) _cmp_key = _cmp_key def _make_named_class(self, name, method_provider, cache=False, picklable=True): '\n Construction of the parent/element/... class of ``self``.\n\n INPUT:\n\n - ``name`` -- a string; the name of the class as an attribute of\n ``self``. E.g. "parent_class"\n - ``method_provider`` -- a string; the name of an attribute of\n ``self`` that provides methods for the new class (in\n addition to those coming from the super categories).\n E.g. "ParentMethods"\n - ``cache`` -- a boolean or ``ignore_reduction`` (default: ``False``)\n (passed down to dynamic_class; for internal use only)\n - ``picklable`` -- a boolean (default: ``True``)\n\n ASSUMPTION:\n\n It is assumed that this method is only called from a lazy\n attribute whose name coincides with the given ``name``.\n\n OUTPUT:\n\n A dynamic class with bases given by the corresponding named\n classes of ``self``\'s super_categories, and methods taken from\n the class ``getattr(self,method_provider)``.\n\n .. NOTE::\n\n - In this default implementation, the reduction data of\n the named class makes it depend on ``self``. Since the\n result is going to be stored in a lazy attribute of\n ``self`` anyway, we may as well disable the caching in\n ``dynamic_class`` (hence the default value\n ``cache=False``).\n\n - :class:`CategoryWithParameters` overrides this method so\n that the same parent/element/... classes can be shared\n between closely related categories.\n\n - The bases of the named class may also contain the named\n classes of some indirect super categories, according to\n :meth:`_super_categories_for_classes`. This is to\n guarantee that Python will build consistent method\n resolution orders. For background, see\n :mod:`sage.misc.c3_controlled`.\n\n .. SEEALSO:: :meth:`CategoryWithParameters._make_named_class`\n\n EXAMPLES::\n\n sage: PC = Rings()._make_named_class("parent_class", "ParentMethods"); PC\n <class \'sage.categories.rings.Rings.parent_class\'>\n sage: type(PC)\n <class \'sage.structure.dynamic_class.DynamicMetaclass\'>\n sage: PC.__bases__\n (<class \'sage.categories.rngs.Rngs.parent_class\'>,\n <class \'sage.categories.semirings.Semirings.parent_class\'>)\n\n Note that, by default, the result is not cached::\n\n sage: PC is Rings()._make_named_class("parent_class", "ParentMethods")\n False\n\n Indeed this method is only meant to construct lazy attributes\n like ``parent_class`` which already handle this caching::\n\n sage: Rings().parent_class\n <class \'sage.categories.rings.Rings.parent_class\'>\n\n Reduction for pickling also assumes the existence of this lazy\n attribute::\n\n sage: PC._reduction\n (<built-in function getattr>, (Category of rings, \'parent_class\'))\n sage: loads(dumps(PC)) is Rings().parent_class\n True\n\n TESTS::\n\n sage: class A: pass\n sage: class BrokenCategory(Category):\n ....: def super_categories(self): return []\n ....: ParentMethods = 1\n ....: class ElementMethods(A):\n ....: pass\n ....: class MorphismMethods():\n ....: pass\n sage: C = BrokenCategory()\n sage: C._make_named_class("parent_class", "ParentMethods")\n Traceback (most recent call last):\n ...\n AssertionError: BrokenCategory.ParentMethods should be a class\n sage: C._make_named_class("element_class", "ElementMethods")\n doctest:...: UserWarning: BrokenCategory.ElementMethods should not have a super class\n <class \'__main__.BrokenCategory.element_class\'>\n sage: C._make_named_class("morphism_class", "MorphismMethods")\n <class \'__main__.BrokenCategory.morphism_class\'>\n ' cls = self.__class__ if isinstance(cls, DynamicMetaclass): cls = cls.__base__ class_name = ('%s.%s' % (cls.__name__, name)) method_provider_cls = getattr(self, method_provider, None) if (method_provider_cls is None): doccls = cls else: assert inspect.isclass(method_provider_cls), ('%s.%s should be a class' % (cls.__name__, method_provider)) mro = inspect.getmro(method_provider_cls) if ((len(mro) > 2) or ((len(mro) == 2) and (mro[1] is not object))): warn(('%s.%s should not have a super class' % (cls.__name__, method_provider))) doccls = method_provider_cls if picklable: reduction = (getattr, (self, name)) else: reduction = None return dynamic_class(class_name, tuple((getattr(cat, name) for cat in self._super_categories_for_classes)), method_provider_cls, prepend_cls_bases=False, doccls=doccls, reduction=reduction, cache=cache) @lazy_attribute def subcategory_class(self): "\n A common superclass for all subcategories of this category (including this one).\n\n This class derives from ``D.subcategory_class`` for each super\n category `D` of ``self``, and includes all the methods from\n the nested class ``self.SubcategoryMethods``, if it exists.\n\n .. SEEALSO::\n\n - :trac:`12895`\n - :meth:`parent_class`\n - :meth:`element_class`\n - :meth:`_make_named_class`\n\n EXAMPLES::\n\n sage: cls = Rings().subcategory_class; cls\n <class 'sage.categories.rings.Rings.subcategory_class'>\n sage: type(cls)\n <class 'sage.structure.dynamic_class.DynamicMetaclass'>\n\n ``Rings()`` is an instance of this class, as well as all its subcategories::\n\n sage: isinstance(Rings(), cls)\n True\n sage: isinstance(AlgebrasWithBasis(QQ), cls)\n True\n\n TESTS::\n\n sage: cls = Algebras(QQ).subcategory_class; cls\n <class 'sage.categories.algebras.Algebras.subcategory_class'>\n sage: type(cls)\n <class 'sage.structure.dynamic_class.DynamicMetaclass'>\n\n " return self._make_named_class('subcategory_class', 'SubcategoryMethods', cache=False, picklable=False) @lazy_attribute def parent_class(self): "\n A common super class for all parents in this category (and its\n subcategories).\n\n This class contains the methods defined in the nested class\n ``self.ParentMethods`` (if it exists), and has as bases the\n parent classes of the super categories of ``self``.\n\n .. SEEALSO::\n\n - :meth:`element_class`, :meth:`morphism_class`\n - :class:`Category` for details\n\n EXAMPLES::\n\n sage: C = Algebras(QQ).parent_class; C\n <class 'sage.categories.algebras.Algebras.parent_class'>\n sage: type(C)\n <class 'sage.structure.dynamic_class.DynamicMetaclass'>\n\n By :trac:`11935`, some categories share their parent\n classes. For example, the parent class of an algebra only\n depends on the category of the base ring. A typical example is\n the category of algebras over a finite field versus algebras\n over a non-field::\n\n sage: Algebras(GF(7)).parent_class is Algebras(GF(5)).parent_class\n True\n sage: Algebras(QQ).parent_class is Algebras(ZZ).parent_class\n False\n sage: Algebras(ZZ['t']).parent_class is Algebras(ZZ['t','x']).parent_class\n True\n\n See :class:`CategoryWithParameters` for an abstract base class for\n categories that depend on parameters, even though the parent\n and element classes only depend on the parent or element\n classes of its super categories. It is used in\n :class:`~sage.categories.bimodules.Bimodules`,\n :class:`~sage.categories.category_types.Category_over_base` and\n :class:`sage.categories.category.JoinCategory`.\n " return self._make_named_class('parent_class', 'ParentMethods') @lazy_attribute def element_class(self): "\n A common super class for all elements of parents in this category\n (and its subcategories).\n\n This class contains the methods defined in the nested class\n ``self.ElementMethods`` (if it exists), and has as bases the\n element classes of the super categories of ``self``.\n\n .. SEEALSO::\n\n - :meth:`parent_class`, :meth:`morphism_class`\n - :class:`Category` for details\n\n EXAMPLES::\n\n sage: C = Algebras(QQ).element_class; C\n <class 'sage.categories.algebras.Algebras.element_class'>\n sage: type(C)\n <class 'sage.structure.dynamic_class.DynamicMetaclass'>\n\n By :trac:`11935`, some categories share their element\n classes. For example, the element class of an algebra only\n depends on the category of the base. A typical example is the\n category of algebras over a field versus algebras over a\n non-field::\n\n sage: Algebras(GF(5)).element_class is Algebras(GF(3)).element_class\n True\n sage: Algebras(QQ).element_class is Algebras(ZZ).element_class\n False\n sage: Algebras(ZZ['t']).element_class is Algebras(ZZ['t','x']).element_class\n True\n\n These classes are constructed with ``__slots__ = ()``, so\n instances may not have a ``__dict__``::\n\n sage: E = FiniteEnumeratedSets().element_class\n sage: E.__dictoffset__\n 0\n\n .. SEEALSO:: :meth:`parent_class`\n " return self._make_named_class('element_class', 'ElementMethods') @lazy_attribute def morphism_class(self): "\n A common super class for all morphisms between parents in this\n category (and its subcategories).\n\n This class contains the methods defined in the nested class\n ``self.MorphismMethods`` (if it exists), and has as bases the\n morphism classes of the super categories of ``self``.\n\n .. SEEALSO::\n\n - :meth:`parent_class`, :meth:`element_class`\n - :class:`Category` for details\n\n EXAMPLES::\n\n sage: C = Algebras(QQ).morphism_class; C\n <class 'sage.categories.algebras.Algebras.morphism_class'>\n sage: type(C)\n <class 'sage.structure.dynamic_class.DynamicMetaclass'>\n " return self._make_named_class('morphism_class', 'MorphismMethods') def required_methods(self): "\n Returns the methods that are required and optional for parents\n in this category and their elements.\n\n EXAMPLES::\n\n sage: Algebras(QQ).required_methods()\n {'element': {'optional': ['_add_', '_mul_'], 'required': ['__bool__']},\n 'parent': {'optional': ['algebra_generators'], 'required': ['__contains__']}}\n " return {'parent': abstract_methods_of_class(self.parent_class), 'element': abstract_methods_of_class(self.element_class)} def is_subcategory(self, c): "\n Returns True if self is naturally embedded as a subcategory of c.\n\n EXAMPLES::\n\n sage: AbGrps = CommutativeAdditiveGroups()\n sage: Rings().is_subcategory(AbGrps)\n True\n sage: AbGrps.is_subcategory(Rings())\n False\n\n The ``is_subcategory`` function takes into account the\n base.\n\n ::\n\n sage: M3 = VectorSpaces(FiniteField(3))\n sage: M9 = VectorSpaces(FiniteField(9, 'a')) # needs sage.rings.finite_rings\n sage: M3.is_subcategory(M9) # needs sage.rings.finite_rings\n False\n\n Join categories are properly handled::\n\n sage: CatJ = Category.join((CommutativeAdditiveGroups(), Semigroups()))\n sage: Rings().is_subcategory(CatJ)\n True\n\n ::\n\n sage: V3 = VectorSpaces(FiniteField(3))\n sage: POSet = PartiallyOrderedSets()\n sage: PoV3 = Category.join((V3, POSet))\n sage: A3 = AlgebrasWithBasis(FiniteField(3))\n sage: PoA3 = Category.join((A3, POSet))\n sage: PoA3.is_subcategory(PoV3)\n True\n sage: PoV3.is_subcategory(PoV3)\n True\n sage: PoV3.is_subcategory(PoA3)\n False\n " if (c is self): return True subcat_hook = c._subcategory_hook_(self) if (subcat_hook is Unknown): return (c in self._set_of_super_categories) return subcat_hook def or_subcategory(self, category=None, join=False): '\n Return ``category`` or ``self`` if ``category`` is ``None``.\n\n INPUT:\n\n - ``category`` -- a sub category of ``self``, tuple/list thereof,\n or ``None``\n - ``join`` -- a boolean (default: ``False``)\n\n OUTPUT:\n\n - a category\n\n EXAMPLES::\n\n sage: Monoids().or_subcategory(Groups())\n Category of groups\n sage: Monoids().or_subcategory(None)\n Category of monoids\n\n If category is a list/tuple, then a join category is returned::\n\n sage: Monoids().or_subcategory((CommutativeAdditiveMonoids(), Groups()))\n Join of Category of groups and Category of commutative additive monoids\n\n If ``join`` is ``False``, an error if raised if category is not a\n subcategory of ``self``::\n\n sage: Monoids().or_subcategory(EnumeratedSets())\n Traceback (most recent call last):\n ...\n ValueError: Subcategory of `Category of monoids` required;\n got `Category of enumerated sets`\n\n Otherwise, the two categories are joined together::\n\n sage: Monoids().or_subcategory(EnumeratedSets(), join=True)\n Category of enumerated monoids\n ' if (category is None): return self if isinstance(category, (tuple, list)): category = Category.join(category) assert isinstance(category, Category) if join: return Category.join([self, category]) else: if (not category.is_subcategory(self)): raise ValueError('Subcategory of `{}` required; got `{}`'.format(self, category)) return category def _is_subclass(self, c): '\n Same as is_subcategory, but c may also be the class of a\n category instead of a category.\n\n EXAMPLES::\n\n sage: Fields()._is_subclass(Rings)\n True\n sage: Algebras(QQ)._is_subclass(Modules)\n True\n sage: Algebras(QQ)._is_subclass(ModulesWithBasis)\n False\n ' assert (isinstance(c, Category) or (issubclass(c.__class__, type) and issubclass(c, Category))) if isinstance(c, Category): return self.is_subcategory(c) return any((isinstance(cat, c) for cat in self._all_super_categories)) @cached_method def _meet_(self, other): '\n Returns the largest common subcategory of self and other:\n\n EXAMPLES::\n\n sage: Monoids()._meet_(Monoids())\n Category of monoids\n sage: Rings()._meet_(Rings())\n Category of rings\n sage: Rings()._meet_(Monoids())\n Category of monoids\n sage: Monoids()._meet_(Rings())\n Category of monoids\n\n sage: VectorSpaces(QQ)._meet_(Modules(ZZ))\n Category of commutative additive groups\n sage: Algebras(ZZ)._meet_(Algebras(QQ))\n Category of rings\n sage: Groups()._meet_(Rings())\n Category of monoids\n sage: Algebras(QQ)._meet_(Category.join([Fields(), ModulesWithBasis(QQ)]))\n Join of Category of rings and Category of vector spaces over Rational Field\n\n Note: abstractly, the category poset is a distributive\n lattice, so this is well defined; however, the subset of those\n categories actually implemented is not: we need to also\n include their join-categories.\n\n For example, the category of rings is *not* the join of the\n category of abelian groups and that of semi groups, just a\n subcategory of their join, since rings further require\n distributivity.\n\n For the meet computation, there may be several lowest common\n sub categories of self and other, in which case, we need to\n take the join of them all.\n\n FIXME:\n\n - If A is a subcategory of B, A has *more* structure than B,\n but then *less* objects in there. We should choose an\n appropriate convention for A<B. Using subcategory calls\n for A<B, but the current meet and join call for A>B.\n ' if (self is other): return self elif self.is_subcategory(other): return other elif other.is_subcategory(self): return self else: return Category.join((self._meet_(sup) for sup in other._super_categories)) @staticmethod def meet(categories): '\n Returns the meet of a list of categories\n\n INPUT:\n\n - ``categories`` - a non empty list (or iterable) of categories\n\n .. SEEALSO:: :meth:`__or__` for a shortcut\n\n EXAMPLES::\n\n sage: Category.meet([Algebras(ZZ), Algebras(QQ), Groups()])\n Category of monoids\n\n That meet of an empty list should be a category which is a\n subcategory of all categories, which does not make practical sense::\n\n sage: Category.meet([])\n Traceback (most recent call last):\n ...\n ValueError: The meet of an empty list of categories is not implemented\n ' categories = tuple(categories) if (not categories): raise ValueError('The meet of an empty list of categories is not implemented') result = categories[0] for category in categories[1:]: result = result._meet_(category) return result @cached_method def axioms(self): "\n Return the axioms known to be satisfied by all the objects of ``self``.\n\n Technically, this is the set of all the axioms ``A`` such that, if\n ``Cs`` is the category defining ``A``, then ``self`` is a subcategory\n of ``Cs().A()``. Any additional axiom ``A`` would yield a strict\n subcategory of ``self``, at the very least ``self & Cs().A()`` where\n ``Cs`` is the category defining ``A``.\n\n EXAMPLES::\n\n sage: Monoids().axioms()\n frozenset({'Associative', 'Unital'})\n sage: (EnumeratedSets().Infinite() & Sets().Facade()).axioms()\n frozenset({'Enumerated', 'Facade', 'Infinite'})\n " return frozenset((axiom for category in self._super_categories for axiom in category.axioms())) @cached_method def _with_axiom_as_tuple(self, axiom): "\n Return a tuple of categories whose join is ``self._with_axiom()``.\n\n INPUT:\n\n - ``axiom`` -- a string, the name of an axiom\n\n This is a lazy version of :meth:`_with_axiom` which is used to\n avoid recursion loops during join calculations.\n\n .. NOTE:: The order in the result is irrelevant.\n\n EXAMPLES::\n\n sage: Sets()._with_axiom_as_tuple('Finite')\n (Category of finite sets,)\n sage: Magmas()._with_axiom_as_tuple('Finite')\n (Category of magmas, Category of finite sets)\n sage: Rings().Division()._with_axiom_as_tuple('Finite')\n (Category of division rings,\n Category of finite monoids,\n Category of commutative magmas,\n Category of finite additive groups)\n sage: HopfAlgebras(QQ)._with_axiom_as_tuple('FiniteDimensional')\n (Category of Hopf algebras over Rational Field,\n Category of finite dimensional vector spaces over Rational Field)\n " if (axiom in self.axioms()): return (self,) axiom_attribute = getattr(self.__class__, axiom, None) if (axiom_attribute is None): return (self,) if (axiom in self.__class__.__base__.__dict__): from .category_with_axiom import CategoryWithAxiom if (inspect.isclass(axiom_attribute) and issubclass(axiom_attribute, CategoryWithAxiom)): return (axiom_attribute(self),) warn('Expecting {}.{} to be a subclass of CategoryWithAxiom to implement a category with axiom; got {}; ignoring'.format(self.__class__.__base__.__name__, axiom, axiom_attribute)) result = ((self,) + tuple((cat for category in self._super_categories for cat in category._with_axiom_as_tuple(axiom)))) hook = getattr(self, (axiom + '_extra_super_categories'), None) if (hook is not None): assert inspect.ismethod(hook) result += tuple(hook()) return _sort_uniq(result) @cached_method def _with_axiom(self, axiom): '\n Return the subcategory of the objects of ``self`` satisfying\n the given ``axiom``.\n\n INPUT:\n\n - ``axiom`` -- a string, the name of an axiom\n\n EXAMPLES::\n\n sage: Sets()._with_axiom("Finite")\n Category of finite sets\n\n sage: type(Magmas().Finite().Commutative())\n <class \'sage.categories.category.JoinCategory_with_category\'>\n sage: Magmas().Finite().Commutative().super_categories()\n [Category of commutative magmas, Category of finite sets]\n sage: C = Algebras(QQ).WithBasis().Commutative()\n sage: C is Algebras(QQ).Commutative().WithBasis()\n True\n\n When ``axiom`` is not defined for ``self``, ``self`` is returned::\n\n sage: Sets()._with_axiom("Associative")\n Category of sets\n\n .. WARNING:: This may be changed in the future to raising an error.\n ' return Category.join(self._with_axiom_as_tuple(axiom)) def _with_axioms(self, axioms): '\n Return the subcategory of the objects of ``self`` satisfying\n the given ``axioms``.\n\n INPUT:\n\n - ``axioms`` -- a list of strings, the names of the axioms\n\n EXAMPLES::\n\n sage: Sets()._with_axioms(["Finite"])\n Category of finite sets\n sage: Sets()._with_axioms(["Infinite"])\n Category of infinite sets\n sage: FiniteSets()._with_axioms(["Finite"])\n Category of finite sets\n\n Axioms that are not defined for the ``self`` are ignored::\n\n sage: Sets()._with_axioms(["FooBar"])\n Category of sets\n sage: Magmas()._with_axioms(["FooBar", "Unital"])\n Category of unital magmas\n\n Note that adding several axioms at once can do more than\n adding them one by one. This is because the availability of an\n axiom may depend on another axiom. For example, for\n semigroups, the ``Inverse`` axiom is meaningless unless there\n is a unit::\n\n sage: Semigroups().Inverse()\n Traceback (most recent call last):\n ...\n AttributeError: \'Semigroups_with_category\' object has no attribute \'Inverse\'...\n sage: Semigroups()._with_axioms(["Inverse"])\n Category of semigroups\n\n So one needs to first add the ``Unital`` axiom, and then the\n ``Inverse`` axiom::\n\n sage: Semigroups().Unital().Inverse()\n Category of groups\n\n or to specify all of them at once, in any order::\n\n sage: Semigroups()._with_axioms(["Inverse", "Unital"])\n Category of groups\n sage: Semigroups()._with_axioms(["Unital", "Inverse"])\n Category of groups\n\n sage: Magmas()._with_axioms([\'Commutative\', \'Associative\', \'Unital\',\'Inverse\'])\n Category of commutative groups\n sage: Magmas()._with_axioms([\'Inverse\', \'Commutative\', \'Associative\', \'Unital\'])\n Category of commutative groups\n ' axioms = frozenset(axioms) previous = None result = self while (result is not previous): previous = result for axiom in axioms: result = result._with_axiom(axiom) axioms = axioms.difference(result.axioms()) return result @cached_method def _without_axiom(self, axiom): '\n Return the category with axiom ``axiom`` removed.\n\n OUTPUT:\n\n A category ``C`` which does not have axiom ``axiom``\n and such that either ``C`` is ``self``, or adding back all the\n axioms of ``self`` gives back ``self``.\n\n .. WARNING:: This is not guaranteed to be robust.\n\n EXAMPLES::\n\n sage: Sets()._without_axiom("Facade")\n Category of sets\n sage: Sets().Facade()._without_axiom("Facade")\n Category of sets\n sage: Algebras(QQ)._without_axiom("Unital")\n Category of associative algebras over Rational Field\n sage: Groups()._without_axiom("Unital") # todo: not implemented\n Category of semigroups\n ' if (axiom not in self.axioms()): return self else: raise ValueError('Cannot remove axiom {} from {}'.format(axiom, self)) def _without_axioms(self, named=False): '\n Return the category without the axioms that have been added\n to create it.\n\n INPUT:\n\n - ``named`` -- a boolean (default: ``False``)\n\n .. TODO:: Improve this explanation.\n\n If ``named`` is ``True``, then this stops at the first\n category that has an explicit name of its own. See\n :meth:`.category_with_axiom.CategoryWithAxiom._without_axioms`\n\n EXAMPLES::\n\n sage: Sets()._without_axioms()\n Category of sets\n sage: Semigroups()._without_axioms()\n Category of magmas\n sage: Algebras(QQ).Commutative().WithBasis()._without_axioms()\n Category of magmatic algebras over Rational Field\n sage: Algebras(QQ).Commutative().WithBasis()._without_axioms(named=True)\n Category of algebras over Rational Field\n ' return self _flatten_categories = staticmethod(_flatten_categories) @staticmethod def _sort(categories): '\n Return the categories after sorting them decreasingly according\n to their comparison key.\n\n .. SEEALSO:: :meth:`_cmp_key`\n\n INPUT:\n\n - ``categories`` -- a list (or iterable) of non-join categories\n\n OUTPUT:\n\n A sorted tuple of categories, possibly with repeats.\n\n .. NOTE::\n\n The auxiliary function ``_flatten_categories`` used in the test\n below expects a second argument, which is a type such that\n instances of that type will be replaced by its super\n categories. Usually, this type is :class:`JoinCategory`.\n\n EXAMPLES::\n\n sage: Category._sort([Sets(), Objects(), Coalgebras(QQ), Monoids(), Sets().Finite()])\n (Category of monoids,\n Category of coalgebras over Rational Field,\n Category of finite sets,\n Category of sets,\n Category of objects)\n sage: Category._sort([Sets().Finite(), Semigroups().Finite(), Sets().Facade(),Magmas().Commutative()])\n (Category of finite semigroups,\n Category of commutative magmas,\n Category of finite sets,\n Category of facade sets)\n sage: Category._sort(Category._flatten_categories([Sets().Finite(), Algebras(QQ).WithBasis(), Semigroups().Finite(),\n ....: Sets().Facade(), Algebras(QQ).Commutative(), Algebras(QQ).Graded().WithBasis()],\n ....: sage.categories.category.JoinCategory))\n (Category of algebras with basis over Rational Field,\n Category of algebras with basis over Rational Field,\n Category of graded algebras over Rational Field,\n Category of commutative algebras over Rational Field,\n Category of finite semigroups,\n Category of finite sets,\n Category of facade sets)\n ' return tuple(sorted(categories, key=category_sort_key, reverse=True)) _sort_uniq = staticmethod(_sort_uniq) def __and__(self, other): '\n Return the intersection of two categories.\n\n This is just a shortcut for :meth:`join`.\n\n EXAMPLES::\n\n sage: Sets().Finite() & Rings().Commutative()\n Category of finite commutative rings\n sage: Monoids() & CommutativeAdditiveMonoids()\n Join of Category of monoids and Category of commutative additive monoids\n ' return Category.join([self, other]) def __or__(self, other): '\n Return the smallest category containing the two categories.\n\n This is just a shortcut for :meth:`meet`.\n\n EXAMPLES::\n\n sage: Algebras(QQ) | Groups()\n Category of monoids\n ' return Category.meet([self, other]) _join_cache = _join_cache @staticmethod def join(categories, as_list=False, ignore_axioms=(), axioms=()): "\n Return the join of the input categories in the lattice of categories.\n\n At the level of objects and morphisms, this operation\n corresponds to intersection: the objects and morphisms of a\n join category are those that belong to all its super\n categories.\n\n INPUT:\n\n - ``categories`` -- a list (or iterable) of categories\n - ``as_list`` -- a boolean (default: ``False``);\n whether the result should be returned as a list\n - ``axioms`` -- a tuple of strings; the names of some\n supplementary axioms\n\n .. SEEALSO:: :meth:`__and__` for a shortcut\n\n EXAMPLES::\n\n sage: J = Category.join((Groups(), CommutativeAdditiveMonoids())); J\n Join of Category of groups and Category of commutative additive monoids\n sage: J.super_categories()\n [Category of groups, Category of commutative additive monoids]\n sage: J.all_super_categories(proper=True)\n [Category of groups, ..., Category of magmas,\n Category of commutative additive monoids, ..., Category of additive magmas,\n Category of sets, ...]\n\n As a short hand, one can use::\n\n sage: Groups() & CommutativeAdditiveMonoids()\n Join of Category of groups and Category of commutative additive monoids\n\n This is a commutative and associative operation::\n\n sage: Groups() & Posets()\n Join of Category of groups and Category of posets\n sage: Posets() & Groups()\n Join of Category of groups and Category of posets\n\n sage: Groups() & (CommutativeAdditiveMonoids() & Posets())\n Join of Category of groups\n and Category of commutative additive monoids\n and Category of posets\n sage: (Groups() & CommutativeAdditiveMonoids()) & Posets()\n Join of Category of groups\n and Category of commutative additive monoids\n and Category of posets\n\n The join of a single category is the category itself::\n\n sage: Category.join([Monoids()])\n Category of monoids\n\n Similarly, the join of several mutually comparable categories is\n the smallest one::\n\n sage: Category.join((Sets(), Rings(), Monoids()))\n Category of rings\n\n In particular, the unit is the top category :class:`Objects`::\n\n sage: Groups() & Objects()\n Category of groups\n\n If the optional parameter ``as_list`` is ``True``, this\n returns the super categories of the join as a list, without\n constructing the join category itself::\n\n sage: Category.join((Groups(), CommutativeAdditiveMonoids()), as_list=True)\n [Category of groups, Category of commutative additive monoids]\n sage: Category.join((Sets(), Rings(), Monoids()), as_list=True)\n [Category of rings]\n sage: Category.join((Modules(ZZ), FiniteFields()), as_list=True)\n [Category of finite enumerated fields, Category of modules over Integer Ring]\n sage: Category.join([], as_list=True)\n []\n sage: Category.join([Groups()], as_list=True)\n [Category of groups]\n sage: Category.join([Groups() & Posets()], as_list=True)\n [Category of groups, Category of posets]\n\n Support for axiom categories (TODO: put here meaningful examples)::\n\n sage: Sets().Facade() & Sets().Infinite()\n Category of facade infinite sets\n sage: Magmas().Infinite() & Sets().Facade()\n Category of facade infinite magmas\n\n sage: FiniteSets() & Monoids()\n Category of finite monoids\n sage: Rings().Commutative() & Sets().Finite()\n Category of finite commutative rings\n\n Note that several of the above examples are actually join\n categories; they are just nicely displayed::\n\n sage: AlgebrasWithBasis(QQ) & FiniteSets().Algebras(QQ)\n Join of Category of finite dimensional algebras with basis over Rational Field\n and Category of finite set algebras over Rational Field\n\n sage: UniqueFactorizationDomains() & Algebras(QQ)\n Join of Category of unique factorization domains\n and Category of commutative algebras over Rational Field\n\n TESTS::\n\n sage: Magmas().Unital().Commutative().Finite() is Magmas().Finite().Commutative().Unital()\n True\n sage: from sage.categories.category_with_axiom import TestObjects\n sage: T = TestObjects()\n sage: TCF = T.Commutative().Facade(); TCF\n Category of facade commutative test objects\n sage: TCF is T.Facade().Commutative()\n True\n sage: TCF is (T.Facade() & T.Commutative())\n True\n sage: TCF.axioms()\n frozenset({'Commutative', 'Facade'})\n sage: type(TCF)\n <class 'sage.categories.category_with_axiom.TestObjects.Commutative.Facade_with_category'>\n\n sage: TCF = T.Commutative().FiniteDimensional()\n sage: TCF is T.FiniteDimensional().Commutative()\n True\n sage: TCF is T.Commutative() & T.FiniteDimensional()\n True\n sage: TCF is T.FiniteDimensional() & T.Commutative()\n True\n sage: type(TCF)\n <class 'sage.categories.category_with_axiom.TestObjects.Commutative.FiniteDimensional_with_category'>\n\n sage: TCU = T.Commutative().Unital()\n sage: TCU is T.Unital().Commutative()\n True\n sage: TCU is T.Commutative() & T.Unital()\n True\n sage: TCU is T.Unital() & T.Commutative()\n True\n\n sage: TUCF = T.Unital().Commutative().FiniteDimensional(); TUCF\n Category of finite dimensional commutative unital test objects\n sage: type(TUCF)\n <class 'sage.categories.category_with_axiom.TestObjects.FiniteDimensional.Unital.Commutative_with_category'>\n\n sage: TFFC = T.Facade().FiniteDimensional().Commutative(); TFFC\n Category of facade finite dimensional commutative test objects\n sage: type(TFFC)\n <class 'sage.categories.category.JoinCategory_with_category'>\n sage: TFFC.super_categories()\n [Category of facade commutative test objects,\n Category of finite dimensional commutative test objects]\n " categories = list(categories) if (not categories): if as_list: return [] else: from .objects import Objects return Objects() elif (len(categories) == 1): category = categories[0] if as_list: if isinstance(category, JoinCategory): return category.super_categories() else: return categories else: return category cache_key = _sort_uniq(_flatten_categories(categories, JoinCategory)) if (not ignore_axioms): try: out = _join_cache[cache_key] if as_list: if isinstance(out, JoinCategory): return out._super_categories return [out] return out except KeyError: pass result = join_as_tuple(cache_key, axioms, ignore_axioms) if as_list: return list(result) if (len(result) == 1): result = result[0] else: result = JoinCategory(result) if (not ignore_axioms): _join_cache[cache_key] = result return result def category(self): '\n Return the category of this category. So far, all categories\n are in the category of objects.\n\n EXAMPLES::\n\n sage: Sets().category()\n Category of objects\n sage: VectorSpaces(QQ).category()\n Category of objects\n ' from .objects import Objects return Objects() def example(self, *args, **keywords): '\n Returns an object in this category. Most of the time, this is a parent.\n\n This serves three purposes:\n\n - Give a typical example to better explain what the category is all about.\n (and by the way prove that the category is non empty :-) )\n - Provide a minimal template for implementing other objects in this category\n - Provide an object on which to test generic code implemented by the category\n\n For all those applications, the implementation of the object\n shall be kept to a strict minimum. The object is therefore not\n meant to be used for other applications; most of the time a\n full featured version is available elsewhere in Sage, and\n should be used instead.\n\n Technical note: by default ``FooBar(...).example()`` is\n constructed by looking up\n ``sage.categories.examples.foo_bar.Example`` and calling it as\n ``Example()``. Extra positional or named parameters are also\n passed down. For a category over base ring, the base ring is\n further passed down as an optional argument.\n\n Categories are welcome to override this default implementation.\n\n EXAMPLES::\n\n sage: Semigroups().example()\n An example of a semigroup: the left zero semigroup\n\n sage: Monoids().Subquotients().example()\n NotImplemented\n ' if ('.' in self.__class__.__name__): return NotImplemented module_name = self.__module__.replace('sage.categories', 'sage.categories.examples') import sys try: __import__(module_name) module = sys.modules[module_name] except ImportError: return NotImplemented try: cls = module.Example except AttributeError: return NotImplemented if ('base_ring' not in keywords): try: keywords['base_ring'] = self.base_ring() except AttributeError: pass return cls(*args, **keywords)
def is_Category(x): '\n Returns True if x is a category.\n\n EXAMPLES::\n\n sage: sage.categories.category.is_Category(CommutativeAdditiveSemigroups())\n True\n sage: sage.categories.category.is_Category(ZZ)\n False\n ' return isinstance(x, Category)
@cached_function def category_sample(): '\n Return a sample of categories.\n\n It is constructed by looking for all concrete category classes declared in\n ``sage.categories.all``, calling :meth:`Category.an_instance` on those and\n taking all their super categories.\n\n EXAMPLES::\n\n sage: from sage.categories.category import category_sample\n sage: sorted(category_sample(), key=str) # needs sage.groups\n [Category of Coxeter groups,\n Category of G-sets for Symmetric group of order 8! as a permutation group,\n Category of Hecke modules over Rational Field,\n Category of Hopf algebras over Rational Field,\n Category of Hopf algebras with basis over Rational Field,\n Category of Lie algebras over Rational Field,\n Category of Weyl groups,\n Category of additive magmas, ...,\n Category of fields, ...,\n Category of graded Hopf algebras with basis over Rational Field, ...,\n Category of modular abelian varieties over Rational Field, ...,\n Category of simplicial complexes, ...,\n Category of vector spaces over Rational Field, ...\n ' import sage.categories.all abstract_classes_for_categories = [Category] return tuple((cls.an_instance() for cls in sage.categories.all.__dict__.values() if (isinstance(cls, type) and issubclass(cls, Category) and (cls not in abstract_classes_for_categories))))
def category_graph(categories=None): "\n Return the graph of the categories in Sage.\n\n INPUT:\n\n - ``categories`` -- a list (or iterable) of categories\n\n If ``categories`` is specified, then the graph contains the\n mentioned categories together with all their super\n categories. Otherwise the graph contains (an instance of) each\n category in :mod:`sage.categories.all` (e.g. ``Algebras(QQ)`` for\n algebras).\n\n For readability, the names of the category are shortened.\n\n .. TODO:: Further remove the base ring (see also :trac:`15801`).\n\n EXAMPLES::\n\n sage: G = sage.categories.category.category_graph(categories=[Groups()]) # needs sage.graphs\n sage: G.vertices(sort=True) # needs sage.graphs\n ['groups', 'inverse unital magmas', 'magmas', 'monoids', 'objects',\n 'semigroups', 'sets', 'sets with partial maps', 'unital magmas']\n sage: G.plot() # needs sage.graphs sage.plot\n Graphics object consisting of 20 graphics primitives\n\n sage: sage.categories.category.category_graph().plot() # needs sage.graphs sage.plot\n Graphics object consisting of ... graphics primitives\n " from sage import graphs if (categories is None): categories = category_sample() categories = {cat for category in categories for cat in category.all_super_categories(proper=isinstance(category, JoinCategory))} g = graphs.digraph.DiGraph() for cat in categories: g.add_vertex(cat._repr_object_names()) for source in categories: for target in source._super_categories: g.add_edge([source._repr_object_names(), target._repr_object_names()]) return g
class CategoryWithParameters(Category): '\n A parametrized category whose parent/element classes depend only on\n its super categories.\n\n Many categories in Sage are parametrized, like ``C = Algebras(K)``\n which takes a base ring as parameter. In many cases, however, the\n operations provided by ``C`` in the parent class and element class\n depend only on the super categories of ``C``. For example, the\n vector space operations are provided if and only if ``K`` is a\n field, since ``VectorSpaces(K)`` is a super category of ``C`` only\n in that case. In such cases, and as an optimization (see :trac:`11935`),\n we want to use the same parent and element class for all fields.\n This is the purpose of this abstract class.\n\n Currently, :class:`~sage.categories.category.JoinCategory`,\n :class:`~sage.categories.category_types.Category_over_base` and\n :class:`~sage.categories.bimodules.Bimodules` inherit from this\n class.\n\n EXAMPLES::\n\n sage: C1 = Algebras(GF(5))\n sage: C2 = Algebras(GF(3))\n sage: C3 = Algebras(ZZ)\n sage: from sage.categories.category import CategoryWithParameters\n sage: isinstance(C1, CategoryWithParameters)\n True\n sage: C1.parent_class is C2.parent_class\n True\n sage: C1.parent_class is C3.parent_class\n False\n\n .. automethod:: Category._make_named_class\n ' def _make_named_class(self, name, method_provider, cache=False, **options): "\n Return the parent/element/... class of ``self``.\n\n INPUT:\n\n - ``name`` -- a string; the name of the class as an attribute\n of ``self``\n - ``method_provider`` -- a string; the name of an attribute of\n ``self`` that provides methods for the new class (in\n addition to what comes from the super categories)\n - ``**options`` -- other named options to pass down to\n :meth:`Category._make_named_class`.\n\n ASSUMPTION:\n\n It is assumed that this method is only called from a lazy\n attribute whose name coincides with the given ``name``.\n\n OUTPUT:\n\n A dynamic class that has the corresponding named classes of\n the super categories of ``self`` as bases and contains the\n methods provided by ``getattr(self, method_provider)``.\n\n .. NOTE::\n\n This method overrides :meth:`Category._make_named_class`\n so that the returned class *only* depends on the\n corresponding named classes of the super categories and on\n the provided methods. This allows for sharing the named\n classes across closely related categories providing the\n same code to their parents, elements and so on.\n\n EXAMPLES:\n\n The categories of bimodules over the fields ``CC`` or ``RR``\n provide the same methods to their parents and elements::\n\n sage: Bimodules(ZZ,RR).parent_class is Bimodules(ZZ,RDF).parent_class # indirect doctest\n True\n sage: Bimodules(CC,ZZ).element_class is Bimodules(RR,ZZ).element_class # needs sage.rings.real_mpfr\n True\n\n On the other hand, modules over a field have more methods than\n modules over a ring::\n\n sage: Modules(GF(3)).parent_class is Modules(ZZ).parent_class\n False\n sage: Modules(GF(3)).element_class is Modules(ZZ).element_class\n False\n\n For a more subtle example, one could possibly share the classes for\n ``GF(3)`` and ``GF(2^3, 'x')``, but this is not currently the case::\n\n sage: Modules(GF(3)).parent_class is Modules(GF(2^3,'x')).parent_class # needs sage.rings.finite_rings\n False\n\n This is because those two fields do not have the exact same category::\n\n sage: GF(3).category()\n Join of Category of finite enumerated fields\n and Category of subquotients of monoids\n and Category of quotients of semigroups\n sage: GF(2^3,'x').category() # needs sage.rings.finite_rings\n Category of finite enumerated fields\n\n Similarly for ``QQ`` and ``RR``::\n\n sage: QQ.category()\n Join of Category of number fields\n and Category of quotient fields\n and Category of metric spaces\n sage: RR.category()\n Join of Category of fields and Category of infinite sets\n and Category of complete metric spaces\n sage: Modules(QQ).parent_class is Modules(RR).parent_class\n False\n\n Some other cases where one could potentially share those classes::\n\n sage: MF = Modules(GF(3), dispatch=False)\n sage: MF.parent_class is Modules(ZZ).parent_class\n False\n sage: MF.element_class is Modules(ZZ).element_class\n False\n\n TESTS::\n\n sage: PC = Algebras(QQ).parent_class; PC # indirect doctest\n <class 'sage.categories.algebras.Algebras.parent_class'>\n sage: type(PC)\n <class 'sage.structure.dynamic_class.DynamicMetaclass'>\n sage: PC.__bases__\n (<class 'sage.categories.rings.Rings.parent_class'>,\n <class 'sage.categories.associative_algebras.AssociativeAlgebras.parent_class'>,\n <class 'sage.categories.unital_algebras.UnitalAlgebras.parent_class'>)\n sage: loads(dumps(PC)) is PC\n True\n " cls = self.__class__ if isinstance(cls, DynamicMetaclass): cls = cls.__base__ key = (cls, name, self._make_named_class_key(name)) try: return self._make_named_class_cache[key] except KeyError: pass result = Category._make_named_class(self, name, method_provider, cache=cache, **options) self._make_named_class_cache[key] = result return result @abstract_method def _make_named_class_key(self, name): '\n Return what the element/parent/... class depend on.\n\n INPUT:\n\n - ``name`` -- a string; the name of the class as an attribute\n of ``self``\n\n .. SEEALSO::\n\n - :meth:`_make_named_class`\n - :meth:`sage.categories.category_types.Category_over_base._make_named_class_key`\n - :meth:`sage.categories.bimodules.Bimodules._make_named_class_key`\n - :meth:`JoinCategory._make_named_class_key`\n\n EXAMPLES:\n\n The parent class of an algebra depends only on the category of the base ring::\n\n sage: Algebras(ZZ)._make_named_class_key("parent_class")\n Join of Category of euclidean domains\n and Category of infinite enumerated sets\n and Category of metric spaces\n\n The morphism class of a bimodule depends only on the category\n of the left and right base rings::\n\n sage: Bimodules(QQ, ZZ)._make_named_class_key("morphism_class")\n (Join of Category of number fields\n and Category of quotient fields\n and Category of metric spaces,\n Join of Category of euclidean domains\n and Category of infinite enumerated sets\n and Category of metric spaces)\n\n The element class of a join category depends only on the\n element class of its super categories::\n\n sage: Category.join([Groups(), Posets()])._make_named_class_key("element_class")\n (<class \'sage.categories.groups.Groups.element_class\'>,\n <class \'sage.categories.posets.Posets.element_class\'>)\n ' _make_named_class_cache = {} _cmp_key = _cmp_key_named def _subcategory_hook_(self, C): '\n A quick but partial test whether ``C`` is a subcategory of ``self``.\n\n INPUT:\n\n - ``C`` -- a category\n\n OUTPUT:\n\n ``False``, if ``C.parent_class`` is not a subclass of\n ``self.parent_class``, and :obj:`~sage.misc.unknown.Unknown`\n otherwise.\n\n EXAMPLES::\n\n sage: Bimodules(QQ,QQ)._subcategory_hook_(Modules(QQ))\n Unknown\n sage: Bimodules(QQ,QQ)._subcategory_hook_(Rings())\n False\n ' if (not issubclass(C.parent_class, self.parent_class)): return False return Unknown
class JoinCategory(CategoryWithParameters): "\n A class for joins of several categories. Do not use directly;\n see Category.join instead.\n\n EXAMPLES::\n\n sage: from sage.categories.category import JoinCategory\n sage: J = JoinCategory((Groups(), CommutativeAdditiveMonoids())); J\n Join of Category of groups and Category of commutative additive monoids\n sage: J.super_categories()\n [Category of groups, Category of commutative additive monoids]\n sage: J.all_super_categories(proper=True)\n [Category of groups, ..., Category of magmas,\n Category of commutative additive monoids, ..., Category of additive magmas,\n Category of sets, Category of sets with partial maps, Category of objects]\n\n By :trac:`11935`, join categories and categories over base rings\n inherit from :class:`CategoryWithParameters`. This allows for\n sharing parent and element classes between similar categories. For\n example, since group algebras belong to a join category and since\n the underlying implementation is the same for all finite fields,\n we have::\n\n sage: # needs sage.groups sage.rings.finite_rings\n sage: G = SymmetricGroup(10)\n sage: A3 = G.algebra(GF(3))\n sage: A5 = G.algebra(GF(5))\n sage: type(A3.category())\n <class 'sage.categories.category.JoinCategory_with_category'>\n sage: type(A3) is type(A5)\n True\n\n .. automethod:: Category._repr_object_names\n .. automethod:: Category._repr_\n .. automethod:: Category._without_axioms\n " def __init__(self, super_categories, **kwds): '\n Initializes this JoinCategory\n\n INPUT:\n\n - ``super_categories`` -- Categories to join. This category will\n consist of objects and morphisms that lie in all of these\n categories.\n\n - ``name`` -- ignored\n\n TESTS::\n\n sage: from sage.categories.category import JoinCategory\n sage: C = JoinCategory((Groups(), CommutativeAdditiveMonoids())); C\n Join of Category of groups and Category of commutative additive monoids\n sage: TestSuite(C).run()\n ' assert (len(super_categories) >= 2) assert all(((not isinstance(category, JoinCategory)) for category in super_categories)) self.__super_categories = list(super_categories) Category.__init__(self) def _make_named_class_key(self, name): "\n Return what the element/parent/... classes depend on.\n\n Since :trac:`11935`, the element/parent classes of a join\n category over base only depend on the element/parent class of\n its super categories.\n\n .. SEEALSO::\n\n - :meth:`CategoryWithParameters`\n - :meth:`CategoryWithParameters._make_named_class_key`\n\n EXAMPLES::\n\n sage: Modules(ZZ)._make_named_class_key('element_class')\n Join of Category of euclidean domains\n and Category of infinite enumerated sets\n and Category of metric spaces\n sage: Modules(QQ)._make_named_class_key('parent_class')\n Join of Category of number fields\n and Category of quotient fields\n and Category of metric spaces\n sage: Schemes(Spec(ZZ))._make_named_class_key('parent_class')\n Category of schemes\n sage: ModularAbelianVarieties(QQ)._make_named_class_key('parent_class')\n Join of Category of number fields\n and Category of quotient fields\n and Category of metric spaces\n " return tuple((getattr(cat, name) for cat in self._super_categories)) def super_categories(self): '\n Returns the immediate super categories, as per :meth:`Category.super_categories`.\n\n EXAMPLES::\n\n sage: from sage.categories.category import JoinCategory\n sage: JoinCategory((Semigroups(), FiniteEnumeratedSets())).super_categories()\n [Category of semigroups, Category of finite enumerated sets]\n ' return self.__super_categories def additional_structure(self): '\n Return ``None``.\n\n Indeed, a join category defines no additional structure.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n EXAMPLES::\n\n sage: Modules(ZZ).additional_structure()\n ' return None def _subcategory_hook_(self, category): "\n Returns whether ``category`` is a subcategory of this join category\n\n INPUT:\n\n - ``category`` -- a category.\n\n .. note::\n\n ``category`` is a sub-category of this join category if\n and only if it is a sub-category of all super categories\n of this join category.\n\n EXAMPLES::\n\n sage: base_cat = Category.join([NumberFields(), QuotientFields().Metric()])\n sage: cat = Category.join([Rings(), VectorSpaces(base_cat)])\n sage: QQ['x'].category().is_subcategory(cat) # indirect doctest\n True\n " return all((category.is_subcategory(X) for X in self._super_categories)) def is_subcategory(self, C): '\n Check whether this join category is subcategory of another\n category ``C``.\n\n EXAMPLES::\n\n sage: Category.join([Rings(),Modules(QQ)]).is_subcategory(Category.join([Rngs(),Bimodules(QQ,QQ)]))\n True\n ' if (C is self): return True hook = C._subcategory_hook_(self) if (hook is Unknown): return any((X.is_subcategory(C) for X in self._super_categories)) return hook def _with_axiom(self, axiom): '\n Return the category obtained by adding an axiom to ``self``.\n\n .. NOTE::\n\n This is just an optimization of\n :meth:`Category._with_axiom`; it\'s not necessarily\n actually useful.\n\n EXAMPLES::\n\n sage: C = Category.join([Monoids(), Posets()])\n sage: C._with_axioms(["Finite"])\n Join of Category of finite monoids and Category of finite posets\n\n TESTS:\n\n Check that axiom categories for a join are reconstructed from\n the base categories::\n\n sage: C = Category.join([Monoids(), Magmas().Commutative()])\n sage: C._with_axioms(["Finite"])\n Category of finite commutative monoids\n\n This helps guaranteeing commutativity of taking axioms::\n\n sage: Monoids().Finite().Commutative() is Monoids().Commutative().Finite()\n True\n ' return Category.join([cat._with_axiom(axiom) for cat in self._super_categories]) @cached_method def _without_axiom(self, axiom): '\n Return this category with axiom ``axiom`` removed.\n\n OUTPUT:\n\n A category ``C`` which does not have axiom ``axiom`` and such\n that either ``C`` is ``self``, or adding back all the\n axioms of ``self`` gives back ``self``.\n\n .. SEEALSO:: :meth:`Category._without_axiom`\n\n .. WARNING:: This is not guaranteed to be robust.\n\n EXAMPLES::\n\n sage: C = Posets() & FiniteEnumeratedSets() & Sets().Facade(); C\n Category of facade finite enumerated posets\n sage: C._without_axiom("Facade")\n Category of finite enumerated posets\n\n sage: C = Sets().Finite().Facade()\n sage: type(C)\n <class \'sage.categories.category.JoinCategory_with_category\'>\n sage: C._without_axiom("Facade")\n Category of finite sets\n ' result = Category.join((C._without_axiom(axiom) for C in self.super_categories())) assert (axiom not in result.axioms()) assert (result._with_axioms(self.axioms()) is self) return result def _without_axioms(self, named=False): "\n When adjoining axioms to a category, one often gets a join\n category; this method tries to recover the original\n category from this join category.\n\n INPUT:\n\n - ``named`` -- a boolean (default: ``False``)\n\n See :meth:`Category._without_axioms` for the description\n of the ``named`` parameter.\n\n EXAMPLES::\n\n sage: C = Category.join([Monoids(), Posets()]).Finite()\n sage: C._repr_(as_join=True)\n 'Join of Category of finite monoids and Category of finite posets'\n sage: C._without_axioms()\n Traceback (most recent call last):\n ...\n ValueError: This join category isn't built by adding axioms to a single category\n sage: C = Monoids().Infinite()\n sage: C._repr_(as_join=True)\n 'Join of Category of monoids and Category of infinite sets'\n sage: C._without_axioms()\n Category of magmas\n sage: C._without_axioms(named=True)\n Category of monoids\n\n TESTS:\n\n ``C`` is in fact a join category::\n\n sage: from sage.categories.category import JoinCategory\n sage: isinstance(C, JoinCategory)\n True\n " axioms = self.axioms() for category in self._super_categories: if (category._with_axioms(axioms) is self): return category._without_axioms(named=named) raise ValueError("This join category isn't built by adding axioms to a single category") def _cmp_key(self): '\n Return a comparison key for ``self``.\n\n See :meth:`Category._cmp_key` for the specifications.\n\n EXAMPLES:\n\n This raises an error since ``_cmp_key`` should not be called\n on join categories::\n\n sage: (Magmas() & CommutativeAdditiveSemigroups())._cmp_key()\n Traceback (most recent call last):\n ...\n ValueError: _cmp_key should not be called on join categories\n ' raise ValueError('_cmp_key should not be called on join categories') def _repr_object_names(self): "\n Return the name of the objects of this category.\n\n .. SEEALSO:: :meth:`Category._repr_object_names`, :meth:`_repr_`, :meth:`._without_axioms`\n\n EXAMPLES::\n\n sage: Groups().Finite().Commutative()._repr_(as_join=True)\n 'Join of Category of finite groups and Category of commutative groups'\n sage: Groups().Finite().Commutative()._repr_object_names()\n 'finite commutative groups'\n\n This uses :meth:`._without_axioms` which may fail if this\n category is not obtained by adjoining axioms to some super\n categories::\n\n sage: Category.join((Groups(), CommutativeAdditiveMonoids()))._repr_object_names()\n Traceback (most recent call last):\n ...\n ValueError: This join category isn't built by adding axioms to a single category\n " from sage.categories.category_with_axiom import CategoryWithAxiom return CategoryWithAxiom._repr_object_names_static(self._without_axioms(named=True), self.axioms()) def _repr_(self, as_join=False): "\n Print representation.\n\n INPUT:\n\n - ``as_join`` -- a boolean (default: False)\n\n EXAMPLES::\n\n sage: Category.join((Groups(), CommutativeAdditiveMonoids())) #indirect doctest\n Join of Category of groups and Category of commutative additive monoids\n\n By default, when a join category is built from category by\n adjoining axioms, a nice name is printed out::\n\n sage: Groups().Facade().Finite()\n Category of facade finite groups\n\n But this is in fact really a join category::\n\n sage: Groups().Facade().Finite()._repr_(as_join = True)\n 'Join of Category of finite groups and Category of facade sets'\n\n The rationale is to make it more readable, and hide the\n technical details of how this category is constructed\n internally, especially since this construction is likely to\n change over time when new axiom categories are implemented.\n\n This join category may possibly be obtained by adding axioms\n to different categories; so the result is not guaranteed to be\n unique; when this is not the case the first found is used.\n\n .. SEEALSO:: :meth:`Category._repr_`, :meth:`_repr_object_names`\n\n TESTS::\n\n sage: Category.join((Sets().Facade(), Groups()))\n Category of facade groups\n " if (not as_join): try: return super()._repr_() except ValueError: pass return ('Join of ' + ' and '.join((str(cat) for cat in self._super_categories)))
class Elements(Category): '\n The category of all elements of a given parent.\n\n EXAMPLES::\n\n sage: a = IntegerRing()(5)\n sage: C = a.category(); C\n Category of elements of Integer Ring\n sage: a in C\n True\n sage: 2/3 in C\n False\n sage: loads(C.dumps()) == C\n True\n ' def __init__(self, object): '\n EXAMPLES::\n\n sage: TestSuite(Elements(ZZ)).run()\n ' Category.__init__(self) self.__object = object @classmethod def an_instance(cls): '\n Returns an instance of this class\n\n EXAMPLES::\n\n sage: Elements.an_instance()\n Category of elements of Rational Field\n ' from sage.rings.rational_field import QQ return cls(QQ) def _call_(self, x): '\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: V = VectorSpace(QQ, 3)\n sage: x = V.0\n sage: C = x.category()\n sage: C\n Category of elements of Vector space of dimension 3 over Rational Field\n sage: w = C([1, 2, 3]); w # indirect doctest\n (1, 2, 3)\n sage: w.category()\n Category of elements of Vector space of dimension 3 over Rational Field\n ' return self.__object(x) def super_categories(self): '\n EXAMPLES::\n\n sage: Elements(ZZ).super_categories()\n [Category of objects]\n\n .. TODO::\n\n Check that this is what we want.\n ' return [Objects()] def object(self): '\n EXAMPLES::\n\n sage: Elements(ZZ).object()\n Integer Ring\n ' return self.__object def __reduce__(self): '\n EXAMPLES::\n\n sage: C = Elements(ZZ)\n sage: loads(dumps(C)) == C\n True\n ' return (Elements, (self.__object,)) def _repr_object_names(self): "\n EXAMPLES::\n\n sage: Elements(ZZ)._repr_object_names()\n 'elements of Integer Ring'\n " return ('elements of %s' % self.object()) def _latex_(self): '\n EXAMPLES::\n\n sage: V = VectorSpace(QQ, 3) # needs sage.modules\n sage: x = V.0 # needs sage.modules\n sage: latex(x.category()) # indirect doctest # needs sage.modules\n \\mathbf{Elt}_{\\Bold{Q}^{3}}\n ' return ('\\mathbf{Elt}_{%s}' % latex(self.__object))
class Category_over_base(CategoryWithParameters): '\n A base class for categories over some base object\n\n INPUT:\n\n - ``base`` -- a category `C` or an object of such a category\n\n Assumption: the classes for the parents, elements, morphisms, of\n ``self`` should only depend on `C`. See :trac:`11935` for details.\n\n EXAMPLES::\n\n sage: Algebras(GF(2)).element_class is Algebras(GF(3)).element_class\n True\n\n sage: C = GF(2).category()\n sage: Algebras(GF(2)).parent_class is Algebras(C).parent_class\n True\n\n sage: C = ZZ.category()\n sage: Algebras(ZZ).element_class is Algebras(C).element_class\n True\n ' def __init__(self, base, name=None): '\n Initialize ``self``.\n\n The ``name`` parameter is ignored.\n\n EXAMPLES::\n\n sage: S = Spec(ZZ)\n sage: C = Schemes(S); C\n Category of schemes over Integer Ring\n sage: C.__class__.__init__ == sage.categories.category_types.Category_over_base.__init__\n True\n sage: C.base() is S\n True\n sage: TestSuite(C).run()\n ' self.__base = base Category.__init__(self) def _test_category_over_bases(self, **options): '\n Run generic tests on this category with parameters.\n\n .. SEEALSO:: :class:`TestSuite`.\n\n EXAMPLES::\n\n sage: Modules(QQ)._test_category_over_bases()\n ' tester = self._tester(**options) from sage.categories.category_singleton import Category_singleton from .bimodules import Bimodules from .schemes import Schemes for cat in self.super_categories(): tester.assertTrue(isinstance(cat, (Category_singleton, Category_over_base, Bimodules, Schemes)), 'The super categories of a category over base should be a category over base (or the related Bimodules) or a singleton category') def _make_named_class_key(self, name): "\n Return what the element/parent/... classes depend on.\n\n Since :trac:`11935`, the element and parent classes of a\n category over base only depend on the category of the base (or\n the base itself if it is a category).\n\n .. SEEALSO::\n\n - :meth:`CategoryWithParameters`\n - :meth:`CategoryWithParameters._make_named_class_key`\n\n EXAMPLES::\n\n sage: Modules(ZZ)._make_named_class_key('element_class')\n Join of Category of euclidean domains\n and Category of infinite enumerated sets\n and Category of metric spaces\n sage: Modules(QQ)._make_named_class_key('parent_class')\n Join of Category of number fields\n and Category of quotient fields\n and Category of metric spaces\n sage: Schemes(Spec(ZZ))._make_named_class_key('parent_class')\n Category of schemes\n sage: ModularAbelianVarieties(QQ)._make_named_class_key('parent_class')\n Join of Category of number fields\n and Category of quotient fields\n and Category of metric spaces\n sage: Algebras(Fields())._make_named_class_key('morphism_class')\n Category of fields\n " if isinstance(self.__base, Category): return self.__base return self.__base.category() @classmethod def an_instance(cls): '\n Returns an instance of this class\n\n EXAMPLES::\n\n sage: Algebras.an_instance()\n Category of algebras over Rational Field\n ' from sage.rings.rational_field import QQ return cls(QQ) def base(self): '\n Return the base over which elements of this category are\n defined.\n\n EXAMPLES::\n\n sage: C = Algebras(QQ)\n sage: C.base()\n Rational Field\n ' return self.__base def _repr_object_names(self): "\n Return the name of the objects of this category.\n\n .. SEEALSO:: :meth:`Category._repr_object_names`\n\n EXAMPLES::\n\n sage: Algebras(QQ)._repr_object_names()\n 'algebras over Rational Field'\n sage: Algebras(Fields())._repr_object_names()\n 'algebras over fields'\n sage: Algebras(GF(2).category())._repr_object_names()\n 'algebras over (finite enumerated fields and subquotients of monoids and quotients of semigroups)'\n " base = self.__base if isinstance(base, Category): if isinstance(base, JoinCategory): name = (('(' + ' and '.join((C._repr_object_names() for C in base.super_categories()))) + ')') else: name = base._repr_object_names() else: name = base return (Category._repr_object_names(self) + (' over %s' % name)) def _latex_(self): '\n EXAMPLES::\n\n sage: latex(ModulesWithBasis(ZZ))\n \\mathbf{ModulesWithBasis}_{\\Bold{Z}}\n ' return ('\\mathbf{%s}_{%s}' % (self._label, latex(self.__base)))
class AbelianCategory(Category): def is_abelian(self): '\n Return ``True`` as ``self`` is an abelian category.\n\n EXAMPLES::\n\n sage: CommutativeAdditiveGroups().is_abelian()\n True\n ' return True
class Category_over_base_ring(Category_over_base): def __init__(self, base, name=None): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: C = Algebras(GF(2)); C\n Category of algebras over Finite Field of size 2\n sage: TestSuite(C).run()\n ' from sage.categories.rings import Rings if (not ((base in Rings()) or (isinstance(base, Category) and base.is_subcategory(Rings())))): raise ValueError('base must be a ring or a subcategory of Rings()') Category_over_base.__init__(self, base, name) def base_ring(self): '\n Return the base ring over which elements of this category are\n defined.\n\n EXAMPLES::\n\n sage: C = Algebras(GF(2))\n sage: C.base_ring()\n Finite Field of size 2\n ' return self.base() def _subcategory_hook_(self, C): '\n A quick test whether a category ``C`` may be a subcategory of\n this category.\n\n INPUT:\n\n - ``C`` -- a category (type not tested)\n\n OUTPUT:\n\n A boolean if it is certain that ``C`` is (or is not) a\n subcategory of self. :obj:`~sage.misc.unknown.Unknown`\n otherwise.\n\n EXAMPLES:\n\n The answer is ``False`` if the subcategory class of ``C`` is\n not a subclass of the subcategory class of ``self``::\n\n sage: Algebras(QQ)._subcategory_hook_(VectorSpaces(QQ))\n False\n sage: VectorSpaces(QQ)._subcategory_hook_(Algebras(ZZ))\n False\n\n .. WARNING::\n\n This test currently includes some false negatives::\n\n sage: VectorSpaces(Fields())._subcategory_hook_(Algebras(Fields().Finite()))\n False\n sage: Modules(Rings())._subcategory_hook_(Modules(GroupAlgebras(Rings())))\n False\n\n The answer is ``Unknown`` if ``C`` is not a category over base ring::\n\n sage: VectorSpaces(QQ)._subcategory_hook_(VectorSpaces(QQ) & Rings())\n Unknown\n\n sage: # needs sage.combinat sage.modules\n sage: Sym = SymmetricFunctions(QQ)\n sage: from sage.combinat.sf.sfa import SymmetricFunctionsBases\n sage: Modules(QQ)._subcategory_hook_(SymmetricFunctionsBases(Sym))\n Unknown\n sage: SymmetricFunctionsBases(Sym).is_subcategory(Modules(QQ))\n True\n\n Case 1: the two bases are categories; then the base of ``C``\n shall be a subcategory of the base of ``self``::\n\n sage: VectorSpaces(Fields())._subcategory_hook_(Algebras(Fields()))\n True\n sage: VectorSpaces(Fields())._subcategory_hook_(Algebras(Fields().Finite())) # todo: not implemented\n True\n sage: VectorSpaces(Fields().Finite())._subcategory_hook_(Algebras(Fields()))\n False\n\n Case 2: the base of ``self`` is a category; then the base of\n ``C`` shall be a parent in this category::\n\n sage: VectorSpaces(Fields())._subcategory_hook_(Algebras(QQ)) # todo: not implemented\n True\n sage: VectorSpaces(Fields().Finite())._subcategory_hook_(Algebras(QQ))\n False\n\n Case 3: the two bases are parents; then they should coincide::\n\n sage: VectorSpaces(QQ)._subcategory_hook_(Algebras(QQ))\n True\n sage: VectorSpaces(CC)._subcategory_hook_(Algebras(QQ)) # base ring in different categories # needs sage.rings.real_mpfr\n False\n sage: VectorSpaces(GF(2))._subcategory_hook_(Algebras(GF(3))) # base ring in the same category\n False\n\n Note; we need both previous tests since the distinction is\n made respectively using the parent class or the base ring::\n\n sage: issubclass(Algebras(QQ).parent_class, # needs sage.modules\n ....: VectorSpaces(CC).parent_class)\n False\n sage: issubclass(Algebras(GF(2)).parent_class,\n ....: VectorSpaces(GF(3)).parent_class)\n True\n\n Check that :trac:`16618` is fixed: this `_subcategory_hook_`\n method is only valid for :class:`Category_over_base_ring`, not\n :class:`Category_over_base`::\n\n sage: # needs sage.groups\n sage: from sage.categories.category_types import Category_over_base\n sage: D = Modules(Rings())\n sage: class Cs(Category_over_base):\n ....: def super_categories(self):\n ....: return [D]\n sage: C = Cs(SymmetricGroup(3))\n sage: C.is_subcategory(D)\n True\n sage: D._subcategory_hook_(C)\n Unknown\n sage: import __main__\n sage: __main__.Cs = Cs # Fake Cs being defined in a python module\n sage: TestSuite(C).run()\n ' if (not issubclass(C.parent_class, self.parent_class)): return False if (not isinstance(C, Category_over_base_ring)): return Unknown base_ring = self.base_ring() if (C.base_ring() is base_ring): return True if isinstance(base_ring, Category): if isinstance(C.base(), Category): return C.base().is_subcategory(base_ring) return (C.base() in base_ring) return False def __contains__(self, x): "\n Return whether ``x`` is an object of this category.\n\n In most cases, ``x`` is an object in this category, if and\n only if the category of ``x`` is a subcategory of ``self``.\n Exception: ``x`` is also an object in this category if ``x``\n is in a category over a base ring category ``C``, and ``self``\n is a category over a base ring in ``C``.\n\n This method implements this exception.\n\n EXAMPLES::\n\n sage: QQ['x'] in Algebras(QQ)\n True\n sage: ZZ['x'] in Algebras(ZZ)\n True\n\n We also would want the following to hold::\n\n sage: QQ['x'] in Algebras(Fields()) # todo: not implemented\n True\n\n " try: if (isinstance(x, self.parent_class) or issubclass(x.category().parent_class, self.parent_class)): if isinstance(self.base(), Category): return True else: return (x.base_ring() is self.base_ring()) else: return super().__contains__(x) except AttributeError: return False
class Category_in_ambient(Category): def __init__(self, ambient, name=None): '\n Initialize ``self``.\n\n The parameter ``name`` is ignored.\n\n EXAMPLES::\n\n sage: C = Ideals(IntegerRing())\n sage: TestSuite(C).run()\n ' self.__ambient = ambient Category.__init__(self) def ambient(self): '\n Return the ambient object in which objects of this category are\n embedded.\n\n EXAMPLES::\n\n sage: C = Ideals(IntegerRing())\n sage: C.ambient()\n Integer Ring\n ' return self.__ambient def _repr_(self): '\n EXAMPLES::\n\n sage: Ideals(IntegerRing())\n Category of ring ideals in Integer Ring\n ' return (Category._repr_(self) + (' in %s' % self.__ambient))
class Category_module(AbelianCategory, Category_over_base_ring): pass
class Category_ideal(Category_in_ambient): @classmethod def an_instance(cls): '\n Return an instance of this class.\n\n EXAMPLES::\n\n sage: AlgebraIdeals.an_instance()\n Category of algebra ideals in Univariate Polynomial Ring in x over Rational Field\n ' from sage.rings.rational_field import QQ return cls(QQ['x']) def ring(self): '\n Return the ambient ring used to describe objects ``self``.\n\n EXAMPLES::\n\n sage: C = Ideals(IntegerRing())\n sage: C.ring()\n Integer Ring\n ' return self.ambient() def __contains__(self, x): '\n EXAMPLES::\n\n sage: C = Ideals(IntegerRing())\n sage: IntegerRing().zero_ideal() in C\n True\n ' if super().__contains__(x): return True from sage.rings.ideal import is_Ideal return (is_Ideal(x) and (x.ring() == self.ring())) def __call__(self, v): '\n EXAMPLES::\n\n sage: R.<x,y> = ZZ[]\n sage: Ig = [x, y]\n sage: I = R.ideal(Ig)\n sage: C = Ideals(R)\n sage: C(Ig)\n Ideal (x, y) of Multivariate Polynomial Ring in x, y over Integer Ring\n sage: I == C(I)\n True\n ' if (v in self): return v return self.ring().ideal(v)
def uncamelcase(s, separator=' '): '\n EXAMPLES::\n\n sage: sage.categories.category_with_axiom.uncamelcase("FiniteDimensionalAlgebras")\n \'finite dimensional algebras\'\n sage: sage.categories.category_with_axiom.uncamelcase("JTrivialMonoids")\n \'j trivial monoids\'\n sage: sage.categories.category_with_axiom.uncamelcase("FiniteDimensionalAlgebras", "_")\n \'finite_dimensional_algebras\'\n ' return re.sub('(?!^)[A-Z]', (lambda match: (separator + match.group()[0])), s).lower()
def base_category_class_and_axiom(cls): "\n Try to deduce the base category and the axiom from the name of ``cls``.\n\n The heuristic is to try to decompose the name as the concatenation\n of the name of a category and the name of an axiom, and looking up\n that category in the standard location (i.e. in\n :mod:`sage.categories.hopf_algebras` for :class:`HopfAlgebras`,\n and in :mod:`sage.categories.sets_cat` as a special case\n for :class:`Sets`).\n\n If the heuristic succeeds, the result is guaranteed to be\n correct. Otherwise, an error is raised.\n\n EXAMPLES::\n\n sage: from sage.categories.category_with_axiom import base_category_class_and_axiom, CategoryWithAxiom\n sage: base_category_class_and_axiom(FiniteSets)\n (<class 'sage.categories.sets_cat.Sets'>, 'Finite')\n sage: Sets.Finite\n <class 'sage.categories.finite_sets.FiniteSets'>\n sage: base_category_class_and_axiom(Sets.Finite)\n (<class 'sage.categories.sets_cat.Sets'>, 'Finite')\n\n sage: base_category_class_and_axiom(FiniteDimensionalHopfAlgebrasWithBasis)\n (<class 'sage.categories.hopf_algebras_with_basis.HopfAlgebrasWithBasis'>,\n 'FiniteDimensional')\n\n sage: base_category_class_and_axiom(HopfAlgebrasWithBasis)\n (<class 'sage.categories.hopf_algebras.HopfAlgebras'>, 'WithBasis')\n\n Along the way, this does some sanity checks::\n\n sage: class FacadeSemigroups(CategoryWithAxiom):\n ....: pass\n sage: base_category_class_and_axiom(FacadeSemigroups)\n Traceback (most recent call last):\n ...\n AssertionError: Missing (lazy import) link\n for <class 'sage.categories.semigroups.Semigroups'>\n to <class '__main__.FacadeSemigroups'> for axiom Facade?\n\n sage: Semigroups.Facade = FacadeSemigroups\n sage: base_category_class_and_axiom(FacadeSemigroups)\n (<class 'sage.categories.semigroups.Semigroups'>, 'Facade')\n\n .. NOTE::\n\n In the following example, we could possibly retrieve ``Sets``\n from the class name. However this cannot be implemented\n robustly until :trac:`9107` is fixed. Anyway this feature\n has not been needed so far::\n\n sage: Sets.Infinite\n <class 'sage.categories.sets_cat.Sets.Infinite'>\n sage: base_category_class_and_axiom(Sets.Infinite)\n Traceback (most recent call last):\n ...\n TypeError: Could not retrieve the base category class and axiom\n for <class 'sage.categories.sets_cat.Sets.Infinite'>.\n ...\n " if ('.' in cls.__name__): pass else: name = cls.__name__ for axiom in all_axioms: if ((axiom == 'WithBasis') and name.endswith(axiom)): base_name = name[:(- len(axiom))] elif name.startswith(axiom): base_name = name[len(axiom):] else: continue if (base_name == 'Sets'): base_module_name = 'sets_cat' else: base_module_name = uncamelcase(base_name, '_') try: base_module = importlib.import_module(('sage.categories.' + base_module_name)) base_category_class = getattr(base_module, base_name) assert (getattr(base_category_class, axiom, None) is cls), 'Missing (lazy import) link for {} to {} for axiom {}?'.format(base_category_class, cls, axiom) return (base_category_class, axiom) except (ImportError, AttributeError): pass raise TypeError('Could not retrieve the base category class and axiom for {}.\nPlease specify it explicitly using the attribute _base_category_class_and_axiom.\nSee CategoryWithAxiom for details.'.format(cls))
@cached_function def axiom_of_nested_class(cls, nested_cls): "\n Given a class and a nested axiom class, return the axiom.\n\n EXAMPLES:\n\n This uses some heuristics like checking if the nested_cls carries\n the name of the axiom, or is built by appending or prepending the\n name of the axiom to that of the class::\n\n sage: from sage.categories.category_with_axiom import TestObjects, axiom_of_nested_class\n sage: axiom_of_nested_class(TestObjects, TestObjects.FiniteDimensional)\n 'FiniteDimensional'\n sage: axiom_of_nested_class(TestObjects.FiniteDimensional,\n ....: TestObjects.FiniteDimensional.Finite)\n 'Finite'\n sage: axiom_of_nested_class(Sets, FiniteSets)\n 'Finite'\n sage: axiom_of_nested_class(Algebras, AlgebrasWithBasis)\n 'WithBasis'\n\n In all other cases, the nested class should provide an attribute\n ``_base_category_class_and_axiom``::\n\n sage: Semigroups._base_category_class_and_axiom\n (<class 'sage.categories.magmas.Magmas'>, 'Associative')\n sage: axiom_of_nested_class(Magmas, Semigroups)\n 'Associative'\n " try: axiom = nested_cls.__dict__['_base_category_class_and_axiom'][1] except KeyError: assert (not isinstance(cls, DynamicMetaclass)) nested_cls_name = nested_cls.__name__.split('.')[(- 1)] if (nested_cls_name in all_axioms): axiom = nested_cls_name else: cls_name = cls.__name__.split('.')[(- 1)] if nested_cls_name.startswith(cls_name): axiom = nested_cls_name[len(cls_name):] elif nested_cls_name.endswith(cls_name): axiom = nested_cls_name[:(- len(cls_name))] else: raise ValueError('could not infer axiom for the nested class {} of {}'.format(nested_cls, cls)) assert (axiom in all_axioms), 'Incorrect deduction ({}) for the name of the axiom for the nested class {} of {}'.format(axiom, nested_cls, cls) assert ((axiom in cls.__dict__) and (cls.__dict__[axiom] == nested_cls)), '{} not a nested axiom class of {} for axiom {}'.format(nested_cls, cls, axiom) return axiom
class CategoryWithAxiom(Category): '\n An abstract class for categories obtained by adding an axiom\n to a base category.\n\n See the :mod:`category primer <sage.categories.primer>`, and in\n particular its :ref:`section about axioms <category-primer-axioms>`\n for an introduction to axioms, and :class:`CategoryWithAxiom` for\n how to implement axioms and the documentation of the axiom\n infrastructure.\n\n .. automethod:: CategoryWithAxiom.__classcall__\n .. automethod:: CategoryWithAxiom.__classget__\n .. automethod:: CategoryWithAxiom.__init__\n .. automethod:: CategoryWithAxiom._repr_object_names\n .. automethod:: CategoryWithAxiom._repr_object_names_static\n .. automethod:: CategoryWithAxiom._test_category_with_axiom\n .. automethod:: CategoryWithAxiom._without_axioms\n ' @lazy_class_attribute def _base_category_class_and_axiom(cls): "\n The class of the base category and the axiom for this class.\n\n By default, and when possible, this attribute is deduced from\n the name of this class (see\n :func:`base_category_class_and_axiom`). For a nested class,\n when the category is first created from its base category as\n in e.g. ``Sets().Infinite()``, this attribute is instead set\n explicitly by :meth:`__classget__`.\n\n When this is not sufficient, that is when ``cls`` is not\n implemented as a nested class and the base category and the\n axiom cannot be deduced from the name of ``cls``, this\n attribute should be set explicitly by ``cls``.\n\n The origin of the attribute is stored in the attribute\n ``_base_category_class_and_axiom_origin``.\n\n .. SEEALSO:: :meth:`_axiom`\n\n EXAMPLES:\n\n ``CommutativeRings`` is not a nested class, but the name of\n the base category and the axiom can be deduced::\n\n sage: CommutativeRings()._base_category_class_and_axiom\n (<class 'sage.categories.rings.Rings'>, 'Commutative')\n sage: CommutativeRings()._base_category_class_and_axiom_origin\n 'deduced by base_category_class_and_axiom'\n\n ``Sets.Infinite`` is a nested class, so the attribute is set\n by :meth:`CategoryWithAxiom.__classget__` the first time\n ``Sets().Infinite()`` is called::\n\n sage: Sets().Infinite()\n Category of infinite sets\n sage: Sets.Infinite._base_category_class_and_axiom\n (<class 'sage.categories.sets_cat.Sets'>, 'Infinite')\n sage: Sets.Infinite._base_category_class_and_axiom_origin\n 'set by __classget__'\n\n ``Fields`` is not a nested class, and the name of the base\n category and axioms cannot be deduced from the name\n ``Fields``; so this attributes needs to be set explicitly in\n the ``Fields`` class::\n\n sage: Fields()._base_category_class_and_axiom\n (<class 'sage.categories.division_rings.DivisionRings'>, 'Commutative')\n sage: Fields()._base_category_class_and_axiom_origin\n 'hardcoded'\n\n .. NOTE::\n\n The base category class is often another category with\n axiom, therefore having a special ``__classget__`` method.\n Storing the base category class and the axiom in a single\n tuple attribute -- instead of two separate attributes --\n has the advantage of not triggering, for example,\n ``Semigroups.__classget__`` upon\n ``Monoids._base_category_class``.\n " (base_category_class, axiom) = base_category_class_and_axiom(cls) cls._base_category_class_and_axiom_origin = 'deduced by base_category_class_and_axiom' return (base_category_class, axiom) _base_category_class_and_axiom_origin = 'hardcoded' @lazy_class_attribute def _axiom(cls): "\n The axiom for this category with axiom.\n\n .. SEEALSO:: :meth:`_base_category_class_and_axiom`\n\n EXAMPLES::\n\n sage: FiniteSets._axiom\n 'Finite'\n sage: Sets.Finite._axiom\n 'Finite'\n sage: Algebras.Commutative._axiom\n 'Commutative'\n\n The result can be less obvious::\n\n sage: Semigroups._axiom\n 'Associative'\n sage: Rings._axiom\n 'Unital'\n sage: Fields._axiom\n 'Commutative'\n " return cls._base_category_class_and_axiom[1] @staticmethod def __classcall__(cls, *args, **options): '\n Make ``FoosBar(**)`` an alias for ``Foos(**)._with_axiom("Bar")``.\n\n EXAMPLES::\n\n sage: FiniteGroups()\n Category of finite groups\n sage: ModulesWithBasis(ZZ)\n Category of modules with basis over Integer Ring\n sage: AlgebrasWithBasis(QQ)\n Category of algebras with basis over Rational Field\n\n This is relevant when e.g. ``Foos(**)`` does some non trivial\n transformations::\n\n sage: Modules(QQ) is VectorSpaces(QQ)\n True\n sage: type(Modules(QQ))\n <class \'sage.categories.vector_spaces.VectorSpaces_with_category\'>\n\n sage: ModulesWithBasis(QQ) is VectorSpaces(QQ).WithBasis()\n True\n sage: type(ModulesWithBasis(QQ))\n <class \'sage.categories.vector_spaces.VectorSpaces.WithBasis_with_category\'>\n ' (base_category_class, axiom) = cls._base_category_class_and_axiom if ((len(args) == 1) and (not options) and isinstance(args[0], base_category_class)): return super().__classcall__(cls, args[0]) else: return base_category_class(*args, **options)._with_axiom(axiom) @staticmethod def __classget__(cls, base_category, base_category_class): "\n Implement the binding behavior for categories with axioms.\n\n This method implements a binding behavior on category with\n axioms so that, when a category ``Cs`` implements an axiom\n ``A`` with a nested class ``Cs.A``, the expression ``Cs().A``\n evaluates to the method defining the axiom ``A`` and not the\n nested class. See `those design notes\n <category-with-axiom-design>`_ for the rationale behind this\n behavior.\n\n EXAMPLES::\n\n sage: Sets().Infinite()\n Category of infinite sets\n sage: Sets().Infinite\n Cached version of <function ...Infinite at ...>\n sage: Sets().Infinite.f == Sets.SubcategoryMethods.Infinite.f\n True\n\n We check that this also works when the class is implemented in\n a separate file, and lazy imported::\n\n sage: Sets().Finite\n Cached version of <function ...Finite at ...>\n\n There is no binding behavior when accessing ``Finite`` or\n ``Infinite`` from the class of the category instead of the\n category itself::\n\n sage: Sets.Finite\n <class 'sage.categories.finite_sets.FiniteSets'>\n sage: Sets.Infinite\n <class 'sage.categories.sets_cat.Sets.Infinite'>\n\n This method also initializes the attribute\n ``_base_category_class_and_axiom`` if not already set::\n\n sage: Sets.Infinite._base_category_class_and_axiom\n (<class 'sage.categories.sets_cat.Sets'>, 'Infinite')\n sage: Sets.Infinite._base_category_class_and_axiom_origin\n 'set by __classget__'\n " if (base_category is not None): assert (base_category.__class__ is base_category_class) assert isinstance(base_category_class, DynamicMetaclass) if isinstance(base_category_class, DynamicMetaclass): base_category_class = base_category_class.__base__ if ('_base_category_class_and_axiom' not in cls.__dict__): cls._base_category_class_and_axiom = (base_category_class, axiom_of_nested_class(base_category_class, cls)) cls._base_category_class_and_axiom_origin = 'set by __classget__' else: assert (cls._base_category_class_and_axiom[0] is base_category_class), 'base category class for {} mismatch; expected {}, got {}'.format(cls, cls._base_category_class_and_axiom[0], base_category_class) if isinstance(base_category_class.__dict__[cls._axiom], LazyImport): setattr(base_category_class, cls._axiom, cls) if (base_category is None): return cls return getattr(super(base_category.__class__.__base__, base_category), cls._axiom) def __init__(self, base_category): "\n TESTS::\n\n sage: C = Sets.Finite(); C\n Category of finite sets\n sage: type(C)\n <class 'sage.categories.finite_sets.FiniteSets_with_category'>\n sage: type(C).__base__.__base__\n <class 'sage.categories.category_with_axiom.CategoryWithAxiom_singleton'>\n\n sage: TestSuite(C).run()\n " if (isinstance(base_category, Category_singleton) and (not isinstance(self, CategoryWithAxiom_singleton))): cls = self.__class__ assert (cls.__base__ == CategoryWithAxiom) cls.__bases__ = ((CategoryWithAxiom_singleton,) + cls.__bases__[1:]) self._base_category = base_category Category.__init__(self) def _test_category_with_axiom(self, **options): '\n Run generic tests on this category with axioms.\n\n .. SEEALSO:: :class:`TestSuite`.\n\n This check that an axiom category of a\n :class:`Category_singleton` is a singleton category, and\n similarwise for :class:`Category_over_base_ring`.\n\n EXAMPLES::\n\n sage: Sets().Finite()._test_category_with_axiom()\n sage: Modules(ZZ).FiniteDimensional()._test_category_with_axiom()\n ' tester = self._tester(**options) base = self.base_category() if isinstance(base, Category_singleton): tester.assertIsInstance(self, CategoryWithAxiom_singleton) if isinstance(base, Category_over_base_ring): tester.assertIsInstance(self, CategoryWithAxiom_over_base_ring) def extra_super_categories(self): '\n Return the extra super categories of a category with axiom.\n\n Default implementation which returns ``[]``.\n\n EXAMPLES::\n\n sage: FiniteSets().extra_super_categories()\n []\n ' return [] @cached_method def super_categories(self): '\n Return a list of the (immediate) super categories of\n ``self``, as per :meth:`Category.super_categories`.\n\n This implements the property that if ``As`` is a subcategory\n of ``Bs``, then the intersection of ``As`` with ``FiniteSets()``\n is a subcategory of ``As`` and of the intersection of ``Bs``\n with ``FiniteSets()``.\n\n EXAMPLES:\n\n A finite magma is both a magma and a finite set::\n\n sage: Magmas().Finite().super_categories()\n [Category of magmas, Category of finite sets]\n\n Variants::\n\n sage: Sets().Finite().super_categories()\n [Category of sets]\n\n sage: Monoids().Finite().super_categories()\n [Category of monoids, Category of finite semigroups]\n\n EXAMPLES:\n\n TESTS::\n\n sage: from sage.categories.category_with_axiom import TestObjects\n sage: C = TestObjects().FiniteDimensional().Unital().Commutative().Finite()\n sage: sorted(C.super_categories(), key=str)\n [Category of finite commutative test objects,\n Category of finite dimensional commutative unital test objects,\n Category of finite finite dimensional test objects]\n ' base_category = self._base_category axiom = self._axiom return Category.join((((base_category,) + tuple((cat for category in base_category._super_categories for cat in category._with_axiom_as_tuple(axiom)))) + tuple(self.extra_super_categories())), ignore_axioms=((base_category, axiom),), as_list=True) def additional_structure(self): "\n Return the additional structure defined by ``self``.\n\n OUTPUT: ``None``\n\n By default, a category with axiom defines no additional\n structure.\n\n .. SEEALSO:: :meth:`Category.additional_structure`.\n\n EXAMPLES::\n\n sage: Sets().Finite().additional_structure()\n sage: Monoids().additional_structure()\n\n TESTS::\n\n sage: Sets().Finite().additional_structure.__module__\n 'sage.categories.category_with_axiom'\n " return None @staticmethod def _repr_object_names_static(category, axioms): '\n INPUT:\n\n - ``base_category`` -- a category\n - ``axioms`` -- a list or iterable of strings\n\n EXAMPLES::\n\n sage: from sage.categories.category_with_axiom import CategoryWithAxiom\n sage: CategoryWithAxiom._repr_object_names_static(Semigroups(), ["Flying", "Blue"])\n \'flying blue semigroups\'\n sage: CategoryWithAxiom._repr_object_names_static(Algebras(QQ), ["Flying", "WithBasis", "Blue"])\n \'flying blue algebras with basis over Rational Field\'\n sage: CategoryWithAxiom._repr_object_names_static(Algebras(QQ), ["WithBasis"])\n \'algebras with basis over Rational Field\'\n sage: CategoryWithAxiom._repr_object_names_static(Sets().Finite().Subquotients(), ["Finite"])\n \'subquotients of finite sets\'\n sage: CategoryWithAxiom._repr_object_names_static(Monoids(), ["Unital"])\n \'monoids\'\n sage: CategoryWithAxiom._repr_object_names_static(Algebras(QQ[\'x\'][\'y\']), ["Flying", "WithBasis", "Blue"])\n \'flying blue algebras with basis over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field\'\n\n If the axioms is a set or frozen set, then they are first\n sorted using :func:`canonicalize_axioms`::\n\n sage: CategoryWithAxiom._repr_object_names_static(Semigroups(), set(["Finite", "Commutative", "Facade"]))\n \'facade finite commutative semigroups\'\n\n .. SEEALSO:: :meth:`_repr_object_names`\n\n .. NOTE::\n\n The logic here is shared between :meth:`_repr_object_names`\n and :meth:`.category.JoinCategory._repr_object_names`\n\n TESTS::\n\n sage: from sage.categories.homsets import Homsets\n sage: CategoryWithAxiom._repr_object_names_static(Homsets(), ["Endset"])\n \'endsets\'\n sage: CategoryWithAxiom._repr_object_names_static(PermutationGroups(), ["FinitelyGeneratedAsMagma"])\n \'finitely generated permutation groups\'\n sage: CategoryWithAxiom._repr_object_names_static(Rings(), ["FinitelyGeneratedAsMagma"])\n \'finitely generated as magma rings\'\n ' from sage.categories.additive_magmas import AdditiveMagmas axioms = canonicalize_axioms(all_axioms, axioms) base_category = category._without_axioms(named=True) if isinstance(base_category, CategoryWithAxiom): result = super(CategoryWithAxiom, base_category)._repr_object_names() else: result = base_category._repr_object_names() for axiom in reversed(axioms): if (axiom in base_category.axioms()): continue base_category = base_category._with_axiom(axiom) if (axiom == 'WithBasis'): result = result.replace(' over ', ' with basis over ', 1) elif ((axiom == 'Connected') and ('graded ' in result)): result = result.replace('graded ', 'graded connected ', 1) elif ((axiom == 'Connected') and ('filtered ' in result)): result = result.replace('filtered ', 'filtered connected ', 1) elif ((axiom == 'Stratified') and ('graded ' in result)): result = result.replace('graded ', 'stratified ', 1) elif ((axiom == 'Nilpotent') and ('finite dimensional ' in result)): result = result.replace('finite dimensional ', 'finite dimensional nilpotent ', 1) elif ((axiom == 'Endset') and ('homsets' in result)): result = result.replace('homsets', 'endsets', 1) elif ((axiom == 'FinitelyGeneratedAsMagma') and (not base_category.is_subcategory(AdditiveMagmas()))): result = ('finitely generated ' + result) elif (axiom == 'FinitelyGeneratedAsLambdaBracketAlgebra'): result = ('finitely generated ' + result) else: result = ((uncamelcase(axiom) + ' ') + result) return result def _repr_object_names(self): "\n The names of the objects of this category, as used by ``_repr_``.\n\n .. SEEALSO:: :meth:`Category._repr_object_names`\n\n EXAMPLES::\n\n sage: FiniteSets()._repr_object_names()\n 'finite sets'\n sage: AlgebrasWithBasis(QQ).FiniteDimensional()._repr_object_names()\n 'finite dimensional algebras with basis over Rational Field'\n sage: Monoids()._repr_object_names()\n 'monoids'\n sage: Semigroups().Unital().Finite()._repr_object_names()\n 'finite monoids'\n sage: Algebras(QQ).Commutative()._repr_object_names()\n 'commutative algebras over Rational Field'\n\n .. NOTE::\n\n This is implemented by taking _repr_object_names from\n self._without_axioms(named=True), and adding the names\n of the relevant axioms in appropriate order.\n " return CategoryWithAxiom._repr_object_names_static(self, self.axioms()) def base_category(self): '\n Return the base category of ``self``.\n\n EXAMPLES::\n\n sage: C = Sets.Finite(); C\n Category of finite sets\n sage: C.base_category()\n Category of sets\n sage: C._without_axioms()\n Category of sets\n\n TESTS::\n\n sage: from sage.categories.category_with_axiom import TestObjects, CategoryWithAxiom\n sage: C = TestObjects().Commutative().Facade()\n sage: assert isinstance(C, CategoryWithAxiom)\n sage: C._without_axioms()\n Category of test objects\n ' return self._base_category def __reduce__(self): "\n Implement the pickle protocol.\n\n This overrides the implementation in\n :meth:`UniqueRepresentation.__reduce__` in order to not\n exposes the implementation detail that, for example, the\n category of magmas which distribute over an associative\n additive magma is implemented as\n ``MagmasAndAdditiveMagmas.Distributive.AdditiveAssociative.AdditiveCommutative``\n and not\n ``MagmasAndAdditiveMagmas.Distributive.AdditiveCommutative.AdditiveAssociative``.\n\n EXAMPLES::\n\n sage: C = Semigroups()\n sage: reduction = C.__reduce__(); reduction\n (<function call_method at ...>, (Category of magmas, '_with_axiom', 'Associative'))\n sage: loads(dumps(C)) is C\n True\n sage: FiniteSets().__reduce__()\n (<function call_method at ...>, (Category of sets, '_with_axiom', 'Finite'))\n\n sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas\n sage: C = MagmasAndAdditiveMagmas().Distributive().AdditiveAssociative().AdditiveCommutative()\n sage: C.__class__\n <class 'sage.categories.distributive_magmas_and_additive_magmas.DistributiveMagmasAndAdditiveMagmas.AdditiveAssociative.AdditiveCommutative_with_category'>\n sage: C.__reduce__()\n (<function call_method at ...>, (Category of additive associative distributive magmas and additive magmas, '_with_axiom', 'AdditiveCommutative'))\n " return (call_method, (self._base_category, '_with_axiom', self._axiom)) @cached_method def _without_axiom(self, axiom): '\n Return this category, with axiom ``axiom`` removed.\n\n OUTPUT:\n\n A category ``C`` which does not have axiom ``axiom`` and such\n that either ``C`` is ``self``, or adding back all the axioms\n of ``self`` gives back ``self``.\n\n .. SEEALSO:: :meth:`Category._without_axiom`\n\n .. WARNING:: This is not guaranteed to be robust.\n\n EXAMPLES::\n\n sage: Groups()._without_axiom("Unital")\n Category of semigroups\n sage: Groups()._without_axiom("Associative")\n Category of inverse unital magmas\n sage: Groups().Commutative()._without_axiom("Unital")\n Category of commutative semigroups\n ' axioms = self.axioms().difference([axiom]) return self._without_axioms()._with_axioms(axioms) @cached_method def _without_axioms(self, named=False): '\n Return the category without the axioms that have been\n added to create it.\n\n EXAMPLES::\n\n sage: Sets().Finite()._without_axioms()\n Category of sets\n sage: Monoids().Finite()._without_axioms()\n Category of magmas\n\n This is because::\n\n sage: Semigroups().Unital() is Monoids()\n True\n\n If ``named`` is ``True``, then ``_without_axioms`` stops at the\n first category that has an explicit name of its own::\n\n sage: Sets().Finite()._without_axioms(named=True)\n Category of sets\n sage: Monoids().Finite()._without_axioms(named=True)\n Category of monoids\n\n Technically we test this by checking if the class specifies\n explicitly the attribute ``_base_category_class_and_axiom``\n by looking up ``_base_category_class_and_axiom_origin``.\n\n Some more examples::\n\n sage: Algebras(QQ).Commutative()._without_axioms()\n Category of magmatic algebras over Rational Field\n sage: Algebras(QQ).Commutative()._without_axioms(named=True)\n Category of algebras over Rational Field\n ' if (named and (self._base_category_class_and_axiom_origin == 'hardcoded')): return self return self._base_category._without_axioms(named=named) @cached_method def axioms(self): "\n Return the axioms known to be satisfied by all the\n objects of ``self``.\n\n .. SEEALSO:: :meth:`Category.axioms`\n\n EXAMPLES::\n\n sage: C = Sets.Finite(); C\n Category of finite sets\n sage: C.axioms()\n frozenset({'Finite'})\n\n sage: C = Modules(GF(5)).FiniteDimensional(); C\n Category of finite dimensional vector spaces over Finite Field of size 5\n sage: sorted(C.axioms())\n ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse',\n 'AdditiveUnital', 'Finite', 'FiniteDimensional']\n\n sage: sorted(FiniteMonoids().Algebras(QQ).axioms())\n ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse',\n 'AdditiveUnital', 'Associative', 'Distributive',\n 'FiniteDimensional', 'Unital', 'WithBasis']\n sage: sorted(FiniteMonoids().Algebras(GF(3)).axioms())\n ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse',\n 'AdditiveUnital', 'Associative', 'Distributive', 'Finite',\n 'FiniteDimensional', 'Unital', 'WithBasis']\n\n sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas\n sage: MagmasAndAdditiveMagmas().Distributive().Unital().axioms()\n frozenset({'Distributive', 'Unital'})\n\n sage: D = MagmasAndAdditiveMagmas().Distributive()\n sage: X = D.AdditiveAssociative().AdditiveCommutative().Associative()\n sage: X.Unital().super_categories()[1]\n Category of monoids\n sage: X.Unital().super_categories()[1] is Monoids()\n True\n " return (frozenset((axiom for category in self._super_categories for axiom in category.axioms())) | {self._axiom})
class CategoryWithAxiom_over_base_ring(CategoryWithAxiom, Category_over_base_ring): def __init__(self, base_category): "\n TESTS::\n\n sage: C = Modules(ZZ).FiniteDimensional(); C\n Category of finite dimensional modules over Integer Ring\n sage: type(C)\n <class 'sage.categories.modules.Modules.FiniteDimensional_with_category'>\n sage: type(C).__base__.__base__\n <class 'sage.categories.category_with_axiom.CategoryWithAxiom_over_base_ring'>\n\n sage: TestSuite(C).run()\n " self._base_category = base_category Category_over_base_ring.__init__(self, base_category.base_ring())
class CategoryWithAxiom_singleton(Category_singleton, CategoryWithAxiom): pass
def axiom(axiom): '\n Return a function/method ``self -> self._with_axiom(axiom)``.\n\n This can used as a shorthand to define axioms, in particular in\n the tests below. Usually one will want to attach documentation to\n an axiom, so the need for such a shorthand in real life might not\n be that clear, unless we start creating lots of axioms.\n\n In the long run maybe this could evolve into an ``@axiom`` decorator.\n\n EXAMPLES::\n\n sage: from sage.categories.category_with_axiom import axiom\n sage: axiom("Finite")(Semigroups())\n Category of finite semigroups\n\n Upon assigning the result to a class this becomes a method::\n\n sage: class As:\n ....: def _with_axiom(self, axiom): return self, axiom\n ....: Finite = axiom("Finite")\n sage: As().Finite()\n (<__main__.As ... at ...>, \'Finite\')\n ' def with_axiom(self): return self._with_axiom(axiom) with_axiom.__name__ = axiom return with_axiom
class Blahs(Category_singleton): "\n A toy singleton category, for testing purposes.\n\n This is the root of a hierarchy of mathematically meaningless\n categories, used for testing Sage's category framework:\n\n - :class:`Bars`\n - :class:`TestObjects`\n - :class:`TestObjectsOverBaseRing`\n " def super_categories(self): '\n TESTS::\n\n sage: from sage.categories.category_with_axiom import Blahs\n sage: Blahs().super_categories()\n [Category of sets]\n sage: TestSuite(Blahs()).run()\n ' from sage.categories.sets_cat import Sets return [Sets()] class SubcategoryMethods(): FiniteDimensional = axiom('FiniteDimensional') Commutative = axiom('Commutative') Unital = axiom('Unital') Connected = axiom('Connected') Flying = axiom('Flying') Blue = axiom('Blue') class FiniteDimensional(CategoryWithAxiom): pass class Commutative(CategoryWithAxiom): pass class Connected(CategoryWithAxiom): pass class Unital(CategoryWithAxiom): class Blue(CategoryWithAxiom): pass class Flying(CategoryWithAxiom): def extra_super_categories(self): '\n This illustrates a way to have an axiom imply another one.\n\n Here, we want ``Flying`` to imply ``Unital``, and to put\n the class for the category of unital flying blahs in\n ``Blahs.Flying`` rather than ``Blahs.Unital.Flying``.\n\n TESTS::\n\n sage: from sage.categories.category_with_axiom import Blahs, TestObjects, Bars\n sage: Blahs().Flying().extra_super_categories()\n [Category of unital blahs]\n sage: Blahs().Flying()\n Category of flying unital blahs\n ' return [Blahs().Unital()] def Blue_extra_super_categories(self): "\n Illustrates a current limitation in the way to have an axiom\n imply another one.\n\n Here, we would want ``Blue`` to imply ``Unital``, and to put\n the class for the category of unital blue blahs in\n ``Blahs.Unital.Blue`` rather than ``Blahs.Blue``.\n\n This currently fails because ``Blahs`` is the category where\n the axiom ``Blue`` is defined, and the specifications\n currently impose that a category defining an axiom should also\n implement it (here in a category with axiom\n ``Blahs.Blue``). In practice, due to this violation of the\n specifications, the axiom is lost during the join calculation.\n\n .. TODO::\n\n Decide whether we care about this feature. In such a\n situation, we are not really defining a new axiom, but\n just defining an axiom as an alias for a couple others,\n which might not be that useful.\n\n .. TODO::\n\n Improve the infrastructure to detect and report this\n violation of the specifications, if this is\n easy. Otherwise, it's not so bad: when defining an axiom A\n in a category ``Cs`` the first thing one is supposed to\n doctest is that ``Cs().A()`` works. So the problem should\n not go unnoticed.\n\n TESTS::\n\n sage: from sage.categories.category_with_axiom import Blahs, TestObjects, Bars\n sage: Blahs().Blue_extra_super_categories()\n [Category of unital blahs]\n sage: Blahs().Blue() # todo: not implemented\n Category of blue unital blahs\n " return [Blahs().Unital()]
class Bars(Category_singleton): '\n A toy singleton category, for testing purposes.\n\n .. SEEALSO:: :class:`Blahs`\n ' def super_categories(self): '\n TESTS::\n\n sage: from sage.categories.category_with_axiom import Bars\n sage: Bars().super_categories()\n [Category of blahs]\n sage: TestSuite(Bars()).run()\n ' return [Blahs()] def Unital_extra_super_categories(self): '\n Return extraneous super categories for the unital objects of ``self``.\n\n This method specifies that a unital bar is a test object.\n Thus, the categories of unital bars and of unital test objects\n coincide.\n\n EXAMPLES::\n\n sage: from sage.categories.category_with_axiom import Bars, TestObjects\n sage: Bars().Unital_extra_super_categories()\n [Category of test objects]\n sage: Bars().Unital()\n Category of unital test objects\n sage: TestObjects().Unital().all_super_categories()\n [Category of unital test objects,\n Category of unital blahs,\n Category of test objects,\n Category of bars,\n Category of blahs,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n ' return [TestObjects()]
class TestObjects(Category_singleton): '\n A toy singleton category, for testing purposes.\n\n .. SEEALSO:: :class:`Blahs`\n ' def super_categories(self): '\n TESTS::\n\n sage: from sage.categories.category_with_axiom import TestObjects\n sage: TestObjects().super_categories()\n [Category of bars]\n sage: TestSuite(TestObjects()).run()\n ' return [Bars()] class FiniteDimensional(CategoryWithAxiom): class Finite(CategoryWithAxiom): pass class Unital(CategoryWithAxiom): class Commutative(CategoryWithAxiom): pass class Commutative(CategoryWithAxiom): class Facade(CategoryWithAxiom): pass class FiniteDimensional(CategoryWithAxiom): pass class Finite(CategoryWithAxiom): pass class Unital(CategoryWithAxiom): pass
class TestObjectsOverBaseRing(Category_over_base_ring): '\n A toy singleton category, for testing purposes.\n\n .. SEEALSO:: :class:`Blahs`\n ' def super_categories(self): '\n TESTS::\n\n sage: from sage.categories.category_with_axiom import TestObjectsOverBaseRing\n sage: TestObjectsOverBaseRing(QQ).super_categories()\n [Category of test objects]\n sage: TestObjectsOverBaseRing.Unital.an_instance()\n Category of unital test objects over base ring over Rational Field\n sage: TestObjectsOverBaseRing.FiniteDimensional.Unital.an_instance()\n Category of finite dimensional unital test objects over base ring over Rational Field\n sage: C = TestObjectsOverBaseRing(QQ).FiniteDimensional().Unital().Commutative()\n sage: TestSuite(C).run()\n ' return [TestObjects()] class FiniteDimensional(CategoryWithAxiom_over_base_ring): class Finite(CategoryWithAxiom_over_base_ring): pass class Unital(CategoryWithAxiom_over_base_ring): class Commutative(CategoryWithAxiom_over_base_ring): pass class Commutative(CategoryWithAxiom_over_base_ring): class Facade(CategoryWithAxiom_over_base_ring): pass class FiniteDimensional(CategoryWithAxiom_over_base_ring): pass class Finite(CategoryWithAxiom_over_base_ring): pass class Unital(CategoryWithAxiom_over_base_ring): pass
class ChainComplexes(Category_module): '\n The category of all chain complexes over a base ring.\n\n EXAMPLES::\n\n sage: ChainComplexes(RationalField())\n Category of chain complexes over Rational Field\n sage: ChainComplexes(Integers(9))\n Category of chain complexes over Ring of integers modulo 9\n\n TESTS::\n\n sage: TestSuite(ChainComplexes(RationalField())).run()\n\n ' def super_categories(self): '\n EXAMPLES::\n\n sage: ChainComplexes(Integers(9)).super_categories()\n [Category of modules over Ring of integers modulo 9]\n\n ' from sage.categories.fields import Fields from sage.categories.modules import Modules from sage.categories.vector_spaces import VectorSpaces base_ring = self.base_ring() if (base_ring in Fields()): return [VectorSpaces(base_ring)] return [Modules(base_ring)] class ParentMethods(): @abstract_method def homology(self, n=None): '\n Return the homology of the chain complex.\n\n INPUT:\n\n - ``n`` -- (default: ``None``) degree of the homology; if none is\n provided, the direct sum homology will be used\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: C = ChainComplex({0: matrix(ZZ, 2, 3, [3, 0, 0, 0, 0, 0])})\n sage: C.homology(0)\n Z x Z\n sage: C.homology(1)\n Z x C3\n sage: C.homology(2)\n 0\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: A.<x,y,z> = GradedCommutativeAlgebra(QQ, degrees=(2, 2, 3))\n sage: C = A.cdg_algebra({z: x*y})\n sage: C.homology(0)\n Free module generated by {[1]} over Rational Field\n sage: C.homology(1)\n Free module generated by {} over Rational Field\n sage: C.homology(2)\n Free module generated by {[x], [y]} over Rational Field\n sage: C.homology(3)\n Free module generated by {} over Rational Field\n sage: C.homology(4)\n Free module generated by {[x^2], [y^2]} over Rational Field\n\n ' @abstract_method def differential(self, *args, **kwargs): "\n Return the differentials (or boundary maps) of the chain complex.\n\n EXAMPLES::\n\n sage: C = ChainComplex({0: matrix(ZZ, 2, 3, [3, 0, 0, 0, 0, 0])}) # needs sage.modules\n sage: C.differential(0) # needs sage.modules\n [3 0 0]\n [0 0 0]\n\n ::\n\n sage: A.<x,y,z> = GradedCommutativeAlgebra(QQ, degrees=(2, 2, 3)) # needs sage.combinat sage.modules\n sage: C = A.cdg_algebra({z: x*y}) # needs sage.combinat sage.modules\n sage: C.differential() # needs sage.combinat sage.modules\n Differential of Commutative Differential Graded Algebra with\n generators ('x', 'y', 'z') in degrees (2, 2, 3) over Rational Field\n Defn: x --> 0\n y --> 0\n z --> x*y\n\n " @abstract_method(optional=True) def lift_from_homology(self, x): '\n Lift the homology element ``x`` to the corresponding module.\n\n EXAMPLES::\n\n sage: # needs sage.symbolic\n sage: E3 = EuclideanSpace(3)\n sage: C = E3.de_rham_complex()\n sage: one = C.homology().one()\n sage: C.lift_from_homology(one)\n Mixed differential form one on the Euclidean space E^3\n ' def reduce_to_homology(self, x, n=None): '\n Reduce a cycle to the corresponding quotient in homology.\n\n INPUT:\n\n - ``x`` -- a cycle\n - ``n`` -- (default: ``None``) degree of the homology; if none is\n provided, the direct sum homology will be used\n\n\n EXAMPLES::\n\n sage: # needs sage.symbolic\n sage: E3 = EuclideanSpace(3)\n sage: C = E3.de_rham_complex()\n sage: one = C.one()\n sage: C.reduce_to_homology(one)\n [one]\n ' try: return self.homology(n)(x) except TypeError: raise NotImplementedError
class HomologyFunctor(Functor): '\n Homology functor.\n\n INPUT:\n\n - ``domain`` -- must be a category of chain complexes\n - ``n`` -- (default: ``None``) degree of the homology; if none is provided,\n the direct sum homology will be used\n\n EXAMPLES::\n\n sage: C = ChainComplex({0: matrix(ZZ, 2, 3, [3, 0, 0, 0, 0, 0])}) # needs sage.modules\n sage: H = HomologyFunctor(ChainComplexes(ZZ), 1)\n sage: H(C) # needs sage.modules\n Z x C3\n\n ::\n\n sage: A.<x,y,z> = GradedCommutativeAlgebra(QQ, degrees=(2, 2, 3)) # needs sage.combinat sage.modules\n sage: C = A.cdg_algebra({z: x*y}) # needs sage.combinat sage.modules\n sage: H = HomologyFunctor(ChainComplexes(QQ), 2)\n sage: H(C) # needs sage.combinat sage.modules\n Free module generated by {[x], [y]} over Rational Field\n\n Applying to a chain map::\n\n sage: # needs sage.graphs sage.modules\n sage: S = simplicial_complexes.Sphere(1); S\n Minimal triangulation of the 1-sphere\n sage: SCC = S.chain_complex()\n sage: SCC.differential()\n {0: [],\n 1: [-1 -1 0]\n [ 1 0 -1]\n [ 0 1 1],\n 2: []}\n sage: f = {0: zero_matrix(ZZ,3,3), 1: zero_matrix(ZZ,3,3)}\n sage: G = Hom(SCC, SCC)\n sage: x = G(f)\n sage: H = HomologyFunctor(ChainComplexes(ZZ), 1)\n sage: H(SCC)\n Z\n sage: H(x)\n Generic morphism:\n From: Z\n To: Z\n\n ' def __init__(self, domain, n=None): '\n Construct the homology functor.\n\n TESTS::\n\n sage: H = HomologyFunctor(ChainComplexes(QQ), 1); H\n Functor from Category of chain complexes over Rational Field to\n Category of commutative additive groups\n\n ' if (not isinstance(domain, ChainComplexes)): raise TypeError(f'{domain} must be a category of chain complexes') codomain = CommutativeAdditiveGroups() super().__init__(domain, codomain) self._n = n def _apply_functor(self, x): '\n Apply ``self`` to a chain complex.\n\n TESTS::\n\n sage: C = ChainComplex({0: matrix(ZZ, 2, 3, [3, 0, 0, 0, 0, 0])}) # needs sage.modules\n sage: H = HomologyFunctor(ChainComplexes(ZZ), 1)\n sage: H._apply_functor(C) # needs sage.modules\n Z x C3\n\n ' return x.homology(self._n) def _apply_functor_to_morphism(self, f): '\n Apply ``self`` to a chain map.\n\n TESTS::\n\n sage: # needs sage.symbolic\n sage: E3 = EuclideanSpace(3)\n sage: C = E3.de_rham_complex()\n sage: id = Hom(C, C).identity()\n sage: H = HomologyFunctor(ChainComplexes(SR))\n sage: id_star = H(id); id_star\n Generic endomorphism of De Rham cohomology ring on the\n Euclidean space E^3\n sage: one = H(C).one()\n sage: id_star(one)\n [one]\n ' from sage.categories.homset import Hom from sage.categories.morphism import SetMorphism domain = f.domain() codomain = f.codomain() lift = domain.lift_from_homology reduce = codomain.reduce_to_homology apply_f_star = (lambda x: reduce(f(lift(x)), self._n)) return SetMorphism(Hom(domain.homology(self._n), codomain.homology(self._n), CommutativeAdditiveGroups()), apply_f_star)
class ClassicalCrystals(Category_singleton): '\n The category of classical crystals, that is crystals of finite Cartan type.\n\n EXAMPLES::\n\n sage: C = ClassicalCrystals()\n sage: C\n Category of classical crystals\n sage: C.super_categories()\n [Category of regular crystals,\n Category of finite crystals,\n Category of highest weight crystals]\n sage: C.example()\n Highest weight crystal of type A_3 of highest weight omega_1\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: B = ClassicalCrystals().example()\n sage: TestSuite(B).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_fast_iter() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n ' def super_categories(self): '\n EXAMPLES::\n\n sage: ClassicalCrystals().super_categories()\n [Category of regular crystals,\n Category of finite crystals,\n Category of highest weight crystals]\n ' return [RegularCrystals(), FiniteCrystals(), HighestWeightCrystals()] def example(self, n=3): '\n Returns an example of highest weight crystals, as per\n :meth:`Category.example`.\n\n EXAMPLES::\n\n sage: B = ClassicalCrystals().example(); B\n Highest weight crystal of type A_3 of highest weight omega_1\n ' return Crystals().example(n) def additional_structure(self): '\n Return ``None``.\n\n Indeed, the category of classical crystals defines no\n additional structure: it only states that its objects are\n `U_q(\\mathfrak{g})`-crystals, where `\\mathfrak{g}` is of\n finite type.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n EXAMPLES::\n\n sage: ClassicalCrystals().additional_structure()\n ' return None class ParentMethods(): def demazure_character(self, w, f=None): '\n Return the Demazure character associated to ``w``.\n\n INPUT:\n\n - ``w`` -- an element of the ambient weight lattice\n realization of the crystal, or a reduced word, or an element\n in the associated Weyl group\n\n OPTIONAL:\n\n - ``f`` -- a function from the crystal to a module\n\n This is currently only supported for crystals whose underlying\n weight space is the ambient space.\n\n The Demazure character is obtained by applying the Demazure operator\n `D_w` (see :meth:`sage.categories.regular_crystals.RegularCrystals.ParentMethods.demazure_operator`)\n to the highest weight element of the classical crystal. The simple\n Demazure operators `D_i` (see\n :meth:`sage.categories.regular_crystals.RegularCrystals.ElementMethods.demazure_operator_simple`)\n do not braid on the level of crystals, but on the level of characters they do.\n That is why it makes sense to input ``w`` either as a weight, a reduced word,\n or as an element of the underlying Weyl group.\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux([\'A\',2], shape = [2,1])\n sage: e = T.weight_lattice_realization().basis()\n sage: weight = e[0] + 2*e[2]\n sage: weight.reduced_word()\n [2, 1]\n sage: T.demazure_character(weight)\n x1^2*x2 + x1*x2^2 + x1^2*x3 + x1*x2*x3 + x1*x3^2\n\n sage: T = crystals.Tableaux([\'A\',3],shape=[2,1])\n sage: T.demazure_character([1,2,3])\n x1^2*x2 + x1*x2^2 + x1^2*x3 + x1*x2*x3 + x2^2*x3\n sage: W = WeylGroup([\'A\',3])\n sage: w = W.from_reduced_word([1,2,3])\n sage: T.demazure_character(w)\n x1^2*x2 + x1*x2^2 + x1^2*x3 + x1*x2*x3 + x2^2*x3\n\n sage: T = crystals.Tableaux([\'B\',2], shape = [2])\n sage: e = T.weight_lattice_realization().basis()\n sage: weight = -2*e[1]\n sage: T.demazure_character(weight)\n x1^2 + x1*x2 + x2^2 + x1 + x2 + x1/x2 + 1/x2 + 1/x2^2 + 1\n\n sage: T = crystals.Tableaux("B2",shape=[1/2,1/2])\n sage: b2=WeylCharacterRing("B2",base_ring=QQ).ambient()\n sage: T.demazure_character([1,2],f=lambda x:b2(x.weight()))\n b2(-1/2,1/2) + b2(1/2,-1/2) + b2(1/2,1/2)\n\n REFERENCES:\n\n - [De1974]_\n\n - [Ma2009]_\n ' from sage.misc.misc_c import prod from sage.rings.integer_ring import ZZ if hasattr(w, 'reduced_word'): word = w.reduced_word() else: word = w n = self.weight_lattice_realization().n u = self.algebra(ZZ).sum_of_monomials(self.module_generators) u = self.demazure_operator(u, word) if (f is None): from sage.symbolic.ring import SR as P x = [P.var(('x%s' % (i + 1))) for i in range(n)] return sum(((coeff * prod(((x[i] ** c.weight()[i]) for i in range(n)), P.one())) for (c, coeff) in u), P.zero()) else: return sum(((coeff * f(c)) for (c, coeff) in u)) def character(self, R=None): '\n Returns the character of this crystal.\n\n INPUT:\n\n - ``R`` -- a :class:`WeylCharacterRing`\n (default: the default :class:`WeylCharacterRing` for this Cartan type)\n\n Returns the character of ``self`` as an element of ``R``.\n\n EXAMPLES::\n\n sage: C = crystals.Tableaux("A2", shape=[2,1])\n sage: chi = C.character(); chi\n A2(2,1,0)\n\n sage: T = crystals.TensorProduct(C,C)\n sage: chiT = T.character(); chiT\n A2(2,2,2) + 2*A2(3,2,1) + A2(3,3,0) + A2(4,1,1) + A2(4,2,0)\n sage: chiT == chi^2\n True\n\n One may specify an alternate :class:`WeylCharacterRing`::\n\n sage: R = WeylCharacterRing("A2", style="coroots")\n sage: chiT = T.character(R); chiT\n A2(0,0) + 2*A2(1,1) + A2(0,3) + A2(3,0) + A2(2,2)\n sage: chiT in R\n True\n\n It should have the same Cartan type and use the same\n realization of the weight lattice as ``self``::\n\n sage: R = WeylCharacterRing("A3", style="coroots")\n sage: T.character(R)\n Traceback (most recent call last):\n ...\n ValueError: Weyl character ring does not have the right Cartan type\n\n ' from sage.combinat.root_system.weyl_characters import WeylCharacterRing if (R is None): R = WeylCharacterRing(self.cartan_type()) if (not (R.cartan_type() == self.cartan_type())): raise ValueError('Weyl character ring does not have the right Cartan type') assert (R.basis().keys() == self.weight_lattice_realization()) return R.sum_of_monomials((x.weight() for x in self.highest_weight_vectors())) def __iter__(self): "\n Returns an iterator over the elements of this crystal.\n\n This iterator uses little memory, storing only one element\n of the crystal at a time. For details on the complexity, see\n :class:`sage.combinat.crystals.crystals.CrystalBacktracker`.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: [x for x in C]\n [1, 2, 3, 4, 5, 6]\n\n TESTS::\n\n sage: C = crystals.Letters(['D',4])\n sage: D = crystals.SpinsPlus(['D',4])\n sage: E = crystals.SpinsMinus(['D',4])\n sage: T = crystals.TensorProduct(D,E,generators=[[D.list()[0],E.list()[0]]])\n sage: U = crystals.TensorProduct(C,E,generators=[[C(1),E.list()[0]]])\n sage: T.cardinality()\n 56\n\n sage: TestSuite(T).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_fast_iter() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n\n sage: TestSuite(U).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_fast_iter() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n\n Bump's systematic tests::\n\n sage: fa3 = lambda a,b,c: crystals.Tableaux(['A',3],shape=[a+b+c,b+c,c])\n sage: fb3 = lambda a,b,c: crystals.Tableaux(['B',3],shape=[a+b+c,b+c,c])\n sage: fc3 = lambda a,b,c: crystals.Tableaux(['C',3],shape=[a+b+c,b+c,c])\n sage: fb4 = lambda a,b,c,d: crystals.Tableaux(['B',4],shape=[a+b+c+d,b+c+d,c+d,d])\n sage: fd4 = lambda a,b,c,d: crystals.Tableaux(['D',4],shape=[a+b+c+d,b+c+d,c+d,d])\n sage: fd5 = lambda a,b,c,d,e: crystals.Tableaux(['D',5],shape=[a+b+c+d+e,b+c+d+e,c+d+e,d+e,e])\n sage: def fd4spinplus(a,b,c,d):\n ....: C = crystals.Tableaux(['D',4],shape=[a+b+c+d,b+c+d,c+d,d])\n ....: D = crystals.SpinsPlus(['D',4])\n ....: return crystals.TensorProduct(C,D,generators=[[C[0],D[0]]])\n sage: def fb3spin(a,b,c):\n ....: C = crystals.Tableaux(['B',3],shape=[a+b+c,b+c,c])\n ....: D = crystals.Spins(['B',3])\n ....: return crystals.TensorProduct(C,D,generators=[[C[0],D[0]]])\n\n .. TODO::\n\n Choose a good panel of values for `a,b,c ...` both for\n basic systematic tests and for conditionally run,\n computationally involved tests.\n\n ::\n\n sage: TestSuite(fb4(1,0,1,0)).run(verbose = True) # long time (8s on sage.math, 2011)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_fast_iter() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n\n ::\n\n #sage: fb4(1,1,1,1).check() # expensive: the crystal is of size 297297\n #True\n " from sage.combinat.crystals.crystals import CrystalBacktracker return iter(CrystalBacktracker(self)) def _test_fast_iter(self, **options): "\n Tests whether the elements returned by :meth:`.__iter__`\n and ``Crystal.list(self)`` are the same (the two\n algorithms are different).\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A', 5])\n sage: C._test_fast_iter()\n " tester = self._tester(**options) S = list(self) SS = list(Crystals().parent_class.__iter__(self)) tester.assertEqual(len(S), len(SS)) tester.assertEqual(len(S), len(set(S))) tester.assertEqual(set(S), set(SS)) def cardinality(self): "\n Returns the number of elements of the crystal, using Weyl's\n dimension formula on each connected component.\n\n EXAMPLES::\n\n sage: C = ClassicalCrystals().example(5)\n sage: C.cardinality()\n 6\n " return sum((self.weight_lattice_realization().weyl_dimension(x.weight()) for x in self.highest_weight_vectors())) class ElementMethods(): def lusztig_involution(self): "\n Return the Lusztig involution on the classical highest weight\n crystal ``self``.\n\n The Lusztig involution on a finite-dimensional highest weight\n crystal `B(\\lambda)` of highest weight `\\lambda` maps the\n highest weight vector to the lowest weight vector and the\n Kashiwara operator `f_i` to `e_{i^*}`, where `i^*` is defined as\n `\\alpha_{i^*} = -w_0(\\alpha_i)`. Here `w_0` is the longest element\n of the Weyl group acting on the `i`-th simple root `\\alpha_i`.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',3],shape=[2,1])\n sage: b = B(rows=[[1,2],[4]])\n sage: b.lusztig_involution()\n [[1, 4], [3]]\n sage: b.to_tableau().schuetzenberger_involution(n=4)\n [[1, 4], [3]]\n\n sage: all(b.lusztig_involution().to_tableau() == b.to_tableau().schuetzenberger_involution(n=4) for b in B)\n True\n\n sage: B = crystals.Tableaux(['D',4],shape=[1])\n sage: [[b,b.lusztig_involution()] for b in B]\n [[[[1]], [[-1]]], [[[2]], [[-2]]], [[[3]], [[-3]]], [[[4]], [[-4]]], [[[-4]],\n [[4]]], [[[-3]], [[3]]], [[[-2]], [[2]]], [[[-1]], [[1]]]]\n\n sage: B = crystals.Tableaux(['D',3],shape=[1])\n sage: [[b,b.lusztig_involution()] for b in B]\n [[[[1]], [[-1]]], [[[2]], [[-2]]], [[[3]], [[3]]], [[[-3]], [[-3]]],\n [[[-2]], [[2]]], [[[-1]], [[1]]]]\n\n sage: C = CartanType(['E',6])\n sage: La = C.root_system().weight_lattice().fundamental_weights()\n sage: T = crystals.HighestWeight(La[1])\n sage: t = T[3]; t\n [(-4, 2, 5)]\n sage: t.lusztig_involution()\n [(-2, -3, 4)]\n " hw = self.to_highest_weight()[1] hw.reverse() A = self.parent().cartan_type().opposition_automorphism() hw = [A[i] for i in hw] return self.to_lowest_weight()[0].e_string(hw) class TensorProducts(TensorProductsCategory): '\n The category of classical crystals constructed by tensor\n product of classical crystals.\n ' @cached_method def extra_super_categories(self): '\n EXAMPLES::\n\n sage: ClassicalCrystals().TensorProducts().extra_super_categories()\n [Category of classical crystals]\n ' return [self.base_category()]
class Coalgebras(Category_over_base_ring): '\n The category of coalgebras\n\n EXAMPLES::\n\n sage: Coalgebras(QQ)\n Category of coalgebras over Rational Field\n sage: Coalgebras(QQ).super_categories()\n [Category of vector spaces over Rational Field]\n\n TESTS::\n\n sage: TestSuite(Coalgebras(ZZ)).run()\n ' def super_categories(self): '\n EXAMPLES::\n\n sage: Coalgebras(QQ).super_categories()\n [Category of vector spaces over Rational Field]\n ' return [Modules(self.base_ring())] WithBasis = LazyImport('sage.categories.coalgebras_with_basis', 'CoalgebrasWithBasis') Graded = LazyImport('sage.categories.graded_coalgebras', 'GradedCoalgebras') class ParentMethods(): @abstract_method def counit(self, x): '\n Return the counit of ``x``.\n\n Eventually, there will be a default implementation,\n delegating to the overloading mechanism and forcing the\n conversion back\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: A = HopfAlgebrasWithBasis(QQ).example(); A\n An example of Hopf algebra with basis:\n the group algebra of the Dihedral group of order 6 as a permutation group over Rational Field\n sage: [a,b] = A.algebra_generators()\n sage: a, A.counit(a)\n (B[(1,2,3)], 1)\n sage: b, A.counit(b)\n (B[(1,3)], 1)\n\n TODO: implement some tests of the axioms of coalgebras, bialgebras\n and Hopf algebras using the counit.\n ' @abstract_method def coproduct(self, x): '\n Return the coproduct of ``x``.\n\n Eventually, there will be a default implementation,\n delegating to the overloading mechanism and forcing the\n conversion back\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: A = HopfAlgebrasWithBasis(QQ).example(); A\n An example of Hopf algebra with basis:\n the group algebra of the Dihedral group of order 6 as a permutation group over Rational Field\n sage: [a,b] = A.algebra_generators()\n sage: a, A.coproduct(a)\n (B[(1,2,3)], B[(1,2,3)] # B[(1,2,3)])\n sage: b, A.coproduct(b)\n (B[(1,3)], B[(1,3)] # B[(1,3)])\n ' class ElementMethods(): def coproduct(self): '\n Return the coproduct of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: A = HopfAlgebrasWithBasis(QQ).example(); A\n An example of Hopf algebra with basis:\n the group algebra of the Dihedral group of order 6 as a permutation group over Rational Field\n sage: [a,b] = A.algebra_generators()\n sage: a, a.coproduct()\n (B[(1,2,3)], B[(1,2,3)] # B[(1,2,3)])\n sage: b, b.coproduct()\n (B[(1,3)], B[(1,3)] # B[(1,3)])\n ' return self.parent().coproduct(self) def counit(self): '\n Return the counit of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: A = HopfAlgebrasWithBasis(QQ).example(); A\n An example of Hopf algebra with basis:\n the group algebra of the Dihedral group of order 6 as a permutation group over Rational Field\n sage: [a,b] = A.algebra_generators()\n sage: a, a.counit()\n (B[(1,2,3)], 1)\n sage: b, b.counit()\n (B[(1,3)], 1)\n ' return self.parent().counit(self) class SubcategoryMethods(): @cached_method def Cocommutative(self): "\n Return the full subcategory of the cocommutative objects\n of ``self``.\n\n A coalgebra `C` is said to be *cocommutative* if\n\n .. MATH::\n\n \\Delta(c) = \\sum_{(c)} c_{(1)} \\otimes c_{(2)}\n = \\sum_{(c)} c_{(2)} \\otimes c_{(1)}\n\n in Sweedler's notation for all `c \\in C`.\n\n EXAMPLES::\n\n sage: C1 = Coalgebras(ZZ).Cocommutative().WithBasis(); C1\n Category of cocommutative coalgebras with basis over Integer Ring\n sage: C2 = Coalgebras(ZZ).WithBasis().Cocommutative()\n sage: C1 is C2\n True\n sage: BialgebrasWithBasis(QQ).Cocommutative()\n Category of cocommutative bialgebras with basis over Rational Field\n\n TESTS::\n\n sage: TestSuite(Coalgebras(ZZ).Cocommutative()).run()\n " return self._with_axiom('Cocommutative') class Cocommutative(CategoryWithAxiom_over_base_ring): '\n Category of cocommutative coalgebras.\n ' class TensorProducts(TensorProductsCategory): @cached_method def extra_super_categories(self): '\n EXAMPLES::\n\n sage: Coalgebras(QQ).TensorProducts().extra_super_categories()\n [Category of coalgebras over Rational Field]\n sage: Coalgebras(QQ).TensorProducts().super_categories()\n [Category of tensor products of vector spaces over Rational Field,\n Category of coalgebras over Rational Field]\n\n Meaning: a tensor product of coalgebras is a coalgebra\n ' return [self.base_category()] class ParentMethods(): pass class ElementMethods(): pass class DualObjects(DualObjectsCategory): def extra_super_categories(self): '\n Return the dual category.\n\n EXAMPLES:\n\n The category of coalgebras over the Rational Field is dual\n to the category of algebras over the same field::\n\n sage: C = Coalgebras(QQ)\n sage: C.dual()\n Category of duals of coalgebras over Rational Field\n sage: C.dual().super_categories() # indirect doctest\n [Category of algebras over Rational Field,\n Category of duals of vector spaces over Rational Field]\n\n .. WARNING::\n\n This is only correct in certain cases (finite dimension, ...).\n See :trac:`15647`.\n ' from sage.categories.algebras import Algebras return [Algebras(self.base_category().base_ring())] class Super(SuperModulesCategory): def extra_super_categories(self): '\n EXAMPLES::\n\n sage: Coalgebras(ZZ).Super().extra_super_categories()\n [Category of graded coalgebras over Integer Ring]\n sage: Coalgebras(ZZ).Super().super_categories()\n [Category of graded coalgebras over Integer Ring,\n Category of super modules over Integer Ring]\n\n Compare this with the situation for bialgebras::\n\n sage: Bialgebras(ZZ).Super().extra_super_categories()\n []\n sage: Bialgebras(ZZ).Super().super_categories()\n [Category of super algebras over Integer Ring,\n Category of super coalgebras over Integer Ring]\n\n The category of bialgebras does not occur in these results,\n since super bialgebras are not bialgebras.\n ' return [self.base_category().Graded()] class SubcategoryMethods(): @cached_method def Supercocommutative(self): '\n Return the full subcategory of the supercocommutative\n objects of ``self``.\n\n EXAMPLES::\n\n sage: Coalgebras(ZZ).WithBasis().Super().Supercocommutative()\n Category of supercocommutative super coalgebras with basis over Integer Ring\n sage: BialgebrasWithBasis(QQ).Super().Supercocommutative()\n Join of Category of super algebras with basis over Rational Field\n and Category of super bialgebras over Rational Field\n and Category of super coalgebras with basis over Rational Field\n and Category of supercocommutative super coalgebras over Rational Field\n\n TESTS::\n\n sage: TestSuite(HopfAlgebras(ZZ).Super().Supercocommutative()).run()\n ' return self._with_axiom('Supercocommutative') class Supercocommutative(CategoryWithAxiom_over_base_ring): '\n Category of supercocommutative coalgebras.\n ' class Filtered(FilteredModulesCategory): '\n Category of filtered coalgebras.\n ' class WithRealizations(WithRealizationsCategory): class ParentMethods(): def coproduct(self, x): "\n Return the coproduct of ``x``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: S = N.complete()\n sage: N.coproduct.__module__\n 'sage.categories.coalgebras'\n sage: N.coproduct(S[2])\n S[] # S[2] + S[1] # S[1] + S[2] # S[]\n " return self.a_realization()(x).coproduct() def counit(self, x): "\n Return the counit of ``x``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: Sym = SymmetricFunctions(QQ)\n sage: s = Sym.schur()\n sage: f = s[2,1]\n sage: f.counit.__module__\n 'sage.categories.coalgebras'\n sage: f.counit()\n 0\n\n ::\n\n sage: # needs sage.modules\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: N.counit.__module__\n 'sage.categories.coalgebras'\n sage: N.counit(N.one())\n 1\n sage: x = N.an_element(); x\n 2*S[] + 2*S[1] + 3*S[1, 1]\n sage: N.counit(x)\n 2\n " return self.a_realization()(x).counit() class Realizations(RealizationsCategory): class ParentMethods(): def coproduct_by_coercion(self, x): "\n Return the coproduct by coercion if ``coproduct_by_basis``\n is not implemented.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: Sym = SymmetricFunctions(QQ)\n sage: m = Sym.monomial()\n sage: f = m[2,1]\n sage: f.coproduct.__module__\n 'sage.categories.coalgebras'\n sage: m.coproduct_on_basis\n NotImplemented\n sage: m.coproduct == m.coproduct_by_coercion\n True\n sage: f.coproduct()\n m[] # m[2, 1] + m[1] # m[2] + m[2] # m[1] + m[2, 1] # m[]\n\n ::\n\n sage: # needs sage.modules\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: R = N.ribbon()\n sage: R.coproduct_by_coercion.__module__\n 'sage.categories.coalgebras'\n sage: R.coproduct_on_basis\n NotImplemented\n sage: R.coproduct == R.coproduct_by_coercion\n True\n sage: R[1].coproduct()\n R[] # R[1] + R[1] # R[]\n " R = self.realization_of().a_realization() return self.tensor_square()(R(x).coproduct()) def counit_by_coercion(self, x): '\n Return the counit of ``x`` if ``counit_by_basis`` is\n not implemented.\n\n EXAMPLES::\n\n sage: sp = SymmetricFunctions(QQ).sp() # needs sage.modules\n sage: sp.an_element() # needs sage.modules\n 2*sp[] + 2*sp[1] + 3*sp[2]\n sage: sp.counit(sp.an_element()) # needs sage.modules\n 2\n\n sage: o = SymmetricFunctions(QQ).o() # needs sage.modules\n sage: o.an_element() # needs sage.modules\n 2*o[] + 2*o[1] + 3*o[2]\n sage: o.counit(o.an_element()) # needs sage.modules\n -1\n ' R = self.realization_of().a_realization() return R(x).counit()
class CoalgebrasWithBasis(CategoryWithAxiom_over_base_ring): '\n The category of coalgebras with a distinguished basis.\n\n EXAMPLES::\n\n sage: CoalgebrasWithBasis(ZZ)\n Category of coalgebras with basis over Integer Ring\n sage: sorted(CoalgebrasWithBasis(ZZ).super_categories(), key=str)\n [Category of coalgebras over Integer Ring,\n Category of modules with basis over Integer Ring]\n\n TESTS::\n\n sage: TestSuite(CoalgebrasWithBasis(ZZ)).run()\n ' Graded = LazyImport('sage.categories.graded_coalgebras_with_basis', 'GradedCoalgebrasWithBasis') class Filtered(FilteredModulesCategory): '\n Category of filtered coalgebras.\n ' class ParentMethods(): @abstract_method(optional=True) def coproduct_on_basis(self, i): '\n The coproduct of the algebra on the basis (optional).\n\n INPUT:\n\n - ``i`` -- the indices of an element of the basis of ``self``\n\n Returns the coproduct of the corresponding basis elements\n If implemented, the coproduct of the algebra is defined\n from it by linearity.\n\n EXAMPLES::\n\n sage: A = HopfAlgebrasWithBasis(QQ).example(); A # needs sage.groups sage.modules\n An example of Hopf algebra with basis:\n the group algebra of the Dihedral group of order 6\n as a permutation group over Rational Field\n sage: (a, b) = A._group.gens() # needs sage.groups sage.modules\n sage: A.coproduct_on_basis(a) # needs sage.groups sage.modules\n B[(1,2,3)] # B[(1,2,3)]\n ' @lazy_attribute def coproduct(self): '\n If :meth:`coproduct_on_basis` is available, construct the\n coproduct morphism from ``self`` to ``self`` `\\otimes`\n ``self`` by extending it by linearity. Otherwise, use\n :meth:`~Coalgebras.Realizations.ParentMethods.coproduct_by_coercion`,\n if available.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: A = HopfAlgebrasWithBasis(QQ).example(); A\n An example of Hopf algebra with basis:\n the group algebra of the Dihedral group of order 6\n as a permutation group over Rational Field\n sage: a, b = A.algebra_generators()\n sage: a, A.coproduct(a)\n (B[(1,2,3)], B[(1,2,3)] # B[(1,2,3)])\n sage: b, A.coproduct(b)\n (B[(1,3)], B[(1,3)] # B[(1,3)])\n\n ' if (self.coproduct_on_basis is not NotImplemented): return Hom(self, tensor([self, self]), ModulesWithBasis(self.base_ring()))(on_basis=self.coproduct_on_basis) elif hasattr(self, 'coproduct_by_coercion'): return self.coproduct_by_coercion @abstract_method(optional=True) def counit_on_basis(self, i): '\n The counit of the algebra on the basis (optional).\n\n INPUT:\n\n - ``i`` -- the indices of an element of the basis of ``self``\n\n Returns the counit of the corresponding basis elements\n If implemented, the counit of the algebra is defined\n from it by linearity.\n\n EXAMPLES::\n\n sage: A = HopfAlgebrasWithBasis(QQ).example(); A # needs sage.groups sage.modules\n An example of Hopf algebra with basis:\n the group algebra of the Dihedral group of order 6\n as a permutation group over Rational Field\n sage: (a, b) = A._group.gens() # needs sage.groups sage.modules\n sage: A.counit_on_basis(a) # needs sage.groups sage.modules\n 1\n ' @lazy_attribute def counit(self): '\n If :meth:`counit_on_basis` is available, construct the\n counit morphism from ``self`` to ``self`` `\\otimes`\n ``self`` by extending it by linearity\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: A = HopfAlgebrasWithBasis(QQ).example(); A\n An example of Hopf algebra with basis:\n the group algebra of the Dihedral group of order 6\n as a permutation group over Rational Field\n sage: a, b = A.algebra_generators()\n sage: a, A.counit(a)\n (B[(1,2,3)], 1)\n sage: b, A.counit(b)\n (B[(1,3)], 1)\n\n ' if (self.counit_on_basis is not NotImplemented): return self.module_morphism(self.counit_on_basis, codomain=self.base_ring()) elif hasattr(self, 'counit_by_coercion'): return self.counit_by_coercion class ElementMethods(): def coproduct_iterated(self, n=1): '\n Apply ``n`` coproducts to ``self``.\n\n .. TODO::\n\n Remove dependency on ``modules_with_basis`` methods.\n\n EXAMPLES::\n\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi() # needs sage.combinat sage.modules\n sage: Psi[2,2].coproduct_iterated(0) # needs sage.combinat sage.modules\n Psi[2, 2]\n sage: Psi[2,2].coproduct_iterated(2) # needs sage.combinat sage.modules\n Psi[] # Psi[] # Psi[2, 2] + 2*Psi[] # Psi[2] # Psi[2]\n + Psi[] # Psi[2, 2] # Psi[] + 2*Psi[2] # Psi[] # Psi[2]\n + 2*Psi[2] # Psi[2] # Psi[] + Psi[2, 2] # Psi[] # Psi[]\n\n TESTS::\n\n sage: p = SymmetricFunctions(QQ).p() # needs sage.combinat sage.modules\n sage: p[5,2,2].coproduct_iterated() # needs sage.combinat sage.modules\n p[] # p[5, 2, 2] + 2*p[2] # p[5, 2] + p[2, 2] # p[5]\n + p[5] # p[2, 2] + 2*p[5, 2] # p[2] + p[5, 2, 2] # p[]\n sage: p([]).coproduct_iterated(3) # needs sage.combinat sage.modules\n p[] # p[] # p[] # p[]\n\n ::\n\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi() # needs sage.combinat sage.modules\n sage: Psi[2,2].coproduct_iterated(0) # needs sage.combinat sage.modules\n Psi[2, 2]\n sage: Psi[2,2].coproduct_iterated(3) # needs sage.combinat sage.modules\n Psi[] # Psi[] # Psi[] # Psi[2, 2] + 2*Psi[] # Psi[] # Psi[2] # Psi[2]\n + Psi[] # Psi[] # Psi[2, 2] # Psi[] + 2*Psi[] # Psi[2] # Psi[] # Psi[2]\n + 2*Psi[] # Psi[2] # Psi[2] # Psi[] + Psi[] # Psi[2, 2] # Psi[] # Psi[]\n + 2*Psi[2] # Psi[] # Psi[] # Psi[2] + 2*Psi[2] # Psi[] # Psi[2] # Psi[]\n + 2*Psi[2] # Psi[2] # Psi[] # Psi[] + Psi[2, 2] # Psi[] # Psi[] # Psi[]\n\n ::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m() # needs sage.combinat sage.modules\n sage: m[[1,3],[2]].coproduct_iterated(2) # needs sage.combinat sage.modules\n m{} # m{} # m{{1, 3}, {2}} + m{} # m{{1}} # m{{1, 2}}\n + m{} # m{{1, 2}} # m{{1}} + m{} # m{{1, 3}, {2}} # m{}\n + m{{1}} # m{} # m{{1, 2}} + m{{1}} # m{{1, 2}} # m{}\n + m{{1, 2}} # m{} # m{{1}} + m{{1, 2}} # m{{1}} # m{}\n + m{{1, 3}, {2}} # m{} # m{}\n sage: m[[]].coproduct_iterated(3), m[[1,3],[2]].coproduct_iterated(0) # needs sage.combinat sage.modules\n (m{} # m{} # m{} # m{}, m{{1, 3}, {2}})\n ' if (n < 0): raise ValueError(('cannot take fewer than 0 coproduct iterations: %s < 0' % str(n))) if (n == 0): return self if (n == 1): return self.coproduct() from sage.rings.integer import Integer fn = (Integer((n - 1)) // 2) cn = ((Integer((n - 1)) // 2) if (n % 2) else (Integer(n) // 2)) split = (lambda a, b: tensor([a.coproduct_iterated(fn), b.coproduct_iterated(cn)])) return self.coproduct().apply_multilinear_morphism(split) class Super(SuperModulesCategory): def extra_super_categories(self): '\n EXAMPLES::\n\n sage: C = Coalgebras(ZZ).WithBasis().Super()\n sage: sorted(C.super_categories(), key=str) # indirect doctest\n [Category of graded coalgebras with basis over Integer Ring,\n Category of super coalgebras over Integer Ring,\n Category of super modules with basis over Integer Ring]\n ' return [self.base_category().Graded()]
class CommutativeAdditiveGroups(CategoryWithAxiom, AbelianCategory): "\n The category of abelian groups, i.e. additive abelian monoids\n where each element has an inverse.\n\n EXAMPLES::\n\n sage: C = CommutativeAdditiveGroups(); C\n Category of commutative additive groups\n sage: C.super_categories()\n [Category of additive groups, Category of commutative additive monoids]\n sage: sorted(C.axioms())\n ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse', 'AdditiveUnital']\n sage: C is CommutativeAdditiveMonoids().AdditiveInverse()\n True\n sage: from sage.categories.additive_groups import AdditiveGroups\n sage: C is AdditiveGroups().AdditiveCommutative()\n True\n\n .. NOTE::\n\n This category is currently empty. It's left there for backward\n compatibility and because it is likely to grow in the future.\n\n TESTS::\n\n sage: TestSuite(CommutativeAdditiveGroups()).run()\n sage: sorted(CommutativeAdditiveGroups().CartesianProducts().axioms())\n ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse', 'AdditiveUnital']\n\n The empty covariant functorial construction category classes\n ``CartesianProducts`` and ``Algebras`` are left here for the sake\n of nicer output since this is a commonly used category::\n\n sage: CommutativeAdditiveGroups().CartesianProducts()\n Category of Cartesian products of commutative additive groups\n sage: CommutativeAdditiveGroups().Algebras(QQ)\n Category of commutative additive group algebras over Rational Field\n\n Also, it's likely that some code will end up there at some point.\n " _base_category_class_and_axiom = (AdditiveGroups, 'AdditiveCommutative') class CartesianProducts(CartesianProductsCategory): class ElementMethods(): def additive_order(self): '\n Return the additive order of this element.\n\n EXAMPLES::\n\n sage: G = cartesian_product([Zmod(3), Zmod(6), Zmod(5)])\n sage: G((1,1,1)).additive_order()\n 30\n sage: any((i * G((1,1,1))).is_zero() for i in range(1,30))\n False\n sage: 30 * G((1,1,1))\n (0, 0, 0)\n\n sage: G = cartesian_product([ZZ, ZZ])\n sage: G((0,0)).additive_order()\n 1\n sage: G((0,1)).additive_order()\n +Infinity\n\n sage: # needs sage.rings.finite_rings\n sage: K = GF(9)\n sage: H = cartesian_product([\n ....: cartesian_product([Zmod(2), Zmod(9)]), K])\n sage: z = H(((1,2), K.gen()))\n sage: z.additive_order()\n 18\n ' from sage.rings.infinity import Infinity orders = [x.additive_order() for x in self.cartesian_factors()] if any(((o is Infinity) for o in orders)): return Infinity else: from sage.arith.functions import LCM_list return LCM_list(orders) class Algebras(AlgebrasCategory): pass
class CommutativeAdditiveMonoids(CategoryWithAxiom): "\n The category of commutative additive monoids, that is abelian\n additive semigroups with a unit\n\n EXAMPLES::\n\n sage: C = CommutativeAdditiveMonoids(); C\n Category of commutative additive monoids\n sage: C.super_categories()\n [Category of additive monoids, Category of commutative additive semigroups]\n sage: sorted(C.axioms())\n ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveUnital']\n sage: C is AdditiveMagmas().AdditiveAssociative().AdditiveCommutative().AdditiveUnital()\n True\n\n .. NOTE::\n\n This category is currently empty and only serves as a place\n holder to make ``C.example()`` work.\n\n TESTS::\n\n sage: TestSuite(CommutativeAdditiveMonoids()).run()\n " _base_category_class_and_axiom = (AdditiveMonoids, 'AdditiveCommutative')
class CommutativeAdditiveSemigroups(CategoryWithAxiom): "\n The category of additive abelian semigroups, i.e. sets with an\n associative and abelian operation +.\n\n EXAMPLES::\n\n sage: C = CommutativeAdditiveSemigroups(); C\n Category of commutative additive semigroups\n sage: C.example()\n An example of a commutative semigroup: the free commutative semigroup generated by ('a', 'b', 'c', 'd')\n\n sage: sorted(C.super_categories(), key=str)\n [Category of additive commutative additive magmas,\n Category of additive semigroups]\n sage: sorted(C.axioms())\n ['AdditiveAssociative', 'AdditiveCommutative']\n sage: C is AdditiveMagmas().AdditiveAssociative().AdditiveCommutative()\n True\n\n .. NOTE::\n\n This category is currently empty and only serves as a place\n holder to make ``C.example()`` work.\n\n TESTS::\n\n sage: TestSuite(C).run()\n " _base_category_class_and_axiom = (AdditiveSemigroups, 'AdditiveCommutative')
class CommutativeAlgebraIdeals(Category_ideal): "\n The category of ideals in a fixed commutative algebra `A`.\n\n EXAMPLES::\n\n sage: C = CommutativeAlgebraIdeals(QQ['x'])\n sage: C\n Category of commutative algebra ideals in\n Univariate Polynomial Ring in x over Rational Field\n " def __init__(self, A): "\n EXAMPLES::\n\n sage: CommutativeAlgebraIdeals(ZZ['x'])\n Category of commutative algebra ideals in\n Univariate Polynomial Ring in x over Integer Ring\n\n sage: CommutativeAlgebraIdeals(ZZ)\n Traceback (most recent call last):\n ...\n TypeError: A (=Integer Ring) must be a commutative algebra\n\n sage: CommutativeAlgebraIdeals(IntegerModRing(4))\n Traceback (most recent call last):\n ...\n TypeError: A (=Ring of integers modulo 4) must be a commutative algebra\n\n sage: CommutativeAlgebraIdeals(Partitions(4)) # needs sage.combinat\n Traceback (most recent call last):\n ...\n TypeError: A (=Partitions of the integer 4) must be a commutative algebra\n\n TESTS::\n\n sage: TestSuite(CommutativeAlgebraIdeals(QQ['x'])).run()\n " try: base_ring = A.base_ring() except AttributeError: raise TypeError(f'A (={A}) must be a commutative algebra') else: if ((base_ring not in CommutativeRings()) or (A not in CommutativeAlgebras(base_ring.category()))): raise TypeError(f'A (={A}) must be a commutative algebra') Category_in_ambient.__init__(self, A) def algebra(self): "\n EXAMPLES::\n\n sage: CommutativeAlgebraIdeals(QQ['x']).algebra()\n Univariate Polynomial Ring in x over Rational Field\n " return self.ambient() def super_categories(self): "\n EXAMPLES::\n\n sage: CommutativeAlgebraIdeals(QQ['x']).super_categories()\n [Category of algebra ideals in Univariate Polynomial Ring in x over Rational Field]\n " R = self.algebra() return [AlgebraIdeals(R)]
class CommutativeAlgebras(CategoryWithAxiom_over_base_ring): '\n The category of commutative algebras with unit over a given base ring.\n\n EXAMPLES::\n\n sage: M = CommutativeAlgebras(GF(19))\n sage: M\n Category of commutative algebras over Finite Field of size 19\n sage: CommutativeAlgebras(QQ).super_categories()\n [Category of algebras over Rational Field, Category of commutative rings]\n\n This is just a shortcut for::\n\n sage: Algebras(QQ).Commutative()\n Category of commutative algebras over Rational Field\n\n TESTS::\n\n sage: Algebras(QQ).Commutative() is CommutativeAlgebras(QQ)\n True\n sage: TestSuite(CommutativeAlgebras(ZZ)).run()\n\n .. TODO::\n\n - product ( = Cartesian product)\n - coproduct ( = tensor product over base ring)\n ' def __contains__(self, A): "\n EXAMPLES::\n\n sage: QQ['a'] in CommutativeAlgebras(QQ)\n True\n sage: QQ['a,b'] in CommutativeAlgebras(QQ)\n True\n sage: FreeAlgebra(QQ, 2, 'a,b') in CommutativeAlgebras(QQ) # needs sage.combinat sage.modules\n False\n\n TODO: get rid of this method once all commutative algebras in\n Sage declare themselves in this category\n " return (super().__contains__(A) or ((A in Algebras(self.base_ring())) and hasattr(A, 'is_commutative') and A.is_commutative())) class TensorProducts(TensorProductsCategory): '\n The category of commutative algebras constructed by tensor product of commutative algebras.\n ' @cached_method def extra_super_categories(self): "\n EXAMPLES::\n\n sage: Algebras(QQ).Commutative().TensorProducts().extra_super_categories()\n [Category of commutative rings]\n sage: Algebras(QQ).Commutative().TensorProducts().super_categories()\n [Category of tensor products of algebras over Rational Field,\n Category of commutative algebras over Rational Field]\n\n TESTS::\n\n sage: # needs sage.combinat sage.modules\n sage: X = algebras.Shuffle(QQ, 'ab')\n sage: Y = algebras.Shuffle(QQ, 'bc')\n sage: X in Algebras(QQ).Commutative()\n True\n sage: T = tensor([X, Y])\n sage: T in CommutativeRings()\n True\n " return [CommutativeRings()]
class CommutativeRingIdeals(Category_ideal): '\n The category of ideals in a fixed commutative ring.\n\n EXAMPLES::\n\n sage: C = CommutativeRingIdeals(IntegerRing())\n sage: C\n Category of commutative ring ideals in Integer Ring\n ' def __init__(self, R): '\n EXAMPLES::\n\n sage: CommutativeRingIdeals(ZZ)\n Category of commutative ring ideals in Integer Ring\n sage: CommutativeRingIdeals(IntegerModRing(4))\n Category of commutative ring ideals in Ring of integers modulo 4\n\n TESTS::\n\n sage: CommutativeRingIdeals(Partitions(4)) # needs sage.combinat\n Traceback (most recent call last):\n ...\n TypeError: R (=Partitions of the integer 4) must be a commutative ring\n sage: TestSuite(CommutativeRingIdeals(ZZ)).run()\n ' if (R not in CommutativeRings()): raise TypeError(('R (=%s) must be a commutative ring' % R)) Category_ideal.__init__(self, R) def super_categories(self): '\n EXAMPLES::\n\n sage: CommutativeRingIdeals(ZZ).super_categories()\n [Category of ring ideals in Integer Ring]\n ' R = self.ring() return [RingIdeals(R)]
class CommutativeRings(CategoryWithAxiom): "\n The category of commutative rings\n\n commutative rings with unity, i.e. rings with commutative * and\n a multiplicative identity\n\n EXAMPLES::\n\n sage: C = CommutativeRings(); C\n Category of commutative rings\n sage: C.super_categories()\n [Category of rings, Category of commutative monoids]\n\n TESTS::\n\n sage: TestSuite(C).run()\n\n sage: QQ['x,y,z'] in CommutativeRings()\n True\n sage: GroupAlgebra(DihedralGroup(3), QQ) in CommutativeRings() # needs sage.groups sage.modules\n False\n sage: MatrixSpace(QQ, 2, 2) in CommutativeRings() # needs sage.modules\n False\n\n GroupAlgebra should be fixed::\n\n sage: GroupAlgebra(CyclicPermutationGroup(3), QQ) in CommutativeRings() # not implemented, needs sage.groups sage.modules\n True\n\n " class ParentMethods(): def _test_divides(self, **options): '\n Run generic tests on the method :meth:`divides`.\n\n EXAMPLES::\n\n sage: ZZ._test_divides()\n ' tester = self._tester(**options) a = self.an_element() try: a.divides except AttributeError: return z = self.zero() o = self.one() tester.assertTrue(z.divides(z)) tester.assertTrue(o.divides(o)) tester.assertTrue(o.divides(z)) tester.assertIs(z.divides(o), self.is_zero()) if (not self.is_exact()): return for (a, b) in tester.some_elements(repeat=2): try: test = a.divides((a * b)) except NotImplementedError: pass else: tester.assertTrue(test) def over(self, base=None, gen=None, gens=None, name=None, names=None): "\n Return this ring, considered as an extension of ``base``.\n\n INPUT:\n\n - ``base`` -- a commutative ring or a morphism or ``None``\n (default: ``None``); the base of this extension or its defining\n morphism\n\n - ``gen`` -- a generator of this extension (over its base) or ``None``\n (default: ``None``);\n\n - ``gens`` -- a list of generators of this extension (over its base)\n or ``None`` (default: ``None``);\n\n - ``name`` -- a variable name or ``None`` (default: ``None``)\n\n - ``names`` -- a list or a tuple of variable names or ``None``\n (default: ``None``)\n\n EXAMPLES:\n\n We construct an extension of finite fields::\n\n sage: # needs sage.rings.finite_rings\n sage: F = GF(5^2)\n sage: k = GF(5^4)\n sage: z4 = k.gen()\n sage: K = k.over(F); K # needs sage.modules\n Field in z4 with defining polynomial\n x^2 + (4*z2 + 3)*x + z2 over its base\n\n If not explicitly given, the default generator of the top ring\n (here k) is used and the same name is kept::\n\n sage: K.gen() # needs sage.modules sage.rings.finite_rings\n z4\n sage: K(z4) # needs sage.modules sage.rings.finite_rings\n z4\n\n However, it is possible to specify another generator and/or\n another name. For example::\n\n sage: # needs sage.modules sage.rings.finite_rings\n sage: Ka = k.over(F, name='a'); Ka\n Field in a with defining polynomial\n x^2 + (4*z2 + 3)*x + z2 over its base\n sage: Ka.gen()\n a\n sage: Ka(z4)\n a\n\n sage: # needs sage.modules sage.rings.finite_rings\n sage: Kb = k.over(F, gen=-z4+1, name='b')\n sage: Kb\n Field in b with defining polynomial x^2 + z2*x + 4 over its base\n sage: Kb.gen()\n b\n sage: Kb(-z4+1)\n b\n\n Note that the shortcut ``K.<a>`` is also available::\n\n sage: KKa.<a> = k.over(F) # needs sage.modules sage.rings.finite_rings\n sage: KKa is Ka # needs sage.modules sage.rings.finite_rings\n True\n\n Building an extension on top of another extension is allowed::\n\n sage: L = GF(5^12).over(K); L # needs sage.modules sage.rings.finite_rings\n Field in z12 with defining polynomial\n x^3 + (1 + (4*z2 + 2)*z4)*x^2 + (2 + 2*z4)*x - z4 over its base\n sage: L.base_ring() # needs sage.modules sage.rings.finite_rings\n Field in z4 with defining polynomial\n x^2 + (4*z2 + 3)*x + z2 over its base\n\n The successive bases of an extension are accessible via the\n method :meth:`sage.rings.ring_extension.RingExtension_generic.bases`::\n\n sage: L.bases() # needs sage.modules sage.rings.finite_rings\n [Field in z12 with defining polynomial\n x^3 + (1 + (4*z2 + 2)*z4)*x^2 + (2 + 2*z4)*x - z4 over its base,\n Field in z4 with defining polynomial\n x^2 + (4*z2 + 3)*x + z2 over its base,\n Finite Field in z2 of size 5^2]\n\n When ``base`` is omitted, the canonical base of the ring is used::\n\n sage: S.<x> = QQ[]\n sage: E = S.over(); E # needs sage.modules\n Univariate Polynomial Ring in x over Rational Field over its base\n sage: E.base_ring() # needs sage.modules\n Rational Field\n\n Here is an example where ``base`` is a defining morphism::\n\n sage: # needs sage.modules sage.rings.number_field\n sage: k.<a> = QQ.extension(x^2 - 2)\n sage: l.<b> = QQ.extension(x^4 - 2)\n sage: f = k.hom([b^2])\n sage: L = l.over(f)\n sage: L\n Field in b with defining polynomial x^2 - a over its base\n sage: L.base_ring()\n Number Field in a with defining polynomial x^2 - 2\n\n Similarly, one can create a tower of extensions::\n\n sage: # needs sage.modules sage.rings.number_field\n sage: K = k.over()\n sage: L = l.over(Hom(K, l)(f)); L\n Field in b with defining polynomial x^2 - a over its base\n sage: L.base_ring()\n Field in a with defining polynomial x^2 - 2 over its base\n sage: L.bases()\n [Field in b with defining polynomial x^2 - a over its base,\n Field in a with defining polynomial x^2 - 2 over its base,\n Rational Field]\n " from sage.rings.ring_extension import RingExtension if (name is not None): if (names is not None): raise ValueError("keyword argument 'name' cannot be combined with 'names'") names = (name,) if (gen is not None): if (gens is not None): raise ValueError("keyword argument 'gen' cannot be combined with 'gens'") gens = (gen,) return RingExtension(self, base, gens, names) class ElementMethods(): pass class Finite(CategoryWithAxiom): '\n Check that Sage knows that Cartesian products of finite commutative\n rings is a finite commutative ring.\n\n EXAMPLES::\n\n sage: cartesian_product([Zmod(34),\n ....: GF(5)]) in Rings().Commutative().Finite()\n True\n ' class ParentMethods(): def cyclotomic_cosets(self, q, cosets=None): "\n Return the (multiplicative) orbits of ``q`` in the ring.\n\n Let `R` be a finite commutative ring. The group of invertible\n elements `R^*` in `R` gives rise to a group action on `R` by\n multiplication. An orbit of the subgroup generated by an\n invertible element `q` is called a `q`-*cyclotomic coset* (since\n in a finite ring, each invertible element is a root of unity).\n\n These cosets arise in the theory of minimal polynomials of\n finite fields, duadic codes and combinatorial designs. Fix a\n primitive element `z` of `GF(q^k)`. The minimal polynomial of\n `z^s` over `GF(q)` is given by\n\n .. MATH::\n\n M_s(x) = \\prod_{i \\in C_s} (x - z^i),\n\n\n where `C_s` is the `q`-cyclotomic coset mod `n` containing `s`,\n `n = q^k - 1`.\n\n .. NOTE::\n\n When `R = \\ZZ / n \\ZZ` the smallest element of each coset is\n sometimes called a *coset leader*. This function returns\n sorted lists so that the coset leader will always be the\n first element of the coset.\n\n INPUT:\n\n - ``q`` -- an invertible element of the ring\n\n - ``cosets`` -- an optional lists of elements of ``self``. If\n provided, the function only return the list of cosets that\n contain some element from ``cosets``.\n\n OUTPUT:\n\n A list of lists.\n\n EXAMPLES::\n\n sage: Zmod(11).cyclotomic_cosets(2)\n [[0], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]\n sage: Zmod(15).cyclotomic_cosets(2)\n [[0], [1, 2, 4, 8], [3, 6, 9, 12], [5, 10], [7, 11, 13, 14]]\n\n Since the group of invertible elements of a finite field is\n cyclic, the set of squares is a particular case of cyclotomic\n coset::\n\n sage: # needs sage.rings.finite_rings\n sage: K = GF(25, 'z')\n sage: a = K.multiplicative_generator()\n sage: K.cyclotomic_cosets(a**2, cosets=[1])\n [[1, 2, 3, 4, z + 1, z + 3,\n 2*z + 1, 2*z + 2, 3*z + 3,\n 3*z + 4, 4*z + 2, 4*z + 4]]\n sage: sorted(b for b in K if not b.is_zero() and b.is_square())\n [1, 2, 3, 4, z + 1, z + 3,\n 2*z + 1, 2*z + 2, 3*z + 3,\n 3*z + 4, 4*z + 2, 4*z + 4]\n\n We compute some examples of minimal polynomials::\n\n sage: # needs sage.rings.finite_rings\n sage: K = GF(27, 'z')\n sage: a = K.multiplicative_generator()\n sage: R.<X> = PolynomialRing(K, 'X')\n sage: a.minimal_polynomial('X')\n X^3 + 2*X + 1\n\n sage: cyc3 = Zmod(26).cyclotomic_cosets(3, cosets=[1]); cyc3\n [[1, 3, 9]]\n sage: prod(X - a**i for i in cyc3[0]) # needs sage.rings.finite_rings\n X^3 + 2*X + 1\n sage: (a**7).minimal_polynomial('X') # needs sage.rings.finite_rings\n X^3 + X^2 + 2*X + 1\n sage: cyc7 = Zmod(26).cyclotomic_cosets(3, cosets=[7]); cyc7\n [[7, 11, 21]]\n sage: prod(X - a**i for i in cyc7[0]) # needs sage.rings.finite_rings\n X^3 + X^2 + 2*X + 1\n\n Cyclotomic cosets of fields are useful in combinatorial design\n theory to provide so called difference families (see\n :wikipedia:`Difference_set` and\n :mod:`~sage.combinat.designs.difference_family`). This is\n illustrated on the following examples::\n\n sage: K = GF(5)\n sage: a = K.multiplicative_generator() # needs sage.libs.pari\n sage: H = K.cyclotomic_cosets(a**2, cosets=[1, 2]); H # needs sage.rings.finite_rings\n [[1, 4], [2, 3]]\n sage: sorted(x - y for D in H for x in D for y in D if x != y) # needs sage.rings.finite_rings\n [1, 2, 3, 4]\n\n sage: K = GF(37)\n sage: a = K.multiplicative_generator() # needs sage.libs.pari\n sage: H = K.cyclotomic_cosets(a**4, cosets=[1]); H # needs sage.rings.finite_rings\n [[1, 7, 9, 10, 12, 16, 26, 33, 34]]\n sage: sorted(x - y for D in H for x in D for y in D if x != y) # needs sage.rings.finite_rings\n [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, ..., 33, 34, 34, 35, 35, 36, 36]\n\n The method ``cyclotomic_cosets`` works on any finite commutative\n ring::\n\n sage: R = cartesian_product([GF(7), Zmod(14)])\n sage: a = R((3,5))\n sage: R.cyclotomic_cosets((3,5), [(1,1)])\n [[(1, 1), (2, 11), (3, 5), (4, 9), (5, 3), (6, 13)]]\n " q = self(q) try: (~ q) except ZeroDivisionError: raise ValueError(('%s is not invertible in %s' % (q, self))) if (cosets is None): rest = set(self) else: rest = {self(x) for x in cosets} orbits = [] while rest: x0 = rest.pop() o = [x0] x = (q * x0) while (x != x0): o.append(x) rest.discard(x) x *= q o.sort() orbits.append(o) orbits.sort() return orbits class CartesianProducts(CartesianProductsCategory): def extra_super_categories(self): '\n Let Sage knows that Cartesian products of commutative rings is a\n commutative ring.\n\n EXAMPLES::\n\n sage: CommutativeRings().Commutative().CartesianProducts().extra_super_categories()\n [Category of commutative rings]\n sage: cartesian_product([ZZ, Zmod(34),\n ....: QQ, GF(5)]) in CommutativeRings()\n True\n ' return [CommutativeRings()]
class CompleteDiscreteValuationRings(Category_singleton): "\n The category of complete discrete valuation rings\n\n EXAMPLES::\n\n sage: Zp(7) in CompleteDiscreteValuationRings() # needs sage.rings.padics\n True\n sage: QQ in CompleteDiscreteValuationRings()\n False\n sage: QQ[['u']] in CompleteDiscreteValuationRings()\n True\n sage: Qp(7) in CompleteDiscreteValuationRings() # needs sage.rings.padics\n False\n sage: TestSuite(CompleteDiscreteValuationRings()).run()\n " def super_categories(self): '\n EXAMPLES::\n\n sage: CompleteDiscreteValuationRings().super_categories()\n [Category of discrete valuation rings]\n ' return [DiscreteValuationRings()] class ElementMethods(): @abstract_method def valuation(self): '\n Return the valuation of this element.\n\n EXAMPLES::\n\n sage: R = Zp(7) # needs sage.rings.padics\n sage: x = R(7); x # needs sage.rings.padics\n 7 + O(7^21)\n sage: x.valuation() # needs sage.rings.padics\n 1\n ' def denominator(self): '\n Return the denominator of this element normalized\n as a power of the uniformizer\n\n EXAMPLES::\n\n sage: # needs sage.rings.padics\n sage: K = Qp(7)\n sage: x = K(1/21)\n sage: x.denominator()\n 7 + O(7^21)\n sage: x = K(7)\n sage: x.denominator()\n 1 + O(7^20)\n\n Note that the denominator lives in the ring of integers::\n\n sage: x.denominator().parent() # needs sage.rings.padics\n 7-adic Ring with capped relative precision 20\n\n When the denominator is indistinguishable from 0 and the\n precision on the input is `O(p^n)`, the return value is `1`\n if `n` is nonnegative and `p^(-n)` otherwise::\n\n sage: # needs sage.rings.padics\n sage: x = K(0, 5); x\n O(7^5)\n sage: x.denominator()\n 1 + O(7^20)\n sage: x = K(0, -5); x\n O(7^-5)\n sage: x.denominator()\n 7^5 + O(7^25)\n ' return self.parent()(1) def numerator(self): '\n Return the numerator of this element, normalized in such a\n way that `x = x.numerator() / x.denominator()` always holds\n true.\n\n EXAMPLES::\n\n sage: # needs sage.rings.padics\n sage: K = Qp(7, 5)\n sage: x = K(1/21)\n sage: x.numerator()\n 5 + 4*7 + 4*7^2 + 4*7^3 + 4*7^4 + O(7^5)\n sage: x == x.numerator() / x.denominator()\n True\n\n Note that the numerator lives in the ring of integers::\n\n sage: x.numerator().parent() # needs sage.rings.padics\n 7-adic Ring with capped relative precision 5\n\n TESTS::\n\n sage: x = K(0, -5); x # needs sage.rings.padics\n O(7^-5)\n sage: x.numerator() # needs sage.rings.padics\n O(7^0)\n sage: x.denominator() # needs sage.rings.padics\n 7^5 + O(7^10)\n ' return self @abstract_method def lift_to_precision(self, absprec=None): '\n Return another element of the same parent with absolute precision\n at least ``absprec``, congruent to this element modulo the\n precision of this element.\n\n INPUT:\n\n - ``absprec`` -- an integer or ``None`` (default: ``None``), the\n absolute precision of the result. If ``None``, lifts to the maximum\n precision allowed.\n\n .. NOTE::\n\n If setting ``absprec`` that high would violate the precision cap,\n raises a precision error. Note that the new digits will not\n necessarily be zero.\n\n EXAMPLES::\n\n sage: # needs sage.rings.padics\n sage: R = ZpCA(17)\n sage: R(-1, 2).lift_to_precision(10)\n 16 + 16*17 + O(17^10)\n sage: R(1, 15).lift_to_precision(10)\n 1 + O(17^15)\n sage: R(1, 15).lift_to_precision(30)\n Traceback (most recent call last):\n ...\n PrecisionError: precision higher than allowed by the precision cap\n sage: (R(-1, 2).lift_to_precision().precision_absolute()\n ....: == R.precision_cap())\n True\n\n sage: R = Zp(5); c = R(17, 3); c.lift_to_precision(8) # needs sage.rings.padics\n 2 + 3*5 + O(5^8)\n sage: c.lift_to_precision().precision_relative() == R.precision_cap() # needs sage.rings.padics\n True\n\n '
class CompleteDiscreteValuationFields(Category_singleton): "\n The category of complete discrete valuation fields\n\n EXAMPLES::\n\n sage: Zp(7) in CompleteDiscreteValuationFields() # needs sage.rings.padics\n False\n sage: QQ in CompleteDiscreteValuationFields()\n False\n sage: LaurentSeriesRing(QQ, 'u') in CompleteDiscreteValuationFields()\n True\n sage: Qp(7) in CompleteDiscreteValuationFields() # needs sage.rings.padics\n True\n sage: TestSuite(CompleteDiscreteValuationFields()).run()\n " def super_categories(self): '\n EXAMPLES::\n\n sage: CompleteDiscreteValuationFields().super_categories()\n [Category of discrete valuation fields]\n ' return [DiscreteValuationFields()] class ElementMethods(): @abstract_method def valuation(self): '\n Return the valuation of this element.\n\n EXAMPLES::\n\n sage: K = Qp(7) # needs sage.rings.padics\n sage: x = K(7); x # needs sage.rings.padics\n 7 + O(7^21)\n sage: x.valuation() # needs sage.rings.padics\n 1\n ' def denominator(self): '\n Return the denominator of this element normalized\n as a power of the uniformizer\n\n EXAMPLES::\n\n sage: # needs sage.rings.padics\n sage: K = Qp(7)\n sage: x = K(1/21)\n sage: x.denominator()\n 7 + O(7^21)\n sage: x = K(7)\n sage: x.denominator()\n 1 + O(7^20)\n\n Note that the denominator lives in the ring of integers::\n\n sage: x.denominator().parent() # needs sage.rings.padics\n 7-adic Ring with capped relative precision 20\n\n When the denominator is indistinguishable from 0 and the\n precision on the input is `O(p^n)`, the return value is `1`\n if `n` is nonnegative and `p^(-n)` otherwise::\n\n sage: # needs sage.rings.padics\n sage: x = K(0, 5); x\n O(7^5)\n sage: x.denominator()\n 1 + O(7^20)\n sage: x = K(0, -5); x\n O(7^-5)\n sage: x.denominator()\n 7^5 + O(7^25)\n ' val = self.valuation() R = self.parent().integer_ring() if (val >= 0): return R(1) else: return (R(1) << (- val)) def numerator(self): '\n Return the numerator of this element, normalized in such a\n way that `x = x.numerator() / x.denominator()` always holds\n true.\n\n EXAMPLES::\n\n sage: # needs sage.rings.padics\n sage: K = Qp(7, 5)\n sage: x = K(1/21)\n sage: x.numerator()\n 5 + 4*7 + 4*7^2 + 4*7^3 + 4*7^4 + O(7^5)\n sage: x == x.numerator() / x.denominator()\n True\n\n Note that the numerator lives in the ring of integers::\n\n sage: x.numerator().parent() # needs sage.rings.padics\n 7-adic Ring with capped relative precision 5\n\n TESTS::\n\n sage: x = K(0, -5); x # needs sage.rings.padics\n O(7^-5)\n sage: x.numerator() # needs sage.rings.padics\n O(7^0)\n sage: x.denominator() # needs sage.rings.padics\n 7^5 + O(7^10)\n ' R = self.parent().integer_ring() return R((self * self.denominator()))
class ComplexReflectionGroups(Category_singleton): '\n The category of complex reflection groups.\n\n Let `V` be a complex vector space. A *complex reflection* is an\n element of `\\operatorname{GL}(V)` fixing a hyperplane pointwise\n and acting by multiplication by a root of unity on a complementary\n line.\n\n A *complex reflection group* is a group `W` that is (isomorphic\n to) a subgroup of some general linear group `\\operatorname{GL}(V)`\n generated by a distinguished set of complex reflections.\n\n The dimension of `V` is the *rank* of `W`.\n\n For a comprehensive treatment of complex reflection groups and\n many definitions and theorems used here, we refer to [LT2009]_.\n See also :wikipedia:`Reflection_group`.\n\n .. SEEALSO::\n\n :func:`ReflectionGroup` for usage examples of this category.\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: ComplexReflectionGroups()\n Category of complex reflection groups\n sage: ComplexReflectionGroups().super_categories()\n [Category of complex reflection or generalized Coxeter groups]\n sage: ComplexReflectionGroups().all_super_categories()\n [Category of complex reflection groups,\n Category of complex reflection or generalized Coxeter groups,\n Category of groups,\n Category of monoids,\n Category of finitely generated semigroups,\n Category of semigroups,\n Category of finitely generated magmas,\n Category of inverse unital magmas,\n Category of unital magmas,\n Category of magmas,\n Category of enumerated sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n An example of a reflection group::\n\n sage: W = ComplexReflectionGroups().example(); W # needs sage.combinat\n 5-colored permutations of size 3\n\n ``W`` is in the category of complex reflection groups::\n\n sage: W in ComplexReflectionGroups() # needs sage.combinat\n True\n\n TESTS::\n\n sage: TestSuite(W).run() # needs sage.combinat\n sage: TestSuite(ComplexReflectionGroups()).run()\n ' @cached_method def super_categories(self): '\n Return the super categories of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: ComplexReflectionGroups().super_categories()\n [Category of complex reflection or generalized Coxeter groups]\n ' return [ComplexReflectionOrGeneralizedCoxeterGroups()] def additional_structure(self): '\n Return ``None``.\n\n Indeed, all the structure complex reflection groups have in\n addition to groups (simple reflections, ...) is already\n defined in the super category.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: ComplexReflectionGroups().additional_structure()\n ' return None def example(self): '\n Return an example of a complex reflection group.\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: ComplexReflectionGroups().example() # needs sage.combinat\n 5-colored permutations of size 3\n ' from sage.combinat.colored_permutations import ColoredPermutations return ColoredPermutations(5, 3) class ParentMethods(): @cached_method def rank(self): '\n Return the rank of ``self``.\n\n The rank of ``self`` is the dimension of the smallest\n faithfull reflection representation of ``self``.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example(); W\n The symmetric group on {0, ..., 3}\n sage: W.rank()\n 3\n ' Finite = LazyImport('sage.categories.finite_complex_reflection_groups', 'FiniteComplexReflectionGroups', as_name='Finite')
class ComplexReflectionOrGeneralizedCoxeterGroups(Category_singleton): '\n The category of complex reflection groups or generalized Coxeter groups.\n\n Finite Coxeter groups can be defined equivalently as groups\n generated by reflections, or by presentations. Over the last\n decades, the theory has been generalized in both directions,\n leading to the study of (finite) complex reflection groups on the\n one hand, and (finite) generalized Coxeter groups on the other\n hand. Many of the features remain similar, yet, in the current\n state of the art, there is no general theory covering both\n directions.\n\n This is reflected by the name of this category which is about\n factoring out the common code, tests, and declarations.\n\n A group in this category has:\n\n - A distinguished finite set of generators `(s_i)_I`, called\n *simple reflections*. The set `I` is called the *index set*. The\n name "reflection" is somewhat of an abuse as they can have\n higher order; still, they are all of finite order: `s_i^k=1` for\n some `k`.\n\n - A collection of *distinguished reflections* which are the\n conjugates of the simple reflections. For complex reflection\n groups, they are in one-to-one correspondence with the\n reflection hyperplanes and share the same index set.\n\n - A collection of *reflections* which are the conjugates of all\n the non trivial powers of the simple reflections.\n\n The usual notions of reduced words, length, irreducibility, etc\n can be canonically defined from the above.\n\n The following methods must be implemented:\n\n - :meth:`ComplexReflectionOrGeneralizedCoxeterGroups.ParentMethods.index_set`\n - :meth:`ComplexReflectionOrGeneralizedCoxeterGroups.ParentMethods.simple_reflection`\n\n Optionally one can define analog methods for distinguished\n reflections and reflections (see below).\n\n At least one of the following methods must be implemented:\n\n - :meth:`ComplexReflectionOrGeneralizedCoxeterGroups.ElementMethods.apply_simple_reflection`\n - :meth:`ComplexReflectionOrGeneralizedCoxeterGroups.ElementMethods.apply_simple_reflection_left`\n - :meth:`ComplexReflectionOrGeneralizedCoxeterGroups.ElementMethods.apply_simple_reflection_right`\n - :meth:`ComplexReflectionOrGeneralizedCoxeterGroups.ElementMethods._mul_`\n\n It\'s recommended to implement either ``_mul_`` or both\n ``apply_simple_reflection_left`` and ``apply_simple_reflection_right``.\n\n .. SEEALSO::\n\n - :class:`complex_reflection_groups.ComplexReflectionGroups`\n - :class:`generalized_coxeter_groups.GeneralizedCoxeterGroups`\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_or_generalized_coxeter_groups import ComplexReflectionOrGeneralizedCoxeterGroups\n sage: C = ComplexReflectionOrGeneralizedCoxeterGroups(); C\n Category of complex reflection or generalized Coxeter groups\n sage: C.super_categories()\n [Category of finitely generated enumerated groups]\n\n sage: C.required_methods()\n {\'element\': {\'optional\': [\'reflection_length\'],\n \'required\': []},\n \'parent\': {\'optional\': [\'distinguished_reflection\', \'hyperplane_index_set\',\n \'irreducible_components\',\n \'reflection\', \'reflection_index_set\'],\n \'required\': [\'__contains__\', \'index_set\']}}\n\n TESTS::\n\n sage: TestSuite(C).run()\n ' @cached_method def super_categories(self): '\n Return the super categories of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: ComplexReflectionGroups().super_categories()\n [Category of complex reflection or generalized Coxeter groups]\n ' return [Groups().FinitelyGenerated()] class SubcategoryMethods(): def Irreducible(self): "\n Return the full subcategory of irreducible objects of ``self``.\n\n A complex reflection group, or generalized Coxeter group\n is *reducible* if its simple reflections can be split in\n two sets `X` and `Y` such that the elements of `X` commute\n with that of `Y`. In particular, the group is then direct\n product of `\\langle X \\rangle` and `\\langle Y \\rangle`.\n It's *irreducible* otherwise.\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: ComplexReflectionGroups().Irreducible()\n Category of irreducible complex reflection groups\n sage: CoxeterGroups().Irreducible()\n Category of irreducible Coxeter groups\n\n TESTS::\n\n sage: TestSuite(ComplexReflectionGroups().Irreducible()).run()\n sage: CoxeterGroups().Irreducible.__module__\n 'sage.categories.complex_reflection_or_generalized_coxeter_groups'\n " return self._with_axiom('Irreducible') class ParentMethods(): @abstract_method def index_set(self): "\n Return the index set of (the simple reflections of)\n ``self``, as a list (or iterable).\n\n .. SEEALSO::\n\n - :meth:`simple_reflection`\n - :meth:`simple_reflections`\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().Finite().example(); W\n The 5-th dihedral group of order 10\n sage: W.index_set()\n (1, 2)\n\n sage: W = ColoredPermutations(1, 4)\n sage: W.index_set()\n (1, 2, 3)\n sage: W = ReflectionGroup((1,1,4), index_set=[1,3,'asdf']) # optional - gap3\n sage: W.index_set() # optional - gap3\n (1, 3, 'asdf')\n sage: W = ReflectionGroup((1,1,4), index_set=('a','b','c')) # optional - gap3\n sage: W.index_set() # optional - gap3\n ('a', 'b', 'c')\n " def simple_reflection(self, i): "\n Return the `i`-th simple reflection `s_i` of ``self``.\n\n INPUT:\n\n - ``i`` -- an element from the index set\n\n .. SEEALSO::\n\n - :meth:`index_set`\n - :meth:`simple_reflections`\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: W\n The symmetric group on {0, ..., 3}\n sage: W.simple_reflection(1)\n (0, 2, 1, 3)\n sage: s = W.simple_reflections()\n sage: s[1]\n (0, 2, 1, 3)\n\n sage: W = ReflectionGroup((1,1,4), index_set=[1,3,'asdf']) # optional - gap3\n sage: for i in W.index_set(): # optional - gap3\n ....: print('%s %s'%(i, W.simple_reflection(i)))\n 1 (1,7)(2,4)(5,6)(8,10)(11,12)\n 3 (1,4)(2,8)(3,5)(7,10)(9,11)\n asdf (2,5)(3,9)(4,6)(8,11)(10,12)\n " if (i not in self.index_set()): raise ValueError(('%s is not in the Dynkin node set %s' % (i, self.index_set()))) return self.one().apply_simple_reflection(i) @cached_method def simple_reflections(self): "\n Return the simple reflections `(s_i)_{i\\in I}` of ``self`` as\n a family indexed by :meth:`index_set`.\n\n .. SEEALSO::\n\n - :meth:`simple_reflection`\n - :meth:`index_set`\n\n EXAMPLES:\n\n For the symmetric group, we recognize the simple transpositions::\n\n sage: W = SymmetricGroup(4); W\n Symmetric group of order 4! as a permutation group\n sage: s = W.simple_reflections()\n sage: s\n Finite family {1: (1,2), 2: (2,3), 3: (3,4)}\n sage: s[1]\n (1,2)\n sage: s[2]\n (2,3)\n sage: s[3]\n (3,4)\n\n Here are the simple reflections for a colored symmetric\n group and a reflection group::\n\n sage: W = ColoredPermutations(1,3)\n sage: W.simple_reflections()\n Finite family {1: [[0, 0, 0], [2, 1, 3]], 2: [[0, 0, 0], [1, 3, 2]]}\n\n sage: W = ReflectionGroup((1,1,3), index_set=['a','b']) # optional - gap3\n sage: W.simple_reflections() # optional - gap3\n Finite family {'a': (1,4)(2,3)(5,6), 'b': (1,3)(2,5)(4,6)}\n\n This default implementation uses :meth:`.index_set` and\n :meth:`.simple_reflection`.\n " from sage.sets.family import Family return Family(self.index_set(), self.simple_reflection) def number_of_simple_reflections(self): '\n Return the number of simple reflections of ``self``.\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(1,3)\n sage: W.number_of_simple_reflections()\n 2\n sage: W = ColoredPermutations(2,3)\n sage: W.number_of_simple_reflections()\n 3\n sage: W = ColoredPermutations(4,3)\n sage: W.number_of_simple_reflections()\n 3\n sage: W = ReflectionGroup((4,2,3)) # optional - gap3\n sage: W.number_of_simple_reflections() # optional - gap3\n 4\n ' return len(self.index_set()) def group_generators(self): '\n Return the simple reflections of ``self``, as\n distinguished group generators.\n\n .. SEEALSO::\n\n - :meth:`simple_reflections`\n - :meth:`Groups.ParentMethods.group_generators`\n - :meth:`Semigroups.ParentMethods.semigroup_generators`\n\n EXAMPLES::\n\n sage: D10 = FiniteCoxeterGroups().example(10)\n sage: D10.group_generators()\n Finite family {1: (1,), 2: (2,)}\n sage: SymmetricGroup(5).group_generators()\n Finite family {1: (1,2), 2: (2,3), 3: (3,4), 4: (4,5)}\n\n sage: W = ColoredPermutations(3,2)\n sage: W.group_generators()\n Finite family {1: [[0, 0],\n [2, 1]],\n 2: [[0, 1],\n [1, 2]]}\n\n The simple reflections are also semigroup generators, even\n for an infinite group::\n\n sage: W = WeylGroup(["A",2,1])\n sage: W.semigroup_generators()\n Finite family {0: [-1 1 1]\n [ 0 1 0]\n [ 0 0 1],\n 1: [ 1 0 0]\n [ 1 -1 1]\n [ 0 0 1],\n 2: [ 1 0 0]\n [ 0 1 0]\n [ 1 1 -1]}\n ' return self.simple_reflections() semigroup_generators = group_generators def simple_reflection_orders(self): "\n Return the orders of the simple reflections.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['B',3])\n sage: W.simple_reflection_orders()\n [2, 2, 2]\n sage: W = CoxeterGroup(['C',4])\n sage: W.simple_reflection_orders()\n [2, 2, 2, 2]\n sage: SymmetricGroup(5).simple_reflection_orders()\n [2, 2, 2, 2]\n sage: C = ColoredPermutations(4, 3)\n sage: C.simple_reflection_orders()\n [2, 2, 4]\n " one = self.one() s = self.simple_reflections() from sage.rings.integer_ring import ZZ def mult_order(x): ct = ZZ.one() cur = x while (cur != one): cur *= x ct += ZZ.one() return ZZ(ct) return [mult_order(s[i]) for i in self.index_set()] def _an_element_(self): '\n Implement: :meth:`Sets.ParentMethods.an_element` by\n returning the product of the simple reflections (a Coxeter\n element).\n\n EXAMPLES::\n\n sage: W = SymmetricGroup(4); W\n Symmetric group of order 4! as a permutation group\n sage: W.an_element() # indirect doctest\n (2,3,4)\n\n For a complex reflection group::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: W = ComplexReflectionGroups().example(); W\n 5-colored permutations of size 3\n sage: W.an_element()\n [[1, 0, 0], [3, 1, 2]]\n ' return self.prod(self.simple_reflections()) def some_elements(self): "\n Implement :meth:`Sets.ParentMethods.some_elements` by\n returning some typical elements of ``self``.\n\n The result is currently composed of the simple reflections\n together with the unit and the result of :meth:`an_element`.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3])\n sage: W.some_elements()\n [\n [0 1 0 0] [1 0 0 0] [1 0 0 0] [1 0 0 0] [0 0 0 1]\n [1 0 0 0] [0 0 1 0] [0 1 0 0] [0 1 0 0] [1 0 0 0]\n [0 0 1 0] [0 1 0 0] [0 0 0 1] [0 0 1 0] [0 1 0 0]\n [0 0 0 1], [0 0 0 1], [0 0 1 0], [0 0 0 1], [0 0 1 0]\n ]\n\n sage: W = ColoredPermutations(1,4)\n sage: W.some_elements()\n [[[0, 0, 0, 0], [2, 1, 3, 4]],\n [[0, 0, 0, 0], [1, 3, 2, 4]],\n [[0, 0, 0, 0], [1, 2, 4, 3]],\n [[0, 0, 0, 0], [1, 2, 3, 4]],\n [[0, 0, 0, 0], [4, 1, 2, 3]]]\n " return (list(self.simple_reflections()) + [self.one(), self.an_element()]) @abstract_method(optional=True) def reflection_index_set(self): "\n Return the index set of the reflections of ``self``.\n\n .. SEEALSO::\n\n - :meth:`reflection`\n - :meth:`reflections`\n\n EXAMPLES::\n\n sage: # optional - gap3\n sage: W = ReflectionGroup((1,1,4))\n sage: W.reflection_index_set()\n (1, 2, 3, 4, 5, 6)\n sage: W = ReflectionGroup((1,1,4), reflection_index_set=[1,3,'asdf',7,9,11])\n sage: W.reflection_index_set()\n (1, 3, 'asdf', 7, 9, 11)\n sage: W = ReflectionGroup((1,1,4), reflection_index_set=('a','b','c','d','e','f'))\n sage: W.reflection_index_set()\n ('a', 'b', 'c', 'd', 'e', 'f')\n " @abstract_method(optional=True) def reflection(self, i): "\n Return the `i`-th reflection of ``self``.\n\n For `i` in `1,\\dots,N`, this gives the `i`-th reflection of\n ``self``.\n\n .. SEEALSO::\n\n - :meth:`reflections_index_set`\n - :meth:`reflections`\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,4)) # optional - gap3\n sage: for i in W.reflection_index_set(): # optional - gap3\n ....: print('%s %s'%(i, W.reflection(i)))\n 1 (1,7)(2,4)(5,6)(8,10)(11,12)\n 2 (1,4)(2,8)(3,5)(7,10)(9,11)\n 3 (2,5)(3,9)(4,6)(8,11)(10,12)\n 4 (1,8)(2,7)(3,6)(4,10)(9,12)\n 5 (1,6)(2,9)(3,8)(5,11)(7,12)\n 6 (1,11)(3,10)(4,9)(5,7)(6,12)\n " @cached_method def reflections(self): "\n Return a finite family containing the reflections of\n ``self``, indexed by :meth:`reflection_index_set`.\n\n .. SEEALSO::\n\n - :meth:`reflection`\n - :meth:`reflection_index_set`\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,3)) # optional - gap3\n sage: reflections = W.reflections() # optional - gap3\n sage: for index in sorted(reflections.keys()): # optional - gap3\n ....: print('%s %s'%(index, reflections[index]))\n 1 (1,4)(2,3)(5,6)\n 2 (1,3)(2,5)(4,6)\n 3 (1,5)(2,4)(3,6)\n\n sage: W = ReflectionGroup((1,1,3),reflection_index_set=['a','b','c']) # optional - gap3\n sage: reflections = W.reflections() # optional - gap3\n sage: for index in sorted(reflections.keys()): # optional - gap3\n ....: print('%s %s'%(index, reflections[index]))\n a (1,4)(2,3)(5,6)\n b (1,3)(2,5)(4,6)\n c (1,5)(2,4)(3,6)\n\n sage: W = ReflectionGroup((3,1,1)) # optional - gap3\n sage: reflections = W.reflections() # optional - gap3\n sage: for index in sorted(reflections.keys()): # optional - gap3\n ....: print('%s %s'%(index, reflections[index]))\n 1 (1,2,3)\n 2 (1,3,2)\n\n sage: W = ReflectionGroup((1,1,3), (3,1,2)) # optional - gap3\n sage: reflections = W.reflections() # optional - gap3\n sage: for index in sorted(reflections.keys()): # optional - gap3\n ....: print('%s %s'%(index, reflections[index]))\n 1 (1,6)(2,5)(7,8)\n 2 (1,5)(2,7)(6,8)\n 3 (3,9,15)(4,10,16)(12,17,23)(14,18,24)(20,25,29)(21,22,26)(27,28,30)\n 4 (3,11)(4,12)(9,13)(10,14)(15,19)(16,20)(17,21)(18,22)(23,27)(24,28)(25,26)(29,30)\n 5 (1,7)(2,6)(5,8)\n 6 (3,19)(4,25)(9,11)(10,17)(12,28)(13,15)(14,30)(16,18)(20,27)(21,29)(22,23)(24,26)\n 7 (4,21,27)(10,22,28)(11,13,19)(12,14,20)(16,26,30)(17,18,25)(23,24,29)\n 8 (3,13)(4,24)(9,19)(10,29)(11,15)(12,26)(14,21)(16,23)(17,30)(18,27)(20,22)(25,28)\n 9 (3,15,9)(4,16,10)(12,23,17)(14,24,18)(20,29,25)(21,26,22)(27,30,28)\n 10 (4,27,21)(10,28,22)(11,19,13)(12,20,14)(16,30,26)(17,25,18)(23,29,24)\n " from sage.sets.family import Family return Family(self.reflection_index_set(), self.reflection) @abstract_method(optional=True) def hyperplane_index_set(self): "\n Return the index set of the distinguished reflections of ``self``.\n\n This is also the index set of the reflection hyperplanes\n of ``self``, hence the name. This name is slightly abusive\n since the concept of reflection hyperplanes is not defined\n for all generalized Coxeter groups. However for all\n practical purposes this is only used for complex\n reflection groups, and there this is the desirable name.\n\n .. SEEALSO::\n\n - :meth:`distinguished_reflection`\n - :meth:`distinguished_reflections`\n\n EXAMPLES::\n\n sage: # optional - gap3\n sage: W = ReflectionGroup((1,1,4))\n sage: W.hyperplane_index_set()\n (1, 2, 3, 4, 5, 6)\n sage: W = ReflectionGroup((1,1,4), hyperplane_index_set=[1,3,'asdf',7,9,11])\n sage: W.hyperplane_index_set()\n (1, 3, 'asdf', 7, 9, 11)\n sage: W = ReflectionGroup((1,1,4), hyperplane_index_set=('a','b','c','d','e','f'))\n sage: W.hyperplane_index_set()\n ('a', 'b', 'c', 'd', 'e', 'f')\n " @abstract_method(optional=True) def distinguished_reflection(self, i): "\n Return the `i`-th distinguished reflection of ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set of the distinguished reflections.\n\n .. SEEALSO::\n\n - :meth:`distinguished_reflections`\n - :meth:`hyperplane_index_set`\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,4), hyperplane_index_set=('a','b','c','d','e','f')) # optional - gap3\n sage: for i in W.hyperplane_index_set(): # optional - gap3\n ....: print('%s %s'%(i, W.distinguished_reflection(i)))\n a (1,7)(2,4)(5,6)(8,10)(11,12)\n b (1,4)(2,8)(3,5)(7,10)(9,11)\n c (2,5)(3,9)(4,6)(8,11)(10,12)\n d (1,8)(2,7)(3,6)(4,10)(9,12)\n e (1,6)(2,9)(3,8)(5,11)(7,12)\n f (1,11)(3,10)(4,9)(5,7)(6,12)\n " @cached_method def distinguished_reflections(self): "\n Return a finite family containing the distinguished\n reflections of ``self``, indexed by\n :meth:`hyperplane_index_set`.\n\n A *distinguished reflection* is a conjugate of a simple\n reflection. For a Coxeter group, reflections and\n distinguished reflections coincide. For a Complex\n reflection groups this is a reflection acting on the\n complement of the fixed hyperplane `H` as\n `\\operatorname{exp}(2 \\pi i / n)`, where `n` is the order\n of the reflection subgroup fixing `H`.\n\n .. SEEALSO::\n\n - :meth:`distinguished_reflection`\n - :meth:`hyperplane_index_set`\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,3)) # optional - gap3\n sage: distinguished_reflections = W.distinguished_reflections() # optional - gap3\n sage: for index in sorted(distinguished_reflections.keys()): # optional - gap3\n ....: print('%s %s'%(index, distinguished_reflections[index]))\n 1 (1,4)(2,3)(5,6)\n 2 (1,3)(2,5)(4,6)\n 3 (1,5)(2,4)(3,6)\n\n sage: W = ReflectionGroup((1,1,3),hyperplane_index_set=['a','b','c']) # optional - gap3\n sage: distinguished_reflections = W.distinguished_reflections() # optional - gap3\n sage: for index in sorted(distinguished_reflections.keys()): # optional - gap3\n ....: print('%s %s'%(index, distinguished_reflections[index]))\n a (1,4)(2,3)(5,6)\n b (1,3)(2,5)(4,6)\n c (1,5)(2,4)(3,6)\n\n sage: W = ReflectionGroup((3,1,1)) # optional - gap3\n sage: distinguished_reflections = W.distinguished_reflections() # optional - gap3\n sage: for index in sorted(distinguished_reflections.keys()): # optional - gap3\n ....: print('%s %s'%(index, distinguished_reflections[index]))\n 1 (1,2,3)\n\n sage: W = ReflectionGroup((1,1,3), (3,1,2)) # optional - gap3\n sage: distinguished_reflections = W.distinguished_reflections() # optional - gap3\n sage: for index in sorted(distinguished_reflections.keys()): # optional - gap3\n ....: print('%s %s'%(index, distinguished_reflections[index]))\n 1 (1,6)(2,5)(7,8)\n 2 (1,5)(2,7)(6,8)\n 3 (3,9,15)(4,10,16)(12,17,23)(14,18,24)(20,25,29)(21,22,26)(27,28,30)\n 4 (3,11)(4,12)(9,13)(10,14)(15,19)(16,20)(17,21)(18,22)(23,27)(24,28)(25,26)(29,30)\n 5 (1,7)(2,6)(5,8)\n 6 (3,19)(4,25)(9,11)(10,17)(12,28)(13,15)(14,30)(16,18)(20,27)(21,29)(22,23)(24,26)\n 7 (4,21,27)(10,22,28)(11,13,19)(12,14,20)(16,26,30)(17,18,25)(23,24,29)\n 8 (3,13)(4,24)(9,19)(10,29)(11,15)(12,26)(14,21)(16,23)(17,30)(18,27)(20,22)(25,28)\n " from sage.sets.family import Family return Family(self.hyperplane_index_set(), self.distinguished_reflection) def from_reduced_word(self, word, word_type='simple'): '\n Return an element of ``self`` from its (reduced) word.\n\n INPUT:\n\n - ``word`` -- a list (or iterable) of elements of the\n index set of ``self`` (resp. of the distinguished\n or of all reflections)\n - ``word_type`` -- (optional, default: ``\'simple\'``):\n either ``\'simple\'``, ``\'distinguished\'``, or ``\'all\'``\n\n If ``word`` is `[i_1,i_2,\\ldots,i_k]`, then this returns\n the corresponding product of simple reflections\n `s_{i_1} s_{i_2} \\cdots s_{i_k}`.\n\n If ``word_type`` is ``\'distinguished\'`` (resp. ``\'all\'``),\n then the product of the distinguished reflections (resp. all\n reflections) is returned.\n\n .. NOTE::\n\n The main use case is for constructing elements from\n reduced words, hence the name of this method.\n However, the input word need *not* be reduced.\n\n .. SEEALSO::\n\n - :meth:`index_set`\n - :meth:`reflection_index_set`\n - :meth:`hyperplane_index_set`\n - :meth:`~ComplexReflectionOrGeneralizedCoxeterGroups.ElementMethods.apply_simple_reflections`\n - :meth:`~CoxeterGroup.ElementMethods.reduced_word`\n - :meth:`~CoxeterGroup.ParentMethods._test_reduced_word`\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: W\n The symmetric group on {0, ..., 3}\n sage: s = W.simple_reflections()\n sage: W.from_reduced_word([0,2,0,1])\n (0, 3, 1, 2)\n sage: W.from_reduced_word((0,2,0,1))\n (0, 3, 1, 2)\n sage: s[0]*s[2]*s[0]*s[1]\n (0, 3, 1, 2)\n\n We now experiment with the different values for\n ``word_type`` for the colored symmetric group::\n\n sage: W = ColoredPermutations(1,4)\n sage: W.from_reduced_word([1,2,1,2,1,2])\n [[0, 0, 0, 0], [1, 2, 3, 4]]\n\n sage: W.from_reduced_word([1, 2, 3]).reduced_word()\n [1, 2, 3]\n\n sage: W = WeylGroup("A3", prefix=\'s\')\n sage: AS = W.domain()\n sage: r1 = AS.roots()[4]\n sage: r1\n (0, 1, 0, -1)\n sage: r2 = AS.roots()[5]\n sage: r2\n (0, 0, 1, -1)\n sage: W.from_reduced_word([r1, r2], word_type=\'all\')\n s3*s2\n\n sage: W = WeylGroup("G2", prefix=\'s\')\n sage: W.from_reduced_word(W.domain().positive_roots(), word_type=\'all\')\n s1*s2\n\n sage: W = ReflectionGroup((1,1,4)) # optional - gap3\n sage: W.from_reduced_word([1,2,3], word_type=\'all\').reduced_word() # optional - gap3\n [1, 2, 3]\n\n sage: W.from_reduced_word([1,2,3], word_type=\'all\').reduced_word_in_reflections() # optional - gap3\n [1, 2, 3]\n\n sage: W.from_reduced_word([1,2,3]).reduced_word_in_reflections() # optional - gap3\n [1, 2, 3]\n\n TESTS::\n\n sage: W = WeylGroup([\'E\',6])\n sage: W.from_reduced_word([2,3,4,2])\n [ 0 1 0 0 0 0 0 0]\n [ 0 0 -1 0 0 0 0 0]\n [-1 0 0 0 0 0 0 0]\n [ 0 0 0 1 0 0 0 0]\n [ 0 0 0 0 1 0 0 0]\n [ 0 0 0 0 0 1 0 0]\n [ 0 0 0 0 0 0 1 0]\n [ 0 0 0 0 0 0 0 1]\n ' if (word_type == 'simple'): return self.one().apply_simple_reflections(word) else: return self.one().apply_reflections(word, word_type=word_type) def irreducible_component_index_sets(self): '\n Return a list containing the index sets of the irreducible components of\n ``self`` as finite reflection groups.\n\n EXAMPLES::\n\n sage: W = ReflectionGroup([1,1,3], [3,1,3], 4); W # optional - gap3\n Reducible complex reflection group of rank 7 and type A2 x G(3,1,3) x ST4\n sage: sorted(W.irreducible_component_index_sets()) # optional - gap3\n [[1, 2], [3, 4, 5], [6, 7]]\n\n ALGORITHM:\n\n Take the connected components of the graph on the\n index set with edges ``(i,j)``, where ``s[i]`` and\n ``s[j]`` do not commute.\n ' I = self.index_set() s = self.simple_reflections() from sage.graphs.graph import Graph G = Graph([I, [[i, j] for (i, j) in itertools.combinations(I, 2) if ((s[i] * s[j]) != (s[j] * s[i]))]], format='vertices_and_edges') return G.connected_components(sort=False) @abstract_method(optional=True) def irreducible_components(self): '\n Return the irreducible components of ``self`` as finite\n reflection groups.\n\n EXAMPLES::\n\n sage: W = ReflectionGroup([1,1,3], [3,1,3], 4) # optional - gap3\n sage: W.irreducible_components() # optional - gap3\n [Irreducible real reflection group of rank 2 and type A2,\n Irreducible complex reflection group of rank 3 and type G(3,1,3),\n Irreducible complex reflection group of rank 2 and type ST4]\n ' def number_of_irreducible_components(self): "\n Return the number of irreducible components of ``self``.\n\n EXAMPLES::\n\n sage: SymmetricGroup(3).number_of_irreducible_components()\n 1\n\n sage: ColoredPermutations(1,3).number_of_irreducible_components()\n 1\n\n sage: ReflectionGroup((1,1,3),(2,1,3)).number_of_irreducible_components() # optional - gap3\n 2\n\n TESTS::\n\n sage: SymmetricGroup(3).number_of_irreducible_components.__module__\n 'sage.categories.complex_reflection_or_generalized_coxeter_groups'\n " return len(self.irreducible_component_index_sets()) def is_irreducible(self): '\n Return ``True`` if ``self`` is irreducible.\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(1,3); W\n 1-colored permutations of size 3\n sage: W.is_irreducible()\n True\n\n sage: W = ReflectionGroup((1,1,3),(2,1,3)); W # optional - gap3\n Reducible real reflection group of rank 5 and type A2 x B3\n sage: W.is_irreducible() # optional - gap3\n False\n ' return (self.number_of_irreducible_components() == 1) def is_reducible(self): '\n Return ``True`` if ``self`` is not irreducible.\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(1,3); W\n 1-colored permutations of size 3\n sage: W.is_reducible()\n False\n\n sage: W = ReflectionGroup((1,1,3), (2,1,3)); W # optional - gap3\n Reducible real reflection group of rank 5 and type A2 x B3\n sage: W.is_reducible() # optional - gap3\n True\n ' return (not self.is_irreducible()) class ElementMethods(): def apply_simple_reflection_left(self, i): "\n Return ``self`` multiplied by the simple reflection ``s[i]``\n on the left.\n\n This low level method is used intensively. Coxeter groups\n are encouraged to override this straightforward\n implementation whenever a faster approach exists.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: w = W.an_element(); w\n (1, 2, 3, 0)\n sage: w.apply_simple_reflection_left(0)\n (0, 2, 3, 1)\n sage: w.apply_simple_reflection_left(1)\n (2, 1, 3, 0)\n sage: w.apply_simple_reflection_left(2)\n (1, 3, 2, 0)\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: W = ComplexReflectionGroups().example()\n sage: w = W.an_element(); w\n [[1, 0, 0], [3, 1, 2]]\n sage: w.apply_simple_reflection_left(1)\n [[0, 1, 0], [1, 3, 2]]\n sage: w.apply_simple_reflection_left(2)\n [[1, 0, 0], [3, 2, 1]]\n sage: w.apply_simple_reflection_left(3)\n [[1, 0, 1], [3, 1, 2]]\n\n TESTS::\n\n sage: w.apply_simple_reflection_left.__module__\n 'sage.categories.complex_reflection_or_generalized_coxeter_groups'\n " s = self.parent().simple_reflections() return (s[i] * self) def apply_simple_reflection_right(self, i): "\n Return ``self`` multiplied by the simple reflection ``s[i]``\n on the right.\n\n This low level method is used intensively. Coxeter groups\n are encouraged to override this straightforward\n implementation whenever a faster approach exists.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: w = W.an_element(); w\n (1, 2, 3, 0)\n sage: w.apply_simple_reflection_right(0)\n (2, 1, 3, 0)\n sage: w.apply_simple_reflection_right(1)\n (1, 3, 2, 0)\n sage: w.apply_simple_reflection_right(2)\n (1, 2, 0, 3)\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: W = ComplexReflectionGroups().example()\n sage: w = W.an_element(); w\n [[1, 0, 0], [3, 1, 2]]\n sage: w.apply_simple_reflection_right(1)\n [[1, 0, 0], [3, 2, 1]]\n sage: w.apply_simple_reflection_right(2)\n [[1, 0, 0], [2, 1, 3]]\n sage: w.apply_simple_reflection_right(3)\n [[2, 0, 0], [3, 1, 2]]\n\n TESTS::\n\n sage: w.apply_simple_reflection_right.__module__\n 'sage.categories.complex_reflection_or_generalized_coxeter_groups'\n " s = self.parent().simple_reflections() return (self * s[i]) def apply_simple_reflection(self, i, side='right'): '\n Return ``self`` multiplied by the simple reflection ``s[i]``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n - ``side`` -- (default: ``"right"``) ``"left"`` or ``"right"``\n\n This default implementation simply calls\n :meth:`apply_simple_reflection_left` or\n :meth:`apply_simple_reflection_right`.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: w = W.an_element(); w\n (1, 2, 3, 0)\n sage: w.apply_simple_reflection(0, side = "left")\n (0, 2, 3, 1)\n sage: w.apply_simple_reflection(1, side = "left")\n (2, 1, 3, 0)\n sage: w.apply_simple_reflection(2, side = "left")\n (1, 3, 2, 0)\n\n sage: w.apply_simple_reflection(0, side = "right")\n (2, 1, 3, 0)\n sage: w.apply_simple_reflection(1, side = "right")\n (1, 3, 2, 0)\n sage: w.apply_simple_reflection(2, side = "right")\n (1, 2, 0, 3)\n\n By default, ``side`` is ``"right"``::\n\n sage: w.apply_simple_reflection(0)\n (2, 1, 3, 0)\n\n Some tests with a complex reflection group::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: W = ComplexReflectionGroups().example(); W\n 5-colored permutations of size 3\n sage: w = W.an_element(); w\n [[1, 0, 0], [3, 1, 2]]\n sage: w.apply_simple_reflection(1, side="left")\n [[0, 1, 0], [1, 3, 2]]\n sage: w.apply_simple_reflection(2, side="left")\n [[1, 0, 0], [3, 2, 1]]\n sage: w.apply_simple_reflection(3, side="left")\n [[1, 0, 1], [3, 1, 2]]\n\n sage: w.apply_simple_reflection(1, side="right")\n [[1, 0, 0], [3, 2, 1]]\n sage: w.apply_simple_reflection(2, side="right")\n [[1, 0, 0], [2, 1, 3]]\n sage: w.apply_simple_reflection(3, side="right")\n [[2, 0, 0], [3, 1, 2]]\n\n TESTS::\n\n sage: w.apply_simple_reflection_right.__module__\n \'sage.categories.complex_reflection_or_generalized_coxeter_groups\'\n ' if (side == 'right'): return self.apply_simple_reflection_right(i) else: return self.apply_simple_reflection_left(i) def apply_simple_reflections(self, word, side='right', type='simple'): "\n Return the result of the (left/right) multiplication of\n ``self`` by ``word``.\n\n INPUT:\n\n - ``word`` -- a sequence of indices of simple reflections\n - ``side`` -- (default: ``'right'``) indicates multiplying\n from left or right\n\n This is a specialized implementation of\n :meth:`apply_reflections` for the simple reflections. The\n rationale for its existence are:\n\n - It can take advantage of ``apply_simple_reflection``,\n which often is less expensive than computing a product.\n\n - It reduced burden on implementations that would want to\n provide an optimized version of this method.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: w = W.an_element(); w\n (1, 2, 3, 0)\n sage: w.apply_simple_reflections([0,1])\n (2, 3, 1, 0)\n sage: w\n (1, 2, 3, 0)\n sage: w.apply_simple_reflections([0,1],side='left')\n (0, 1, 3, 2)\n " for i in word: self = self.apply_simple_reflection(i, side) return self def apply_reflections(self, word, side='right', word_type='all'): '\n Return the result of the (left/right) multiplication of\n ``self`` by ``word``.\n\n INPUT:\n\n - ``word`` -- a sequence of indices of reflections\n - ``side`` -- (default: ``\'right\'``) indicates multiplying\n from left or right\n - ``word_type`` -- (optional, default: ``\'all\'``):\n either ``\'simple\'``, ``\'distinguished\'``, or ``\'all\'``\n\n EXAMPLES::\n\n sage: # optional - gap3\n sage: W = ReflectionGroup((1,1,3))\n sage: W.one().apply_reflections([1])\n (1,4)(2,3)(5,6)\n sage: W.one().apply_reflections([2])\n (1,3)(2,5)(4,6)\n sage: W.one().apply_reflections([2,1])\n (1,2,6)(3,4,5)\n\n\n sage: W = CoxeterGroups().example()\n sage: w = W.an_element(); w\n (1, 2, 3, 0)\n sage: w.apply_reflections([0,1], word_type=\'simple\')\n (2, 3, 1, 0)\n sage: w\n (1, 2, 3, 0)\n sage: w.apply_reflections([0,1], side=\'left\', word_type=\'simple\')\n (0, 1, 3, 2)\n\n\n sage: W = WeylGroup("A3", prefix=\'s\')\n sage: w = W.an_element(); w\n s1*s2*s3\n sage: AS = W.domain()\n sage: r1 = AS.roots()[4]\n sage: r1\n (0, 1, 0, -1)\n sage: r2 = AS.roots()[5]\n sage: r2\n (0, 0, 1, -1)\n sage: w.apply_reflections([r1, r2], word_type=\'all\')\n s1\n\n\n sage: # optional - gap3\n sage: W = ReflectionGroup((1,1,3))\n sage: W.one().apply_reflections([1], word_type=\'distinguished\')\n (1,4)(2,3)(5,6)\n sage: W.one().apply_reflections([2], word_type=\'distinguished\')\n (1,3)(2,5)(4,6)\n sage: W.one().apply_reflections([3], word_type=\'distinguished\')\n (1,5)(2,4)(3,6)\n sage: W.one().apply_reflections([2,1], word_type=\'distinguished\')\n (1,2,6)(3,4,5)\n\n sage: W = ReflectionGroup((1,1,3), hyperplane_index_set=[\'A\',\'B\',\'C\']); W # optional - gap3\n Irreducible real reflection group of rank 2 and type A2\n sage: W.one().apply_reflections([\'A\'], word_type=\'distinguished\') # optional - gap3\n (1,4)(2,3)(5,6)\n ' if (word_type == 'simple'): reflections = self.parent().simple_reflections() elif (word_type == 'distinguished'): reflections = self.parent().distinguished_reflections() else: reflections = self.parent().reflections() if (side == 'left'): for i in word: self = (reflections[i] * self) else: for i in word: self = (self * reflections[i]) return self def _mul_(self, other): "\n Return the product of ``self`` and ``other``\n\n This default implementation computes a reduced word of\n ``other`` using :meth:`reduced_word`, and applies the\n corresponding simple reflections on ``self`` using\n :meth:`apply_simple_reflections`.\n\n EXAMPLES::\n\n sage: W = FiniteCoxeterGroups().example(); W\n The 5-th dihedral group of order 10\n sage: w = W.an_element()\n sage: w\n (1, 2)\n sage: w._mul_(w)\n (1, 2, 1, 2)\n sage: w._mul_(w)._mul_(w)\n (2, 1, 2, 1)\n\n This method is called when computing ``self * other``::\n\n sage: w * w\n (1, 2, 1, 2)\n\n TESTS::\n\n sage: w._mul_.__module__\n 'sage.categories.complex_reflection_or_generalized_coxeter_groups'\n " return self.apply_simple_reflections(other.reduced_word()) def __invert__(self): "\n Return the inverse of ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['B',7])\n sage: w = W.an_element()\n sage: u = w.inverse() # indirect doctest\n sage: u == ~w\n True\n sage: u * w == w * u\n True\n sage: u * w\n [1 0 0 0 0 0 0]\n [0 1 0 0 0 0 0]\n [0 0 1 0 0 0 0]\n [0 0 0 1 0 0 0]\n [0 0 0 0 1 0 0]\n [0 0 0 0 0 1 0]\n [0 0 0 0 0 0 1]\n " return self.parent().one().apply_simple_reflections(self.reduced_word_reverse_iterator()) def apply_conjugation_by_simple_reflection(self, i): "\n Conjugate ``self`` by the ``i``-th simple reflection.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3])\n sage: w = W.from_reduced_word([3,1,2,1])\n sage: w.apply_conjugation_by_simple_reflection(1).reduced_word()\n [3, 2]\n " return self.apply_simple_reflection(i).apply_simple_reflection(i, side='left') @abstract_method(optional=True) def reflection_length(self): '\n Return the reflection length of ``self``.\n\n This is the minimal length of a factorization of ``self``\n into reflections.\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,2)) # optional - gap3\n sage: sorted([t.reflection_length() for t in W]) # optional - gap3\n [0, 1]\n\n sage: W = ReflectionGroup((2,1,2)) # optional - gap3\n sage: sorted([t.reflection_length() for t in W]) # optional - gap3\n [0, 1, 1, 1, 1, 2, 2, 2]\n\n sage: W = ReflectionGroup((3,1,2)) # optional - gap3\n sage: sorted([t.reflection_length() for t in W]) # optional - gap3\n [0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]\n\n sage: W = ReflectionGroup((2,2,2)) # optional - gap3\n sage: sorted([t.reflection_length() for t in W]) # optional - gap3\n [0, 1, 1, 2]\n ' def is_reflection(self): '\n Return whether ``self`` is a reflection.\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,4)) # optional - gap3\n sage: [t.is_reflection() for t in W.reflections()] # optional - gap3\n [True, True, True, True, True, True]\n sage: len([t for t in W.reflections() if t.is_reflection()]) # optional - gap3\n 6\n\n sage: W = ReflectionGroup((2,1,3)) # optional - gap3\n sage: [t.is_reflection() for t in W.reflections()] # optional - gap3\n [True, True, True, True, True, True, True, True, True]\n sage: len([t for t in W.reflections() if t.is_reflection()]) # optional - gap3\n 9\n ' return (self.reflection_length() == 1) class Irreducible(CategoryWithAxiom): class ParentMethods(): def irreducible_components(self): '\n Return a list containing all irreducible components of\n ``self`` as finite reflection groups.\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(4, 3)\n sage: W.irreducible_components()\n [4-colored permutations of size 3]\n ' return [self]
class CovariantFunctorialConstruction(UniqueRepresentation, SageObject): '\n An abstract class for construction functors `F` (eg `F` = Cartesian\n product, tensor product, `\\QQ`-algebra, ...) such that:\n\n - Each category `Cat` (eg `Cat=` ``Groups()``) can provide a category\n `F_{Cat}` for parents constructed via this functor (e.g.\n `F_{Cat} =` ``CartesianProductsOf(Groups())``).\n\n - For every category `Cat`, `F_{Cat}` is a subcategory of\n `F_{SuperCat}` for every super category `SuperCat` of\n `Cat` (the functorial construction is (category)-covariant).\n\n - For parents `A`, `B`, ..., respectively in the categories\n `Cat_A`, `Cat_B`, ..., the category of `F(A,B,...)` is\n `F_{Cat}` where `Cat` is the meet of the categories `Cat_A`,\n `Cat_B`, ...,.\n\n This covers two slightly different use cases:\n\n - In the first use case, one uses directly the construction\n functor to create new parents::\n\n sage: tensor() # todo: not implemented (add an example)\n\n or even new elements, which indirectly constructs the\n corresponding parent::\n\n sage: tensor(...) # todo: not implemented\n\n - In the second use case, one implements a parent, and then put\n it in the category `F_{Cat}` to specify supplementary\n mathematical information about that parent.\n\n The main purpose of this class is to handle automatically the\n trivial part of the category hierarchy. For example,\n ``CartesianProductsOf(Groups())`` is set automatically as a\n subcategory of ``CartesianProductsOf(Monoids())``.\n\n In practice, each subclass of this class should provide the\n following attributes:\n\n - ``_functor_category`` - a string which should match the name of\n the nested category class to be used in each category to\n specify information and generic operations for elements of this\n category.\n\n - ``_functor_name`` - a string which specifies the name of the\n functor, and also (when relevant) of the method on parents and\n elements used for calling the construction.\n\n TODO: What syntax do we want for `F_{Cat}`? For example, for the\n tensor product construction, which one do we want among (see\n chat on IRC, on 07/12/2009):\n\n - ``tensor(Cat)``\n - ``tensor((Cat, Cat))``\n - ``tensor.of((Cat, Cat))``\n - ``tensor.category_from_categories((Cat, Cat, Cat))``\n - ``Cat.TensorProducts()``\n\n The syntax ``Cat.TensorProducts()`` does not supports well multivariate\n constructions like ``tensor.of([Algebras(), HopfAlgebras(), ...])``.\n Also it forces every category to be (somehow) aware of all the\n tensorial construction that could apply to it, even those which\n are only induced from super categories.\n\n Note: for each functorial construction, there probably is one (or several)\n largest categories on which it applies. For example, the\n :func:`~sage.categories.cartesian_product.CartesianProducts` construction makes\n only sense for concrete categories, that is subcategories of\n ``Sets()``. Maybe we want to model this one way or the other.\n ' def category_from_parents(self, parents): '\n Return the category of `F(A,B,...)` for `A,B,...` parents.\n\n INPUT:\n\n - self: a functor F\n - parents: a list (or iterable) of parents.\n\n EXAMPLES::\n\n sage: E = CombinatorialFreeModule(QQ, ["a", "b", "c"]) # needs sage.modules\n sage: tensor.category_from_parents((E, E, E)) # needs sage.modules\n Category of tensor products of\n finite dimensional vector spaces with basis over Rational Field\n ' from sage.structure.parent import Parent assert all((isinstance(parent, Parent) for parent in parents)) return self.category_from_categories(tuple({parent.category() for parent in parents})) @cached_method def category_from_categories(self, categories): '\n Return the category of `F(A,B,...)` for `A,B,...` parents in\n the given categories.\n\n INPUT:\n\n - ``self``: a functor `F`\n - ``categories``: a non empty tuple of categories\n\n EXAMPLES::\n\n sage: Cat1 = Rings()\n sage: Cat2 = Groups()\n sage: cartesian_product.category_from_categories((Cat1, Cat1, Cat1))\n Join of Category of rings and ...\n and Category of Cartesian products of monoids\n and Category of Cartesian products of commutative additive groups\n\n sage: cartesian_product.category_from_categories((Cat1, Cat2))\n Category of Cartesian products of monoids\n ' assert (len(categories) > 0) return self.category_from_category(Category.meet(categories)) def category_from_category(self, category): '\n Return the category of `F(A,B,...)` for `A,B,...` parents in\n ``category``.\n\n INPUT:\n\n - ``self``: a functor `F`\n - ``category``: a category\n\n EXAMPLES::\n\n sage: tensor.category_from_category(ModulesWithBasis(QQ))\n Category of tensor products of vector spaces with basis over Rational Field\n\n # TODO: add support for parametrized functors\n ' return getattr(category, self._functor_category)() def _repr_(self): '\n EXAMPLES::\n\n sage: tensor # indirect doctest\n The tensor functorial construction\n ' return ('The %s functorial construction' % self._functor_name) def __call__(self, args, **kwargs): '\n Functorial construction application\n\n INPUT:\n\n - ``self``: a covariant functorial construction `F`\n - ``args``: a tuple (or iterable) of parents or elements\n\n Returns `F(args)`\n\n EXAMPLES::\n\n sage: E = CombinatorialFreeModule(QQ, ["a", "b", "c"]); E.rename("E") # needs sage.modules\n sage: tensor((E, E, E)) # needs sage.modules\n E # E # E\n ' args = tuple(args) assert all((hasattr(arg, self._functor_name) for arg in args)) assert (len(args) > 0) return getattr(args[0], self._functor_name)(*args[1:], **kwargs)
class FunctorialConstructionCategory(Category): '\n Abstract class for categories `F_{Cat}` obtained through a\n functorial construction\n ' @lazy_class_attribute def _base_category_class(cls): "\n Recover the class of the base category.\n\n OUTPUT:\n\n A *tuple* whose single entry is the base category class.\n\n .. WARNING::\n\n This is only used for functorial construction categories\n that are not implemented as nested classes, and won't work\n otherwise.\n\n .. SEEALSO:: :meth:`__classcall__`\n\n EXAMPLES::\n\n sage: GradedModules._base_category_class\n (<class 'sage.categories.modules.Modules'>,)\n sage: GradedAlgebrasWithBasis._base_category_class\n (<class 'sage.categories.algebras_with_basis.AlgebrasWithBasis'>,)\n\n The reason for wrapping the base category class in a tuple is\n that, often, the base category class implements a\n :meth:`__classget__` method which would get in the way upon\n attribute access::\n\n sage: F = GradedAlgebrasWithBasis\n sage: F._foo = F._base_category_class[0]\n sage: F._foo\n Traceback (most recent call last):\n ...\n AssertionError: base category class for <...AlgebrasWithBasis'>\n mismatch; expected <...Algebras'>,\n got <...GradedAlgebrasWithBasis'>\n\n We note that because ``Algebras.WithBasis`` is not lazily imported\n on startup (see :trac:`22955`), the test fails at a different\n point in the code. However, if this import becomes lazy again, then\n the following error will be generated and can replace the above::\n\n sage: F._foo # not tested\n Traceback (most recent call last):\n ...\n ValueError: could not infer axiom for the nested class\n <...AlgebrasWithBasis'> of <...GradedAlgebrasWithBasis'>\n\n .. TODO::\n\n The logic is very similar to that implemented in\n :class:`CategoryWithAxiom._base_category_class`. Find a\n way to refactor this to avoid the duplication.\n " module_name = cls.__module__.replace((cls._functor_category.lower() + '_'), '') import sys name = cls.__name__.replace(cls._functor_category, '') __import__(module_name) module = sys.modules[module_name] return (module.__dict__[name],) @staticmethod def __classcall__(cls, category=None, *args): '\n Make ``XXXCat(**)`` a shorthand for ``Cat(**).XXX()``.\n\n EXAMPLES::\n\n sage: GradedModules(ZZ) # indirect doctest\n Category of graded modules over Integer Ring\n sage: Modules(ZZ).Graded()\n Category of graded modules over Integer Ring\n sage: Modules.Graded(ZZ)\n Category of graded modules over Integer Ring\n sage: GradedModules(ZZ) is Modules(ZZ).Graded()\n True\n\n .. SEEALSO:: :meth:`_base_category_class`\n\n .. TODO::\n\n The logic is very similar to that implemented in\n :class:`CategoryWithAxiom.__classcall__`. Find a way to\n refactor this to avoid the duplication.\n ' base_category_class = cls._base_category_class[0] if isinstance(category, base_category_class): return super().__classcall__(cls, category, *args) else: return cls.category_of(base_category_class(category, *args)) @staticmethod def __classget__(cls, base_category, base_category_class): '\n Special binding for covariant constructions.\n\n This implements a hack allowing e.g. ``category.Subquotients``\n to recover the default ``Subquotients`` method defined in\n ``Category``, even if it has been overridden by a\n ``Subquotients`` class.\n\n EXAMPLES::\n\n sage: Sets.Subquotients\n <class \'sage.categories.sets_cat.Sets.Subquotients\'>\n sage: Sets().Subquotients\n Cached version of <function ...Subquotients at ...>\n\n This method also initializes the attribute\n ``_base_category_class`` if not already set::\n\n sage: Sets.Subquotients._base_category_class\n (<class \'sage.categories.sets_cat.Sets\'>,)\n\n It also forces the resolution of lazy imports (see :trac:`15648`)::\n\n sage: type(Algebras.__dict__["Graded"])\n <class \'sage.misc.lazy_import.LazyImport\'>\n sage: Algebras.Graded\n <class \'sage.categories.graded_algebras.GradedAlgebras\'>\n sage: type(Algebras.__dict__["Graded"])\n <class \'sage.misc.classcall_metaclass.ClasscallMetaclass\'>\n\n .. TODO::\n\n The logic is very similar to that implemented in\n :class:`CategoryWithAxiom.__classget__`. Find a way to\n refactor this to avoid the duplication.\n ' if (base_category is not None): assert (base_category.__class__ is base_category_class) assert isinstance(base_category_class, DynamicMetaclass) if isinstance(base_category_class, DynamicMetaclass): base_category_class = base_category_class.__base__ if ('_base_category_class' not in cls.__dict__): cls._base_category_class = (base_category_class,) else: assert (cls._base_category_class[0] is base_category_class), 'base category class for {} mismatch; expected {}, got {}'.format(cls, cls._base_category_class[0], base_category_class) if isinstance(base_category_class.__dict__[cls._functor_category], LazyImport): setattr(base_category_class, cls._functor_category, cls) if (base_category is None): return cls return getattr(super(base_category.__class__.__base__, base_category), cls._functor_category) @classmethod @cached_function def category_of(cls, category, *args): '\n Return the image category of the functor `F_{Cat}`.\n\n This is the main entry point for constructing the category\n `F_{Cat}` of parents `F(A,B,...)` constructed from parents\n `A,B,...` in `Cat`.\n\n INPUT:\n\n - ``cls`` -- the category class for the functorial construction `F`\n - ``category`` -- a category `Cat`\n - ``*args`` -- further arguments for the functor\n\n EXAMPLES::\n\n sage: C = sage.categories.tensor.TensorProductsCategory\n sage: C.category_of(ModulesWithBasis(QQ))\n Category of tensor products of vector spaces with basis over Rational Field\n\n sage: C = sage.categories.algebra_functor.AlgebrasCategory\n sage: C.category_of(FiniteMonoids(), QQ)\n Join of Category of finite dimensional algebras with basis over Rational Field\n and Category of monoid algebras over Rational Field\n and Category of finite set algebras over Rational Field\n ' functor_category = getattr(category.__class__, cls._functor_category) if (isinstance(functor_category, type) and issubclass(functor_category, Category)): return functor_category(category, *args) else: return cls.default_super_categories(category, *args) def __init__(self, category, *args): '\n TESTS::\n\n sage: from sage.categories.covariant_functorial_construction import CovariantConstructionCategory\n sage: class FooBars(CovariantConstructionCategory):\n ....: _functor_category = "FooBars"\n ....: _base_category_class = (Category,)\n sage: Category.FooBars = lambda self: FooBars.category_of(self)\n sage: C = FooBars(ModulesWithBasis(ZZ))\n sage: C\n Category of foo bars of modules with basis over Integer Ring\n sage: C.base_category()\n Category of modules with basis over Integer Ring\n sage: latex(C)\n \\mathbf{FooBars}(\\mathbf{ModulesWithBasis}_{\\Bold{Z}})\n sage: import __main__; __main__.FooBars = FooBars # Fake FooBars being defined in a python module\n sage: TestSuite(C).run()\n ' assert isinstance(category, Category) self._base_category = category self._args = args super().__init__(*args) def base_category(self): '\n Return the base category of the category ``self``.\n\n For any category ``B`` = `F_{Cat}` obtained through a functorial\n construction `F`, the call ``B.base_category()`` returns the\n category `Cat`.\n\n EXAMPLES::\n\n sage: Semigroups().Quotients().base_category()\n Category of semigroups\n ' return self._base_category def extra_super_categories(self): '\n Return the extra super categories of a construction category.\n\n Default implementation which returns ``[]``.\n\n EXAMPLES::\n\n sage: Sets().Subquotients().extra_super_categories()\n []\n sage: Semigroups().Quotients().extra_super_categories()\n []\n ' return [] def super_categories(self): '\n Return the super categories of a construction category.\n\n EXAMPLES::\n\n sage: Sets().Subquotients().super_categories()\n [Category of sets]\n sage: Semigroups().Quotients().super_categories()\n [Category of subquotients of semigroups, Category of quotients of sets]\n ' return Category.join(([self.__class__.default_super_categories(self.base_category(), *self._args)] + self.extra_super_categories()), as_list=True) def _repr_object_names(self): '\n EXAMPLES::\n\n sage: Semigroups().Subquotients() # indirect doctest\n Category of subquotients of semigroups\n ' return ('%s of %s' % (Category._repr_object_names(self), self.base_category()._repr_object_names())) def _latex_(self): '\n EXAMPLES::\n\n sage: latex(Semigroups().Subquotients()) # indirect doctest\n \\mathbf{Subquotients}(\\mathbf{Semigroups})\n sage: latex(ModulesWithBasis(QQ).TensorProducts())\n \\mathbf{TensorProducts}(\\mathbf{WithBasis}_{\\Bold{Q}})\n sage: latex(Semigroups().Algebras(QQ))\n \\mathbf{Algebras}(\\mathbf{Semigroups})\n ' from sage.misc.latex import latex return ('\\mathbf{%s}(%s)' % (self._short_name(), latex(self.base_category())))
class CovariantConstructionCategory(FunctorialConstructionCategory): '\n Abstract class for categories `F_{Cat}` obtained through a\n covariant functorial construction\n ' @classmethod def default_super_categories(cls, category, *args): '\n Return the default super categories of `F_{Cat}(A,B,...)` for\n `A,B,...` parents in `Cat`.\n\n INPUT:\n\n - ``cls`` -- the category class for the functor `F`\n - ``category`` -- a category `Cat`\n - ``*args`` -- further arguments for the functor\n\n OUTPUT: a (join) category\n\n The default implementation is to return the join of the\n categories of `F(A,B,...)` for `A,B,...` in turn in each of\n the super categories of ``category``.\n\n This is implemented as a class method, in order to be able to\n reconstruct the functorial category associated to each of the\n super categories of ``category``.\n\n EXAMPLES:\n\n Bialgebras are both algebras and coalgebras::\n\n sage: Bialgebras(QQ).super_categories()\n [Category of algebras over Rational Field,\n Category of coalgebras over Rational Field]\n\n Hence tensor products of bialgebras are tensor products of\n algebras and tensor products of coalgebras::\n\n sage: Bialgebras(QQ).TensorProducts().super_categories()\n [Category of tensor products of algebras over Rational Field,\n Category of tensor products of coalgebras over Rational Field]\n\n Here is how :meth:`default_super_categories` was called internally::\n\n sage: C = sage.categories.tensor.TensorProductsCategory\n sage: C.default_super_categories(Bialgebras(QQ))\n Join of Category of tensor products of algebras over Rational Field\n and Category of tensor products of coalgebras over Rational Field\n\n We now show a similar example, with the ``Algebra`` functor\n which takes a parameter `\\QQ`::\n\n sage: FiniteMonoids().super_categories()\n [Category of monoids, Category of finite semigroups]\n sage: sorted(FiniteMonoids().Algebras(QQ).super_categories(), key=str)\n [Category of finite dimensional algebras with basis over Rational Field,\n Category of finite set algebras over Rational Field,\n Category of monoid algebras over Rational Field]\n\n Note that neither the category of *finite* semigroup algebras\n nor that of monoid algebras appear in the result; this is\n because there is currently nothing specific implemented about them.\n\n Here is how :meth:`default_super_categories` was called internally::\n\n sage: C = sage.categories.algebra_functor.AlgebrasCategory\n sage: C.default_super_categories(FiniteMonoids(), QQ)\n Join of Category of finite dimensional algebras with basis over Rational Field\n and Category of monoid algebras over Rational Field\n and Category of finite set algebras over Rational Field\n ' return Category.join([getattr(cat, cls._functor_category)(*args) for cat in category._super_categories if hasattr(cat, cls._functor_category)]) def is_construction_defined_by_base(self): "\n Return whether the construction is defined by the base of ``self``.\n\n EXAMPLES:\n\n The graded functorial construction is defined by the modules\n category. Hence this method returns ``True`` for graded\n modules and ``False`` for other graded xxx categories::\n\n sage: Modules(ZZ).Graded().is_construction_defined_by_base()\n True\n sage: Algebras(QQ).Graded().is_construction_defined_by_base()\n False\n sage: Modules(ZZ).WithBasis().Graded().is_construction_defined_by_base()\n False\n\n This is implemented as follows: given the base category `A`\n and the construction `F` of ``self``, that is ``self=A.F()``,\n check whether no super category of `A` has `F` defined.\n\n .. NOTE::\n\n Recall that, when `A` does not implement the construction\n ``F``, a join category is returned. Therefore, in such\n cases, this method is not available::\n\n sage: Bialgebras(QQ).Graded().is_construction_defined_by_base()\n Traceback (most recent call last):\n ...\n AttributeError: 'JoinCategory_with_category' object has\n no attribute 'is_construction_defined_by_base'\n " base = self.base_category() f = self._functor_category return (not any((hasattr(C, f) for C in base.super_categories()))) def additional_structure(self): "\n Return the additional structure defined by ``self``.\n\n By default, a functorial construction category ``A.F()``\n defines additional structure if and only if `A` is the\n category defining `F`. The rationale is that, for a\n subcategory `B` of `A`, the fact that `B.F()` morphisms shall\n preserve the `F`-specific structure is already imposed by\n `A.F()`.\n\n .. SEEALSO::\n\n - :meth:`Category.additional_structure`.\n - :meth:`is_construction_defined_by_base`.\n\n EXAMPLES::\n\n sage: Modules(ZZ).Graded().additional_structure()\n Category of graded modules over Integer Ring\n sage: Algebras(ZZ).Graded().additional_structure()\n\n TESTS::\n\n sage: Modules(ZZ).Graded().additional_structure.__module__\n 'sage.categories.covariant_functorial_construction'\n " if self.is_construction_defined_by_base(): return self else: return None
class RegressiveCovariantConstructionCategory(CovariantConstructionCategory): '\n Abstract class for categories `F_{Cat}` obtained through a\n regressive covariant functorial construction\n ' @classmethod def default_super_categories(cls, category, *args): '\n Return the default super categories of `F_{Cat}(A,B,...)` for\n `A,B,...` parents in `Cat`.\n\n INPUT:\n\n - ``cls`` -- the category class for the functor `F`\n - ``category`` -- a category `Cat`\n - ``*args`` -- further arguments for the functor\n\n OUTPUT:\n\n A join category.\n\n This implements the property that an induced subcategory is a\n subcategory.\n\n EXAMPLES:\n\n A subquotient of a monoid is a monoid, and a subquotient of\n semigroup::\n\n sage: Monoids().Subquotients().super_categories()\n [Category of monoids, Category of subquotients of semigroups]\n\n TESTS::\n\n sage: C = Monoids().Subquotients()\n sage: C.__class__.default_super_categories(C.base_category(), *C._args)\n Category of unital subquotients of semigroups\n ' return Category.join([category, super().default_super_categories(category, *args)])
class CoxeterGroupAlgebras(AlgebrasCategory): class ParentMethods(): def demazure_lusztig_operator_on_basis(self, w, i, q1, q2, side='right'): '\n Return the result of applying the `i`-th Demazure Lusztig\n operator on ``w``.\n\n INPUT:\n\n - ``w`` -- an element of the Coxeter group\n - ``i`` -- an element of the index set\n - ``q1,q2`` -- two elements of the ground ring\n - ``bar`` -- a boolean (default ``False``)\n\n See :meth:`demazure_lusztig_operators` for details.\n\n EXAMPLES::\n\n sage: W = WeylGroup(["B",3])\n sage: W.element_class._repr_=lambda x: "".join(str(i) for i in x.reduced_word())\n sage: K = QQ[\'q1,q2\']\n sage: q1, q2 = K.gens()\n sage: KW = W.algebra(K)\n sage: w = W.an_element()\n sage: KW.demazure_lusztig_operator_on_basis(w, 0, q1, q2)\n (-q2)*323123 + (q1+q2)*123\n sage: KW.demazure_lusztig_operator_on_basis(w, 1, q1, q2)\n q1*1231\n sage: KW.demazure_lusztig_operator_on_basis(w, 2, q1, q2)\n q1*1232\n sage: KW.demazure_lusztig_operator_on_basis(w, 3, q1, q2)\n (q1+q2)*123 + (-q2)*12\n\n At `q_1=1` and `q_2=0` we recover the action of the\n isobaric divided differences `\\pi_i`::\n\n sage: KW.demazure_lusztig_operator_on_basis(w, 0, 1, 0)\n 123\n sage: KW.demazure_lusztig_operator_on_basis(w, 1, 1, 0)\n 1231\n sage: KW.demazure_lusztig_operator_on_basis(w, 2, 1, 0)\n 1232\n sage: KW.demazure_lusztig_operator_on_basis(w, 3, 1, 0)\n 123\n\n At `q_1=1` and `q_2=-1` we recover the action of the\n simple reflection `s_i`::\n\n sage: KW.demazure_lusztig_operator_on_basis(w, 0, 1, -1)\n 323123\n sage: KW.demazure_lusztig_operator_on_basis(w, 1, 1, -1)\n 1231\n sage: KW.demazure_lusztig_operator_on_basis(w, 2, 1, -1)\n 1232\n sage: KW.demazure_lusztig_operator_on_basis(w, 3, 1, -1)\n 12\n ' return (((q1 + q2) * self.monomial(w.apply_simple_projection(i, side=side))) - self.term(w.apply_simple_reflection(i, side=side), q2)) def demazure_lusztig_operators(self, q1, q2, side='right', affine=True): '\n Return the Demazure Lusztig operators acting on ``self``.\n\n INPUT:\n\n - ``q1,q2`` -- two elements of the ground ring `K`\n - ``side`` -- ``"left"`` or ``"right"`` (default: ``"right"``);\n which side to act upon\n - ``affine`` -- a boolean (default: ``True``)\n\n The Demazure-Lusztig operator `T_i` is the linear map\n `R \\to R` obtained by interpolating between the\n simple projection `\\pi_i` (see\n :meth:`CoxeterGroups.ElementMethods.simple_projection`)\n and the simple reflection `s_i` so that `T_i` has\n eigenvalues `q_1` and `q_2`:\n\n .. MATH::\n\n (q_1 + q_2) \\pi_i - q_2 s_i.\n\n The Demazure-Lusztig operators give the usual\n representation of the operators `T_i` of the `q_1,q_2`\n Hecke algebra associated to the Coxeter group.\n\n For a finite Coxeter group, and if ``affine=True``, the\n Demazure-Lusztig operators `T_1,\\dots,T_n` are completed\n by `T_0` to implement the level `0` action of the affine\n Hecke algebra.\n\n EXAMPLES::\n\n sage: W = WeylGroup(["B",3])\n sage: W.element_class._repr_=lambda x: "".join(str(i) for i in x.reduced_word())\n sage: K = QQ[\'q1,q2\']\n sage: q1, q2 = K.gens()\n sage: KW = W.algebra(K)\n sage: T = KW.demazure_lusztig_operators(q1, q2, affine=True)\n sage: x = KW.monomial(W.an_element()); x\n 123\n sage: T[0](x)\n (-q2)*323123 + (q1+q2)*123\n sage: T[1](x)\n q1*1231\n sage: T[2](x)\n q1*1232\n sage: T[3](x)\n (q1+q2)*123 + (-q2)*12\n\n sage: T._test_relations()\n\n .. NOTE::\n\n For a finite Weyl group `W`, the level 0 action of the\n affine Weyl group `\\tilde W` only depends on the\n Coxeter diagram of the affinization, not its Dynkin\n diagram. Hence it is possible to explore all cases\n using only untwisted affinizations.\n ' from sage.combinat.root_system.hecke_algebra_representation import HeckeAlgebraRepresentation W = self.basis().keys() cartan_type = W.cartan_type() if (affine and cartan_type.is_finite()): cartan_type = cartan_type.affine() T_on_basis = functools.partial(self.demazure_lusztig_operator_on_basis, q1=q1, q2=q2, side=side) return HeckeAlgebraRepresentation(self, T_on_basis, cartan_type, q1, q2) @cached_method def demazure_lusztig_eigenvectors(self, q1, q2): '\n Return the family of eigenvectors for the Cherednik operators.\n\n INPUT:\n\n - ``self`` -- a finite Coxeter group `W`\n - ``q1,q2`` -- two elements of the ground ring `K`\n\n The affine Hecke algebra `H_{q_1,q_2}(\\tilde W)` acts on\n the group algebra of `W` through the Demazure-Lusztig\n operators `T_i`. Its Cherednik operators `Y^\\lambda` can\n be simultaneously diagonalized as long as `q_1/q_2` is not\n a small root of unity [HST2008]_.\n\n This method returns the family of joint eigenvectors,\n indexed by `W`.\n\n .. SEEALSO::\n\n - :meth:`demazure_lusztig_operators`\n - :class:`sage.combinat.root_system.hecke_algebra_representation.CherednikOperatorsEigenvectors`\n\n EXAMPLES::\n\n sage: W = WeylGroup(["B",2])\n sage: W.element_class._repr_=lambda x: "".join(str(i) for i in x.reduced_word())\n sage: K = QQ[\'q1,q2\'].fraction_field()\n sage: q1, q2 = K.gens()\n sage: KW = W.algebra(K)\n sage: E = KW.demazure_lusztig_eigenvectors(q1,q2)\n sage: E.keys() # needs sage.rings.number_field\n Weyl Group of type [\'B\', 2] (as a matrix group acting on the ambient space)\n sage: w = W.an_element()\n sage: E[w] # needs sage.rings.number_field\n (q2/(-q1+q2))*2121 + ((-q2)/(-q1+q2))*121 - 212 + 12\n ' W = self.basis().keys() if (not W.cartan_type().is_finite()): raise ValueError('the Demazure-Lusztig eigenvectors are only defined for finite Coxeter groups') result = self.demazure_lusztig_operators(q1, q2, affine=True).Y_eigenvectors() w0 = W.long_element() result.affine_lift = w0._mul_ result.affine_retract = w0._mul_ return result
class CoxeterGroups(Category_singleton): '\n The category of Coxeter groups.\n\n A *Coxeter group* is a group `W` with a distinguished (finite)\n family of involutions `(s_i)_{i\\in I}`, called the *simple\n reflections*, subject to relations of the form `(s_is_j)^{m_{i,j}} = 1`.\n\n `I` is the *index set* of `W` and `|I|` is the *rank* of `W`.\n\n See :wikipedia:`Coxeter_group` for details.\n\n EXAMPLES::\n\n sage: C = CoxeterGroups(); C\n Category of Coxeter groups\n sage: C.super_categories()\n [Category of generalized Coxeter groups]\n\n sage: W = C.example(); W\n The symmetric group on {0, ..., 3}\n\n sage: W.simple_reflections()\n Finite family {0: (1, 0, 2, 3), 1: (0, 2, 1, 3), 2: (0, 1, 3, 2)}\n\n Here are some further examples::\n\n sage: FiniteCoxeterGroups().example()\n The 5-th dihedral group of order 10\n sage: FiniteWeylGroups().example()\n The symmetric group on {0, ..., 3}\n sage: WeylGroup(["B", 3]) # needs sage.combinat sage.groups\n Weyl Group of type [\'B\', 3] (as a matrix group acting on the ambient space)\n\n sage: S4 = SymmetricGroup(4); S4 # needs sage.groups\n Symmetric group of order 4! as a permutation group\n sage: S4 in CoxeterGroups().Finite() # needs sage.groups\n True\n\n Those will eventually be also in this category::\n\n sage: DihedralGroup(5) # needs sage.groups\n Dihedral group of order 10 as a permutation group\n\n .. TODO:: add a demo of usual computations on Coxeter groups.\n\n .. SEEALSO::\n\n - :mod:`sage.combinat.root_system`\n - :class:`WeylGroups`\n - :class:`GeneralizedCoxeterGroups`\n\n .. WARNING::\n\n It is assumed that morphisms in this category preserve the\n distinguished choice of simple reflections. In particular,\n subobjects in this category are parabolic subgroups. In this\n sense, this category might be better named ``Coxeter\n Systems``. In the long run we might want to have two distinct\n categories, one for Coxeter groups (with morphisms being just\n group morphisms) and one for Coxeter systems::\n\n sage: CoxeterGroups().is_full_subcategory(Groups())\n False\n sage: from sage.categories.generalized_coxeter_groups import GeneralizedCoxeterGroups\n sage: CoxeterGroups().is_full_subcategory(GeneralizedCoxeterGroups())\n True\n\n TESTS::\n\n sage: W = CoxeterGroups().example()\n sage: TestSuite(W).run()\n ' def super_categories(self): '\n EXAMPLES::\n\n sage: CoxeterGroups().super_categories()\n [Category of generalized Coxeter groups]\n ' return [GeneralizedCoxeterGroups()] def additional_structure(self): '\n Return ``None``.\n\n Indeed, all the structure Coxeter groups have in addition to\n groups (simple reflections, ...) is already defined in the\n super category.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n EXAMPLES::\n\n sage: CoxeterGroups().additional_structure()\n ' return None Finite = LazyImport('sage.categories.finite_coxeter_groups', 'FiniteCoxeterGroups') Algebras = LazyImport('sage.categories.coxeter_group_algebras', 'CoxeterGroupAlgebras') class ParentMethods(): @abstract_method def coxeter_matrix(self): "\n Return the Coxeter matrix associated to ``self``.\n\n EXAMPLES::\n\n sage: G = WeylGroup(['A', 3]) # needs sage.combinat sage.groups\n sage: G.coxeter_matrix() # needs sage.combinat sage.groups\n [1 3 2]\n [3 1 3]\n [2 3 1]\n " @cached_method def index_set(self): "\n Return the index set of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = CoxeterGroup([[1,3],[3,1]])\n sage: W.index_set()\n (1, 2)\n sage: W = CoxeterGroup([[1,3],[3,1]], index_set=['x', 'y'])\n sage: W.index_set()\n ('x', 'y')\n sage: W = CoxeterGroup(['H', 3])\n sage: W.index_set()\n (1, 2, 3)\n " return self.coxeter_matrix().index_set() def coxeter_diagram(self): '\n Return the Coxeter diagram of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.graphs sage.groups\n sage: W = CoxeterGroup([\'H\', 3], implementation="reflection")\n sage: G = W.coxeter_diagram(); G\n Graph on 3 vertices\n sage: G.edges(sort=True)\n [(1, 2, 3), (2, 3, 5)]\n sage: CoxeterGroup(G) is W\n True\n sage: G = Graph([(0, 1, 3), (1, 2, oo)])\n sage: W = CoxeterGroup(G)\n sage: W.coxeter_diagram() == G\n True\n sage: CoxeterGroup(W.coxeter_diagram()) is W\n True\n ' return self.coxeter_matrix().coxeter_graph() def coxeter_type(self): "\n Return the Coxeter type of ``self``.\n\n EXAMPLES::\n\n sage: W = CoxeterGroup(['H', 3]) # needs sage.combinat sage.groups\n sage: W.coxeter_type() # needs sage.combinat sage.groups\n Coxeter type of ['H', 3]\n " return self.coxeter_matrix().coxeter_type() def braid_relations(self): '\n Return the braid relations of ``self`` as a list of reduced\n words of the braid relations.\n\n EXAMPLES::\n\n sage: W = WeylGroup(["A", 2]) # needs sage.combinat sage.groups\n sage: W.braid_relations() # needs sage.combinat sage.groups\n [[[1, 2, 1], [2, 1, 2]]]\n\n sage: W = WeylGroup(["B", 3]) # needs sage.combinat sage.groups\n sage: W.braid_relations() # needs sage.combinat sage.groups\n [[[1, 2, 1], [2, 1, 2]], [[1, 3], [3, 1]], [[2, 3, 2, 3], [3, 2, 3, 2]]]\n ' rels = [] M = self.coxeter_matrix() I = self.index_set() for (ii, i) in enumerate(I): for j in I[(ii + 1):]: m = M[(i, j)] rel = ([i, j] * m) rels.append([rel[:m], (rel[m:] if (m % 2) else list(reversed(rel[m:])))]) return rels def braid_group_as_finitely_presented_group(self): '\n Return the associated braid group.\n\n EXAMPLES::\n\n sage: W = CoxeterGroup([\'A\', 2]) # needs sage.combinat sage.groups\n sage: W.braid_group_as_finitely_presented_group() # needs sage.combinat sage.groups\n Finitely presented group < S1, S2 | S1*S2*S1*S2^-1*S1^-1*S2^-1 >\n\n sage: W = WeylGroup([\'B\', 2]) # needs sage.combinat sage.groups\n sage: W.braid_group_as_finitely_presented_group() # needs sage.combinat sage.groups\n Finitely presented group < S1, S2 | (S1*S2)^2*(S1^-1*S2^-1)^2 >\n\n sage: W = ReflectionGroup([\'B\',3], index_set=["AA","BB","5"]) # optional - gap3\n sage: W.braid_group_as_finitely_presented_group() # optional - gap3\n Finitely presented group < SAA, SBB, S5 |\n (SAA*SBB)^2*(SAA^-1*SBB^-1)^2, SAA*S5*SAA^-1*S5^-1,\n SBB*S5*SBB*S5^-1*SBB^-1*S5^-1 >\n ' from sage.groups.free_group import FreeGroup from sage.misc.misc_c import prod I = self.index_set() F = FreeGroup([('S%s' % i) for i in I]) S = F.gens() rels = self.braid_relations() return (F / [(prod((S[I.index(i)] for i in l)) * prod(((S[I.index(i)] ** (- 1)) for i in reversed(r)))) for (l, r) in rels]) def braid_orbit_iter(self, word): '\n Iterate over the braid orbit of a word ``word`` of indices.\n\n The input word does not need to be a reduced expression of\n an element.\n\n INPUT:\n\n - ``word`` -- a list (or iterable) of indices in\n ``self.index_set()``\n\n OUTPUT:\n\n all lists that can be obtained from\n ``word`` by replacements of braid relations\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: sorted(W.braid_orbit_iter([0, 1, 2, 1])) # needs sage.combinat sage.graphs\n [[0, 1, 2, 1], [0, 2, 1, 2], [2, 0, 1, 2]]\n ' word = list(word) from sage.combinat.root_system.braid_orbit import BraidOrbit braid_rels = self.braid_relations() I = self.index_set() from sage.rings.integer_ring import ZZ be_careful = any(((i not in ZZ) for i in I)) if be_careful: Iinv = {i: j for (j, i) in enumerate(I)} word = [Iinv[i] for i in word] braid_rels = [[[Iinv[i] for i in l], [Iinv[i] for i in r]] for (l, r) in braid_rels] orb = BraidOrbit(word, braid_rels) if be_careful: for word in orb: (yield [I[i] for i in word]) else: for I in orb: (yield list(I)) def braid_orbit(self, word): '\n Return the braid orbit of a word ``word`` of indices.\n\n The input word does not need to be a reduced expression of\n an element.\n\n INPUT:\n\n - ``word``: a list (or iterable) of indices in\n ``self.index_set()``\n\n OUTPUT:\n\n a list of all lists that can be obtained from\n ``word`` by replacements of braid relations\n\n See :meth:`braid_relations` for the definition of braid\n relations.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: s = W.simple_reflections()\n sage: w = s[0] * s[1] * s[2] * s[1]\n sage: word = w.reduced_word(); word\n [0, 1, 2, 1]\n\n sage: sorted(W.braid_orbit(word)) # needs sage.combinat sage.graphs\n [[0, 1, 2, 1], [0, 2, 1, 2], [2, 0, 1, 2]]\n\n sage: sorted(W.braid_orbit([2,1,1,2,1])) # needs sage.combinat sage.graphs\n [[1, 2, 1, 1, 2], [2, 1, 1, 2, 1], [2, 1, 2, 1, 2], [2, 2, 1, 2, 2]]\n\n sage: # optional - gap3\n sage: W = ReflectionGroup([\'A\',3], index_set=["AA","BB","5"])\n sage: w = W.long_element()\n sage: W.braid_orbit(w.reduced_word())\n [[\'BB\', \'5\', \'AA\', \'BB\', \'5\', \'AA\'],\n [\'5\', \'BB\', \'5\', \'AA\', \'BB\', \'5\'],\n [\'BB\', \'AA\', \'BB\', \'5\', \'BB\', \'AA\'],\n [\'AA\', \'5\', \'BB\', \'AA\', \'5\', \'BB\'],\n [\'5\', \'AA\', \'BB\', \'AA\', \'5\', \'BB\'],\n [\'AA\', \'BB\', \'5\', \'AA\', \'BB\', \'AA\'],\n [\'AA\', \'BB\', \'AA\', \'5\', \'BB\', \'AA\'],\n [\'AA\', \'BB\', \'5\', \'BB\', \'AA\', \'BB\'],\n [\'BB\', \'AA\', \'5\', \'BB\', \'AA\', \'5\'],\n [\'BB\', \'5\', \'AA\', \'BB\', \'AA\', \'5\'],\n [\'AA\', \'5\', \'BB\', \'5\', \'AA\', \'BB\'],\n [\'5\', \'BB\', \'AA\', \'5\', \'BB\', \'5\'],\n [\'5\', \'BB\', \'AA\', \'BB\', \'5\', \'BB\'],\n [\'5\', \'AA\', \'BB\', \'5\', \'AA\', \'BB\'],\n [\'BB\', \'5\', \'BB\', \'AA\', \'BB\', \'5\'],\n [\'BB\', \'AA\', \'5\', \'BB\', \'5\', \'AA\']]\n\n .. TODO::\n\n The result should be full featured finite enumerated set\n (e.g., counting can be done much faster than iterating).\n\n .. SEEALSO::\n\n :meth:`.reduced_words`\n ' return list(self.braid_orbit_iter(word)) def __iter__(self): '\n Return an iterator over the elements of this Coxeter group.\n\n EXAMPLES::\n\n sage: D5 = FiniteCoxeterGroups().example(5)\n sage: sorted(list(D5)) # indirect doctest (but see :meth:`._test_enumerated_set_iter_list`)\n [(),\n (1,),\n (1, 2),\n (1, 2, 1),\n (1, 2, 1, 2),\n (1, 2, 1, 2, 1),\n (2,),\n (2, 1),\n (2, 1, 2),\n (2, 1, 2, 1)]\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup(["A", 2, 1])\n sage: g = iter(W)\n sage: next(g)\n [1 0 0]\n [0 1 0]\n [0 0 1]\n sage: next(g)\n [-1 1 1]\n [ 0 1 0]\n [ 0 0 1]\n sage: next(g)\n [ 1 0 0]\n [ 1 -1 1]\n [ 0 0 1]\n ' return iter(self.weak_order_ideal(predicate=ConstantFunction(True))) def _element_constructor_(self, x, **args): '\n Construct an element of ``self`` from ``x``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W1 = WeylGroup("G2", prefix="s")\n sage: W2 = CoxeterGroup("G2")\n sage: W3 = CoxeterGroup("G2", implementation="permutation")\n sage: W1(W2.an_element())\n s1*s2\n sage: W2(W1.an_element())\n [ 2 -a]\n [ a -1]\n sage: W1(W3.an_element())\n s1*s2\n sage: s1, s2 = W1.simple_reflections()\n sage: W = CoxeterGroup("A1")\n sage: W(s1 * s2)\n Traceback (most recent call last):\n ...\n ValueError: inconsistent number of rows: should be 1 but got 3\n ' P = parent(x) if (P in CoxeterGroups()): try: return self.from_reduced_word(x.reduced_word()) except KeyError: pass return self.element_class(self, x, **args) def weak_order_ideal(self, predicate, side='right', category=None): '\n Return a weak order ideal defined by a predicate\n\n INPUT:\n\n - ``predicate``: a predicate on the elements of ``self`` defining an\n weak order ideal in ``self``\n - ``side``: "left" or "right" (default: "right")\n\n OUTPUT: an enumerated set\n\n EXAMPLES::\n\n sage: D6 = FiniteCoxeterGroups().example(5)\n sage: I = D6.weak_order_ideal(predicate=lambda w: w.length() <= 3)\n sage: I.cardinality()\n 7\n sage: list(I)\n [(), (1,), (2,), (1, 2), (2, 1), (1, 2, 1), (2, 1, 2)]\n\n We now consider an infinite Coxeter group::\n\n sage: W = WeylGroup(["A",1,1]) # needs sage.groups sage.rings.number_field\n sage: I = W.weak_order_ideal(predicate=lambda w: w.length() <= 2) # needs sage.groups sage.rings.number_field\n sage: list(iter(I)) # needs sage.groups sage.rings.number_field\n [\n [1 0] [-1 2] [ 1 0] [ 3 -2] [-1 2]\n [0 1], [ 0 1], [ 2 -1], [ 2 -1], [-2 3]\n ]\n\n Even when the result is finite, some features of\n :class:`FiniteEnumeratedSets` are not available::\n\n sage: I.cardinality() # todo: not implemented\n 5\n sage: list(I) # todo: not implemented\n\n unless this finiteness is explicitly specified::\n\n sage: I = W.weak_order_ideal(predicate=lambda w: w.length() <= 2, # needs sage.groups sage.rings.number_field\n ....: category=FiniteEnumeratedSets())\n sage: I.cardinality() # needs sage.groups sage.rings.number_field\n 5\n sage: list(I) # needs sage.groups sage.rings.number_field\n [\n [1 0] [-1 2] [ 1 0] [ 3 -2] [-1 2]\n [0 1], [ 0 1], [ 2 -1], [ 2 -1], [-2 3]\n ]\n\n .. rubric:: Background\n\n The weak order is returned as a :class:`RecursivelyEnumeratedSet_forest`.\n This is achieved by assigning to each element `u1` of the\n ideal a single ancestor `u=u1 s_i`, where `i` is the\n smallest descent of `u`.\n\n This allows for iterating through the elements in\n roughly Constant Amortized Time and constant memory\n (taking the operations and size of the generated objects\n as constants).\n\n TESTS:\n\n We iterate over each level (i.e., breadth-first-search in the\n search forest), see :trac:`19926`::\n\n sage: W = CoxeterGroup([\'A\',2]) # needs sage.groups sage.rings.number_field\n sage: [x.length() for x in W] # needs sage.groups sage.rings.number_field\n [0, 1, 1, 2, 2, 3]\n ' from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet_forest def succ(u): for i in u.descents(positive=True, side=side): u1 = u.apply_simple_reflection(i, side) if ((i == u1.first_descent(side=side)) and predicate(u1)): (yield u1) from sage.categories.finite_coxeter_groups import FiniteCoxeterGroups default_category = (FiniteEnumeratedSets() if (self in FiniteCoxeterGroups()) else EnumeratedSets()) cat = default_category.or_subcategory(category) return RecursivelyEnumeratedSet_forest((self.one(),), succ, algorithm='breadth', category=cat) @cached_method def coxeter_element(self): "\n Return a Coxeter element.\n\n The result is the product of the simple reflections, in some order.\n\n .. NOTE::\n\n This implementation is shared with well generated\n complex reflection groups. It would be nicer to put it\n in some joint super category; however, in the current\n state of the art, there is none where it is clear that\n this is the right construction for obtaining a Coxeter\n element.\n\n In this context, this is an element having a regular\n eigenvector (a vector not contained in any reflection\n hyperplane of ``self``).\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: CoxeterGroup(['A', 4]).coxeter_element().reduced_word()\n [1, 2, 3, 4]\n sage: CoxeterGroup(['B', 4]).coxeter_element().reduced_word()\n [1, 2, 3, 4]\n sage: CoxeterGroup(['D', 4]).coxeter_element().reduced_word()\n [1, 2, 4, 3]\n sage: CoxeterGroup(['F', 4]).coxeter_element().reduced_word()\n [1, 2, 3, 4]\n sage: CoxeterGroup(['E', 8]).coxeter_element().reduced_word()\n [1, 3, 2, 4, 5, 6, 7, 8]\n sage: CoxeterGroup(['H', 3]).coxeter_element().reduced_word()\n [1, 2, 3]\n\n This method is also used for well generated finite complex\n reflection groups::\n\n sage: W = ReflectionGroup((1,1,4)) # optional - gap3\n sage: W.coxeter_element().reduced_word() # optional - gap3\n [1, 2, 3]\n\n sage: W = ReflectionGroup((2,1,4)) # optional - gap3\n sage: W.coxeter_element().reduced_word() # optional - gap3\n [1, 2, 3, 4]\n\n sage: W = ReflectionGroup((4,1,4)) # optional - gap3\n sage: W.coxeter_element().reduced_word() # optional - gap3\n [1, 2, 3, 4]\n\n sage: W = ReflectionGroup((4,4,4)) # optional - gap3\n sage: W.coxeter_element().reduced_word() # optional - gap3\n [1, 2, 3, 4]\n\n TESTS::\n\n sage: WeylGroup(['A', 4]).coxeter_element().reduced_word() # needs sage.combinat sage.groups\n [1, 2, 3, 4]\n sage: SymmetricGroup(3).coxeter_element() # needs sage.groups\n (1,3,2)\n " return self.prod(self.simple_reflections()) @cached_method def standard_coxeter_elements(self): "\n Return all standard Coxeter elements in ``self``.\n\n This is the set of all elements in self obtained from any\n product of the simple reflections in ``self``.\n\n .. NOTE::\n\n - ``self`` is assumed to be well-generated.\n - This works even beyond real reflection groups, but the conjugacy\n class is not unique and we only obtain one such class.\n\n EXAMPLES::\n\n sage: W = ReflectionGroup(4) # optional - gap3\n sage: sorted(W.standard_coxeter_elements()) # optional - gap3\n [(1,7,6,12,23,20)(2,8,17,24,9,5)(3,16,10,19,15,21)(4,14,11,22,18,13),\n (1,10,4,12,21,22)(2,11,19,24,13,3)(5,15,7,17,16,23)(6,18,8,20,14,9)]\n\n TESTS::\n\n sage: W = SymmetricGroup(3) # needs sage.groups\n sage: sorted(W.standard_coxeter_elements()) # needs sage.combinat sage.groups\n [(1,2,3), (1,3,2)]\n\n sage: W = Permutations(3)\n sage: sorted(W.standard_coxeter_elements()) # needs sage.graphs\n [[2, 3, 1], [3, 1, 2]]\n\n sage: W = CoxeterGroup(['D', 3]) # needs sage.combinat sage.groups\n sage: sorted(W.standard_coxeter_elements()) # needs sage.combinat sage.groups\n [\n [-1 1 1] [ 0 -1 1] [ 0 1 -1] [ 1 -1 -1]\n [-1 0 1] [ 1 -1 0] [ 0 0 -1] [ 1 -1 0]\n [-1 1 0], [ 0 -1 0], [ 1 0 -1], [ 1 0 -1]\n ]\n\n sage: W = ColoredPermutations(3,2) # needs sage.combinat\n sage: len(W.standard_coxeter_elements()) # needs sage.combinat sage.graphs\n 2\n " if ((not self.is_irreducible()) or (not self.is_well_generated())): raise ValueError('this method is available for irreducible, well-generated complex reflection groups') from sage.combinat.permutation import Permutations return {self.from_reduced_word(w) for w in Permutations(self.index_set())} def grassmannian_elements(self, side='right'): '\n Return the left or right Grassmannian elements of ``self``\n as an enumerated set.\n\n INPUT:\n\n - ``side`` -- (default: ``"right"``) ``"left"`` or ``"right"``\n\n EXAMPLES::\n\n sage: S = CoxeterGroups().example()\n sage: G = S.grassmannian_elements()\n sage: G.cardinality()\n 12\n sage: G.list()\n [(0, 1, 2, 3), (1, 0, 2, 3), (0, 2, 1, 3), (0, 1, 3, 2),\n (2, 0, 1, 3), (1, 2, 0, 3), (0, 3, 1, 2), (0, 2, 3, 1),\n (3, 0, 1, 2), (1, 3, 0, 2), (1, 2, 3, 0), (2, 3, 0, 1)]\n sage: sorted(tuple(w.descents()) for w in G)\n [(), (0,), (0,), (0,), (1,), (1,), (1,), (1,), (1,), (2,), (2,), (2,)]\n sage: G = S.grassmannian_elements(side = "left")\n sage: G.cardinality()\n 12\n sage: sorted(tuple(w.descents(side = "left")) for w in G)\n [(), (0,), (0,), (0,), (1,), (1,), (1,), (1,), (1,), (2,), (2,), (2,)]\n ' order_side = ('left' if (side == 'right') else 'right') return self.weak_order_ideal(attrcall('is_grassmannian', side=side), side=order_side) def fully_commutative_elements(self): "\n Return the set of fully commutative elements in this Coxeter group.\n\n .. SEEALSO::\n\n :class:`~sage.combinat.fully_commutative_elements.FullyCommutativeElements`\n\n EXAMPLES::\n\n sage: CoxeterGroup(['A', 3]).fully_commutative_elements() # needs sage.combinat sage.groups\n Fully commutative elements of\n Finite Coxeter group over Integer Ring with Coxeter matrix:\n [1 3 2]\n [3 1 3]\n [2 3 1]\n " from sage.combinat.fully_commutative_elements import FullyCommutativeElements return FullyCommutativeElements(self) def _test_reduced_word(self, **options): '\n Run sanity checks on :meth:`CoxeterGroups.ElementMethods.reduced_word` and\n :meth:`~sage.categories.complex_reflection_or_generalized_coxeter_groups.ComplexReflectionOrGeneralizedCoxeterGroups.ParentMethods.from_reduced_word`\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: W._test_reduced_word()\n ' tester = self._tester(**options) s = self.simple_reflections() for x in tester.some_elements(): red = x.reduced_word() tester.assertEqual(self.from_reduced_word(red), x) tester.assertEqual(self.prod((s[i] for i in red)), x) def simple_projection(self, i, side='right', length_increasing=True): '\n Return the simple projection `\\pi_i` (or `\\overline\\pi_i` if ``length_increasing`` is ``False``).\n\n INPUT:\n\n - ``i`` - an element of the index set of ``self``\n\n See :meth:`.simple_projections` for the options and for\n the definition of the simple projections.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: W\n The symmetric group on {0, ..., 3}\n sage: s = W.simple_reflections()\n sage: sigma = W.an_element()\n sage: sigma\n (1, 2, 3, 0)\n sage: u0 = W.simple_projection(0)\n sage: d0 = W.simple_projection(0, length_increasing=False)\n sage: sigma.length()\n 3\n sage: pi=sigma*s[0]\n sage: pi.length()\n 4\n sage: u0(sigma)\n (2, 1, 3, 0)\n sage: pi\n (2, 1, 3, 0)\n sage: u0(pi)\n (2, 1, 3, 0)\n sage: d0(sigma)\n (1, 2, 3, 0)\n sage: d0(pi)\n (1, 2, 3, 0)\n\n ' if (not ((i in self.index_set()) or (i == 0))): raise ValueError(('%s is not 0 and not in the Dynkin node set %s' % (i, self.index_set()))) return (lambda x: x.apply_simple_projection(i, side=side, length_increasing=length_increasing)) def kazhdan_lusztig_cells(self, side='left'): "\n Compute the left, right, or two-sided Kazhdan-Lusztig cells of\n ``self`` if ``self`` is finite.\n\n The cells are computed by using :func:`kazhdan_lusztig_cell()\n <CoxeterGroups.ElementMethods.kazhdan_lusztig_cell()>`.\n\n As detailed there, installation of the optional package ``coxeter3``\n is recommended (though not required) before using this function\n as it speeds up the computation.\n\n INPUT:\n\n - ``side`` -- (default: ``'left'``) either ``'left'``,\n ``'right'``, or ``'two-sided'``\n\n EXAMPLES:\n\n We compute the right cells in the Coxeter group of type `A_2`\n below. Note that each Coxeter group may be created with multiple\n implementations, namely, 'reflection' (default), 'permutation',\n 'matrix', or 'coxeter3'. The choice of implementation affects the\n representation of elements in the output cells but not the method\n used for the cell computation::\n\n sage: # needs sage.combinat sage.groups\n sage: W = CoxeterGroup('A2')\n sage: KL_cells = W.kazhdan_lusztig_cells(side='right')\n sage: set([tuple(sorted(C, key=lambda w: w.reduced_word()))\n ....: for C in KL_cells])\n {(\n [-1 1] [ 0 -1]\n [ 0 1], [ 1 -1]\n ),\n (\n [ 0 -1]\n [-1 0]\n ),\n (\n [1 0]\n [0 1]\n ),\n (\n [ 1 0] [-1 1]\n [ 1 -1], [-1 0]\n )}\n sage: len(KL_cells)\n 4\n\n sage: W = CoxeterGroup('A2', implementation='permutation') # needs sage.combinat sage.groups\n sage: len(W.kazhdan_lusztig_cells(side='right')) # needs sage.combinat sage.groups\n 4\n\n We compute the left cells in the Coxeter group of type `A_3`\n below. If the optional package ``coxeter3`` is installed, it\n runs in the background even if the group is not created with\n the ``'coxeter3'`` implementation::\n\n sage: # optional - coxeter3, needs sage.combinat sage.groups sage.libs.gap sage.modules sage.rings.number_field\n sage: W = CoxeterGroup('A3', implementation='coxeter3')\n sage: KL_cells = W.kazhdan_lusztig_cells()\n sage: set([tuple(sorted(C)) for C in KL_cells])\n {([],),\n ([1], [2, 1], [3, 2, 1]),\n ([1, 2], [2], [3, 2]),\n ([1, 2, 1], [1, 3, 2, 1], [2, 1, 3, 2, 1]),\n ([1, 2, 1, 3], [1, 2, 3, 2, 1], [2, 3, 2, 1]),\n ([1, 2, 1, 3, 2], [1, 2, 3, 2], [2, 3, 2]),\n ([1, 2, 1, 3, 2, 1],),\n ([1, 2, 3], [2, 3], [3]),\n ([1, 3], [2, 1, 3]),\n ([1, 3, 2], [2, 1, 3, 2])}\n sage: len(KL_cells)\n 10\n sage: W = CoxeterGroup('A3', implementation='permutation')\n sage: len(W.kazhdan_lusztig_cells())\n 10\n\n Computing the two sided cells in `B_3`::\n\n sage: # optional - coxeter3, needs sage.combinat sage.groups sage.libs.gap sage.modules sage.rings.number_field\n sage: W = CoxeterGroup('B3', implementation='coxeter3')\n sage: b3_cells = W.kazhdan_lusztig_cells('two-sided')\n sage: len(b3_cells)\n 6\n sage: set([tuple(sorted(C))\n ....: for C in W.kazhdan_lusztig_cells()])\n {([],),\n ([1], [1, 2, 3, 2, 1], [2, 1], [2, 3, 2, 1], [3, 2, 1]),\n ([1, 2], [1, 2, 3, 2], [2], [2, 3, 2], [3, 2]),\n ([1, 2, 3], [2, 3], [3], [3, 2, 3]),\n ([2, 1, 2], [2, 3, 2, 1, 2], [3, 2, 1, 2]),\n ([2, 1, 2, 3], [2, 3, 2, 1, 2, 3], [3, 2, 1, 2, 3]),\n ([2, 1, 2, 3, 2], [2, 3, 2, 1, 2, 3, 2], [3, 2, 1, 2, 3, 2]),\n ([2, 1, 2, 3, 2, 1],\n [2, 3, 2, 1, 2, 3, 2, 1],\n [3, 2, 1, 2, 3, 2, 1],\n [3, 2, 3, 2, 1, 2]),\n ([2, 3, 1], [3, 1], [3, 2, 3, 1]),\n ([2, 3, 1, 2], [3, 1, 2], [3, 2, 3, 1, 2]),\n ([2, 3, 1, 2, 3], [3, 1, 2, 3], [3, 2, 3, 1, 2, 3]),\n ([2, 3, 1, 2, 3, 2],\n [3, 1, 2, 3, 2],\n [3, 2, 3, 1, 2, 3, 2],\n [3, 2, 3, 2],\n [3, 2, 3, 2, 1, 2, 3, 2]),\n ([2, 3, 1, 2, 3, 2, 1],\n [3, 1, 2, 3, 2, 1],\n [3, 2, 3, 1, 2, 3, 2, 1],\n [3, 2, 3, 2, 1],\n [3, 2, 3, 2, 1, 2, 3]),\n ([3, 2, 3, 2, 1, 2, 3, 2, 1],)}\n\n TESTS::\n\n sage: W = CoxeterGroup(['A', 2, 1]) # needs sage.combinat sage.groups\n sage: W.kazhdan_lusztig_cells() # needs sage.combinat sage.groups\n Traceback (most recent call last):\n ...\n ValueError: the Coxeter group must be finite to compute Kazhdan--Lusztig cells\n " if (not self.coxeter_type().is_finite()): raise ValueError('the Coxeter group must be finite to compute Kazhdan--Lusztig cells') identity = frozenset([self.one()]) cells = {identity} for w in self: if (not any(((w in c) for c in cells))): cell = w.kazhdan_lusztig_cell(side=side) cells.add(frozenset(cell)) return cells @cached_method def simple_projections(self, side='right', length_increasing=True): "\n Return the family of simple projections, also known as 0-Hecke or Demazure operators.\n\n INPUT:\n\n - ``self`` -- a Coxeter group `W`\n - ``side`` -- 'left' or 'right' (default: 'right')\n - ``length_increasing`` -- a boolean (default: ``True``) specifying\n whether the operator increases or decreases length\n\n This returns the simple projections of `W`, as a family.\n\n To each simple reflection `s_i` of `W`, corresponds a\n *simple projection* `\\pi_i` from `W` to `W` defined by:\n\n `\\pi_i(w) = w s_i` if `i` is not a descent of `w`\n `\\pi_i(w) = w` otherwise.\n\n The simple projections `(\\pi_i)_{i\\in I}` move elements\n down the right permutohedron, toward the maximal element.\n They satisfy the same braid relations as the simple reflections,\n but are idempotents `\\pi_i^2=\\pi` not involutions `s_i^2 = 1`. As such,\n the simple projections generate the `0`-Hecke monoid.\n\n By symmetry, one can also define the projections\n `(\\overline\\pi_i)_{i\\in I}` (when the option ``length_increasing`` is False):\n\n `\\overline\\pi_i(w) = w s_i` if `i` is a descent of `w`\n `\\overline\\pi_i(w) = w` otherwise.\n\n as well as the analogues acting on the left (when the option ``side`` is 'left').\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example(); W\n The symmetric group on {0, ..., 3}\n sage: s = W.simple_reflections()\n sage: sigma = W.an_element(); sigma\n (1, 2, 3, 0)\n sage: pi = W.simple_projections(); pi\n Finite family {0: <function ...<lambda> at ...>,\n 1: <function ...<lambda> at ...>,\n 2: <function ...<lambda> ...>}\n sage: pi[1](sigma)\n (1, 3, 2, 0)\n sage: W.simple_projection(1)(sigma)\n (1, 3, 2, 0)\n " from sage.sets.family import Family return Family(self.index_set(), (lambda i: self.simple_projection(i, side=side, length_increasing=length_increasing))) def sign_representation(self, base_ring=None, side='twosided'): '\n Return the sign representation of ``self`` over ``base_ring``.\n\n INPUT:\n\n - ``base_ring`` -- (optional) the base ring; the default is `\\ZZ`\n - ``side`` -- ignored\n\n EXAMPLES::\n\n sage: W = WeylGroup(["A", 1, 1]) # needs sage.combinat sage.groups\n sage: W.sign_representation() # needs sage.combinat sage.groups\n Sign representation of\n Weyl Group of type [\'A\', 1, 1] (as a matrix group acting on the root space)\n over Integer Ring\n\n ' if (base_ring is None): from sage.rings.integer_ring import ZZ base_ring = ZZ from sage.modules.with_basis.representation import SignRepresentationCoxeterGroup return SignRepresentationCoxeterGroup(self, base_ring) def demazure_product(self, Q): "\n Return the Demazure product of the list ``Q`` in ``self``.\n\n INPUT:\n\n - ``Q`` is a list of elements from the index set of ``self``.\n\n This returns the Coxeter group element that represents the\n composition of 0-Hecke or Demazure operators.\n\n See :meth:`CoxeterGroups.ParentMethods.simple_projections`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup(['A', 2])\n sage: w = W.demazure_product([2,2,1])\n sage: w.reduced_word()\n [2, 1]\n sage: w = W.demazure_product([2,1,2,1,2])\n sage: w.reduced_word()\n [1, 2, 1]\n\n sage: W = WeylGroup(['B', 2]) # needs sage.combinat sage.groups\n sage: w = W.demazure_product([2,1,2,1,2]) # needs sage.combinat sage.groups\n sage: w.reduced_word() # needs sage.combinat sage.groups\n [2, 1, 2, 1]\n " return self.one().apply_demazure_product(Q) def bruhat_interval(self, x, y): '\n Return the list of ``t`` such that ``x <= t <= y``.\n\n EXAMPLES::\n\n sage: W = WeylGroup("A3", prefix="s") # needs sage.combinat sage.groups\n sage: s1, s2, s3 = W.simple_reflections() # needs sage.combinat sage.groups\n sage: W.bruhat_interval(s2, s1*s3*s2*s1*s3) # needs sage.combinat sage.groups\n [s1*s2*s3*s2*s1, s2*s3*s2*s1, s3*s1*s2*s1, s1*s2*s3*s1,\n s1*s2*s3*s2, s3*s2*s1, s2*s3*s1, s2*s3*s2, s1*s2*s1,\n s3*s1*s2, s1*s2*s3, s2*s1, s3*s2, s2*s3, s1*s2, s2]\n\n sage: W = WeylGroup([\'A\', 2, 1], prefix="s") # needs sage.combinat sage.groups\n sage: s0, s1, s2 = W.simple_reflections() # needs sage.combinat sage.groups\n sage: W.bruhat_interval(1, s0*s1*s2) # needs sage.combinat sage.groups\n [s0*s1*s2, s1*s2, s0*s2, s0*s1, s2, s1, s0, 1]\n ' if (x == 1): x = self.one() if (y == 1): y = self.one() if (x == y): return [x] ret = [] if (not x.bruhat_le(y)): return ret ret.append([y]) while ret[(- 1)]: nextlayer = [] for z in ret[(- 1)]: for t in z.bruhat_lower_covers(): if (t not in nextlayer): if x.bruhat_le(t): nextlayer.append(t) ret.append(nextlayer) return flatten(ret) def bruhat_interval_poset(self, x, y, facade=False): '\n Return the poset of the Bruhat interval between ``x`` and ``y``\n in Bruhat order.\n\n EXAMPLES::\n\n sage: W = WeylGroup("A3", prefix="s") # needs sage.combinat sage.groups\n sage: s1, s2, s3 = W.simple_reflections() # needs sage.combinat sage.groups\n sage: W.bruhat_interval_poset(s2, s1*s3*s2*s1*s3) # needs sage.combinat sage.groups\n Finite poset containing 16 elements\n\n sage: W = WeylGroup([\'A\', 2, 1], prefix="s") # needs sage.combinat sage.groups\n sage: s0, s1, s2 = W.simple_reflections() # needs sage.combinat sage.groups\n sage: W.bruhat_interval_poset(1, s0*s1*s2) # needs sage.combinat sage.groups\n Finite poset containing 8 elements\n\n TESTS::\n\n sage: W.bruhat_interval_poset(s0*s1*s2, s0*s1*s2) # needs sage.combinat sage.groups\n Finite poset containing 1 elements\n ' if (x == 1): x = self.one() if (y == 1): y = self.one() from sage.combinat.posets.posets import Poset if (x == y): return Poset([[x], []]) if (not x.bruhat_le(y)): return Poset() curlayer = {y} d = {} while curlayer: nextlayer = set() for z in curlayer: for t in z.bruhat_lower_covers(): if (not x.bruhat_le(t)): continue if (t in d): d[t].append(z) else: d[t] = [z] if (t not in nextlayer): nextlayer.add(t) curlayer = nextlayer from sage.graphs.digraph import DiGraph return Poset(DiGraph(d, format='dict_of_lists', data_structure='static_sparse'), cover_relations=True, facade=facade) def bruhat_graph(self, x=None, y=None, edge_labels=False): '\n Return the Bruhat graph as a directed graph, with an edge `u \\to v`\n if and only if `u < v` in the Bruhat order, and `u = r \\cdot v`.\n\n The Bruhat graph `\\Gamma(x,y)`, defined if `x \\leq y` in the\n Bruhat order, has as its vertices the Bruhat interval\n `\\{ t | x \\leq t \\leq y \\}`, and as its edges are the pairs\n `(u, v)` such that `u = r \\cdot v` where `r` is a reflection,\n that is, a conjugate of a simple reflection.\n\n REFERENCES:\n\n Carrell, The Bruhat graph of a Coxeter group, a conjecture of Deodhar,\n and rational smoothness of Schubert varieties. Algebraic groups and\n their generalizations: classical methods (University Park, PA, 1991),\n 53--61, Proc. Sympos. Pure Math., 56, Part 1, Amer. Math. Soc.,\n Providence, RI, 1994.\n\n EXAMPLES::\n\n sage: W = CoxeterGroup([\'H\', 3]) # needs sage.combinat sage.graphs sage.groups\n sage: G = W.bruhat_graph(); G # needs sage.combinat sage.graphs sage.groups\n Digraph on 120 vertices\n\n sage: # needs sage.combinat sage.graphs sage.groups\n sage: W = CoxeterGroup([\'A\', 2, 1])\n sage: s1, s2, s3 = W.simple_reflections()\n sage: W.bruhat_graph(s1, s1*s3*s2*s3)\n Digraph on 6 vertices\n sage: W.bruhat_graph(s1, s3*s2*s3)\n Digraph on 0 vertices\n\n sage: W = WeylGroup("A3", prefix="s") # needs sage.combinat sage.graphs sage.groups\n sage: s1, s2, s3 = W.simple_reflections() # needs sage.combinat sage.graphs sage.groups\n sage: G = W.bruhat_graph(s1*s3, s1*s2*s3*s2*s1); G # needs sage.combinat sage.graphs sage.groups\n Digraph on 10 vertices\n\n Check that the graph has the correct number of edges\n (see :trac:`17744`)::\n\n sage: len(G.edges(sort=False)) # needs sage.combinat sage.graphs sage.groups\n 16\n ' if ((x is None) or (x == 1)): x = self.one() if (y is None): if self.is_finite(): y = self.long_element() else: raise TypeError('infinite groups must specify a maximal element') elif (y == 1): y = self.one() g = sorted(self.bruhat_interval(x, y), key=(lambda w: (- w.length()))) d = [] if self.is_finite(): ref = self.reflections() for (i, u) in enumerate(g): for v in g[:i]: w = (u * v.inverse()) if (w in ref): if edge_labels: d.append((u, v, w)) else: d.append((u, v)) else: for (i, u) in enumerate(g): for v in g[:i]: w = (u * v.inverse()) if w.is_reflection(): if edge_labels: d.append((u, v, w)) else: d.append((u, v)) from sage.graphs.digraph import DiGraph return DiGraph(d) def canonical_representation(self): '\n Return the canonical faithful representation of ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup("A3") # needs sage.combinat sage.groups\n sage: W.canonical_representation() # needs sage.combinat sage.groups\n Finite Coxeter group over Integer Ring with Coxeter matrix:\n [1 3 2]\n [3 1 3]\n [2 3 1]\n ' from sage.groups.matrix_gps.coxeter_group import CoxeterMatrixGroup return CoxeterMatrixGroup(self.coxeter_matrix(), index_set=self.index_set()) def elements_of_length(self, n): "\n Return all elements of length `n`.\n\n EXAMPLES::\n\n sage: A = AffinePermutationGroup(['A', 2, 1]) # needs sage.combinat\n sage: [len(list(A.elements_of_length(i))) for i in [0..5]] # needs sage.combinat\n [1, 3, 6, 9, 12, 15]\n\n sage: W = CoxeterGroup(['H', 3]) # needs sage.combinat sage.groups\n sage: [len(list(W.elements_of_length(i))) for i in range(4)] # needs sage.combinat sage.groups\n [1, 3, 5, 7]\n\n sage: W = CoxeterGroup(['A', 2]) # needs sage.combinat sage.groups\n sage: [len(list(W.elements_of_length(i))) for i in range(6)] # needs sage.combinat sage.groups\n [1, 2, 2, 1, 0, 0]\n " I = self.weak_order_ideal(ConstantFunction(True), side='right') return I.elements_of_depth_iterator(n) def random_element_of_length(self, n): "\n Return a random element of length ``n`` in ``self``.\n\n Starts at the identity, then chooses an upper cover at random.\n\n Not very uniform: actually constructs a uniformly random\n reduced word of length `n`. Thus we most likely get\n elements with lots of reduced words!\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: A = AffinePermutationGroup(['A', 7, 1])\n sage: p = A.random_element_of_length(10)\n sage: p in A\n True\n sage: p.length() == 10\n True\n\n sage: # needs sage.combinat sage.groups\n sage: W = CoxeterGroup(['A', 4])\n sage: p = W.random_element_of_length(5)\n sage: p in W\n True\n sage: p.length() == 5\n True\n " from sage.misc.prandom import randint x = self.one() for _ in range(1, (n + 1)): antiD = x.descents(positive=True) rnd = randint(0, (len(antiD) - 1)) x = x.apply_simple_reflection_right(antiD[rnd]) return x def _test_simple_projections(self, **options): '\n Runs sanity checks on :meth:`.simple_projections`\n and :meth:`CoxeterGroups.ElementMethods.apply_simple_projection`\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: W._test_simple_projections()\n ' tester = self._tester(**options) for side in ['left', 'right']: pi = self.simple_projections(side=side) opi = self.simple_projections(side=side, length_increasing=False) for i in self.index_set(): for w in tester.some_elements(): tester.assertEqual(pi[i](w), w.apply_simple_projection(i, side=side)) tester.assertEqual(pi[i](w), w.apply_simple_projection(i, side=side, length_increasing=True)) tester.assertEqual(opi[i](w), w.apply_simple_projection(i, side=side, length_increasing=False)) tester.assertTrue(pi[i](w).has_descent(i, side=side)) tester.assertFalse(opi[i](w).has_descent(i, side=side)) tester.assertEqual({pi[i](w), opi[i](w)}, {w, w.apply_simple_reflection(i, side=side)}) def _test_has_descent(self, **options): '\n Run sanity checks on the method\n :meth:`CoxeterGroups.ElementMethods.has_descent` of the\n elements of self.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: W._test_has_descent()\n\n sage: # needs sage.combinat sage.groups\n sage: W = Permutations(4)\n sage: W._test_has_descent()\n sage: sage.combinat.permutation.Permutations.options.mult = "r2l"\n sage: W._test_has_descent()\n sage: sage.combinat.permutation.Permutations.options._reset()\n\n sage: W = SignedPermutations(3) # needs sage.combinat\n sage: W._test_has_descent()\n ' tester = self._tester(**options) s = self.simple_reflections() for i in self.index_set(): tester.assertTrue((not self.one().has_descent(i))) tester.assertTrue((not self.one().has_descent(i, side='left'))) tester.assertTrue((not self.one().has_descent(i, side='right'))) tester.assertTrue(self.one().has_descent(i, positive=True)) tester.assertTrue(self.one().has_descent(i, positive=True, side='left')) tester.assertTrue(self.one().has_descent(i, positive=True, side='right')) for j in self.index_set(): tester.assertEqual(s[i].has_descent(j, side='left'), (i == j)) tester.assertEqual(s[i].has_descent(j, side='right'), (i == j)) tester.assertEqual(s[i].has_descent(j), (i == j)) tester.assertEqual(s[i].has_descent(j, positive=True, side='left'), (i != j)) tester.assertEqual(s[i].has_descent(j, positive=True, side='right'), (i != j)) tester.assertEqual(s[i].has_descent(j, positive=True), (i != j)) if (i == j): continue u = s[i].apply_simple_reflection_right(j) v = s[j].apply_simple_reflection_right(i) tester.assertTrue(u.has_descent(i, side='left')) tester.assertTrue(u.has_descent(j, side='right')) tester.assertEqual(u.has_descent(j, side='left'), (u == v)) tester.assertEqual(u.has_descent(i, side='right'), (u == v)) def _test_descents(self, **options): '\n Run sanity checks on the method\n :meth:`CoxeterGroups.ElementMethods.descents` of the\n elements of ``self``.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: W._test_descents()\n ' tester = self._tester(**options) s = self.simple_reflections() tester.assertEqual(len(self.one().descents(side='right')), 0) tester.assertEqual(len(self.one().descents(side='left')), 0) for i in self.index_set(): si = s[i] tester.assertEqual([i], si.descents(side='left')) tester.assertEqual([i], si.descents(side='right')) tester.assertNotIn(i, si.descents(positive=True, side='left')) tester.assertNotIn(i, si.descents(positive=True, side='right')) def _test_coxeter_relations(self, **options): '\n Test whether the Coxeter relations hold for ``self``.\n\n This checks nothing in the case of infinite order.\n\n TESTS::\n\n sage: A = AffinePermutationGroup([\'A\', 7, 1]) # needs sage.combinat\n sage: A._test_coxeter_relations() # needs sage.combinat\n\n sage: cm = CartanMatrix([[2,-5,0], [-2,2,-1], [0,-1,2]]) # needs sage.graphs\n sage: W = WeylGroup(cm) # needs sage.combinat sage.graphs sage.groups\n sage: W._test_coxeter_relations() # needs sage.combinat sage.graphs sage.groups\n\n sage: # needs sage.combinat sage.groups\n sage: W = Permutations(4)\n sage: W._test_coxeter_relations()\n sage: sage.combinat.permutation.Permutations.options.mult = "r2l"\n sage: W._test_coxeter_relations()\n sage: sage.combinat.permutation.Permutations.options._reset()\n\n sage: W = SignedPermutations(3) # needs sage.combinat\n sage: W._test_coxeter_relations() # needs sage.combinat\n ' tester = self._tester(**options) s = self.simple_reflections() one = self.one() for si in s: tester.assertEqual((si ** 2), one) try: cox_mat = self.coxeter_matrix() except ImportError: return I = cox_mat.index_set() for (ii, i) in enumerate(I): for j in I[(ii + 1):]: mij = cox_mat[(i, j)] if (mij == (- 1)): continue l = (s[i] * s[j]) tester.assertEqual((l ** mij), one, 'Coxeter relation fails') for p in range(1, mij): tester.assertNotEqual((l ** p), one, 'unexpected relation') class ElementMethods(): def has_descent(self, i, side='right', positive=False): "\n Return whether i is a (left/right) descent of self.\n\n See :meth:`.descents` for a description of the options.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: s = W.simple_reflections()\n sage: w = s[0] * s[1] * s[2]\n sage: w.has_descent(2)\n True\n sage: [ w.has_descent(i) for i in [0,1,2] ]\n [False, False, True]\n sage: [ w.has_descent(i, side='left') for i in [0,1,2] ]\n [True, False, False]\n sage: [ w.has_descent(i, positive=True) for i in [0,1,2] ]\n [True, True, False]\n\n This default implementation delegates the work to\n :meth:`.has_left_descent` and :meth:`.has_right_descent`.\n " if (not isinstance(positive, bool)): raise TypeError(('%s is not a boolean' % bool)) if (side == 'right'): return (self.has_right_descent(i) != positive) if (side != 'left'): raise ValueError(("%s is neither 'right' nor 'left'" % side)) return (self.has_left_descent(i) != positive) def has_right_descent(self, i): '\n Return whether ``i`` is a right descent of self.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example(); W\n The symmetric group on {0, ..., 3}\n sage: w = W.an_element(); w\n (1, 2, 3, 0)\n sage: w.has_right_descent(0)\n False\n sage: w.has_right_descent(1)\n False\n sage: w.has_right_descent(2)\n True\n ' return (~ self).has_left_descent(i) def has_left_descent(self, i): "\n Return whether `i` is a left descent of self.\n\n This default implementation uses that a left descent of\n `w` is a right descent of `w^{-1}`.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example(); W\n The symmetric group on {0, ..., 3}\n sage: w = W.an_element(); w\n (1, 2, 3, 0)\n sage: w.has_left_descent(0)\n True\n sage: w.has_left_descent(1)\n False\n sage: w.has_left_descent(2)\n False\n\n TESTS::\n\n sage: w.has_left_descent.__module__\n 'sage.categories.coxeter_groups'\n " return (~ self).has_right_descent(i) def first_descent(self, side='right', index_set=None, positive=False): '\n Return the first left (resp. right) descent of self, as\n an element of ``index_set``, or ``None`` if there is none.\n\n See :meth:`.descents` for a description of the options.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: s = W.simple_reflections()\n sage: w = s[2]*s[0]\n sage: w.first_descent()\n 0\n sage: w = s[0]*s[2]\n sage: w.first_descent()\n 0\n sage: w = s[0]*s[1]\n sage: w.first_descent()\n 1\n ' if (index_set is None): index_set = self.parent().index_set() for i in index_set: if self.has_descent(i, side=side, positive=positive): return i return None def descents(self, side='right', index_set=None, positive=False): "\n Return the descents of self, as a list of elements of the\n index_set.\n\n INPUT:\n\n - ``index_set`` - a subset (as a list or iterable) of the nodes of the Dynkin diagram;\n (default: all of them)\n - ``side`` - 'left' or 'right' (default: 'right')\n - ``positive`` - a boolean (default: ``False``)\n\n The ``index_set`` option can be used to restrict to the\n parabolic subgroup indexed by ``index_set``.\n\n If positive is ``True``, then returns the non-descents\n instead\n\n .. TODO::\n\n find a better name for ``positive``: complement? non_descent?\n\n Caveat: the return type may change to some other iterable\n (tuple, ...) in the future. Please use keyword arguments\n also, as the order of the arguments may change as well.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: s = W.simple_reflections()\n sage: w = s[0]*s[1]\n sage: w.descents()\n [1]\n sage: w = s[0]*s[2]\n sage: w.descents()\n [0, 2]\n\n .. TODO:: side, index_set, positive\n " if (index_set is None): index_set = self.parent().index_set() return [i for i in index_set if self.has_descent(i, side=side, positive=positive)] def is_grassmannian(self, side='right') -> bool: '\n Return whether ``self`` is Grassmannian.\n\n INPUT:\n\n - ``side`` -- "left" or "right" (default: "right")\n\n An element is Grassmannian if it has at\n most one descent on the right (resp. on the left).\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example(); W\n The symmetric group on {0, ..., 3}\n sage: s = W.simple_reflections()\n sage: W.one().is_grassmannian()\n True\n sage: s[1].is_grassmannian()\n True\n sage: (s[1]*s[2]).is_grassmannian()\n True\n sage: (s[0]*s[1]).is_grassmannian()\n True\n sage: (s[1]*s[2]*s[1]).is_grassmannian()\n False\n\n sage: (s[0]*s[2]*s[1]).is_grassmannian(side="left")\n False\n sage: (s[0]*s[2]*s[1]).is_grassmannian(side="right")\n True\n sage: (s[0]*s[2]*s[1]).is_grassmannian()\n True\n ' return (len(self.descents(side=side)) <= 1) def is_fully_commutative(self) -> bool: "\n Check if ``self`` is a fully-commutative element.\n\n We use the characterization that an element `w` in a Coxeter\n system `(W,S)` is fully-commutative if and only if for every pair\n of generators `s,t \\in S` for which `m(s,t)>2`, no reduced\n word of `w` contains the 'braid' word `sts...` of length\n `m(s,t)` as a contiguous subword. See [Ste1996]_.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = CoxeterGroup(['A', 3])\n sage: len([1 for w in W if w.is_fully_commutative()])\n 14\n sage: W = CoxeterGroup(['B', 3])\n sage: len([1 for w in W if w.is_fully_commutative()])\n 24\n\n TESTS::\n\n sage: W = CoxeterGroup(matrix(2,2,[1,7,7,1]), index_set='ab') # needs sage.combinat sage.groups\n sage: len([1 for w in W if w.is_fully_commutative()]) # needs sage.combinat sage.groups\n 13\n " word = self.reduced_word() from sage.combinat.root_system.braid_orbit import is_fully_commutative as is_fully_comm group = self.parent() braid_rels = group.braid_relations() I = group.index_set() from sage.rings.integer_ring import ZZ be_careful = any(((i not in ZZ) for i in I)) if be_careful: Iinv = {i: j for (j, i) in enumerate(I)} word = [Iinv[i] for i in word] braid_rels = [[[Iinv[i] for i in l], [Iinv[i] for i in r]] for (l, r) in braid_rels] return is_fully_comm(word, braid_rels) def reduced_word_reverse_iterator(self): '\n Return a reverse iterator on a reduced word for ``self``.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: s = W.simple_reflections()\n sage: sigma = s[0]*s[1]*s[2]\n sage: rI=sigma.reduced_word_reverse_iterator()\n sage: [i for i in rI]\n [2, 1, 0]\n sage: s[0]*s[1]*s[2]==sigma\n True\n sage: sigma.length()\n 3\n\n .. SEEALSO::\n\n :meth:`.reduced_word`\n\n Default implementation: recursively remove the first right\n descent until the identity is reached (see :meth:`.first_descent` and\n :meth:`~sage.categories.complex_reflection_or_generalized_coxeter_groups.ComplexReflectionOrGeneralizedCoxeterGroups.ElementMethods.apply_simple_reflection`).\n ' while True: i = self.first_descent() if (i is None): return self = self.apply_simple_reflection(i, 'right') (yield i) def reduced_word(self): '\n Return a reduced word for ``self``.\n\n This is a word `[i_1,i_2,\\ldots,i_k]` of minimal length\n such that\n `s_{i_1} s_{i_2} \\cdots s_{i_k} = \\operatorname{self}`,\n where the `s_i` are the simple reflections.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: s = W.simple_reflections()\n sage: w = s[0]*s[1]*s[2]\n sage: w.reduced_word()\n [0, 1, 2]\n sage: w = s[0]*s[2]\n sage: w.reduced_word()\n [2, 0]\n\n .. SEEALSO::\n\n - :meth:`.reduced_words`, :meth:`.reduced_word_reverse_iterator`,\n - :meth:`length`, :meth:`reduced_word_graph`\n ' result = list(self.reduced_word_reverse_iterator()) return list(reversed(result)) def reduced_words_iter(self): '\n Iterate over all reduced words for ``self``.\n\n See :meth:`reduced_word` for the definition of a reduced\n word.\n\n The algorithm uses the Matsumoto property that any two\n reduced expressions are related by braid relations, see\n Theorem 3.3.1(ii) in [BB2005]_.\n\n .. SEEALSO::\n\n :meth:`braid_orbit_iter`\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: s = W.simple_reflections()\n sage: w = s[0] * s[2]\n sage: sorted(w.reduced_words_iter()) # needs sage.combinat sage.graphs\n [[0, 2], [2, 0]]\n ' return self.parent().braid_orbit_iter(self.reduced_word()) def reduced_words(self): '\n Return all reduced words for ``self``.\n\n See :meth:`reduced_word` for the definition of a reduced\n word.\n\n The algorithm uses the Matsumoto property that any two\n reduced expressions are related by braid relations, see\n Theorem 3.3.1(ii) in [BB2005]_.\n\n .. SEEALSO::\n\n :meth:`braid_orbit`\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: s = W.simple_reflections()\n sage: w = s[0] * s[2]\n sage: sorted(w.reduced_words()) # needs sage.graphs sage.modules\n [[0, 2], [2, 0]]\n\n sage: W = WeylGroup([\'E\', 6]) # needs sage.combinat sage.groups\n sage: w = W.from_reduced_word([2,3,4,2]) # needs sage.combinat sage.groups\n sage: sorted(w.reduced_words()) # needs sage.combinat sage.groups\n [[2, 3, 4, 2], [3, 2, 4, 2], [3, 4, 2, 4]]\n\n sage: # optional - gap3, needs sage.combinat sage.groups\n sage: W = ReflectionGroup([\'A\',3],\n ....: index_set=["AA","BB","5"])\n sage: w = W.long_element()\n sage: w.reduced_words()\n [[\'BB\', \'5\', \'AA\', \'BB\', \'5\', \'AA\'],\n [\'5\', \'BB\', \'5\', \'AA\', \'BB\', \'5\'],\n [\'BB\', \'AA\', \'BB\', \'5\', \'BB\', \'AA\'],\n [\'AA\', \'5\', \'BB\', \'AA\', \'5\', \'BB\'],\n [\'5\', \'AA\', \'BB\', \'AA\', \'5\', \'BB\'],\n [\'AA\', \'BB\', \'5\', \'AA\', \'BB\', \'AA\'],\n [\'AA\', \'BB\', \'AA\', \'5\', \'BB\', \'AA\'],\n [\'AA\', \'BB\', \'5\', \'BB\', \'AA\', \'BB\'],\n [\'BB\', \'AA\', \'5\', \'BB\', \'AA\', \'5\'],\n [\'BB\', \'5\', \'AA\', \'BB\', \'AA\', \'5\'],\n [\'AA\', \'5\', \'BB\', \'5\', \'AA\', \'BB\'],\n [\'5\', \'BB\', \'AA\', \'5\', \'BB\', \'5\'],\n [\'5\', \'BB\', \'AA\', \'BB\', \'5\', \'BB\'],\n [\'5\', \'AA\', \'BB\', \'5\', \'AA\', \'BB\'],\n [\'BB\', \'5\', \'BB\', \'AA\', \'BB\', \'5\'],\n [\'BB\', \'AA\', \'5\', \'BB\', \'5\', \'AA\']]\n\n .. TODO::\n\n The result should be full featured finite enumerated set\n (e.g., counting can be done much faster than iterating).\n\n .. SEEALSO::\n\n :meth:`.reduced_word`, :meth:`.reduced_word_reverse_iterator`,\n :meth:`length`, :meth:`reduced_word_graph`\n ' return list(self.reduced_words_iter()) def support(self): '\n Return the support of ``self``, that is the simple reflections that\n appear in the reduced expressions of ``self``.\n\n OUTPUT:\n\n The support of ``self`` as a set of integers\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: w = W.from_reduced_word([1,2,1])\n sage: w.support()\n {1, 2}\n ' return set(self.reduced_word()) def has_full_support(self): '\n Return whether ``self`` has full support.\n\n An element is said to have full support if its support contains\n all simple reflections.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: w = W.from_reduced_word([1,2,1])\n sage: w.has_full_support()\n False\n sage: w = W.from_reduced_word([1,2,1,0,1])\n sage: w.has_full_support()\n True\n ' return (self.support() == set(self.parent().index_set())) def reduced_word_graph(self): "\n Return the reduced word graph of ``self``.\n\n The reduced word graph of an element `w` in a Coxeter group\n is the graph whose vertices are the reduced words for `w`\n (see :meth:`reduced_word` for a definition of this term),\n and which has an `m`-colored edge between two reduced words\n `x` and `y` whenever `x` and `y` differ by exactly one\n length-`m` braid move (with `m \\geq 2`).\n\n This graph is always connected (a theorem due to Tits) and\n has no multiple edges.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.graphs sage.groups\n sage: W = WeylGroup(['A', 3], prefix='s')\n sage: w0 = W.long_element()\n sage: G = w0.reduced_word_graph()\n sage: G.num_verts()\n 16\n sage: len(w0.reduced_words())\n 16\n sage: G.num_edges()\n 18\n sage: len([e for e in G.edges(sort=False) if e[2] == 2])\n 10\n sage: len([e for e in G.edges(sort=False) if e[2] == 3])\n 8\n\n TESTS::\n\n sage: p = Permutation([3,2,4,1])\n sage: pp = WeylGroup(['A',3]).from_reduced_word(p.reduced_word()) # needs sage.combinat sage.groups\n sage: pp.reduced_word_graph() # needs sage.combinat sage.graphs sage.groups\n Graph on 3 vertices\n\n sage: # needs sage.combinat sage.graphs sage.groups\n sage: w1 = W.one()\n sage: G = w1.reduced_word_graph()\n sage: G.num_verts()\n 1\n sage: G.num_edges()\n 0\n\n .. SEEALSO::\n\n :meth:`.reduced_words`, :meth:`.reduced_word_reverse_iterator`,\n :meth:`length`, :meth:`reduced_word`\n " R = self.reduced_words() from sage.graphs.graph import Graph if (len(R) == 1): return Graph({tuple(R[0]): []}, immutable=True) P = self.parent() edges = [] for (i, x) in enumerate(R): x = tuple(x) for y in R[i:]: y = tuple(y) j = 0 while ((j < len(x)) and (x[j] == y[j])): j += 1 if (j == len(x)): continue (a, b) = (x[j], y[j]) m = P.coxeter_matrix()[(a, b)] subword = ([a, b] * (m // 2)) subword2 = ([b, a] * (m // 2)) if (m % 2): subword.append(a) subword2.append(b) if ((x[j:(j + m)] != tuple(subword)) or (y[j:(j + m)] != tuple(subword2)) or (x[(j + m):] != y[(j + m):])): continue edges.append([x, y, m]) G = Graph(edges, immutable=True, format='list_of_edges') colors = {2: 'blue', 3: 'red', 4: 'green'} G.set_latex_options(edge_labels=True, color_by_label=(lambda x: colors[x])) return G def length(self): '\n Return the length of ``self``.\n\n This is the minimal length of\n a product of simple reflections giving ``self``.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: s1 = W.simple_reflection(1)\n sage: s2 = W.simple_reflection(2)\n sage: s1.length()\n 1\n sage: (s1*s2).length()\n 2\n sage: W = CoxeterGroups().example()\n sage: s = W.simple_reflections()\n sage: w = s[0]*s[1]*s[0]\n sage: w.length()\n 3\n sage: W = CoxeterGroups().example()\n sage: R.<x> = ZZ[]\n sage: s = sum(x^w.length() for w in W)\n sage: p = prod(sum(x^i for i in range(j)) for j in range(1, 5))\n sage: s - p\n 0\n\n .. SEEALSO::\n\n :meth:`.reduced_word`\n\n .. TODO::\n\n Should use reduced_word_iterator (or reverse_iterator)\n ' return len(self.reduced_word()) def reflection_length(self): "\n Return the reflection length of ``self``.\n\n The reflection length is the length of the shortest expression\n of the element as a product of reflections.\n\n .. SEEALSO::\n\n :meth:`absolute_length`\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A', 3]) # needs sage.combinat sage.groups\n sage: s = W.simple_reflections() # needs sage.combinat sage.groups\n sage: (s[1]*s[2]*s[3]).reflection_length() # needs sage.combinat sage.groups\n 3\n\n sage: W = SymmetricGroup(4) # needs sage.groups\n sage: s = W.simple_reflections() # needs sage.groups\n sage: (s[3]*s[2]*s[3]).reflection_length() # needs sage.combinat sage.groups\n 1\n\n " return self.absolute_length() def absolute_length(self): '\n Return the absolute length of ``self``.\n\n The absolute length is the length of the shortest expression\n of the element as a product of reflections.\n\n For permutations in the symmetric groups, the absolute\n length is the size minus the number of its disjoint\n cycles.\n\n .. SEEALSO::\n\n :meth:`absolute_le`\n\n EXAMPLES::\n\n sage: W = WeylGroup(["A", 3]) # needs sage.combinat sage.groups\n sage: s = W.simple_reflections() # needs sage.combinat sage.groups\n sage: (s[1]*s[2]*s[3]).absolute_length() # needs sage.combinat sage.groups\n 3\n\n sage: W = SymmetricGroup(4) # needs sage.groups\n sage: s = W.simple_reflections() # needs sage.groups\n sage: (s[3]*s[2]*s[1]).absolute_length() # needs sage.combinat sage.groups\n 3\n ' M = self.canonical_matrix() return (M - 1).image().dimension() def absolute_le(self, other): '\n Return whether ``self`` is smaller than ``other`` in the absolute\n order.\n\n A general reflection is an element of the form `w s_i w^{-1}`,\n where `s_i` is a simple reflection. The absolute order is defined\n analogously to the weak order but using general reflections rather\n than just simple reflections.\n\n This partial order can be used to define noncrossing partitions\n associated with this Coxeter group.\n\n .. SEEALSO::\n\n :meth:`absolute_length`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup(["A", 3])\n sage: s = W.simple_reflections()\n sage: w0 = s[1]\n sage: w1 = s[1]*s[2]*s[3]\n sage: w0.absolute_le(w1)\n True\n sage: w1.absolute_le(w0)\n False\n sage: w1.absolute_le(w1)\n True\n\n TESTS:\n\n Check that this is independent of the implementation of the group, see :trac:`34799`::\n\n sage: # needs sage.combinat sage.groups\n sage: W1 = WeylGroup([\'A\', 2])\n sage: W2 = Permutations(3)\n sage: P = lambda pi: W2(list(pi.to_permutation()))\n sage: d1 = set((P(w1), P(w2)) for w1 in W1 for w2 in W1\n ....: if w1.absolute_le(w2))\n sage: d2 = set((w1, w2) for w1 in W2 for w2 in W2\n ....: if w1.absolute_le(w2))\n sage: d1 == d2\n True\n sage: sage.combinat.permutation.Permutations.options.mult = "r2l"\n sage: d3 = set((w1, w2)\n ....: for w1 in W2 for w2 in W2 if w1.absolute_le(w2))\n sage: d1 == d3\n True\n sage: sage.combinat.permutation.Permutations.options._reset()\n\n sage: # needs sage.combinat sage.groups\n sage: W1 = WeylGroup([\'B\', 2])\n sage: W2 = SignedPermutations(2)\n sage: P = lambda pi: W2(list(pi.to_permutation()))\n sage: d1 = set((P(w1), P(w2))\n ....: for w1 in W1 for w2 in W1 if w1.absolute_le(w2))\n sage: d2 = set((w1, w2)\n ....: for w1 in W2 for w2 in W2 if w1.absolute_le(w2))\n sage: d1 == d2\n True\n ' if (self == other): return True if (self.absolute_length() >= other.absolute_length()): return False return ((self.absolute_length() + (self.inverse() * other).absolute_length()) == other.absolute_length()) def absolute_covers(self): '\n Return the list of covers of ``self`` in absolute order.\n\n .. SEEALSO::\n\n :meth:`absolute_length`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup(["A", 3])\n sage: s = W.simple_reflections()\n sage: w0 = s[1]\n sage: w1 = s[1]*s[2]*s[3]\n sage: w0.absolute_covers()\n [\n [0 0 1 0] [0 1 0 0] [0 1 0 0] [0 0 0 1] [0 1 0 0]\n [1 0 0 0] [1 0 0 0] [0 0 1 0] [1 0 0 0] [0 0 0 1]\n [0 1 0 0] [0 0 0 1] [1 0 0 0] [0 0 1 0] [0 0 1 0]\n [0 0 0 1], [0 0 1 0], [0 0 0 1], [0 1 0 0], [1 0 0 0]\n ]\n ' W = self.parent() return [(self * t) for t in W.reflections() if (self.absolute_length() < (self * t).absolute_length())] def canonical_matrix(self): '\n Return the matrix of ``self`` in the canonical faithful\n representation.\n\n This is an `n`-dimension real faithful essential representation,\n where `n` is the number of generators of the Coxeter group.\n Note that this is not always the most natural matrix\n representation, for instance in type `A_n`.\n\n EXAMPLES::\n\n sage: W = WeylGroup(["A", 3]) # needs sage.combinat sage.groups\n sage: s = W.simple_reflections() # needs sage.combinat sage.groups\n sage: (s[1]*s[2]*s[3]).canonical_matrix() # needs sage.combinat sage.groups\n [ 0 0 -1]\n [ 1 0 -1]\n [ 0 1 -1]\n ' G = self.parent().canonical_representation() return G.prod((G.simple_reflection(i) for i in self.reduced_word())).matrix() def coset_representative(self, index_set, side='right'): "\n Return the unique shortest element of the Coxeter group\n `W` which is in the same left (resp. right) coset as\n ``self``, with respect to the parabolic subgroup `W_I`.\n\n INPUT:\n\n - ``index_set`` - a subset (or iterable) of the nodes of the Dynkin diagram\n - ``side`` - 'left' or 'right'\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example(5)\n sage: s = W.simple_reflections()\n sage: w = s[2]*s[1]*s[3]\n sage: w.coset_representative([]).reduced_word()\n [2, 3, 1]\n sage: w.coset_representative([1]).reduced_word()\n [2, 3]\n sage: w.coset_representative([1,2]).reduced_word()\n [2, 3]\n sage: w.coset_representative([1,3] ).reduced_word()\n [2]\n sage: w.coset_representative([2,3] ).reduced_word()\n [2, 1]\n sage: w.coset_representative([1,2,3] ).reduced_word()\n []\n sage: w.coset_representative([], side='left').reduced_word()\n [2, 3, 1]\n sage: w.coset_representative([1], side='left').reduced_word()\n [2, 3, 1]\n sage: w.coset_representative([1,2], side='left').reduced_word()\n [3]\n sage: w.coset_representative([1,3], side='left').reduced_word()\n [2, 3, 1]\n sage: w.coset_representative([2,3], side='left').reduced_word()\n [1]\n sage: w.coset_representative([1,2,3], side='left').reduced_word()\n []\n\n " while True: i = self.first_descent(side=side, index_set=index_set) if (i is None): return self self = self.apply_simple_reflection(i, side=side) def apply_simple_projection(self, i, side='right', length_increasing=True): '\n Return the result of the application of the simple\n projection `\\pi_i` (resp. `\\overline\\pi_i`) on ``self``.\n\n INPUT:\n\n - ``i`` - an element of the index set of the Coxeter group\n - ``side`` - \'left\' or \'right\' (default: \'right\')\n - ``length_increasing`` - a boolean (default: True) specifying\n the direction of the projection\n\n See :meth:`CoxeterGroups.ParentMethods.simple_projections`\n for the definition of the simple projections.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: w = W.an_element()\n sage: w\n (1, 2, 3, 0)\n sage: w.apply_simple_projection(2)\n (1, 2, 3, 0)\n sage: w.apply_simple_projection(2, length_increasing=False)\n (1, 2, 0, 3)\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup([\'C\', 4], prefix="s")\n sage: v = W.from_reduced_word([1,2,3,4,3,1])\n sage: v\n s1*s2*s3*s4*s3*s1\n sage: v.apply_simple_projection(2)\n s1*s2*s3*s4*s3*s1*s2\n sage: v.apply_simple_projection(2, side=\'left\')\n s1*s2*s3*s4*s3*s1\n sage: v.apply_simple_projection(1, length_increasing=False)\n s1*s2*s3*s4*s3\n\n ' if self.has_descent(i, side=side, positive=length_increasing): return self.apply_simple_reflection(i, side=side) return self def binary_factorizations(self, predicate=ConstantFunction(True)): '\n Return the set of all the factorizations `self = u v` such\n that `l(self) = l(u) + l(v)`.\n\n Iterating through this set is Constant Amortized Time\n (counting arithmetic operations in the Coxeter group as\n constant time) complexity, and memory linear in the length\n of `self`.\n\n One can pass as optional argument a predicate p such that\n `p(u)` implies `p(u\')` for any `u` left factor of `self`\n and `u\'` left factor of `u`. Then this returns only the\n factorizations `self = uv` such `p(u)` holds.\n\n EXAMPLES:\n\n We construct the set of all factorizations of the maximal\n element of the group::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup([\'A\', 3])\n sage: s = W.simple_reflections()\n sage: w0 = W.from_reduced_word([1,2,3,1,2,1])\n sage: w0.binary_factorizations().cardinality()\n 24\n\n The same number of factorizations, by bounded length::\n\n sage: [w0.binary_factorizations( # needs sage.combinat sage.groups\n ....: lambda u: u.length() <= l\n ....: ).cardinality()\n ....: for l in [-1,0,1,2,3,4,5,6]]\n [0, 1, 4, 9, 15, 20, 23, 24]\n\n The number of factorizations of the elements just below\n the maximal element::\n\n sage: [(s[i]*w0).binary_factorizations().cardinality() # needs sage.combinat sage.groups\n ....: for i in [1,2,3]]\n [12, 12, 12]\n sage: w0.binary_factorizations(lambda u: False).cardinality() # needs sage.combinat sage.groups\n 0\n\n TESTS::\n\n sage: w0.binary_factorizations().category() # needs sage.combinat sage.groups\n Category of finite enumerated sets\n\n Check that this is independent of the implementation of the group, see :trac:`34799`::\n\n sage: # needs sage.combinat sage.groups\n sage: W1 = WeylGroup([\'A\', 3])\n sage: W2 = Permutations(4)\n sage: P = lambda pi: W2(list(pi.to_permutation()))\n sage: d1 = {P(pi): set((P(w[0]), P(w[1]))\n ....: for w in pi.binary_factorizations())\n ....: for pi in W1}\n sage: d2 = {pi: set(pi.binary_factorizations()) for pi in W2}\n sage: d1 == d2\n True\n sage: sage.combinat.permutation.Permutations.options.mult = "r2l"\n sage: d3 = {pi: set(pi.binary_factorizations()) for pi in W2}\n sage: d1 == d3\n True\n sage: sage.combinat.permutation.Permutations.options._reset()\n ' from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet_forest W = self.parent() if (not predicate(W.one())): from sage.sets.finite_enumerated_set import FiniteEnumeratedSet return FiniteEnumeratedSet([]) def succ(u_v): (u, v) = u_v for i in v.descents(side='left'): u1 = u.apply_simple_reflection_right(i) if ((i == u1.first_descent()) and predicate(u1)): (yield (u1, v.apply_simple_reflection_left(i))) return RecursivelyEnumeratedSet_forest(((W.one(), self),), succ, category=FiniteEnumeratedSets()) @cached_in_parent_method def bruhat_lower_covers(self): '\n Return all elements that ``self`` covers in (strong) Bruhat order.\n\n If ``w = self`` has a descent at `i`, then the elements that\n `w` covers are exactly `\\{ws_i, u_1s_i, u_2s_i,..., u_js_i\\}`,\n where the `u_k` are elements that `ws_i` covers that also\n do not have a descent at `i`.\n\n EXAMPLES::\n\n sage: W = WeylGroup(["A", 3]) # needs sage.combinat sage.groups\n sage: w = W.from_reduced_word([3,2,3]) # needs sage.combinat sage.groups\n sage: print([v.reduced_word() for v in w.bruhat_lower_covers()]) # needs sage.combinat sage.groups\n [[3, 2], [2, 3]]\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup(["A", 3])\n sage: print([v.reduced_word()\n ....: for v in W.simple_reflection(1).bruhat_lower_covers()])\n [[]]\n sage: print([v.reduced_word()\n ....: for v in W.one().bruhat_lower_covers()])\n []\n sage: W = WeylGroup(["B", 4, 1])\n sage: w = W.from_reduced_word([0,2])\n sage: print([v.reduced_word() for v in w.bruhat_lower_covers()])\n [[2], [0]]\n sage: W = WeylGroup("A3", prefix="s", implementation="permutation")\n sage: s1, s2, s3 = W.simple_reflections()\n sage: (s1*s2*s3*s1).bruhat_lower_covers()\n [s2*s1*s3, s1*s2*s1, s1*s2*s3]\n\n We now show how to construct the Bruhat poset::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup(["A", 3])\n sage: covers = tuple([u, v]\n ....: for v in W for u in v.bruhat_lower_covers())\n sage: P = Poset((W, covers), cover_relations=True) # needs sage.graphs\n sage: P.show() # needs sage.graphs sage.plot\n\n Alternatively, one can just use::\n\n sage: P = W.bruhat_poset() # needs sage.combinat sage.graphs sage.groups\n\n The algorithm is taken from Stembridge\'s \'coxeter/weyl\' package for Maple.\n ' desc = self.first_descent(side='right') if (desc is None): return [] ww = self.apply_simple_reflection(desc, side='right') return ([u.apply_simple_reflection(desc, side='right') for u in ww.bruhat_lower_covers() if (not u.has_descent(desc, side='right'))] + [ww]) @cached_in_parent_method def bruhat_upper_covers(self): '\n Return all elements that cover ``self`` in (strong) Bruhat order.\n\n The algorithm works recursively, using the \'inverse\' of the method described for\n lower covers :meth:`bruhat_lower_covers`. Namely, it runs through all `i` in the\n index set. Let `w` equal ``self``. If `w` has no right descent `i`, then `w s_i` is a cover;\n if `w` has a decent at `i`, then `u_j s_i` is a cover of `w` where `u_j` is a cover\n of `w s_i`.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\', 3, 1], prefix="s") # needs sage.combinat sage.groups\n sage: w = W.from_reduced_word([1,2,1]) # needs sage.combinat sage.groups\n sage: w.bruhat_upper_covers() # needs sage.combinat sage.groups\n [s1*s2*s1*s0, s1*s2*s0*s1, s0*s1*s2*s1, s3*s1*s2*s1, s2*s3*s1*s2, s1*s2*s3*s1]\n\n sage: W = WeylGroup([\'A\', 3]) # needs sage.combinat sage.groups\n sage: w = W.long_element() # needs sage.combinat sage.groups\n sage: w.bruhat_upper_covers() # needs sage.combinat sage.groups\n []\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup([\'A\', 3])\n sage: w = W.from_reduced_word([1,2,1])\n sage: S = [v for v in W if w in v.bruhat_lower_covers()]\n sage: C = w.bruhat_upper_covers()\n sage: set(S) == set(C)\n True\n ' Covers = set() for i in self.parent().index_set(): if (i in self.descents(side='right')): Covers.update((x.apply_simple_reflection(i, side='right') for x in self.apply_simple_reflection(i, side='right').bruhat_upper_covers() if (i not in x.descents(side='right')))) else: Covers.add(self.apply_simple_reflection(i, side='right')) return sorted(Covers) @cached_in_parent_method def bruhat_lower_covers_reflections(self): '\n Return all 2-tuples of lower_covers and reflections (``v``, ``r``) where ``v`` is covered by ``self`` and ``r`` is the reflection such that ``self`` = ``v`` ``r``.\n\n ALGORITHM:\n\n See :meth:`.bruhat_lower_covers`\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\', 3], prefix="s") # needs sage.combinat sage.groups\n sage: w = W.from_reduced_word([3,1,2,1]) # needs sage.combinat sage.groups\n sage: w.bruhat_lower_covers_reflections() # needs sage.combinat sage.groups\n [(s1*s2*s1, s1*s2*s3*s2*s1), (s3*s2*s1, s2), (s3*s1*s2, s1)]\n\n TESTS:\n\n Check bug discovered in :trac:`32669` is fixed::\n\n sage: W = CoxeterGroup([\'A\', 3], implementation=\'permutation\') # needs sage.combinat sage.groups\n sage: W.w0.bruhat_lower_covers_reflections() # needs sage.combinat sage.groups\n [((1,3,7,9)(2,11,6,10)(4,8,5,12), (2,5)(3,9)(4,6)(8,11)(10,12)),\n ((1,11)(3,10)(4,9)(5,7)(6,12), (1,4)(2,8)(3,5)(7,10)(9,11)),\n ((1,9,7,3)(2,10,6,11)(4,12,5,8), (1,7)(2,4)(5,6)(8,10)(11,12))]\n ' i = self.first_descent(side='right') if (i is None): return [] wi = self.apply_simple_reflection(i, side='right') return ([(u.apply_simple_reflection(i, side='right'), r.apply_conjugation_by_simple_reflection(i)) for (u, r) in wi.bruhat_lower_covers_reflections() if (not u.has_descent(i, side='right'))] + [(wi, self.parent().simple_reflection(i))]) def lower_cover_reflections(self, side='right'): '\n Return the reflections ``t`` such that ``self`` covers ``self`` ``t``.\n\n If ``side`` is \'left\', ``self`` covers ``t`` ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup([\'A\', 3],prefix="s")\n sage: w = W.from_reduced_word([3,1,2,1])\n sage: w.lower_cover_reflections()\n [s1*s2*s3*s2*s1, s2, s1]\n sage: w.lower_cover_reflections(side=\'left\')\n [s2*s3*s2, s3, s1]\n\n ' if (side == 'left'): self = self.inverse() return [x[1] for x in self.bruhat_lower_covers_reflections()] @cached_in_parent_method def bruhat_upper_covers_reflections(self): '\n Return all 2-tuples of covers and reflections (``v``, ``r``) where ``v`` covers ``self`` and ``r`` is the reflection such that ``self`` = ``v`` ``r``.\n\n ALGORITHM:\n\n See :meth:`.bruhat_upper_covers`\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\', 4], prefix="s") # needs sage.combinat sage.groups\n sage: w = W.from_reduced_word([3,1,2,1]) # needs sage.combinat sage.groups\n sage: w.bruhat_upper_covers_reflections() # needs sage.combinat sage.groups\n [(s1*s2*s3*s2*s1, s3), (s2*s3*s1*s2*s1, s2*s3*s2),\n (s3*s4*s1*s2*s1, s4), (s4*s3*s1*s2*s1, s1*s2*s3*s4*s3*s2*s1)]\n ' Covers = set() for i in self.parent().index_set(): wi = self.apply_simple_reflection(i) if (i in self.descents()): Covers.update(((u.apply_simple_reflection(i), r.apply_conjugation_by_simple_reflection(i)) for (u, r) in wi.bruhat_upper_covers_reflections() if (i not in u.descents()))) else: Covers.add((wi, self.parent().simple_reflection(i))) return sorted(Covers) def cover_reflections(self, side='right'): '\n Return the set of reflections ``t`` such that ``self`` ``t`` covers ``self``.\n\n If ``side`` is \'left\', ``t`` ``self`` covers ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup([\'A\', 4], prefix="s")\n sage: w = W.from_reduced_word([3,1,2,1])\n sage: w.cover_reflections()\n [s3, s2*s3*s2, s4, s1*s2*s3*s4*s3*s2*s1]\n sage: w.cover_reflections(side=\'left\')\n [s4, s2, s1*s2*s1, s3*s4*s3]\n\n ' if (side == 'left'): self = self.inverse() return [x[1] for x in self.bruhat_upper_covers_reflections()] @cached_in_parent_method def bruhat_le(self, other): '\n Return whether ``self`` <= ``other`` in the Bruhat order.\n\n INPUT:\n\n - other -- an element of the same Coxeter group\n\n OUTPUT: a boolean\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup(["A", 3])\n sage: u = W.from_reduced_word([1,2,1])\n sage: v = W.from_reduced_word([1,2,3,2,1])\n sage: u.bruhat_le(u)\n True\n sage: u.bruhat_le(v)\n True\n sage: v.bruhat_le(u)\n False\n sage: v.bruhat_le(v)\n True\n sage: s = W.simple_reflections()\n sage: s[1].bruhat_le(W.one())\n False\n\n The implementation uses the equivalent condition that any\n reduced word for ``other`` contains a reduced word for\n ``self`` as subword. See Stembridge, A short derivation of\n the Möbius function for the Bruhat order. J. Algebraic\n Combin. 25 (2007), no. 2, 141--148, Proposition 1.1.\n\n Complexity: `O(l * c)`, where `l` is the minimum of the\n lengths of `u` and of `v`, and `c` is the cost of the low\n level methods :meth:`first_descent`, :meth:`has_descent`,\n :meth:`~sage.categories.complex_reflection_or_generalized_coxeter_groups.ComplexReflectionOrGeneralizedCoxeterGroups.ElementMethods.apply_simple_reflection`),\n etc. Those are typically `O(n)`, where `n` is the rank of the\n Coxeter group.\n\n TESTS:\n\n We now run consistency tests with permutations and\n :meth:`bruhat_lower_covers`::\n\n sage: W = WeylGroup(["A", 3]) # needs sage.combinat sage.groups\n sage: P4 = Permutations(4)\n sage: def P4toW(w): return W.from_reduced_word(w.reduced_word())\n sage: for u in P4: # needs sage.combinat sage.groups\n ....: for v in P4:\n ....: assert u.bruhat_lequal(v) == P4toW(u).bruhat_le(P4toW(v))\n\n sage: # needs sage.combinat sage.graphs sage.groups\n sage: W = WeylGroup(["B", 3])\n sage: P = W.bruhat_poset() # This is built from bruhat_lower_covers\n sage: Q = Poset((W, attrcall("bruhat_le"))) # long time (10s)\n sage: all(u.bruhat_le(v) == P.is_lequal(u,v) # long time (7s)\n ....: for u in W for v in W)\n True\n sage: all(P.is_lequal(u,v) == Q.is_lequal(u,v) # long time (9s)\n ....: for u in W for v in W)\n True\n ' if (not have_same_parent(self, other)): raise TypeError(('%s and %s do not have the same parent' % (self, other))) desc = other.first_descent() if (desc is not None): return self.apply_simple_projection(desc, length_increasing=False).bruhat_le(other.apply_simple_reflection(desc)) return (self == other) def weak_le(self, other, side='right'): '\n Comparison in weak order.\n\n INPUT:\n\n - other -- an element of the same Coxeter group\n - side -- \'left\' or \'right\' (default: \'right\')\n\n OUTPUT: a boolean\n\n This returns whether ``self`` <= ``other`` in left\n (resp. right) weak order, that is if \'v\' can be obtained\n from \'v\' by length increasing multiplication by simple\n reflections on the left (resp. right).\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup(["A", 3])\n sage: u = W.from_reduced_word([1,2])\n sage: v = W.from_reduced_word([1,2,3,2])\n sage: u.weak_le(u)\n True\n sage: u.weak_le(v)\n True\n sage: v.weak_le(u)\n False\n sage: v.weak_le(v)\n True\n\n Comparison for left weak order is achieved with the option ``side``::\n\n sage: u.weak_le(v, side=\'left\') # needs sage.combinat sage.groups\n False\n\n The implementation uses the equivalent condition that any\n reduced word for `u` is a right (resp. left) prefix of\n some reduced word for `v`.\n\n Complexity: `O(l * c)`, where `l` is the minimum of the\n lengths of `u` and of `v`, and `c` is the cost of the low\n level methods :meth:`first_descent`, :meth:`has_descent`,\n :meth:`~sage.categories.complex_reflection_or_generalized_coxeter_groups.ComplexReflectionOrGeneralizedCoxeterGroups.ElementMethods.apply_simple_reflection`),\n etc. Those are typically `O(n)`, where `n` is the rank of the\n Coxeter group.\n\n We now run consistency tests with permutations::\n\n sage: W = WeylGroup(["A", 3]) # needs sage.combinat sage.groups\n sage: P4 = Permutations(4)\n sage: def P4toW(w): return W.from_reduced_word(w.reduced_word())\n sage: for u in P4: # long time (5s on sage.math, 2011), needs sage.combinat sage.groups\n ....: for v in P4:\n ....: assert u.permutohedron_lequal(v) == P4toW(u).weak_le(P4toW(v))\n ....: assert u.permutohedron_lequal(v, side=\'left\') == P4toW(u).weak_le(P4toW(v), side=\'left\')\n ' if (not have_same_parent(self, other)): raise TypeError(f'{self} and {other} do not have the same parent') prefix_side = ('left' if (side == 'right') else 'right') while True: desc = self.first_descent(side=prefix_side) if (desc is None): return True if (not other.has_descent(desc, side=prefix_side)): return False self = self.apply_simple_reflection(desc, side=prefix_side) other = other.apply_simple_reflection(desc, side=prefix_side) def weak_covers(self, side='right', index_set=None, positive=False): "\n Return all elements that ``self`` covers in weak order.\n\n INPUT:\n\n - side -- 'left' or 'right' (default: 'right')\n - positive -- a boolean (default: False)\n - index_set -- a list of indices or None\n\n OUTPUT: a list\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A', 3]) # needs sage.combinat sage.groups\n sage: w = W.from_reduced_word([3,2,1]) # needs sage.combinat sage.groups\n sage: [x.reduced_word() for x in w.weak_covers()] # needs sage.combinat sage.groups\n [[3, 2]]\n\n To obtain instead elements that cover self, set ``positive=True``::\n\n sage: [x.reduced_word() for x in w.weak_covers(positive=True)] # needs sage.combinat sage.groups\n [[3, 1, 2, 1], [2, 3, 2, 1]]\n\n To obtain covers for left weak order, set the option side to 'left'::\n\n sage: # needs sage.combinat sage.groups\n sage: [x.reduced_word() for x in w.weak_covers(side='left')]\n [[2, 1]]\n sage: w = W.from_reduced_word([3,2,3,1])\n sage: [x.reduced_word() for x in w.weak_covers()]\n [[2, 3, 2], [3, 2, 1]]\n sage: [x.reduced_word() for x in w.weak_covers(side='left')]\n [[3, 2, 1], [2, 3, 1]]\n\n Covers w.r.t. a parabolic subgroup are obtained with the option ``index_set``::\n\n sage: [x.reduced_word() for x in w.weak_covers(index_set=[1,2])] # needs sage.combinat sage.groups\n [[2, 3, 2]]\n " return [self.apply_simple_reflection(i, side=side) for i in self.descents(side=side, index_set=index_set, positive=positive)] def coxeter_sorting_word(self, c): '\n Return the ``c``-sorting word of ``self``.\n\n For a Coxeter element `c` and an element `w`, the `c`-sorting\n word of `w` is the lexicographic minimal reduced expression of\n `w` in the infinite word `c^\\infty`.\n\n INPUT:\n\n - ``c``-- a Coxeter element.\n\n OUTPUT:\n\n the ``c``-sorting word of ``self`` as a list of integers.\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: c = W.from_reduced_word([0,2,1])\n sage: w = W.from_reduced_word([1,2,1,0,1])\n sage: w.coxeter_sorting_word(c)\n [2, 1, 2, 0, 1]\n ' if hasattr(c, 'reduced_word'): c = c.reduced_word() elif (not isinstance(c, list)): c = list(c) n = self.parent().rank() pi = self l = pi.length() i = 0 sorting_word = [] while (l > 0): s = c[i] if pi.has_left_descent(s): pi = pi.apply_simple_reflection_left(s) l -= 1 sorting_word.append(s) i += 1 if (i == n): i = 0 return sorting_word def is_coxeter_sortable(self, c, sorting_word=None): "\n Return whether ``self`` is ``c``-sortable.\n\n Given a Coxeter element `c`, an element `w` is `c`-sortable if\n its `c`-sorting word decomposes into a sequence of weakly\n decreasing subwords of `c`.\n\n INPUT:\n\n - ``c`` -- a Coxeter element.\n - ``sorting_word`` -- sorting word (default: None) used to\n not recompute the ``c``-sorting word if already computed.\n\n OUTPUT:\n\n is ``self`` ``c``-sortable\n\n EXAMPLES::\n\n sage: W = CoxeterGroups().example()\n sage: c = W.from_reduced_word([0,2,1])\n sage: w = W.from_reduced_word([1,2,1,0,1])\n sage: w.coxeter_sorting_word(c)\n [2, 1, 2, 0, 1]\n sage: w.is_coxeter_sortable(c)\n False\n sage: w = W.from_reduced_word([0,2,1,0,2])\n sage: w.coxeter_sorting_word(c)\n [2, 0, 1, 2, 0]\n sage: w.is_coxeter_sortable(c)\n True\n\n sage: W = CoxeterGroup(['A', 3]) # needs sage.combinat sage.groups\n sage: c = W.from_reduced_word([1,2,3]) # needs sage.combinat sage.groups\n\n Number of `c`-sortable elements in `A_3` (Catalan number)::\n\n sage: len([w for w in W if w.is_coxeter_sortable(c)])\n 14\n\n TESTS::\n\n sage: W = SymmetricGroup(3) # needs sage.groups\n sage: c = Permutation((1,2,3))\n sage: sorted(w for w in W if w.is_coxeter_sortable(c)) # needs sage.combinat sage.groups\n [(), (2,3), (1,2), (1,3,2), (1,3)]\n " if hasattr(c, 'reduced_word'): c = c.reduced_word() elif (not isinstance(c, list)): c = list(c) if (sorting_word is None): sorting_word = self.coxeter_sorting_word(c) n = len(c) containment_list = ([True] * n) l = 0 i = 0 while (l < len(sorting_word)): s = c[i] t = sorting_word[l] if (s == t): l += 1 if (not containment_list[i]): return False else: containment_list[i] = False i += 1 if (i == n): i = 0 return True def apply_demazure_product(self, element, side='right', length_increasing=True): '\n Return the Demazure or 0-Hecke product of ``self`` with another Coxeter group element.\n\n See :meth:`CoxeterGroups.ParentMethods.simple_projections`.\n\n INPUT:\n\n - ``element`` -- either an element of the same Coxeter\n group as ``self`` or a tuple or a list (such as a\n reduced word) of elements from the index set of the\n Coxeter group.\n\n - ``side`` -- \'left\' or \'right\' (default: \'right\'); the\n side of ``self`` on which the element should be\n applied. If ``side`` is \'left\' then the operation is\n applied on the left.\n\n - ``length_increasing`` -- a boolean (default True)\n whether to act length increasingly or decreasingly\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup([\'C\', 4], prefix="s")\n sage: v = W.from_reduced_word([1,2,3,4,3,1])\n sage: v.apply_demazure_product([1,3,4,3,3])\n s4*s1*s2*s3*s4*s3*s1\n sage: v.apply_demazure_product([1,3,4,3], side=\'left\')\n s3*s4*s1*s2*s3*s4*s2*s3*s1\n sage: v.apply_demazure_product((1,3,4,3), side=\'left\')\n s3*s4*s1*s2*s3*s4*s2*s3*s1\n sage: v.apply_demazure_product(v)\n s2*s3*s4*s1*s2*s3*s4*s2*s3*s2*s1\n\n ' if self.parent().is_parent_of(element): the_word = element.reduced_word() else: if isinstance(element, tuple): element = list(element) elif (not isinstance(element, list)): raise TypeError(f'Bad Coxeter group element input: {element}') I = self.parent().index_set() if (not all(((i in I) for i in element))): raise ValueError(('%s does not have all its members in the index set of the %s' % (element, self.parent()))) the_word = copy(element) if (side == 'left'): the_word.reverse() for i in the_word: self = self.apply_simple_projection(i, side=side, length_increasing=length_increasing) return self def min_demazure_product_greater(self, element): '\n Find the unique Bruhat-minimum element ``u`` such that ``v`` `\\le` ``w`` * ``u`` where ``v`` is ``self``, ``w`` is ``element`` and ``*`` is the Demazure product.\n\n INPUT:\n\n - ``element`` is either an element of the same Coxeter group as ``self`` or a list (such as a reduced word) of elements from the index set of the Coxeter group.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup([\'A\', 4], prefix="s")\n sage: v = W.from_reduced_word([2,3,4,1,2])\n sage: u = W.from_reduced_word([2,3,2,1])\n sage: v.min_demazure_product_greater(u)\n s4*s2\n sage: v.min_demazure_product_greater([2,3,2,1])\n s4*s2\n sage: v.min_demazure_product_greater((2,3,2,1))\n s4*s2\n\n ' if self.parent().is_parent_of(element): the_word = element.reduced_word() else: if (not isinstance(element, (tuple, list))): raise TypeError(('Bad Coxeter group element input: %s' % element)) I = self.parent().index_set() if (not all(((i in I) for i in element))): raise ValueError(('%s does not have all its members in the index set of the %s' % (element, self.parent()))) the_word = element for i in the_word: if self.has_descent(i, side='left'): self = self.apply_simple_reflection(i, side='left') return self def deodhar_factor_element(self, w, index_set): '\n Return Deodhar\'s Bruhat order factoring element.\n\n INPUT:\n\n - ``w`` is an element of the same Coxeter group ``W`` as ``self``\n - ``index_set`` is a subset of Dynkin nodes defining a parabolic subgroup ``W\'`` of ``W``\n\n It is assumed that ``v = self`` and ``w`` are minimum length coset representatives\n for ``W/W\'`` such that ``v`` `\\le` ``w`` in Bruhat order.\n\n OUTPUT:\n\n Deodhar\'s element ``f(v,w)`` is the unique element of ``W\'`` such that,\n for all ``v\'`` and ``w\'`` in ``W\'``, ``vv\'`` `\\le` ``ww\'`` in ``W`` if and only if\n ``v\'`` `\\le` ``f(v,w) * w\'`` in ``W\'`` where ``*`` is the Demazure product.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup([\'A\', 5], prefix="s")\n sage: v = W.from_reduced_word([5])\n sage: w = W.from_reduced_word([4,5,2,3,1,2])\n sage: v.deodhar_factor_element(w, [1,3,4])\n s3*s1\n sage: W = WeylGroup([\'C\', 2])\n sage: w = W.from_reduced_word([2,1])\n sage: w.deodhar_factor_element(W.from_reduced_word([2]),[1])\n Traceback (most recent call last):\n ...\n ValueError: [2, 1] is not of minimum length in its coset\n for the parabolic subgroup with index set [1]\n\n REFERENCES:\n\n - [Deo1987a]_\n ' if (self != self.coset_representative(index_set)): raise ValueError(('%s is not of minimum length in its coset for the parabolic subgroup with index set %s' % (self.reduced_word(), index_set))) if (w != w.coset_representative(index_set)): raise ValueError(('%s is not of minimum length in its coset for the parabolic subgroup with index set %s' % (w.reduced_word(), index_set))) if (not self.bruhat_le(w)): raise ValueError(('Must have %s <= %s' % (self.reduced_word(), w.reduced_word()))) if w.is_one(): return w i = w.first_descent(side='left') sw = w.apply_simple_reflection(i, side='left') sv = self.apply_simple_reflection(i, side='left') if self.has_descent(i, side='left'): return sv.deodhar_factor_element(sw, index_set) dsp = self.deodhar_factor_element(sw, index_set) des = sv.first_descent(side='right', index_set=index_set) if (des is None): return dsp return dsp.apply_simple_projection(des, side='left') def deodhar_lift_up(self, w, index_set): '\n Letting ``v = self``, given a Bruhat relation ``v W\'`` `\\le` ``w W\'`` among cosets\n with respect to the subgroup ``W\'`` given by the Dynkin node subset ``index_set``,\n returns the Bruhat-minimum lift ``x`` of ``wW\'`` such that ``v`` `\\le` ``x``.\n\n INPUT:\n\n - ``w`` is an element of the same Coxeter group ``W`` as ``self``.\n - ``index_set`` is a subset of Dynkin nodes defining a parabolic subgroup ``W\'``.\n\n OUTPUT:\n\n The unique Bruhat-minimum element ``x`` in ``W`` such that ``x W\' = w W\'``\n and ``v`` `\\le` ``x``.\n\n .. SEEALSO:: :meth:`sage.categories.coxeter_groups.CoxeterGroups.ElementMethods.deodhar_lift_down`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup([\'A\', 3], prefix="s")\n sage: v = W.from_reduced_word([1,2,3])\n sage: w = W.from_reduced_word([1,3,2])\n sage: v.deodhar_lift_up(w, [3])\n s1*s2*s3*s2\n ' vmin = self.coset_representative(index_set) wmin = w.coset_representative(index_set) if (not vmin.bruhat_le(wmin)): raise ValueError(('Must have %s <= %s mod the parabolic subgroup with index set %s' % (self.reduced_word(), w.reduced_word(), index_set))) vJ = (vmin.inverse() * self) dsp = vmin.deodhar_factor_element(wmin, index_set) return (wmin * vJ.min_demazure_product_greater(dsp)) def deodhar_lift_down(self, w, index_set): '\n Letting ``v = self``, given a Bruhat relation ``v W\'`` `\\ge` ``w W\'`` among cosets\n with respect to the subgroup ``W\'`` given by the Dynkin node subset ``index_set``,\n returns the Bruhat-maximum lift ``x`` of ``wW\'`` such that ``v`` `\\ge` ``x``.\n\n INPUT:\n\n - ``w`` is an element of the same Coxeter group ``W`` as ``self``.\n - ``index_set`` is a subset of Dynkin nodes defining a parabolic subgroup ``W\'``.\n\n OUTPUT:\n\n The unique Bruhat-maximum element ``x`` in ``W`` such that ``x W\' = w W\'``\n and ``v`` `\\ge` ``x``.\n\n .. SEEALSO:: :meth:`sage.categories.coxeter_groups.CoxeterGroups.ElementMethods.deodhar_lift_up`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = WeylGroup([\'A\', 3], prefix="s")\n sage: v = W.from_reduced_word([1,2,3,2])\n sage: w = W.from_reduced_word([3,2])\n sage: v.deodhar_lift_down(w, [3])\n s2*s3*s2\n\n ' vmin = self.coset_representative(index_set) wmin = w.coset_representative(index_set) if (not wmin.bruhat_le(vmin)): raise ValueError(('Must have %s <= %s mod the parabolic subgroup with index set %s' % (w.reduced_word(), self.reduced_word(), index_set))) vJ = (vmin.inverse() * self) dsp = wmin.deodhar_factor_element(vmin, index_set) return (wmin * dsp.apply_demazure_product(vJ)) @cached_in_parent_method def inversions_as_reflections(self): '\n Return the set of reflections ``r`` such that ``self`` ``r < self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\', 3], prefix="s") # needs sage.combinat sage.groups\n sage: w = W.from_reduced_word([3,1,2,1]) # needs sage.combinat sage.groups\n sage: w.inversions_as_reflections() # needs sage.combinat sage.groups\n [s1, s1*s2*s1, s2, s1*s2*s3*s2*s1]\n ' i = self.first_descent() if (i is None): return [] wi = self.apply_simple_reflection(i) return ([self.parent().simple_reflection(i)] + [u.apply_conjugation_by_simple_reflection(i) for u in wi.inversions_as_reflections()]) def left_inversions_as_reflections(self): '\n Return the set of reflections ``r`` such that ``r`` ``self`` < ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\', 3], prefix="s") # needs sage.combinat sage.groups\n sage: w = W.from_reduced_word([3,1,2,1]) # needs sage.combinat sage.groups\n sage: w.left_inversions_as_reflections() # needs sage.combinat sage.groups\n [s1, s3, s1*s2*s3*s2*s1, s2*s3*s2]\n ' return self.inverse().inversions_as_reflections() def lower_covers(self, side='right', index_set=None): "\n Return all elements that ``self`` covers in weak order.\n\n INPUT:\n\n - ``side`` -- ``'left'`` or ``'right'`` (default: ``'right'``)\n - ``index_set`` -- a list of indices or ``None``\n\n OUTPUT: a list\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A', 3]) # needs sage.combinat sage.groups\n sage: w = W.from_reduced_word([3,2,1]) # needs sage.combinat sage.groups\n sage: [x.reduced_word() for x in w.lower_covers()] # needs sage.combinat sage.groups\n [[3, 2]]\n\n To obtain covers for left weak order, set the option side to 'left'::\n\n sage: [x.reduced_word() for x in w.lower_covers(side='left')] # needs sage.combinat sage.groups\n [[2, 1]]\n sage: w = W.from_reduced_word([3,2,3,1]) # needs sage.combinat sage.groups\n sage: [x.reduced_word() for x in w.lower_covers()] # needs sage.combinat sage.groups\n [[2, 3, 2], [3, 2, 1]]\n\n Covers w.r.t. a parabolic subgroup are obtained with the option ``index_set``::\n\n sage: [x.reduced_word() for x in w.lower_covers(index_set=[1,2])] # needs sage.combinat sage.groups\n [[2, 3, 2]]\n sage: [x.reduced_word() for x in w.lower_covers(side='left')] # needs sage.combinat sage.groups\n [[3, 2, 1], [2, 3, 1]]\n " return self.weak_covers(side=side, index_set=index_set, positive=False) def upper_covers(self, side='right', index_set=None): "\n Return all elements that cover ``self`` in weak order.\n\n INPUT:\n\n - ``side`` -- ``'left'`` or ``'right'`` (default: ``'right'``)\n - ``index_set`` -- a list of indices or ``None``\n\n OUTPUT: a list\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A', 3]) # needs sage.combinat sage.groups\n sage: w = W.from_reduced_word([2,3]) # needs sage.combinat sage.groups\n sage: [x.reduced_word() for x in w.upper_covers()] # needs sage.combinat sage.groups\n [[2, 3, 1], [2, 3, 2]]\n\n To obtain covers for left weak order, set the option ``side`` to 'left'::\n\n sage: [x.reduced_word() for x in w.upper_covers(side='left')] # needs sage.combinat sage.groups\n [[1, 2, 3], [2, 3, 2]]\n\n Covers w.r.t. a parabolic subgroup are obtained with the option ``index_set``::\n\n sage: [x.reduced_word() for x in w.upper_covers(index_set=[1])] # needs sage.combinat sage.groups\n [[2, 3, 1]]\n sage: [x.reduced_word() # needs sage.combinat sage.groups\n ....: for x in w.upper_covers(side='left', index_set=[1])]\n [[1, 2, 3]]\n " return self.weak_covers(side=side, index_set=index_set, positive=True) def kazhdan_lusztig_cell(self, side='left'): "\n Compute the left, right, or two-sided Kazhdan-Lusztig cell\n containing the element ``self`` depending on the specified ``side``.\n\n Let `C'` denote the Kazhdan-Lusztig `C^{\\prime}`-basis of the\n Iwahori-Hecke algebra `H` of a Coxeter system `(W,S)`. Two elements\n `x,y` of the Coxeter group `W` are said to lie in the same left\n Kazhdan-Lusztig cell if there exist sequences `x = w_1, w_2, \\ldots,\n w_k = y` and `y = u_1, u_2, \\ldots, u_l = x` such that for all\n `1 \\leq i < k` and all `1 \\leq j < l`, there exist some Coxeter\n generators `s,t \\in S` for which `C'_{w_{i+1}}` appears in\n `C'_s C'_{w_i}` and `C'_{u_{j+1}}` appears in `C'_s C'_{u_j}`\n in `H`. Right and two-sided Kazhdan-Lusztig cells of `W` are\n defined similarly; see [Lus2013]_.\n\n In this function, we compute products in the `C^{\\prime}` basis by\n using :class:`IwahoriHeckeAlgebra.Cp`. As mentioned in that class,\n installing the optional package ``coxeter3`` is recommended\n (though not required) before using this function because the\n package speeds up product computations that are sometimes\n computationally infeasible without it.\n\n INPUT:\n\n - ``w`` -- an element of ``self``\n\n - ``side`` -- (default: ``'left'``) the kind of cell to compute;\n must be either ``'left'``, ``'right'``, or ``'two-sided'``\n\n EXAMPLES:\n\n We compute the left cell of the generator `s_1` in type `A_3` in\n three different implementations of the Coxeter group. Note that the\n choice of implementation affects the representation of elements in\n the output cell but not the method used for the cell computation::\n\n sage: W = CoxeterGroup('A3', implementation='permutation') # needs sage.combinat sage.groups\n sage: s1, s2, s3 = W.simple_reflections() # needs sage.combinat sage.groups\n sage: s1.kazhdan_lusztig_cell() # needs sage.combinat sage.groups\n {(1,2,3,12)(4,5,10,11)(6,7,8,9),\n (1,2,10)(3,6,5)(4,7,8)(9,12,11),\n (1,7)(2,4)(5,6)(8,10)(11,12)}\n\n The cell computation uses the optional package ``coxeter3`` in\n the background if available to speed up the computation,\n even in the different implementations::\n\n sage: # optional - coxeter3, needs sage.combinat sage.groups sage.modules\n sage: W = WeylGroup('A3', prefix='s')\n sage: s1,s2,s3 = W.simple_reflections()\n sage: s1.kazhdan_lusztig_cell()\n {s3*s2*s1, s2*s1, s1}\n sage: W = CoxeterGroup('A3', implementation='coxeter3')\n sage: s1,s2,s3 = W.simple_reflections()\n sage: s1.kazhdan_lusztig_cell()\n {[1], [2, 1], [3, 2, 1]}\n\n Next, we compute a right cell and a two-sided cell in `A_3`::\n\n sage: # optional - coxeter3, needs sage.combinat sage.groups sage.modules\n sage: W = CoxeterGroup('A3', implementation='coxeter3')\n sage: s1,s2,s3 = W.simple_reflections()\n sage: w = s1 * s3\n sage: w.kazhdan_lusztig_cell(side='right')\n {[1, 3], [1, 3, 2]}\n sage: w.kazhdan_lusztig_cell(side='two-sided')\n {[1, 3], [1, 3, 2], [2, 1, 3], [2, 1, 3, 2]}\n\n Some slightly longer computations in `B_4`::\n\n sage: # optional - coxeter3, needs sage.combinat sage.groups sage.modules\n sage: W = CoxeterGroup('B4', implementation='coxeter3')\n sage: s1,s2,s3,s4 = W.simple_reflections()\n sage: s1.kazhdan_lusztig_cell(side='right') # long time (4 seconds)\n {[1],\n [1, 2],\n [1, 2, 3],\n [1, 2, 3, 4],\n [1, 2, 3, 4, 3],\n [1, 2, 3, 4, 3, 2],\n [1, 2, 3, 4, 3, 2, 1]}\n sage: (s4*s2*s3*s4).kazhdan_lusztig_cell(side='two-sided') # long time (8 seconds)\n {[2, 3, 1],\n [2, 3, 1, 2],\n [2, 3, 4, 1],\n [2, 3, 4, 1, 2],\n [2, 3, 4, 1, 2, 3],\n [2, 3, 4, 1, 2, 3, 4],\n [2, 3, 4, 3, 1],\n [2, 3, 4, 3, 1, 2],\n ...\n [4, 3, 4, 2, 3, 4, 1, 2, 3, 4]}\n " from sage.algebras.iwahori_hecke_algebra import IwahoriHeckeAlgebra from sage.rings.polynomial.laurent_polynomial_ring import LaurentPolynomialRing from sage.rings.integer_ring import ZZ R = LaurentPolynomialRing(ZZ, 'v') v = R.gen(0) H = IwahoriHeckeAlgebra(self.parent(), (v ** 2)) Cp = H.Cp() w = self.parent()(self) (vertices, edges) = ({w}, set()) queue = deque([w]) while queue: x = queue.pop() cp_x = Cp(x) for s in self.parent().simple_reflections(): cp_s = Cp(s) terms = [] if ((side == 'left') or (side == 'two-sided')): terms.extend(list((cp_s * cp_x))) if ((side == 'right') or (side == 'two-sided')): terms.extend(list((cp_x * cp_s))) for (y, _) in terms: if (y != x): edges.add((x, y)) if (y not in vertices): vertices.add(y) queue.appendleft(y) from sage.graphs.digraph import DiGraph g = DiGraph([list(vertices), list(edges)]) return set(g.strongly_connected_component_containing_vertex(w))
class Crystals(Category_singleton): "\n The category of crystals.\n\n See :mod:`sage.combinat.crystals.crystals` for an introduction to crystals.\n\n EXAMPLES::\n\n sage: C = Crystals()\n sage: C\n Category of crystals\n sage: C.super_categories()\n [Category of... enumerated sets]\n sage: C.example()\n Highest weight crystal of type A_3 of highest weight omega_1\n\n Parents in this category should implement the following methods:\n\n - either an attribute ``_cartan_type`` or a method ``cartan_type``\n\n - ``module_generators``: a list (or container) of distinct elements\n which generate the crystal using `f_i`\n\n Furthermore, their elements ``x`` should implement the following\n methods:\n\n - ``x.e(i)`` (returning `e_i(x)`)\n\n - ``x.f(i)`` (returning `f_i(x)`)\n\n - ``x.epsilon(i)`` (returning `\\varepsilon_i(x)`)\n\n - ``x.phi(i)`` (returning `\\varphi_i(x)`)\n\n EXAMPLES::\n\n sage: from sage.misc.abstract_method import abstract_methods_of_class\n sage: abstract_methods_of_class(Crystals().element_class)\n {'optional': [], 'required': ['e', 'epsilon', 'f', 'phi', 'weight']}\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: B = Crystals().example()\n sage: TestSuite(B).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_fast_iter() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n " def super_categories(self): '\n EXAMPLES::\n\n sage: Crystals().super_categories()\n [Category of enumerated sets]\n ' return [EnumeratedSets()] def example(self, choice='highwt', **kwds): "\n Returns an example of a crystal, as per\n :meth:`Category.example()\n <sage.categories.category.Category.example>`.\n\n INPUT:\n\n - ``choice`` -- str [default: 'highwt']. Can be either 'highwt'\n for the highest weight crystal of type A, or 'naive' for an\n example of a broken crystal.\n\n - ``**kwds`` -- keyword arguments passed onto the constructor for the\n chosen crystal.\n\n EXAMPLES::\n\n sage: Crystals().example(choice='highwt', n=5)\n Highest weight crystal of type A_5 of highest weight omega_1\n sage: Crystals().example(choice='naive')\n A broken crystal, defined by digraph, of dimension five.\n " import sage.categories.examples.crystals as examples if (choice == 'naive'): return examples.NaiveCrystal(**kwds) else: from sage.rings.integer import Integer if isinstance(choice, Integer): return examples.HighestWeightCrystalOfTypeA(n=choice, **kwds) else: return examples.HighestWeightCrystalOfTypeA(**kwds) class MorphismMethods(): @cached_method def is_isomorphism(self): "\n Check if ``self`` is a crystal isomorphism.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['C',2], shape=[1,1])\n sage: C = crystals.Tableaux(['C',2], ([2,1], [1,1]))\n sage: psi = B.crystal_morphism(C.module_generators[1:], codomain=C)\n sage: psi.is_isomorphism()\n False\n " if (self.domain().cardinality() != self.codomain().cardinality()): return False if (self.domain().cardinality() == float('inf')): raise NotImplementedError('unable to determine if an isomorphism') index_set = self._cartan_type.index_set() G = self.domain().digraph(index_set=index_set) if (self.codomain().cardinality() != G.num_verts()): return False H = self.codomain().digraph(index_set=index_set) return G.is_isomorphic(H, edge_labels=True) @cached_method def is_embedding(self): "\n Check if ``self`` is an injective crystal morphism.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['C',2], shape=[1,1])\n sage: C = crystals.Tableaux(['C',2], ([2,1], [1,1]))\n sage: psi = B.crystal_morphism(C.module_generators[1:], codomain=C)\n sage: psi.is_embedding()\n True\n\n sage: C = crystals.Tableaux(['A',2], shape=[2,1])\n sage: B = crystals.infinity.Tableaux(['A',2])\n sage: La = RootSystem(['A',2]).weight_lattice().fundamental_weights()\n sage: W = crystals.elementary.T(['A',2], La[1]+La[2])\n sage: T = W.tensor(B)\n sage: mg = T(W.module_generators[0], B.module_generators[0])\n sage: psi = Hom(C,T)([mg])\n sage: psi.is_embedding()\n True\n " if (self.domain().cardinality() > self.codomain().cardinality()): return False if (self.domain().cardinality() == float('inf')): raise NotImplementedError('unable to determine if an embedding') S = set() for x in self.domain(): y = self(x) if ((y is None) or (y in S)): return False S.add(y) return True @cached_method def is_strict(self): "\n Check if ``self`` is a strict crystal morphism.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['C',2], shape=[1,1])\n sage: C = crystals.Tableaux(['C',2], ([2,1], [1,1]))\n sage: psi = B.crystal_morphism(C.module_generators[1:], codomain=C)\n sage: psi.is_strict()\n True\n " if (self.domain().cardinality() == float('inf')): raise NotImplementedError('unable to determine if strict') index_set = self._cartan_type.index_set() for x in self.domain(): y = self(x) if any((((self(x.f(i)) != y.f(i)) or (self(x.e(i)) != y.e(i))) for i in index_set)): return False return True class ParentMethods(): def an_element(self): "\n Returns an element of ``self``\n\n sage: C = crystals.Letters(['A', 5])\n sage: C.an_element()\n 1\n " return self.first() @cached_method def weight_lattice_realization(self): '\n Return the weight lattice realization used to express weights\n in ``self``.\n\n This default implementation uses the ambient space of the\n root system for (non relabelled) finite types and the\n weight lattice otherwise. This is a legacy from when\n ambient spaces were partially implemented, and may be\n changed in the future.\n\n For affine types, this returns the extended weight lattice\n by default.\n\n EXAMPLES::\n\n sage: C = crystals.Letters([\'A\', 5])\n sage: C.weight_lattice_realization()\n Ambient space of the Root system of type [\'A\', 5]\n sage: K = crystals.KirillovReshetikhin([\'A\',2,1], 1, 1)\n sage: K.weight_lattice_realization()\n Weight lattice of the Root system of type [\'A\', 2, 1]\n\n TESTS:\n\n Check that crystals have the correct weight lattice realization::\n\n sage: A = crystals.KirillovReshetikhin([\'A\',2,1], 1, 1).affinization()\n sage: A.weight_lattice_realization()\n Extended weight lattice of the Root system of type [\'A\', 2, 1]\n\n sage: B = crystals.AlcovePaths([\'A\',2,1],[1,0,0])\n sage: B.weight_lattice_realization()\n Extended weight lattice of the Root system of type [\'A\', 2, 1]\n\n sage: C = crystals.AlcovePaths("B3",[1,0,0])\n sage: C.weight_lattice_realization()\n Ambient space of the Root system of type [\'B\', 3]\n\n sage: M = crystals.infinity.NakajimaMonomials([\'A\',3,2])\n sage: M.weight_lattice_realization()\n Extended weight lattice of the Root system of type [\'B\', 2, 1]^*\n sage: M = crystals.infinity.NakajimaMonomials([\'A\',2])\n sage: M.weight_lattice_realization()\n Ambient space of the Root system of type [\'A\', 2]\n sage: A = CartanMatrix([[2,-3],[-3,2]])\n sage: M = crystals.infinity.NakajimaMonomials(A)\n sage: M.weight_lattice_realization()\n Weight lattice of the Root system of type Dynkin diagram of rank 2\n\n sage: Y = crystals.infinity.GeneralizedYoungWalls(3)\n sage: Y.weight_lattice_realization()\n Extended weight lattice of the Root system of type [\'A\', 3, 1]\n ' F = self.cartan_type().root_system() if (self.cartan_type().is_finite() and (F.ambient_space() is not None)): return F.ambient_space() if self.cartan_type().is_affine(): return F.weight_lattice(extended=True) return F.weight_lattice() def cartan_type(self): "\n Returns the Cartan type of the crystal\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',2])\n sage: C.cartan_type()\n ['A', 2]\n " return self._cartan_type @cached_method def index_set(self): "\n Returns the index set of the Dynkin diagram underlying the crystal\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A', 5])\n sage: C.index_set()\n (1, 2, 3, 4, 5)\n " return self.cartan_type().index_set() def Lambda(self): "\n Returns the fundamental weights in the weight lattice\n realization for the root system associated with the crystal\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A', 5])\n sage: C.Lambda()\n Finite family {1: (1, 0, 0, 0, 0, 0), 2: (1, 1, 0, 0, 0, 0), 3: (1, 1, 1, 0, 0, 0), 4: (1, 1, 1, 1, 0, 0), 5: (1, 1, 1, 1, 1, 0)}\n " return self.weight_lattice_realization().fundamental_weights() def __iter__(self, index_set=None, max_depth=float('inf')): "\n Return an iterator over the elements of ``self``.\n\n INPUT:\n\n - ``index_set`` -- (Default: ``None``) the index set; if ``None``\n then use the index set of the crystal\n\n - ``max_depth`` -- (Default: infinity) the maximum depth to build\n\n The iteration order is not specified except that, if\n ``max_depth`` is finite, then the iteration goes depth by\n depth.\n\n EXAMPLES::\n\n sage: C = crystals.LSPaths(['A',2,1],[-1,0,1])\n sage: C.__iter__.__module__\n 'sage.categories.crystals'\n sage: g = C.__iter__()\n sage: for _ in range(5): next(g)\n (-Lambda[0] + Lambda[2],)\n (Lambda[1] - Lambda[2],)\n (Lambda[0] - Lambda[1] + delta,)\n (Lambda[0] - Lambda[1],)\n (Lambda[1] - Lambda[2] + delta,)\n\n sage: sorted(C.__iter__(index_set=[1,2]), key=str)\n [(-Lambda[0] + Lambda[2],),\n (Lambda[0] - Lambda[1],),\n (Lambda[1] - Lambda[2],)]\n\n sage: sorted(C.__iter__(max_depth=1), key=str)\n [(-Lambda[0] + Lambda[2],),\n (Lambda[0] - Lambda[1] + delta,),\n (Lambda[1] - Lambda[2],)]\n\n " if (index_set is None): index_set = self.index_set() succ = (lambda x: ([x.f(i) for i in index_set] + [x.e(i) for i in index_set])) from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet R = RecursivelyEnumeratedSet(self.module_generators, succ, structure=None) return R.breadth_first_search_iterator(max_depth) def subcrystal(self, index_set=None, generators=None, max_depth=float('inf'), direction='both', contained=None, virtualization=None, scaling_factors=None, cartan_type=None, category=None): "\n Construct the subcrystal from ``generators`` using `e_i` and/or\n `f_i` for all `i` in ``index_set``.\n\n INPUT:\n\n - ``index_set`` -- (default: ``None``) the index set; if ``None``\n then use the index set of the crystal\n\n - ``generators`` -- (default: ``None``) the list of generators; if\n ``None`` then use the module generators of the crystal\n\n - ``max_depth`` -- (default: infinity) the maximum depth to build\n\n - ``direction`` -- (default: ``'both'``) the direction to build\n the subcrystal; it can be one of the following:\n\n - ``'both'`` - using both `e_i` and `f_i`\n - ``'upper'`` - using `e_i`\n - ``'lower'`` - using `f_i`\n\n - ``contained`` -- (optional) a set or function defining the\n containment in the subcrystal\n\n - ``virtualization``, ``scaling_factors`` -- (optional)\n dictionaries whose key `i` corresponds to the sets `\\sigma_i`\n and `\\gamma_i` respectively used to define virtual crystals; see\n :class:`~sage.combinat.crystals.virtual_crystal.VirtualCrystal`\n\n - ``cartan_type`` -- (optional) specify the Cartan type of the\n subcrystal\n\n - ``category`` -- (optional) specify the category of the subcrystal\n\n EXAMPLES::\n\n sage: C = crystals.KirillovReshetikhin(['A',3,1], 1, 2)\n sage: S = list(C.subcrystal(index_set=[1,2])); S\n [[[1, 1]], [[1, 2]], [[2, 2]], [[1, 3]], [[2, 3]], [[3, 3]]]\n sage: C.cardinality()\n 10\n sage: len(S)\n 6\n sage: list(C.subcrystal(index_set=[1,3], generators=[C(1,4)]))\n [[[1, 4]], [[2, 4]], [[1, 3]], [[2, 3]]]\n sage: list(C.subcrystal(index_set=[1,3], generators=[C(1,4)], max_depth=1))\n [[[1, 4]], [[2, 4]], [[1, 3]]]\n sage: list(C.subcrystal(index_set=[1,3], generators=[C(1,4)], direction='upper'))\n [[[1, 4]], [[1, 3]]]\n sage: list(C.subcrystal(index_set=[1,3], generators=[C(1,4)], direction='lower'))\n [[[1, 4]], [[2, 4]]]\n\n sage: G = C.subcrystal(index_set=[1,2,3]).digraph()\n sage: GA = crystals.Tableaux('A3', shape=[2]).digraph()\n sage: G.is_isomorphic(GA, edge_labels=True)\n True\n\n We construct the subcrystal which contains the necessary data\n to construct the corresponding dual equivalence graph::\n\n sage: C = crystals.Tableaux(['A',5], shape=[3,3])\n sage: is_wt0 = lambda x: all(x.epsilon(i) == x.phi(i) for i in x.parent().index_set())\n sage: def check(x):\n ....: if is_wt0(x):\n ....: return True\n ....: for i in x.parent().index_set()[:-1]:\n ....: L = [x.e(i), x.e_string([i,i+1]), x.f(i), x.f_string([i,i+1])]\n ....: if any(y is not None and is_wt0(y) for y in L):\n ....: return True\n ....: return False\n sage: wt0 = [x for x in C if is_wt0(x)]\n sage: S = C.subcrystal(contained=check, generators=wt0)\n sage: S.module_generators[0]\n [[1, 3, 5], [2, 4, 6]]\n sage: S.module_generators[0].e(2).e(3).f(2).f(3)\n [[1, 2, 5], [3, 4, 6]]\n\n An example of a type `B_2` virtual crystal inside of a\n type `A_3` ambient crystal::\n\n sage: A = crystals.Tableaux(['A',3], shape=[2,1,1])\n sage: S = A.subcrystal(virtualization={1:[1,3], 2:[2]},\n ....: scaling_factors={1:1,2:1}, cartan_type=['B',2])\n sage: B = crystals.Tableaux(['B',2], shape=[1])\n sage: S.digraph().is_isomorphic(B.digraph(), edge_labels=True)\n True\n\n TESTS:\n\n Check that :trac:`23942` is fixed::\n\n sage: B = crystals.infinity.Tableaux(['A',2])\n sage: S = B.subcrystal(max_depth=3, category=HighestWeightCrystals())\n sage: S.category()\n Category of finite highest weight crystals\n\n sage: K = crystals.KirillovReshetikhin(['A',3,1], 2,3)\n sage: S = K.subcrystal(index_set=[1,3], category=HighestWeightCrystals())\n sage: S.category()\n Category of finite highest weight crystals\n " from sage.combinat.crystals.subcrystal import Subcrystal from sage.categories.finite_crystals import FiniteCrystals if (cartan_type is None): cartan_type = self.cartan_type() else: from sage.combinat.root_system.cartan_type import CartanType cartan_type = CartanType(cartan_type) if (index_set is None): index_set = cartan_type.index_set() if (generators is None): generators = self.module_generators if (max_depth == float('inf')): if (self not in FiniteCrystals()): if ((contained is None) and (index_set == self.index_set()) and (generators == self.module_generators) and (scaling_factors is None) and (virtualization is None)): return self return Subcrystal(self, contained, generators, virtualization, scaling_factors, cartan_type, index_set, category) if (direction == 'both'): if (category is None): category = FiniteCrystals() else: category = (FiniteCrystals() & category) return Subcrystal(self, contained, generators, virtualization, scaling_factors, cartan_type, index_set, category) if (direction == 'both'): succ = (lambda x: ([x.f(i) for i in index_set] + [x.e(i) for i in index_set])) elif (direction == 'upper'): succ = (lambda x: [x.e(i) for i in index_set]) elif (direction == 'lower'): succ = (lambda x: [x.f(i) for i in index_set]) else: raise ValueError("direction must be either 'both', 'upper', or 'lower'") from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet subset = RecursivelyEnumeratedSet(generators, succ, structure=None, enumeration='breadth', max_depth=max_depth) if (contained is not None): try: subset = frozenset((x for x in subset if (x in contained))) except TypeError: subset = frozenset((x for x in subset if contained(x))) else: subset = frozenset(subset) if (category is None): category = FiniteCrystals() else: category = (FiniteCrystals() & category) if ((self in FiniteCrystals()) and (len(subset) == self.cardinality())): if (index_set == self.index_set()): return self return Subcrystal(self, subset, generators, virtualization, scaling_factors, cartan_type, index_set, category) def _Hom_(self, Y, category=None, **options): "\n Return the homset from ``self`` to ``Y`` in the\n category ``category``.\n\n INPUT:\n\n - ``Y`` -- a crystal\n - ``category`` -- a subcategory of :class:`Crystals`() or ``None``\n\n The sole purpose of this method is to construct the homset\n as a :class:`~sage.categories.crystals.CrystalHomset`. If\n ``category`` is specified and is not a subcategory of\n :class:`Crystals`, a :class:`TypeError` is raised instead.\n\n This method is not meant to be called directly. Please use\n :func:`sage.categories.homset.Hom` instead.\n\n EXAMPLES::\n\n sage: B = crystals.elementary.B(['A',2], 1)\n sage: H = B._Hom_(B); H\n Set of Crystal Morphisms from The 1-elementary crystal of type ['A', 2]\n to The 1-elementary crystal of type ['A', 2]\n " if (category is None): category = self.category() elif (not category.is_subcategory(Crystals())): raise TypeError('{} is not a subcategory of Crystals()'.format(category)) if (Y not in Crystals()): raise TypeError('{} is not a crystal'.format(Y)) return CrystalHomset(self, Y, category=category, **options) def crystal_morphism(self, on_gens, codomain=None, cartan_type=None, index_set=None, generators=None, automorphism=None, virtualization=None, scaling_factors=None, category=None, check=True): '\n Construct a crystal morphism from ``self`` to another crystal\n ``codomain``.\n\n INPUT:\n\n - ``on_gens`` -- a function or list that determines the image\n of the generators (if given a list, then this uses the order\n of the generators of the domain) of ``self`` under the\n crystal morphism\n - ``codomain`` -- (default: ``self``) the codomain of the morphism\n - ``cartan_type`` -- (optional) the Cartan type of the morphism;\n the default is the Cartan type of ``self``\n - ``index_set`` -- (optional) the index set of the morphism;\n the default is the index set of the Cartan type\n - ``generators`` -- (optional) the generators to define the\n morphism; the default is the generators of ``self``\n - ``automorphism`` -- (optional) the automorphism to perform the\n twisting\n - ``virtualization`` -- (optional) a dictionary whose keys are\n in the index set of the domain and whose values are lists of\n entries in the index set of the codomain; the default is the\n identity dictionary\n - ``scaling_factors`` -- (optional) a dictionary whose keys are\n in the index set of the domain and whose values are scaling\n factors for the weight, `\\varepsilon` and `\\varphi`; the\n default are all scaling factors to be one\n - ``category`` -- (optional) the category for the crystal morphism;\n the default is the category of :class:`Crystals`.\n - ``check`` -- (default: ``True``) check if the crystal morphism\n is valid\n\n .. SEEALSO::\n\n For more examples, see\n :class:`sage.categories.crystals.CrystalHomset`.\n\n EXAMPLES:\n\n We construct the natural embedding of a crystal using tableaux\n into the tensor product of single boxes via the reading word::\n\n sage: B = crystals.Tableaux([\'A\',2], shape=[2,1])\n sage: F = crystals.Tableaux([\'A\',2], shape=[1])\n sage: T = crystals.TensorProduct(F, F, F)\n sage: mg = T.highest_weight_vectors()[2]; mg\n [[[1]], [[2]], [[1]]]\n sage: psi = B.crystal_morphism([mg], codomain=T); psi\n [\'A\', 2] Crystal morphism:\n From: The crystal of tableaux of type [\'A\', 2] and shape(s) [[2, 1]]\n To: Full tensor product of the crystals\n [The crystal of tableaux of type [\'A\', 2] and shape(s) [[1]],\n The crystal of tableaux of type [\'A\', 2] and shape(s) [[1]],\n The crystal of tableaux of type [\'A\', 2] and shape(s) [[1]]]\n Defn: [[1, 1], [2]] |--> [[[1]], [[2]], [[1]]]\n sage: b = B.module_generators[0]\n sage: b.pp()\n 1 1\n 2\n sage: psi(b)\n [[[1]], [[2]], [[1]]]\n sage: psi(b.f(2))\n [[[1]], [[3]], [[1]]]\n sage: psi(b.f_string([2,1,1]))\n [[[2]], [[3]], [[2]]]\n sage: lw = b.to_lowest_weight()[0]\n sage: lw.pp()\n 2 3\n 3\n sage: psi(lw)\n [[[3]], [[3]], [[2]]]\n sage: psi(lw) == mg.to_lowest_weight()[0]\n True\n\n We now take the other isomorphic highest weight component\n in the tensor product::\n\n sage: mg = T.highest_weight_vectors()[1]; mg\n [[[2]], [[1]], [[1]]]\n sage: psi = B.crystal_morphism([mg], codomain=T)\n sage: psi(lw)\n [[[3]], [[2]], [[3]]]\n\n We construct a crystal morphism of classical crystals using a\n Kirillov-Reshetikhin crystal::\n\n sage: B = crystals.Tableaux([\'D\', 4], shape=[1,1])\n sage: K = crystals.KirillovReshetikhin([\'D\',4,1], 2,2)\n sage: K.module_generators\n [[], [[1], [2]], [[1, 1], [2, 2]]]\n sage: v = K.module_generators[1]\n sage: psi = B.crystal_morphism([v], codomain=K, category=FiniteCrystals())\n sage: psi\n [\'D\', 4] -> [\'D\', 4, 1] Virtual Crystal morphism:\n From: The crystal of tableaux of type [\'D\', 4] and shape(s) [[1, 1]]\n To: Kirillov-Reshetikhin crystal of type [\'D\', 4, 1] with (r,s)=(2,2)\n Defn: [[1], [2]] |--> [[1], [2]]\n sage: b = B.module_generators[0]\n sage: psi(b)\n [[1], [2]]\n sage: psi(b.to_lowest_weight()[0])\n [[-2], [-1]]\n\n We can define crystal morphisms using a different set of\n generators. For example, we construct an example using the\n lowest weight vector::\n\n sage: B = crystals.Tableaux([\'A\',2], shape=[1])\n sage: La = RootSystem([\'A\',2]).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T([\'A\',2], La[2])\n sage: Bp = T.tensor(B)\n sage: C = crystals.Tableaux([\'A\',2], shape=[2,1])\n sage: x = C.module_generators[0].f_string([1,2])\n sage: psi = Bp.crystal_morphism([x], generators=Bp.lowest_weight_vectors())\n sage: psi(Bp.highest_weight_vector())\n [[1, 1], [2]]\n\n We can also use a dictionary to specify the generators and\n their images::\n\n sage: psi = Bp.crystal_morphism({Bp.lowest_weight_vectors()[0]: x})\n sage: psi(Bp.highest_weight_vector())\n [[1, 1], [2]]\n\n We construct a twisted crystal morphism induced from the diagram\n automorphism of type `A_3^{(1)}`::\n\n sage: La = RootSystem([\'A\',3,1]).weight_lattice(extended=True).fundamental_weights()\n sage: B0 = crystals.GeneralizedYoungWalls(3, La[0])\n sage: B1 = crystals.GeneralizedYoungWalls(3, La[1])\n sage: phi = B0.crystal_morphism(B1.module_generators, automorphism={0:1, 1:2, 2:3, 3:0})\n sage: phi\n [\'A\', 3, 1] Twisted Crystal morphism:\n From: Highest weight crystal of generalized Young walls of Cartan type [\'A\', 3, 1] and highest weight Lambda[0]\n To: Highest weight crystal of generalized Young walls of Cartan type [\'A\', 3, 1] and highest weight Lambda[1]\n Defn: [] |--> []\n sage: x = B0.module_generators[0].f_string([0,1,2,3]); x\n [[0, 3], [1], [2]]\n sage: phi(x)\n [[], [1, 0], [2], [3]]\n\n We construct a virtual crystal morphism from type `G_2` into\n type `D_4`::\n\n sage: D = crystals.Tableaux([\'D\',4], shape=[1,1])\n sage: G = crystals.Tableaux([\'G\',2], shape=[1])\n sage: psi = G.crystal_morphism(D.module_generators,\n ....: virtualization={1:[2],2:[1,3,4]},\n ....: scaling_factors={1:1, 2:1})\n sage: for x in G:\n ....: ascii_art(x, psi(x), sep=\' |--> \')\n ....: print("")\n 1\n 1 |--> 2\n <BLANKLINE>\n 1\n 2 |--> 3\n <BLANKLINE>\n 2\n 3 |--> -3\n <BLANKLINE>\n 3\n 0 |--> -3\n <BLANKLINE>\n 3\n -3 |--> -2\n <BLANKLINE>\n -3\n -2 |--> -1\n <BLANKLINE>\n -2\n -1 |--> -1\n ' if (codomain is None): if hasattr(on_gens, 'codomain'): codomain = on_gens.codomain() elif isinstance(on_gens, collections.abc.Sequence): if on_gens: codomain = on_gens[0].parent() elif isinstance(on_gens, collections.abc.Mapping): if on_gens: codomain = next(iter(on_gens.values())).parent() else: for x in self.module_generators: y = on_gens(x) if (y is not None): codomain = y.parent() break if (codomain is None): codomain = self elif (codomain not in Crystals()): raise ValueError('the codomain must be a crystal') homset = Hom(self, codomain, category=category) return homset(on_gens, cartan_type, index_set, generators, automorphism, virtualization, scaling_factors, check) def digraph(self, subset=None, index_set=None): '\n Return the :class:`DiGraph` associated to ``self``.\n\n INPUT:\n\n - ``subset`` -- (optional) a subset of vertices for\n which the digraph should be constructed\n\n - ``index_set`` -- (optional) the index set to draw arrows\n\n EXAMPLES::\n\n sage: C = Crystals().example(5)\n sage: C.digraph()\n Digraph on 6 vertices\n\n The edges of the crystal graph are by default colored using\n blue for edge 1, red for edge 2, and green for edge 3::\n\n sage: C = Crystals().example(3)\n sage: G = C.digraph()\n sage: view(G) # optional - dot2tex graphviz, not tested (opens external window)\n\n One may also overwrite the colors::\n\n sage: C = Crystals().example(3)\n sage: G = C.digraph()\n sage: G.set_latex_options(color_by_label = {1:"red", 2:"purple", 3:"blue"})\n sage: view(G) # optional - dot2tex graphviz, not tested (opens external window)\n\n Or one may add colors to yet unspecified edges::\n\n sage: C = Crystals().example(4)\n sage: G = C.digraph()\n sage: C.cartan_type()._index_set_coloring[4]="purple"\n sage: view(G) # optional - dot2tex graphviz, not tested (opens external window)\n\n Here is an example of how to take the top part up to a\n given depth of an infinite dimensional crystal::\n\n sage: C = CartanType([\'C\',2,1])\n sage: La = C.root_system().weight_lattice().fundamental_weights()\n sage: T = crystals.HighestWeight(La[0])\n sage: S = T.subcrystal(max_depth=3)\n sage: G = T.digraph(subset=S); G\n Digraph on 5 vertices\n sage: G.vertices(sort=True, key=str)\n [(-Lambda[0] + 2*Lambda[1] - delta,),\n (1/2*Lambda[0] + Lambda[1] - Lambda[2] - 1/2*delta, -1/2*Lambda[0] + Lambda[1] - 1/2*delta),\n (1/2*Lambda[0] - Lambda[1] + Lambda[2] - 1/2*delta, -1/2*Lambda[0] + Lambda[1] - 1/2*delta),\n (Lambda[0] - 2*Lambda[1] + 2*Lambda[2] - delta,),\n (Lambda[0],)]\n\n Here is a way to construct a picture of a Demazure crystal using\n the ``subset`` option::\n\n sage: B = crystals.Tableaux([\'A\',2], shape=[2,1])\n sage: t = B.highest_weight_vector()\n sage: D = B.demazure_subcrystal(t, [2,1])\n sage: list(D)\n [[[1, 1], [2]], [[1, 2], [2]], [[1, 1], [3]],\n [[1, 3], [2]], [[1, 3], [3]]]\n sage: view(D) # optional - dot2tex graphviz, not tested (opens external window)\n\n We can also choose to display particular arrows using the\n ``index_set`` option::\n\n sage: C = crystals.KirillovReshetikhin([\'D\',4,1], 2, 1)\n sage: G = C.digraph(index_set=[1,3])\n sage: len(G.edges(sort=False))\n 20\n sage: view(G) # optional - dot2tex graphviz, not tested (opens external window)\n\n TESTS:\n\n We check that infinite crystals raise an error (:trac:`21986`)::\n\n sage: B = crystals.infinity.Tableaux([\'A\',2])\n sage: B.digraph()\n Traceback (most recent call last):\n ...\n NotImplementedError: crystals not known to be finite\n must specify either the subset or depth\n sage: B.digraph(depth=10)\n Digraph on 161 vertices\n\n .. TODO:: Add more tests.\n ' from sage.graphs.digraph import DiGraph d = {} if (subset is None): if (self not in Crystals().Finite()): raise NotImplementedError('crystals not known to be finite must specify the subset') subset = self if (index_set is None): index_set = self.index_set() for x in subset: d[x] = {} for i in index_set: child = x.f(i) if ((child is None) or (child not in subset)): continue d[x][child] = i G = DiGraph(d) from sage.graphs.dot2tex_utils import have_dot2tex if have_dot2tex(): G.set_latex_options(format='dot2tex', edge_labels=True, color_by_label=self.cartan_type()._index_set_coloring) return G def latex_file(self, filename): "\n Export a file, suitable for pdflatex, to ``filename``.\n\n This requires\n a proper installation of ``dot2tex`` in sage-python. For more\n information see the documentation for ``self.latex()``.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A', 5])\n sage: fn = tmp_filename(ext='.tex')\n sage: C.latex_file(fn)\n " header = '\\documentclass{article}\n \\usepackage[x11names, rgb]{xcolor}\n \\usepackage[utf8]{inputenc}\n \\usepackage{tikz}\n \\usetikzlibrary{snakes,arrows,shapes}\n \\usepackage{amsmath}\n \\usepackage[active,tightpage]{preview}\n \\newenvironment{bla}{}{}\n \\PreviewEnvironment{bla}\n\n \\begin{document}\n \\begin{bla}' footer = '\\end{bla}\n \\end{document}' f = open(filename, 'w') f.write(((header + self.latex()) + footer)) f.close() def _latex_(self, **options): '\n Returns the crystal graph as a latex string. This can be exported\n to a file with ``self.latex_file(\'filename\')``.\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux([\'A\',2],shape=[1])\n sage: T._latex_()\n \'...tikzpicture...\'\n sage: view(T) # optional - dot2tex graphviz, not tested (opens external window)\n\n One can for example also color the edges using the following options::\n\n sage: T = crystals.Tableaux([\'A\',2],shape=[1])\n sage: T._latex_(color_by_label={0:"black", 1:"red", 2:"blue"})\n \'...tikzpicture...\'\n ' G = self.digraph() G.set_latex_options(**options) return G._latex_() latex = _latex_ def metapost(self, filename, thicklines=False, labels=True, scaling_factor=1.0, tallness=1.0): "\n Export a file, suitable for MetaPost, to ``filename``.\n\n Root operators `e(1)` or `f(1)` move along red lines, `e(2)` or `f(2)`\n along green. The highest weight is in the lower left. Vertices with\n the same weight are kept close together. The concise labels on the\n nodes are strings introduced by Berenstein and Zelevinsky and\n Littelmann; see Littelmann's paper Cones, Crystals, Patterns,\n sections 5 and 6.\n\n For Cartan types B2 or C2, the pattern has the form\n\n `a_2 a_3 a_4 a_1`\n\n where `c*a_2 = a_3 = 2*a_4 = 0` and `a_1=0`, with `c=2` for B2, `c=1` for C2.\n Applying `e(2)` `a_1` times, `e(1)` `a_2` times, `e(2)` `a_3` times, `e(1)` `a_4` times\n returns to the highest weight. (Observe that Littelmann writes the\n roots in opposite of the usual order, so our `e(1)` is his `e(2)` for\n these Cartan types.) For type A2, the pattern has the form\n\n `a_3 a_2 a_1`\n\n where applying `e(1)` `a_3` times, `e(2)` `a_2` times then `e(1)` `a_1` times\n returns to the highest weight. These data determine the vertex and\n may be translated into a Gelfand-Tsetlin pattern or tableau.\n\n INPUT:\n\n - ``filename`` -- name of the output file, e.g., ``'filename.mp'``\n\n - ``thicklines`` -- (default: ``True``) for thicker edges\n\n - ``labels`` -- (default: False) to suppress labeling of the vertices\n\n - ``scaling_factor`` -- (default: ``1.0``) Increasing or decreasing the\n scaling factor changes the size of the image\n\n - ``tallness`` -- (default: ``1.0``) Increasing makes the image taller\n without increasing the width\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A', 2])\n sage: C.metapost(tmp_filename())\n\n ::\n\n sage: C = crystals.Letters(['A', 5])\n sage: C.metapost(tmp_filename())\n Traceback (most recent call last):\n ...\n NotImplementedError\n " if ((self.cartan_type()[0] == 'B') and (self.cartan_type()[1] == 2)): word = [2, 1, 2, 1] elif ((self.cartan_type()[0] == 'C') and (self.cartan_type()[1] == 2)): word = [2, 1, 2, 1] elif ((self.cartan_type()[0] == 'A') and (self.cartan_type()[1] == 2)): word = [1, 2, 1] else: raise NotImplementedError size = self.cardinality() string_data = [] for i in range(size): turtle = self.list()[i] string_datum = [] for j in word: turtlewalk = 0 while (turtle.e(j) is not None): turtle = turtle.e(j) turtlewalk += 1 string_datum.append(turtlewalk) string_data.append(string_datum) if (self.cartan_type()[0] == 'A'): if labels: c0 = int((55 * scaling_factor)) c1 = int(((- 25) * scaling_factor)) c2 = int(((45 * tallness) * scaling_factor)) c3 = int(((- 12) * scaling_factor)) c4 = int(((- 12) * scaling_factor)) else: c0 = int((45 * scaling_factor)) c1 = int(((- 20) * scaling_factor)) c2 = int(((35 * tallness) * scaling_factor)) c3 = int((12 * scaling_factor)) c4 = int(((- 12) * scaling_factor)) outstring = ('verbatimtex\n\\magnification=600\netex\n\nbeginfig(-1);\nsx:=35; sy:=30;\n\nz1000=(%d,0);\nz1001=(%d,%d);\nz1002=(%d,%d);\nz2001=(-3,3);\nz2002=(3,3);\nz2003=(0,-3);\nz2004=(7,0);\nz2005=(0,7);\nz2006=(-7,0);\nz2007=(0,7);\n\n' % (c0, c1, c2, c3, c4)) elif labels: outstring = ('verbatimtex\n\\magnification=600\netex\n\nbeginfig(-1);\n\nsx := %d;\nsy=%d;\n\nz1000=(2*sx,0);\nz1001=(-sx,sy);\nz1002=(-16,-10);\n\nz2001=(0,-3);\nz2002=(-5,3);\nz2003=(0,3);\nz2004=(5,3);\nz2005=(10,1);\nz2006=(0,10);\nz2007=(-10,1);\nz2008=(0,-8);\n\n' % (int((scaling_factor * 40)), int(((tallness * scaling_factor) * 40)))) else: outstring = ('beginfig(-1);\n\nsx := %d;\nsy := %d;\n\nz1000=(2*sx,0);\nz1001=(-sx,sy);\nz1002=(-5,-5);\n\nz1003=(10,10);\n\n' % (int((scaling_factor * 35)), int(((tallness * scaling_factor) * 35)))) for i in range(size): if (self.cartan_type()[0] == 'A'): [a1, a2, a3] = string_data[i] else: [a1, a2, a3, a4] = string_data[i] shift = 0 for j in range(i): if (self.cartan_type()[0] == 'A'): [b1, b2, b3] = string_data[j] if (((b1 + b3) == (a1 + a3)) and (b2 == a2)): shift += 1 else: [b1, b2, b3, b4] = string_data[j] if (((b1 + b3) == (a1 + a3)) and ((b2 + b4) == (a2 + a4))): shift += 1 if (self.cartan_type()[0] == 'A'): outstring = (outstring + ('z%d=%d*z1000+%d*z1001+%d*z1002;\n' % (i, (a1 + a3), a2, shift))) else: outstring = (outstring + ('z%d=%d*z1000+%d*z1001+%d*z1002;\n' % (i, (a1 + a3), (a2 + a4), shift))) outstring = (outstring + '\n') if thicklines: outstring = (outstring + 'pickup pencircle scaled 2\n\n') for i in range(size): for j in range(1, 3): dest = self.list()[i].f(j) if (dest is not None): dest = self.list().index(dest) if (j == 1): col = 'red;' else: col = 'green; ' if (self.cartan_type()[0] == 'A'): [a1, a2, a3] = string_data[i] outstring = (outstring + ('draw z%d--z%d withcolor %s %% %d %d %d\n' % (i, dest, col, a1, a2, a3))) else: [a1, a2, a3, a4] = string_data[i] outstring = (outstring + ('draw z%d--z%d withcolor %s %% %d %d %d %d\n' % (i, dest, col, a1, a2, a3, a4))) outstring += '\npickup pencircle scaled 3;\n\n' for i in range(self.cardinality()): if labels: if (self.cartan_type()[0] == 'A'): outstring = (outstring + ('pickup pencircle scaled 15;\nfill z%d+z2004..z%d+z2006..z%d+z2006..z%d+z2007..cycle withcolor white;\nlabel(btex %d etex, z%d+z2001);\nlabel(btex %d etex, z%d+z2002);\nlabel(btex %d etex, z%d+z2003);\npickup pencircle scaled .5;\ndraw z%d+z2004..z%d+z2006..z%d+z2006..z%d+z2007..cycle;\n' % (i, i, i, i, string_data[i][2], i, string_data[i][1], i, string_data[i][0], i, i, i, i, i))) else: outstring = (outstring + ('%%%d %d %d %d\npickup pencircle scaled 1;\nfill z%d+z2005..z%d+z2006..z%d+z2007..z%d+z2008..cycle withcolor white;\nlabel(btex %d etex, z%d+z2001);\nlabel(btex %d etex, z%d+z2002);\nlabel(btex %d etex, z%d+z2003);\nlabel(btex %d etex, z%d+z2004);\npickup pencircle scaled .5;\ndraw z%d+z2005..z%d+z2006..z%d+z2007..z%d+z2008..cycle;\n\n' % (string_data[i][0], string_data[i][1], string_data[i][2], string_data[i][3], i, i, i, i, string_data[i][0], i, string_data[i][1], i, string_data[i][2], i, string_data[i][3], i, i, i, i, i))) else: outstring += ('drawdot z%d;\n' % i) outstring += '\nendfig;\n\nend;\n\n' f = open(filename, 'w') f.write(outstring) f.close() def dot_tex(self): '\n Return a dot_tex string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.Letters([\'A\',2])\n sage: C.dot_tex()\n \'digraph G { \\n node [ shape=plaintext ];\\n N_0 [ label = " ", texlbl = "$1$" ];\\n N_1 [ label = " ", texlbl = "$2$" ];\\n N_2 [ label = " ", texlbl = "$3$" ];\\n N_0 -> N_1 [ label = " ", texlbl = "1" ];\\n N_1 -> N_2 [ label = " ", texlbl = "2" ];\\n}\'\n ' import re from sage.combinat import ranker rank = ranker.from_list(self.list())[0] vertex_key = (lambda x: ('N_' + str(rank(x)))) from sage.misc.latex import latex quoted_latex = (lambda x: re.sub('"|\r|(%[^\n]*)?\n', '', latex(x))) result = 'digraph G { \n node [ shape=plaintext ];\n' for x in self: result += ((((' ' + vertex_key(x)) + ' [ label = " ", texlbl = "$') + quoted_latex(x)) + '$" ];\n') for x in self: for i in self.index_set(): child = x.f(i) if (child is None): continue if (i == 0): option = 'dir = back, ' (source, target) = (child, x) else: option = '' (source, target) = (x, child) result += ((((((((' ' + vertex_key(source)) + ' -> ') + vertex_key(target)) + ' [ ') + option) + 'label = " ", texlbl = "') + quoted_latex(i)) + '" ];\n') result += '}' return result def plot(self, **options): "\n Return the plot of ``self`` as a directed graph.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A', 5])\n sage: print(C.plot())\n Graphics object consisting of 17 graphics primitives\n " return self.digraph().plot(edge_labels=True, vertex_size=0, **options) def plot3d(self, **options): "\n Return the 3-dimensional plot of ``self`` as a directed graph.\n\n EXAMPLES::\n\n sage: C = crystals.KirillovReshetikhin(['A',3,1],2,1)\n sage: print(C.plot3d())\n Graphics3d Object\n " G = self.digraph(**options) return G.plot3d() def tensor(self, *crystals, **options): "\n Return the tensor product of ``self`` with the crystals ``B``.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A', 3])\n sage: B = crystals.infinity.Tableaux(['A', 3])\n sage: T = C.tensor(C, B); T\n Full tensor product of the crystals\n [The crystal of letters for type ['A', 3],\n The crystal of letters for type ['A', 3],\n The infinity crystal of tableaux of type ['A', 3]]\n sage: tensor([C, C, B]) is T\n True\n\n sage: C = crystals.Letters(['A',2])\n sage: T = C.tensor(C, C, generators=[[C(2),C(1),C(1)],[C(1),C(2),C(1)]]); T\n The tensor product of the crystals\n [The crystal of letters for type ['A', 2],\n The crystal of letters for type ['A', 2],\n The crystal of letters for type ['A', 2]]\n sage: T.module_generators\n ([2, 1, 1], [1, 2, 1])\n " from sage.combinat.crystals.tensor_product import TensorProductOfCrystals return TensorProductOfCrystals(self, *crystals, **options) def direct_sum(self, X): "\n Return the direct sum of ``self`` with ``X``.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: C = crystals.Letters(['A',2])\n sage: B.direct_sum(C)\n Direct sum of the crystals Family\n (The crystal of tableaux of type ['A', 2] and shape(s) [[2, 1]],\n The crystal of letters for type ['A', 2])\n\n As a shorthand, we can use ``+``::\n\n sage: B + C\n Direct sum of the crystals Family\n (The crystal of tableaux of type ['A', 2] and shape(s) [[2, 1]],\n The crystal of letters for type ['A', 2])\n " if (X not in Crystals()): raise ValueError('{} is not a crystal'.format(X)) from sage.combinat.crystals.direct_sum import DirectSumOfCrystals return DirectSumOfCrystals([self, X]) __add__ = direct_sum @abstract_method(optional=True) def connected_components_generators(self): "\n Return a tuple of generators for each of the connected components\n of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: C = crystals.Letters(['A',2])\n sage: T = crystals.TensorProduct(B,C)\n sage: T.connected_components_generators()\n ([[[1, 1], [2]], 1], [[[1, 2], [2]], 1], [[[1, 2], [3]], 1])\n " def connected_components(self): "\n Return the connected components of ``self`` as subcrystals.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: C = crystals.Letters(['A',2])\n sage: T = crystals.TensorProduct(B,C)\n sage: T.connected_components()\n [Subcrystal of Full tensor product of the crystals\n [The crystal of tableaux of type ['A', 2] and shape(s) [[2, 1]],\n The crystal of letters for type ['A', 2]],\n Subcrystal of Full tensor product of the crystals\n [The crystal of tableaux of type ['A', 2] and shape(s) [[2, 1]],\n The crystal of letters for type ['A', 2]],\n Subcrystal of Full tensor product of the crystals\n [The crystal of tableaux of type ['A', 2] and shape(s) [[2, 1]],\n The crystal of letters for type ['A', 2]]]\n " return [self.subcrystal(generators=[mg]) for mg in self.connected_components_generators()] def number_of_connected_components(self): "\n Return the number of connected components of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: C = crystals.Letters(['A',2])\n sage: T = crystals.TensorProduct(B,C)\n sage: T.number_of_connected_components()\n 3\n " return len(self.connected_components_generators()) def is_connected(self): "\n Return ``True`` if ``self`` is a connected crystal.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: C = crystals.Letters(['A',2])\n sage: T = crystals.TensorProduct(B,C)\n sage: B.is_connected()\n True\n sage: T.is_connected()\n False\n " return (self.number_of_connected_components() == 1) class ElementMethods(): @cached_method def index_set(self): "\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C(1).index_set()\n (1, 2, 3, 4, 5)\n " return self.parent().index_set() def cartan_type(self): "\n Returns the Cartan type associated to ``self``\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A', 5])\n sage: C(1).cartan_type()\n ['A', 5]\n " return self.parent().cartan_type() @abstract_method def e(self, i): '\n Return `e_i` of ``self`` if it exists or ``None`` otherwise.\n\n This method should be implemented by the element class of\n the crystal.\n\n EXAMPLES::\n\n sage: C = Crystals().example(5)\n sage: x = C[2]; x\n 3\n sage: x.e(1), x.e(2), x.e(3)\n (None, 2, None)\n ' @abstract_method def f(self, i): '\n Return `f_i` of ``self`` if it exists or ``None`` otherwise.\n\n This method should be implemented by the element class of\n the crystal.\n\n EXAMPLES::\n\n sage: C = Crystals().example(5)\n sage: x = C[1]; x\n 2\n sage: x.f(1), x.f(2), x.f(3)\n (None, 3, None)\n ' @abstract_method def epsilon(self, i): "\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C(1).epsilon(1)\n 0\n sage: C(2).epsilon(1)\n 1\n " @abstract_method def phi(self, i): "\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C(1).phi(1)\n 1\n sage: C(2).phi(1)\n 0\n " @abstract_method def weight(self): "\n Return the weight of this crystal element.\n\n This method should be implemented by the element class of\n the crystal.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C(1).weight()\n (1, 0, 0, 0, 0, 0)\n " def phi_minus_epsilon(self, i): "\n Return `\\varphi_i - \\varepsilon_i` of ``self``.\n\n There are sometimes better implementations using the\n weight for this. It is used for reflections along a string.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C(1).phi_minus_epsilon(1)\n 1\n " return (self.phi(i) - self.epsilon(i)) def Epsilon(self): "\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C(0).Epsilon()\n (0, 0, 0, 0, 0, 0)\n sage: C(1).Epsilon()\n (0, 0, 0, 0, 0, 0)\n sage: C(2).Epsilon()\n (1, 0, 0, 0, 0, 0)\n " Lambda = self.parent().Lambda() return sum(((self.epsilon(i) * Lambda[i]) for i in self.index_set())) def Phi(self): "\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C(0).Phi()\n (0, 0, 0, 0, 0, 0)\n sage: C(1).Phi()\n (1, 0, 0, 0, 0, 0)\n sage: C(2).Phi()\n (1, 1, 0, 0, 0, 0)\n " Lambda = self.parent().Lambda() return sum(((self.phi(i) * Lambda[i]) for i in self.index_set())) def f_string(self, list): "\n Applies `f_{i_r} \\cdots f_{i_1}` to ``self`` for ``list`` as\n `[i_1, ..., i_r]`\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',3])\n sage: b = C(1)\n sage: b.f_string([1,2])\n 3\n sage: b.f_string([2,1])\n " b = self for i in list: b = b.f(i) if (b is None): return None return b def e_string(self, list): "\n Applies `e_{i_r} \\cdots e_{i_1}` to ``self`` for ``list`` as\n `[i_1, ..., i_r]`\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',3])\n sage: b = C(3)\n sage: b.e_string([2,1])\n 1\n sage: b.e_string([1,2])\n " b = self for i in list: b = b.e(i) if (b is None): return None return b def s(self, i): "\n Return the reflection of ``self`` along its `i`-string.\n\n EXAMPLES::\n\n sage: C = crystals.Tableaux(['A',2], shape=[2,1])\n sage: b = C(rows=[[1,1],[3]])\n sage: b.s(1)\n [[2, 2], [3]]\n sage: b = C(rows=[[1,2],[3]])\n sage: b.s(2)\n [[1, 2], [3]]\n sage: T = crystals.Tableaux(['A',2],shape=[4])\n sage: t = T(rows=[[1,2,2,2]])\n sage: t.s(1)\n [[1, 1, 1, 2]]\n " d = self.phi_minus_epsilon(i) b = self if (d > 0): for j in range(d): b = b.f(i) else: for j in range((- d)): b = b.e(i) return b def is_highest_weight(self, index_set=None): "\n Return ``True`` if ``self`` is a highest weight.\n\n Specifying the option ``index_set`` to be a subset `I` of the\n index set of the underlying crystal, finds all highest\n weight vectors for arrows in `I`.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C(1).is_highest_weight()\n True\n sage: C(2).is_highest_weight()\n False\n sage: C(2).is_highest_weight(index_set = [2,3,4,5])\n True\n " if (index_set is None): index_set = self.index_set() return all(((self.e(i) is None) for i in index_set)) def is_lowest_weight(self, index_set=None): "\n Returns ``True`` if ``self`` is a lowest weight.\n Specifying the option ``index_set`` to be a subset `I` of the\n index set of the underlying crystal, finds all lowest\n weight vectors for arrows in `I`.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C(1).is_lowest_weight()\n False\n sage: C(6).is_lowest_weight()\n True\n sage: C(4).is_lowest_weight(index_set = [1,3])\n True\n " if (index_set is None): index_set = self.index_set() return all(((self.f(i) is None) for i in index_set)) def to_highest_weight(self, index_set=None): "\n Return the highest weight element `u` and a list `[i_1,...,i_k]`\n such that ``self`` `= f_{i_1} ... f_{i_k} u`, where `i_1,...,i_k` are\n elements in ``index_set``.\n\n By default the ``index_set`` is assumed to be\n the full index set of ``self``.\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',3], shape = [1])\n sage: t = T(rows = [[3]])\n sage: t.to_highest_weight()\n [[[1]], [2, 1]]\n sage: T = crystals.Tableaux(['A',3], shape = [2,1])\n sage: t = T(rows = [[1,2],[4]])\n sage: t.to_highest_weight()\n [[[1, 1], [2]], [1, 3, 2]]\n sage: t.to_highest_weight(index_set = [3])\n [[[1, 2], [3]], [3]]\n sage: K = crystals.KirillovReshetikhin(['A',3,1],2,1)\n sage: t = K(rows=[[2],[3]]); t.to_highest_weight(index_set=[1])\n [[[1], [3]], [1]]\n sage: t.to_highest_weight()\n Traceback (most recent call last):\n ...\n ValueError: this is not a highest weight crystal\n " from sage.categories.highest_weight_crystals import HighestWeightCrystals if (index_set is None): if (HighestWeightCrystals() not in self.parent().categories()): raise ValueError('this is not a highest weight crystal') index_set = self.index_set() for i in index_set: next = self.e(i) if (next is not None): hw = next.to_highest_weight(index_set=index_set) return [hw[0], ([i] + hw[1])] return [self, []] def to_lowest_weight(self, index_set=None): "\n Return the lowest weight element `u` and a list `[i_1,...,i_k]`\n such that ``self`` `= e_{i_1} ... e_{i_k} u`, where `i_1,...,i_k` are\n elements in ``index_set``.\n\n By default the ``index_set`` is assumed to be the full index\n set of ``self``.\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',3], shape = [1])\n sage: t = T(rows = [[3]])\n sage: t.to_lowest_weight()\n [[[4]], [3]]\n sage: T = crystals.Tableaux(['A',3], shape = [2,1])\n sage: t = T(rows = [[1,2],[4]])\n sage: t.to_lowest_weight()\n [[[3, 4], [4]], [1, 2, 2, 3]]\n sage: t.to_lowest_weight(index_set = [3])\n [[[1, 2], [4]], []]\n sage: K = crystals.KirillovReshetikhin(['A',3,1],2,1)\n sage: t = K.module_generator(); t\n [[1], [2]]\n sage: t.to_lowest_weight(index_set=[1,2,3])\n [[[3], [4]], [2, 1, 3, 2]]\n sage: t.to_lowest_weight()\n Traceback (most recent call last):\n ...\n ValueError: this is not a highest weight crystal\n " from sage.categories.highest_weight_crystals import HighestWeightCrystals if (index_set is None): if (HighestWeightCrystals() not in self.parent().categories()): raise ValueError('this is not a highest weight crystal') index_set = self.index_set() for i in index_set: next = self.f(i) if (next is not None): lw = next.to_lowest_weight(index_set=index_set) return [lw[0], ([i] + lw[1])] return [self, []] def all_paths_to_highest_weight(self, index_set=None): '\n Iterate over all paths to the highest weight from ``self``\n with respect to ``index_set``.\n\n INPUT:\n\n - ``index_set`` -- (optional) a subset of the index set of ``self``\n\n EXAMPLES::\n\n sage: B = crystals.infinity.Tableaux("A2")\n sage: b0 = B.highest_weight_vector()\n sage: b = b0.f_string([1, 2, 1, 2])\n sage: L = b.all_paths_to_highest_weight()\n sage: list(L)\n [[2, 1, 2, 1], [2, 2, 1, 1]]\n\n sage: Y = crystals.infinity.GeneralizedYoungWalls(3)\n sage: y0 = Y.highest_weight_vector()\n sage: y = y0.f_string([0, 1, 2, 3, 2, 1, 0])\n sage: list(y.all_paths_to_highest_weight())\n [[0, 1, 2, 3, 2, 1, 0],\n [0, 1, 3, 2, 2, 1, 0],\n [0, 3, 1, 2, 2, 1, 0],\n [0, 3, 2, 1, 1, 0, 2],\n [0, 3, 2, 1, 1, 2, 0]]\n\n sage: B = crystals.Tableaux("A3", shape=[4,2,1])\n sage: b0 = B.highest_weight_vector()\n sage: b = b0.f_string([1, 1, 2, 3])\n sage: list(b.all_paths_to_highest_weight())\n [[1, 3, 2, 1], [3, 1, 2, 1], [3, 2, 1, 1]]\n ' if (index_set is None): index_set = self.index_set() hw = True for i in index_set: next = self.e(i) if (next is not None): for x in next.all_paths_to_highest_weight(index_set): (yield ([i] + x)) hw = False if hw: (yield []) def subcrystal(self, index_set=None, max_depth=float('inf'), direction='both', contained=None, cartan_type=None, category=None): "\n Construct the subcrystal generated by ``self`` using `e_i` and/or\n `f_i` for all `i` in ``index_set``.\n\n INPUT:\n\n - ``index_set`` -- (default: ``None``) the index set; if ``None``\n then use the index set of the crystal\n\n - ``max_depth`` -- (default: infinity) the maximum depth to build\n\n - ``direction`` -- (default: ``'both'``) the direction to build\n the subcrystal; it can be one of the following:\n\n - ``'both'`` - using both `e_i` and `f_i`\n - ``'upper'`` - using `e_i`\n - ``'lower'`` - using `f_i`\n\n - ``contained`` -- (optional) a set (or function) defining the\n containment in the subcrystal\n\n - ``cartan_type`` -- (optional) specify the Cartan type of the\n subcrystal\n\n - ``category`` -- (optional) specify the category of the subcrystal\n\n .. SEEALSO::\n\n - :meth:`Crystals.ParentMethods.subcrystal()`\n\n EXAMPLES::\n\n sage: C = crystals.KirillovReshetikhin(['A',3,1], 1, 2)\n sage: elt = C(1,4)\n sage: list(elt.subcrystal(index_set=[1,3]))\n [[[1, 4]], [[2, 4]], [[1, 3]], [[2, 3]]]\n sage: list(elt.subcrystal(index_set=[1,3], max_depth=1))\n [[[1, 4]], [[2, 4]], [[1, 3]]]\n sage: list(elt.subcrystal(index_set=[1,3], direction='upper'))\n [[[1, 4]], [[1, 3]]]\n sage: list(elt.subcrystal(index_set=[1,3], direction='lower'))\n [[[1, 4]], [[2, 4]]]\n\n TESTS:\n\n Check that :trac:`23942` is fixed::\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1], 1,1)\n sage: cat = HighestWeightCrystals().Finite()\n sage: S = K.module_generator().subcrystal(index_set=[1,2], category=cat)\n sage: S.category()\n Category of finite highest weight crystals\n " return self.parent().subcrystal(generators=[self], index_set=index_set, max_depth=max_depth, direction=direction, category=category) def tensor(self, *elts): "\n Return the tensor product of ``self`` with the crystal\n elements ``elts``.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A', 3])\n sage: B = crystals.infinity.Tableaux(['A', 3])\n sage: c = C[0]\n sage: b = B.highest_weight_vector()\n sage: t = c.tensor(c, b)\n sage: ascii_art(t)\n 1 1 1\n 1 # 1 # 2 2\n 3\n sage: tensor([c, c, b]) == t\n True\n sage: ascii_art(tensor([b, b, c]))\n 1 1 1 1 1 1\n 2 2 # 2 2 # 1\n 3 3\n " T = self.parent().tensor(*[b.parent() for b in elts]) return T(self, *elts) class SubcategoryMethods(): '\n Methods for all subcategories.\n ' def TensorProducts(self): '\n Return the full subcategory of objects of ``self`` constructed\n as tensor products.\n\n .. SEEALSO::\n\n - :class:`.tensor.TensorProductsCategory`\n - :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction`.\n\n EXAMPLES::\n\n sage: HighestWeightCrystals().TensorProducts()\n Category of tensor products of highest weight crystals\n ' return TensorProductsCategory.category_of(self) class TensorProducts(TensorProductsCategory): '\n The category of crystals constructed by tensor product of crystals.\n ' @cached_method def extra_super_categories(self): '\n EXAMPLES::\n\n sage: Crystals().TensorProducts().extra_super_categories()\n [Category of crystals]\n ' return [self.base_category()] Finite = LazyImport('sage.categories.finite_crystals', 'FiniteCrystals')
class CrystalMorphism(Morphism): '\n A crystal morphism.\n\n INPUT:\n\n - ``parent`` -- a homset\n - ``cartan_type`` -- (optional) a Cartan type; the default is the\n Cartan type of the domain\n - ``virtualization`` -- (optional) a dictionary whose keys are in\n the index set of the domain and whose values are lists of entries\n in the index set of the codomain\n - ``scaling_factors`` -- (optional) a dictionary whose keys are in\n the index set of the domain and whose values are scaling factors\n for the weight, `\\varepsilon` and `\\varphi`\n ' def __init__(self, parent, cartan_type=None, virtualization=None, scaling_factors=None): "\n Initialize ``self``.\n\n TESTS::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: H = Hom(B, B)\n sage: psi = H.an_element()\n " if (cartan_type is None): cartan_type = parent.domain().cartan_type() self._cartan_type = cartan_type index_set = cartan_type.index_set() if (scaling_factors is None): scaling_factors = {i: 1 for i in index_set} if (virtualization is None): virtualization = {i: (i,) for i in index_set} elif (not isinstance(virtualization, collections.abc.Mapping)): try: virtualization = dict(virtualization) except (TypeError, ValueError): virtualization = {i: (virtualization(i),) for i in index_set} from sage.sets.family import Family self._virtualization = Family(virtualization) self._scaling_factors = Family(scaling_factors) Morphism.__init__(self, parent) def _repr_type(self): '\n Used internally in printing this morphism.\n\n TESTS::\n\n sage: B = crystals.Tableaux([\'A\',2], shape=[2,1])\n sage: H = Hom(B, B)\n sage: psi = H.an_element()\n sage: psi._repr_type()\n "[\'A\', 2] Crystal"\n\n sage: psi = H(lambda x: None, index_set=[1])\n sage: psi._repr_type()\n "[\'A\', 1] -> [\'A\', 2] Virtual Crystal"\n\n sage: B = crystals.Tableaux([\'A\',3], shape=[1])\n sage: BT = crystals.Tableaux([\'A\',3], shape=[1,1,1])\n sage: psi = B.crystal_morphism(BT.module_generators, automorphism={1:3, 2:2, 3:1})\n sage: psi._repr_type()\n "[\'A\', 3] Twisted Crystal"\n\n sage: KD = crystals.KirillovReshetikhin([\'D\',3,1], 2,1)\n sage: KA = crystals.KirillovReshetikhin([\'A\',3,1], 2,1)\n sage: psi = KD.crystal_morphism(KA.module_generators)\n sage: psi._repr_type()\n "[\'D\', 3, 1] -> [\'A\', 3, 1] Virtual Crystal"\n ' if (self.codomain().cartan_type() != self._cartan_type): return '{} -> {} Virtual Crystal'.format(self._cartan_type, self.codomain().cartan_type()) if any(((self._virtualization[i] != (i,)) for i in self._cartan_type.index_set())): return '{} Twisted Crystal'.format(self._cartan_type) return '{} Crystal'.format(self._cartan_type) def cartan_type(self): "\n Return the Cartan type of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: psi = Hom(B, B).an_element()\n sage: psi.cartan_type()\n ['A', 2]\n " return self._cartan_type def is_injective(self): "\n Return if ``self`` is an injective crystal morphism.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: psi = Hom(B, B).an_element()\n sage: psi.is_injective()\n False\n " return self.is_embedding() @cached_method def is_surjective(self): "\n Check if ``self`` is a surjective crystal morphism.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['C',2], shape=[1,1])\n sage: C = crystals.Tableaux(['C',2], ([2,1], [1,1]))\n sage: psi = B.crystal_morphism(C.module_generators[1:], codomain=C)\n sage: psi.is_surjective()\n False\n sage: im_gens = [None, B.module_generators[0]]\n sage: psi = C.crystal_morphism(im_gens, codomain=B)\n sage: psi.is_surjective()\n True\n\n sage: C = crystals.Tableaux(['A',2], shape=[2,1])\n sage: B = crystals.infinity.Tableaux(['A',2])\n sage: La = RootSystem(['A',2]).weight_lattice().fundamental_weights()\n sage: W = crystals.elementary.T(['A',2], La[1]+La[2])\n sage: T = W.tensor(B)\n sage: mg = T(W.module_generators[0], B.module_generators[0])\n sage: psi = Hom(C,T)([mg])\n sage: psi.is_surjective()\n False\n " if (self.domain().cardinality() == float('inf')): raise NotImplementedError('unable to determine if surjective') if (self.domain().cardinality() < self.codomain().cardinality()): return False S = set(self.codomain()) for x in self.domain(): S.discard(self(x)) if (not S): return True return False def __call__(self, x, *args, **kwds): "\n Apply this map to ``x``. We need to do special processing\n for ``None``.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: F = crystals.Tableaux(['A',2], shape=[1])\n sage: T = crystals.TensorProduct(F, F, F)\n sage: H = Hom(T, B)\n sage: b = B.module_generators[0]\n sage: psi = H((None, b, b, None), generators=T.highest_weight_vectors())\n sage: psi(None)\n sage: [psi(v) for v in T.highest_weight_vectors()]\n [None, [[1, 1], [2]], [[1, 1], [2]], None]\n " if (x is None): return None return super().__call__(x, *args, **kwds) def virtualization(self): "\n Return the virtualization sets `\\sigma_i`.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['B',3], shape=[1])\n sage: C = crystals.Tableaux(['D',4], shape=[2])\n sage: psi = B.crystal_morphism(C.module_generators)\n sage: psi.virtualization()\n Finite family {1: (1,), 2: (2,), 3: (3, 4)}\n " return self._virtualization def scaling_factors(self): "\n Return the scaling factors `\\gamma_i`.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['B',3], shape=[1])\n sage: C = crystals.Tableaux(['D',4], shape=[2])\n sage: psi = B.crystal_morphism(C.module_generators)\n sage: psi.scaling_factors()\n Finite family {1: 2, 2: 2, 3: 1}\n " return self._scaling_factors
class CrystalMorphismByGenerators(CrystalMorphism): '\n A crystal morphism defined by a set of generators which create a virtual\n crystal inside the codomain.\n\n INPUT:\n\n - ``parent`` -- a homset\n - ``on_gens`` -- a function or list that determines the image of the\n generators (if given a list, then this uses the order of the\n generators of the domain) of the domain under ``self``\n - ``cartan_type`` -- (optional) a Cartan type; the default is the\n Cartan type of the domain\n - ``virtualization`` -- (optional) a dictionary whose keys are in\n the index set of the domain and whose values are lists of entries\n in the index set of the codomain\n - ``scaling_factors`` -- (optional) a dictionary whose keys are in\n the index set of the domain and whose values are scaling factors\n for the weight, `\\varepsilon` and `\\varphi`\n - ``gens`` -- (optional) a finite list of generators to define the\n morphism; the default is to use the highest weight vectors of the crystal\n - ``check`` -- (default: ``True``) check if the crystal morphism is valid\n\n .. SEEALSO::\n\n :meth:`sage.categories.crystals.Crystals.ParentMethods.crystal_morphism`\n ' def __init__(self, parent, on_gens, cartan_type=None, virtualization=None, scaling_factors=None, gens=None, check=True): "\n Construct a virtual crystal morphism.\n\n TESTS::\n\n sage: B = crystals.Tableaux(['D',4], shape=[1])\n sage: H = Hom(B, B)\n sage: d = {1:1, 2:2, 3:4, 4:3}\n sage: psi = H(B.module_generators, automorphism=d)\n\n sage: B = crystals.Tableaux(['B',3], shape=[1])\n sage: C = crystals.Tableaux(['D',4], shape=[2])\n sage: H = Hom(B, C)\n sage: psi = H(C.module_generators)\n " CrystalMorphism.__init__(self, parent, cartan_type, virtualization, scaling_factors) if (gens is None): if isinstance(on_gens, collections.abc.Mapping): gens = on_gens.keys() else: gens = parent.domain().module_generators self._gens = tuple(gens) if isinstance(on_gens, collections.abc.Mapping): f = (lambda x: on_gens[x]) elif isinstance(on_gens, collections.abc.Sequence): if (len(self._gens) != len(on_gens)): raise ValueError('invalid generator images') d = dict(zip(self._gens, on_gens)) f = (lambda x: d[x]) else: f = on_gens self._on_gens = f self._path_mg_cache = {x: (x, [], []) for x in self._gens} if check: self._check() def _repr_defn(self): "\n Used in constructing string representation of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: F = crystals.Tableaux(['A',2], shape=[1])\n sage: T = crystals.TensorProduct(F, F, F)\n sage: H = Hom(T, B)\n sage: b = B.highest_weight_vector()\n sage: psi = H((None, b, b, None), generators=T.highest_weight_vectors())\n sage: print(psi._repr_defn())\n [[[1]], [[1]], [[1]]] |--> None\n [[[2]], [[1]], [[1]]] |--> [[1, 1], [2]]\n [[[1]], [[2]], [[1]]] |--> [[1, 1], [2]]\n [[[3]], [[2]], [[1]]] |--> None\n " return '\n'.join(('{} |--> {}'.format(mg, im) for (mg, im) in zip(self._gens, self.im_gens()))) def _check(self): "\n Check if ``self`` is a valid virtual crystal morphism.\n\n TESTS::\n\n sage: B = crystals.Tableaux(['D',4], shape=[1])\n sage: H = Hom(B, B)\n sage: d = {1:1, 2:2, 3:4, 4:3}\n sage: psi = H(B.module_generators, automorphism=d) # indirect doctest\n\n sage: B = crystals.Tableaux(['B',3], shape=[1])\n sage: C = crystals.Tableaux(['D',4], shape=[2])\n sage: H = Hom(B, C)\n sage: psi = H(C.module_generators) # indirect doctest\n " index_set = self._cartan_type.index_set() acx = self.domain().weight_lattice_realization().simple_coroots() acy = self.codomain().weight_lattice_realization().simple_coroots() v = self._virtualization sf = self._scaling_factors for x in self._gens: y = self._on_gens(x) if (y is None): continue xwt = x.weight() ywt = y.weight() for i in index_set: ind = v[i] if any((((sf[i] * xwt.scalar(acx[i])) != ywt.scalar(acy[j])) for j in ind)): raise ValueError('invalid crystal morphism: weights do not match') if any((((sf[i] * x.epsilon(i)) != y.epsilon(j)) for j in ind)): raise ValueError('invalid crystal morphism: epsilons are not aligned') if any((((sf[i] * x.phi(i)) != y.phi(j)) for j in ind)): raise ValueError('invalid crystal morphism: phis are not aligned') def _call_(self, x): "\n Return the image of ``x`` under ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: H = Hom(B, B)\n sage: psi = H(B.module_generators)\n sage: psi(B.highest_weight_vector())\n [[1, 1], [2]]\n\n sage: B = crystals.Tableaux(['D',4], shape=[1])\n sage: H = Hom(B, B)\n sage: d = {1:1, 2:2, 3:4, 4:3}\n sage: psi = H(B.module_generators, automorphism=d)\n sage: b = B.highest_weight_vector()\n sage: psi(b.f_string([1,2,3]))\n [[-4]]\n sage: psi(b.f_string([1,2,4]))\n [[4]]\n\n sage: B = crystals.Tableaux(['B',3], shape=[1])\n sage: C = crystals.Tableaux(['D',4], shape=[2])\n sage: H = Hom(B, C)\n sage: psi = H(C.module_generators)\n sage: psi(B.highest_weight_vector())\n [[1, 1]]\n " (mg, ef, indices) = self.to_module_generator(x) cur = self._on_gens(mg) for (op, i) in reversed(list(zip(ef, indices))): if (cur is None): return None s = [] sf = self._scaling_factors[i] for j in self._virtualization[i]: s += ([j] * sf) if (op == 'e'): cur = cur.f_string(s) elif (op == 'f'): cur = cur.e_string(s) return cur def __bool__(self) -> bool: "\n Return if ``self`` is a non-zero morphism.\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['A',2], 2)\n sage: H = Hom(B, B)\n sage: psi = H(B.module_generators)\n sage: bool(psi)\n True\n sage: psi = H(lambda x: None)\n sage: bool(psi)\n False\n " return any(((self._on_gens(mg) is not None) for mg in self._gens)) def to_module_generator(self, x): "\n Return a generator ``mg`` and a path of `e_i` and `f_i` operations\n to ``mg``.\n\n OUTPUT:\n\n A tuple consisting of:\n\n - a module generator,\n - a list of ``'e'`` and ``'f'`` to denote which operation, and\n - a list of matching indices.\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['A',2], 2)\n sage: psi = B.crystal_morphism(B.module_generators)\n sage: psi.to_module_generator(B(4))\n (0, ['f', 'f', 'f', 'f'], [2, 2, 2, 2])\n sage: psi.to_module_generator(B(-2))\n (0, ['e', 'e'], [2, 2])\n " if (x in self._path_mg_cache): return self._path_mg_cache[x] mg = set(self._path_mg_cache.keys()) visited = {None, x} index_set = self._cartan_type.index_set() todo = [x] ef = [[]] indices = [[]] while todo: cur = todo.pop(0) cur_ef = ef.pop(0) cur_indices = indices.pop(0) for i in index_set: next = cur.e(i) if (next in mg): (gen, ef, indices) = self._path_mg_cache[next] ef = ((cur_ef + ['e']) + ef) indices = ((cur_indices + [i]) + indices) self._path_mg_cache[x] = (gen, ef, indices) return (gen, ef, indices) if (next not in visited): todo.append(next) ef.append((cur_ef + ['e'])) indices.append((cur_indices + [i])) visited.add(next) next = cur.f(i) if (next in mg): (gen, ef, indices) = self._path_mg_cache[next] ef = ((cur_ef + ['f']) + ef) indices = ((cur_indices + [i]) + indices) self._path_mg_cache[x] = (gen, ef, indices) return (gen, ef, indices) if (next not in visited): todo.append(next) ef.append((cur_ef + ['f'])) indices.append((cur_indices + [i])) visited.add(next) raise ValueError('no module generator in the component of {}'.format(x)) @cached_method def im_gens(self): "\n Return the image of the generators of ``self`` as a tuple.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: F = crystals.Tableaux(['A',2], shape=[1])\n sage: T = crystals.TensorProduct(F, F, F)\n sage: H = Hom(T, B)\n sage: b = B.highest_weight_vector()\n sage: psi = H((None, b, b, None), generators=T.highest_weight_vectors())\n sage: psi.im_gens()\n (None, [[1, 1], [2]], [[1, 1], [2]], None)\n " return tuple([self._on_gens(g) for g in self._gens]) def image(self): "\n Return the image of ``self`` in the codomain as a\n :class:`~sage.combinat.crystals.subcrystal.Subcrystal`.\n\n .. WARNING::\n\n This assumes that ``self`` is a strict crystal morphism.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['B',3], shape=[1])\n sage: C = crystals.Tableaux(['D',4], shape=[2])\n sage: H = Hom(B, C)\n sage: psi = H(C.module_generators)\n sage: psi.image()\n Virtual crystal of The crystal of tableaux of type ['D', 4] and shape(s) [[2]] of type ['B', 3]\n " from sage.combinat.crystals.subcrystal import Subcrystal return Subcrystal(self.codomain(), virtualization=self._virtualization, scaling_factors=self._scaling_factors, generators=self.im_gens(), cartan_type=self._cartan_type, index_set=self._cartan_type.index_set(), category=self.domain().category())
class CrystalHomset(Homset): '\n The set of crystal morphisms from one crystal to another.\n\n An `U_q(\\mathfrak{g})` `I`-crystal morphism `\\Psi : B \\to C` is a map\n `\\Psi : B \\cup \\{ 0 \\} \\to C \\cup \\{ 0 \\}` such that:\n\n - `\\Psi(0) = 0`.\n - If `b \\in B` and `\\Psi(b) \\in C`, then\n `\\mathrm{wt}(\\Psi(b)) = \\mathrm{wt}(b)`,\n `\\varepsilon_i(\\Psi(b)) = \\varepsilon_i(b)`, and\n `\\varphi_i(\\Psi(b)) = \\varphi_i(b)` for all `i \\in I`.\n - If `b, b^{\\prime} \\in B`, `\\Psi(b), \\Psi(b^{\\prime}) \\in C` and\n `f_i b = b^{\\prime}`, then `f_i \\Psi(b) = \\Psi(b^{\\prime})` and\n `\\Psi(b) = e_i \\Psi(b^{\\prime})` for all `i \\in I`.\n\n If the Cartan type is unambiguous, it is suppressed from the notation.\n\n We can also generalize the definition of a crystal morphism by considering\n a map of `\\sigma` of the (now possibly different) Dynkin diagrams\n corresponding to `B` and `C` along with scaling factors\n `\\gamma_i \\in \\ZZ` for `i \\in I`. Let `\\sigma_i` denote the orbit of\n `i` under `\\sigma`. We write objects for `B` as `X` with\n corresponding objects of `C` as `\\widehat{X}`.\n Then a *virtual* crystal morphism `\\Psi` is a map such that\n the following holds:\n\n - `\\Psi(0) = 0`.\n - If `b \\in B` and `\\Psi(b) \\in C`, then for all `j \\in \\sigma_i`:\n\n .. MATH::\n\n \\varepsilon_i(b) = \\frac{1}{\\gamma_j} \\widehat{\\varepsilon}_j(\\Psi(b)),\n \\quad \\varphi_i(b) = \\frac{1}{\\gamma_j} \\widehat{\\varphi}_j(\\Psi(b)),\n \\quad \\mathrm{wt}(\\Psi(b)) = \\sum_i c_i \\sum_{j \\in \\sigma_i} \\gamma_j\n \\widehat{\\Lambda}_j,\n\n where `\\mathrm{wt}(b) = \\sum_i c_i \\Lambda_i`.\n\n - If `b, b^{\\prime} \\in B`, `\\Psi(b), \\Psi(b^{\\prime}) \\in C` and\n `f_i b = b^{\\prime}`, then independent of the ordering of `\\sigma_i`\n we have:\n\n .. MATH::\n\n \\Psi(b^{\\prime}) = e_i \\Psi(b) =\n \\prod_{j \\in \\sigma_i} \\widehat{e}_j^{\\gamma_i} \\Psi(b), \\quad\n \\Psi(b^{\\prime}) = f_i \\Psi(b) =\n \\prod_{j \\in \\sigma_i} \\widehat{f}_j^{\\gamma_i} \\Psi(b).\n\n If `\\gamma_i = 1` for all `i \\in I` and the Dynkin diagrams are\n the same, then we call `\\Psi` a *twisted* crystal morphism.\n\n INPUT:\n\n - ``X`` -- the domain\n - ``Y`` -- the codomain\n - ``category`` -- (optional) the category of the crystal morphisms\n\n .. SEEALSO::\n\n For the construction of an element of the homset, see\n :class:`CrystalMorphismByGenerators` and\n :meth:`~sage.categories.crystals.Crystals.ParentMethods.crystal_morphism`.\n\n EXAMPLES:\n\n We begin with the natural embedding of `B(2\\Lambda_1)` into\n `B(\\Lambda_1) \\otimes B(\\Lambda_1)` in type `A_1`::\n\n sage: B = crystals.Tableaux([\'A\',1], shape=[2])\n sage: F = crystals.Tableaux([\'A\',1], shape=[1])\n sage: T = crystals.TensorProduct(F, F)\n sage: v = T.highest_weight_vectors()[0]; v\n [[[1]], [[1]]]\n sage: H = Hom(B, T)\n sage: psi = H([v])\n sage: b = B.highest_weight_vector(); b\n [[1, 1]]\n sage: psi(b)\n [[[1]], [[1]]]\n sage: b.f(1)\n [[1, 2]]\n sage: psi(b.f(1))\n [[[1]], [[2]]]\n\n We now look at the decomposition of `B(\\Lambda_1) \\otimes B(\\Lambda_1)`\n into `B(2\\Lambda_1) \\oplus B(0)`::\n\n sage: B0 = crystals.Tableaux([\'A\',1], shape=[])\n sage: D = crystals.DirectSum([B, B0])\n sage: H = Hom(T, D)\n sage: psi = H(D.module_generators)\n sage: psi\n [\'A\', 1] Crystal morphism:\n From: Full tensor product of the crystals\n [The crystal of tableaux of type [\'A\', 1] and shape(s) [[1]],\n The crystal of tableaux of type [\'A\', 1] and shape(s) [[1]]]\n To: Direct sum of the crystals Family\n (The crystal of tableaux of type [\'A\', 1] and shape(s) [[2]],\n The crystal of tableaux of type [\'A\', 1] and shape(s) [[]])\n Defn: [[[1]], [[1]]] |--> [[1, 1]]\n [[[2]], [[1]]] |--> []\n sage: psi.is_isomorphism()\n True\n\n We can always construct the trivial morphism which sends\n everything to `0`::\n\n sage: Binf = crystals.infinity.Tableaux([\'B\', 2])\n sage: B = crystals.Tableaux([\'B\',2], shape=[1])\n sage: H = Hom(Binf, B)\n sage: psi = H(lambda x: None)\n sage: psi(Binf.highest_weight_vector())\n\n For Kirillov-Reshetikhin crystals, we consider the map to the\n corresponding classical crystal::\n\n sage: K = crystals.KirillovReshetikhin([\'D\',4,1], 2,1)\n sage: B = K.classical_decomposition()\n sage: H = Hom(K, B)\n sage: psi = H(lambda x: x.lift(), cartan_type=[\'D\',4])\n sage: L = [psi(mg) for mg in K.module_generators]; L\n [[], [[1], [2]]]\n sage: all(x.parent() == B for x in L)\n True\n\n Next we consider a type `D_4` crystal morphism where we twist by\n `3 \\leftrightarrow 4`::\n\n sage: B = crystals.Tableaux([\'D\',4], shape=[1])\n sage: H = Hom(B, B)\n sage: d = {1:1, 2:2, 3:4, 4:3}\n sage: psi = H(B.module_generators, automorphism=d)\n sage: b = B.highest_weight_vector()\n sage: b.f_string([1,2,3])\n [[4]]\n sage: b.f_string([1,2,4])\n [[-4]]\n sage: psi(b.f_string([1,2,3]))\n [[-4]]\n sage: psi(b.f_string([1,2,4]))\n [[4]]\n\n We construct the natural virtual embedding of a type `B_3` into a type\n `D_4` crystal::\n\n sage: B = crystals.Tableaux([\'B\',3], shape=[1])\n sage: C = crystals.Tableaux([\'D\',4], shape=[2])\n sage: H = Hom(B, C)\n sage: psi = H(C.module_generators)\n sage: psi\n [\'B\', 3] -> [\'D\', 4] Virtual Crystal morphism:\n From: The crystal of tableaux of type [\'B\', 3] and shape(s) [[1]]\n To: The crystal of tableaux of type [\'D\', 4] and shape(s) [[2]]\n Defn: [[1]] |--> [[1, 1]]\n sage: for b in B: print("{} |--> {}".format(b, psi(b)))\n [[1]] |--> [[1, 1]]\n [[2]] |--> [[2, 2]]\n [[3]] |--> [[3, 3]]\n [[0]] |--> [[3, -3]]\n [[-3]] |--> [[-3, -3]]\n [[-2]] |--> [[-2, -2]]\n [[-1]] |--> [[-1, -1]]\n ' def __init__(self, X, Y, category=None): "\n Initialize ``self``.\n\n TESTS::\n\n sage: B = crystals.Tableaux(['A', 2], shape=[2,1])\n sage: H = Hom(B, B)\n sage: Binf = crystals.infinity.Tableaux(['B',2])\n sage: H = Hom(Binf, B)\n " if (category is None): category = Crystals() Homset.__init__(self, X, Y, category) def _repr_(self): "\n TESTS::\n\n sage: B = crystals.Tableaux(['A', 2], shape=[2,1])\n sage: Hom(B, B)\n Set of Crystal Morphisms from The crystal of tableaux of type ['A', 2] and shape(s) [[2, 1]]\n to The crystal of tableaux of type ['A', 2] and shape(s) [[2, 1]]\n " return 'Set of Crystal Morphisms from {} to {}'.format(self.domain(), self.codomain()) def _coerce_impl(self, x): "\n Check to see if we can coerce ``x`` into a morphism with the\n correct parameters.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['B',3], shape=[2,1])\n sage: H = Hom(B, B)\n sage: H(H.an_element()) # indirect doctest\n ['B', 3] Crystal endomorphism of The crystal of tableaux of type ['B', 3] and shape(s) [[2, 1]]\n Defn: [[1, 1], [2]] |--> None\n " if (not isinstance(x, CrystalMorphism)): raise TypeError if (x.parent() is self): return x if (x.parent() == self): return self.element_class(self, x._on_gens, x._virtualization, x._scaling_factors, x._cartan_type, x._gens) raise ValueError def __call__(self, on_gens, cartan_type=None, index_set=None, generators=None, automorphism=None, virtualization=None, scaling_factors=None, check=True): "\n Construct a crystal morphism.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A', 2], shape=[2,1])\n sage: H = Hom(B, B)\n sage: psi = H(B.module_generators)\n\n sage: F = crystals.Tableaux(['A',3], shape=[1])\n sage: T = crystals.TensorProduct(F, F, F)\n sage: H = Hom(B, T)\n sage: v = T.highest_weight_vectors()[2]\n sage: psi = H([v], cartan_type=['A',2])\n " if isinstance(on_gens, CrystalMorphism): return self._coerce_impl(on_gens) if (cartan_type is None): cartan_type = self.domain().cartan_type() else: from sage.combinat.root_system.cartan_type import CartanType cartan_type = CartanType(cartan_type) if (index_set is None): index_set = cartan_type.index_set() else: cartan_type = cartan_type.subtype(index_set) if (cartan_type != self.codomain().cartan_type()): fct = self.domain().cartan_type().as_folding() if (fct.folding_of() == self.codomain().cartan_type()): if (virtualization is None): virtualization = fct.folding_orbit() if (scaling_factors is None): scaling_factors = fct.scaling_factors() if (automorphism is not None): if (virtualization is not None): raise ValueError('the automorphism and virtualization cannot both be specified') if (not isinstance(automorphism, collections.abc.Mapping)): try: automorphism = dict(automorphism) virtualization = {i: (automorphism[i],) for i in automorphism} except (TypeError, ValueError): virtualization = {i: (automorphism(i),) for i in index_set} else: virtualization = {i: (automorphism[i],) for i in automorphism} return self.element_class(self, on_gens, cartan_type, virtualization, scaling_factors, generators, check) def _an_element_(self): "\n Return an element of ``self``. Every homset has the crystal morphism\n which sends all elements to ``None``.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A', 2], shape=[2,1])\n sage: C = crystals.infinity.Tableaux(['A', 2])\n sage: H = Hom(B, C)\n sage: H.an_element()\n ['A', 2] Crystal morphism:\n From: The crystal of tableaux of type ['A', 2] and shape(s) [[2, 1]]\n To: The infinity crystal of tableaux of type ['A', 2]\n Defn: [[1, 1], [2]] |--> None\n " return self.element_class(self, (lambda x: None)) Element = CrystalMorphismByGenerators
class CWComplexes(Category_singleton): '\n The category of CW complexes.\n\n A CW complex is a Closure-finite cell complex in the Weak topology.\n\n REFERENCES:\n\n - :wikipedia:`CW_complex`\n\n .. NOTE::\n\n The notion of "finite" is that the number of cells is finite.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: C = CWComplexes(); C\n Category of CW complexes\n\n TESTS::\n\n sage: TestSuite(C).run()\n ' @cached_method def super_categories(self): '\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: CWComplexes().super_categories()\n [Category of topological spaces]\n ' return [Sets().Topological()] def _repr_object_names(self): '\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: CWComplexes() # indirect doctest\n Category of CW complexes\n ' return 'CW complexes' class SubcategoryMethods(): @cached_method def Connected(self): "\n Return the full subcategory of the connected objects of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: CWComplexes().Connected()\n Category of connected CW complexes\n\n TESTS::\n\n sage: TestSuite(CWComplexes().Connected()).run()\n sage: CWComplexes().Connected.__module__\n 'sage.categories.cw_complexes'\n " return self._with_axiom('Connected') @cached_method def FiniteDimensional(self): "\n Return the full subcategory of the finite dimensional\n objects of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: C = CWComplexes().FiniteDimensional(); C\n Category of finite dimensional CW complexes\n\n TESTS::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: C = CWComplexes().FiniteDimensional()\n sage: TestSuite(C).run()\n sage: CWComplexes().Connected().FiniteDimensional.__module__\n 'sage.categories.cw_complexes'\n " return self._with_axiom('FiniteDimensional') class Connected(CategoryWithAxiom): '\n The category of connected CW complexes.\n ' class FiniteDimensional(CategoryWithAxiom): '\n Category of finite dimensional CW complexes.\n ' class Finite(CategoryWithAxiom): '\n Category of finite CW complexes.\n\n A finite CW complex is a CW complex with a finite number of cells.\n ' def extra_super_categories(self): '\n Return the extra super categories of ``self``.\n\n A finite CW complex is a compact finite-dimensional CW complex.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: C = CWComplexes().Finite()\n sage: C.extra_super_categories()\n [Category of finite dimensional CW complexes,\n Category of compact topological spaces]\n ' return [CWComplexes().FiniteDimensional(), Sets().Topological().Compact()] class ParentMethods(): @cached_method def dimension(self): '\n Return the dimension of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: X = CWComplexes().example()\n sage: X.dimension()\n 2\n ' C = self.cells() return max((c.dimension() for d in C.keys() for c in C[d])) def Compact_extra_super_categories(self): '\n Return extraneous super categories for ``CWComplexes().Compact()``.\n\n A compact CW complex is finite, see Proposition A.1 in [Hat2002]_.\n\n .. TODO::\n\n Fix the name of finite CW complexes.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: CWComplexes().Compact() # indirect doctest\n Category of finite finite dimensional CW complexes\n sage: CWComplexes().Compact() is CWComplexes().Finite()\n True\n ' return (Sets().Finite(),) class ElementMethods(): @abstract_method def dimension(self): '\n Return the dimension of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: X = CWComplexes().example()\n sage: X.an_element().dimension()\n 2\n ' class ParentMethods(): @abstract_method def dimension(self): '\n Return the dimension of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: X = CWComplexes().example()\n sage: X.dimension()\n 2\n ' @abstract_method(optional=True) def cells(self): '\n Return the cells of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: X = CWComplexes().example()\n sage: C = X.cells()\n sage: sorted((d, C[d]) for d in C.keys())\n [(0, (0-cell v,)),\n (1, (0-cell e1, 0-cell e2)),\n (2, (2-cell f,))]\n '
class DiscreteValuationRings(Category_singleton): "\n The category of discrete valuation rings\n\n EXAMPLES::\n\n sage: GF(7)[['x']] in DiscreteValuationRings()\n True\n sage: TestSuite(DiscreteValuationRings()).run()\n " def super_categories(self): '\n EXAMPLES::\n\n sage: DiscreteValuationRings().super_categories()\n [Category of euclidean domains]\n ' return [EuclideanDomains()] class ParentMethods(): @abstract_method def uniformizer(self): '\n Return a uniformizer of this ring.\n\n EXAMPLES::\n\n sage: Zp(5).uniformizer() # needs sage.rings.padics\n 5 + O(5^21)\n\n sage: K.<u> = QQ[[]]\n sage: K.uniformizer()\n u\n ' @abstract_method def residue_field(self): '\n Return the residue field of this ring.\n\n EXAMPLES::\n\n sage: Zp(5).residue_field() # needs sage.rings.padics\n Finite Field of size 5\n\n sage: K.<u> = QQ[[]]\n sage: K.residue_field()\n Rational Field\n ' def _matrix_charpoly(self, M, var): '\n Return the characteristic polynomial of `M`.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: R.<t> = PowerSeriesRing(GF(5))\n sage: M = matrix(4, 4, [(t^(i+j)).add_bigoh(10)\n ....: for i in range(4) for j in range(4)])\n sage: M\n [ 1 + O(t^10) t + O(t^10) t^2 + O(t^10) t^3 + O(t^10)]\n [ t + O(t^10) t^2 + O(t^10) t^3 + O(t^10) t^4 + O(t^10)]\n [t^2 + O(t^10) t^3 + O(t^10) t^4 + O(t^10) t^5 + O(t^10)]\n [t^3 + O(t^10) t^4 + O(t^10) t^5 + O(t^10) t^6 + O(t^10)]\n sage: M.charpoly() # indirect doctest\n x^4 + (4 + 4*t^2 + 4*t^4 + 4*t^6 + O(t^10))*x^3\n\n Note that this function uses a Hessenberg-like algorithm\n that performs divisions. Hence, truncations may show up\n even if the input matrix is exact::\n\n sage: # needs sage.modules\n sage: M = matrix(3, 3, [ 1, t, t^2, 1+t, t^2, t^3, t^2, t^3, t^4 ])\n sage: M\n [ 1 t t^2]\n [1 + t t^2 t^3]\n [ t^2 t^3 t^4]\n sage: M.charpoly()\n x^3 + (4 + 4*t^2 + 4*t^4 + O(t^25))*x^2 + (4*t + O(t^24))*x\n\n Another example over the p-adics::\n\n sage: # needs sage.modules sage.rings.padics\n sage: R = Zp(5, print_mode="digits", prec=5)\n sage: M = matrix(R, 3, 3, range(9))\n sage: M\n [ 0 ...00001 ...00002]\n [ ...00003 ...00004 ...000010]\n [ ...00011 ...00012 ...00013]\n sage: M.charpoly()\n ...00001*x^3 + ...44423*x^2 + ...44412*x + ...00000\n ' return M._charpoly_hessenberg(var) class ElementMethods(): @abstract_method def valuation(self): '\n Return the valuation of this element.\n\n EXAMPLES::\n\n sage: # needs sage.rings.padics\n sage: x = Zp(5)(50)\n sage: x.valuation()\n 2\n ' def euclidean_degree(self): '\n Return the Euclidean degree of this element.\n\n TESTS::\n\n sage: R.<q> = GF(5)[[]]\n sage: (q^3).euclidean_degree()\n 3\n sage: R(0).euclidean_degree()\n Traceback (most recent call last):\n ...\n ValueError: Euclidean degree of the zero element not defined\n\n ' if (not self): raise ValueError('Euclidean degree of the zero element not defined') return self.valuation() def quo_rem(self, other): "\n Return the quotient and remainder for Euclidean division\n of ``self`` by ``other``.\n\n EXAMPLES::\n\n sage: R.<q> = GF(5)[[]]\n sage: (q^2 + q).quo_rem(q)\n (1 + q, 0)\n sage: (q + 1).quo_rem(q^2)\n (0, 1 + q)\n\n TESTS::\n\n sage: q.quo_rem(0)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: Euclidean division by the zero element not defined\n\n sage: L = PowerSeriesRing(QQ, 't')\n sage: t = L.gen()\n sage: F = algebras.Free(L, ['A', 'B'])\n sage: A, B = F.gens()\n sage: f = t*A+t**2*B/2\n " if (not other): raise ZeroDivisionError('Euclidean division by the zero element not defined') P = self.parent() other = P(other) if (self.valuation() >= other.valuation()): return (P((self / other)), P.zero()) else: return (P.zero(), self) def is_unit(self): '\n Return ``True`` if ``self`` is invertible.\n\n EXAMPLES::\n\n sage: # needs sage.rings.padics\n sage: x = Zp(5)(50)\n sage: x.is_unit()\n False\n\n sage: # needs sage.rings.padics\n sage: x = Zp(7)(50)\n sage: x.is_unit()\n True\n ' return (self.valuation() == 0) def gcd(self, other): '\n Return the greatest common divisor of self and other,\n normalized so that it is a power of the distinguished\n uniformizer.\n ' from sage.rings.infinity import Infinity val = min(self.valuation(), other.valuation()) if (val is Infinity): return self.parent()(0) else: return (self.parent().uniformizer() ** val) def lcm(self, other): '\n Return the least common multiple of self and other,\n normalized so that it is a power of the distinguished\n uniformizer.\n ' from sage.rings.infinity import Infinity val = max(self.valuation(), other.valuation()) if (val is Infinity): return self.parent()(0) else: return (self.parent().uniformizer() ** val)
class DiscreteValuationFields(Category_singleton): '\n The category of discrete valuation fields\n\n EXAMPLES::\n\n sage: Qp(7) in DiscreteValuationFields() # needs sage.rings.padics\n True\n sage: TestSuite(DiscreteValuationFields()).run()\n ' def super_categories(self): '\n EXAMPLES::\n\n sage: DiscreteValuationFields().super_categories()\n [Category of fields]\n ' return [Fields()] class ParentMethods(): @abstract_method def uniformizer(self): '\n Return a uniformizer of this ring.\n\n EXAMPLES::\n\n sage: Qp(5).uniformizer() # needs sage.rings.padics\n 5 + O(5^21)\n ' @abstract_method def residue_field(self): '\n Return the residue field of the ring of integers of\n this discrete valuation field.\n\n EXAMPLES::\n\n sage: Qp(5).residue_field() # needs sage.rings.padics\n Finite Field of size 5\n\n sage: K.<u> = LaurentSeriesRing(QQ)\n sage: K.residue_field()\n Rational Field\n ' def _matrix_hessenbergize(self, H): '\n Replace `H` with a Hessenberg form of it.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: R.<t> = PowerSeriesRing(GF(5))\n sage: K = R.fraction_field()\n sage: H = matrix(K, 4, 4, [(t^(i+j)).add_bigoh(10)\n ....: for i in range(4) for j in range(4)])\n sage: H\n [ 1 + O(t^10) t + O(t^10) t^2 + O(t^10) t^3 + O(t^10)]\n [ t + O(t^10) t^2 + O(t^10) t^3 + O(t^10) t^4 + O(t^10)]\n [t^2 + O(t^10) t^3 + O(t^10) t^4 + O(t^10) t^5 + O(t^10)]\n [t^3 + O(t^10) t^4 + O(t^10) t^5 + O(t^10) t^6 + O(t^10)]\n sage: H.hessenbergize()\n sage: H\n [ 1 + O(t^10) t + t^3 + t^5 + O(t^10) t^2 + O(t^10) t^3 + O(t^10)]\n [ t + O(t^10) t^2 + t^4 + t^6 + O(t^10) t^3 + O(t^10) t^4 + O(t^10)]\n [ O(t^10) O(t^10) O(t^10) O(t^10)]\n [ O(t^10) O(t^10) O(t^10) O(t^10)]\n\n Another example over the p-adics::\n\n sage: # needs sage.modules sage.rings.padics\n sage: K = Qp(5, print_mode="digits", prec=5)\n sage: H = matrix(K, 3, 3, range(9)); H\n [ 0 ...00001 ...00002]\n [ ...00003 ...00004 ...000010]\n [ ...00011 ...00012 ...00013]\n sage: H.hessenbergize(); H\n [ 0 ...00010 ...00002]\n [ ...00003 ...00024 ...000010]\n [ ...00000 ...44440 ...44443]\n ' from sage.matrix.matrix_cdv import hessenbergize_cdvf hessenbergize_cdvf(H) class ElementMethods(): @abstract_method def valuation(self): '\n Return the valuation of this element.\n\n EXAMPLES::\n\n sage: # needs sage.rings.padics\n sage: x = Qp(5)(50)\n sage: x.valuation()\n 2\n '
class DistributiveMagmasAndAdditiveMagmas(CategoryWithAxiom): '\n The category of sets `(S,+,*)` with `*` distributing on `+`.\n\n This is similar to a ring, but `+` and `*` are only required to be\n (additive) magmas.\n\n EXAMPLES::\n\n sage: from sage.categories.distributive_magmas_and_additive_magmas import DistributiveMagmasAndAdditiveMagmas\n sage: C = DistributiveMagmasAndAdditiveMagmas(); C\n Category of distributive magmas and additive magmas\n sage: C.super_categories()\n [Category of magmas and additive magmas]\n\n TESTS::\n\n sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas\n sage: C is MagmasAndAdditiveMagmas().Distributive()\n True\n sage: C is (Magmas() & AdditiveMagmas()).Distributive()\n True\n sage: TestSuite(C).run()\n ' class AdditiveAssociative(CategoryWithAxiom): class AdditiveCommutative(CategoryWithAxiom): class AdditiveUnital(CategoryWithAxiom): class Associative(CategoryWithAxiom): AdditiveInverse = LazyImport('sage.categories.rngs', 'Rngs', at_startup=True) Unital = LazyImport('sage.categories.semirings', 'Semirings', at_startup=True) class ParentMethods(): def _test_distributivity(self, **options): '\n Test the distributivity of `*` on `+` on (not necessarily\n all) elements of this set.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`\n\n EXAMPLES:\n\n By default, this method runs the tests only on the\n elements returned by ``self.some_elements()``::\n\n sage: NN.some_elements()\n [0, 1, 3, 42]\n sage: NN._test_distributivity()\n\n However, the elements tested can be customized with the\n ``elements`` keyword argument::\n\n sage: CC._test_distributivity(elements=[CC(0),CC(1),CC(3),CC(I)]) # needs sage.symbolic\n\n See the documentation for :class:`TestSuite` for more information.\n ' tester = self._tester(**options) tester.some_elements() from sage.misc.misc import some_tuples for (x, y, z) in some_tuples(tester.some_elements(), 3, tester._max_runs): tester.assertEqual((x * (y + z)), ((x * y) + (x * z))) tester.assertEqual(((x + y) * z), ((x * z) + (y * z))) class CartesianProducts(CartesianProductsCategory): def extra_super_categories(self): "\n Implement the fact that a Cartesian product of magmas distributing\n over additive magmas is a magma distributing over an\n additive magma.\n\n EXAMPLES::\n\n sage: C = (Magmas() & AdditiveMagmas()).Distributive().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of distributive magmas and additive magmas]\n sage: C.axioms()\n frozenset({'Distributive'})\n " return [DistributiveMagmasAndAdditiveMagmas()]
class DivisionRings(CategoryWithAxiom): '\n The category of division rings\n\n A division ring (or skew field) is a not necessarily commutative\n ring where all non-zero elements have multiplicative inverses\n\n EXAMPLES::\n\n sage: DivisionRings()\n Category of division rings\n sage: DivisionRings().super_categories()\n [Category of domains]\n\n TESTS::\n\n sage: TestSuite(DivisionRings()).run()\n ' _base_category_class_and_axiom = (Rings, 'Division') def extra_super_categories(self): '\n Return the :class:`Domains` category.\n\n This method specifies that a division ring has no zero\n divisors, i.e. is a domain.\n\n .. SEEALSO::\n\n The :ref:`axioms-deduction-rules` section in the\n documentation of axioms\n\n EXAMPLES::\n\n sage: DivisionRings().extra_super_categories()\n (Category of domains,)\n sage: "NoZeroDivisors" in DivisionRings().axioms()\n True\n ' return (Rings().NoZeroDivisors(),) Commutative = LazyImport('sage.categories.fields', 'Fields', at_startup=True) def Finite_extra_super_categories(self): '\n Return extraneous super categories for ``DivisionRings().Finite()``.\n\n EXAMPLES:\n\n Any field is a division ring::\n\n sage: Fields().is_subcategory(DivisionRings())\n True\n\n This methods specifies that, by Weddeburn theorem, the\n reciprocal holds in the finite case: a finite division ring is\n commutative and thus a field::\n\n sage: DivisionRings().Finite_extra_super_categories()\n (Category of commutative magmas,)\n sage: DivisionRings().Finite()\n Category of finite enumerated fields\n\n .. WARNING::\n\n This is not implemented in\n ``DivisionRings.Finite.extra_super_categories`` because\n the categories of finite division rings and of finite\n fields coincide. See the section\n :ref:`axioms-deduction-rules` in the documentation of\n axioms.\n\n TESTS::\n\n sage: DivisionRings().Finite() is Fields().Finite()\n True\n\n This works also for subcategories::\n\n sage: class Foo(Category):\n ....: def super_categories(self): return [DivisionRings()]\n sage: Foo().Finite().is_subcategory(Fields())\n True\n ' from sage.categories.magmas import Magmas return (Magmas().Commutative(),) class ParentMethods(): pass class ElementMethods(): pass
class Domains(CategoryWithAxiom): '\n The category of domains\n\n A domain (or non-commutative integral domain), is a ring, not\n necessarily commutative, with no nonzero zero divisors.\n\n EXAMPLES::\n\n sage: C = Domains(); C\n Category of domains\n sage: C.super_categories()\n [Category of rings]\n sage: C is Rings().NoZeroDivisors()\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\n ' _base_category_class_and_axiom = (Rings, 'NoZeroDivisors') def super_categories(self): '\n EXAMPLES::\n\n sage: Domains().super_categories()\n [Category of rings]\n ' return [Rings()] Commutative = LazyImport('sage.categories.integral_domains', 'IntegralDomains', at_startup=True) class ParentMethods(): def _test_zero_divisors(self, **options): '\n Check to see that there are no zero divisors.\n\n .. NOTE::\n\n In rings whose elements can not be represented exactly, there\n may be zero divisors in practice, even though these rings do\n not have them in theory. For such inexact rings, these tests\n are not performed::\n\n sage: # needs sage.rings.padics\n sage: R = ZpFM(5); R\n 5-adic Ring of fixed modulus 5^20\n sage: R.is_exact()\n False\n sage: a = R(5^19)\n sage: a.is_zero()\n False\n sage: (a * a).is_zero()\n True\n sage: R._test_zero_divisors()\n\n EXAMPLES::\n\n sage: ZZ._test_zero_divisors()\n sage: ZpFM(5)._test_zero_divisors() # needs sage.rings.padics\n\n ' if (not self.is_exact()): return tester = self._tester(**options) S = [s for s in tester.some_elements() if (not s.is_zero())] from sage.misc.misc import some_tuples for (a, b) in some_tuples(S, 2, tester._max_runs): p = (a * b) tester.assertFalse(p.is_zero()) class ElementMethods(): pass
class DrinfeldModules(Category_over_base_ring): "\n This class implements the category of Drinfeld\n `\\mathbb{F}_q[T]`-modules on a given base field.\n\n Let `\\mathbb{F}_q[T]` be a polynomial ring with coefficients in a\n finite field `\\mathbb{F}_q` and let `K` be a field. Fix a ring\n morphism `\\gamma: \\mathbb{F}_q[T] \\to K`; we say that `K` is an\n `\\mathbb{F}_q[T]`*-field*. Let `K\\{\\tau\\}` be the ring of Ore\n polynomials with coefficients in `K`, whose multiplication is given\n by the rule `\\tau \\lambda = \\lambda^q \\tau` for any `\\lambda \\in K`.\n\n The extension `K`/`\\mathbb{F}_q[T]` (represented as an instance of\n the class :class:`sage.rings.ring_extension.RingExtension`) is the\n *base field* of the category; its defining morphism `\\gamma` is\n called the *base morphism*.\n\n The monic polynomial that generates the kernel of `\\gamma` is called\n the `\\mathbb{F}_q[T]`-*characteristic*, or *function-field\n characteristic*, of the base field. We say that `\\mathbb{F}_q[T]` is\n the *function ring* of the category; `K\\{\\tau\\}` is the *Ore\n polynomial ring*. The constant coefficient of the category is the\n image of `T` under the base morphism.\n\n .. RUBRIC:: Construction\n\n Generally, Drinfeld modules objects are created before their\n category, and the category is retrieved as an attribute of the\n Drinfeld module::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n sage: C\n Category of Drinfeld modules over Finite Field in z of size 11^4 over its base\n\n The output tells the user that the category is only defined by its\n base.\n\n .. RUBRIC:: Properties of the category\n\n The base field is retrieved using the method :meth:`base`.\n\n sage: C.base()\n Finite Field in z of size 11^4 over its base\n\n Equivalently, one can use :meth:`base_morphism` to retrieve the base\n morphism::\n\n sage: C.base_morphism()\n Ring morphism:\n From: Univariate Polynomial Ring in T over Finite Field of size 11\n To: Finite Field in z of size 11^4 over its base\n Defn: T |--> z^3 + 7*z^2 + 6*z + 10\n\n The so-called constant coefficient --- which is the same for all\n Drinfeld modules in the category --- is simply the image of `T` by\n the base morphism::\n\n sage: C.constant_coefficient()\n z^3 + 7*z^2 + 6*z + 10\n sage: C.base_morphism()(T) == C.constant_coefficient()\n True\n\n Similarly, the function ring-characteristic of the category is\n either `0` or the unique monic polynomial in `\\mathbb{F}_q[T]` that\n generates the kernel of the base::\n\n sage: C.characteristic()\n T^2 + 7*T + 2\n sage: C.base_morphism()(C.characteristic())\n 0\n\n The base field, base morphism, function ring and Ore polynomial ring\n are the same for the category and its objects::\n\n sage: C.base() is phi.base()\n True\n sage: C.base_morphism() is phi.base_morphism()\n True\n\n sage: C.function_ring()\n Univariate Polynomial Ring in T over Finite Field of size 11\n sage: C.function_ring() is phi.function_ring()\n True\n\n sage: C.ore_polring()\n Ore Polynomial Ring in t over Finite Field in z of size 11^4 over its base twisted by Frob\n sage: C.ore_polring() is phi.ore_polring()\n True\n\n\n .. RUBRIC:: Creating Drinfeld module objects from the category\n\n Calling :meth:`object` with an Ore polynomial creates a Drinfeld module\n object in the category whose generator is the input::\n\n sage: psi = C.object([p_root, 1])\n sage: psi\n Drinfeld module defined by T |--> t + z^3 + 7*z^2 + 6*z + 10\n sage: psi.category() is C\n True\n\n Of course, the constant coefficient of the input must be the same as\n the category::\n\n sage: C.object([z, 1])\n Traceback (most recent call last):\n ...\n ValueError: constant coefficient must equal that of the category\n\n It is also possible to create a random object in the category. The\n input is the desired rank::\n\n sage: rho = C.random_object(2)\n sage: rho # random\n Drinfeld module defined by T |--> (7*z^3 + 7*z^2 + 10*z + 2)*t^2 + (9*z^3 + 5*z^2 + 2*z + 7)*t + z^3 + 7*z^2 + 6*z + 10\n sage: rho.rank() == 2\n True\n sage: rho.category() is C\n True\n\n TESTS::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: from sage.categories.drinfeld_modules import DrinfeldModules\n sage: base = Hom(A, K)(0)\n sage: C = DrinfeldModules(base)\n Traceback (most recent call last):\n ...\n TypeError: base field must be a ring extension\n\n ::\n\n sage: C.base().defining_morphism() == C.base_morphism()\n True\n\n ::\n\n sage: base = Hom(A, A)(1)\n sage: C = DrinfeldModules(base)\n Traceback (most recent call last):\n ...\n TypeError: base field must be a ring extension\n\n ::\n\n sage: base = 'I hate Rostropovitch'\n sage: C = DrinfeldModules(base) # known bug (blankline)\n <BLANKLINE>\n Traceback (most recent call last):\n ...\n TypeError: input must be a ring morphism\n\n ::\n\n sage: ZZT.<T> = ZZ[]\n sage: base = Hom(ZZT, K)(1)\n sage: C = DrinfeldModules(base) # known bug (blankline)\n <BLANKLINE>\n Traceback (most recent call last):\n ...\n TypeError: function ring base must be a finite field\n " def __init__(self, base_field, name='t'): "\n Initialize `self`.\n\n INPUT:\n\n - ``base_field`` -- the base field, which is a ring extension\n over a base\n\n - ``name`` (default: ``'t'``) -- the name of the Ore polynomial\n variable\n\n TESTS::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n sage: ore_polring.<t> = OrePolynomialRing(phi.base(), phi.base().frobenius_endomorphism())\n sage: C._ore_polring is ore_polring\n True\n sage: i = phi.base().coerce_map_from(K)\n sage: base_morphism = Hom(A, K)(p_root)\n sage: C.base() == K.over(base_morphism)\n True\n sage: C._base_morphism == i * base_morphism\n True\n sage: C._function_ring is A\n True\n sage: C._constant_coefficient == base_morphism(T)\n True\n sage: C._characteristic(C._constant_coefficient)\n 0\n " if (not isinstance(base_field, RingExtension_generic)): raise TypeError('base field must be a ring extension') base_morphism = base_field.defining_morphism() self._base_morphism = base_morphism if (not base_field.is_field()): raise TypeError('input must be a field') self._base_field = base_field self._function_ring = base_morphism.domain() function_ring = self._function_ring if (not isinstance(function_ring, PolynomialRing_general)): raise NotImplementedError('function ring must be a polynomial ring') function_ring_base = function_ring.base_ring() if ((not function_ring_base.is_field()) or (not function_ring_base.is_finite())): raise TypeError('function ring base must be a finite field') Fq = function_ring_base A = function_ring T = A.gen() K = base_field d = log(Fq.cardinality(), Fq.characteristic()) tau = K.frobenius_endomorphism(d) self._ore_polring = OrePolynomialRing(K, tau, names=name, polcast=False) self._constant_coefficient = base_morphism(T) self._characteristic = None if K.is_finite(): self._characteristic = A(K.over(Fq)(base_morphism(T)).minpoly()) else: try: if base_morphism.is_injective(): self._characteristic = Integer(0) except NotImplementedError: pass i = A.coerce_map_from(Fq) Fq_to_K = (self._base_morphism * i) self._base_over_constants_field = base_field.over(Fq_to_K) super().__init__(base=base_field) def _latex_(self): '\n Return a latex representation of the category.\n\n OUTPUT: a string\n\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n sage: latex(C)\n \\text{Category{ }of{ }Drinfeld{ }modules{ }over{ }\\Bold{F}_{11^{4}}\n ' return f' ext{{Category{{ }}of{{ }}Drinfeld{{ }}modules{{ }}over{{ }}{latex(self._base_field)}' def _repr_(self): '\n Return a string representation of the category.\n\n OUTPUT: a string\n\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n sage: C\n Category of Drinfeld modules over Finite Field in z of size 11^4 over its base\n ' return f'Category of Drinfeld modules over {self._base_field}' def Homsets(self): '\n Return the category of homsets.\n\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n\n sage: from sage.categories.homsets import Homsets\n sage: C.Homsets() is Homsets()\n True\n ' return Homsets() def Endsets(self): '\n Return the category of endsets.\n\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n\n sage: from sage.categories.homsets import Homsets\n sage: C.Endsets() is Homsets().Endsets()\n True\n ' return Homsets().Endsets() def base_morphism(self): '\n Return the base morphism of the category.\n\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n sage: C.base_morphism()\n Ring morphism:\n From: Univariate Polynomial Ring in T over Finite Field of size 11\n To: Finite Field in z of size 11^4 over its base\n Defn: T |--> z^3 + 7*z^2 + 6*z + 10\n\n sage: C.constant_coefficient() == C.base_morphism()(T)\n True\n ' return self._base_morphism def base_over_constants_field(self): '\n Return the base field, seen as an extension over the constants\n field `\\mathbb{F}_q`.\n\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n sage: C.base_over_constants_field()\n Field in z with defining polynomial x^4 + 8*x^2 + 10*x + 2 over its base\n ' return self._base_over_constants_field def characteristic(self): '\n Return the function ring-characteristic.\n\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n sage: C.characteristic()\n T^2 + 7*T + 2\n\n ::\n\n sage: psi = DrinfeldModule(A, [Frac(A).gen(), 1])\n sage: C = psi.category()\n sage: C.characteristic()\n 0\n ' if (self._characteristic is None): raise NotImplementedError('function ring characteristic not implemented in this case') return self._characteristic def constant_coefficient(self): '\n Return the constant coefficient of the category.\n\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n sage: C.constant_coefficient()\n z^3 + 7*z^2 + 6*z + 10\n sage: C.constant_coefficient() == C.base()(T)\n True\n ' return self._constant_coefficient def function_ring(self): '\n Return the function ring of the category.\n\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n sage: C.function_ring()\n Univariate Polynomial Ring in T over Finite Field of size 11\n sage: C.function_ring() is A\n True\n ' return self._function_ring def object(self, gen): '\n Return a Drinfeld module object in the category whose generator\n is the input.\n\n INPUT:\n\n - ``gen`` -- the generator of the Drinfeld module, given as an Ore\n polynomial or a list of coefficients\n\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: psi = DrinfeldModule(A, [p_root, 1])\n sage: C = psi.category()\n\n sage: phi = C.object([p_root, 0, 1])\n sage: phi\n Drinfeld module defined by T |--> t^2 + z^3 + 7*z^2 + 6*z + 10\n sage: t = phi.ore_polring().gen()\n sage: C.object(t^2 + z^3 + 7*z^2 + 6*z + 10) is phi\n True\n ' from sage.rings.function_field.drinfeld_modules.drinfeld_module import DrinfeldModule gen = self._ore_polring(gen) T = self._function_ring.gen() if (gen[0] != self._base_morphism(T)): raise ValueError('constant coefficient must equal that of the category') return DrinfeldModule(self._function_ring, gen) def ore_polring(self): '\n Return the Ore polynomial ring of the category\n\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n sage: C.ore_polring()\n Ore Polynomial Ring in t over Finite Field in z of size 11^4 over its base twisted by Frob\n ' return self._ore_polring def random_object(self, rank): '\n Return a random Drinfeld module in the category with given rank.\n\n INPUT:\n\n - ``rank`` -- an integer, the rank of the Drinfeld module\n\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n\n sage: psi = C.random_object(3) # random\n Drinfeld module defined by T |--> (6*z^3 + 4*z^2 + 10*z + 9)*t^3 + (4*z^3 + 8*z^2 + 8*z)*t^2 + (10*z^3 + 3*z^2 + 6*z)*t + z^3 + 7*z^2 + 6*z + 10\n sage: psi.rank() == 3\n True\n ' if (not isinstance(rank, Integer)): raise TypeError('rank must be a positive integer') if (rank <= 0): raise ValueError('rank must be a positive integer') K = self._base_field coeffs = [self._constant_coefficient] for _ in range((rank - 1)): coeffs.append(K.random_element()) dom_coeff = 0 while (dom_coeff == 0): dom_coeff = K.random_element() coeffs.append(dom_coeff) return self.object(coeffs) def super_categories(self): '\n EXAMPLES::\n\n sage: Fq = GF(11)\n sage: A.<T> = Fq[]\n sage: K.<z> = Fq.extension(4)\n sage: p_root = z^3 + 7*z^2 + 6*z + 10\n sage: phi = DrinfeldModule(A, [p_root, 0, 0, 1])\n sage: C = phi.category()\n sage: C.super_categories()\n [Category of objects]\n ' return [Objects()] class ParentMethods(): def base(self): '\n Return the base field of this Drinfeld module, viewed as\n an algebra over the function ring.\n\n This is an instance of the class\n :class:`sage.rings.ring_extension.RingExtension`.\n\n EXAMPLES::\n\n sage: Fq = GF(25)\n sage: A.<T> = Fq[]\n sage: K.<z12> = Fq.extension(6)\n sage: p_root = 2*z12^11 + 2*z12^10 + z12^9 + 3*z12^8 + z12^7 + 2*z12^5 + 2*z12^4 + 3*z12^3 + z12^2 + 2*z12\n sage: phi = DrinfeldModule(A, [p_root, z12^3, z12^5])\n sage: phi.base()\n Finite Field in z12 of size 5^12 over its base\n\n The base can be infinite::\n\n sage: sigma = DrinfeldModule(A, [Frac(A).gen(), 1])\n sage: sigma.base()\n Fraction Field of Univariate Polynomial Ring in T over Finite Field in z2 of size 5^2 over its base\n ' return self.category().base() def base_morphism(self): '\n Return the base morphism of this Drinfeld module.\n\n EXAMPLES::\n\n sage: Fq = GF(25)\n sage: A.<T> = Fq[]\n sage: K.<z12> = Fq.extension(6)\n sage: p_root = 2*z12^11 + 2*z12^10 + z12^9 + 3*z12^8 + z12^7 + 2*z12^5 + 2*z12^4 + 3*z12^3 + z12^2 + 2*z12\n sage: phi = DrinfeldModule(A, [p_root, z12^3, z12^5])\n sage: phi.base_morphism()\n Ring morphism:\n From: Univariate Polynomial Ring in T over Finite Field in z2 of size 5^2\n To: Finite Field in z12 of size 5^12 over its base\n Defn: T |--> 2*z12^11 + 2*z12^10 + z12^9 + 3*z12^8 + z12^7 + 2*z12^5 + 2*z12^4 + 3*z12^3 + z12^2 + 2*z12\n\n The base field can be infinite::\n\n sage: sigma = DrinfeldModule(A, [Frac(A).gen(), 1])\n sage: sigma.base_morphism()\n Ring morphism:\n From: Univariate Polynomial Ring in T over Finite Field in z2 of size 5^2\n To: Fraction Field of Univariate Polynomial Ring in T over Finite Field in z2 of size 5^2 over its base\n Defn: T |--> T\n ' return self.category().base_morphism() def base_over_constants_field(self): '\n Return the base field, seen as an extension over the constants\n field `\\mathbb{F}_q`.\n\n This is an instance of the class\n :class:`sage.rings.ring_extension.RingExtension`.\n\n EXAMPLES::\n\n sage: Fq = GF(25)\n sage: A.<T> = Fq[]\n sage: K.<z12> = Fq.extension(6)\n sage: p_root = 2*z12^11 + 2*z12^10 + z12^9 + 3*z12^8 + z12^7 + 2*z12^5 + 2*z12^4 + 3*z12^3 + z12^2 + 2*z12\n sage: phi = DrinfeldModule(A, [p_root, z12^3, z12^5])\n sage: phi.base_over_constants_field()\n Field in z12 with defining polynomial x^6 + (4*z2 + 3)*x^5 + x^4 + (3*z2 + 1)*x^3 + x^2 + (4*z2 + 1)*x + z2 over its base\n ' return self.category().base_over_constants_field() def characteristic(self): '\n Return the function ring-characteristic.\n\n EXAMPLES::\n\n sage: Fq = GF(25)\n sage: A.<T> = Fq[]\n sage: K.<z12> = Fq.extension(6)\n sage: p_root = 2*z12^11 + 2*z12^10 + z12^9 + 3*z12^8 + z12^7 + 2*z12^5 + 2*z12^4 + 3*z12^3 + z12^2 + 2*z12\n sage: phi = DrinfeldModule(A, [p_root, z12^3, z12^5])\n sage: phi.characteristic()\n T^2 + (4*z2 + 2)*T + 2\n sage: phi.base_morphism()(phi.characteristic())\n 0\n\n ::\n\n sage: B.<Y> = Fq[]\n sage: L = Frac(B)\n sage: psi = DrinfeldModule(A, [L(1), 0, 0, L(1)])\n sage: psi.characteristic()\n Traceback (most recent call last):\n ...\n NotImplementedError: function ring characteristic not implemented in this case\n ' return self.category().characteristic() def function_ring(self): '\n Return the function ring of this Drinfeld module.\n\n EXAMPLES::\n\n sage: Fq = GF(25)\n sage: A.<T> = Fq[]\n sage: K.<z12> = Fq.extension(6)\n sage: p_root = 2*z12^11 + 2*z12^10 + z12^9 + 3*z12^8 + z12^7 + 2*z12^5 + 2*z12^4 + 3*z12^3 + z12^2 + 2*z12\n sage: phi = DrinfeldModule(A, [p_root, z12^3, z12^5])\n sage: phi.function_ring()\n Univariate Polynomial Ring in T over Finite Field in z2 of size 5^2\n sage: phi.function_ring() is A\n True\n ' return self.category().function_ring() def constant_coefficient(self): '\n Return the constant coefficient of the generator\n of this Drinfeld module.\n\n OUTPUT: an element in the base field\n\n EXAMPLES::\n\n sage: Fq = GF(25)\n sage: A.<T> = Fq[]\n sage: K.<z12> = Fq.extension(6)\n sage: p_root = 2*z12^11 + 2*z12^10 + z12^9 + 3*z12^8 + z12^7 + 2*z12^5 + 2*z12^4 + 3*z12^3 + z12^2 + 2*z12\n sage: phi = DrinfeldModule(A, [p_root, z12^3, z12^5])\n sage: phi.constant_coefficient() == p_root\n True\n\n Let `\\mathbb{F}_q[T]` be the function ring, and let `\\gamma` be\n the base of the Drinfeld module. The constant coefficient is\n `\\gamma(T)`::\n\n sage: C = phi.category()\n sage: base = C.base()\n sage: base(T) == phi.constant_coefficient()\n True\n\n Naturally, two Drinfeld modules in the same category have the\n same constant coefficient::\n\n sage: t = phi.ore_polring().gen()\n sage: psi = C.object(phi.constant_coefficient() + t^3)\n sage: psi\n Drinfeld module defined by T |--> t^3 + 2*z12^11 + 2*z12^10 + z12^9 + 3*z12^8 + z12^7 + 2*z12^5 + 2*z12^4 + 3*z12^3 + z12^2 + 2*z12\n\n Reciprocally, it is impossible to create two Drinfeld modules in\n this category if they do not share the same constant\n coefficient::\n\n sage: rho = C.object(phi.constant_coefficient() + 1 + t^3)\n Traceback (most recent call last):\n ...\n ValueError: constant coefficient must equal that of the category\n ' return self.category().constant_coefficient() def ore_polring(self): '\n Return the Ore polynomial ring of this Drinfeld module.\n\n EXAMPLES::\n\n sage: Fq = GF(25)\n sage: A.<T> = Fq[]\n sage: K.<z12> = Fq.extension(6)\n sage: p_root = 2*z12^11 + 2*z12^10 + z12^9 + 3*z12^8 + z12^7 + 2*z12^5 + 2*z12^4 + 3*z12^3 + z12^2 + 2*z12\n sage: phi = DrinfeldModule(A, [p_root, z12^3, z12^5])\n sage: S = phi.ore_polring()\n sage: S\n Ore Polynomial Ring in t over Finite Field in z12 of size 5^12 over its base twisted by Frob^2\n\n The Ore polynomial ring can also be retrieved from the category\n of the Drinfeld module::\n\n sage: S is phi.category().ore_polring()\n True\n\n The generator of the Drinfeld module is in the Ore polynomial\n ring::\n\n sage: phi(T) in S\n True\n ' return self.category().ore_polring() def ore_variable(self): '\n Return the variable of the Ore polynomial ring of this Drinfeld module.\n\n EXAMPLES::\n\n sage: Fq = GF(25)\n sage: A.<T> = Fq[]\n sage: K.<z12> = Fq.extension(6)\n sage: p_root = 2*z12^11 + 2*z12^10 + z12^9 + 3*z12^8 + z12^7 + 2*z12^5 + 2*z12^4 + 3*z12^3 + z12^2 + 2*z12\n sage: phi = DrinfeldModule(A, [p_root, z12^3, z12^5])\n\n sage: phi.ore_polring()\n Ore Polynomial Ring in t over Finite Field in z12 of size 5^12 over its base twisted by Frob^2\n sage: phi.ore_variable()\n t\n\n ' return self.category().ore_polring().gen()
class DualFunctor(CovariantFunctorialConstruction): '\n A singleton class for the dual functor\n ' _functor_name = 'dual' _functor_category = 'DualObjects' symbol = '^*'
class DualObjectsCategory(CovariantConstructionCategory): _functor_category = 'DualObjects' def _repr_object_names(self): '\n EXAMPLES::\n\n sage: VectorSpaces(QQ).DualObjects() # indirect doctest\n Category of duals of vector spaces over Rational Field\n ' return ('duals of %s' % self.base_category()._repr_object_names())
class EnumeratedSets(CategoryWithAxiom): '\n The category of enumerated sets\n\n An *enumerated set* is a *finite* or *countable* set or multiset `S`\n together with a canonical enumeration of its elements;\n conceptually, this is very similar to an immutable list. The main\n difference lies in the names and the return type of the methods,\n and of course the fact that the list of elements is not supposed to\n be expanded in memory. Whenever possible one should use one of the\n two sub-categories :class:`FiniteEnumeratedSets` or\n :class:`InfiniteEnumeratedSets`.\n\n The purpose of this category is threefold:\n\n - to fix a common interface for all these sets;\n - to provide a bunch of default implementations;\n - to provide consistency tests.\n\n The standard methods for an enumerated set ``S`` are:\n\n - ``S.cardinality()``: the number of elements of the set. This\n is the equivalent for ``len`` on a list except that the\n return value is specified to be a Sage :class:`Integer` or\n ``infinity``, instead of a Python ``int``.\n\n - ``iter(S)``: an iterator for the elements of the set;\n\n - ``S.list()``: a fresh list of the elements of the set, when\n possible; raises a :class:`NotImplementedError` if the list is\n predictably too large to be expanded in memory.\n\n - ``S.tuple()``: a tuple of the elements of the set, when\n possible; raises a :class:`NotImplementedError` if the tuple is\n predictably too large to be expanded in memory.\n\n - ``S.unrank(n)``: the ``n``-th element of the set when ``n`` is a sage\n ``Integer``. This is the equivalent for ``l[n]`` on a list.\n\n - ``S.rank(e)``: the position of the element ``e`` in the set;\n This is equivalent to ``l.index(e)`` for a list except that\n the return value is specified to be a Sage :class:`Integer`,\n instead of a Python ``int``.\n\n - ``S.first()``: the first object of the set; it is equivalent to\n ``S.unrank(0)``.\n\n - ``S.next(e)``: the object of the set which follows ``e``; it is\n equivalent to ``S.unrank(S.rank(e) + 1)``.\n\n - ``S.random_element()``: a random generator for an element of\n the set. Unless otherwise stated, and for finite enumerated\n sets, the probability is uniform.\n\n For examples and tests see:\n\n - ``FiniteEnumeratedSets().example()``\n - ``InfiniteEnumeratedSets().example()``\n\n\n EXAMPLES::\n\n sage: EnumeratedSets()\n Category of enumerated sets\n sage: EnumeratedSets().super_categories()\n [Category of sets]\n sage: EnumeratedSets().all_super_categories()\n [Category of enumerated sets, Category of sets,\n Category of sets with partial maps, Category of objects]\n\n TESTS::\n\n sage: C = EnumeratedSets()\n sage: TestSuite(C).run()\n ' def super_categories(self): '\n EXAMPLES::\n\n sage: EnumeratedSets().super_categories()\n [Category of sets]\n ' return [Sets()] def additional_structure(self): '\n Return ``None``.\n\n Indeed, morphisms of enumerated sets are not required to\n preserve the enumeration.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n EXAMPLES::\n\n sage: EnumeratedSets().additional_structure()\n ' return None def _call_(self, X): '\n Construct an object in this category from the data in ``X``.\n\n EXAMPLES::\n\n sage: EnumeratedSets()(Primes())\n Set of all prime numbers: 2, 3, 5, 7, ...\n\n For now, lists, tuples, sets, Sets are coerced into finite\n enumerated sets::\n\n sage: S = EnumeratedSets()([1, 2, 3]); S\n {1, 2, 3}\n sage: S.category()\n Category of facade finite enumerated sets\n\n sage: S = EnumeratedSets()((1, 2, 3)); S\n {1, 2, 3}\n sage: S = EnumeratedSets()(set([1, 2, 3])); S\n {1, 2, 3}\n sage: S = EnumeratedSets()(Set([1, 2, 3])); S\n {1, 2, 3}\n sage: S.category()\n Category of finite enumerated sets\n\n Also Python3 range are now accepted::\n\n sage: S = EnumeratedSets()(range(4)); S\n {0, 1, 2, 3}\n ' import sage.sets.set if isinstance(X, (tuple, list, set, range, sage.sets.set.Set_object_enumerated)): return sage.sets.finite_enumerated_set.FiniteEnumeratedSet(X) raise NotImplementedError class ParentMethods(): def __iter__(self): '\n An iterator for the enumerated set.\n\n ``iter(self)`` allows the combinatorial class to be treated as an\n iterable. This is the default implementation from the category\n ``EnumeratedSets()``; it just goes through the iterator of the set\n to count the number of objects.\n\n By decreasing order of priority, the second column of the\n following array shows which method is used to define\n ``__iter__``, when the methods of the first column are overloaded:\n\n +------------------------+---------------------------------+\n | Needed methods | Default ``__iterator`` provided |\n +========================+=================================+\n | ``first`` and ``next`` | ``_iterator_from_next`` |\n +------------------------+---------------------------------+\n | ``unrank`` | ``_iterator_from_unrank`` |\n +------------------------+---------------------------------+\n | ``list`` | ``_iterator_from_next`` |\n +------------------------+---------------------------------+\n\n It is also possible to override ``__iter__`` method itself. Then\n the methods of the first column are defined using ``__iter__``\n\n If none of these are provided, this raises\n a :class:`NotImplementedError`.\n\n EXAMPLES:\n\n We start with an example where nothing is implemented::\n\n sage: class broken(UniqueRepresentation, Parent):\n ....: def __init__(self):\n ....: Parent.__init__(self, category = EnumeratedSets())\n sage: it = iter(broken()); [next(it), next(it), next(it)]\n Traceback (most recent call last):\n ...\n NotImplementedError: iterator called but not implemented\n\n Here is what happens when ``first`` and ``next`` are implemented::\n\n sage: class set_first_next(UniqueRepresentation, Parent):\n ....: def __init__(self):\n ....: Parent.__init__(self, category = EnumeratedSets())\n ....: def first(self):\n ....: return 0\n ....: def next(self, elt):\n ....: return elt+1\n sage: it = iter(set_first_next()); [next(it), next(it), next(it)]\n [0, 1, 2]\n\n Let us try with ``unrank``::\n\n sage: class set_unrank(UniqueRepresentation, Parent):\n ....: def __init__(self):\n ....: Parent.__init__(self, category = EnumeratedSets())\n ....: def unrank(self, i):\n ....: return i + 5\n sage: it = iter(set_unrank()); [next(it), next(it), next(it)]\n [5, 6, 7]\n\n Let us finally try with ``list``::\n\n sage: class set_list(UniqueRepresentation, Parent):\n ....: def __init__(self):\n ....: Parent.__init__(self, category = EnumeratedSets())\n ....: def list(self):\n ....: return [5, 6, 7]\n sage: it = iter(set_list()); [next(it), next(it), next(it)]\n [5, 6, 7]\n\n ' if ((self.first != self._first_from_iterator) and (self.next != self._next_from_iterator)): return self._iterator_from_next() elif (self.unrank != self._unrank_from_iterator): return self._iterator_from_unrank() elif (self.list != self._list_default): return self._iterator_from_list() else: raise NotImplementedError('iterator called but not implemented') def is_empty(self): "\n Return whether this set is empty.\n\n EXAMPLES::\n\n sage: F = FiniteEnumeratedSet([1,2,3])\n sage: F.is_empty()\n False\n sage: F = FiniteEnumeratedSet([])\n sage: F.is_empty()\n True\n\n TESTS::\n\n sage: F.is_empty.__module__\n 'sage.categories.enumerated_sets'\n " try: next(iter(self)) except StopIteration: return True else: return False def iterator_range(self, start=None, stop=None, step=None): '\n Iterate over the range of elements of ``self`` starting\n at ``start``, ending at ``stop``, and stepping by ``step``.\n\n .. SEEALSO::\n\n ``unrank()``, ``unrank_range()``\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: P = Partitions()\n sage: list(P.iterator_range(stop=5))\n [[], [1], [2], [1, 1], [3]]\n sage: list(P.iterator_range(0, 5))\n [[], [1], [2], [1, 1], [3]]\n sage: list(P.iterator_range(3, 5))\n [[1, 1], [3]]\n sage: list(P.iterator_range(3, 10))\n [[1, 1], [3], [2, 1], [1, 1, 1], [4], [3, 1], [2, 2]]\n sage: list(P.iterator_range(3, 10, 2))\n [[1, 1], [2, 1], [4], [2, 2]]\n sage: it = P.iterator_range(3)\n sage: [next(it) for x in range(10)]\n [[1, 1],\n [3], [2, 1], [1, 1, 1],\n [4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1],\n [5]]\n sage: it = P.iterator_range(3, step=2)\n sage: [next(it) for x in range(5)]\n [[1, 1],\n [2, 1],\n [4], [2, 2], [1, 1, 1, 1]]\n sage: next(P.iterator_range(stop=-3))\n Traceback (most recent call last):\n ...\n NotImplementedError: cannot list an infinite set\n sage: next(P.iterator_range(start=-3))\n Traceback (most recent call last):\n ...\n NotImplementedError: cannot list an infinite set\n ' if (stop is None): if (start is None): if (step is None): (yield from self) return start = 0 elif (start < 0): (yield from self.tuple()[start::step]) return if (step is None): step = 1 while True: try: (yield self.unrank(start)) except ValueError: return start += step elif (stop < 0): (yield from self.tuple()[start:stop:step]) return if (start is None): if (step is None): it = self.__iter__() for j in range(stop): (yield next(it)) return start = 0 elif (start < 0): (yield from self.tuple()[start:stop:step]) if (step is None): step = 1 for j in range(start, stop, step): (yield self.unrank(j)) def unrank_range(self, start=None, stop=None, step=None): '\n Return the range of elements of ``self`` starting at ``start``,\n ending at ``stop``, and stepping by ``step``.\n\n .. SEEALSO::\n\n ``unrank()``, ``iterator_range()``\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: P = Partitions()\n sage: P.unrank_range(stop=5)\n [[], [1], [2], [1, 1], [3]]\n sage: P.unrank_range(0, 5)\n [[], [1], [2], [1, 1], [3]]\n sage: P.unrank_range(3, 5)\n [[1, 1], [3]]\n sage: P.unrank_range(3, 10)\n [[1, 1], [3], [2, 1], [1, 1, 1], [4], [3, 1], [2, 2]]\n sage: P.unrank_range(3, 10, 2)\n [[1, 1], [2, 1], [4], [2, 2]]\n sage: P.unrank_range(3)\n Traceback (most recent call last):\n ...\n NotImplementedError: cannot list an infinite set\n sage: P.unrank_range(stop=-3)\n Traceback (most recent call last):\n ...\n NotImplementedError: cannot list an infinite set\n sage: P.unrank_range(start=-3)\n Traceback (most recent call last):\n ...\n NotImplementedError: cannot list an infinite set\n ' if (stop is None): return list(self.tuple()[start::step]) if (stop < 0): return list(self.tuple()[start:stop:step]) if ((start is not None) and (start < 0)): return list(self.tuple()[start:stop:step]) return list(self.iterator_range(start, stop, step)) def __getitem__(self, i): '\n Return the item indexed by ``i``.\n\n .. WARNING::\n\n This method is only meant as a convenience shorthand for\n ``self.unrank(i)`` and\n ``self.unrank_range(start, stop, step)`` respectively, for\n casual use (e.g. in interactive sessions). Subclasses are\n hereby explicitly permitted to overload ``__getitem__``\n with a different semantic, typically for enumerated sets\n that are naturally indexed by some `I` not of the\n form `\\{0, 1, \\ldots\\}`. In particular, generic code\n *should not* use this shorthand.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: P = Partitions()\n sage: P[:5]\n [[], [1], [2], [1, 1], [3]]\n sage: P[0:5]\n [[], [1], [2], [1, 1], [3]]\n sage: P[3:5]\n [[1, 1], [3]]\n sage: P[3:10]\n [[1, 1], [3], [2, 1], [1, 1, 1], [4], [3, 1], [2, 2]]\n sage: P[3:10:2]\n [[1, 1], [2, 1], [4], [2, 2]]\n sage: P[3:]\n Traceback (most recent call last):\n ...\n NotImplementedError: cannot list an infinite set\n sage: P[3]\n [1, 1]\n sage: P[-1]\n Traceback (most recent call last):\n ...\n NotImplementedError: cannot list an infinite set\n\n ::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C.list()\n [1, 2, 3]\n sage: C[1]\n 2\n sage: C[:]\n [1, 2, 3]\n sage: C[1:]\n [2, 3]\n sage: C[0:1:2]\n [1]\n\n sage: F = FiniteEnumeratedSet([1,2,3])\n sage: F[1:]\n [2, 3]\n sage: F[:2]\n [1, 2]\n sage: F[:2:2]\n [1]\n sage: F[1::2]\n [2]\n ' if isinstance(i, slice): return self.unrank_range(i.start, i.stop, i.step) if (i < 0): return self.list()[i] return self.unrank(i) def __len__(self): '\n Return the number of elements of ``self``.\n\n EXAMPLES::\n\n sage: len(GF(5))\n 5\n sage: len(MatrixSpace(GF(2), 3, 3)) # needs sage.modules\n 512\n ' from sage.rings.infinity import Infinity try: c = self.cardinality() if (c is Infinity): raise NotImplementedError('infinite set') return int(c) except AttributeError: return len(self.tuple()) def tuple(self): '\n Return a tuple of the elements of ``self``.\n\n The tuple of elements of ``x`` is created and cached on the first call\n of ``x.tuple()``. Each following call of ``x.tuple()`` returns the same tuple.\n\n For looping, it may be better to do ``for e in x:``, not ``for e in x.tuple():``.\n\n If ``x`` is not known to be finite, then an exception is raised.\n\n EXAMPLES::\n\n sage: (GF(3)^2).tuple() # needs sage.modules\n ((0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (2, 2))\n sage: R = Integers(11)\n sage: l = R.tuple(); l\n (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n sage: l is R.tuple()\n True\n ' try: if (self._list is not None): return self._tuple_from_list() except AttributeError: pass if (self.list != self._list_default): return tuple(self.list()) from sage.rings.infinity import Infinity try: if (self.cardinality() is Infinity): raise NotImplementedError('cannot list an infinite set') else: return self._tuple_from_iterator() except AttributeError: raise NotImplementedError('unknown cardinality') _tuple_default = tuple def _tuple_from_iterator(self): '\n Return a tuple of the elements of ``self``.\n\n This implementation of :meth:`tuple` creates the tuple of elements and caches it for\n later uses.\n\n TESTS::\n\n sage: R = Integers(11)\n sage: R._list is None\n False\n sage: R._tuple_from_iterator()\n (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n sage: _ is R._list\n True\n ' self._list_from_iterator() return self._tuple_from_list() def _tuple_from_list(self): '\n Return a tuple of the elements of ``self``.\n\n This implementation of :meth:`tuple` assumes that the tuple of elements is already\n cached and just returns it.\n\n TESTS::\n\n sage: R = Integers(11)\n sage: R.tuple()\n (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n sage: R._tuple_from_list() is R.tuple()\n True\n ' return tuple(self._list) def list(self): '\n Return a list of the elements of ``self``.\n\n The elements of set ``x`` are created and cached on the first call\n of ``x.list()``. Then each call of ``x.list()`` returns a new list\n from the cached result. Thus in looping, it may be better to do\n ``for e in x:``, not ``for e in x.list():``.\n\n If ``x`` is not known to be finite, then an exception is raised.\n\n EXAMPLES::\n\n sage: (GF(3)^2).list() # needs sage.modules\n [(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (2, 2)]\n sage: R = Integers(11)\n sage: R.list()\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n sage: l = R.list(); l\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n sage: l.remove(0); l\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n sage: R.list()\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C.list()\n [1, 2, 3]\n ' return list(self.tuple()) _list_default = list def _list_from_iterator(self): "\n Return a list of the elements of ``self`` after cached.\n\n TESTS:\n\n Trying to list an infinite vector space raises an error\n instead of running forever (see :trac:`10470`)::\n\n sage: (QQ^2).list() # indirect test # needs sage.modules\n Traceback (most recent call last):\n ...\n AttributeError: 'FreeModule_ambient_field_with_category' object has no attribute 'list'...\n\n Here we test that for an object that does not know whether it\n is finite or not. Calling ``x.list()`` simply tries to create\n the list (but here it fails, since the object is not\n iterable). This was fixed :trac:`11350` ::\n\n sage: R.<t,p> = QQ[]\n sage: Q = R.quotient(t^2-t+1)\n sage: Q.is_finite()\n Traceback (most recent call last):\n ...\n AttributeError: 'QuotientRing_generic_with_category' object has no attribute 'is_finite'...\n sage: Q.list() # indirect test\n Traceback (most recent call last):\n ...\n AttributeError: 'QuotientRing_generic_with_category' object has no attribute 'list'...\n\n Here is another example. We artificially create a version of\n the ring of integers that does not know whether it is finite\n or not::\n\n sage: from sage.rings.integer_ring import IntegerRing_class\n sage: class MyIntegers_class(IntegerRing_class):\n ....: def is_finite(self):\n ....: raise NotImplementedError\n sage: MyIntegers = MyIntegers_class()\n sage: MyIntegers.is_finite()\n Traceback (most recent call last):\n ...\n NotImplementedError\n\n Asking for ``list(MyIntegers)`` will also raise an exception::\n\n sage: list(MyIntegers) # indirect test\n Traceback (most recent call last):\n ...\n NotImplementedError\n " try: if (self._list is not None): return list(self._list) except AttributeError: pass result = tuple(self.__iter__()) try: self._list = result except AttributeError: pass return list(result) def _first_from_iterator(self): '\n The "first" element of ``self``.\n\n ``self.first()`` returns the first element of the set\n ``self``. This is a generic implementation from the category\n ``EnumeratedSets()`` which can be used when the method ``__iter__`` is\n provided.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C.first() # indirect doctest\n 1\n ' return next(iter(self)) first = _first_from_iterator def _next_from_iterator(self, obj): '\n The "next" element after ``obj`` in ``self``.\n\n ``self.next(e)`` returns the element of the set ``self`` which\n follows ``e``. This is a generic implementation from the category\n ``EnumeratedSets()`` which can be used when the method ``__iter__``\n is provided.\n\n Remark: this is the default (brute force) implementation\n of the category ``EnumeratedSets()``. Its complexity is\n `O(r)`, where `r` is the rank of ``obj``.\n\n EXAMPLES::\n\n sage: C = InfiniteEnumeratedSets().example()\n sage: C._next_from_iterator(10) # indirect doctest\n 11\n\n TODO: specify the behavior when ``obj`` is not in ``self``.\n ' it = iter(self) el = next(it) while (el != obj): el = next(it) return next(it) next = _next_from_iterator def _unrank_from_iterator(self, r): '\n The ``r``-th element of ``self``\n\n ``self.unrank(r)`` returns the ``r``-th element of ``self``, where\n ``r`` is an integer between ``0`` and ``n-1`` where ``n`` is the\n cardinality of ``self``.\n\n This is the default (brute force) implementation from the\n category ``EnumeratedSets()`` which can be used when the\n method ``__iter__`` is provided. Its complexity is `O(r)`,\n where `r` is the rank of ``obj``.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C.unrank(2) # indirect doctest\n 3\n sage: C._unrank_from_iterator(5)\n Traceback (most recent call last):\n ...\n ValueError: the rank must be in the range from 0 to 2\n sage: ZZ._unrank_from_iterator(-1)\n Traceback (most recent call last):\n ...\n ValueError: the rank must be greater than or equal to 0\n ' from sage.rings.integer_ring import ZZ if (r < 0): raise ValueError('the rank must be greater than or equal to 0') if (r not in ZZ): raise ValueError(f'r={r!r} must be an integer') for (counter, u) in enumerate(self): if (counter == r): return u raise ValueError(('the rank must be in the range from %s to %s' % (0, counter))) unrank = _unrank_from_iterator def _rank_from_iterator(self, x): "\n The rank of an element of ``self``\n\n ``self.rank(x)`` returns the rank of `x`, that is its\n position in the enumeration of ``self``. This is an\n integer between ``0`` and ``n-1`` where ``n`` is the\n cardinality of ``self``, or None if `x` is not in `self`.\n\n This is the default (brute force) implementation from the\n category ``EnumeratedSets()`` which can be used when the\n method ``__iter__`` is provided. Its complexity is `O(r)`,\n where `r` is the rank of ``obj``. For infinite enumerated\n sets, this won't terminate when `x` is not in ``self``\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: list(C)\n [1, 2, 3]\n sage: C.rank(3) # indirect doctest\n 2\n sage: C.rank(5) # indirect doctest\n " counter = 0 for u in self: if (u == x): return counter counter += 1 return None rank = _rank_from_iterator def _iterator_from_list(self): '\n An iterator for the elements of ``self``.\n\n ``iter(self)`` returns an iterator for the elements\n of ``self``. This is a generic implementation from the\n category ``EnumeratedSets()`` which can be used when the\n method ``list`` is provided.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: it = C._iterator_from_list()\n sage: [next(it), next(it), next(it)]\n [1, 2, 3]\n ' (yield from self.tuple()) def _iterator_from_next(self): '\n An iterator for the elements of ``self``.\n\n ``iter(self)`` returns an iterator for the element of\n the set ``self``. This is a generic implementation from\n the category ``EnumeratedSets()`` which can be used when\n the methods ``first`` and ``next`` are provided.\n\n EXAMPLES::\n\n sage: C = InfiniteEnumeratedSets().example()\n sage: it = C._iterator_from_next()\n sage: [next(it), next(it), next(it), next(it), next(it)]\n [0, 1, 2, 3, 4]\n ' f = self.first() while (not ((f is None) or (f is False))): (yield f) try: f = self.next(f) except (TypeError, ValueError): f = None def _iterator_from_unrank(self): '\n An iterator for the elements of ``self``.\n\n ``iter(self)`` returns an iterator for the elements\n of the set ``self``. This is a generic implementation from\n the category ``EnumeratedSets()`` which can be used when\n the method ``unrank`` is provided.\n\n EXAMPLES::\n\n sage: C = InfiniteEnumeratedSets().example()\n sage: it = C._iterator_from_unrank()\n sage: [next(it), next(it), next(it), next(it), next(it)]\n [0, 1, 2, 3, 4]\n ' r = 0 try: u = self.unrank(r) except (TypeError, ValueError, IndexError): return (yield u) while True: r += 1 try: u = self.unrank(r) except (TypeError, ValueError, IndexError): break if (u is None): break else: (yield u) @cached_method def _an_element_from_iterator(self): '\n Return the first element of ``self`` returned by :meth:`__iter__`\n\n If ``self`` is empty, the exception\n :class:`~sage.categories.sets_cat.EmptySetError` is raised instead.\n\n This provides a generic implementation of the method\n :meth:`_an_element_` for all parents in :class:`EnumeratedSets`.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example(); C\n An example of a finite enumerated set: {1,2,3}\n sage: C.an_element() # indirect doctest\n 1\n sage: S = Set([])\n sage: S.an_element()\n Traceback (most recent call last):\n ...\n EmptySetError\n\n TESTS::\n\n sage: super(Parent, C)._an_element_\n Cached version of <function ..._an_element_from_iterator at ...>\n ' it = iter(self) try: return next(it) except StopIteration: raise EmptySetError _an_element_ = _an_element_from_iterator def _some_elements_from_iterator(self): '\n Return some elements in ``self``.\n\n See :class:`TestSuite` for a typical use case.\n\n This is a generic implementation from the category\n ``EnumeratedSets()`` which can be used when the method\n ``__iter__`` is provided. It returns an iterator for up to\n the first 100 elements of ``self``\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: list(C.some_elements()) # indirect doctest\n [1, 2, 3]\n ' nb = 0 for i in self: (yield i) nb += 1 if (nb >= 100): break some_elements = _some_elements_from_iterator def random_element(self): '\n Return a random element in ``self``.\n\n Unless otherwise stated, and for finite enumerated sets,\n the probability is uniform.\n\n This is a generic implementation from the category\n ``EnumeratedSets()``. It raises a :class:`NotImplementedError`\n since one does not know whether the set is finite.\n\n EXAMPLES::\n\n sage: class broken(UniqueRepresentation, Parent):\n ....: def __init__(self):\n ....: Parent.__init__(self, category = EnumeratedSets())\n sage: broken().random_element()\n Traceback (most recent call last):\n ...\n NotImplementedError: unknown cardinality\n ' raise NotImplementedError('unknown cardinality') def map(self, f, name=None, *, is_injective=True): "\n Return the image `\\{f(x) | x \\in \\text{self}\\}` of this\n enumerated set by `f`, as an enumerated set.\n\n INPUT:\n\n - ``is_injective`` -- boolean (default: ``True``) whether to assume\n that ``f`` is injective.\n\n EXAMPLES::\n\n sage: R = Compositions(4).map(attrcall('partial_sums')); R\n Image of Compositions of 4 by The map *.partial_sums()\n from Compositions of 4\n sage: R.cardinality()\n 8\n sage: R.list()\n [[1, 2, 3, 4], [1, 2, 4], [1, 3, 4], [1, 4], [2, 3, 4], [2, 4], [3, 4], [4]]\n sage: [r for r in R]\n [[1, 2, 3, 4], [1, 2, 4], [1, 3, 4], [1, 4], [2, 3, 4], [2, 4], [3, 4], [4]]\n sage: R.category()\n Category of finite enumerated subobjects of sets\n\n .. WARNING::\n\n If the function is not injective, then there may be\n repeated elements::\n\n sage: P = Compositions(4)\n sage: P.list()\n [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2, 2], [3, 1], [4]]\n sage: P.map(attrcall('major_index')).list()\n [6, 3, 4, 1, 5, 2, 3, 0]\n\n Pass ``is_injective=False`` to get a correct result in this case::\n\n sage: P.map(attrcall('major_index'), is_injective=False).list()\n [6, 3, 4, 1, 5, 2, 0]\n\n TESTS::\n\n sage: TestSuite(R).run(skip=['_test_an_element',\n ....: '_test_enumerated_set_contains',\n ....: '_test_some_elements'])\n " from sage.combinat.combinat import MapCombinatorialClass return MapCombinatorialClass(self, f, name, is_injective=is_injective) def _test_enumerated_set_contains(self, **options): '\n Checks that the methods :meth:`.__contains__` and :meth:`.__iter__` are consistent.\n\n See also :class:`TestSuite`.\n\n TESTS::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C._test_enumerated_set_contains()\n sage: TestSuite(C).run()\n\n Let us now break the class::\n\n sage: from sage.categories.examples.finite_enumerated_sets import Example\n sage: class CCls(Example):\n ....: def __contains__(self, obj):\n ....: if obj == 3:\n ....: return False\n ....: else:\n ....: return obj in C\n sage: CC = CCls()\n sage: CC._test_enumerated_set_contains()\n Traceback (most recent call last):\n ...\n AssertionError: 3 not found in An example\n of a finite enumerated set: {1,2,3}\n ' tester = self._tester(**options) i = 0 for w in self: tester.assertIn(w, self) i += 1 if (i > tester._max_runs): return def _test_enumerated_set_iter_list(self, **options): '\n Checks that the methods :meth:`.list` and :meth:`.__iter__` are consistent.\n\n See also: :class:`TestSuite`.\n\n .. NOTE::\n\n This test does nothing if the cardinality of the set\n is larger than the max_runs argument.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C._test_enumerated_set_iter_list()\n sage: TestSuite(C).run()\n\n Let us now break the class::\n\n sage: from sage.categories.examples.finite_enumerated_sets import Example\n sage: class CCls(Example):\n ....: def list(self):\n ....: return [1,2,3,4]\n sage: CC = CCls()\n sage: CC._test_enumerated_set_iter_list()\n Traceback (most recent call last):\n ...\n AssertionError: 3 != 4\n\n For a large enumerated set this test does nothing:\n increase tester._max_runs if you want to actually run the\n test::\n\n sage: class CCls(Example):\n ....: def list(self):\n ....: return [1,2,3]\n sage: CC = CCls()\n sage: CC._test_enumerated_set_iter_list(verbose=True,max_runs=2)\n Enumerated set too big; skipping test; increase tester._max_runs\n ' tester = self._tester(**options) if (self.list != self._list_default): if (self.cardinality() > tester._max_runs): tester.info('Enumerated set too big; skipping test; increase tester._max_runs') return ls = self.list() i = 0 for obj in self: tester.assertEqual(obj, ls[i]) i += 1 tester.assertEqual(i, len(ls)) class ElementMethods(): def rank(self): "\n Return the rank of ``self`` in its parent.\n\n See also :meth:`EnumeratedSets.ElementMethods.rank`\n\n EXAMPLES::\n\n sage: F = FiniteSemigroups().example(('a','b','c'))\n sage: L = list(F)\n sage: L[7].rank()\n 7\n sage: all(x.rank() == i for i,x in enumerate(L))\n True\n " return self.parent().rank(self) Finite = LazyImport('sage.categories.finite_enumerated_sets', 'FiniteEnumeratedSets', at_startup=True) Infinite = LazyImport('sage.categories.infinite_enumerated_sets', 'InfiniteEnumeratedSets', at_startup=True) class CartesianProducts(CartesianProductsCategory): class ParentMethods(): def first(self): '\n Return the first element.\n\n EXAMPLES::\n\n sage: cartesian_product([ZZ]*10).first()\n (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)\n ' return self._cartesian_product_of_elements(tuple((c.first() for c in self.cartesian_factors())))
class EuclideanDomains(Category_singleton): '\n The category of constructive euclidean domains, i.e., one can divide\n producing a quotient and a remainder where the remainder is either zero or\n its :meth:`ElementMethods.euclidean_degree` is smaller than the divisor.\n\n EXAMPLES::\n\n sage: EuclideanDomains()\n Category of euclidean domains\n sage: EuclideanDomains().super_categories()\n [Category of principal ideal domains]\n\n TESTS::\n\n sage: TestSuite(EuclideanDomains()).run()\n\n ' def super_categories(self): '\n EXAMPLES::\n\n sage: EuclideanDomains().super_categories()\n [Category of principal ideal domains]\n ' return [PrincipalIdealDomains()] class ParentMethods(): def is_euclidean_domain(self): '\n Return True, since this in an object of the category of Euclidean domains.\n\n EXAMPLES::\n\n sage: Parent(QQ,category=EuclideanDomains()).is_euclidean_domain()\n True\n\n ' return True def gcd_free_basis(self, elts): '\n Compute a set of coprime elements that can be used to express the\n elements of ``elts``.\n\n INPUT:\n\n - ``elts`` - A sequence of elements of ``self``.\n\n OUTPUT:\n\n A GCD-free basis (also called a coprime base) of ``elts``; that is,\n a set of pairwise relatively prime elements of ``self`` such that\n any element of ``elts`` can be written as a product of elements of\n the set.\n\n ALGORITHM:\n\n Naive implementation of the algorithm described in Section 4.8 of\n Bach & Shallit [BS1996]_.\n\n EXAMPLES::\n\n sage: ZZ.gcd_free_basis([1])\n []\n sage: ZZ.gcd_free_basis([4, 30, 14, 49])\n [2, 15, 7]\n\n sage: Pol.<x> = QQ[]\n sage: sorted(Pol.gcd_free_basis([\n ....: (x+1)^3*(x+2)^3*(x+3), (x+1)*(x+2)*(x+3),\n ....: (x+1)*(x+2)*(x+4)]))\n [x + 3, x + 4, x^2 + 3*x + 2]\n\n TESTS::\n\n sage: R.<x> = QQ[]\n sage: QQ.gcd_free_basis([x+1,x+2])\n Traceback (most recent call last):\n ...\n TypeError: unable to convert x + 1 to an element of Rational Field\n ' def refine(a, b): g = a.gcd(b) if g.is_unit(): return (a, set(), b) (l1, s1, r1) = refine((a // g), g) (l2, s2, r2) = refine(r1, (b // g)) s1.update(s2) s1.add(l2) return (l1, s1, r2) elts = Sequence(elts, universe=self) res = set() if (len(elts) == 1): res.update(elts) else: r = elts[(- 1)] for t in self.gcd_free_basis(elts[:(- 1)]): (l, s, r) = refine(t, r) res.update(s) res.add(l) res.add(r) units = [x for x in res if x.is_unit()] res.difference_update(units) return Sequence(res, universe=self, check=False) def _test_euclidean_degree(self, **options): '\n Test that the assumptions on an Euclidean degree are met.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: R._test_euclidean_degree()\n\n .. SEEALSO::\n\n :meth:`_test_quo_rem`\n ' tester = self._tester(**options) S = [s for s in tester.some_elements() if (not s.is_zero())] min_degree = self.one().euclidean_degree() from sage.rings.semirings.non_negative_integer_semiring import NN for a in S: tester.assertIn(a.euclidean_degree(), NN) tester.assertGreaterEqual(a.euclidean_degree(), min_degree) tester.assertEqual((a.euclidean_degree() == min_degree), a.is_unit()) from sage.misc.misc import some_tuples for (a, b) in some_tuples(S, 2, tester._max_runs): p = (a * b) if p.is_zero(): continue tester.assertLessEqual(a.euclidean_degree(), p.euclidean_degree()) def _test_quo_rem(self, **options): '\n Test that the assumptions on a quotient with remainder of an\n euclidean domain are met.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: R._test_quo_rem()\n\n .. SEEALSO::\n\n :meth:`_test_euclidean_degree`\n ' tester = self._tester(**options) S = tester.some_elements() from sage.misc.misc import some_tuples for (a, b) in some_tuples(S, 2, tester._max_runs): if b.is_zero(): tester.assertRaises(ZeroDivisionError, (lambda : a.quo_rem(b))) else: (q, r) = a.quo_rem(b) tester.assertIn(q, self) tester.assertIn(r, self) tester.assertEqual(a, ((q * b) + r)) if (r != 0): tester.assertLess(r.euclidean_degree(), b.euclidean_degree()) class ElementMethods(): @abstract_method def euclidean_degree(self): '\n Return the degree of this element as an element of an Euclidean\n domain, i.e., for elements `a`, `b` the euclidean degree `f`\n satisfies the usual properties:\n\n 1. if `b` is not zero, then there are elements `q` and `r` such\n that `a = bq + r` with `r = 0` or `f(r) < f(b)`\n 2. if `a,b` are not zero, then `f(a) \\leq f(ab)`\n\n .. NOTE::\n\n The name ``euclidean_degree`` was chosen because the euclidean\n function has different names in different contexts, e.g.,\n absolute value for integers, degree for polynomials.\n\n OUTPUT:\n\n For non-zero elements, a natural number. For the zero element, this\n might raise an exception or produce some other output, depending on\n the implementation.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: x.euclidean_degree()\n 1\n sage: ZZ.one().euclidean_degree()\n 1\n ' @coerce_binop def gcd(self, other): '\n Return the greatest common divisor of this element and ``other``.\n\n INPUT:\n\n - ``other`` -- an element in the same ring as ``self``\n\n ALGORITHM:\n\n Algorithm 3.2.1 in [Coh1993]_.\n\n EXAMPLES::\n\n sage: R.<x> = PolynomialRing(QQ, sparse=True)\n sage: EuclideanDomains().element_class.gcd(x,x+1)\n -1\n ' A = self B = other while (not B.is_zero()): (Q, R) = A.quo_rem(B) A = B B = R return A @abstract_method def quo_rem(self, other): '\n Return the quotient and remainder of the division of this element\n by the non-zero element ``other``.\n\n INPUT:\n\n - ``other`` -- an element in the same euclidean domain\n\n OUTPUT:\n\n a pair of elements\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: x.quo_rem(x)\n (1, 0)\n '
class FreeAlgebra(CombinatorialFreeModule): '\n An example of an algebra with basis: the free algebra\n\n This class illustrates a minimal implementation of an algebra with basis.\n ' def __init__(self, R, alphabet=('a', 'b', 'c')): "\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).example(); A # needs sage.modules\n An example of an algebra with basis: the free algebra on the generators ('a', 'b', 'c') over Rational Field\n sage: TestSuite(A).run() # needs sage.modules\n\n " self._alphabet = alphabet CombinatorialFreeModule.__init__(self, R, Words(alphabet, infinite=False), category=AlgebrasWithBasis(R)) def _repr_(self): "\n EXAMPLES::\n\n sage: AlgebrasWithBasis(QQ).example() # indirect doctest # needs sage.modules\n An example of an algebra with basis: the free algebra on the generators ('a', 'b', 'c') over Rational Field\n " return ('An example of an algebra with basis: the free algebra on the generators %s over %s' % (self._alphabet, self.base_ring())) @cached_method def one_basis(self): '\n Returns the empty word, which index the one of this algebra,\n as per :meth:`AlgebrasWithBasis.ParentMethods.one_basis`.\n\n EXAMPLES::r\n\n sage: A = AlgebrasWithBasis(QQ).example() # needs sage.modules\n sage: A.one_basis() # needs sage.modules\n word:\n sage: A.one() # needs sage.modules\n B[word: ]\n ' return self.basis().keys()([]) def product_on_basis(self, w1, w2): '\n Product of basis elements, as per\n :meth:`AlgebrasWithBasis.ParentMethods.product_on_basis`.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: A = AlgebrasWithBasis(QQ).example()\n sage: Words = A.basis().keys()\n sage: A.product_on_basis(Words("acb"), Words("cba"))\n B[word: acbcba]\n sage: (a,b,c) = A.algebra_generators()\n sage: a * (1-b)^2 * c\n B[word: abbc] - 2*B[word: abc] + B[word: ac]\n ' return self.basis()[(w1 + w2)] @cached_method def algebra_generators(self): "\n Return the generators of this algebra, as per :meth:`~.magmatic_algebras.MagmaticAlgebras.ParentMethods.algebra_generators`.\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).example(); A # needs sage.modules\n An example of an algebra with basis: the free algebra on the generators ('a', 'b', 'c') over Rational Field\n sage: A.algebra_generators() # needs sage.modules\n Family (B[word: a], B[word: b], B[word: c])\n " Words = self.basis().keys() return Family([self.monomial(Words(a)) for a in self._alphabet])
class FreeCommutativeAdditiveMonoid(FreeCommutativeAdditiveSemigroup): "\n An example of a commutative additive monoid: the free commutative monoid\n\n This class illustrates a minimal implementation of a commutative monoid.\n\n EXAMPLES::\n\n sage: S = CommutativeAdditiveMonoids().example(); S\n An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c', 'd')\n\n sage: S.category()\n Category of commutative additive monoids\n\n This is the free semigroup generated by::\n\n sage: S.additive_semigroup_generators()\n Family (a, b, c, d)\n\n with product rule given by `a \\times b = a` for all `a, b`::\n\n sage: (a,b,c,d) = S.additive_semigroup_generators()\n\n We conclude by running systematic tests on this commutative monoid::\n\n sage: TestSuite(S).run(verbose = True)\n running ._test_additive_associativity() . . . pass\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_nonzero_equal() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n running ._test_zero() . . . pass\n " def __init__(self, alphabet=('a', 'b', 'c', 'd')): "\n The free commutative monoid\n\n INPUT:\n\n - ``alphabet`` -- a tuple of strings: the generators of the monoid\n\n EXAMPLES::\n\n sage: M = CommutativeAdditiveMonoids().example(alphabet=('a','b','c')); M\n An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c')\n\n TESTS::\n\n sage: TestSuite(M).run()\n\n " self.alphabet = alphabet Parent.__init__(self, category=CommutativeAdditiveMonoids()) def _repr_(self): '\n TESTS::\n\n sage: M = CommutativeAdditiveMonoids().example(alphabet=(\'a\',\'b\',\'c\'))\n sage: M._repr_()\n "An example of a commutative monoid: the free commutative monoid generated by (\'a\', \'b\', \'c\')"\n\n ' return ('An example of a commutative monoid: the free commutative monoid generated by %s' % (self.alphabet,)) @cached_method def zero(self): "\n Returns the zero of this additive monoid, as per :meth:`CommutativeAdditiveMonoids.ParentMethods.zero`.\n\n EXAMPLES::\n\n sage: M = CommutativeAdditiveMonoids().example(); M\n An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c', 'd')\n sage: M.zero()\n 0\n " return self(()) class Element(FreeCommutativeAdditiveSemigroup.Element): def __bool__(self) -> bool: '\n Check if ``self`` is not the zero of the monoid\n\n EXAMPLES::\n\n sage: M = CommutativeAdditiveMonoids().example()\n sage: bool(M.zero())\n False\n sage: [bool(m) for m in M.additive_semigroup_generators()]\n [True, True, True, True]\n ' return any(self.value.values())