code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
import sage.combinat.root_system.weyl_characters from sage.combinat.root_system.root_system import RootSystem from sage.matrix.constructor import matrix from sage.misc.flatten import flatten from sage.structure.sage_object import SageObject from sage.combinat.root_system.cartan_type import CartanType from sage.modules.free_module_element import vector from sage.rings.rational_field import QQ from sage.misc.functional import is_even, is_odd def branch_weyl_character(chi, R, S, rule="default"): r""" A branching rule describes the restriction of representations from a Lie group or algebra `G` to a subgroup `H`. See for example, R. C. King, Branching rules for classical Lie groups using tensor and spinor methods. J. Phys. A 8 (1975), 429-449, Howe, Tan and Willenbring, Stable branching rules for classical symmetric pairs, Trans. Amer. Math. Soc. 357 (2005), no. 4, 1601-1626, McKay and Patera, Tables of Dimensions, Indices and Branching Rules for Representations of Simple Lie Algebras (Marcel Dekker, 1981), and Fauser, Jarvis, King and Wybourne, New branching rules induced by plethysm. J. Phys. A 39 (2006), no. 11, 2611--2655. If `H\subset G` we will write `G\Rightarrow H` to denote the branching rule, which is a homomorphism of WeylCharacterRings. INPUT: - ``chi`` -- a character of `G` - ``R`` -- the Weyl Character Ring of `G` - ``S`` -- the Weyl Character Ring of `H` - ``rule`` -- an element of the ``BranchingRule`` class or one (most usually) a keyword such as: * ``"levi"`` * ``"automorphic"`` * ``"symmetric"`` * ``"extended"`` * ``"orthogonal_sum"`` * ``"tensor"`` * ``"triality"`` * ``"miscellaneous"`` The ``BranchingRule`` class is a wrapper for functions from the weight lattice of `G` to the weight lattice of `H`. An instance of this class encodes an embedding of `H` into `G`. The usual way to specify an embedding is to supply a keyword, which tells Sage to use one of the built-in rules. We will discuss these first. To explain the predefined rules, we survey the most important branching rules. These may be classified into several cases, and once this is understood, the detailed classification can be read off from the Dynkin diagrams. Dynkin classified the maximal subgroups of Lie groups in Mat. Sbornik N.S. 30(72):349-462 (1952). We will list give predefined rules that cover most cases where the branching rule is to a maximal subgroup. For convenience, we also give some branching rules to subgroups that are not maximal. For example, a Levi subgroup may or may not be maximal. For example, there is a "levi" branching rule defined from `SL(5)` (with Cartan type `A_4`) to `SL(4)` (with Cartan type `A_3`), so we may compute the branching rule as follows: EXAMPLES:: sage: A3=WeylCharacterRing("A3",style="coroots") sage: A2=WeylCharacterRing("A2",style="coroots") sage: [A3(fw).branch(A2,rule="levi") for fw in A3.fundamental_weights()] [A2(0,0) + A2(1,0), A2(0,1) + A2(1,0), A2(0,0) + A2(0,1)] In this case the Levi branching rule is the default branching rule so we may omit the specification rule="levi". If a subgroup is not maximal, you may specify a branching rule by finding a chain of intermediate subgroups. For this purpose, branching rules may be multiplied as in the following example. EXAMPLES:: sage: A4=WeylCharacterRing("A4",style="coroots") sage: A2=WeylCharacterRing("A2",style="coroots") sage: br=branching_rule("A4","A3")*branching_rule("A3","A2") sage: A4(1,0,0,0).branch(A2,rule=br) 2*A2(0,0) + A2(1,0) You may try omitting the rule if it is "obvious". Default rules are provided for the following cases: .. MATH:: \begin{aligned} A_{2s} & \Rightarrow B_s, \\ A_{2s-1} & \Rightarrow C_s, \\ A_{2*s-1} & \Rightarrow D_s. \end{aligned} The above default rules correspond to embedding the group `SO(2s+1)`, `Sp(2s)` or `SO(2s)` into the corresponding general or special linear group by the standard representation. Default rules are also specified for the following cases: .. MATH:: \begin{aligned} B_{s+1} & \Rightarrow D_s, \\ D_s & \Rightarrow B_s. \end{aligned} These correspond to the embedding of `O(n)` into `O(n+1)` where `n = 2s` or `2s + 1`. Finally, the branching rule for the embedding of a Levi subgroup is also implemented as a default rule. EXAMPLES:: sage: A1 = WeylCharacterRing("A1", style="coroots") sage: A2 = WeylCharacterRing("A2", style="coroots") sage: D4 = WeylCharacterRing("D4", style="coroots") sage: B3 = WeylCharacterRing("B3", style="coroots") sage: B4 = WeylCharacterRing("B4", style="coroots") sage: A6 = WeylCharacterRing("A6", style="coroots") sage: A7 = WeylCharacterRing("A7", style="coroots") sage: def try_default_rule(R,S): return [R(f).branch(S) for f in R.fundamental_weights()] sage: try_default_rule(A2,A1) [A1(0) + A1(1), A1(0) + A1(1)] sage: try_default_rule(D4,B3) [B3(0,0,0) + B3(1,0,0), B3(1,0,0) + B3(0,1,0), B3(0,0,1), B3(0,0,1)] sage: try_default_rule(B4,D4) [D4(0,0,0,0) + D4(1,0,0,0), D4(1,0,0,0) + D4(0,1,0,0), D4(0,1,0,0) + D4(0,0,1,1), D4(0,0,1,0) + D4(0,0,0,1)] sage: try_default_rule(A7,D4) [D4(1,0,0,0), D4(0,1,0,0), D4(0,0,1,1), D4(0,0,2,0) + D4(0,0,0,2), D4(0,0,1,1), D4(0,1,0,0), D4(1,0,0,0)] sage: try_default_rule(A6,B3) [B3(1,0,0), B3(0,1,0), B3(0,0,2), B3(0,0,2), B3(0,1,0), B3(1,0,0)] If a default rule is not known, you may cue Sage as to what the Lie group embedding is by supplying a rule from the list of predefined rules. We will treat these next. .. RUBRIC:: Levi Type These can be read off from the Dynkin diagram. If removing a node from the Dynkin diagram produces another Dynkin diagram, there is a branching rule. A Levi subgroup may or may not be maximal. If it is maximal, there may or may not be a built-in branching rule for but you may obtain the Levi branching rule by first branching to a suitable maximal subgroup. For these rules use the option ``rule="levi"``: .. MATH:: \begin{aligned} A_r & \Rightarrow A_{r-1} \\ B_r & \Rightarrow A_{r-1} \\ B_r & \Rightarrow B_{r-1} \\ C_r & \Rightarrow A_{r-1} \\ C_r & \Rightarrow C_{r-1} \\ D_r & \Rightarrow A_{r-1} \\ D_r & \Rightarrow D_{r-1} \\ E_r & \Rightarrow A_{r-1} \quad r = 7,8 \\ E_r & \Rightarrow D_{r-1} \quad r = 6,7,8 \\ E_r & \Rightarrow E_{r-1} \\ F_4 & \Rightarrow B_3 \\ F_4 & \Rightarrow C_3 \\ G_2 & \Rightarrow A_1 \text{(short root)} \end{aligned} Not all Levi subgroups are maximal subgroups. If the Levi is not maximal there may or may not be a preprogrammed ``rule="levi"`` for it. If there is not, the branching rule may still be obtained by going through an intermediate subgroup that is maximal using rule="extended". Thus the other Levi branching rule from `G_2 \Rightarrow A_1` corresponding to the long root is available by first branching `G_2 \Rightarrow A_2` then `A_2 \Rightarrow A_1`. Similarly the branching rules to the Levi subgroup: .. MATH:: E_r \Rightarrow A_{r-1} \quad r = 6,7,8 may be obtained by first branching `E_6 \Rightarrow A_5 \times A_1`, `E_7 \Rightarrow A_7` or `E_8 \Rightarrow A_8`. EXAMPLES:: sage: A1 = WeylCharacterRing("A1") sage: A2 = WeylCharacterRing("A2") sage: A3 = WeylCharacterRing("A3") sage: A4 = WeylCharacterRing("A4") sage: A5 = WeylCharacterRing("A5") sage: B2 = WeylCharacterRing("B2") sage: B3 = WeylCharacterRing("B3") sage: B4 = WeylCharacterRing("B4") sage: C2 = WeylCharacterRing("C2") sage: C3 = WeylCharacterRing("C3") sage: D3 = WeylCharacterRing("D3") sage: D4 = WeylCharacterRing("D4") sage: G2 = WeylCharacterRing("G2") sage: F4 = WeylCharacterRing("F4",style="coroots") sage: E6=WeylCharacterRing("E6",style="coroots") sage: E7=WeylCharacterRing("E7",style="coroots") sage: D5=WeylCharacterRing("D5",style="coroots") sage: D6=WeylCharacterRing("D6",style="coroots") sage: [B3(w).branch(A2,rule="levi") for w in B3.fundamental_weights()] [A2(0,0,0) + A2(1,0,0) + A2(0,0,-1), A2(0,0,0) + A2(1,0,0) + A2(1,1,0) + A2(1,0,-1) + A2(0,-1,-1) + A2(0,0,-1), A2(-1/2,-1/2,-1/2) + A2(1/2,-1/2,-1/2) + A2(1/2,1/2,-1/2) + A2(1/2,1/2,1/2)] The last example must be understood as follows. The representation of `B_3` being branched is spin, which is not a representation of `SO(7)` but of its double cover `\mathrm{spin}(7)`. The group `A_2` is really GL(3) and the double cover of `SO(7)` induces a cover of `GL(3)` that is trivial over `SL(3)` but not over the center of `GL(3)`. The weight lattice for this `GL(3)` consists of triples `(a,b,c)` of half integers such that `a - b` and `b - c` are in `\ZZ`, and this is reflected in the last decomposition. :: sage: [C3(w).branch(A2,rule="levi") for w in C3.fundamental_weights()] [A2(1,0,0) + A2(0,0,-1), A2(1,1,0) + A2(1,0,-1) + A2(0,-1,-1), A2(-1,-1,-1) + A2(1,-1,-1) + A2(1,1,-1) + A2(1,1,1)] sage: [D4(w).branch(A3,rule="levi") for w in D4.fundamental_weights()] [A3(1,0,0,0) + A3(0,0,0,-1), A3(0,0,0,0) + A3(1,1,0,0) + A3(1,0,0,-1) + A3(0,0,-1,-1), A3(1/2,-1/2,-1/2,-1/2) + A3(1/2,1/2,1/2,-1/2), A3(-1/2,-1/2,-1/2,-1/2) + A3(1/2,1/2,-1/2,-1/2) + A3(1/2,1/2,1/2,1/2)] sage: [B3(w).branch(B2,rule="levi") for w in B3.fundamental_weights()] [2*B2(0,0) + B2(1,0), B2(0,0) + 2*B2(1,0) + B2(1,1), 2*B2(1/2,1/2)] sage: C3 = WeylCharacterRing(['C',3]) sage: [C3(w).branch(C2,rule="levi") for w in C3.fundamental_weights()] [2*C2(0,0) + C2(1,0), C2(0,0) + 2*C2(1,0) + C2(1,1), C2(1,0) + 2*C2(1,1)] sage: [D5(w).branch(D4,rule="levi") for w in D5.fundamental_weights()] [2*D4(0,0,0,0) + D4(1,0,0,0), D4(0,0,0,0) + 2*D4(1,0,0,0) + D4(1,1,0,0), D4(1,0,0,0) + 2*D4(1,1,0,0) + D4(1,1,1,0), D4(1/2,1/2,1/2,-1/2) + D4(1/2,1/2,1/2,1/2), D4(1/2,1/2,1/2,-1/2) + D4(1/2,1/2,1/2,1/2)] sage: G2(1,0,-1).branch(A1,rule="levi") A1(1,0) + A1(1,-1) + A1(0,-1) sage: E6=WeylCharacterRing("E6",style="coroots") sage: D5=WeylCharacterRing("D5",style="coroots") sage: fw = E6.fundamental_weights() sage: [E6(fw[i]).branch(D5,rule="levi") for i in [1,2,6]] [D5(0,0,0,0,0) + D5(0,0,0,0,1) + D5(1,0,0,0,0), D5(0,0,0,0,0) + D5(0,0,0,1,0) + D5(0,0,0,0,1) + D5(0,1,0,0,0), D5(0,0,0,0,0) + D5(0,0,0,1,0) + D5(1,0,0,0,0)] sage: E7=WeylCharacterRing("E7",style="coroots") sage: A3xA3xA1=WeylCharacterRing("A3xA3xA1",style="coroots") sage: E7(1,0,0,0,0,0,0).branch(A3xA3xA1,rule="extended") # long time (0.7s) A3xA3xA1(0,0,1,0,0,1,1) + A3xA3xA1(0,1,0,0,1,0,0) + A3xA3xA1(1,0,0,1,0,0,1) + A3xA3xA1(1,0,1,0,0,0,0) + A3xA3xA1(0,0,0,1,0,1,0) + A3xA3xA1(0,0,0,0,0,0,2) sage: fw = E7.fundamental_weights() sage: [E7(fw[i]).branch(D6,rule="levi") for i in [1,2,7]] # long time (0.3s) [3*D6(0,0,0,0,0,0) + 2*D6(0,0,0,0,1,0) + D6(0,1,0,0,0,0), 3*D6(0,0,0,0,0,1) + 2*D6(1,0,0,0,0,0) + 2*D6(0,0,1,0,0,0) + D6(1,0,0,0,1,0), D6(0,0,0,0,0,1) + 2*D6(1,0,0,0,0,0)] sage: D7=WeylCharacterRing("D7",style="coroots") sage: E8=WeylCharacterRing("E8",style="coroots") sage: D7=WeylCharacterRing("D7",style="coroots") sage: E8(1,0,0,0,0,0,0,0).branch(D7,rule="levi") # long time (7s) 3*D7(0,0,0,0,0,0,0) + 2*D7(0,0,0,0,0,1,0) + 2*D7(0,0,0,0,0,0,1) + 2*D7(1,0,0,0,0,0,0) + D7(0,1,0,0,0,0,0) + 2*D7(0,0,1,0,0,0,0) + D7(0,0,0,1,0,0,0) + D7(1,0,0,0,0,1,0) + D7(1,0,0,0,0,0,1) + D7(2,0,0,0,0,0,0) sage: E8(0,0,0,0,0,0,0,1).branch(D7,rule="levi") # long time (0.6s) D7(0,0,0,0,0,0,0) + D7(0,0,0,0,0,1,0) + D7(0,0,0,0,0,0,1) + 2*D7(1,0,0,0,0,0,0) + D7(0,1,0,0,0,0,0) sage: [F4(fw).branch(B3,rule="levi") for fw in F4.fundamental_weights()] # long time (1s) [B3(0,0,0) + 2*B3(1/2,1/2,1/2) + 2*B3(1,0,0) + B3(1,1,0), B3(0,0,0) + 6*B3(1/2,1/2,1/2) + 5*B3(1,0,0) + 7*B3(1,1,0) + 3*B3(1,1,1) + 6*B3(3/2,1/2,1/2) + 2*B3(3/2,3/2,1/2) + B3(2,0,0) + 2*B3(2,1,0) + B3(2,1,1), 3*B3(0,0,0) + 6*B3(1/2,1/2,1/2) + 4*B3(1,0,0) + 3*B3(1,1,0) + B3(1,1,1) + 2*B3(3/2,1/2,1/2), 3*B3(0,0,0) + 2*B3(1/2,1/2,1/2) + B3(1,0,0)] sage: [F4(fw).branch(C3,rule="levi") for fw in F4.fundamental_weights()] # long time (1s) [3*C3(0,0,0) + 2*C3(1,1,1) + C3(2,0,0), 3*C3(0,0,0) + 6*C3(1,1,1) + 4*C3(2,0,0) + 2*C3(2,1,0) + 3*C3(2,2,0) + C3(2,2,2) + C3(3,1,0) + 2*C3(3,1,1), 2*C3(1,0,0) + 3*C3(1,1,0) + C3(2,0,0) + 2*C3(2,1,0) + C3(2,1,1), 2*C3(1,0,0) + C3(1,1,0)] sage: A1xA1 = WeylCharacterRing("A1xA1") sage: [A3(hwv).branch(A1xA1,rule="levi") for hwv in A3.fundamental_weights()] [A1xA1(1,0,0,0) + A1xA1(0,0,1,0), A1xA1(1,1,0,0) + A1xA1(1,0,1,0) + A1xA1(0,0,1,1), A1xA1(1,1,1,0) + A1xA1(1,0,1,1)] sage: A1xB1=WeylCharacterRing("A1xB1",style="coroots") sage: [B3(x).branch(A1xB1,rule="levi") for x in B3.fundamental_weights()] [2*A1xB1(1,0) + A1xB1(0,2), 3*A1xB1(0,0) + 2*A1xB1(1,2) + A1xB1(2,0) + A1xB1(0,2), A1xB1(1,1) + 2*A1xB1(0,1)] .. RUBRIC:: Automorphic Type If the Dynkin diagram has a symmetry, then there is an automorphism that is a special case of a branching rule. There is also an exotic "triality" automorphism of `D_4` having order 3. Use ``rule="automorphic"`` (or for `D_4` ``rule="triality"``): .. MATH:: \begin{aligned} A_r & \Rightarrow A_r \\ D_r & \Rightarrow D_r \\ E_6 & \Rightarrow E_6 \end{aligned} EXAMPLES:: sage: [A3(chi).branch(A3,rule="automorphic") for chi in A3.fundamental_weights()] [A3(0,0,0,-1), A3(0,0,-1,-1), A3(0,-1,-1,-1)] sage: [D4(chi).branch(D4,rule="automorphic") for chi in D4.fundamental_weights()] [D4(1,0,0,0), D4(1,1,0,0), D4(1/2,1/2,1/2,1/2), D4(1/2,1/2,1/2,-1/2)] Here is an example with `D_4` triality:: sage: [D4(chi).branch(D4,rule="triality") for chi in D4.fundamental_weights()] [D4(1/2,1/2,1/2,-1/2), D4(1,1,0,0), D4(1/2,1/2,1/2,1/2), D4(1,0,0,0)] .. RUBRIC:: Symmetric Type Related to the automorphic type, when `G` admits an outer automorphism (usually of degree 2) we may consider the branching rule to the isotropy subgroup `H`. Outer automorphisms correspond to symmetries of the Dynkin diagram. For such isotropy subgroups use ``rule="symmetric"``. We may thus obtain the following branching rules. .. MATH:: A_{2r} & \Rightarrow B_r \\ A_{2r-1} & \Rightarrow C_r \\ A_{2r-1} & \Rightarrow D_r \\ D_r & \Rightarrow B_{r-1} \\ E_6 & \Rightarrow F_4 \\ E_6 & \Rightarrow C_4 \\ D_4 & \Rightarrow G_2 The last branching rule, `D_4 \Rightarrow G_2` is not to a maximal subgroup since `D_4 \Rightarrow B_3 \Rightarrow G_2`, but it is included for convenience. In some cases, two outer automorphisms that differ by an inner automorphism may have different fixed subgroups. Thus, while the Dynkin diagram of `E_6` has a single involutory automorphism, there are two involutions of the group (differing by an inner automorphism) with fixed subgroups `F_4` and `C_4`. Similarly `SL(2r)`, of Cartan type `A_{2r-1}`, has subgroups `SO(2r)` and `Sp(2r)`, both fixed subgroups of outer automorphisms that differ from each other by an inner automorphism. In many cases the Dynkin diagram of `H` can be obtained by folding the Dynkin diagram of `G`. EXAMPLES:: sage: [w.branch(B2,rule="symmetric") for w in [A4(1,0,0,0,0),A4(1,1,0,0,0),A4(1,1,1,0,0),A4(2,0,0,0,0)]] [B2(1,0), B2(1,1), B2(1,1), B2(0,0) + B2(2,0)] sage: [A5(w).branch(C3,rule="symmetric") for w in A5.fundamental_weights()] [C3(1,0,0), C3(0,0,0) + C3(1,1,0), C3(1,0,0) + C3(1,1,1), C3(0,0,0) + C3(1,1,0), C3(1,0,0)] sage: [A5(w).branch(D3,rule="symmetric") for w in A5.fundamental_weights()] [D3(1,0,0), D3(1,1,0), D3(1,1,-1) + D3(1,1,1), D3(1,1,0), D3(1,0,0)] sage: [D4(x).branch(B3,rule="symmetric") for x in D4.fundamental_weights()] [B3(0,0,0) + B3(1,0,0), B3(1,0,0) + B3(1,1,0), B3(1/2,1/2,1/2), B3(1/2,1/2,1/2)] sage: [D4(x).branch(G2,rule="symmetric") for x in D4.fundamental_weights()] [G2(0,0,0) + G2(1,0,-1), 2*G2(1,0,-1) + G2(2,-1,-1), G2(0,0,0) + G2(1,0,-1), G2(0,0,0) + G2(1,0,-1)] sage: [E6(fw).branch(F4,rule="symmetric") for fw in E6.fundamental_weights()] # long time (4s) [F4(0,0,0,0) + F4(0,0,0,1), F4(0,0,0,1) + F4(1,0,0,0), F4(0,0,0,1) + F4(1,0,0,0) + F4(0,0,1,0), F4(1,0,0,0) + 2*F4(0,0,1,0) + F4(1,0,0,1) + F4(0,1,0,0), F4(0,0,0,1) + F4(1,0,0,0) + F4(0,0,1,0), F4(0,0,0,0) + F4(0,0,0,1)] sage: E6=WeylCharacterRing("E6",style="coroots") sage: C4=WeylCharacterRing("C4",style="coroots") sage: chi = E6(1,0,0,0,0,0); chi.degree() 27 sage: chi.branch(C4,rule="symmetric") C4(0,1,0,0) .. RUBRIC:: Extended Type If removing a node from the extended Dynkin diagram results in a Dynkin diagram, then there is a branching rule. Use ``rule="extended"`` for these. We will also use this classification for some rules that are not of this type, mainly involving type `B`, such as `D_6 \Rightarrow B_3 \times B_3`. Here is the extended Dynkin diagram for `D_6`:: 0 6 O O | | | | O---O---O---O---O 1 2 3 4 6 Removing the node 3 results in an embedding `D_3 \times D_3 \Rightarrow D_6`. This corresponds to the embedding `SO(6) \times SO(6) \Rightarrow SO(12)`, and is of extended type. On the other hand the embedding `SO(5) \times SO(7) \Rightarrow SO(12)` (e.g. `B_2 \times B_3 \Rightarrow D_6`) cannot be explained this way but for uniformity is implemented under ``rule="extended"``. The following rules are implemented as special cases of ``rule="extended"``: .. MATH:: \begin{aligned} E_6 & \Rightarrow A_5 \times A_1, A_2 \times A_2 \times A_2 \\ E_7 & \Rightarrow A_7, D_6 \times A_1, A_3 \times A_3 \times A_1 \\ E_8 & \Rightarrow A_8, D_8, E_7 \times A_1, A_4 \times A_4, D_5 \times A_3, E_6 \times A_2 \\ F_4 & \Rightarrow B_4, C_3 \times A_1, A_2 \times A_2, A_3 \times A_1 \\ G_2 & \Rightarrow A_1 \times A_1 \end{aligned} Note that `E_8` has only a limited number of representations of reasonably low degree. EXAMPLES:: sage: [B3(x).branch(D3,rule="extended") for x in B3.fundamental_weights()] [D3(0,0,0) + D3(1,0,0), D3(1,0,0) + D3(1,1,0), D3(1/2,1/2,-1/2) + D3(1/2,1/2,1/2)] sage: [G2(w).branch(A2, rule="extended") for w in G2.fundamental_weights()] [A2(0,0,0) + A2(1/3,1/3,-2/3) + A2(2/3,-1/3,-1/3), A2(1/3,1/3,-2/3) + A2(2/3,-1/3,-1/3) + A2(1,0,-1)] sage: [F4(fw).branch(B4,rule="extended") for fw in F4.fundamental_weights()] # long time (2s) [B4(1/2,1/2,1/2,1/2) + B4(1,1,0,0), B4(1,1,0,0) + B4(1,1,1,0) + B4(3/2,1/2,1/2,1/2) + B4(3/2,3/2,1/2,1/2) + B4(2,1,1,0), B4(1/2,1/2,1/2,1/2) + B4(1,0,0,0) + B4(1,1,0,0) + B4(1,1,1,0) + B4(3/2,1/2,1/2,1/2), B4(0,0,0,0) + B4(1/2,1/2,1/2,1/2) + B4(1,0,0,0)] sage: E6 = WeylCharacterRing("E6", style="coroots") sage: A2xA2xA2 = WeylCharacterRing("A2xA2xA2",style="coroots") sage: A5xA1 = WeylCharacterRing("A5xA1",style="coroots") sage: G2 = WeylCharacterRing("G2", style="coroots") sage: A1xA1 = WeylCharacterRing("A1xA1", style="coroots") sage: F4 = WeylCharacterRing("F4",style="coroots") sage: A3xA1 = WeylCharacterRing("A3xA1", style="coroots") sage: A2xA2 = WeylCharacterRing("A2xA2", style="coroots") sage: A1xC3 = WeylCharacterRing("A1xC3",style="coroots") sage: E6(1,0,0,0,0,0).branch(A5xA1,rule="extended") # (0.7s) A5xA1(0,0,0,1,0,0) + A5xA1(1,0,0,0,0,1) sage: E6(1,0,0,0,0,0).branch(A2xA2xA2, rule="extended") # (0.7s) A2xA2xA2(0,1,1,0,0,0) + A2xA2xA2(1,0,0,0,0,1) + A2xA2xA2(0,0,0,1,1,0) sage: E7 = WeylCharacterRing("E7",style="coroots") sage: A7 = WeylCharacterRing("A7",style="coroots") sage: E7(1,0,0,0,0,0,0).branch(A7,rule="extended") A7(0,0,0,1,0,0,0) + A7(1,0,0,0,0,0,1) sage: D6xA1 = WeylCharacterRing("D6xA1",style="coroots") sage: E7(1,0,0,0,0,0,0).branch(D6xA1,rule="extended") D6xA1(0,0,0,0,1,0,1) + D6xA1(0,1,0,0,0,0,0) + D6xA1(0,0,0,0,0,0,2) sage: A5xA2 = WeylCharacterRing("A5xA2",style="coroots") sage: E7(1,0,0,0,0,0,0).branch(A5xA2,rule="extended") A5xA2(0,0,0,1,0,1,0) + A5xA2(0,1,0,0,0,0,1) + A5xA2(1,0,0,0,1,0,0) + A5xA2(0,0,0,0,0,1,1) sage: E8 = WeylCharacterRing("E8",style="coroots") sage: D8 = WeylCharacterRing("D8",style="coroots") sage: A8 = WeylCharacterRing("A8",style="coroots") sage: E8(0,0,0,0,0,0,0,1).branch(D8,rule="extended") # long time (0.56s) D8(0,0,0,0,0,0,1,0) + D8(0,1,0,0,0,0,0,0) sage: E8(0,0,0,0,0,0,0,1).branch(A8,rule="extended") # long time (0.73s) A8(0,0,0,0,0,1,0,0) + A8(0,0,1,0,0,0,0,0) + A8(1,0,0,0,0,0,0,1) sage: F4(1,0,0,0).branch(A1xC3,rule="extended") # (0.05s) A1xC3(1,0,0,1) + A1xC3(2,0,0,0) + A1xC3(0,2,0,0) sage: G2(0,1).branch(A1xA1, rule="extended") A1xA1(2,0) + A1xA1(3,1) + A1xA1(0,2) sage: F4(0,0,0,1).branch(A2xA2, rule="extended") # (0.4s) A2xA2(0,1,0,1) + A2xA2(1,0,1,0) + A2xA2(0,0,1,1) sage: F4(0,0,0,1).branch(A3xA1,rule="extended") # (0.34s) A3xA1(0,0,0,0) + A3xA1(0,0,1,1) + A3xA1(0,1,0,0) + A3xA1(1,0,0,1) + A3xA1(0,0,0,2) sage: D4=WeylCharacterRing("D4",style="coroots") sage: D2xD2=WeylCharacterRing("D2xD2",style="coroots") # We get D4 => A1xA1xA1xA1 by remembering that A1xA1 = D2. sage: [D4(fw).branch(D2xD2, rule="extended") for fw in D4.fundamental_weights()] [D2xD2(1,1,0,0) + D2xD2(0,0,1,1), D2xD2(2,0,0,0) + D2xD2(0,2,0,0) + D2xD2(1,1,1,1) + D2xD2(0,0,2,0) + D2xD2(0,0,0,2), D2xD2(1,0,0,1) + D2xD2(0,1,1,0), D2xD2(1,0,1,0) + D2xD2(0,1,0,1)] .. RUBRIC:: Orthogonal Sum Using ``rule="orthogonal_sum"``, for `n = a + b + c + \cdots`, you can get any branching rule .. MATH:: \begin{aligned} SO(n) & \Rightarrow SO(a) \times SO(b) \times SO(c) \times \cdots, \\ Sp(2n) & \Rightarrow Sp(2a) \times Sp(2b) \times Sp(2c) x \times \cdots, \end{aligned} where `O(a)` is type `D_r` for `a = 2r` or `B_r` for `a = 2r+1` and `Sp(2r)` is type `C_r`. In some cases these are also of extended type, as in the case `D_3 \times D_3 \Rightarrow D_6` discussed above. But in other cases, for example `B_3 \times B_3 \Rightarrow D_7`, they are not of extended type. .. RUBRIC:: Tensor There are branching rules: .. MATH:: \begin{aligned} A_{rs-1} & \Rightarrow A_{r-1} \times A_{s-1}, \\ B_{2rs+r+s} & \Rightarrow B_r \times B_s, \\ D_{2rs+s} & \Rightarrow B_r \times D_s, \\ D_{2rs} & \Rightarrow D_r \times D_s, \\ D_{2rs} & \Rightarrow C_r \times C_s, \\ C_{2rs+s} & \Rightarrow B_r \times C_s, \\ C_{2rs} & \Rightarrow C_r \times D_s. \end{aligned} corresponding to the tensor product homomorphism. For type `A`, the homomorphism is `GL(r) \times GL(s) \Rightarrow GL(rs)`. For the classical types, the relevant fact is that if `V, W` are orthogonal or symplectic spaces, that is, spaces endowed with symmetric or skew-symmetric bilinear forms, then `V \otimes W` is also an orthogonal space (if `V` and `W` are both orthogonal or both symplectic) or symplectic (if one of `V` and `W` is orthogonal and the other symplectic). The corresponding branching rules are obtained using ``rule="tensor"``. EXAMPLES:: sage: A5=WeylCharacterRing("A5", style="coroots") sage: A2xA1=WeylCharacterRing("A2xA1", style="coroots") sage: [A5(hwv).branch(A2xA1, rule="tensor") for hwv in A5.fundamental_weights()] [A2xA1(1,0,1), A2xA1(0,1,2) + A2xA1(2,0,0), A2xA1(1,1,1) + A2xA1(0,0,3), A2xA1(1,0,2) + A2xA1(0,2,0), A2xA1(0,1,1)] sage: B4=WeylCharacterRing("B4",style="coroots") sage: B1xB1=WeylCharacterRing("B1xB1",style="coroots") sage: [B4(f).branch(B1xB1,rule="tensor") for f in B4.fundamental_weights()] [B1xB1(2,2), B1xB1(2,0) + B1xB1(2,4) + B1xB1(4,2) + B1xB1(0,2), B1xB1(2,0) + B1xB1(2,2) + B1xB1(2,4) + B1xB1(4,2) + B1xB1(4,4) + B1xB1(6,0) + B1xB1(0,2) + B1xB1(0,6), B1xB1(1,3) + B1xB1(3,1)] sage: D4=WeylCharacterRing("D4",style="coroots") sage: C2xC1=WeylCharacterRing("C2xC1",style="coroots") sage: [D4(f).branch(C2xC1,rule="tensor") for f in D4.fundamental_weights()] [C2xC1(1,0,1), C2xC1(0,1,2) + C2xC1(2,0,0) + C2xC1(0,0,2), C2xC1(1,0,1), C2xC1(0,1,0) + C2xC1(0,0,2)] sage: C3=WeylCharacterRing("C3",style="coroots") sage: B1xC1=WeylCharacterRing("B1xC1",style="coroots") sage: [C3(f).branch(B1xC1,rule="tensor") for f in C3.fundamental_weights()] [B1xC1(2,1), B1xC1(2,2) + B1xC1(4,0), B1xC1(4,1) + B1xC1(0,3)] .. RUBRIC:: Symmetric Power The `k`-th symmetric and exterior power homomorphisms map .. MATH:: GL(n) \Rightarrow GL\left(\binom{n+k-1}{k}\right) \times GL\left(\binom{n}{k}\right). The corresponding branching rules are not implemented but a special case is. The `k`-th symmetric power homomorphism `SL(2) \Rightarrow GL(k+1)` has its image inside of `SO(2r+1)` if `k = 2r` and inside of `Sp(2r)` if `k = 2r - 1`. Hence there are branching rules: .. MATH:: \begin{aligned} B_r & \Rightarrow A_1 \\ C_r & \Rightarrow A_1 \end{aligned} and these may be obtained using the rule "symmetric_power". EXAMPLES:: sage: A1=WeylCharacterRing("A1",style="coroots") sage: B3=WeylCharacterRing("B3",style="coroots") sage: C3=WeylCharacterRing("C3",style="coroots") sage: [B3(fw).branch(A1,rule="symmetric_power") for fw in B3.fundamental_weights()] [A1(6), A1(2) + A1(6) + A1(10), A1(0) + A1(6)] sage: [C3(fw).branch(A1,rule="symmetric_power") for fw in C3.fundamental_weights()] [A1(5), A1(4) + A1(8), A1(3) + A1(9)] .. RUBRIC:: Miscellaneous Use ``rule="miscellaneous"`` for the following embeddings of maximal subgroups, all involving exceptional groups. .. MATH:: \begin{aligned} B_3 & \Rightarrow G_2, \\ E_6 & \Rightarrow G_2, \\ E_6 & \Rightarrow A_2, \\ F_4 & \Rightarrow G_2 \times A_1, \\ E_6 & \Rightarrow G_2 \times A_2, \\ E_7 & \Rightarrow G_2 \times C_3, \\ E_7 & \Rightarrow F_4 \times A_1, \\ E_7 & \Rightarrow A_1 \times A_1, \\ E_7 & \Rightarrow G_2 \times A_1, \\ E_8 & \Rightarrow G_2 \times F_4. \\ E_8 & \Rightarrow A2 \times A_1. \\ E_8 & \Rightarrow B2. \end{aligned} Except for those embeddings available by ``rule="extended"``, these are the only embeddings of these groups as maximal subgroups. There may be other embeddings besides these. For example, there are other more obvious embeddings of `A_2` and `G_2` into `E_6`. However the embeddings in this table are characterized as embeddings as maximal subgroups. Regarding the embeddings of `A_2` and `G_2` in `E_6`, the embeddings in question may be characterized by the condition that the 27-dimensional representations of `E_6` restrict irreducibly to `A_2` or `G_2`. Since `G_2` has a subgroup isomorphic to `A_2`, it is worth mentioning that the composite branching rules:: branching_rule("E6","G2","miscellaneous")*branching_rule("G2","A2","extended") branching_rule("E6","A2","miscellaneous") are distinct. These embeddings are described more completely (with references to the literature) in the thematic tutorial at: https://doc.sagemath.org/html/en/thematic_tutorials/lie.html EXAMPLES:: sage: G2 = WeylCharacterRing("G2") sage: [fw1, fw2, fw3] = B3.fundamental_weights() sage: B3(fw1+fw3).branch(G2, rule="miscellaneous") G2(1,0,-1) + G2(2,-1,-1) + G2(2,0,-2) sage: E6 = WeylCharacterRing("E6",style="coroots") sage: G2 = WeylCharacterRing("G2",style="coroots") sage: E6(1,0,0,0,0,0).branch(G2,"miscellaneous") G2(2,0) sage: A2=WeylCharacterRing("A2",style="coroots") sage: E6(1,0,0,0,0,0).branch(A2,rule="miscellaneous") A2(2,2) sage: E6(0,1,0,0,0,0).branch(A2,rule="miscellaneous") A2(1,1) + A2(1,4) + A2(4,1) sage: E6(0,0,0,0,0,2).branch(G2,"miscellaneous") # long time (0.59s) G2(0,0) + G2(2,0) + G2(1,1) + G2(0,2) + G2(4,0) sage: F4=WeylCharacterRing("F4",style="coroots") sage: G2xA1=WeylCharacterRing("G2xA1",style="coroots") sage: F4(0,0,1,0).branch(G2xA1,rule="miscellaneous") G2xA1(1,0,0) + G2xA1(1,0,2) + G2xA1(1,0,4) + G2xA1(1,0,6) + G2xA1(0,1,4) + G2xA1(2,0,2) + G2xA1(0,0,2) + G2xA1(0,0,6) sage: E6 = WeylCharacterRing("E6",style="coroots") sage: A2xG2 = WeylCharacterRing("A2xG2",style="coroots") sage: E6(1,0,0,0,0,0).branch(A2xG2,rule="miscellaneous") A2xG2(0,1,1,0) + A2xG2(2,0,0,0) sage: E7=WeylCharacterRing("E7",style="coroots") sage: G2xC3=WeylCharacterRing("G2xC3",style="coroots") sage: E7(0,1,0,0,0,0,0).branch(G2xC3,rule="miscellaneous") # long time (1.84s) G2xC3(1,0,1,0,0) + G2xC3(1,0,1,1,0) + G2xC3(0,1,0,0,1) + G2xC3(2,0,1,0,0) + G2xC3(0,0,1,1,0) sage: F4xA1=WeylCharacterRing("F4xA1",style="coroots") sage: E7(0,0,0,0,0,0,1).branch(F4xA1,"miscellaneous") F4xA1(0,0,0,1,1) + F4xA1(0,0,0,0,3) sage: A1xA1=WeylCharacterRing("A1xA1",style="coroots") sage: E7(0,0,0,0,0,0,1).branch(A1xA1,rule="miscellaneous") A1xA1(2,5) + A1xA1(4,1) + A1xA1(6,3) sage: A2=WeylCharacterRing("A2",style="coroots") sage: E7(0,0,0,0,0,0,1).branch(A2,rule="miscellaneous") A2(0,6) + A2(6,0) sage: G2xA1=WeylCharacterRing("G2xA1",style="coroots") sage: E7(1,0,0,0,0,0,0).branch(G2xA1,rule="miscellaneous") G2xA1(1,0,4) + G2xA1(0,1,0) + G2xA1(2,0,2) + G2xA1(0,0,2) sage: E8 = WeylCharacterRing("E8",style="coroots") sage: G2xF4 = WeylCharacterRing("G2xF4",style="coroots") sage: E8(0,0,0,0,0,0,0,1).branch(G2xF4,rule="miscellaneous") # long time (0.76s) G2xF4(1,0,0,0,0,1) + G2xF4(0,1,0,0,0,0) + G2xF4(0,0,1,0,0,0) sage: E8=WeylCharacterRing("E8",style="coroots") sage: A1xA2=WeylCharacterRing("A1xA2",style="coroots") sage: E8(0,0,0,0,0,0,0,1).branch(A1xA2,rule="miscellaneous") # long time (0.76s) A1xA2(2,0,0) + A1xA2(2,2,2) + A1xA2(4,0,3) + A1xA2(4,3,0) + A1xA2(6,1,1) + A1xA2(0,1,1) sage: B2=WeylCharacterRing("B2",style="coroots") sage: E8(0,0,0,0,0,0,0,1).branch(B2,rule="miscellaneous") # long time (0.53s) B2(0,2) + B2(0,6) + B2(3,2) .. RUBRIC:: A1 maximal subgroups of exceptional groups There are seven cases where the exceptional group `G_2`, `F_4`, `E_7` or `E_8` contains a maximal subgroup of type `A_1`. These are tabulated in Theorem 1 of Testerman, The construction of the maximal A1's in the exceptional algebraic groups, Proc. Amer. Math. Soc. 116 (1992), no. 3, 635-644. The names of these branching rules are roman numerals referring to the seven cases of her Theorem 1. Use these branching rules as in the following examples. EXAMPLES:: sage: A1=WeylCharacterRing("A1",style="coroots") sage: G2=WeylCharacterRing("G2",style="coroots") sage: F4=WeylCharacterRing("F4",style="coroots") sage: E7=WeylCharacterRing("E7",style="coroots") sage: E8=WeylCharacterRing("E8",style="coroots") sage: [G2(f).branch(A1,rule="i") for f in G2.fundamental_weights()] [A1(6), A1(2) + A1(10)] sage: F4(1,0,0,0).branch(A1,rule="ii") A1(2) + A1(10) + A1(14) + A1(22) sage: E7(0,0,0,0,0,0,1).branch(A1,rule="iii") A1(9) + A1(17) + A1(27) sage: E7(0,0,0,0,0,0,1).branch(A1,rule="iv") A1(5) + A1(11) + A1(15) + A1(21) sage: E8(0,0,0,0,0,0,0,1).branch(A1,rule="v") # long time (0.6s) A1(2) + A1(14) + A1(22) + A1(26) + A1(34) + A1(38) + A1(46) + A1(58) sage: E8(0,0,0,0,0,0,0,1).branch(A1,rule="vi") # long time (0.6s) A1(2) + A1(10) + A1(14) + A1(18) + A1(22) + A1(26) + A1(28) + A1(34) + A1(38) + A1(46) sage: E8(0,0,0,0,0,0,0,1).branch(A1,rule="vii") # long time (0.6s) A1(2) + A1(6) + A1(10) + A1(14) + A1(16) + A1(18) + 2*A1(22) + A1(26) + A1(28) + A1(34) + A1(38) .. RUBRIC:: Branching Rules From Plethysms Nearly all branching rules `G \Rightarrow H` where `G` is of type `A`, `B`, `C` or `D` are covered by the preceding rules. The function :func:`branching_rule_from_plethysm` covers the remaining cases. This is a general rule that includes any branching rule from types `A`, `B`, `C`, or `D` as a special case. Thus it could be used in place of the above rules and would give the same results. However it is most useful when branching from `G` to a maximal subgroup `H` such that `\mathrm{rank}(H) < \mathrm{rank}(G) - 1`. We consider a homomorphism `H \Rightarrow G` where `G` is one of `SL(r+1)`, `SO(2r+1)`, `Sp(2r)` or `SO(2r)`. The function :func:`branching_rule_from_plethysm` produces the corresponding branching rule. The main ingredient is the character `\chi` of the representation of `H` that is the homomorphism to `GL(r+1)`, `GL(2r+1)` or `GL(2r)`. This rule is so powerful that it contains the other rules implemented above as special cases. First let us consider the symmetric fifth power representation of `SL(2)`. :: sage: A1=WeylCharacterRing("A1",style="coroots") sage: chi=A1([5]) sage: chi.degree() 6 sage: chi.frobenius_schur_indicator() -1 This confirms that the character has degree 6 and is symplectic, so it corresponds to a homomorphism `SL(2) \Rightarrow Sp(6)`, and there is a corresponding branching rule `C_3 \Rightarrow A_1`. :: sage: C3 = WeylCharacterRing("C3",style="coroots") sage: sym5rule = branching_rule_from_plethysm(chi,"C3") sage: [C3(hwv).branch(A1,rule=sym5rule) for hwv in C3.fundamental_weights()] [A1(5), A1(4) + A1(8), A1(3) + A1(9)] This is identical to the results we would obtain using ``rule="symmetric_power"``. The next example gives a branching not available by other standard rules. :: sage: G2 = WeylCharacterRing("G2",style="coroots") sage: D7 = WeylCharacterRing("D7",style="coroots") sage: ad=G2(0,1); ad.degree(); ad.frobenius_schur_indicator() 14 1 sage: spin = D7(0,0,0,0,0,1,0); spin.degree() 64 sage: spin.branch(G2, rule=branching_rule_from_plethysm(ad, "D7")) G2(1,1) We have confirmed that the adjoint representation of `G_2` gives a homomorphism into `SO(14)`, and that the pullback of the one of the two 64 dimensional spin representations to `SO(14)` is an irreducible representation of `G_2`. We do not actually have to create the character or its parent WeylCharacterRing to create the branching rule:: sage: b = branching_rule("C7","C3(0,0,1)","plethysm"); b plethysm (along C3(0,0,1)) branching rule C7 => C3 .. RUBRIC:: Isomorphic Type Although not usually referred to as a branching rule, the effects of the accidental isomorphisms may be handled using ``rule="isomorphic"``: .. MATH:: \begin{aligned} B_2 & \Rightarrow C_2 \\ C_2 & \Rightarrow B_2 \\ A_3 & \Rightarrow D_3 \\ D_3 & \Rightarrow A_3 \\ D_2 & \Rightarrow A_1 \Rightarrow A_1 \\ B_1 & \Rightarrow A_1 \\ C_1 & \Rightarrow A_1 \end{aligned} EXAMPLES:: sage: B2 = WeylCharacterRing("B2") sage: C2 = WeylCharacterRing("C2") sage: [B2(x).branch(C2, rule="isomorphic") for x in B2.fundamental_weights()] [C2(1,1), C2(1,0)] sage: [C2(x).branch(B2, rule="isomorphic") for x in C2.fundamental_weights()] [B2(1/2,1/2), B2(1,0)] sage: D3 = WeylCharacterRing("D3") sage: A3 = WeylCharacterRing("A3") sage: [A3(x).branch(D3,rule="isomorphic") for x in A3.fundamental_weights()] [D3(1/2,1/2,1/2), D3(1,0,0), D3(1/2,1/2,-1/2)] sage: [D3(x).branch(A3,rule="isomorphic") for x in D3.fundamental_weights()] [A3(1/2,1/2,-1/2,-1/2), A3(1/4,1/4,1/4,-3/4), A3(3/4,-1/4,-1/4,-1/4)] Here `A_3(x,y,z,w)` can be understood as a representation of `SL(4)`. The weights `x,y,z,w` and `x+t,y+t,z+t,w+t` represent the same representation of `SL(4)` - though not of `GL(4)` - since `A_3(x+t,y+t,z+t,w+t)` is the same as `A_3(x,y,z,w)` tensored with `\mathrm{det}^t`. So as a representation of `SL(4)`, ``A3(1/4,1/4,1/4,-3/4)`` is the same as ``A3(1,1,1,0)``. The exterior square representation `SL(4) \Rightarrow GL(6)` admits an invariant symmetric bilinear form, so is a representation `SL(4) \Rightarrow SO(6)` that lifts to an isomorphism `SL(4) \Rightarrow \mathrm{Spin}(6)`. Conversely, there are two isomorphisms `SO(6) \Rightarrow SL(4)`, of which we've selected one. In cases like this you might prefer ``style="coroots"``:: sage: A3 = WeylCharacterRing("A3",style="coroots") sage: D3 = WeylCharacterRing("D3",style="coroots") sage: [D3(fw) for fw in D3.fundamental_weights()] [D3(1,0,0), D3(0,1,0), D3(0,0,1)] sage: [D3(fw).branch(A3,rule="isomorphic") for fw in D3.fundamental_weights()] [A3(0,1,0), A3(0,0,1), A3(1,0,0)] sage: D2 = WeylCharacterRing("D2", style="coroots") sage: A1xA1 = WeylCharacterRing("A1xA1", style="coroots") sage: [D2(fw).branch(A1xA1,rule="isomorphic") for fw in D2.fundamental_weights()] [A1xA1(1,0), A1xA1(0,1)] .. RUBRIC:: Branching From a Reducible WeylCharacterRing If the Cartan Type of R is reducible, we may project a character onto any of the components, or any combination of components. The rule to project on the first component is specified by the string ``"proj1"``, the rule to project on the second component is ``"proj2". To project on the first and third components, use ``"proj13"`` and so on. EXAMPLES:: sage: A2xG2=WeylCharacterRing("A2xG2",style="coroots") sage: A2=WeylCharacterRing("A2",style="coroots") sage: G2=WeylCharacterRing("G2",style="coroots") sage: A2xG2(1,0,1,0).branch(A2,rule="proj1") 7*A2(1,0) sage: A2xG2(1,0,1,0).branch(G2,rule="proj2") 3*G2(1,0) sage: A2xA2xG2=WeylCharacterRing("A2xA2xG2",style="coroots") sage: A2xA2xG2(0,1,1,1,0,1).branch(A2xG2,rule="proj13") 8*A2xG2(0,1,0,1) A more general way of specifying a branching rule from a reducible type is to supply a *list* of rules, one *component rule* for each component type in the root system. In the following example, we branch the fundamental representations of `D_4` down to `A_1\times A_1\times A_1 \times A_1` through the intermediate group `D_2\times D_2`. We use multiplicative notation to compose the branching rules. There is no need to construct the intermediate WeylCharacterRing with type `D_2\times D_2`. EXAMPLES:: sage: D4 = WeylCharacterRing("D4",style="coroots") sage: A1xA1xA1xA1 = WeylCharacterRing("A1xA1xA1xA1",style="coroots") sage: b = branching_rule("D2","A1xA1","isomorphic") sage: br = branching_rule("D4","D2xD2","extended")*branching_rule("D2xD2","A1xA1xA1xA1",[b,b]) sage: [D4(fw).branch(A1xA1xA1xA1,rule=br) for fw in D4.fundamental_weights()] [A1xA1xA1xA1(1,1,0,0) + A1xA1xA1xA1(0,0,1,1), A1xA1xA1xA1(1,1,1,1) + A1xA1xA1xA1(2,0,0,0) + A1xA1xA1xA1(0,2,0,0) + A1xA1xA1xA1(0,0,2,0) + A1xA1xA1xA1(0,0,0,2), A1xA1xA1xA1(1,0,0,1) + A1xA1xA1xA1(0,1,1,0), A1xA1xA1xA1(1,0,1,0) + A1xA1xA1xA1(0,1,0,1)] In the list of rules to be supplied in branching from a reducible root system, we may use two key words "omit" and "identity". The term "omit" means that we omit one factor, projecting onto the remaining factors. The term "identity" is supplied when the irreducible factor Cartan Types of both the target and the source are the same, and the component branching rule is to be the identity map. For example, we have projection maps from `A_3\times A_2` to `A_3` and `A_2`, and the corresponding branching may be accomplished as follows. In this example the same could be accomplished using ``rule="proj2"``. EXAMPLES:: sage: A3xA2=WeylCharacterRing("A3xA2",style="coroots") sage: A3=WeylCharacterRing("A3",style="coroots") sage: chi = A3xA2(0,1,0,1,0) sage: chi.branch(A3,rule=["identity","omit"]) 3*A3(0,1,0) sage: A2=WeylCharacterRing("A2",style="coroots") sage: chi.branch(A2,rule=["omit","identity"]) 6*A2(1,0) Yet another way of branching from a reducible root system with repeated Cartan types is to embed along the diagonal. The branching rule is equivalent to the tensor product, as the example shows:: sage: G2=WeylCharacterRing("G2",style="coroots") sage: G2xG2=WeylCharacterRing("G2xG2",style="coroots") sage: G2=WeylCharacterRing("G2",style="coroots") sage: G2xG2(1,0,0,1).branch(G2,rule="diagonal") G2(1,0) + G2(2,0) + G2(1,1) sage: G2xG2(1,0,0,1).branch(G2,rule="diagonal") == G2(1,0)*G2(0,1) True .. RUBRIC:: Writing Your Own (Branching) Rules Suppose you want to branch from a group `G` to a subgroup `H`. Arrange the embedding so that a Cartan subalgebra `U` of `H` is contained in a Cartan subalgebra `T` of `G`. There is thus a mapping from the weight spaces `\mathrm{Lie}(T)^* \Rightarrow \mathrm{Lie}(U)^*`. Two embeddings will produce identical branching rules if they differ by an element of the Weyl group of `H`. The *rule* is this map `\mathrm{Lie}(T)^*`, which is ``G.space()``, to `\mathrm{Lie}(U)^*`, which is ``H.space()``, which you may implement as a function. As an example, let us consider how to implement the branching rule `A_3 \Rightarrow C_2`. Here `H = C_2 = Sp(4)` embedded as a subgroup in `A_3 = GL(4)`. The Cartan subalgebra `U` consists of diagonal matrices with eigenvalues `u_1, u_2, -u_2, -u_1`. The ``C2.space()`` is the two dimensional vector spaces consisting of the linear functionals `u_1` and `u_2` on `U`. On the other hand `\mathrm{Lie}(T)` is `\RR^4`. A convenient way to see the restriction is to think of it as the adjoint of the map `(u_1, u_2) \mapsto (u_1,u_2, -u_2, -u_1)`, that is, `(x_0, x_1, x_2, x_3) \Rightarrow (x_0 - x_3, x_1 - x_2)`. Hence we may encode the rule as follows:: def rule(x): return [x[0]-x[3],x[1]-x[2]] or simply:: rule = lambda x: [x[0]-x[3],x[1]-x[2]] We may now make and use the branching rule as follows. EXAMPLES:: sage: br = BranchingRule("A3", "C2", lambda x: [x[0]-x[3],x[1]-x[2]], "homemade"); br homemade branching rule A3 => C2 sage: [A3,C2]=[WeylCharacterRing(x,style="coroots") for x in ["A3","C2"]] sage: A3(0,1,0).branch(C2,rule=br) C2(0,0) + C2(0,1) """ if isinstance(rule, (str, list)): rule = branching_rule(R._cartan_type, S._cartan_type, rule) if hasattr(rule, "_S"): if rule._S != S.cartan_type(): raise ValueError("rule has wrong target Cartan type") mdict = {} for k in chi.weight_multiplicities(): # TODO: Could this use the new from_vector of ambient_space ? if S._style == "coroots": if S._cartan_type.is_atomic() and S._cartan_type[0] == 'E': if S._cartan_type[1] == 6: h = S._space(rule(list(k.to_vector()))).coerce_to_e6() elif S._cartan_type[1] == 7: h = S._space(rule(list(k.to_vector()))).coerce_to_e7() else: h = (S._space(rule(list(k.to_vector())))).coerce_to_sl() else: h = S._space(rule(list(k.to_vector()))) chi_mdict = chi.weight_multiplicities() if h in mdict: mdict[h] += chi_mdict[k] else: mdict[h] = chi_mdict[k] return S.char_from_weights(mdict) class BranchingRule(SageObject): """ A class for branching rules. """ def __init__(self, R, S, f, name="default", intermediate_types=[], intermediate_names=[]): """ INPUT: - ``R, S`` -- CartanTypes - ``f`` -- a function from the weight lattice of R to the weight lattice of S. """ self._R = CartanType(R) self._S = CartanType(S) self._f = f self._intermediate_types = intermediate_types if intermediate_names: self._intermediate_names = intermediate_names else: self._intermediate_names = [name] self._name = name def _repr_(self): """ EXAMPLES:: sage: branching_rule("E6","F4","symmetric") symmetric branching rule E6 => F4 sage: b=branching_rule("F4","B3",rule="levi")*branching_rule("B3","G2",rule="miscellaneous"); b composite branching rule F4 => (levi) B3 => (miscellaneous) G2 """ R_repr = self._R._repr_(compact=True) S_repr = self._S._repr_(compact=True) if self._name == "composite": ret = "composite branching rule %s => " % R_repr for i in range(len(self._intermediate_types)): intt = self._intermediate_types[i] intn = self._intermediate_names[i] ret += "(%s) %s => " % (intn, intt._repr_(compact=True)) ret += "(%s) %s" % (self._intermediate_names[-1], S_repr) return ret return "%s branching rule %s => %s" % (self._name, R_repr, S_repr) def __call__(self, x): """ EXAMPLES:: sage: b=branching_rule("A3","C2","symmetric") sage: b([2,1,0,0]) [2, 1] """ try: return self._f(x) except Exception: return self._f(x.to_vector()) def __eq__(self, other): """ Two branching rules with the same source and target Cartan types are considered equal if they are the same as mappings from the weight lattice of the larger group to the smaller. The last example shows that two rules may be different by this criterion yet describe the same branching, if they differ by conjugation by an element of the Weyl group. EXAMPLES:: sage: b = branching_rule("E6","F4","symmetric")*branching_rule("F4","B3","levi")*branching_rule("B3","G2","miscellaneous"); b composite branching rule E6 => (symmetric) F4 => (levi) B3 => (miscellaneous) G2 sage: c = branching_rule("E6", "G2xA2", "miscellaneous")*branching_rule("G2xA2", "G2", "proj1"); c composite branching rule E6 => (miscellaneous) G2xA2 => (proj1) G2 sage: b == c True sage: d = branching_rule("A3","A2","levi")*branching_rule("A2","A1","levi"); d composite branching rule A3 => (levi) A2 => (levi) A1 sage: e = branching_rule("A3","D3","isomorphic")*branching_rule("D3","B2","symmetric")*branching_rule("B2","A1","levi"); e composite branching rule A3 => (isomorphic) D3 => (symmetric) B2 => (levi) A1 sage: d == e False sage: b1 = BranchingRule("A2","A2",lambda x: [x[2], x[1], x[0]], "long Weyl element conjugation") sage: b2 = BranchingRule("A2","A2",lambda x: x, "identity map") sage: b1 == b2 False sage: A2 = WeylCharacterRing("A2",style="coroots") sage: [A2(f).branch(A2,rule=b1) == A2(f).branch(A2,rule=b2) for f in A2.fundamental_weights()] [True, True] """ if not isinstance(other, BranchingRule): return False Rspace = RootSystem(self._R).ambient_space() Rspace_other = RootSystem(other._R).ambient_space() if Rspace != Rspace_other: return False Sspace = RootSystem(self._S).ambient_space() Sspace_other = RootSystem(other._S).ambient_space() if Sspace != Sspace_other: return False for v in Rspace.fundamental_weights(): w = list(v.to_vector()) if Sspace(self(w)) != Sspace(other(w)): return False return True def __ne__(self, other): """ Test inequality EXAMPLES:: sage: b1 = BranchingRule("A2","A2",lambda x: [x[2], x[1], x[0]], "long Weyl element conjugation") sage: b2 = BranchingRule("A2","A2",lambda x: x, "identity map") sage: b1 != b2 True """ return not(self == other) def __mul__(self, other): """ EXAMPLES:: sage: E6 = WeylCharacterRing("E6",style="coroots") sage: A5 = WeylCharacterRing("A5",style="coroots") sage: br = branching_rule("E6","A5xA1",rule="extended")*branching_rule("A5xA1","A5",rule="proj1"); br composite branching rule E6 => (extended) A5xA1 => (proj1) A5 sage: E6(1,0,0,0,0,0).branch(A5,rule=br) A5(0,0,0,1,0) + 2*A5(1,0,0,0,0) """ if self._S == other._R: intermediates = flatten([self._intermediate_types, self._S, other._intermediate_types]) internames = flatten([self._intermediate_names, other._intermediate_names]) def f(x): return other._f(self._f(x)) return BranchingRule(self._R, other._S, f, "composite", intermediate_types=intermediates, intermediate_names=internames) else: raise ValueError("unable to define composite: source and target don't agree") def Rtype(self): """ In a branching rule R => S, returns the Cartan Type of the ambient group R. EXAMPLES:: sage: branching_rule("A3","A2","levi").Rtype() ['A', 3] """ return self._R def Stype(self): """ In a branching rule R => S, returns the Cartan Type of the subgroup S. EXAMPLES:: sage: branching_rule("A3","A2","levi").Stype() ['A', 2] """ return self._S def describe(self, verbose=False, debug=False, no_r=False): """ Describes how extended roots restrict under self. EXAMPLES:: sage: branching_rule("G2","A2","extended").describe() <BLANKLINE> 3 O=<=O---O 1 2 0 G2~ <BLANKLINE> root restrictions G2 => A2: <BLANKLINE> O---O 1 2 A2 <BLANKLINE> 0 => 2 2 => 1 <BLANKLINE> For more detailed information use verbose=True In this example, `0` is the affine root, that is, the negative of the highest root, for `"G2"`. If `i => j` is printed, this means that the i-th simple (or affine) root of the ambient group restricts to the j-th simple root of the subgroup. For reference the Dynkin diagrams are also printed. The extended Dynkin diagram of the ambient group is printed if the affine root restricts to a simple root. More information is printed if the parameter `verbose` is true. """ Rspace = RootSystem(self._R).ambient_space() Sspace = RootSystem(self._S).ambient_space() if self._R.is_compound(): raise ValueError("Cannot describe branching rule from reducible type") if not no_r: print("\n%r" % self._R.affine().dynkin_diagram()) if self._S.is_compound(): for j in range(len(self._S.component_types())): ctype = self._S.component_types()[j] component_rule = self*branching_rule(self._S, ctype, "proj%s" % (j + 1)) print("\nprojection %d on %s " % (j + 1, ctype._repr_(compact=True)), component_rule.describe(verbose=verbose, no_r=True)) if not verbose: print("\nfor more detailed information use verbose=True") else: print("root restrictions %s => %s:" % (self._R._repr_(compact=True), self._S._repr_(compact=True))) print("\n%r\n" % self._S.dynkin_diagram()) for j in self._R.affine().index_set(): if j == 0: r = -Rspace.highest_root() else: r = Rspace.simple_roots()[j] resr = Sspace(self(list(r.to_vector()))) if debug: print("root %d: r = %s, b(r)=%s" % (j, r, resr)) done = False if resr == Sspace.zero(): done = True print("%s => (zero)" % j) else: for s in Sspace.roots(): if s == resr: for i in self._S.index_set(): if s == Sspace.simple_root(i): print("%s => %s" % (j, i)) done = True break if not done: done = True if verbose: print("%s => root %s" % (j, s)) if not done: done = True if verbose: print("%s => weight %s" % (j, resr)) if verbose: print("\nfundamental weight restrictions %s => %s:" % (self._R._repr_(compact=True),self._S._repr_(compact=True))) for j in self._R.index_set(): resfw = Sspace(self(list(Rspace.fundamental_weight(j).to_vector()))) print("%d => %s" % (j, tuple([resfw.inner_product(a) for a in Sspace.simple_coroots()]))) if not no_r and not verbose: print("\nFor more detailed information use verbose=True") def branch(self, chi, style=None): """ INPUT: - ``chi`` -- A character of the WeylCharacterRing with Cartan type self.Rtype(). Returns the branched character. EXAMPLES:: sage: G2=WeylCharacterRing("G2",style="coroots") sage: chi=G2(1,1); chi.degree() 64 sage: b=G2.maximal_subgroup("A2"); b extended branching rule G2 => A2 sage: b.branch(chi) A2(0,1) + A2(1,0) + A2(0,2) + 2*A2(1,1) + A2(2,0) + A2(1,2) + A2(2,1) sage: A2=WeylCharacterRing("A2",style="coroots"); A2 The Weyl Character Ring of Type A2 with Integer Ring coefficients sage: chi.branch(A2,rule=b) A2(0,1) + A2(1,0) + A2(0,2) + 2*A2(1,1) + A2(2,0) + A2(1,2) + A2(2,1) """ from sage.combinat.root_system.weyl_characters import WeylCharacterRing if style is None: style = chi.parent()._style S = WeylCharacterRing(self.Stype(), style=style) return chi.branch(S, rule=self) def branching_rule(Rtype, Stype, rule="default"): """ Creates a branching rule. INPUT: - ``R`` -- the Weyl Character Ring of `G` - ``S`` -- the Weyl Character Ring of `H` - ``rule`` -- a string describing the branching rule as a map from the weight space of `S` to the weight space of `R`. If the rule parameter is omitted, in some cases, a default rule is supplied. See :func:`~sage.combinat.root_system.branching_rules.branch_weyl_character`. EXAMPLES:: sage: rule = branching_rule(CartanType("A3"),CartanType("C2"),"symmetric") sage: [rule(x) for x in WeylCharacterRing("A3").fundamental_weights()] [[1, 0], [1, 1], [1, 0]] """ if rule == "plethysm": try: S = sage.combinat.root_system.weyl_characters.WeylCharacterRing(Stype.split("(")[0], style="coroots") chi = S(eval("("+Stype.split("(")[1])) except Exception: S = sage.combinat.root_system.weyl_characters.WeylCharacterRing(Stype.split(".")[0], style="coroots") chi = eval("S." + Stype.split(".")[1]) return branching_rule_from_plethysm(chi, Rtype) Rtype = CartanType(Rtype) Stype = CartanType(Stype) r = Rtype.rank() s = Stype.rank() rdim = Rtype.root_system().ambient_space().dimension() sdim = Stype.root_system().ambient_space().dimension() if Rtype.is_compound(): Rtypes = Rtype.component_types() if isinstance(rule, str): if rule[:4] == "proj": name = rule proj = [int(j)-1 for j in rule[4:]] rule = [] for j in range(len(Rtypes)): if j in proj: rule.append("identity") else: rule.append("omit") elif rule == "diagonal": if not Stype.is_compound(): k = len(Rtypes) n = RootSystem(Stype).ambient_space().dimension() return BranchingRule(Rtype, Stype, lambda x: [sum(x[i+n*j] for j in range(k)) for i in range(n)], "diagonal") raise ValueError("invalid Cartan types for diagonal branching rule") else: raise ValueError("Rule not found") else: name = repr(rule) rules = [] stor = [] for i in range(len(Rtypes)): l = rule[i] if l != "omit": if l == "identity": rules.append(BranchingRule(Rtypes[i], Rtypes[i], lambda x: x, "identity")) else: rules.append(l) stor.append(i) shifts = Rtype._shifts Stypes = [CartanType(ru._S) for ru in rules] ntypes = len(Stypes) if Stype.is_compound(): def br(x): yl = [] for i in range(ntypes): yl.append(rules[i](x[shifts[stor[i]]:shifts[stor[i]+1]])) return flatten(yl) else: j = stor[0] rulej = rules[0] def br(x): return rulej(x[shifts[j]:shifts[j+1]]) return BranchingRule(Rtype, Stype, br, name) if Stype.is_compound(): stypes = Stype.component_types() if rule == "default": if not Rtype.is_compound(): if Stype.is_compound() and s == r-1: try: return branching_rule(Rtype, Stype, rule="levi") except Exception: pass if Rtype[0] == "A": if Stype[0] == "B" and r == 2*s: return branching_rule(Rtype, Stype, rule="symmetric") elif Stype[0] == "C" and r == 2*s-1: return branching_rule(Rtype, Stype, rule="symmetric") elif Stype[0] == "D" and r == 2*s-1: return branching_rule(Rtype, Stype, rule="symmetric") elif Rtype[0] == "B" and Stype[0] == "D" and r == s: return branching_rule(Rtype, Stype, rule="extended") elif Rtype[0] == "D" and Stype[0] == "B" and r == s+1: return branching_rule(Rtype, Stype, rule="symmetric") if s == r-1: try: return branching_rule(Rtype, Stype, rule="levi") except Exception: pass raise ValueError("No default rule found (you must specify the rule)") elif rule == "identity": if Rtype is not Stype: raise ValueError("Cartan types must match for identity rule") return BranchingRule(Rtype, Stype, lambda x: x, "identity") elif rule == "levi": if not s == r-1: raise ValueError("Incompatible ranks") if Rtype[0] == 'A': if Stype.is_compound(): if all(ct[0] == 'A' for ct in stypes) and rdim == sdim: return BranchingRule(Rtype, Stype, lambda x: x, "levi") else: raise ValueError("Rule not found") elif Stype[0] == 'A': return BranchingRule(Rtype, Stype, lambda x: list(x)[:r], "levi") else: raise ValueError("Rule not found") elif Rtype[0] in ['B', 'C', 'D']: if Stype.is_atomic(): if Stype[0] == 'A': return BranchingRule(Rtype, Stype, lambda x: x, "levi") elif Stype[0] == Rtype[0]: return BranchingRule(Rtype, Stype, lambda x: list(x)[1:], "levi") elif stypes[-1][0] == Rtype[0] and all(t[0] == 'A' for t in stypes[:-1]): return BranchingRule(Rtype, Stype, lambda x: x, "levi") else: raise ValueError("Rule not found") elif Rtype == CartanType("E6"): if Stype == CartanType("D5"): return BranchingRule(Rtype, Stype, lambda x: [-x[4],-x[3],-x[2],-x[1],-x[0]], "levi") elif Stype == CartanType("A5"): # non-maximal levi return branching_rule("E6","A5xA1","extended")*branching_rule("A5xA1","A5","proj1") elif Stype.is_compound(): if Stype[0] == CartanType("A4") and Stype[1] == CartanType("A1"): # non-maximal levi return branching_rule("E6","A5xA1","extended")*branching_rule("A5xA1","A4xA1",[branching_rule("A5","A4","levi"),"identity"]) if Stype[0] == CartanType("A1") and Stype[1] == CartanType("A4"): # non-maximal levi return branching_rule("E6","A1xA5","extended")*branching_rule("A1xA5","A1xA4",["identity",branching_rule("A5","A4","levi")]) elif Stype[0] == CartanType("A2") and Stype[1] == CartanType("A2") and Stype[2] == CartanType("A1"): # non-maximal levi return branching_rule("E6","A2xA2xA2","extended")*branching_rule("A2xA2xA2","A2xA2xA2",["identity","identity",branching_rule("A2","A2","automorphic")*branching_rule("A2","A1","levi")]) elif Stype[0] == CartanType("A2") and Stype[1] == CartanType("A1") and Stype[2] == CartanType("A2"): # non-maximal levi raise ValueError("Not implemented: use A2xA2xA1 levi or A2xA2xA2 extended rule. (Non-maximal Levi.)") elif Stype[0] == CartanType("A1") and Stype[1] == CartanType("A2") and Stype[2] == CartanType("A2"): # non-maximal levi raise ValueError("Not implemented: use A2xA2xA1 levi or A2xA2xA2 extended rule. (Non-maximal Levi.)") elif Rtype == CartanType("E7"): if Stype == CartanType("D6"): return branching_rule("E7","D6xA1","extended")*branching_rule("D6xA1","D6","proj1") # non-maximal levi if Stype == CartanType("E6"): return BranchingRule(Rtype, Stype, lambda x: [x[0], x[1], x[2], x[3], x[4], (x[5]+x[6]-x[7])/3, (2*x[5]+5*x[6]+x[7])/6, (-2*x[5]+x[6]+5*x[7])/6], "levi") elif Stype == CartanType("A6"): # non-maximal levi return branching_rule("E7","A7","extended")*branching_rule("A7","A7","automorphic")*branching_rule("A7","A6","levi") if Stype.is_compound(): if Stype[0] == CartanType("A5") and Stype[1] == CartanType("A1"): return branching_rule("E7","A5xA2","extended")*branching_rule("A5xA2","A5xA1",["identity",branching_rule("A2","A2","automorphic")*branching_rule("A2","A1","levi")]) elif Stype[0] == CartanType("A1") and Stype[1] == CartanType("A5"): raise NotImplementedError("Not implemented: use A5xA1") elif Rtype == CartanType("E8"): if Stype == CartanType("D7"): return BranchingRule(Rtype, Stype, lambda x: [-x[6],-x[5],-x[4],-x[3],-x[2],-x[1],-x[0]], "levi") elif Stype == CartanType("E7"): return BranchingRule(Rtype, Stype, lambda x: [x[0],x[1],x[2],x[3],x[4],x[5],(x[6]-x[7])/2,(x[7]-x[6])/2], "levi") elif Stype == CartanType("A7"): return branching_rule("E8","A8","extended")*branching_rule("A8","A7","levi") raise NotImplementedError("Not implemented yet: branch first using extended rule to get non-maximal levis") elif Rtype == CartanType("F4"): if Stype == CartanType("B3"): return BranchingRule(Rtype, Stype, lambda x: x[1:], "levi") elif Stype == CartanType("C3"): return BranchingRule(Rtype, Stype, lambda x: [x[1]-x[0],x[2]+x[3],x[2]-x[3]], "levi") else: raise NotImplementedError("Not implemented yet") elif Rtype == CartanType("G2") and Stype == CartanType("A1"): return BranchingRule(Rtype, Stype, lambda x: list(x)[1:][:2], "levi") else: raise ValueError("Rule not found") elif rule == "automorphic": if not Rtype == Stype: raise ValueError("Cartan types must agree for automorphic branching rule") elif Rtype[0] == 'A': def rule(x): y = [-i for i in x] y.reverse() return y return BranchingRule(Rtype, Stype, rule, "automorphic") elif Rtype[0] == 'D': def rule(x): x[len(x) - 1] = -x[len(x) - 1] return x return BranchingRule(Rtype, Stype, rule, "automorphic") elif Rtype[0] == 'E' and r == 6: M = matrix(QQ,[(3, 3, 3, -3, 0, 0, 0, 0), (3, 3, -3, 3, 0, 0, 0, 0), (3, -3, 3, 3, 0, 0, 0, 0), (-3, 3, 3, 3, 0, 0, 0, 0), (0, 0, 0, 0, -3, -3, -3, 3), (0, 0, 0, 0, -3, 5, -1, 1), (0, 0, 0, 0, -3, -1, 5, 1), (0, 0, 0, 0, 3, 1, 1, 5)])/6 return BranchingRule(Rtype, Stype, lambda x: tuple(M*vector(x)), "automorphic") else: raise ValueError("No automorphism found") elif rule == "triality": if not Rtype == Stype: raise ValueError("Triality is an automorphic type (for D4 only)") elif not Rtype[0] == 'D' and r == 4: raise ValueError("Triality is for D4 only") else: return BranchingRule(Rtype, Stype, lambda x: [(x[0]+x[1]+x[2]+x[3])/2,(x[0]+x[1]-x[2]-x[3])/2,(x[0]-x[1]+x[2]-x[3])/2,(-x[0]+x[1]+x[2]-x[3])/2], "triality") elif rule == "symmetric": if Rtype[0] == 'A': if (Stype[0] == 'C' or Stype[0] == 'D' and r == 2*s-1) or (Stype[0] == 'B' and r == 2*s): return BranchingRule(Rtype, Stype, lambda x: [x[i]-x[r-i] for i in range(s)], "symmetric") else: raise ValueError("Rule not found") elif Rtype[0] == 'D' and Stype[0] == 'B' and s == r-1: return BranchingRule(Rtype, Stype, lambda x: x[:s], "symmetric") elif Rtype == CartanType("D4") and Stype == CartanType("G2"): return BranchingRule(Rtype, Stype, lambda x: [x[0]+x[1], -x[1]+x[2], -x[0]-x[2]], "symmetric") elif Rtype == CartanType("E6") and Stype == CartanType("F4"): return BranchingRule(Rtype, Stype, lambda x: [(x[4]-3*x[5])/2,(x[0]+x[1]+x[2]+x[3])/2,(-x[0]-x[1]+x[2]+x[3])/2,(-x[0]+x[1]-x[2]+x[3])/2], "symmetric") elif Rtype == CartanType("E6") and Stype == CartanType("C4"): def f(x): [x0, x1, x2, x3, x4, x5] = x[:6] return [(x0+x1+x2+x3+x4-3*x5)/2, (-x0-x1-x2-x3+x4-3*x5)/2, -x0 + x3, -x1 + x2] return BranchingRule(Rtype, Stype, f, "symmetric") else: raise ValueError("Rule not found") elif rule == "extended" or rule == "orthogonal_sum": if rule == "extended" and not s == r: raise ValueError('Ranks should be equal for rule="extended"') if Stype.is_compound(): if Rtype[0] in ['B','D'] and all(t[0] in ['B','D'] for t in stypes): if Rtype[0] == 'D': rdeg = 2*r else: rdeg = 2*r+1 sdeg = 0 for t in stypes: if t[0] == 'D': sdeg += 2*t[1] else: sdeg += 2*t[1]+1 if rdeg == sdeg: return BranchingRule(Rtype, Stype, lambda x: x[:s], "orthogonal_sum") else: raise ValueError("Rule not found") elif Rtype[0] == 'C': if all(t[0] == Rtype[0] for t in stypes): return BranchingRule(Rtype, Stype, lambda x: x, "orthogonal_sum") if rule == "orthogonal_sum": raise ValueError("Rule not found") elif Rtype[0] == 'E': if r == 6: if stypes == [CartanType("A5"),CartanType("A1")]: M = matrix(QQ,[(-3, -3, -3, -3, -3, -5, -5, 5), (-9, 3, 3, 3, 3, 1, 1, -1), (3, -9, 3, 3, 3, 1, 1, -1), (3, 3, -9, 3, 3, 1, 1, -1), (3, 3, 3, -9, 3, 1, 1, -1), (3, 3, 3, 3, -9, 9, -3, 3), (-3, -3, -3, -3, -3, -1, 11, 1), (3, 3, 3, 3, 3, 1, 1, 11)])/12 return BranchingRule(Rtype, Stype, lambda x: tuple(M*vector(x)), "extended") if stypes == [CartanType("A1"),CartanType("A5")]: M = matrix(QQ,[(-3, -3, -3, -3, -3, -1, 11, 1), (3, 3, 3, 3, 3, 1, 1, 11), (-3, -3, -3, -3, -3, -5, -5, 5), (-9, 3, 3, 3, 3, 1, 1, -1), (3, -9, 3, 3, 3, 1, 1, -1), (3, 3, -9, 3, 3, 1, 1, -1), (3, 3, 3, -9, 3, 1, 1, -1), (3, 3, 3, 3, -9, 9, -3, 3)])/12 return BranchingRule(Rtype, Stype, lambda x: tuple(M*vector(x)), "extended") if stypes == [CartanType("A2"),CartanType("A2"),CartanType("A2")]: M = matrix(QQ,[(0, 0, -2, -2, -2, -2, -2, 2), (-3, 3, 1, 1, 1, 1, 1, -1), (3, -3, 1, 1, 1, 1, 1, -1), (0, 0, -2, -2, 4, 0, 0, 0), (0, 0, -2, 4, -2, 0, 0, 0), (0, 0, 4, -2, -2, 0, 0, 0), (0, 0, -2, -2, -2, 2, 2, -2), (3, 3, 1, 1, 1, -1, -1, 1), (-3, -3, 1, 1, 1, -1, -1, 1)])/6 return BranchingRule(Rtype, Stype, lambda x: tuple(M*vector(x)), "extended") elif r == 7: if stypes == [CartanType("D6"),CartanType("A1")]: return BranchingRule(Rtype, Stype, lambda x: [x[5],x[4],x[3],x[2],x[1],x[0],x[6],x[7]], "extended") elif stypes == [CartanType("A1"),CartanType("D6")]: return BranchingRule(Rtype, Stype, lambda x: [x[6],x[7],x[5],x[4],x[3],x[2],x[1],x[0]], "extended") elif stypes == [CartanType("A5"),CartanType("A2")]: M = matrix(QQ,[(5, 1, 1, 1, 1, 1, 0, 0), (-1, -5, 1, 1, 1, 1, 0, 0), (-1, 1, -5, 1, 1, 1, 0, 0), (-1, 1, 1, -5, 1, 1, 0, 0), (-1, 1, 1, 1, -5, 1, 0, 0), (-1, 1, 1, 1, 1, -5, 0, 0), (1, -1, -1, -1, -1, -1, 0, -6), (1, -1, -1, -1, -1, -1, -6, 0), (-2, 2, 2, 2, 2, 2, -3, -3)])/6 return BranchingRule(Rtype, Stype, lambda x: tuple(M*vector(x)), "extended") elif stypes == [CartanType("A3"),CartanType("A3"),CartanType("A1")]: M = matrix(QQ, [(0, 0, -1, -1, -1, -1, 2, -2), (0, 0, -1, -1, -1, -1, -2, 2), (-2, 2, 1, 1, 1, 1, 0, 0), (2, -2, 1, 1, 1, 1, 0, 0), (0, 0, -1, -1, -1, 3, 0, 0), (0, 0, -1, -1, 3, -1, 0, 0), (0, 0, -1, 3, -1, -1, 0, 0), (0, 0, 3, -1, -1, -1, 0, 0), (2, 2, 0, 0, 0, 0, -2, -2), (-2, -2, 0, 0, 0, 0, -2, -2)])/4 return BranchingRule(Rtype, Stype, lambda x: tuple(M*vector(x)), "extended") elif r == 8: if stypes == [CartanType("A4"),CartanType("A4")]: M = matrix(QQ,[(0, 0, 0, -4, -4, -4, -4, 4), (-5, 5, 5, 1, 1, 1, 1, -1), (5, -5, 5, 1, 1, 1, 1, -1), (5, 5, -5, 1, 1, 1, 1, -1), (-5, -5, -5, 1, 1, 1, 1, -1), (0, 0, 0, -8, 2, 2, 2, -2), (0, 0, 0, 2, -8, 2, 2, -2), (0, 0, 0, 2, 2, -8, 2, -2), (0, 0, 0, 2, 2, 2, -8, -2), (0, 0, 0, 2, 2, 2, 2, 8)])/10 return BranchingRule(Rtype, Stype, lambda x: tuple(M*vector(x)), "extended") elif len(stypes) == 3: if 5 in stypes[0][i]: # S is A5xA2xA1 raise NotImplementedError("Not maximal: first branch to A7xA1") elif stypes == [CartanType("D5"), CartanType("A3")]: raise NotImplementedError("Not maximal: first branch to D8 then D5xD3=D5xA3") elif stypes == [CartanType("A3"), CartanType("D5")]: raise NotImplementedError("Not maximal: first branch to D8 then D5xD3=D5xA3") elif stypes == [CartanType("E6"), CartanType("A2")]: def br(x): return [x[0], x[1], x[2], x[3], x[4], (x[5]+x[6]-x[7])/3,(x[5]+x[6]-x[7])/3, (-x[5]-x[6]+x[7])/3, (-x[5]-x[6]-2*x[7])/3, (-x[5]+2*x[6]+x[7])/3, (2*x[5]-x[6]+x[7])/3] return BranchingRule(Rtype, Stype, br, "extended") elif stypes == [CartanType("E7"), CartanType("A1")]: def br(x): return [x[0], x[1], x[2], x[3], x[4], x[5], (x[6]-x[7])/2, (-x[6]+x[7])/2, (-x[6]-x[7])/2, (x[6]+x[7])/2] return BranchingRule(Rtype, Stype, br, "extended") raise ValueError("Rule not found") elif Rtype[0] == 'F': if stypes == [CartanType("C3"), CartanType("A1")]: return BranchingRule(Rtype, Stype, lambda x: [x[0]-x[1],x[2]+x[3],x[2]-x[3],(-x[0]-x[1])/2,(x[0]+x[1])/2], "extended") elif stypes == [CartanType("A1"), CartanType("C3")]: return BranchingRule(Rtype, Stype, lambda x: [(-x[0]-x[1])/2,(x[0]+x[1])/2,x[0]-x[1],x[2]+x[3],x[2]-x[3]], "extended") elif stypes == [CartanType("A2"), CartanType("A2")]: M = matrix(QQ,[(-2, -1, -1, 0), (1, 2, -1, 0), (1, -1, 2, 0), (1, -1, -1, 3), (1, -1, -1, -3), (-2, 2, 2, 0)])/3 elif stypes == [CartanType("A3"), CartanType("A1")]: M = matrix(QQ,[(-3, -1, -1, -1), (1, 3, -1, -1), (1, -1, 3, -1), (1, -1, -1, 3), (2, -2, -2, -2), (-2, 2, 2, 2)])/4 elif stypes == [CartanType("A1"), CartanType("A3")]: M = matrix(QQ,[(2, -2, -2, -2), (-2, 2, 2, 2), (-3, -1, -1, -1), (1, 3, -1, -1), (1, -1, 3, -1), (1, -1, -1, 3)])/4 else: raise ValueError("Rule not found") return BranchingRule(Rtype, Stype, lambda x: tuple(M*vector(x)), "extended") elif Rtype[0] == 'G': if stypes == [CartanType("A1"), CartanType("A1")]: return BranchingRule(Rtype, Stype, lambda x: [(x[1]-x[2])/2,-(x[1]-x[2])/2, x[0]/2, -x[0]/2], "extended") raise ValueError("Rule not found") else: # irreducible Stype if Rtype[0] == 'B' and Stype[0] == 'D': return BranchingRule(Rtype, Stype, lambda x: x, "extended") elif Rtype == CartanType("E7"): if Stype == CartanType("A7"): M = matrix(QQ, [(-1, -1, -1, -1, -1, -1, 2, -2), (-1, -1, -1, -1, -1, -1, -2, 2), (-3, 1, 1, 1, 1, 1, 0, 0), (1, -3, 1, 1, 1, 1, 0, 0), (1, 1, -3, 1, 1, 1, 0, 0), (1, 1, 1, -3, 1, 1, 0, 0), (1, 1, 1, 1, -3, 1, 2, 2), (1, 1, 1, 1, 1, -3, 2, 2)])/4 return BranchingRule(Rtype, Stype, lambda x: tuple(M*vector(x)), "extended") elif Rtype == CartanType("E8"): if Stype == CartanType("D8"): return BranchingRule(Rtype, Stype, lambda x: [-x[7],x[6],x[5],x[4],x[3],x[2],x[1],x[0]], "extended") elif Stype == CartanType("A8"): M = matrix([(-2, -2, -2, -2, -2, -2, -2, 2), (-5, 1, 1, 1, 1, 1, 1, -1), (1, -5, 1, 1, 1, 1, 1, -1), (1, 1, -5, 1, 1, 1, 1, -1), (1, 1, 1, -5, 1, 1, 1, -1), (1, 1, 1, 1, -5, 1, 1, -1), (1, 1, 1, 1, 1, -5, 1, -1), (1, 1, 1, 1, 1, 1, -5, -1), (1, 1, 1, 1, 1, 1, 1, 5)])/6 return BranchingRule(Rtype, Stype, lambda x: tuple(M*vector(x)), "extended") elif Rtype == CartanType("F4") and Stype == CartanType("B4"): return BranchingRule(Rtype, Stype, lambda x: [-x[0], x[1], x[2], x[3]], "extended") elif Rtype == CartanType("G2") and Stype == CartanType("A2"): return BranchingRule(Rtype, Stype, lambda x: [(-x[1]+x[2])/3, (-x[0]+x[1])/3, (x[0]-x[2])/3], "extended") else: raise ValueError("Rule not found") elif rule == "isomorphic": if r != s: raise ValueError("Incompatible ranks") if Rtype == Stype: return BranchingRule(Rtype, Stype, lambda x: x, "isomorphic") elif Rtype == CartanType("B2") and Stype == CartanType("C2"): def rule(x): [x1, x2] = x return [x1 + x2, x1 - x2] return BranchingRule(Rtype, Stype, rule, "isomorphic") elif Rtype == CartanType("C2") and Stype == CartanType("B2"): def rule(x): [x1, x2] = x return [(x1 + x2) / 2, (x1 - x2) / 2] return BranchingRule(Rtype, Stype, rule, "isomorphic") elif Rtype == CartanType("B1") and Stype == CartanType("A1"): return BranchingRule(Rtype, Stype, lambda x: [x[0],-x[0]], "isomorphic") elif Rtype == CartanType("A1") and Stype == CartanType("B1"): return BranchingRule(Rtype, Stype, lambda x: [(x[0]-x[1])/2], "isomorphic") elif Rtype == CartanType("C1") and Stype == CartanType("A1"): return BranchingRule(Rtype, Stype, lambda x: [x[0]/2,-x[0]/2], "isomorphic") elif Rtype == CartanType("A1") and Stype == CartanType("C1"): return BranchingRule(Rtype, Stype, lambda x: [x[0]-x[1]], "isomorphic") elif Rtype == CartanType("A3") and Stype == CartanType("D3"): def rule(x): [x1, x2, x3, x4] = x return [(x1+x2-x3-x4)/2, (x1-x2+x3-x4)/2, (x1-x2-x3+x4)/2] return BranchingRule(Rtype, Stype, rule, "isomorphic") elif Rtype == CartanType("D3") and Stype == CartanType("A3"): def rule(x): [t1, t2, t3] = x return [(t1+t2+t3)/2, (t1-t2-t3)/2, (-t1+t2-t3)/2, (-t1-t2+t3)/2] return BranchingRule(Rtype, Stype, rule, "isomorphic") elif Rtype == CartanType("D2") and Stype == CartanType("A1xA1"): def rule(x): [t1, t2] = x return [(t1-t2)/2, -(t1-t2)/2, (t1+t2)/2, -(t1+t2)/2] return BranchingRule(Rtype, Stype, rule, "isomorphic") else: raise ValueError("Rule not found") elif rule == "tensor" or rule == "tensor-debug": if not Stype.is_compound(): raise ValueError("Tensor product requires more than one factor") if len(stypes) != 2: raise ValueError("Not implemented") if Rtype[0] == 'A': nr = Rtype[1]+1 elif Rtype[0] == 'B': nr = 2*Rtype[1]+1 elif Rtype[0] in ['C', 'D']: nr = 2*Rtype[1] else: raise ValueError("Rule not found") [s1, s2] = [stypes[i][1] for i in range(2)] ns = [s1, s2] for i in range(2): if stypes[i][0] == 'A': ns[i] = ns[i]+1 if stypes[i][0] == 'B': ns[i] = 2*ns[i]+1 if stypes[i][0] in ['C','D']: ns[i] = 2*ns[i] if nr != ns[0]*ns[1]: raise ValueError("Ranks don't agree with tensor product") if Rtype[0] == 'A': if all(t[0] == 'A' for t in stypes): def rule(x): ret = [sum(x[i*ns[1]:(i+1)*ns[1]]) for i in range(ns[0])] ret.extend([sum(x[ns[1]*j+i] for j in range(ns[0])) for i in range(ns[1])]) return ret return BranchingRule(Rtype, Stype, rule, "tensor") else: raise ValueError("Rule not found") elif Rtype[0] == 'B': if not all(t[0] == 'B' for t in stypes): raise ValueError("Rule not found") elif Rtype[0] == 'C': if stypes[0][0] in ['B','D'] and stypes[1][0] == 'C': pass elif stypes[1][0] in ['B','D'] and stypes[0][0] == 'C': pass else: raise ValueError("Rule not found") elif Rtype[0] == 'D': if stypes[0][0] in ['B','D'] and stypes[1][0] == 'D': pass elif stypes[1][0] == 'B' and stypes[0][0] == 'D': pass elif stypes[1][0] == 'C' and stypes[0][0] == 'C': pass else: raise ValueError("Rule not found") rows = [] for i in range(s1): for j in range(s2): nextrow = (s1+s2)*[0] nextrow[i] = 1 nextrow[s1+j] = 1 rows.append(nextrow) if stypes[1][0] == 'B': for i in range(s1): nextrow = (s1+s2)*[0] nextrow[i] = 1 rows.append(nextrow) for i in range(s1): for j in range(s2): nextrow = (s1+s2)*[0] nextrow[i] = 1 nextrow[s1+j] = -1 rows.append(nextrow) if stypes[0][0] == 'B': for j in range(s2): nextrow = (s1+s2)*[0] nextrow[s1+j] = 1 rows.append(nextrow) mat = matrix(rows).transpose() if rule == "tensor-debug": print(mat) return BranchingRule(Rtype, Stype, lambda x: tuple(mat*vector(x)), "tensor") elif rule == "symmetric_power": if Stype[0] == 'A' and s == 1: if Rtype[0] == 'B': def rule(x): a = sum((r-i)*x[i] for i in range(r)) return [a,-a] return BranchingRule(Rtype, Stype, rule, "symmetric_power") elif Rtype[0] == 'C': def rule(x): a = sum((2*r-2*i-1)*x[i] for i in range(r)) return [a/2,-a/2] return BranchingRule(Rtype, Stype, rule, "symmetric_power") elif rule == "miscellaneous": if Rtype[0] == 'B' and Stype[0] == 'G' and r == 3: return BranchingRule(Rtype, Stype, lambda x: [x[0]+x[1], -x[1]+x[2], -x[0]-x[2]], "miscellaneous") elif Rtype == CartanType("E6"): if Stype.is_compound(): if stypes == [CartanType("A2"),CartanType("G2")]: return BranchingRule(Rtype, Stype, lambda x: [-2*x[5],x[5]+x[4],x[5]-x[4],x[2]+x[3],x[1]-x[2],-x[1]-x[3]], "miscellaneous") elif stypes == [CartanType("G2"),CartanType("A2")]: return BranchingRule(Rtype, Stype, lambda x: [x[2]+x[3],x[1]-x[2],-x[1]-x[3],-2*x[5],x[5]+x[4],x[5]-x[4]], "miscellaneous") else: if Stype == CartanType("G2"): return BranchingRule(Rtype, Stype, lambda x: [x[2]+x[3]+x[4]-3*x[5], x[1]-2*x[2]-x[3], -x[1]+x[2]-x[4]+3*x[5]],"miscellaneous") if Stype == CartanType("A2"): return BranchingRule(Rtype, Stype, lambda x: [x[2]+x[3]+x[4]-3*x[5], x[1]-2*x[2]-x[3], -x[1]+x[2]-x[4]+3*x[5]],"miscellaneous") elif Rtype == CartanType("E7"): if Stype.is_compound(): if stypes == [CartanType("C3"), CartanType("G2")]: return BranchingRule(Rtype, Stype, lambda x: [-2*x[6],x[4]+x[5],-x[4]+x[5],x[1]+x[3],x[2]-x[3],-x[1]-x[2]], "miscellaneous") elif stypes == [CartanType("G2"), CartanType("C3")]: return BranchingRule(Rtype, Stype, lambda x: [x[1]+x[3],x[2]-x[3],-x[1]-x[2],-2*x[6],x[4]+x[5],-x[4]+x[5]], "miscellaneous") elif stypes == [CartanType("F4"), CartanType("A1")]: def f(x): [x0, x1, x2, x3, x4, x5, x6] = x[:7] return [(x4-x5)/2-x6, (x0+x1+x2+x3)/2, (-x0-x1+x2+x3)/2, (-x0+x1-x2+x3)/2, x5-x6, x6-x5] return BranchingRule(Rtype, Stype, f, "miscellaneous") elif stypes == [CartanType("A1"), CartanType("F4")]: def f(x): [x0, x1, x2, x3, x4, x5, x6] = x[:7] return [x5-x6, x6-x5, (x4-x5)/2-x6, (x0+x1+x2+x3)/2, (-x0-x1+x2+x3)/2, (-x0+x1-x2+x3)/2] return BranchingRule(Rtype, Stype, f, "miscellaneous") elif stypes == [CartanType("A1"), CartanType("A1")]: return BranchingRule(Rtype, Stype, lambda x: [x[1]+2*x[2]-2*x[3]-x[4]-2*x[6], -x[1]-2*x[2]+2*x[3]+x[4]+2*x[6], (x[3]+x[4]+x[5]-3*x[6]),-(x[3]+x[4]+x[5]-3*x[6])], "miscellaneous") elif stypes == [CartanType("G2"), CartanType("A1")]: def f(x): return [(x[0]-x[1]+x[2]+3*x[3]+x[4]-x[5]+2*x[6])/2, (-3*x[0]-x[1]-x[2]-x[3]+x[4]+x[5]-2*x[6])/2, (2*x[0]+2*x[1]-2*x[3]-2*x[4])/2, (x[0]+x[1]+x[2]+x[3]+x[4]+x[5]-4*x[6])/2, -(x[0]+x[1]+x[2]+x[3]+x[4]+x[5]-4*x[6])/2] return BranchingRule(Rtype, Stype, f, "miscellaneous") elif stypes == [CartanType("A1"), CartanType("G2")]: def f(x): return [(x[0]+x[1]+x[2]+x[3]+x[4]+x[5]-4*x[6])/2, -(x[0]+x[1]+x[2]+x[3]+x[4]+x[5]-4*x[6])/2, (x[0]-x[1]+x[2]+3*x[3]+x[4]-x[5]+2*x[6])/2, (-3*x[0]-x[1]-x[2]-x[3]+x[4]+x[5]-2*x[6])/2, (2*x[0]+2*x[1]-2*x[3]-2*x[4])/2] return BranchingRule(Rtype, Stype, f, "miscellaneous") elif Stype == CartanType("A2"): return BranchingRule(Rtype, Stype, lambda x: (x[1]+x[2]+2*x[4]-4*x[6],-2*x[1]-x[2]+x[3]-2*x[4]+2*x[5],x[1]-x[3]-2*x[5]+4*x[6]), "miscellaneous") elif Rtype == CartanType("E8"): if Stype.is_compound(): if stypes == [CartanType("F4"),CartanType("G2")]: return BranchingRule(Rtype, Stype, lambda x: [x[7], x[6], x[5], x[4], x[1]+x[3], -x[3]+x[2], -x[1]-x[2]], "miscellaneous") elif stypes == [CartanType("G2"),CartanType("F4")]: return BranchingRule(Rtype, Stype, lambda x: [x[1]+x[3], -x[3]+x[2], -x[1]-x[2], x[7], x[6], x[5], x[4]], "miscellaneous") elif stypes == [CartanType("A2"), CartanType("A1")]: def f(x): return [(x[0]-x[1]+x[2]+x[3]+3*x[4]+x[5]-x[6]-x[7])/2, (-3*x[0]-x[1]-x[2]-x[3]-x[4]+x[5]+x[6]+x[7])/2, (2*x[0]+2*x[1]-2*x[4]-2*x[5])/2, (x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]+5*x[7])/2, -(x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]+5*x[7])/2] return BranchingRule("E8","A2xA1",f,"miscellaneous") elif stypes == [CartanType("A1"), CartanType("A2")]: def f(x): return [(x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]+5*x[7])/2, -(x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]+5*x[7])/2, (x[0]-x[1]+x[2]+x[3]+3*x[4]+x[5]-x[6]-x[7])/2, (-3*x[0]-x[1]-x[2]-x[3]-x[4]+x[5]+x[6]+x[7])/2, (2*x[0]+2*x[1]-2*x[4]-2*x[5])/2] return BranchingRule("E8", "A1xA2", f, "miscellaneous") elif Stype == CartanType("B2"): return BranchingRule("E8", "B2", lambda x: [-x[0] + x[2] + x[5] + 3*x[7], 2*x[0] - x[2] + x[3] + x[4] + 2*x[6] + x[7]], "miscellaneous") elif Rtype[0] == 'F': if Stype.is_compound(): if stypes == [CartanType("A1"), CartanType("G2")]: return BranchingRule("F4", "A1xG2", lambda x: [2*x[0], -2*x[0], x[1]+x[2], -x[2]+x[3], -x[1]-x[3]], "miscellaneous") elif stypes == [CartanType("G2"), CartanType("A1")]: return BranchingRule("F4","G2xA1", lambda x: [x[1]+x[2], -x[2]+x[3], -x[1]-x[3], 2*x[0], -2*x[0]], "miscellaneous") raise ValueError("Rule not found") elif rule in ["i", "ii", "iii", "iv", "v", "vi", "vii"]: if Stype != CartanType("A1"): raise ValueError("Wrong target Cartan Type for rule %s" % rule) if rule == "i" and Rtype == CartanType("G2"): return BranchingRule(Rtype, Stype, lambda x: [(5*x[0]-x[1]-4*x[2])/3,-(5*x[0]-x[1]-4*x[2])/3], "i") elif rule == "ii" and Rtype == CartanType("F4"): return BranchingRule(Rtype, Stype, lambda x: [8*x[0]+3*x[1]+2*x[2]+x[3],-(8*x[0]+3*x[1]+2*x[2]+x[3])], "ii") elif rule == "iii" and Rtype == CartanType("E7"): return BranchingRule(Rtype, Stype, lambda x: [x[1]+2*x[2]+3*x[3]+4*x[4]+5*x[5]-17*x[6],-(x[1]+2*x[2]+3*x[3]+4*x[4]+5*x[5]-17*x[6])], "iii") elif rule == "iv" and Rtype == CartanType("E7"): return BranchingRule(Rtype, Stype, lambda x: [x[1]+x[2]+2*x[3]+3*x[4]+4*x[5]-13*x[6],-(x[1]+x[2]+2*x[3]+3*x[4]+4*x[5]-13*x[6])], "iv") elif rule == "v" and Rtype == CartanType("E8"): return BranchingRule(Rtype, Stype, lambda x: [x[1]+2*x[2]+3*x[3]+4*x[4]+5*x[5]+6*x[6]+23*x[7],-(x[1]+2*x[2]+3*x[3]+4*x[4]+5*x[5]+6*x[6]+23*x[7])], "v") elif rule == "vi" and Rtype == CartanType("E8"): return BranchingRule(Rtype, Stype, lambda x: [x[1]+x[2]+2*x[3]+3*x[4]+4*x[5]+5*x[6]+18*x[7],-(x[1]+x[2]+2*x[3]+3*x[4]+4*x[5]+5*x[6]+18*x[7])], "vi") elif rule == "vii" and Rtype == CartanType("E8"): return BranchingRule(Rtype, Stype, lambda x: [x[1]+x[2]+2*x[3]+2*x[4]+3*x[5]+4*x[6]+15*x[7],-(x[1]+x[2]+2*x[3]+2*x[4]+3*x[5]+4*x[6]+15*x[7])], "vii") raise ValueError("Wrong source Cartan Type for rule %s" % rule) raise ValueError("Rule not found") get_branching_rule = branching_rule def branching_rule_from_plethysm(chi, cartan_type, return_matrix=False): r""" Create the branching rule of a plethysm. INPUT: - ``chi`` -- the character of an irreducible representation `\pi` of a group `G` - ``cartan_type`` -- a classical Cartan type (`A`,`B`,`C` or `D`). It is assumed that the image of the irreducible representation pi naturally has its image in the group `G`. Returns a branching rule for this plethysm. EXAMPLES: The adjoint representation `SL(3) \to GL(8)` factors through `SO(8)`. The branching rule in question will describe how representations of `SO(8)` composed with this homomorphism decompose into irreducible characters of `SL(3)`:: sage: A2 = WeylCharacterRing("A2") sage: A2 = WeylCharacterRing("A2", style="coroots") sage: ad = A2.adjoint_representation(); ad A2(1,1) sage: ad.degree() 8 sage: ad.frobenius_schur_indicator() 1 This confirms that `ad` has degree 8 and is orthogonal, hence factors through `SO(8)` which is type `D_4`:: sage: br = branching_rule_from_plethysm(ad,"D4") sage: D4 = WeylCharacterRing("D4") sage: [D4(f).branch(A2,rule = br) for f in D4.fundamental_weights()] [A2(1,1), A2(0,3) + A2(1,1) + A2(3,0), A2(1,1), A2(1,1)] """ ct = CartanType(cartan_type) if ct[0] not in ["A", "B", "C", "D"]: raise ValueError("not implemented for type {}".format(ct[0])) if ct[0] == "A": ret = [] ml = chi.weight_multiplicities() for v in ml: n = ml[v] ret.extend(n * [v.to_vector()]) M = matrix(ret).transpose() if len(M.columns()) != ct[1] + 1: raise ValueError("representation has wrong degree for type {}".format(ct)) return BranchingRule(ct, chi.parent().cartan_type(), lambda x: tuple(M*vector(x)), "plethysm (along %s)" % chi) if ct[0] in ["B", "D"]: if chi.frobenius_schur_indicator() != 1: raise ValueError("character is not orthogonal") if ct[0] == "C": if chi.frobenius_schur_indicator() != -1: raise ValueError("character is not symplectic") if ct[0] == "B": if is_even(chi.degree()): raise ValueError("degree is not odd") if ct[0] in ["C", "D"]: if is_odd(chi.degree()): raise ValueError("degree is not even") ret = [] ml = chi.weight_multiplicities() for v in ml: n = ml[v] vec = v.to_vector() if all(x == 0 for x in vec): if ct[0] == "B": n = (n-1)/2 else: n = n/2 elif [x for x in vec if x != 0][0] < 0: continue ret.extend(n * [vec]) M = matrix(ret).transpose() if len(M.columns()) != ct.root_system().ambient_space().dimension(): raise ValueError("representation has wrong degree for type {}".format(ct)) if return_matrix: return M else: return BranchingRule(ct, chi.parent().cartan_type(), lambda x: tuple(M*vector(x)), "plethysm (along %s)" % chi) def maximal_subgroups(ct, mode="print_rules"): """ Given a classical Cartan type (of rank less than or equal to 8) this prints the Cartan types of maximal subgroups, with a method of obtaining the branching rule. The string to the right of the colon in the output is a command to create a branching rule. INPUT: - ``ct`` -- a classical irreducible Cartan type Returns a list of maximal subgroups of ct. EXAMPLES:: sage: from sage.combinat.root_system.branching_rules import maximal_subgroups sage: maximal_subgroups("D4") B3:branching_rule("D4","B3","symmetric") A2:branching_rule("D4","A2(1,1)","plethysm") A1xC2:branching_rule("D4","C1xC2","tensor")*branching_rule("C1xC2","A1xC2",[branching_rule("C1","A1","isomorphic"),"identity"]) A1xA1xA1xA1:branching_rule("D4","D2xD2","orthogonal_sum")*branching_rule("D2xD2","A1xA1xA1xA1",[branching_rule("D2","A1xA1","isomorphic"),branching_rule("D2","A1xA1","isomorphic")]) .. SEEALSO:: :meth:`~sage.combinat.root_system.weyl_characters.WeylCharacterRing.ParentMethods.maximal_subgroups` """ if CartanType(ct) == CartanType("A2"): rul = ["""A1:branching_rule("A2","A1","levi")"""] elif CartanType(ct) == CartanType("A3"): rul = ["""A2:branching_rule("A3","A2","levi")""", """A1xA1:branching_rule("A3","A1xA1","tensor")""", """C2:branching_rule("A3","C2","symmetric")""", """A1xA1:branching_rule("A3","A1xA1","levi")"""] elif CartanType(ct) == CartanType("A4"): rul = ["""A3:branching_rule("A4","A3","levi")""", """B2:branching_rule("A4","B2","symmetric")""", """A1xA2:branching_rule("A4","A1xA2","levi")"""] elif CartanType(ct) == CartanType("A5"): rul = ["""A4:branching_rule("A5","A4","levi")""", """A3:branching_rule("A5","D3","symmetric")*branching_rule("D3","A3","isomorphic")""", """A3:branching_rule("A5","A3(0,1,0)","plethysm") # alternative""", """C3:branching_rule("A5","C3","symmetric")""", """A2:branching_rule("A5","A2(2,0)","plethysm")""", """A1xA2:branching_rule("A5","A1xA2","tensor")""", """A1xA3:branching_rule("A5","A1xA3","levi")""", """A2xA2:branching_rule("A5","A2xA2","levi")"""] elif CartanType(ct) == CartanType("A6"): rul = ["""A5:branching_rule("A6","A5","levi")""", """B3:branching_rule("A6","B3","symmetric")""", """A1xA4:branching_rule("A6","A1xA4","levi")""", """A2xA3:branching_rule("A6","A2xA3","levi")"""] elif CartanType(ct) == CartanType("A7"): rul = ["""A6:branching_rule("A7","A6","levi")""", """C4:branching_rule("A7","C4","symmetric")""", """D4:branching_rule("A7","D4","symmetric")""", """A1xA3:branching_rule("A7","A1xA3","tensor")""", """A1xA5:branching_rule("A7","A1xA5","levi")""", """A2xA4:branching_rule("A7","A2xA4","levi")""", """A3xA3:branching_rule("A7","A3xA3","levi")"""] elif CartanType(ct) == CartanType("A8"): rul = ["""A7:branching_rule("A8","A7","levi")""", """B4:branching_rule("A8","B4","symmetric")""", """A2xA2:branching_rule("A8","A2xA2","tensor")""", """A1xA6:branching_rule("A8","A1xA6","levi")""", """A2xA5:branching_rule("A8","A2xA5","levi")""", """A3xA4:branching_rule("A8","A3xA4","levi")"""] elif CartanType(ct) == CartanType("B3"): rul = ["""G2:branching_rule("B3","G2","miscellaneous")""", """A3:branching_rule("B3","D3","extended")*branching_rule("D3","A3","isomorphic")""", """A1xA1xA1:branching_rule("B3","D2xB1","orthogonal_sum")*branching_rule("D2xB1","A1xA1xA1",[branching_rule("D2","A1xA1","isomorphic"),branching_rule("B1","A1","isomorphic")])"""] elif CartanType(ct) == CartanType("B4"): rul = ["""D4:branching_rule("B4","D4","extended")""", """A1:branching_rule("B4","A1","symmetric_power")""", """A1xA1:branching_rule("B4","B1xB1","tensor")*branching_rule("B1xB1","A1xA1",[branching_rule("B1","A1","isomorphic"),branching_rule("B1","A1","isomorphic")])""", """A1xA1xB2:branching_rule("B4","D2xB2","extended")*branching_rule("D2xB2","A1xA1xB2",[branching_rule("D2","A1xA1","isomorphic"),"identity"])""", """A1xA3:branching_rule("B4","B1xD3","extended")*branching_rule("B1xD3","A1xA3",[branching_rule("B1","A1","isomorphic"),branching_rule("D3","A3","isomorphic")])"""] elif CartanType(ct) == CartanType("B5"): rul = ["""D5:branching_rule("B5","D5","extended")""", """A1:branching_rule("B5","A1","symmetric_power")""", """A1xA2xB3:branching_rule("B5","D2xB3","extended")*branching_rule("D2xB3","A1xA2xB3",[branching_rule("D2","A1xA1","isomorphic"),"identity"])""", """A1xD4:branching_rule("B5","B1xD4","orthogonal_sum")*branching_rule("B1xD4","A1xD4",[branching_rule("B1","A1","isomorphic"),"identity"])""", """A3xB2:branching_rule("B5","D3xB2","orthogonal_sum")*branching_rule("D3xB2","A3xB2",[branching_rule("D3","A3","isomorphic"),"identity"])"""] elif CartanType(ct) == CartanType("B6"): rul = ["""D6:branching_rule("B6","D6","extended")""", """A1:branching_rule("B6","A1","symmetric_power")""", """A1xA1xB4:branching_rule("B6","D2xB4","orthogonal_sum")*branching_rule("D2xB4","A1xA1xB4",[branching_rule("D2","A1xA1","isomorphic"),"identity"])""", """A1xD5:branching_rule("B6","B1xD5","orthogonal_sum")*branching_rule("B1xD5","A1xD5",[branching_rule("B1","A1","isomorphic"),"identity"])""", """A3xB3:branching_rule("B6","D3xB3","orthogonal_sum")*branching_rule("D3xB3","A3xB3",[branching_rule("D3","A3","isomorphic"),"identity"])""", """B2xD4:branching_rule("B6","B2xD4","orthogonal_sum")"""] elif CartanType(ct) == CartanType("B7"): rul = ["""D7:branching_rule("B7","D7","extended")""", """A3:branching_rule("B7","A3(1,0,1)","plethysm")""", """A1:branching_rule("B7","A1","symmetric_power")""", """A1xB2:branching_rule("B7","B1xB2","tensor")*branching_rule("B1xB2","A1xB2",[branching_rule("B1","A1","isomorphic"),"identity"])""", """A1xD6:branching_rule("B7","B1xD6","extended")*branching_rule("B1xD6","A1xD6",[branching_rule("B1","A1","isomorphic"),"identity"])""", """A1xA1xB5:branching_rule("B7","D2xB5","extended")*branching_rule("D2xB5","A1xA1xB5",[branching_rule("D2","A1xA1","isomorphic"),"identity"])""", """B2xD5:branching_rule("B7","B2xD5","orthogonal_sum")""", """A3xB4:branching_rule("B7","D3xB4","orthogonal_sum")*branching_rule("D3xB4","A3xB4",[branching_rule("D3","A3","isomorphic"),"identity"])""", """B3xD4:branching_rule("B7","B3xD4","orthogonal_sum")"""] elif CartanType(ct) == CartanType("B8"): rul = ["""D8:branching_rule("B8","D8","extended")""", """A1:branching_rule("B8","A1","symmetric_power")""", """A1xD7:branching_rule("B8","B1xD7","orthogonal_sum")*branching_rule("B1xD7","A1xD7",[branching_rule("B1","A1","isomorphic"),"identity"])""", """A1xA1xB6:branching_rule("B8","D2xB6","orthogonal_sum")*branching_rule("D2xB6","A1xA1xB6",[branching_rule("D2","A1xA1","isomorphic"),"identity"])""", """B2xD6:branching_rule("B8","B2xD6","orthogonal_sum")""", """A3xB5:branching_rule("B8","D3xB5","orthogonal_sum")*branching_rule("D3xB5","A3xB5",[branching_rule("D3","A3","isomorphic"),"identity"])""", """B3xD5:branching_rule("B8","B3xD5","orthogonal_sum")""", """B4xD4:branching_rule("B8","B4xD4","orthogonal_sum")"""] elif CartanType(ct) == CartanType("C2"): rul = ["""A1:branching_rule("C2","A1","symmetric_power")""", """A1xA1:branching_rule("C2","C1xC1","orthogonal_sum")*branching_rule("C1xC1","A1xA1",[branching_rule("C1","A1","isomorphic"),branching_rule("C1","A1","isomorphic")])"""] elif CartanType(ct) == CartanType("C3"): rul = ["""A2:branching_rule("C3","A2","levi")""", """A1:branching_rule("C3","A1","symmetric_power")""", """A1xA1:branching_rule("C3","B1xC1","tensor")*branching_rule("B1xC1","A1xA1",[branching_rule("B1","A1","isomorphic"),branching_rule("C1","A1","isomorphic")])""", """A1xC2:branching_rule("C3","C1xC2","orthogonal_sum")*branching_rule("C1xC2","A1xC2",[branching_rule("C1","A1","isomorphic"),"identity"])"""] elif CartanType(ct) == CartanType("C4"): rul = ["""A3:branching_rule("C4","A3","levi")""", """A1:branching_rule("C4","A1","symmetric_power")""", """A1xA3:branching_rule("C4","C1xC3","orthogonal_sum")*branching_rule("C1xC3","A1xA3",[branching_rule("C1","A1","isomorphic"),"identity"])""", """C2xC2:branching_rule("C4","C2xC2","orthogonal_sum")""", """A1xA1xA1:branching_rule("C4","C1xD2","tensor")*branching_rule("C1xD2","A1xA1xA1",[branching_rule("C1","A1","isomorphic"),branching_rule("D2","A1xA1","isomorphic")])"""] elif CartanType(ct) == CartanType("C5"): rul = ["""A4:branching_rule("C5","A4","levi")""", """A1:branching_rule("C5","A1","symmetric_power")""", """A1xC4:branching_rule("C5","C1xC4","orthogonal_sum")*branching_rule("C1xC4","A1xC4",[branching_rule("C1","A1","isomorphic"),"identity"])""", """C2xC3:branching_rule("C5","C2xC3","orthogonal_sum")""", """A1xB2:branching_rule("C5","C1xB2","tensor")*branching_rule("C1xB2","A1xB2",[branching_rule("C1","A1","isomorphic"),"identity"])"""] elif CartanType(ct) == CartanType("C6"): rul = ["""A5:branching_rule("C6","A5","levi")""", """A1:branching_rule("C6","A1","symmetric_power")""", """A1xA3:branching_rule("C6","C1xD3","tensor")*branching_rule("C1xD3","A1xA3",[branching_rule("C1","A1","isomorphic"),branching_rule("D3","A3","isomorphic")])""", """A1xC2:branching_rule("C6","B1xC2","tensor")*branching_rule("B1xC2","A1xC2",[branching_rule("B1","A1","isomorphic"),"identity"])""", """A1xC5:branching_rule("C6","C1xC5","orthogonal_sum")*branching_rule("C1xC5","A1xC5",[branching_rule("C1","A1","isomorphic"),"identity"])""", """C2xC4:branching_rule("C6","C2xC4","orthogonal_sum")""", """C3xC3:branching_rule("C6","C3xC3","orthogonal_sum")"""] elif CartanType(ct) == CartanType("C7"): rul = ["""A6:branching_rule("C7","A6","levi")""", """A1:branching_rule("C7","A1","symmetric_power")""", """A1xB3:branching_rule("C7","C1xB3","tensor")*branching_rule("C1xB3","A1xB3",[branching_rule("C1","A1","isomorphic"),"identity"])""", """A1xC6:branching_rule("C7","C1xC6","orthogonal_sum")*branching_rule("C1xC6","A1xC6",[branching_rule("C1","A1","isomorphic"),"identity"])""", """C2xC5:branching_rule("C7","C2xC5","orthogonal_sum")""", """C3xC4:branching_rule("C7","C3xC4","orthogonal_sum")""", """C3:branching_rule("C7","C3(0,0,1)","plethysm") # overlooked by Patera and McKay"""] elif CartanType(ct) == CartanType("C8"): rul = ["""A7:branching_rule("C8","A7","levi")""", """A1:branching_rule("C8","A1","symmetric_power")""", """C2:branching_rule("C8","C2(1,1)","plethysm")""", """A1xD4:branching_rule("C8","C1xD4","tensor")*branching_rule("C1xD4","A1xD4",[branching_rule("C1","A1","isomorphic"),"identity"])""", """A1xC7:branching_rule("C8","C1xC7","orthogonal_sum")*branching_rule("C1xC7","A1xC7",[branching_rule("C1","A1","isomorphic"),"identity"])""", """C2xC6:branching_rule("C8","C2xC6","orthogonal_sum")""", """C3xC5:branching_rule("C8","C3xC5","orthogonal_sum")""", """C4xC4:branching_rule("C8","C4xC4","orthogonal_sum")"""] elif CartanType(ct) == CartanType("D4"): rul = ["""B3:branching_rule("D4","B3","symmetric")""", """A2:branching_rule("D4","A2(1,1)","plethysm")""", """A1xC2:branching_rule("D4","C1xC2","tensor")*branching_rule("C1xC2","A1xC2",[branching_rule("C1","A1","isomorphic"),"identity"])""", """A1xA1xA1xA1:branching_rule("D4","D2xD2","orthogonal_sum")*branching_rule("D2xD2","A1xA1xA1xA1",[branching_rule("D2","A1xA1","isomorphic"),branching_rule("D2","A1xA1","isomorphic")])"""] elif CartanType(ct) == CartanType("D5"): rul = ["""A4:branching_rule("D5","A4","levi")""", """B4:branching_rule("D5","B4","symmetric")""", """C2:branching_rule("D5","C2(2,0)","plethysm")""", """A1xA1xA3:branching_rule("D5","D2xD3","orthogonal_sum")*branching_rule("D2xD3","A1xA1xA3",[branching_rule("D2","A1xA1","isomorphic"),branching_rule("D3","A3","isomorphic")])""", """A1xA3:branching_rule("D5","B1xB3","orthogonal_sum")*branching_rule("B1xB3","A1xA3",[branching_rule("B1","A1","isomorphic"),"identity"])""", """B2xB2:branching_rule("D5","B2xB2","orthogonal_sum")"""] elif CartanType(ct) == CartanType("D6"): rul = ["""A5:branching_rule("D6","A5","levi")""", """B5:branching_rule("D6","B5","symmetric")""", """A1xA3:branching_rule("D6","C1xC3","tensor")*branching_rule("C1xC3","A1xA3",[branching_rule("C1","A1","isomorphic"),"identity"])""", """A1xA1xD4:branching_rule("D6","D2xD4","orthogonal_sum")*branching_rule("D2xD4","A1xA1xD4",[branching_rule("D2","A1xA1","isomorphic"),"identity"])""", """A3xA3:branching_rule("D6","D3xD3","orthogonal_sum")*branching_rule("D3xD3","A3xA3",[branching_rule("D3","A3","isomorphic"),branching_rule("D3","A3","isomorphic")])""", """A1xB4:branching_rule("D6","B1xB4","orthogonal_sum")*branching_rule("B1xB4","A1xB4",[branching_rule("B1","A1","isomorphic"),"identity"])""", """B2xB3:branching_rule("D6","B2xB3","orthogonal_sum")""", """A1xA1xA1:branching_rule("D6","B1xD2","tensor")*branching_rule("B1xD2","A1xA1xA1",[branching_rule("B1","A1","isomorphic"),branching_rule("D2","A1xA1","isomorphic")])"""] elif CartanType(ct) == CartanType("D7"): rul = ["""A6:branching_rule("D7","A6","levi")""", """B6:branching_rule("D7","B6","symmetric")""", """C3:branching_rule("D7","C3(0,1,0)","plethysm")""", """C2:branching_rule("D7","C2(0,2)","plethysm")""", """G2:branching_rule("D7","G2(0,1)","plethysm")""", """A1xA1xD5:branching_rule("D7","D2xD5","orthogonal_sum")*branching_rule("D2xD5","A1xA1xD5",[branching_rule("D2","A1xA1","isomorphic"),"identity"])""", """A3xD4:branching_rule("D7","D3xD4","orthogonal_sum")*branching_rule("D3xD4","A3xD4",[branching_rule("D3","A3","isomorphic"),"identity"])""", """A1xB5:branching_rule("D7","B1xB5","orthogonal_sum")*branching_rule("B1xB5","A1xB5",[branching_rule("B1","A1","isomorphic"),"identity"])""", """B2xB4:branching_rule("D7","B2xB4","orthogonal_sum")""", """B3xB3:branching_rule("D7","B3xB3","orthogonal_sum")"""] elif CartanType(ct) == CartanType("D8"): rul = ["""A7:branching_rule("D8","A7","levi")""", """B7:branching_rule("D8","B7","symmetric")""", """B4:branching_rule("D8","B4(0,0,0,1)","plethysm")""", """A1xC4:branching_rule("D8","C1xC4","tensor")*branching_rule("C1xC4","A1xC4",[branching_rule("C1","A1","isomorphic"),"identity"])""", """A1xA1xD6:branching_rule("D8","D2xD6","orthogonal_sum")*branching_rule("D2xD6","A1xA1xD6",[branching_rule("D2","A1xA1","isomorphic"),"identity"])""", """A3xD5:branching_rule("D8","D3xD5","orthogonal_sum")*branching_rule("D3xD5","A3xD5",[branching_rule("D3","A3","isomorphic"),"identity"])""", """D4xD4:branching_rule("D8","D4xD4","orthogonal_sum")""", """A1xB6:branching_rule("D8","B1xB6","orthogonal_sum")*branching_rule("B1xB6","A1xB6",[branching_rule("B1","A1","isomorphic"),"identity"])""", """B2xB5:branching_rule("D8","B2xB5","orthogonal_sum")""", """B3xB4:branching_rule("D8","B3xB4","orthogonal_sum")""", """C2xC2:branching_rule("D8","C2xC2","tensor")"""] elif CartanType(ct) == CartanType("G2"): rul = ["""A2:branching_rule("G2","A2","extended")""", """A1:branching_rule("G2","A1","i")""", """A1xA1:branching_rule("G2","A1xA1","extended")"""] elif CartanType(ct) == CartanType("F4"): rul = ["""B4:branching_rule("F4","B4","extended")""", """A1:branching_rule("F4","A1","ii")""", """A1xG2:branching_rule("F4","A1xG2","miscellaneous")""", """A1xC3:branching_rule("F4","A1xC3","extended")""", """A2xA2:branching_rule("F4","A2xA2","extended")"""] elif CartanType(ct) == CartanType("E6"): rul = ["""D5:branching_rule("E6","D5","levi")""", """C4:branching_rule("E6","C4","symmetric")""", """F4:branching_rule("E6","F4","symmetric")""", """A2:branching_rule("E6","A2","miscellaneous")""", """G2:branching_rule("E6","G2","miscellaneous")""", """A2xG2:branching_rule("E6","A2xG2","miscellaneous")""", """A1xA5:branching_rule("E6","A1xA5","extended")""", """A2xA2xA2:branching_rule("E6","A2xA2xA2","extended")"""] elif CartanType(ct) == CartanType("E7"): rul = ["""A7:branching_rule("E7","A7","extended")""", """E6:branching_rule("E7","E6","levi")""", """A2:branching_rule("E7","A2","miscellaneous")""", """A1:branching_rule("E7","A1","iii")""", """A1:branching_rule("E7","A1","iv")""", """A1xF4:branching_rule("E7","A1xF4","miscellaneous")""", """G2xC3:branching_rule("E7","G2xC3","miscellaneous")""", """A1xG2:branching_rule("E7","A1xG2","miscellaneous")""", """A1xA1:branching_rule("E7","A1xA1","miscellaneous")""", """A1xD6:branching_rule("E7","A1xD6","extended")""", """A5xA2:branching_rule("E7","A5xA2","extended")"""] elif CartanType(ct) == CartanType("E8"): rul = ["""A4xA4:branching_rule("E8","A4xA4","extended")""", """G2xF4:branching_rule("E8","G2xF4","miscellaneous")""", """E6xA2:branching_rule("E8","E6xA2","extended")""", """E7xA1:branching_rule("E8","E7xA1","extended")""", """D8:branching_rule("E8","D8","extended")""", """A8:branching_rule("E8","A8","extended")""", """B2:branching_rule("E8","B2","miscellaneous")""", """A1xA2:branching_rule("E8","A1xA2","miscellaneous")""", """A1:branching_rule("E8","A1","v")""", """A1:branching_rule("E8","A1","vi")""", """A1:branching_rule("E8","A1","vii")"""] else: raise ValueError("Argument must be an irreducible classical Cartan Type with rank less than or equal to 8") if mode == "print_rules": for line in rul: print(line) elif mode == "get_rule": d = {} for line in rul: [k, br] = line.split(":") br = eval(br) if k in d: if not isinstance(d[k], list): d[k] = [d[k]] d[k].append(br) else: d[k] = br return d
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/branching_rules.py
0.884794
0.620995
branching_rules.py
pypi
from . import ambient_space from sage.sets.family import Family from sage.combinat.root_system.root_lattice_realizations import RootLatticeRealizations class AmbientSpace(ambient_space.AmbientSpace): """ EXAMPLES:: sage: e = RootSystem(['G',2]).ambient_space(); e Ambient space of the Root system of type ['G', 2] One can not construct the ambient lattice because the simple coroots have rational coefficients:: sage: e.simple_coroots() Finite family {1: (0, 1, -1), 2: (1/3, -2/3, 1/3)} sage: e.smallest_base_ring() Rational Field By default, this ambient space uses the barycentric projection for plotting:: sage: L = RootSystem(["G",2]).ambient_space() sage: e = L.basis() sage: L._plot_projection(e[0]) (1/2, 989/1142) sage: L._plot_projection(e[1]) (-1, 0) sage: L._plot_projection(e[2]) (1/2, -989/1142) sage: L = RootSystem(["A",3]).ambient_space() sage: l = L.an_element(); l (2, 2, 3, 0) sage: L._plot_projection(l) (0, -1121/1189, 7/3) .. SEEALSO:: - :meth:`sage.combinat.root_system.root_lattice_realizations.RootLatticeRealizations.ParentMethods._plot_projection` TESTS:: sage: TestSuite(e).run() sage: [WeylDim(['G',2],[a,b]) for a,b in [[0,0], [1,0], [0,1], [1,1]]] # indirect doctest [1, 7, 14, 64] """ def dimension(self): """ EXAMPLES:: sage: e = RootSystem(['G',2]).ambient_space() sage: e.dimension() 3 """ return 3 def simple_root(self, i): """ EXAMPLES:: sage: CartanType(['G',2]).root_system().ambient_space().simple_roots() Finite family {1: (0, 1, -1), 2: (1, -2, 1)} """ return self.monomial(1)-self.monomial(2) if i == 1 else self.monomial(0)-2*self.monomial(1)+self.monomial(2) def positive_roots(self): """ EXAMPLES:: sage: CartanType(['G',2]).root_system().ambient_space().positive_roots() [(0, 1, -1), (1, -2, 1), (1, -1, 0), (1, 0, -1), (1, 1, -2), (2, -1, -1)] """ return [ self(v) for v in [[0,1,-1],[1,-2,1],[1,-1,0],[1,0,-1],[1,1,-2],[2,-1,-1]]] def negative_roots(self): """ EXAMPLES:: sage: CartanType(['G',2]).root_system().ambient_space().negative_roots() [(0, -1, 1), (-1, 2, -1), (-1, 1, 0), (-1, 0, 1), (-1, -1, 2), (-2, 1, 1)] """ return [ self(v) for v in [[0,-1,1],[-1,2,-1],[-1,1,0],[-1,0,1],[-1,-1,2],[-2,1,1]]] def fundamental_weights(self): """ EXAMPLES:: sage: CartanType(['G',2]).root_system().ambient_space().fundamental_weights() Finite family {1: (1, 0, -1), 2: (2, -1, -1)} """ return Family({ 1: self([1,0,-1]), 2: self([2,-1,-1])}) _plot_projection = RootLatticeRealizations.ParentMethods.__dict__['_plot_projection_barycentric'] from .cartan_type import CartanType_standard_finite, CartanType_simple, CartanType_crystallographic class CartanType(CartanType_standard_finite, CartanType_simple, CartanType_crystallographic): def __init__(self): """ EXAMPLES:: sage: ct = CartanType(['G',2]) sage: ct ['G', 2] sage: ct._repr_(compact = True) 'G2' sage: ct.is_irreducible() True sage: ct.is_finite() True sage: ct.is_crystallographic() True sage: ct.is_simply_laced() False sage: ct.dual() ['G', 2] relabelled by {1: 2, 2: 1} sage: ct.affine() ['G', 2, 1] TESTS:: sage: TestSuite(ct).run() """ CartanType_standard_finite.__init__(self, "G", 2) def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: latex(CartanType(['G',2])) G_2 sage: latex(CartanType(['G',2]).dual()) G_2 \text{ relabelled by } \left\{1 : 2, 2 : 1\right\} """ return "G_2" AmbientSpace = AmbientSpace def coxeter_number(self): """ Return the Coxeter number associated with ``self``. EXAMPLES:: sage: CartanType(['G',2]).coxeter_number() 6 """ return 6 def dual_coxeter_number(self): """ Return the dual Coxeter number associated with ``self``. EXAMPLES:: sage: CartanType(['G',2]).dual_coxeter_number() 4 """ return 4 def dynkin_diagram(self): """ Returns a Dynkin diagram for type G. EXAMPLES:: sage: g = CartanType(['G',2]).dynkin_diagram() sage: g 3 O=<=O 1 2 G2 sage: g.edges(sort=True) [(1, 2, 1), (2, 1, 3)] """ from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) g.add_edge(1,2) g.set_edge_label(2,1,3) return g def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['G',2])._latex_dynkin_diagram()) \draw (0,0) -- (2 cm,0); \draw (0, 0.15 cm) -- +(2 cm,0); \draw (0, -0.15 cm) -- +(2 cm,0); \draw[shift={(0.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; <BLANKLINE> """ if node is None: node = self._latex_draw_node ret = "\\draw (0,0) -- (%s cm,0);\n"%node_dist ret += "\\draw (0, 0.15 cm) -- +(%s cm,0);\n"%node_dist ret += "\\draw (0, -0.15 cm) -- +(%s cm,0);\n"%node_dist if dual: ret += self._latex_draw_arrow_tip(0.5*node_dist+0.2, 0, 0) else: ret += self._latex_draw_arrow_tip(0.5*node_dist-0.2, 0, 180) ret += node(0, 0, label(1)) ret += node(node_dist, 0, label(2)) return ret def ascii_art(self, label=lambda i: i, node=None): """ Return an ascii art representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['G',2]).ascii_art(label=lambda x: x+2)) 3 O=<=O 3 4 """ if node is None: node = self._ascii_art_node ret = " 3\n{}=<={}\n".format(node(label(1)), node(label(2))) return ret + "{!s:4}{!s:4}".format(label(1), label(2)) def dual(self): r""" Return the dual Cartan type. This uses that `G_2` is self-dual up to relabelling. EXAMPLES:: sage: G2 = CartanType(['G',2]) sage: G2.dual() ['G', 2] relabelled by {1: 2, 2: 1} sage: G2.dynkin_diagram() 3 O=<=O 1 2 G2 sage: G2.dual().dynkin_diagram() 3 O=<=O 2 1 G2 relabelled by {1: 2, 2: 1} """ return self.relabel({1:2, 2:1}) def _default_folded_cartan_type(self): """ Return the default folded Cartan type. EXAMPLES:: sage: CartanType(['G', 2])._default_folded_cartan_type() ['G', 2] as a folding of ['D', 4] """ from sage.combinat.root_system.type_folded import CartanTypeFolded return CartanTypeFolded(self, ['D', 4], [[1, 3, 4], [2]]) # For unpickling backward compatibility (Sage <= 4.1) from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.combinat.root_system.type_G', 'ambient_space', AmbientSpace)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_G.py
0.849285
0.614437
type_G.py
pypi
from .cartan_type import CartanType_standard_untwisted_affine class CartanType(CartanType_standard_untwisted_affine): def __init__(self, n): """ EXAMPLES:: sage: ct = CartanType(['B',4,1]) sage: ct ['B', 4, 1] sage: ct._repr_(compact = True) 'B4~' sage: ct.is_irreducible() True sage: ct.is_finite() False sage: ct.is_affine() True sage: ct.is_untwisted_affine() True sage: ct.is_crystallographic() True sage: ct.is_simply_laced() False sage: ct.classical() ['B', 4] sage: ct.dual() ['B', 4, 1]^* sage: ct.dual().is_untwisted_affine() False TESTS:: sage: TestSuite(ct).run() """ assert n >= 1 CartanType_standard_untwisted_affine.__init__(self, "B", n) def dynkin_diagram(self): """ Return the extended Dynkin diagram for affine type `B`. EXAMPLES:: sage: b = CartanType(['B',3,1]).dynkin_diagram() sage: b O 0 | | O---O=>=O 1 2 3 B3~ sage: b.edges(sort=True) [(0, 2, 1), (1, 2, 1), (2, 0, 1), (2, 1, 1), (2, 3, 2), (3, 2, 1)] sage: b = CartanType(['B',2,1]).dynkin_diagram(); b O=>=O=<=O 0 2 1 B2~ sage: b.edges(sort=True) [(0, 2, 2), (1, 2, 2), (2, 0, 1), (2, 1, 1)] sage: b = CartanType(['B',1,1]).dynkin_diagram(); b O<=>O 0 1 B1~ sage: b.edges(sort=True) [(0, 1, 2), (1, 0, 2)] """ from . import cartan_type n = self.n if n == 1: res = cartan_type.CartanType(["A",1,1]).dynkin_diagram() res._cartan_type = self return res if n == 2: res = cartan_type.CartanType(["C",2,1]).relabel({0:0, 1:2, 2:1}).dynkin_diagram() res._cartan_type = self return res from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) for i in range(1, n): g.add_edge(i, i+1) g.set_edge_label(n-1, n, 2) g.add_edge(0,2) return g def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['B',4,1])._latex_dynkin_diagram()) \draw (0,0.7 cm) -- (2 cm,0); \draw (0,-0.7 cm) -- (2 cm,0); \draw (2 cm,0) -- (4 cm,0); \draw (4 cm, 0.1 cm) -- +(2 cm,0); \draw (4 cm, -0.1 cm) -- +(2 cm,0); \draw[shift={(5.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0.7 cm) circle (.25cm) node[left=3pt]{$0$}; \draw[fill=white] (0 cm, -0.7 cm) circle (.25cm) node[left=3pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; <BLANKLINE> sage: print(CartanType(['B',4,1]).dual()._latex_dynkin_diagram()) \draw (0,0.7 cm) -- (2 cm,0); \draw (0,-0.7 cm) -- (2 cm,0); \draw (2 cm,0) -- (4 cm,0); \draw (4 cm, 0.1 cm) -- +(2 cm,0); \draw (4 cm, -0.1 cm) -- +(2 cm,0); \draw[shift={(4.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0.7 cm) circle (.25cm) node[left=3pt]{$0$}; \draw[fill=white] (0 cm, -0.7 cm) circle (.25cm) node[left=3pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; <BLANKLINE> """ if node is None: node = self._latex_draw_node if self.n == 1: from . import cartan_type return cartan_type.CartanType(["A",1,1])._latex_dynkin_diagram(label, node, node_dist) elif self.n == 2: from . import cartan_type return cartan_type.CartanType(["C",2,1])._latex_dynkin_diagram(label, node, node_dist, dual) n = self.n single_end = (n-2)*node_dist # Where the single line ends ret = "\\draw (0,0.7 cm) -- (%s cm,0);\n"%node_dist ret += "\\draw (0,-0.7 cm) -- (%s cm,0);\n"%node_dist ret += "\\draw (%s cm,0) -- (%s cm,0);\n"%(node_dist, single_end) ret += "\\draw (%s cm, 0.1 cm) -- +(%s cm,0);\n"%(single_end, node_dist) ret += "\\draw (%s cm, -0.1 cm) -- +(%s cm,0);\n"%(single_end, node_dist) if dual: ret += self._latex_draw_arrow_tip(single_end+0.5*node_dist-0.2, 0, 180) else: ret += self._latex_draw_arrow_tip(single_end+0.5*node_dist+0.2, 0, 0) ret += node(0, 0.7, label(0), 'left=3pt') ret +=node(0, -0.7, label(1), 'left=3pt') for i in range(1, n): ret += node(i*node_dist, 0, label(i+1)) return ret def ascii_art(self, label=lambda i: i, node=None): """ Return an ascii art representation of the extended Dynkin diagram. EXAMPLES:: sage: print(CartanType(['B',3,1]).ascii_art()) O 0 | | O---O=>=O 1 2 3 sage: print(CartanType(['B',5,1]).ascii_art(label = lambda x: x+2)) O 2 | | O---O---O---O=>=O 3 4 5 6 7 sage: print(CartanType(['B',2,1]).ascii_art(label = lambda x: x+2)) O=>=O=<=O 2 4 3 sage: print(CartanType(['B',1,1]).ascii_art(label = lambda x: x+2)) O<=>O 2 3 """ n = self.n from .cartan_type import CartanType if node is None: node = self._ascii_art_node if n == 1: return CartanType(["A",1,1]).ascii_art(label, node) if n == 2: return CartanType(["C",2,1]).relabel({0:0, 1:2, 2:1}).ascii_art(label, node) ret = " {} {}\n |\n |\n".format(node(label(0)), label(0)) ret += "---".join(node(label(i)) for i in range(1,n)) + "=>={}\n".format(node(label(n))) ret += "".join("{!s:4}".format(label(i)) for i in range(1,n+1)) return ret def _default_folded_cartan_type(self): """ Return the default folded Cartan type. EXAMPLES:: sage: CartanType(['B', 4, 1])._default_folded_cartan_type() ['B', 4, 1] as a folding of ['D', 5, 1] """ from sage.combinat.root_system.type_folded import CartanTypeFolded n = self.n if n == 1: return CartanTypeFolded(self, ['A', 1, 1], [[0], [1]]) return CartanTypeFolded(self, ['D', n + 1, 1], [[i] for i in range(n)] + [[n, n+1]])
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_B_affine.py
0.743261
0.456955
type_B_affine.py
pypi
from sage.combinat.root_system.weyl_group import WeylGroup from sage.combinat.root_system.reflection_group_real import ReflectionGroup from sage.combinat.root_system.cartan_type import CartanType def CoxeterGroup(data, implementation="reflection", base_ring=None, index_set=None): """ Return an implementation of the Coxeter group given by ``data``. INPUT: - ``data`` -- a Cartan type (or coercible into; see :class:`CartanType`) or a Coxeter matrix or graph - ``implementation`` -- (default: ``'reflection'``) can be one of the following: * ``'permutation'`` - as a permutation representation * ``'matrix'`` - as a Weyl group (as a matrix group acting on the root space); if this is not implemented, this uses the "reflection" implementation * ``'coxeter3'`` - using the coxeter3 package * ``'reflection'`` - as elements in the reflection representation; see :class:`~sage.groups.matrix_gps.coxeter_groups.CoxeterMatrixGroup` - ``base_ring`` -- (optional) the base ring for the ``'reflection'`` implementation - ``index_set`` -- (optional) the index set for the ``'reflection'`` implementation EXAMPLES: Now assume that ``data`` represents a Cartan type. If ``implementation`` is not specified, the reflection representation is returned:: sage: W = CoxeterGroup(["A",2]) sage: W Finite Coxeter group over Integer Ring with Coxeter matrix: [1 3] [3 1] sage: W = CoxeterGroup(["A",3,1]); W Coxeter group over Integer Ring with Coxeter matrix: [1 3 2 3] [3 1 3 2] [2 3 1 3] [3 2 3 1] sage: W = CoxeterGroup(['H',3]); W Finite Coxeter group over Number Field in a with defining polynomial x^2 - 5 with a = 2.236067977499790? with Coxeter matrix: [1 3 2] [3 1 5] [2 5 1] We now use the ``implementation`` option:: sage: W = CoxeterGroup(["A",2], implementation = "permutation") # optional - gap3 sage: W # optional - gap3 Permutation Group with generators [(1,4)(2,3)(5,6), (1,3)(2,5)(4,6)] sage: W.category() # optional - gap3 Join of Category of finite enumerated permutation groups and Category of finite weyl groups and Category of well generated finite irreducible complex reflection groups sage: W = CoxeterGroup(["A",2], implementation="matrix") sage: W Weyl Group of type ['A', 2] (as a matrix group acting on the ambient space) sage: W = CoxeterGroup(["H",3], implementation="matrix") sage: W Finite Coxeter group over Number Field in a with defining polynomial x^2 - 5 with a = 2.236067977499790? with Coxeter matrix: [1 3 2] [3 1 5] [2 5 1] sage: W = CoxeterGroup(["H",3], implementation="reflection") sage: W Finite Coxeter group over Number Field in a with defining polynomial x^2 - 5 with a = 2.236067977499790? with Coxeter matrix: [1 3 2] [3 1 5] [2 5 1] sage: W = CoxeterGroup(["A",4,1], implementation="permutation") Traceback (most recent call last): ... ValueError: the type must be finite sage: W = CoxeterGroup(["A",4], implementation="chevie"); W # optional - gap3 Irreducible real reflection group of rank 4 and type A4 We use the different options for the "reflection" implementation:: sage: W = CoxeterGroup(["H",3], implementation="reflection", base_ring=RR) sage: W Finite Coxeter group over Real Field with 53 bits of precision with Coxeter matrix: [1 3 2] [3 1 5] [2 5 1] sage: W = CoxeterGroup([[1,10],[10,1]], implementation="reflection", index_set=['a','b'], base_ring=SR) sage: W Finite Coxeter group over Symbolic Ring with Coxeter matrix: [ 1 10] [10 1] TESTS:: sage: W = groups.misc.CoxeterGroup(["H",3]) """ if implementation not in ["permutation", "matrix", "coxeter3", "reflection", "chevie", None]: raise ValueError("invalid type implementation") from sage.groups.matrix_gps.coxeter_group import CoxeterMatrixGroup try: cartan_type = CartanType(data) except (TypeError, ValueError): # If it is not a Cartan type, try to see if we can represent it as a matrix group return CoxeterMatrixGroup(data, base_ring, index_set) if implementation is None: implementation = "matrix" if implementation == "reflection": return CoxeterMatrixGroup(cartan_type, base_ring, index_set) if implementation == "coxeter3": try: from sage.libs.coxeter3.coxeter_group import CoxeterGroup except ImportError: raise RuntimeError("coxeter3 must be installed") else: return CoxeterGroup(cartan_type) if implementation == "permutation": if not cartan_type.is_finite(): raise ValueError("the type must be finite") if cartan_type.is_crystallographic(): return WeylGroup(cartan_type, implementation="permutation") return ReflectionGroup(cartan_type, index_set=index_set) elif implementation == "matrix": if cartan_type.is_crystallographic(): return WeylGroup(cartan_type) return CoxeterMatrixGroup(cartan_type, base_ring, index_set) elif implementation == "chevie": return ReflectionGroup(cartan_type, index_set=index_set) raise NotImplementedError("Coxeter group of type {} as {} group not implemented".format(cartan_type, implementation)) from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.combinat.root_system.coxeter_group', 'CoxeterGroupAsPermutationGroup', ReflectionGroup)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/coxeter_group.py
0.907507
0.554772
coxeter_group.py
pypi
from . import ambient_space class AmbientSpace(ambient_space.AmbientSpace): def dimension(self): """ EXAMPLES:: sage: e = RootSystem(['B',3]).ambient_space() sage: e.dimension() 3 """ return self.root_system.cartan_type().rank() def root(self, i, j): """ Note that indexing starts at 0. EXAMPLES:: sage: e = RootSystem(['B',3]).ambient_space() sage: e.root(0,1) (1, -1, 0) """ return self.monomial(i) - self.monomial(j) def simple_root(self, i): """ EXAMPLES:: sage: e = RootSystem(['B',4]).ambient_space() sage: e.simple_roots() Finite family {1: (1, -1, 0, 0), 2: (0, 1, -1, 0), 3: (0, 0, 1, -1), 4: (0, 0, 0, 1)} sage: e.positive_roots() [(1, -1, 0, 0), (1, 1, 0, 0), (1, 0, -1, 0), (1, 0, 1, 0), (1, 0, 0, -1), (1, 0, 0, 1), (0, 1, -1, 0), (0, 1, 1, 0), (0, 1, 0, -1), (0, 1, 0, 1), (0, 0, 1, -1), (0, 0, 1, 1), (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)] sage: e.fundamental_weights() Finite family {1: (1, 0, 0, 0), 2: (1, 1, 0, 0), 3: (1, 1, 1, 0), 4: (1/2, 1/2, 1/2, 1/2)} """ if i not in self.index_set(): raise ValueError("{} is not in the index set".format(i)) return self.root(i-1, i) if i < self.n else self.monomial(self.n-1) def negative_roots(self): """ EXAMPLES:: sage: RootSystem(['B',3]).ambient_space().negative_roots() [(-1, 1, 0), (-1, -1, 0), (-1, 0, 1), (-1, 0, -1), (0, -1, 1), (0, -1, -1), (-1, 0, 0), (0, -1, 0), (0, 0, -1)] """ return [-a for a in self.positive_roots()] def positive_roots(self): """ EXAMPLES:: sage: RootSystem(['B',3]).ambient_space().positive_roots() [(1, -1, 0), (1, 1, 0), (1, 0, -1), (1, 0, 1), (0, 1, -1), (0, 1, 1), (1, 0, 0), (0, 1, 0), (0, 0, 1)] """ res = [] for i in range(self.n-1): for j in range(i + 1, self.n): res.append(self.monomial(i) - self.monomial(j)) res.append(self.monomial(i) + self.monomial(j)) for i in range(self.n): res.append(self.monomial(i)) return res def fundamental_weight(self, i): """ EXAMPLES:: sage: RootSystem(['B',3]).ambient_space().fundamental_weights() Finite family {1: (1, 0, 0), 2: (1, 1, 0), 3: (1/2, 1/2, 1/2)} """ if i not in self.index_set(): raise ValueError("{} is not in the index set".format(i)) n = self.dimension() if i == n: return self.sum(self.monomial(j) for j in range(n)) / 2 else: return self.sum(self.monomial(j) for j in range(i)) from .cartan_type import CartanType_standard_finite, CartanType_simple, CartanType_crystallographic, CartanType_simply_laced class CartanType(CartanType_standard_finite, CartanType_simple, CartanType_crystallographic): def __init__(self, n): """ EXAMPLES:: sage: ct = CartanType(['B',4]) sage: ct ['B', 4] sage: ct._repr_(compact = True) 'B4' sage: ct.is_irreducible() True sage: ct.is_finite() True sage: ct.is_affine() False sage: ct.is_crystallographic() True sage: ct.is_simply_laced() False sage: ct.affine() ['B', 4, 1] sage: ct.dual() ['C', 4] sage: ct = CartanType(['B',1]) sage: ct.is_simply_laced() True sage: ct.affine() ['B', 1, 1] TESTS:: sage: TestSuite(ct).run() """ assert n >= 1 CartanType_standard_finite.__init__(self, "B", n) if n == 1: self._add_abstract_superclass(CartanType_simply_laced) def _latex_(self): """ Return a latex representation of ``self``. EXAMPLES:: sage: latex(CartanType(['B',4])) B_{4} """ return "B_{%s}" % self.n AmbientSpace = AmbientSpace def coxeter_number(self): """ Return the Coxeter number associated with ``self``. EXAMPLES:: sage: CartanType(['B',4]).coxeter_number() 8 """ return 2*self.n def dual_coxeter_number(self): """ Return the dual Coxeter number associated with ``self``. EXAMPLES:: sage: CartanType(['B',4]).dual_coxeter_number() 7 """ return 2*self.n - 1 def dual(self): """ Types B and C are in duality: EXAMPLES:: sage: CartanType(["C", 3]).dual() ['B', 3] """ from . import cartan_type return cartan_type.CartanType(["C", self.n]) def dynkin_diagram(self): """ Returns a Dynkin diagram for type B. EXAMPLES:: sage: b = CartanType(['B',3]).dynkin_diagram() sage: b O---O=>=O 1 2 3 B3 sage: b.edges(sort=True) [(1, 2, 1), (2, 1, 1), (2, 3, 2), (3, 2, 1)] sage: b = CartanType(['B',1]).dynkin_diagram() sage: b O 1 B1 sage: b.edges(sort=True) [] """ from .dynkin_diagram import DynkinDiagram_class n = self.n g = DynkinDiagram_class(self) for i in range(1, n): g.add_edge(i, i+1) if n >= 2: g.set_edge_label(n-1, n, 2) return g def ascii_art(self, label=lambda i: i, node=None): """ Return an ascii art representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['B',1]).ascii_art()) O 1 sage: print(CartanType(['B',2]).ascii_art()) O=>=O 1 2 sage: print(CartanType(['B',5]).ascii_art(label = lambda x: x+2)) O---O---O---O=>=O 3 4 5 6 7 """ if node is None: node = self._ascii_art_node n = self.n if n == 1: ret = node(label(1)) + "\n" else: ret = "---".join(node(label(i)) for i in range(1, n)) + "=>=" + node(label(n)) + '\n' ret += "".join("{!s:4}".format(label(i)) for i in range(1, n + 1)) return ret def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['B',4])._latex_dynkin_diagram()) \draw (0 cm,0) -- (4 cm,0); \draw (4 cm, 0.1 cm) -- +(2 cm,0); \draw (4 cm, -0.1 cm) -- +(2 cm,0); \draw[shift={(5.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; <BLANKLINE> When ``dual=True``, the Dynkin diagram for the dual Cartan type `C_n` is returned:: sage: print(CartanType(['B',4])._latex_dynkin_diagram(dual=True)) \draw (0 cm,0) -- (4 cm,0); \draw (4 cm, 0.1 cm) -- +(2 cm,0); \draw (4 cm, -0.1 cm) -- +(2 cm,0); \draw[shift={(4.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; <BLANKLINE> .. SEEALSO:: - :meth:`sage.combinat.root_system.type_C.CartanType._latex_dynkin_diagram` - :meth:`sage.combinat.root_system.type_BC_affine.CartanType._latex_dynkin_diagram` """ if node is None: node = self._latex_draw_node if self.n == 1: return node(0, 0, label(1)) n = self.n ret = "\\draw (0 cm,0) -- (%s cm,0);\n" % ((n-2)*node_dist) ret += "\\draw (%s cm, 0.1 cm) -- +(%s cm,0);\n" % ((n-2)*node_dist, node_dist) ret += "\\draw (%s cm, -0.1 cm) -- +(%s cm,0);\n" % ((n-2)*node_dist, node_dist) if dual: ret += self._latex_draw_arrow_tip((n-1.5)*node_dist-0.2, 0, 180) else: ret += self._latex_draw_arrow_tip((n-1.5)*node_dist+0.2, 0, 0) for i in range(self.n): ret += node(i*node_dist, 0, label(i+1)) return ret def _default_folded_cartan_type(self): """ Return the default folded Cartan type. EXAMPLES:: sage: CartanType(['B', 3])._default_folded_cartan_type() ['B', 3] as a folding of ['D', 4] """ from sage.combinat.root_system.type_folded import CartanTypeFolded n = self.n return CartanTypeFolded(self, ['D', n + 1], [[i] for i in range(1, n)] + [[n, n + 1]]) # For unpickling backward compatibility (Sage <= 4.1) from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.combinat.root_system.type_B', 'ambient_space', AmbientSpace)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_B.py
0.828696
0.550909
type_B.py
pypi
from . import ambient_space class AmbientSpace(ambient_space.AmbientSpace): def dimension(self): """ EXAMPLES:: sage: e = RootSystem(['D',3]).ambient_space() sage: e.dimension() 3 """ return self.root_system.cartan_type().rank() def root(self, i, j, p1, p2): """ Note that indexing starts at 0. EXAMPLES:: sage: e = RootSystem(['D',3]).ambient_space() sage: e.root(0, 1, 1, 1) (-1, -1, 0) sage: e.root(0, 0, 1, 1) (-1, 0, 0) """ if i != j: return (-1)**p1 * self.monomial(i) + (-1)**p2 * self.monomial(j) return (-1)**p1 * self.monomial(i) def simple_root(self, i): """ EXAMPLES:: sage: RootSystem(['D',4]).ambient_space().simple_roots() Finite family {1: (1, -1, 0, 0), 2: (0, 1, -1, 0), 3: (0, 0, 1, -1), 4: (0, 0, 1, 1)} """ if i not in self.index_set(): raise ValueError("{} is not in the index set".format(i)) return self.root(i-1, i, 0, 1) if i < self.n else self.root(self.n-2, self.n-1, 0, 0) def positive_roots(self): """ EXAMPLES:: sage: RootSystem(['D',4]).ambient_space().positive_roots() [(1, 1, 0, 0), (1, 0, 1, 0), (0, 1, 1, 0), (1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1), (1, -1, 0, 0), (1, 0, -1, 0), (0, 1, -1, 0), (1, 0, 0, -1), (0, 1, 0, -1), (0, 0, 1, -1)] """ res = [] for p in [0, 1]: for j in range(self.n): res.extend([self.root(i, j, 0, p) for i in range(j)]) return res def negative_roots(self): """ EXAMPLES:: sage: RootSystem(['D',4]).ambient_space().negative_roots() [(-1, 1, 0, 0), (-1, 0, 1, 0), (0, -1, 1, 0), (-1, 0, 0, 1), (0, -1, 0, 1), (0, 0, -1, 1), (-1, -1, 0, 0), (-1, 0, -1, 0), (0, -1, -1, 0), (-1, 0, 0, -1), (0, -1, 0, -1), (0, 0, -1, -1)] """ res = [] for p in [0, 1]: for j in range(self.n): res.extend([self.root(i, j, 1, p) for i in range(j)]) return res def fundamental_weight(self, i): """ EXAMPLES:: sage: RootSystem(['D',4]).ambient_space().fundamental_weights() Finite family {1: (1, 0, 0, 0), 2: (1, 1, 0, 0), 3: (1/2, 1/2, 1/2, -1/2), 4: (1/2, 1/2, 1/2, 1/2)} """ if i not in self.index_set(): raise ValueError("{} is not in the index set".format(i)) n = self.dimension() if i == n: return self.sum(self.monomial(j) for j in range(n)) / 2 elif i == n - 1: return (self.sum(self.monomial(j) for j in range(n-1)) - self.monomial(n-1)) / 2 else: return self.sum(self.monomial(j) for j in range(i)) from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.combinat.root_system.type_A', 'ambient_space', AmbientSpace) from sage.misc.cachefunc import cached_method from .cartan_type import CartanType_standard_finite, CartanType_simply_laced, CartanType_simple class CartanType(CartanType_standard_finite, CartanType_simply_laced): def __init__(self, n): """ EXAMPLES:: sage: ct = CartanType(['D',4]) sage: ct ['D', 4] sage: ct._repr_(compact = True) 'D4' sage: ct.is_irreducible() True sage: ct.is_finite() True sage: ct.is_crystallographic() True sage: ct.is_simply_laced() True sage: ct.dual() ['D', 4] sage: ct.affine() ['D', 4, 1] sage: ct = CartanType(['D',2]) sage: ct.is_irreducible() False sage: ct.dual() ['D', 2] sage: ct.affine() Traceback (most recent call last): ... ValueError: ['D', 2, 1] is not a valid Cartan type TESTS:: sage: TestSuite(ct).run() """ assert n >= 2 CartanType_standard_finite.__init__(self, "D", n) if n >= 3: self._add_abstract_superclass(CartanType_simple) def _latex_(self): """ Return a latex representation of ``self``. EXAMPLES:: sage: latex(CartanType(['D',4])) D_{4} """ return "D_{%s}" % self.n AmbientSpace = AmbientSpace def is_atomic(self): """ Implements :meth:`CartanType_abstract.is_atomic` `D_2` is atomic, like all `D_n`, despite being non irreducible. EXAMPLES:: sage: CartanType(["D",2]).is_atomic() True sage: CartanType(["D",2]).is_irreducible() False """ return True def coxeter_number(self): """ Return the Coxeter number associated with ``self``. EXAMPLES:: sage: CartanType(['D',4]).coxeter_number() 6 """ return 2*self.n - 2 def dual_coxeter_number(self): """ Return the dual Coxeter number associated with ``self``. EXAMPLES:: sage: CartanType(['D',4]).dual_coxeter_number() 6 """ return 2*self.n - 2 @cached_method def dynkin_diagram(self): """ Returns a Dynkin diagram for type D. EXAMPLES:: sage: d = CartanType(['D',5]).dynkin_diagram(); d O 5 | | O---O---O---O 1 2 3 4 D5 sage: d.edges(sort=True) [(1, 2, 1), (2, 1, 1), (2, 3, 1), (3, 2, 1), (3, 4, 1), (3, 5, 1), (4, 3, 1), (5, 3, 1)] sage: d = CartanType(['D',4]).dynkin_diagram(); d O 4 | | O---O---O 1 2 3 D4 sage: d.edges(sort=True) [(1, 2, 1), (2, 1, 1), (2, 3, 1), (2, 4, 1), (3, 2, 1), (4, 2, 1)] sage: d = CartanType(['D',3]).dynkin_diagram(); d O 3 | | O---O 1 2 D3 sage: d.edges(sort=True) [(1, 2, 1), (1, 3, 1), (2, 1, 1), (3, 1, 1)] sage: d = CartanType(['D',2]).dynkin_diagram(); d O O 1 2 D2 sage: d.edges(sort=True) [] """ from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) n = self.n if n >= 3: for i in range(1, n-1): g.add_edge(i, i+1) g.add_edge(n-2, n) return g def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['D',4])._latex_dynkin_diagram()) \draw (0 cm,0) -- (2 cm,0); \draw (2 cm,0) -- (4 cm,0.7 cm); \draw (2 cm,0) -- (4 cm,-0.7 cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0.7 cm) circle (.25cm) node[right=3pt]{$4$}; \draw[fill=white] (4 cm, -0.7 cm) circle (.25cm) node[right=3pt]{$3$}; <BLANKLINE> """ if node is None: node = self._latex_draw_node if self.n == 2: ret = node(0, 0, label(1)) ret += node(node_dist, 0, label(2)) return ret rt_most = (self.n-2) * node_dist center_point = rt_most - node_dist ret = "\\draw (0 cm,0) -- (%s cm,0);\n"%center_point ret += "\\draw (%s cm,0) -- (%s cm,0.7 cm);\n"%(center_point, rt_most) ret += "\\draw (%s cm,0) -- (%s cm,-0.7 cm);\n"%(center_point, rt_most) for i in range(self.n-2): ret += node(i*node_dist, 0, label(i+1)) ret += node(rt_most, 0.7, label(self.n), 'right=3pt') ret += node(rt_most, -0.7, label(self.n-1), 'right=3pt') return ret def ascii_art(self, label=lambda i: i, node=None): """ Return a ascii art representation of the extended Dynkin diagram. EXAMPLES:: sage: print(CartanType(['D',3]).ascii_art()) O 3 | | O---O 1 2 sage: print(CartanType(['D',4]).ascii_art()) O 4 | | O---O---O 1 2 3 sage: print(CartanType(['D',4]).ascii_art(label = lambda x: x+2)) O 6 | | O---O---O 3 4 5 sage: print(CartanType(['D',6]).ascii_art(label = lambda x: x+2)) O 8 | | O---O---O---O---O 3 4 5 6 7 """ if node is None: node = self._ascii_art_node n = self.n if n == 2: ret = "{} {}\n".format(node(label(1)), node(label(2))) return ret + "{!s:4}{!s:4}".format(label(1), label(2)) ret = (4*(n-3))*" "+"{} {}\n".format(node(label(n)), label(n)) ret += ((4*(n-3))*" " +"|\n")*2 ret += "---".join(node(label(i)) for i in range(1, n)) +"\n" ret += "".join("{!s:4}".format(label(i)) for i in range(1,n)) return ret # For unpickling backward compatibility (Sage <= 4.1) from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.combinat.root_system.type_D', 'ambient_space', AmbientSpace)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_D.py
0.747155
0.553324
type_D.py
pypi
from .cartan_type import CartanType_standard_finite, CartanType_simple class CartanType(CartanType_standard_finite, CartanType_simple): def __init__(self, n): """ EXAMPLES:: sage: ct = CartanType(['H',3]) sage: ct ['H', 3] sage: ct._repr_(compact = True) 'H3' sage: ct.rank() 3 sage: ct.is_irreducible() True sage: ct.is_finite() True sage: ct.is_affine() False sage: ct.is_crystallographic() False sage: ct.is_simply_laced() False TESTS:: sage: TestSuite(ct).run() """ assert n in [3, 4] CartanType_standard_finite.__init__(self, "H", n) def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: latex(CartanType(['H',3])) H_3 """ return "H_{}".format(self.n) def coxeter_diagram(self): """ Returns a Coxeter diagram for type H. EXAMPLES:: sage: ct = CartanType(['H',3]) sage: ct.coxeter_diagram() Graph on 3 vertices sage: ct.coxeter_diagram().edges(sort=True) [(1, 2, 3), (2, 3, 5)] sage: ct.coxeter_matrix() [1 3 2] [3 1 5] [2 5 1] sage: ct = CartanType(['H',4]) sage: ct.coxeter_diagram() Graph on 4 vertices sage: ct.coxeter_diagram().edges(sort=True) [(1, 2, 3), (2, 3, 3), (3, 4, 5)] sage: ct.coxeter_matrix() [1 3 2 2] [3 1 3 2] [2 3 1 5] [2 2 5 1] """ from sage.graphs.graph import Graph n = self.n g = Graph(multiedges=False) for i in range(1, n): g.add_edge(i, i+1, 3) g.set_edge_label(n-1, n, 5) return g def coxeter_number(self): """ Return the Coxeter number associated with ``self``. EXAMPLES:: sage: CartanType(['H',3]).coxeter_number() 10 sage: CartanType(['H',4]).coxeter_number() 30 """ if self.n == 3: return 10 return 30
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_H.py
0.883914
0.628977
type_H.py
pypi
from .cartan_type import CartanType_standard, CartanType_simple from sage.rings.integer_ring import ZZ class CartanType(CartanType_standard, CartanType_simple): r""" The Cartan type `A_{\infty}`. We use ``NN`` and ``ZZ`` to explicitly differentiate between the `A_{+\infty}` and `A_{\infty}` root systems, respectively. While ``oo`` is the same as ``+Infinity`` in Sage, it is used as an alias for ``ZZ``. """ # We do not inherit from CartanType_crystallographic because it provides # methods that are not implemented for A_oo. def __init__(self, index_set): """ EXAMPLES:: sage: CartanType(['A',oo]) is CartanType(['A', ZZ]) True sage: CartanType(['A',oo]) is CartanType(['A', NN]) False sage: ct=CartanType(['A',ZZ]) sage: ct ['A', ZZ] sage: ct._repr_(compact = True) 'A_ZZ' sage: ct.is_irreducible() True sage: ct.is_finite() False sage: ct.is_affine() False sage: ct.is_untwisted_affine() False sage: ct.is_crystallographic() True sage: ct.is_simply_laced() True sage: ct.dual() ['A', ZZ] TESTS:: sage: TestSuite(ct).run() """ super().__init__() self.letter = 'A' self.n = index_set def _repr_(self, compact=False): """ Return a representation of ``self``. TESTS:: sage: CartanType(['A',ZZ]) ['A', ZZ] sage: CartanType(['A',NN])._repr_(compact=True) 'A_NN' """ ret = '%s_%s' if compact else "['%s', %s]" return ret % (self.letter, 'ZZ' if self.n == ZZ else 'NN') def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: latex( CartanType(['A',NN]) ) A_{\Bold{N}} sage: latex( CartanType(['A',ZZ]) ) A_{\Bold{Z}} """ return 'A_{{{}}}'.format(self.n._latex_()) def ascii_art(self, label=lambda i: i, node=None): """ Return an ascii art representation of the extended Dynkin diagram. EXAMPLES:: sage: print(CartanType(['A', ZZ]).ascii_art()) ..---O---O---O---O---O---O---O---.. -3 -2 -1 0 1 2 3 sage: print(CartanType(['A', NN]).ascii_art()) O---O---O---O---O---O---O---.. 0 1 2 3 4 5 6 """ if node is None: node = self._ascii_art_node if self.n == ZZ: ret = '..---' + '---'.join(node(label(i)) for i in range(7)) + '---..\n' ret += ' ' + ''.join("{:4}".format(label(i)) for i in range(-3, 4)) else: ret = '---'.join(node(label(i)) for i in range(7)) + '---..\n' ret += '0' + ''.join("{:4}".format(label(i)) for i in range(1, 7)) return ret def dual(self): """ Simply laced Cartan types are self-dual, so return ``self``. EXAMPLES:: sage: CartanType(["A", NN]).dual() ['A', NN] sage: CartanType(["A", ZZ]).dual() ['A', ZZ] """ return self def is_simply_laced(self): """ Return ``True`` because ``self`` is simply laced. EXAMPLES:: sage: CartanType(['A', NN]).is_simply_laced() True sage: CartanType(['A', ZZ]).is_simply_laced() True """ return True def is_crystallographic(self): """ Return ``False`` because ``self`` is not crystallographic. EXAMPLES:: sage: CartanType(['A', NN]).is_crystallographic() True sage: CartanType(['A', ZZ]).is_crystallographic() True """ return True def is_finite(self): """ Return ``True`` because ``self`` is not finite. EXAMPLES:: sage: CartanType(['A', NN]).is_finite() False sage: CartanType(['A', ZZ]).is_finite() False """ return False def is_affine(self): """ Return ``False`` because ``self`` is not (untwisted) affine. EXAMPLES:: sage: CartanType(['A', NN]).is_affine() False sage: CartanType(['A', ZZ]).is_affine() False """ return False def is_untwisted_affine(self): """ Return ``False`` because ``self`` is not (untwisted) affine. EXAMPLES:: sage: CartanType(['A', NN]).is_untwisted_affine() False sage: CartanType(['A', ZZ]).is_untwisted_affine() False """ return False def rank(self): """ Return the rank of ``self`` which for type `X_n` is `n`. EXAMPLES:: sage: CartanType(['A', NN]).rank() +Infinity sage: CartanType(['A', ZZ]).rank() +Infinity As this example shows, the rank is slightly ambiguous because the root systems of type `['A',NN]` and type `['A',ZZ]` have the same rank. Instead, it is better ot use :meth:`index_set` to differentiate between these two root systems. """ return self.n.cardinality() def type(self): """ Return the type of ``self``. EXAMPLES:: sage: CartanType(['A', NN]).type() 'A' sage: CartanType(['A', ZZ]).type() 'A' """ return self.letter def index_set(self): r""" Return the index set for the Cartan type ``self``. The index set for all standard finite Cartan types is of the form `\{1, \ldots, n\}`. (See :mod:`~sage.combinat.root_system.type_I` for a slight abuse of this). EXAMPLES:: sage: CartanType(['A', NN]).index_set() Non negative integer semiring sage: CartanType(['A', ZZ]).index_set() Integer Ring """ return self.n
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_A_infinity.py
0.905433
0.711384
type_A_infinity.py
pypi
from .cartan_type import CartanType_standard_untwisted_affine class CartanType(CartanType_standard_untwisted_affine): def __init__(self, n): """ EXAMPLES:: sage: ct = CartanType(['C',4,1]) sage: ct ['C', 4, 1] sage: ct._repr_(compact = True) 'C4~' sage: ct.is_irreducible() True sage: ct.is_finite() False sage: ct.is_affine() True sage: ct.is_untwisted_affine() True sage: ct.is_crystallographic() True sage: ct.is_simply_laced() False sage: ct.classical() ['C', 4] sage: ct.dual() ['C', 4, 1]^* sage: ct.dual().is_untwisted_affine() False TESTS:: sage: TestSuite(ct).run() """ assert n >= 1 CartanType_standard_untwisted_affine.__init__(self, "C", n) def dynkin_diagram(self): """ Returns the extended Dynkin diagram for affine type C. EXAMPLES:: sage: c = CartanType(['C',3,1]).dynkin_diagram() sage: c O=>=O---O=<=O 0 1 2 3 C3~ sage: c.edges(sort=True) [(0, 1, 2), (1, 0, 1), (1, 2, 1), (2, 1, 1), (2, 3, 1), (3, 2, 2)] """ n = self.n if n == 1: from . import cartan_type res = cartan_type.CartanType(["A",1,1]).dynkin_diagram() res._cartan_type = self return res from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) for i in range(1, n): g.add_edge(i, i+1) g.set_edge_label(n,n-1,2) g.add_edge(0,1,2) return g def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['C',4,1])._latex_dynkin_diagram()) \draw (0, 0.1 cm) -- +(2 cm,0); \draw (0, -0.1 cm) -- +(2 cm,0); \draw[shift={(1.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); { \pgftransformxshift{2 cm} \draw (0 cm,0) -- (4 cm,0); \draw (4 cm, 0.1 cm) -- +(2 cm,0); \draw (4 cm, -0.1 cm) -- +(2 cm,0); \draw[shift={(4.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; } \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; sage: print(CartanType(['C',4,1]).dual()._latex_dynkin_diagram()) \draw (0, 0.1 cm) -- +(2 cm,0); \draw (0, -0.1 cm) -- +(2 cm,0); \draw[shift={(0.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); { \pgftransformxshift{2 cm} \draw (0 cm,0) -- (4 cm,0); \draw (4 cm, 0.1 cm) -- +(2 cm,0); \draw (4 cm, -0.1 cm) -- +(2 cm,0); \draw[shift={(5.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; } \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; <BLANKLINE> """ if node is None: node = self._latex_draw_node if self.n == 1: from . import cartan_type return cartan_type.CartanType(["A",1,1])._latex_dynkin_diagram(label, node, node_dist) ret = "\\draw (0, 0.1 cm) -- +(%s cm,0);\n"%node_dist ret += "\\draw (0, -0.1 cm) -- +(%s cm,0);\n"%node_dist if dual: ret += self._latex_draw_arrow_tip(0.5*node_dist-0.2, 0, 180) else: ret += self._latex_draw_arrow_tip(0.5*node_dist+0.2, 0, 0) ret += "{\n\\pgftransformxshift{%s cm}\n"%node_dist ret += self.classical()._latex_dynkin_diagram(label, node, node_dist, dual) ret += "}\n" + node(0, 0, label(0)) return ret def ascii_art(self, label=lambda i: i, node=None): """ Return a ascii art representation of the extended Dynkin diagram. EXAMPLES:: sage: print(CartanType(['C',5,1]).ascii_art(label = lambda x: x+2)) O=>=O---O---O---O=<=O 2 3 4 5 6 7 sage: print(CartanType(['C',3,1]).ascii_art()) O=>=O---O=<=O 0 1 2 3 sage: print(CartanType(['C',2,1]).ascii_art()) O=>=O=<=O 0 1 2 sage: print(CartanType(['C',1,1]).ascii_art()) O<=>O 0 1 """ if node is None: node = self._ascii_art_node n = self.n from .cartan_type import CartanType if n == 1: return CartanType(["A",1,1]).ascii_art(label, node) ret = node(label(0)) + "=>=" + "---".join(node(label(i)) for i in range(1,n)) ret += "=<=" + node(label(n)) + '\n' ret += "".join("{!s:4}".format(label(i)) for i in range(n+1)) return ret def _default_folded_cartan_type(self): """ Return the default folded Cartan type. EXAMPLES:: sage: CartanType(['C', 3, 1])._default_folded_cartan_type() ['C', 3, 1] as a folding of ['A', 5, 1] """ from sage.combinat.root_system.type_folded import CartanTypeFolded n = self.n if n == 1: return CartanTypeFolded(self, ['A', 1, 1], [[0], [1]]) return CartanTypeFolded(self, ['A', 2*n-1, 1], [[0]] + [[i, 2*n-i] for i in range(1, n)] + [[n]])
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_C_affine.py
0.759493
0.323013
type_C_affine.py
pypi
from sage.rings.integer_ring import ZZ from sage.misc.cachefunc import cached_method from . import ambient_space from .cartan_type import SuperCartanType_standard class AmbientSpace(ambient_space.AmbientSpace): r""" The ambient space for (super) type `A(m|n)`. EXAMPLES:: sage: R = RootSystem(['A', [2,1]]) sage: AL = R.ambient_space(); AL Ambient space of the Root system of type ['A', [2, 1]] sage: AL.basis() Finite family {-3: (1, 0, 0, 0, 0), -2: (0, 1, 0, 0, 0), -1: (0, 0, 1, 0, 0), 1: (0, 0, 0, 1, 0), 2: (0, 0, 0, 0, 1)} """ def __init__(self, root_system, base_ring, index_set=None): """ Initialize ``self``. TESTS:: sage: R = RootSystem(['A', [4,2]]) sage: AL = R.ambient_space(); AL Ambient space of the Root system of type ['A', [4, 2]] sage: TestSuite(AL).run(skip="_test_norm_of_simple_roots") """ ct = root_system.cartan_type() if index_set is None: index_set = tuple(list(range(-ct.m - 1, 0)) + list(range(1, ct.n + 2))) ambient_space.AmbientSpace.__init__(self, root_system, base_ring, index_set=index_set) @classmethod def smallest_base_ring(cls, cartan_type=None): """ Return the smallest base ring the ambient space can be defined upon. .. SEEALSO:: :meth:`~sage.combinat.root_system.ambient_space.AmbientSpace.smallest_base_ring` EXAMPLES:: sage: e = RootSystem(['A', [3,1]]).ambient_space() sage: e.smallest_base_ring() Integer Ring """ return ZZ def dimension(self): """ Return the dimension of this ambient space. EXAMPLES:: sage: e = RootSystem(['A', [4,2]]).ambient_space() sage: e.dimension() 8 """ ct = self.root_system.cartan_type() return ct.m + ct.n + 2 def simple_root(self, i): """ Return the `i`-th simple root of ``self``. EXAMPLES:: sage: e = RootSystem(['A', [2,1]]).ambient_lattice() sage: list(e.simple_roots()) [(1, -1, 0, 0, 0), (0, 1, -1, 0, 0), (0, 0, 1, -1, 0), (0, 0, 0, 1, -1)] """ if i < 0: return self.monomial(i-1) - self.monomial(i) if i == 0: return self.monomial(-1) - self.monomial(1) return self.monomial(i) - self.monomial(i+1) def positive_roots(self): """ Return the positive roots of ``self``. EXAMPLES:: sage: e = RootSystem(['A', [2,1]]).ambient_lattice() sage: e.positive_roots() [(0, 1, -1, 0, 0), (1, 0, -1, 0, 0), (1, -1, 0, 0, 0), (0, 0, 0, 1, -1), (0, 0, 1, -1, 0), (0, 0, 1, 0, -1), (0, 1, 0, -1, 0), (0, 1, 0, 0, -1), (1, 0, 0, -1, 0), (1, 0, 0, 0, -1)] """ return self.positive_even_roots() + self.positive_odd_roots() def positive_even_roots(self): """ Return the positive even roots of ``self``. EXAMPLES:: sage: e = RootSystem(['A', [2,1]]).ambient_lattice() sage: e.positive_even_roots() [(0, 1, -1, 0, 0), (1, 0, -1, 0, 0), (1, -1, 0, 0, 0), (0, 0, 0, 1, -1)] """ ct = self.root_system.cartan_type() ret = [] ret += [self.monomial(-j) - self.monomial(-i) for i in range(1, ct.m + 2) for j in range(i + 1, ct.m + 2)] ret += [self.monomial(i) - self.monomial(j) for i in range(1, ct.n + 2) for j in range(i + 1, ct.n + 2)] return ret def positive_odd_roots(self): """ Return the positive odd roots of ``self``. EXAMPLES:: sage: e = RootSystem(['A', [2,1]]).ambient_lattice() sage: e.positive_odd_roots() [(0, 0, 1, -1, 0), (0, 0, 1, 0, -1), (0, 1, 0, -1, 0), (0, 1, 0, 0, -1), (1, 0, 0, -1, 0), (1, 0, 0, 0, -1)] """ ct = self.root_system.cartan_type() return [self.monomial(-i) - self.monomial(j) for i in range(1, ct.m + 2) for j in range(1, ct.n + 2)] def highest_root(self): """ Return the highest root of ``self``. EXAMPLES:: sage: e = RootSystem(['A', [4,2]]).ambient_lattice() sage: e.highest_root() (1, 0, 0, 0, 0, 0, 0, -1) """ ct = self.root_system.cartan_type() return self.monomial(-ct.m-1) - self.monomial(ct.n+1) def negative_roots(self): """ Return the negative roots of ``self``. EXAMPLES:: sage: e = RootSystem(['A', [2,1]]).ambient_lattice() sage: e.negative_roots() [(0, -1, 1, 0, 0), (-1, 0, 1, 0, 0), (-1, 1, 0, 0, 0), (0, 0, 0, -1, 1), (0, 0, -1, 1, 0), (0, 0, -1, 0, 1), (0, -1, 0, 1, 0), (0, -1, 0, 0, 1), (-1, 0, 0, 1, 0), (-1, 0, 0, 0, 1)] """ return self.negative_even_roots() + self.negative_odd_roots() def negative_even_roots(self): """ Return the negative even roots of ``self``. EXAMPLES:: sage: e = RootSystem(['A', [2,1]]).ambient_lattice() sage: e.negative_even_roots() [(0, -1, 1, 0, 0), (-1, 0, 1, 0, 0), (-1, 1, 0, 0, 0), (0, 0, 0, -1, 1)] """ ct = self.root_system.cartan_type() ret = [] ret += [self.monomial(-i) - self.monomial(-j) for i in range(1, ct.m + 2) for j in range(i + 1, ct.m + 2)] ret += [self.monomial(j) - self.monomial(i) for i in range(1, ct.n + 2) for j in range(i + 1, ct.n + 2)] return ret def negative_odd_roots(self): """ Return the negative odd roots of ``self``. EXAMPLES:: sage: e = RootSystem(['A', [2,1]]).ambient_lattice() sage: e.negative_odd_roots() [(0, 0, -1, 1, 0), (0, 0, -1, 0, 1), (0, -1, 0, 1, 0), (0, -1, 0, 0, 1), (-1, 0, 0, 1, 0), (-1, 0, 0, 0, 1)] """ ct = self.root_system.cartan_type() return [self.monomial(j) - self.monomial(-i) for i in range(1, ct.m + 2) for j in range(1, ct.n + 2)] def fundamental_weight(self, i): r""" Return the fundamental weight `\Lambda_i` of ``self``. EXAMPLES:: sage: L = RootSystem(['A', [3,2]]).ambient_space() sage: L.fundamental_weight(-1) (1, 1, 1, 0, 0, 0, 0) sage: L.fundamental_weight(0) (1, 1, 1, 1, 0, 0, 0) sage: L.fundamental_weight(2) (1, 1, 1, 1, -1, -1, -2) sage: list(L.fundamental_weights()) [(1, 0, 0, 0, 0, 0, 0), (1, 1, 0, 0, 0, 0, 0), (1, 1, 1, 0, 0, 0, 0), (1, 1, 1, 1, 0, 0, 0), (1, 1, 1, 1, -1, -2, -2), (1, 1, 1, 1, -1, -1, -2)] :: sage: L = RootSystem(['A', [2,3]]).ambient_space() sage: La = L.fundamental_weights() sage: al = L.simple_roots() sage: I = L.index_set() sage: matrix([[al[i].scalar(La[j]) for i in I] for j in I]) [ 1 0 0 0 0 0] [ 0 1 0 0 0 0] [ 0 0 1 0 0 0] [ 0 0 0 -1 0 0] [ 0 0 0 0 -1 0] [ 0 0 0 0 0 -1] """ m = self.root_system.cartan_type().m n = self.root_system.cartan_type().n if i <= 0: return self.sum(self.monomial(j) for j in range(-m-1,i)) return (self.sum(self.monomial(j) for j in range(-m-1,1)) - self.sum(self.monomial(j) for j in range(i+1)) - 2*self.sum(self.monomial(j) for j in range(i+1,n+2))) def simple_coroot(self, i): """ Return the simple coroot `h_i` of ``self``. EXAMPLES:: sage: L = RootSystem(['A', [3,2]]).ambient_space() sage: L.simple_coroot(-2) (0, 1, -1, 0, 0, 0, 0) sage: L.simple_coroot(0) (0, 0, 0, 1, -1, 0, 0) sage: L.simple_coroot(2) (0, 0, 0, 0, 0, -1, 1) sage: list(L.simple_coroots()) [(1, -1, 0, 0, 0, 0, 0), (0, 1, -1, 0, 0, 0, 0), (0, 0, 1, -1, 0, 0, 0), (0, 0, 0, 1, -1, 0, 0), (0, 0, 0, 0, -1, 1, 0), (0, 0, 0, 0, 0, -1, 1)] """ if i <= 0: return self.simple_root(i) return -self.simple_root(i) class Element(ambient_space.AmbientSpaceElement): def inner_product(self, lambdacheck): """ The scalar product with elements of the coroot lattice embedded in the ambient space. EXAMPLES:: sage: L = RootSystem(['A', [2,1]]).ambient_space() sage: a = L.simple_roots() sage: matrix([[a[i].inner_product(a[j]) for j in L.index_set()] for i in L.index_set()]) [ 2 -1 0 0] [-1 2 -1 0] [ 0 -1 0 1] [ 0 0 1 -2] """ self_mc = self._monomial_coefficients lambdacheck_mc = lambdacheck._monomial_coefficients result = self.parent().base_ring().zero() for t,c in lambdacheck_mc.items(): if t not in self_mc: continue if t > 0: result -= c*self_mc[t] else: result += c*self_mc[t] return result scalar = inner_product dot_product = inner_product def associated_coroot(self): """ Return the coroot associated to ``self``. EXAMPLES:: sage: L = RootSystem(['A', [3,2]]).ambient_space() sage: al = L.simple_roots() sage: al[-1].associated_coroot() (0, 0, 1, -1, 0, 0, 0) sage: al[0].associated_coroot() (0, 0, 0, 1, -1, 0, 0) sage: al[1].associated_coroot() (0, 0, 0, 0, -1, 1, 0) sage: a = al[-1] + al[0] + al[1]; a (0, 0, 1, 0, 0, -1, 0) sage: a.associated_coroot() (0, 0, 1, 0, -2, 1, 0) sage: h = L.simple_coroots() sage: h[-1] + h[0] + h[1] (0, 0, 1, 0, -2, 1, 0) sage: (al[-1] + al[0] + al[2]).associated_coroot() (0, 0, 1, 0, -1, -1, 1) """ P = self.parent() al = P.simple_roots() h = P.simple_coroots() try: return h[al.inverse_family()[self]] except KeyError: pass V = P._dense_free_module() dep = V.linear_dependence([self._vector_()] + [al[i]._vector_() for i in P.index_set()])[0] I = P.index_set() return P.sum((-c/dep[0]) * h[I[i]] for i,c in dep[1:].items()) def has_descent(self, i, positive=False): """ Test if ``self`` has a descent at position `i`, that is if ``self`` is on the strict negative side of the `i^{th}` simple reflection hyperplane. If ``positive`` is ``True``, tests if it is on the strict positive side instead. EXAMPLES:: sage: L = RootSystem(['A', [2,1]]).ambient_space() sage: al = L.simple_roots() sage: [al[i].has_descent(1) for i in L.index_set()] [False, False, True, False] sage: [(-al[i]).has_descent(1) for i in L.index_set()] [False, False, False, True] sage: [al[i].has_descent(1, True) for i in L.index_set()] [False, False, False, True] sage: [(-al[i]).has_descent(1, True) for i in L.index_set()] [False, False, True, False] sage: (al[-2] + al[0] + al[1]).has_descent(-1) True sage: (al[-2] + al[0] + al[1]).has_descent(1) False sage: (al[-2] + al[0] + al[1]).has_descent(1, positive=True) True sage: all(all(not la.has_descent(i) for i in L.index_set()) ....: for la in L.fundamental_weights()) True """ s = self.scalar(self.parent().simple_roots()[i]) if i > 0: s = -s if positive: return s > 0 else: return s < 0 def is_dominant_weight(self): """ Test whether ``self`` is a dominant element of the weight lattice. EXAMPLES:: sage: L = RootSystem(['A',2]).ambient_lattice() sage: Lambda = L.fundamental_weights() sage: [x.is_dominant() for x in Lambda] [True, True] sage: (3*Lambda[1]+Lambda[2]).is_dominant() True sage: (Lambda[1]-Lambda[2]).is_dominant() False sage: (-Lambda[1]+Lambda[2]).is_dominant() False Tests that the scalar products with the coroots are all nonnegative integers. For example, if `x` is the sum of a dominant element of the weight lattice plus some other element orthogonal to all coroots, then the implementation correctly reports `x` to be a dominant weight:: sage: x = Lambda[1] + L([-1,-1,-1]) sage: x.is_dominant_weight() True """ alpha = self.parent().simple_roots() l = self.parent().cartan_type().symmetrizer() from sage.rings.semirings.non_negative_integer_semiring import NN return all(l[i] * self.inner_product(alpha[i]) in NN for i in self.parent().index_set()) class CartanType(SuperCartanType_standard): """ Cartan Type `A(m|n)`. .. SEEALSO:: :func:`~sage.combinat.root_systems.cartan_type.CartanType` """ def __init__(self, m, n): """ EXAMPLES:: sage: ct = CartanType(['A', [4,2]]) sage: ct ['A', [4, 2]] sage: ct._repr_(compact=True) 'A4|2' sage: ct.is_irreducible() True sage: ct.is_finite() True sage: ct.is_affine() False sage: ct.affine() # Not tested -- to be implemented ['A', [4, 2], 1] sage: ct.dual() ['A', [4, 2]] TESTS:: sage: TestSuite(ct).run() """ self.m = m self.n = n self.letter = "A" def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: latex(CartanType(['A',[4,3]])) A(4|3) """ return "A(%s|%s)" % (self.m, self.n) def index_set(self): """ Return the index set of ``self``. EXAMPLES:: sage: CartanType(['A', [2,3]]).index_set() (-2, -1, 0, 1, 2, 3) """ return tuple(range(-self.m, self.n + 1)) AmbientSpace = AmbientSpace def is_irreducible(self): """ Return whether ``self`` is irreducible, which is ``True``. EXAMPLES:: sage: CartanType(['A', [3,4]]).is_irreducible() True """ return True # A lot of these methods should be implemented by the ABCs of CartanType def is_affine(self): """ Return whether ``self`` is affine or not. EXAMPLES:: sage: CartanType(['A', [2,3]]).is_affine() False """ return False def is_finite(self): """ Return whether ``self`` is finite or not. EXAMPLES:: sage: CartanType(['A', [2,3]]).is_finite() True """ return True def dual(self): """ Return dual of ``self``. EXAMPLES:: sage: CartanType(['A', [2,3]]).dual() ['A', [2, 3]] """ return self def type(self): """ Return type of ``self``. EXAMPLES:: sage: CartanType(['A', [2,3]]).type() 'A' """ return 'A' def root_system(self): """ Return root system of ``self``. EXAMPLES:: sage: CartanType(['A', [2,3]]).root_system() Root system of type ['A', [2, 3]] """ from sage.combinat.root_system.root_system import RootSystem return RootSystem(self) @cached_method def symmetrizer(self): """ Return symmetrizing matrix for ``self``. EXAMPLES:: sage: CartanType(['A', [2,3]]).symmetrizer() Finite family {-2: 1, -1: 1, 0: 1, 1: -1, 2: -1, 3: -1} """ from sage.sets.family import Family def ell(i): return ZZ.one() if i <= 0 else -ZZ.one() return Family(self.index_set(), ell) def dynkin_diagram(self): """ Return the Dynkin diagram of super type A. EXAMPLES:: sage: a = CartanType(['A', [4,2]]).dynkin_diagram() sage: a O---O---O---O---X---O---O -4 -3 -2 -1 0 1 2 A4|2 sage: a.edges(sort=True) [(-4, -3, 1), (-3, -4, 1), (-3, -2, 1), (-2, -3, 1), (-2, -1, 1), (-1, -2, 1), (-1, 0, 1), (0, -1, 1), (0, 1, 1), (1, 0, -1), (1, 2, 1), (2, 1, 1)] TESTS:: sage: a = DynkinDiagram(['A', [0,0]]); a X 0 A0|0 sage: a.vertices(sort=False), a.edges(sort=False) ([0], []) sage: a = DynkinDiagram(['A', [1,0]]); a O---X -1 0 A1|0 sage: a.vertices(sort=True), a.edges(sort=True) ([-1, 0], [(-1, 0, 1), (0, -1, 1)]) sage: a = DynkinDiagram(['A', [0,1]]); a X---O 0 1 A0|1 sage: a.vertices(sort=True), a.edges(sort=True) ([0, 1], [(0, 1, 1), (1, 0, -1)]) """ from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self, odd_isotropic_roots=[0]) for i in range(self.m): g.add_edge(-i-1, -i) for i in range(1, self.n): g.add_edge(i, i+1) g.add_vertex(0) # Usually there, but not when m == n == 0 if self.m > 0: g.add_edge(-1, 0) if self.n > 0: g.add_edge(1, 0, -1) return g def cartan_matrix(self): """ Return the Cartan matrix associated to ``self``. EXAMPLES:: sage: ct = CartanType(['A', [2,3]]) sage: ct.cartan_matrix() [ 2 -1 0 0 0 0] [-1 2 -1 0 0 0] [ 0 -1 0 1 0 0] [ 0 0 -1 2 -1 0] [ 0 0 0 -1 2 -1] [ 0 0 0 0 -1 2] TESTS:: sage: ct = CartanType(['A', [0,0]]) sage: ct.cartan_matrix() [0] sage: ct = CartanType(['A', [1,0]]) sage: ct.cartan_matrix() [ 2 -1] [-1 0] sage: ct = CartanType(['A', [0,1]]) sage: ct.cartan_matrix() [ 0 1] [-1 2] """ return self.dynkin_diagram().cartan_matrix() def relabel(self, relabelling): """ Return a relabelled copy of this Cartan type. INPUT: - ``relabelling`` -- a function (or a list or dictionary) OUTPUT: an isomorphic Cartan type obtained by relabelling the nodes of the Dynkin diagram. Namely, the node with label ``i`` is relabelled ``f(i)`` (or, by ``f[i]`` if ``f`` is a list or dictionary). EXAMPLES:: sage: ct = CartanType(['A', [1,2]]) sage: ct.dynkin_diagram() O---X---O---O -1 0 1 2 A1|2 sage: f={1:2,2:1,0:0,-1:-1} sage: ct.relabel(f) ['A', [1, 2]] relabelled by {-1: -1, 0: 0, 1: 2, 2: 1} sage: ct.relabel(f).dynkin_diagram() O---X---O---O -1 0 2 1 A1|2 relabelled by {-1: -1, 0: 0, 1: 2, 2: 1} """ from . import type_relabel return type_relabel.CartanType(self, relabelling) def _latex_draw_node(self, x, y, label, position="below=4pt"): r""" Draw (possibly marked [crossed out]) circular node ``i`` at the position ``(x,y)`` with node label ``label`` . - ``position`` -- position of the label relative to the node - ``anchor`` -- (optional) the anchor point for the label EXAMPLES:: sage: t = CartanType(['A', [3,2]]) sage: print(t._latex_draw_node(0, 0, 0)) \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; \draw[-,thick] (0.17 cm, 0.17 cm) -- (-0.17 cm, -0.17 cm); \draw[-,thick] (0.17 cm, -0.17 cm) -- (-0.17 cm, 0.17 cm); sage: print(t._latex_draw_node(0, 0, 1)) \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; """ ret = "\\draw[fill={}] ({} cm, {} cm) circle (.25cm) node[{}]{{${}$}};\n".format( 'white', x, y, position, label) if label == 0: ret += "\\draw[-,thick] ({} cm, {} cm) -- ({} cm, {} cm);\n".format( x+.17, y+.17, x-.17, y-.17) ret += "\\draw[-,thick] ({} cm, {} cm) -- ({} cm, {} cm);\n".format( x+.17, y-.17, x-.17, y+.17) return ret def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['A', [3,2]])._latex_dynkin_diagram()) \draw (0 cm, 0 cm) -- (10 cm, 0 cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$-3$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$-2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$-1$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; \draw[-,thick] (6.17 cm, 0.17 cm) -- (5.83 cm, -0.17 cm); \draw[-,thick] (6.17 cm, -0.17 cm) -- (5.83 cm, 0.17 cm); \draw[fill=white] (8 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (10 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; sage: print(CartanType(['A', [0,2]])._latex_dynkin_diagram()) \draw (0 cm, 0 cm) -- (4 cm, 0 cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; \draw[-,thick] (0.17 cm, 0.17 cm) -- (-0.17 cm, -0.17 cm); \draw[-,thick] (0.17 cm, -0.17 cm) -- (-0.17 cm, 0.17 cm); \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; sage: print(CartanType(['A', [2,0]])._latex_dynkin_diagram()) \draw (0 cm, 0 cm) -- (4 cm, 0 cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$-2$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$-1$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; \draw[-,thick] (4.17 cm, 0.17 cm) -- (3.83 cm, -0.17 cm); \draw[-,thick] (4.17 cm, -0.17 cm) -- (3.83 cm, 0.17 cm); sage: print(CartanType(['A', [0,0]])._latex_dynkin_diagram()) \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; \draw[-,thick] (0.17 cm, 0.17 cm) -- (-0.17 cm, -0.17 cm); \draw[-,thick] (0.17 cm, -0.17 cm) -- (-0.17 cm, 0.17 cm); """ if node is None: node = self._latex_draw_node if self.n + self.m > 1: ret = "\\draw (0 cm, 0 cm) -- ({} cm, 0 cm);\n".format((self.n+self.m)*node_dist) else: ret = "" return ret + "".join(node((self.m+i)*node_dist, 0, label(i)) for i in self.index_set()) def ascii_art(self, label=lambda i: i, node=None): """ Return an ascii art representation of the Dynkin diagram. EXAMPLES:: sage: t = CartanType(['A', [3,2]]) sage: print(t.ascii_art()) O---O---O---X---O---O -3 -2 -1 0 1 2 sage: t = CartanType(['A', [3,7]]) sage: print(t.ascii_art()) O---O---O---X---O---O---O---O---O---O---O -3 -2 -1 0 1 2 3 4 5 6 7 sage: t = CartanType(['A', [0,7]]) sage: print(t.ascii_art()) X---O---O---O---O---O---O---O 0 1 2 3 4 5 6 7 sage: t = CartanType(['A', [0,0]]) sage: print(t.ascii_art()) X 0 sage: t = CartanType(['A', [5,0]]) sage: print(t.ascii_art()) O---O---O---O---O---X -5 -4 -3 -2 -1 0 """ if node is None: node = lambda i: 'O' ret = "---".join(node(label(i)) for i in range(1,self.m+1)) if self.m == 0: if self.n == 0: ret = "X" else: ret += "X---" else: if self.n == 0: ret += "---X" else: ret += "---X---" ret += "---".join(node(label(i)) for i in range(1,self.n+1)) + "\n" ret += "".join("{!s:4}".format(label(-i)) for i in reversed(range(1,self.m+1))) ret += "{!s:4}".format(label(0)) ret += "".join("{!s:4}".format(label(i)) for i in range(1,self.n+1)) return ret
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_super_A.py
0.877529
0.53443
type_super_A.py
pypi
from .cartan_type import CartanType_standard_untwisted_affine, CartanType_simply_laced class CartanType(CartanType_standard_untwisted_affine, CartanType_simply_laced): def __init__(self, n): """ EXAMPLES:: sage: ct = CartanType(['E',6,1]) sage: ct ['E', 6, 1] sage: ct._repr_(compact = True) 'E6~' sage: ct.is_irreducible() True sage: ct.is_finite() False sage: ct.is_affine() True sage: ct.is_untwisted_affine() True sage: ct.is_crystallographic() True sage: ct.is_simply_laced() True sage: ct.classical() ['E', 6] sage: ct.dual() ['E', 6, 1] TESTS:: sage: TestSuite(ct).run() """ if n < 6 or n > 8: raise ValueError("Invalid Cartan Type for Type E") CartanType_standard_untwisted_affine.__init__(self, "E", n) def _latex_(self): """ Return a latex representation of ``self``. EXAMPLES:: sage: latex(CartanType(['E',7,1])) E_7^{(1)} """ return "E_%s^{(1)}" % self.n def dynkin_diagram(self): """ Returns the extended Dynkin diagram for affine type E. EXAMPLES:: sage: e = CartanType(['E', 6, 1]).dynkin_diagram() sage: e O 0 | | O 2 | | O---O---O---O---O 1 3 4 5 6 E6~ sage: e.edges(sort=True) [(0, 2, 1), (1, 3, 1), (2, 0, 1), (2, 4, 1), (3, 1, 1), (3, 4, 1), (4, 2, 1), (4, 3, 1), (4, 5, 1), (5, 4, 1), (5, 6, 1), (6, 5, 1)] sage: e = CartanType(['E', 7, 1]).dynkin_diagram() sage: e O 2 | | O---O---O---O---O---O---O 0 1 3 4 5 6 7 E7~ sage: e.edges(sort=True) [(0, 1, 1), (1, 0, 1), (1, 3, 1), (2, 4, 1), (3, 1, 1), (3, 4, 1), (4, 2, 1), (4, 3, 1), (4, 5, 1), (5, 4, 1), (5, 6, 1), (6, 5, 1), (6, 7, 1), (7, 6, 1)] sage: e = CartanType(['E', 8, 1]).dynkin_diagram() sage: e O 2 | | O---O---O---O---O---O---O---O 1 3 4 5 6 7 8 0 E8~ sage: e.edges(sort=True) [(0, 8, 1), (1, 3, 1), (2, 4, 1), (3, 1, 1), (3, 4, 1), (4, 2, 1), (4, 3, 1), (4, 5, 1), (5, 4, 1), (5, 6, 1), (6, 5, 1), (6, 7, 1), (7, 6, 1), (7, 8, 1), (8, 0, 1), (8, 7, 1)] """ from .dynkin_diagram import DynkinDiagram_class n = self.n g = DynkinDiagram_class(self) g.add_edge(1,3) g.add_edge(2,4) for i in range(3,n): g.add_edge(i, i+1) if n == 6: g.add_edge(0, 2) elif n == 7: g.add_edge(0, 1) elif n == 8: g.add_edge(0, 8) else: raise ValueError("Invalid Cartan Type for Type E affine") return g def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['E',7,1])._latex_dynkin_diagram()) \draw (0 cm,0) -- (12 cm,0); \draw (6 cm, 0 cm) -- +(0,2 cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; \draw[fill=white] (8 cm, 0 cm) circle (.25cm) node[below=4pt]{$5$}; \draw[fill=white] (10 cm, 0 cm) circle (.25cm) node[below=4pt]{$6$}; \draw[fill=white] (12 cm, 0 cm) circle (.25cm) node[below=4pt]{$7$}; \draw[fill=white] (6 cm, 2 cm) circle (.25cm) node[right=3pt]{$2$}; <BLANKLINE> """ n = self.n if node is None: node = self._latex_draw_node if n == 7: ret = "\\draw (0 cm,0) -- (%s cm,0);\n"%((n-1)*node_dist) ret += "\\draw (%s cm, 0 cm) -- +(0,%s cm);\n"%(3*node_dist, node_dist) ret += node(0, 0, label(0)) ret += node(node_dist, 0, label(1)) for i in range(2, n): ret += node(i*node_dist, 0, label(i+1)) ret += node(3*node_dist, node_dist, label(2), "right=3pt") return ret ret = "\\draw (0 cm,0) -- (%s cm,0);\n"%((n-2)*node_dist) ret += "\\draw (%s cm, 0 cm) -- +(0,%s cm);\n"%(2*node_dist, node_dist) if n == 6: ret += "\\draw (%s cm, %s cm) -- +(0,%s cm);\n"%(2*node_dist, node_dist, node_dist) ret += node(2*node_dist, 2*node_dist, label(0), "right=3pt") else: # n == 8 ret += "\\draw (%s cm,0) -- +(%s cm,0);\n"%((n-2)*node_dist, node_dist) ret += node((n-1)*node_dist, 0, label(0)) ret += node(0, 0, label(1)) for i in range(1, n-1): ret += node(i*node_dist, 0, label(i+2)) ret += node(2*node_dist, node_dist, label(2), "right=3pt") return ret def ascii_art(self, label=lambda x: x, node=None): """ Return an ascii art representation of the extended Dynkin diagram. EXAMPLES:: sage: print(CartanType(['E',6,1]).ascii_art(label = lambda x: x+2)) O 2 | | O 4 | | O---O---O---O---O 3 5 6 7 8 sage: print(CartanType(['E',7,1]).ascii_art(label = lambda x: x+2)) O 4 | | O---O---O---O---O---O---O 2 3 5 6 7 8 9 sage: print(CartanType(['E',8,1]).ascii_art(label = lambda x: x-3)) O -1 | | O---O---O---O---O---O---O---O -2 0 1 2 3 4 5 -3 """ n = self.n if node is None: node = self._ascii_art_node if n == 6: ret = " {} {}\n |\n |\n".format(node(label(0)), label(0)) return ret + self.classical().ascii_art(label, node) elif n == 7: ret = " {} {}\n |\n |\n".format(node(label(2)), label(2)) labels = [label(i) for i in [0,1,3,4,5,6,7]] nodes = [node(i) for i in labels] return ret + '---'.join(n for n in nodes) + '\n' + "".join("{!s:4}".format(i) for i in labels) elif n == 8: ret = " {} {}\n |\n |\n".format(node(label(2)), label(2)) labels = [label(i) for i in [1,3,4,5,6,7,8,0]] nodes = [node(i) for i in labels] return ret + '---'.join(n for n in nodes) + '\n' + "".join("{!s:4}".format(i) for i in labels)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_E_affine.py
0.759671
0.434881
type_E_affine.py
pypi
from sage.misc.cachefunc import cached_method, cached_in_parent_method from sage.rings.integer_ring import ZZ from sage.combinat.free_module import CombinatorialFreeModule from .root_lattice_realizations import RootLatticeRealizations import functools class RootSpace(CombinatorialFreeModule): r""" The root space of a root system over a given base ring INPUT: - ``root_system`` - a root system - ``base_ring``: a ring `R` The *root space* (or lattice if ``base_ring`` is `\ZZ`) of a root system is the formal free module `\bigoplus_i R \alpha_i` generated by the simple roots `(\alpha_i)_{i\in I}` of the root system. This class is also used for coroot spaces (or lattices). .. SEEALSO:: - :meth:`RootSystem` - :meth:`RootSystem.root_lattice` and :meth:`RootSystem.root_space` - :meth:`~sage.combinat.root_system.root_lattice_realizations.RootLatticeRealizations` Todo: standardize the variable used for the root space in the examples (P?) TESTS:: sage: for ct in CartanType.samples(crystallographic=True)+[CartanType(["A",2],["C",5,1])]: ....: TestSuite(ct.root_system().root_lattice()).run() ....: TestSuite(ct.root_system().root_space()).run() sage: r = RootSystem(['A',4]).root_lattice() sage: r.simple_root(1) alpha[1] sage: latex(r.simple_root(1)) \alpha_{1} """ def __init__(self, root_system, base_ring): """ EXAMPLES:: sage: P = RootSystem(['A',4]).root_space() sage: s = P.simple_reflections() """ from sage.categories.morphism import SetMorphism from sage.categories.homset import Hom from sage.categories.sets_with_partial_maps import SetsWithPartialMaps self.root_system = root_system CombinatorialFreeModule.__init__(self, base_ring, root_system.index_set(), prefix = "alphacheck" if root_system.dual_side else "alpha", latex_prefix = "\\alpha^\\vee" if root_system.dual_side else "\\alpha", category = RootLatticeRealizations(base_ring)) if base_ring is not ZZ: # Register the partial conversion back from ``self`` to the root lattice # See :meth:`_to_root_lattice` for tests root_lattice = self.root_system.root_lattice() SetMorphism(Hom(self, root_lattice, SetsWithPartialMaps()), self._to_root_lattice ).register_as_conversion() def _repr_(self): """ EXAMPLES:: sage: RootSystem(['A',4]).root_lattice() # indirect doctest Root lattice of the Root system of type ['A', 4] sage: RootSystem(['B',4]).root_space() Root space over the Rational Field of the Root system of type ['B', 4] sage: RootSystem(['A',4]).coroot_lattice() Coroot lattice of the Root system of type ['A', 4] sage: RootSystem(['B',4]).coroot_space() Coroot space over the Rational Field of the Root system of type ['B', 4] """ return self._name_string() def _name_string(self, capitalize=True, base_ring=True, type=True): """ EXAMPLES:: sage: RootSystem(['A',4]).root_space()._name_string() "Root space over the Rational Field of the Root system of type ['A', 4]" """ return self._name_string_helper("root", capitalize=capitalize, base_ring=base_ring, type=type) simple_root = CombinatorialFreeModule.monomial @cached_method def to_coroot_space_morphism(self): """ Returns the ``nu`` map to the coroot space over the same base ring, using the symmetrizer of the Cartan matrix It does not map the root lattice to the coroot lattice, but has the property that any root is mapped to some scalar multiple of its associated coroot. EXAMPLES:: sage: R = RootSystem(['A',3]).root_space() sage: alpha = R.simple_roots() sage: f = R.to_coroot_space_morphism() sage: f(alpha[1]) alphacheck[1] sage: f(alpha[1]+alpha[2]) alphacheck[1] + alphacheck[2] sage: R = RootSystem(['A',3]).root_lattice() sage: alpha = R.simple_roots() sage: f = R.to_coroot_space_morphism() sage: f(alpha[1]) alphacheck[1] sage: f(alpha[1]+alpha[2]) alphacheck[1] + alphacheck[2] sage: S = RootSystem(['G',2]).root_space() sage: alpha = S.simple_roots() sage: f = S.to_coroot_space_morphism() sage: f(alpha[1]) alphacheck[1] sage: f(alpha[1]+alpha[2]) alphacheck[1] + 3*alphacheck[2] """ R = self.base_ring() C = self.cartan_type().symmetrizer().map(R) return self.module_morphism(diagonal = C.__getitem__, codomain=self.coroot_space(R)) def _to_root_lattice(self, x): """ Try to convert ``x`` to the root lattice. INPUT: - ``x`` -- an element of ``self`` EXAMPLES:: sage: R = RootSystem(['A',3]) sage: root_space = R.root_space() sage: x = root_space.an_element(); x 2*alpha[1] + 2*alpha[2] + 3*alpha[3] sage: root_space._to_root_lattice(x) 2*alpha[1] + 2*alpha[2] + 3*alpha[3] sage: root_space._to_root_lattice(x).parent() Root lattice of the Root system of type ['A', 3] This will fail if ``x`` does not have integral coefficients:: sage: root_space._to_root_lattice(x/2) Traceback (most recent call last): ... ValueError: alpha[1] + alpha[2] + 3/2*alpha[3] does not have integral coefficients .. note:: For internal use only; instead use a conversion:: sage: R.root_lattice()(x) 2*alpha[1] + 2*alpha[2] + 3*alpha[3] sage: R.root_lattice()(x/2) Traceback (most recent call last): ... ValueError: alpha[1] + alpha[2] + 3/2*alpha[3] does not have integral coefficients .. TODO:: generalize diagonal module morphisms to implement this """ try: return self.root_system.root_lattice().sum_of_terms((i, ZZ(c)) for i, c in x) except TypeError: raise ValueError("%s does not have integral coefficients" % x) @cached_method def _to_classical_on_basis(self, i): r""" Implement the projection onto the corresponding classical root space or lattice, on the basis. EXAMPLES:: sage: L = RootSystem(["A",3,1]).root_space() sage: L._to_classical_on_basis(0) -alpha[1] - alpha[2] - alpha[3] sage: L._to_classical_on_basis(1) alpha[1] sage: L._to_classical_on_basis(2) alpha[2] """ if i == self.cartan_type().special_node(): return self._classical_alpha_0() else: return self.classical().simple_root(i) @cached_method def to_ambient_space_morphism(self): r""" The morphism from ``self`` to its associated ambient space. EXAMPLES:: sage: CartanType(['A',2]).root_system().root_lattice().to_ambient_space_morphism() Generic morphism: From: Root lattice of the Root system of type ['A', 2] To: Ambient space of the Root system of type ['A', 2] """ if self.root_system.dual_side: L = self.cartan_type().dual().root_system().ambient_space() basis = L.simple_coroots() else: L = self.cartan_type().root_system().ambient_space() basis = L.simple_roots() def basis_value(basis, i): return basis[i] return self.module_morphism(on_basis = functools.partial(basis_value, basis) , codomain=L) class RootSpaceElement(CombinatorialFreeModule.Element): def scalar(self, lambdacheck): """ The scalar product between the root lattice and the coroot lattice. EXAMPLES:: sage: L = RootSystem(['B',4]).root_lattice() sage: alpha = L.simple_roots() sage: alphacheck = L.simple_coroots() sage: alpha[1].scalar(alphacheck[1]) 2 sage: alpha[1].scalar(alphacheck[2]) -1 The scalar products between the roots and coroots are given by the Cartan matrix:: sage: matrix([ [ alpha[i].scalar(alphacheck[j]) ....: for i in L.index_set() ] ....: for j in L.index_set() ]) [ 2 -1 0 0] [-1 2 -1 0] [ 0 -1 2 -1] [ 0 0 -2 2] sage: L.cartan_type().cartan_matrix() [ 2 -1 0 0] [-1 2 -1 0] [ 0 -1 2 -1] [ 0 0 -2 2] """ # Find some better test if not (lambdacheck in self.parent().coroot_lattice() or lambdacheck in self.parent().coroot_space()): raise TypeError("%s is not in a coroot lattice/space"%(lambdacheck)) zero = self.parent().base_ring().zero() cartan_matrix = self.parent().dynkin_diagram() return sum( (sum( (lambdacheck[i]*s for i,s in cartan_matrix.column(j)), zero) * c for j,c in self), zero) def is_positive_root(self): """ Checks whether an element in the root space lies in the nonnegative cone spanned by the simple roots. EXAMPLES:: sage: R=RootSystem(['A',3,1]).root_space() sage: B=R.basis() sage: w=B[0]+B[3] sage: w.is_positive_root() True sage: w=B[1]-B[2] sage: w.is_positive_root() False """ return all( c>= 0 for c in self.coefficients() ) @cached_in_parent_method def associated_coroot(self): r""" Returns the coroot associated to this root OUTPUT: An element of the coroot space over the same base ring; in particular the result is in the coroot lattice whenever ``self`` is in the root lattice. EXAMPLES:: sage: L = RootSystem(["B", 3]).root_space() sage: alpha = L.simple_roots() sage: alpha[1].associated_coroot() alphacheck[1] sage: alpha[1].associated_coroot().parent() Coroot space over the Rational Field of the Root system of type ['B', 3] sage: L.highest_root() alpha[1] + 2*alpha[2] + 2*alpha[3] sage: L.highest_root().associated_coroot() alphacheck[1] + 2*alphacheck[2] + alphacheck[3] sage: alpha = RootSystem(["B", 3]).root_lattice().simple_roots() sage: alpha[1].associated_coroot() alphacheck[1] sage: alpha[1].associated_coroot().parent() Coroot lattice of the Root system of type ['B', 3] """ #assert(self in self.parent().roots() is not False) scaled_coroot = self.parent().to_coroot_space_morphism()(self) s = self.scalar(scaled_coroot) return scaled_coroot.map_coefficients(lambda c: (2*c) // s) def quantum_root(self): r""" Returns True if ``self`` is a quantum root and False otherwise. INPUT: - ``self`` -- an element of the nonnegative integer span of simple roots. A root `\alpha` is a quantum root if `\ell(s_\alpha) = \langle 2 \rho, \alpha^\vee \rangle - 1` where `\ell` is the length function, `s_\alpha` is the reflection across the hyperplane orthogonal to `\alpha`, and `2\rho` is the sum of positive roots. .. warning:: This implementation only handles finite Cartan types and assumes that ``self`` is a root. .. TODO:: Rename to is_quantum_root EXAMPLES:: sage: Q = RootSystem(['C',2]).root_lattice() sage: positive_roots = Q.positive_roots() sage: for x in sorted(positive_roots): ....: print("{} {}".format(x, x.quantum_root())) alpha[1] True alpha[1] + alpha[2] False 2*alpha[1] + alpha[2] True alpha[2] True """ return len(self.associated_reflection()) == -1 + (self.parent().nonparabolic_positive_root_sum(())).scalar(self.associated_coroot()) def max_coroot_le(self): r""" Returns the highest positive coroot whose associated root is less than or equal to ``self``. INPUT: - ``self`` -- an element of the nonnegative integer span of simple roots. Returns None for the zero element. Really ``self`` is an element of a coroot lattice and this method returns the highest root whose associated coroot is <= ``self``. .. warning:: This implementation only handles finite Cartan types EXAMPLES:: sage: root_lattice = RootSystem(['C',2]).root_lattice() sage: root_lattice.from_vector(vector([1,1])).max_coroot_le() alphacheck[1] + 2*alphacheck[2] sage: root_lattice.from_vector(vector([2,1])).max_coroot_le() alphacheck[1] + 2*alphacheck[2] sage: root_lattice = RootSystem(['B',2]).root_lattice() sage: root_lattice.from_vector(vector([1,1])).max_coroot_le() 2*alphacheck[1] + alphacheck[2] sage: root_lattice.from_vector(vector([1,2])).max_coroot_le() 2*alphacheck[1] + alphacheck[2] sage: root_lattice.zero().max_coroot_le() is None True sage: root_lattice.from_vector(vector([-1,0])).max_coroot_le() Traceback (most recent call last): ... ValueError: -alpha[1] is not in the positive cone of roots sage: root_lattice = RootSystem(['A',2,1]).root_lattice() sage: root_lattice.simple_root(1).max_coroot_le() Traceback (most recent call last): ... NotImplementedError: Only implemented for finite Cartan type """ if not self.parent().cartan_type().is_finite(): raise NotImplementedError("Only implemented for finite Cartan type") if not self.is_positive_root(): raise ValueError(f"{self} is not in the positive cone of roots") coroots = self.parent().coroot_lattice().positive_roots_by_height(increasing=False) for beta in coroots: if beta.quantum_root(): gamma = self - beta.associated_coroot() if gamma.is_positive_root(): return beta return None def max_quantum_element(self): r""" Returns a reduced word for the longest element of the Weyl group whose shortest path in the quantum Bruhat graph to the identity, has sum of quantum coroots at most ``self``. INPUT: - ``self`` -- an element of the nonnegative integer span of simple roots. Really ``self`` is an element of a coroot lattice. .. warning:: This implementation only handles finite Cartan types EXAMPLES:: sage: Qvee = RootSystem(['C',2]).coroot_lattice() sage: Qvee.from_vector(vector([1,2])).max_quantum_element() [2, 1, 2, 1] sage: Qvee.from_vector(vector([1,1])).max_quantum_element() [1, 2, 1] sage: Qvee.from_vector(vector([0,2])).max_quantum_element() [2] """ Qvee = self.parent() word = [] while self != Qvee.zero(): beta = self.max_coroot_le() word += [x for x in beta.associated_reflection()] self = self - beta.associated_coroot() W = self.parent().weyl_group() return (W.demazure_product(word)).reduced_word() def to_ambient(self): r""" Map ``self`` to the ambient space. EXAMPLES:: sage: alpha = CartanType(['B',2]).root_system().root_lattice().an_element(); alpha 2*alpha[1] + 2*alpha[2] sage: alpha.to_ambient() (2, 0) sage: alphavee = CartanType(['B',2]).root_system().coroot_lattice().an_element(); alphavee 2*alphacheck[1] + 2*alphacheck[2] sage: alphavee.to_ambient() (2, 2) """ return self.parent().to_ambient_space_morphism()(self) RootSpace.Element = RootSpaceElement
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/root_space.py
0.891955
0.537709
root_space.py
pypi
from .cartan_type import CartanType_standard_untwisted_affine class CartanType(CartanType_standard_untwisted_affine): def __init__(self): """ EXAMPLES:: sage: ct = CartanType(['F',4,1]) sage: ct ['F', 4, 1] sage: ct._repr_(compact = True) 'F4~' sage: ct.is_irreducible() True sage: ct.is_finite() False sage: ct.is_affine() True sage: ct.is_untwisted_affine() True sage: ct.is_crystallographic() True sage: ct.is_simply_laced() False sage: ct.classical() ['F', 4] sage: ct.dual() ['F', 4, 1]^* sage: ct.dual().is_untwisted_affine() False TESTS:: sage: TestSuite(ct).run() """ CartanType_standard_untwisted_affine.__init__(self, "F", 4) def dynkin_diagram(self): """ Returns the extended Dynkin diagram for affine type F. EXAMPLES:: sage: f = CartanType(['F', 4, 1]).dynkin_diagram() sage: f O---O---O=>=O---O 0 1 2 3 4 F4~ sage: f.edges(sort=True) [(0, 1, 1), (1, 0, 1), (1, 2, 1), (2, 1, 1), (2, 3, 2), (3, 2, 1), (3, 4, 1), (4, 3, 1)] """ from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) for i in range(1, 4): g.add_edge(i, i+1) g.set_edge_label(2,3,2) g.add_edge(0, 1) return g def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['F',4,1])._latex_dynkin_diagram()) \draw (0 cm,0) -- (2 cm,0); { \pgftransformxshift{2 cm} \draw (0 cm,0) -- (2 cm,0); \draw (2 cm, 0.1 cm) -- +(2 cm,0); \draw (2 cm, -0.1 cm) -- +(2 cm,0); \draw (4.0 cm,0) -- +(2 cm,0); \draw[shift={(3.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; } \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; <BLANKLINE> """ if node is None: node = self._latex_draw_node ret = "\\draw (0 cm,0) -- (%s cm,0);\n"%node_dist ret += "{\n\\pgftransformxshift{%s cm}\n"%node_dist ret += self.classical()._latex_dynkin_diagram(label, node, node_dist, dual) ret += "}\n" + node(0, 0, label(0)) return ret def ascii_art(self, label=lambda i: i, node=None): """ Returns a ascii art representation of the extended Dynkin diagram EXAMPLES:: sage: print(CartanType(['F',4,1]).ascii_art(label = lambda x: x+2)) O---O---O=>=O---O 2 3 4 5 6 """ if node is None: node = self._ascii_art_node ret = "{}---{}---{}=>={}---{}\n".format(node(label(0)), node(label(1)), node(label(2)), node(label(3)), node(label(4))) ret += ("{!s:4}"*5 + "\n").format(label(0), label(1), label(2), label(3), label(4)) return ret def _default_folded_cartan_type(self): """ Return the default folded Cartan type. EXAMPLES:: sage: CartanType(['F', 4, 1])._default_folded_cartan_type() ['F', 4, 1] as a folding of ['E', 6, 1] """ from sage.combinat.root_system.type_folded import CartanTypeFolded return CartanTypeFolded(self, ['E', 6, 1], [[0], [2], [4], [3, 5], [1, 6]])
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_F_affine.py
0.814201
0.420064
type_F_affine.py
pypi
from sage.misc.cachefunc import cached_method from sage.combinat.free_module import CombinatorialFreeModule from .weight_lattice_realizations import WeightLatticeRealizations class AmbientSpace(CombinatorialFreeModule): r""" Ambient space for affine types. This is constructed from the data in the corresponding classical ambient space. Namely, this space is obtained by adding two elements `\delta` and `\delta^\vee` to the basis of the classical ambient space, and by endowing it with the canonical scalar product. The coefficient of an element in `\delta^\vee`, thus its scalar product with `\delta^\vee` gives its level, and dually for the colevel. The canonical projection onto the classical ambient space (by killing `\delta` and `\delta^\vee`) maps the simple roots (except `\alpha_0`) onto the corresponding classical simple roots, and similarly for the coroots, fundamental weights, ... Altogether, this uniquely determines the embedding of the root, coroot, weight, and coweight lattices. See :meth:`simple_root` and :meth:`fundamental_weight` for the details. .. WARNING:: In type `BC`, the null root is in fact:: sage: R = RootSystem(["BC",3,2]).ambient_space() sage: R.null_root() 2*e['delta'] .. WARNING:: In the literature one often considers a larger affine ambient space obtained from the classical ambient space by adding four dimensions, namely for the fundamental weight `\Lambda_0` the fundamental coweight `\Lambda^\vee_0`, the null root `\delta`, and the null coroot `c` (aka central element). In this larger ambient space, the scalar product is degenerate: `\langle \delta,\delta\rangle=0` and similarly for the null coroot. In the current implementation, `\Lambda_0` and the null coroot are identified: sage: L = RootSystem(["A",3,1]).ambient_space() sage: Lambda = L.fundamental_weights() sage: Lambda[0] e['deltacheck'] sage: L.null_coroot() e['deltacheck'] Therefore the scalar product of the null coroot with itself differs from the larger ambient space:: sage: L.null_coroot().scalar(L.null_coroot()) 1 In general, scalar products between two elements that do not live on "opposite sides" won't necessarily match. EXAMPLES:: sage: R = RootSystem(["A",3,1]) sage: e = R.ambient_space(); e Ambient space of the Root system of type ['A', 3, 1] sage: TestSuite(e).run() Systematic checks on all affine types:: sage: for ct in CartanType.samples(affine=True, crystallographic=True): ....: if ct.classical().root_system().ambient_space() is not None: ....: print(ct) ....: L = ct.root_system().ambient_space() ....: assert L ....: TestSuite(L).run() ['A', 1, 1] ['A', 5, 1] ['B', 1, 1] ['B', 5, 1] ['C', 1, 1] ['C', 5, 1] ['D', 3, 1] ['D', 5, 1] ['E', 6, 1] ['E', 7, 1] ['E', 8, 1] ['F', 4, 1] ['G', 2, 1] ['BC', 1, 2] ['BC', 5, 2] ['B', 5, 1]^* ['C', 4, 1]^* ['F', 4, 1]^* ['G', 2, 1]^* ['BC', 1, 2]^* ['BC', 5, 2]^* TESTS:: sage: Lambda[1] e[0] + e['deltacheck'] """ @classmethod def smallest_base_ring(cls, cartan_type): r""" Return the smallest base ring the ambient space can be defined on. This is the smallest base ring for the associated classical ambient space. .. SEEALSO:: :meth:`~sage.combinat.root_system.ambient_space.AmbientSpace.smallest_base_ring` EXAMPLES:: sage: cartan_type = CartanType(["A",3,1]) sage: cartan_type.AmbientSpace.smallest_base_ring(cartan_type) Integer Ring sage: cartan_type = CartanType(["B",3,1]) sage: cartan_type.AmbientSpace.smallest_base_ring(cartan_type) Rational Field """ classical = cartan_type.classical() return cartan_type.classical().root_system().ambient_space().smallest_base_ring(classical) def __init__(self, root_system, base_ring): r""" EXAMPLES:: sage: R = RootSystem(["A",3,1]) sage: R.cartan_type().AmbientSpace <class 'sage.combinat.root_system.type_affine.AmbientSpace'> sage: e = R.ambient_space(); e Ambient space of the Root system of type ['A', 3, 1] sage: TestSuite(R.ambient_space()).run() sage: L = RootSystem(['A',3]).coroot_lattice() sage: e.has_coerce_map_from(L) True sage: e(L.simple_root(1)) e[0] - e[1] """ self.root_system = root_system classical = root_system.cartan_type().classical().root_system().ambient_space(base_ring) basis_keys = tuple(classical.basis().keys()) + ("delta", "deltacheck") def sortkey(x): return (1 if isinstance(x, str) else 0, x) CombinatorialFreeModule.__init__(self, base_ring, basis_keys, prefix = "e", latex_prefix = "e", sorting_key=sortkey, category = WeightLatticeRealizations(base_ring)) self._weight_space = self.root_system.weight_space(base_ring=base_ring,extended=True) self.classical().module_morphism(self.monomial, codomain=self).register_as_coercion() # Duplicated from ambient_space.AmbientSpace coroot_lattice = self.root_system.coroot_lattice() coroot_lattice.module_morphism(self.simple_coroot, codomain=self).register_as_coercion() def _name_string(self, capitalize=True, base_ring=False, type=True): r""" Utility to implement _repr_ EXAMPLES:: sage: RootSystem(['A',4,1]).ambient_lattice() Ambient lattice of the Root system of type ['A', 4, 1] sage: RootSystem(['A',4,1]).ambient_space() Ambient space of the Root system of type ['A', 4, 1] sage: RootSystem(['A',4,1]).dual.ambient_lattice() Coambient lattice of the Root system of type ['A', 4, 1] sage: RootSystem(['A',4,1]).ambient_lattice()._repr_() "Ambient lattice of the Root system of type ['A', 4, 1]" sage: RootSystem(['A',4,1]).ambient_lattice()._name_string() "Ambient lattice of the Root system of type ['A', 4, 1]" """ return self._name_string_helper("ambient", capitalize=capitalize, base_ring=base_ring, type=type) _repr_ = _name_string @cached_method def _to_classical_on_basis(self, i): r""" Implement the projection onto the corresponding classical space or lattice, on the basis. INPUT: - ``i`` -- the index of an element of the basis of ``self``, namely 0, 1, 2, ..., "delta", or "deltacheck" EXAMPLES:: sage: L = RootSystem(["A",2,1]).ambient_space() sage: L._to_classical_on_basis("delta") (0, 0, 0) sage: L._to_classical_on_basis("deltacheck") (0, 0, 0) sage: L._to_classical_on_basis(0) (1, 0, 0) sage: L._to_classical_on_basis(1) (0, 1, 0) sage: L._to_classical_on_basis(2) (0, 0, 1) """ if i=="delta" or i=="deltacheck": return self.classical().zero() else: return self.classical().monomial(i) def is_extended(self): r""" Return whether this is a realization of the extended weight lattice: yes! .. SEEALSO:: - :class:`sage.combinat.root_system.weight_space.WeightSpace` - :meth:`sage.combinat.root_system.weight_lattice_realizations.WeightLatticeRealizations.ParentMethods.is_extended` EXAMPLES:: sage: RootSystem(['A',3,1]).ambient_space().is_extended() True """ return True @cached_method def fundamental_weight(self, i): r""" Return the fundamental weight `\Lambda_i` in this ambient space. It is constructed by taking the corresponding fundamental weight of the classical ambient space (or `0` for `\Lambda_0`) and raising it to the appropriate level by adding a suitable multiple of `\delta^\vee`. EXAMPLES:: sage: RootSystem(['A',3,1]).ambient_space().fundamental_weight(2) e[0] + e[1] + e['deltacheck'] sage: RootSystem(['A',3,1]).ambient_space().fundamental_weights() Finite family {0: e['deltacheck'], 1: e[0] + e['deltacheck'], 2: e[0] + e[1] + e['deltacheck'], 3: e[0] + e[1] + e[2] + e['deltacheck']} sage: RootSystem(['A',3]).ambient_space().fundamental_weights() Finite family {1: (1, 0, 0, 0), 2: (1, 1, 0, 0), 3: (1, 1, 1, 0)} sage: RootSystem(['A',3,1]).weight_lattice().fundamental_weights().map(attrcall("level")) Finite family {0: 1, 1: 1, 2: 1, 3: 1} sage: RootSystem(['B',3,1]).ambient_space().fundamental_weights() Finite family {0: e['deltacheck'], 1: e[0] + e['deltacheck'], 2: e[0] + e[1] + 2*e['deltacheck'], 3: 1/2*e[0] + 1/2*e[1] + 1/2*e[2] + e['deltacheck']} sage: RootSystem(['B',3]).ambient_space().fundamental_weights() Finite family {1: (1, 0, 0), 2: (1, 1, 0), 3: (1/2, 1/2, 1/2)} sage: RootSystem(['B',3,1]).weight_lattice().fundamental_weights().map(attrcall("level")) Finite family {0: 1, 1: 1, 2: 2, 3: 1} In type `BC` dual, the coefficient of '\delta^\vee' is the level divided by `2` to take into account that the null coroot is `2\delta^\vee`:: sage: R = CartanType(['BC',3,2]).dual().root_system() sage: R.ambient_space().fundamental_weights() Finite family {0: e['deltacheck'], 1: e[0] + e['deltacheck'], 2: e[0] + e[1] + e['deltacheck'], 3: 1/2*e[0] + 1/2*e[1] + 1/2*e[2] + 1/2*e['deltacheck']} sage: R.weight_lattice().fundamental_weights().map(attrcall("level")) Finite family {0: 2, 1: 2, 2: 2, 3: 1} sage: R.ambient_space().null_coroot() 2*e['deltacheck'] By a slight naming abuse this function also accepts "delta" as input so that it can be used to implement the embedding from the extended weight lattice:: sage: RootSystem(['A',3,1]).ambient_space().fundamental_weight("delta") e['delta'] """ if i == "delta": return self.monomial("delta") deltacheck = self.monomial("deltacheck") result = deltacheck * self._weight_space.fundamental_weight(i).level() / deltacheck.level() if i != self.cartan_type().special_node(): result += self(self.classical().fundamental_weight(i)) return result @cached_method def simple_root(self, i): r""" Return the `i`-th simple root of this affine ambient space. EXAMPLES: It is built straightforwardly from the corresponding simple root `\alpha_i` in the classical ambient space:: sage: RootSystem(["A",3,1]).ambient_space().simple_root(1) e[0] - e[1] For the special node (typically `i=0`), `\alpha_0` is built from the other simple roots using the column annihilator of the Cartan matrix and adding `\delta`, where `\delta` is the null root:: sage: RootSystem(["A",3]).ambient_space().simple_roots() Finite family {1: (1, -1, 0, 0), 2: (0, 1, -1, 0), 3: (0, 0, 1, -1)} sage: RootSystem(["A",3,1]).ambient_space().simple_roots() Finite family {0: -e[0] + e[3] + e['delta'], 1: e[0] - e[1], 2: e[1] - e[2], 3: e[2] - e[3]} Here is a twisted affine example:: sage: RootSystem(CartanType(["B",3,1]).dual()).ambient_space().simple_roots() Finite family {0: -e[0] - e[1] + e['delta'], 1: e[0] - e[1], 2: e[1] - e[2], 3: 2*e[2]} In fact `\delta` is really `1/a_0` times the null root (see the discussion in :class:`~sage.combinat.root_system.weight_space.WeightSpace`) but this only makes a difference in type `BC`:: sage: L = RootSystem(CartanType(["BC",3,2])).ambient_space() sage: L.simple_roots() Finite family {0: -e[0] + e['delta'], 1: e[0] - e[1], 2: e[1] - e[2], 3: 2*e[2]} sage: L.null_root() 2*e['delta'] .. NOTE:: An alternative would have been to use the default implementation of the simple roots as linear combinations of the fundamental weights. However, as in type `A_n` it is preferable to take a slight variant to avoid rational coefficient (the usual `GL_n` vs `SL_n` issue). .. SEEALSO:: - :meth:`~sage.combinat.root_system.weight_space.WeightSpace.simple_root` - :class:`~sage.combinat.root_system.weight_space.WeightSpace` - :meth:`CartanType.col_annihilator` - :meth:`null_root` """ cartan_type = self.cartan_type() special_node = cartan_type.special_node() if i == special_node: return self(self._classical_alpha_0()) + self.monomial("delta") else: return self(self.classical().simple_root(i)) @cached_method def simple_coroot(self, i): r""" Return the `i`-th simple coroot `\alpha_i^\vee` of this affine ambient space. EXAMPLES:: sage: RootSystem(["A",3,1]).ambient_space().simple_coroot(1) e[0] - e[1] It is built as the coroot associated to the simple root `\alpha_i`:: sage: RootSystem(["B",3,1]).ambient_space().simple_roots() Finite family {0: -e[0] - e[1] + e['delta'], 1: e[0] - e[1], 2: e[1] - e[2], 3: e[2]} sage: RootSystem(["B",3,1]).ambient_space().simple_coroots() Finite family {0: -e[0] - e[1] + e['deltacheck'], 1: e[0] - e[1], 2: e[1] - e[2], 3: 2*e[2]} .. TODO:: Factor out this code with the classical ambient space. """ return self.simple_root(i).associated_coroot() def coroot_lattice(self): """ EXAMPLES:: sage: RootSystem(["A",3,1]).ambient_lattice().coroot_lattice() Ambient lattice of the Root system of type ['A', 3, 1] .. TODO:: Factor out this code with the classical ambient space. """ return self def _plot_projection(self, x): r""" Implements the default projection to be used for plots For affine ambient spaces, the default implementation is to project onto the classical coordinates according to the default projection for the classical ambient space, while keeping an extra coordinate for the coefficient of `\delta^\vee` to keep the level information. .. SEEALSO:: :meth:`sage.combinat.root_system.root_lattice_realizations.RootLatticeRealizations._plot_projection` EXAMPLES:: sage: L = RootSystem(["B",2,1]).ambient_space() sage: e = L.basis() sage: L._plot_projection(e[0]) (1, 0, 0) sage: L._plot_projection(e[1]) (0, 1, 0) sage: L._plot_projection(e["delta"]) (0, 0, 0) sage: L._plot_projection(e["deltacheck"]) (0, 0, 1) sage: L = RootSystem(["A",2,1]).ambient_space() sage: e = L.basis() sage: L._plot_projection(e[0]) (1/2, 989/1142, 0) sage: L._plot_projection(e[1]) (-1, 0, 0) sage: L._plot_projection(e["delta"]) (0, 0, 0) sage: L._plot_projection(e["deltacheck"]) (0, 0, 1) """ from sage.modules.free_module_element import vector classical = self.classical() # Any better way to concatenate two vectors? return vector(list(vector(classical._plot_projection(classical(x)))) + [x["deltacheck"]]) class Element(CombinatorialFreeModule.Element): def inner_product(self, other): r""" Implement the canonical inner product of ``self`` with ``other``. EXAMPLES:: sage: e = RootSystem(['B',3,1]).ambient_space() sage: B = e.basis() sage: matrix([[x.inner_product(y) for x in B] for y in B]) [1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0] [0 0 0 1 0] [0 0 0 0 1] sage: x = e.an_element(); x 2*e[0] + 2*e[1] + 3*e[2] sage: x.inner_product(x) 17 :meth:`scalar` is an alias for this method:: sage: x.scalar(x) 17 .. TODO:: Lift to CombinatorialFreeModule.Element as canonical_inner_product """ if self.parent() is not other.parent(): raise TypeError("the parents must be the same") return self.base_ring().sum( self[i] * c for (i,c) in other ) scalar = inner_product def associated_coroot(self): r""" Return the coroot associated to ``self``. INPUT: - ``self`` -- a root EXAMPLES:: sage: alpha = RootSystem(['C',2,1]).ambient_space().simple_roots() sage: alpha Finite family {0: -2*e[0] + e['delta'], 1: e[0] - e[1], 2: 2*e[1]} sage: alpha[0].associated_coroot() -e[0] + e['deltacheck'] sage: alpha[1].associated_coroot() e[0] - e[1] sage: alpha[2].associated_coroot() e[1] """ # CHECKME: does it make any sense to not rescale the delta term? L = self.parent() c = self["delta"] self = self - L.term("delta", c) return (2*self) / self.inner_product(self) + L.term("deltacheck", c)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_affine.py
0.929672
0.745653
type_affine.py
pypi
from .cartan_type import CartanType_standard_untwisted_affine, CartanType_simply_laced class CartanType(CartanType_standard_untwisted_affine, CartanType_simply_laced): def __init__(self, n): """ EXAMPLES:: sage: ct = CartanType(['D',4,1]) sage: ct ['D', 4, 1] sage: ct._repr_(compact = True) 'D4~' sage: ct.is_irreducible() True sage: ct.is_finite() False sage: ct.is_affine() True sage: ct.is_untwisted_affine() True sage: ct.is_crystallographic() True sage: ct.is_simply_laced() True sage: ct.classical() ['D', 4] sage: ct.dual() ['D', 4, 1] TESTS:: sage: TestSuite(ct).run() """ assert n >= 3 CartanType_standard_untwisted_affine.__init__(self, "D", n) def dynkin_diagram(self): """ Returns the extended Dynkin diagram for affine type D. EXAMPLES:: sage: d = CartanType(['D', 6, 1]).dynkin_diagram() sage: d 0 O O 6 | | | | O---O---O---O---O 1 2 3 4 5 D6~ sage: d.edges(sort=True) [(0, 2, 1), (1, 2, 1), (2, 0, 1), (2, 1, 1), (2, 3, 1), (3, 2, 1), (3, 4, 1), (4, 3, 1), (4, 5, 1), (4, 6, 1), (5, 4, 1), (6, 4, 1)] sage: d = CartanType(['D', 4, 1]).dynkin_diagram() sage: d O 4 | | O---O---O 1 |2 3 | O 0 D4~ sage: d.edges(sort=True) [(0, 2, 1), (1, 2, 1), (2, 0, 1), (2, 1, 1), (2, 3, 1), (2, 4, 1), (3, 2, 1), (4, 2, 1)] sage: d = CartanType(['D', 3, 1]).dynkin_diagram() sage: d 0 O-------+ | | | | O---O---O 3 1 2 D3~ sage: d.edges(sort=True) [(0, 2, 1), (0, 3, 1), (1, 2, 1), (1, 3, 1), (2, 0, 1), (2, 1, 1), (3, 0, 1), (3, 1, 1)] """ from .dynkin_diagram import DynkinDiagram_class n = self.n if n == 3: from . import cartan_type res = cartan_type.CartanType(["A",3,1]).relabel({0:0, 1:3, 2:1, 3: 2}).dynkin_diagram() res._cartan_type = self return res g = DynkinDiagram_class(self) for i in range(1, n-1): g.add_edge(i, i+1) g.add_edge(n-2,n) g.add_edge(0,2) return g def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['D',4,1])._latex_dynkin_diagram()) \draw (0,0.7 cm) -- (2 cm,0); \draw (0,-0.7 cm) -- (2 cm,0); \draw (2 cm,0) -- (2 cm,0); \draw (2 cm,0) -- (4 cm,0.7 cm); \draw (2 cm,0) -- (4 cm,-0.7 cm); \draw[fill=white] (0 cm, 0.7 cm) circle (.25cm) node[left=3pt]{$0$}; \draw[fill=white] (0 cm, -0.7 cm) circle (.25cm) node[left=3pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0.7 cm) circle (.25cm) node[right=3pt]{$4$}; \draw[fill=white] (4 cm, -0.7 cm) circle (.25cm) node[right=3pt]{$3$}; <BLANKLINE> """ if node is None: node = self._latex_draw_node n = self.n if n == 3: from . import cartan_type relabel = {0:label(0), 1:label(3), 2:label(1), 3:label(2)} return cartan_type.CartanType(["A",3,1]).relabel(relabel)._latex_dynkin_diagram(node_dist=node_dist) rt_most = (n - 2) * node_dist center_point = rt_most - node_dist ret = "\\draw (0,0.7 cm) -- (%s cm,0);\n"%node_dist ret += "\\draw (0,-0.7 cm) -- (%s cm,0);\n"%node_dist ret += "\\draw (%s cm,0) -- (%s cm,0);\n"%(node_dist, center_point) ret += "\\draw (%s cm,0) -- (%s cm,0.7 cm);\n"%(center_point, rt_most) ret += "\\draw (%s cm,0) -- (%s cm,-0.7 cm);\n"%(center_point, rt_most) ret += node(0, 0.7, label(0), "left=3pt") ret += node(0, -0.7, label(1), "left=3pt") for i in range(1, self.n-2): ret += node(i*node_dist, 0, label(i+1)) ret += node(rt_most, 0.7, label(n), "right=3pt") ret += node(rt_most, -0.7, label(n-1), "right=3pt") return ret def ascii_art(self, label=lambda i: i, node=None): """ Return an ascii art representation of the extended Dynkin diagram. TESTS:: sage: print(CartanType(['D',6,1]).ascii_art(label = lambda x: x+2)) 2 O O 8 | | | | O---O---O---O---O 3 4 5 6 7 sage: print(CartanType(['D',4,1]).ascii_art(label = lambda x: x+2)) O 6 | | O---O---O 3 |4 5 | O 2 sage: print(CartanType(['D',3,1]).ascii_art(label = lambda x: x+2)) 2 O-------+ | | | | O---O---O 5 3 4 """ if node is None: node = self._ascii_art_node n = self.n if n == 3: from . import cartan_type return cartan_type.CartanType(["A",3,1]).relabel({0:0, 1:3, 2:1, 3: 2}).ascii_art(label, node) if n == 4: ret = " {} {}\n".format(node(label(4)), label(4)) + " |\n |\n" ret += "{}---{}---{}\n".format(node(label(1)), node(label(2)), node(label(3))) ret += "{!s:4}|{!s:3}{!s:4}\n".format(label(1), label(2), label(3)) ret += " |\n {} {}".format(node(label(0)), label(0)) return ret ret = "{!s:>3} {}".format(label(0), node(label(0))) ret += (4*(n-4)-1)*" "+"{} {}\n".format(node(label(n)), label(n)) ret += " |" + (4*(n-4)-1)*" " + "|\n" ret += " |" + (4*(n-4)-1)*" " + "|\n" ret += "---".join(node(label(i)) for i in range(1, n)) ret += '\n' + "".join("{!s:4}".format(label(i)) for i in range(1,n)) return ret
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_D_affine.py
0.808257
0.496887
type_D_affine.py
pypi
from .cartan_type import CartanType_standard_affine from sage.rings.integer_ring import ZZ class CartanType(CartanType_standard_affine): def __init__(self, n): """ EXAMPLES:: sage: ct = CartanType(['BC',4,2]) sage: ct ['BC', 4, 2] sage: ct._repr_(compact = True) 'BC4~' sage: ct.dynkin_diagram() O=<=O---O---O=<=O 0 1 2 3 4 BC4~ sage: ct.is_irreducible() True sage: ct.is_finite() False sage: ct.is_affine() True sage: ct.is_crystallographic() True sage: ct.is_simply_laced() False sage: ct.classical() ['C', 4] sage: dual = ct.dual() sage: dual.dynkin_diagram() O=>=O---O---O=>=O 0 1 2 3 4 BC4~* sage: dual.special_node() 0 sage: dual.classical().dynkin_diagram() O---O---O=>=O 1 2 3 4 B4 sage: CartanType(['BC',1,2]).dynkin_diagram() 4 O=<=O 0 1 BC1~ TESTS:: sage: TestSuite(ct).run() """ assert n in ZZ and n >= 1 CartanType_standard_affine.__init__(self, "BC", n, 2) def dynkin_diagram(self): """ Returns the extended Dynkin diagram for affine type BC. EXAMPLES:: sage: c = CartanType(['BC',3,2]).dynkin_diagram() sage: c O=<=O---O=<=O 0 1 2 3 BC3~ sage: c.edges(sort=True) [(0, 1, 1), (1, 0, 2), (1, 2, 1), (2, 1, 1), (2, 3, 1), (3, 2, 2)] sage: c = CartanType(["A", 6, 2]).dynkin_diagram() # should be the same as above; did fail at some point! sage: c O=<=O---O=<=O 0 1 2 3 BC3~ sage: c.edges(sort=True) [(0, 1, 1), (1, 0, 2), (1, 2, 1), (2, 1, 1), (2, 3, 1), (3, 2, 2)] sage: c = CartanType(['BC',2,2]).dynkin_diagram() sage: c O=<=O=<=O 0 1 2 BC2~ sage: c.edges(sort=True) [(0, 1, 1), (1, 0, 2), (1, 2, 1), (2, 1, 2)] sage: c = CartanType(['BC',1,2]).dynkin_diagram() sage: c 4 O=<=O 0 1 BC1~ sage: c.edges(sort=True) [(0, 1, 1), (1, 0, 4)] """ from .dynkin_diagram import DynkinDiagram_class n = self.n g = DynkinDiagram_class(self) if n == 1: g.add_edge(1,0,4) return g g.add_edge(1,0,2) for i in range(1, n-1): g.add_edge(i, i+1) g.add_edge(n,n-1,2) return g def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: latex(CartanType(['BC',4,2])) BC_{4}^{(2)} sage: CartanType.options.notation = 'Kac' sage: latex(CartanType(['BC',4,2])) A_{8}^{(2)} sage: latex(CartanType(['A',8,2])) A_{8}^{(2)} sage: CartanType.options._reset() """ if self.options.notation == "Kac": return "A_{%s}^{(2)}" % (2 * self.classical().rank()) else: return "BC_{%s}^{(2)}" % self.n def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['BC',4,2])._latex_dynkin_diagram()) \draw (0, 0.1 cm) -- +(2 cm,0); \draw (0, -0.1 cm) -- +(2 cm,0); \draw[shift={(0.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); { \pgftransformxshift{2 cm} \draw (0 cm,0) -- (4 cm,0); \draw (4 cm, 0.1 cm) -- +(2 cm,0); \draw (4 cm, -0.1 cm) -- +(2 cm,0); \draw[shift={(4.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; } \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; <BLANKLINE> sage: print(CartanType(['BC',4,2]).dual()._latex_dynkin_diagram()) \draw (0, 0.1 cm) -- +(2 cm,0); \draw (0, -0.1 cm) -- +(2 cm,0); \draw[shift={(1.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); { \pgftransformxshift{2 cm} \draw (0 cm,0) -- (4 cm,0); \draw (4 cm, 0.1 cm) -- +(2 cm,0); \draw (4 cm, -0.1 cm) -- +(2 cm,0); \draw[shift={(5.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; } \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; <BLANKLINE> """ if node is None: node = self._latex_draw_node if self.n == 1: ret = "\\draw (0, 0.05 cm) -- +(%s cm,0);\n"%node_dist ret += "\\draw (0, -0.05 cm) -- +(%s cm,0);\n"%node_dist ret += "\\draw (0, 0.15 cm) -- +(%s cm,0);\n"%node_dist ret += "\\draw (0, -0.15 cm) -- +(%s cm,0);\n"%node_dist if dual: ret += self._latex_draw_arrow_tip(0.5*node_dist+0.2, 0, 0) else: ret += self._latex_draw_arrow_tip(0.5*node_dist-0.2, 0, 180) ret += node(0, 0, label(0)) ret += node(node_dist, 0, label(1)) return ret ret = "\\draw (0, 0.1 cm) -- +(%s cm,0);\n"%node_dist ret += "\\draw (0, -0.1 cm) -- +(%s cm,0);\n"%node_dist if dual: ret += self._latex_draw_arrow_tip(0.5*node_dist+0.2, 0, 0) else: ret += self._latex_draw_arrow_tip(0.5*node_dist-0.2, 0, 180) ret += "{\n\\pgftransformxshift{%s cm}\n"%node_dist ret += self.classical()._latex_dynkin_diagram(label, node, node_dist, dual=dual) ret += "}\n" + node(0, 0, label(0)) return ret def ascii_art(self, label=lambda i: i, node=None): """ Return a ascii art representation of the extended Dynkin diagram. EXAMPLES:: sage: print(CartanType(['BC',2,2]).ascii_art()) O=<=O=<=O 0 1 2 sage: print(CartanType(['BC',3,2]).ascii_art()) O=<=O---O=<=O 0 1 2 3 sage: print(CartanType(['BC',5,2]).ascii_art(label = lambda x: x+2)) O=<=O---O---O---O=<=O 2 3 4 5 6 7 sage: print(CartanType(['BC',1,2]).ascii_art(label = lambda x: x+2)) 4 O=<=O 2 3 """ if node is None: node = self._ascii_art_node n = self.n if n == 1: return " 4\n{}=<={}\n{!s:4}{!s:4}".format(node(label(0)), node(label(1)), label(0), label(1)) ret = node(label(0)) + "=<=" + "---".join(node(label(i)) for i in range(1,n)) ret += "=<=" + node(label(n)) + '\n' ret += "".join("{!s:4}".format(label(i)) for i in range(n+1)) return ret def classical(self): """ Returns the classical Cartan type associated with self sage: CartanType(["BC", 3, 2]).classical() ['C', 3] """ from . import cartan_type return cartan_type.CartanType(["C", self.n]) def basic_untwisted(self): r""" Return the basic untwisted Cartan type associated with this affine Cartan type. Given an affine type `X_n^{(r)}`, the basic untwisted type is `X_n`. In other words, it is the classical Cartan type that is twisted to obtain ``self``. EXAMPLES:: sage: CartanType(['A', 2, 2]).basic_untwisted() ['A', 2] sage: CartanType(['A', 4, 2]).basic_untwisted() ['A', 4] sage: CartanType(['BC', 4, 2]).basic_untwisted() ['A', 8] """ from . import cartan_type return cartan_type.CartanType(["A", 2*self.n]) def _default_folded_cartan_type(self): """ Return the default folded Cartan type. EXAMPLES:: sage: CartanType(['BC', 3, 2])._default_folded_cartan_type() ['BC', 3, 2] as a folding of ['A', 5, 1] """ from sage.combinat.root_system.type_folded import CartanTypeFolded n = self.n return CartanTypeFolded(self, ['A', 2*n - 1, 1], [[0]] + [[i, 2*n-i] for i in range(1, n)] + [[n]])
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_BC_affine.py
0.796015
0.440529
type_BC_affine.py
pypi
from .cartan_type import CartanType_standard_untwisted_affine class CartanType(CartanType_standard_untwisted_affine): def __init__(self): """ EXAMPLES:: sage: ct = CartanType(['G',2,1]) sage: ct ['G', 2, 1] sage: ct._repr_(compact = True) 'G2~' sage: ct.is_irreducible() True sage: ct.is_finite() False sage: ct.is_affine() True sage: ct.is_untwisted_affine() True sage: ct.is_crystallographic() True sage: ct.is_simply_laced() False sage: ct.classical() ['G', 2] sage: ct.dual() ['G', 2, 1]^* sage: ct.dual().is_untwisted_affine() False TESTS:: sage: TestSuite(ct).run() """ CartanType_standard_untwisted_affine.__init__(self, "G",2) def dynkin_diagram(self): """ Returns the extended Dynkin diagram for type G. EXAMPLES:: sage: g = CartanType(['G',2,1]).dynkin_diagram() sage: g 3 O=<=O---O 1 2 0 G2~ sage: g.edges(sort=True) [(0, 2, 1), (1, 2, 1), (2, 0, 1), (2, 1, 3)] """ from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) g.add_edge(1, 2) g.set_edge_label(2,1,3) g.add_edge(0, 2) return g def _latex_dynkin_diagram(self, label=lambda x: x, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['G',2,1])._latex_dynkin_diagram()) \draw (2 cm,0) -- (4.0 cm,0); \draw (0, 0.15 cm) -- +(2 cm,0); \draw (0, -0.15 cm) -- +(2 cm,0); \draw (0,0) -- (2 cm,0); \draw (0, 0.15 cm) -- +(2 cm,0); \draw (0, -0.15 cm) -- +(2 cm,0); \draw[shift={(0.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$}; <BLANKLINE> """ if node is None: node = self._latex_draw_node ret = "\\draw (%s cm,0) -- (%s cm,0);\n"%(node_dist, node_dist*2.0) ret += "\\draw (0, 0.15 cm) -- +(%s cm,0);\n"%node_dist ret += "\\draw (0, -0.15 cm) -- +(%s cm,0);\n"%node_dist ret += self.classical()._latex_dynkin_diagram(label, node, node_dist, dual) ret += node(2*node_dist, 0, label(0)) return ret def ascii_art(self, label=lambda i: i, node=None): """ Returns an ascii art representation of the Dynkin diagram EXAMPLES:: sage: print(CartanType(['G',2,1]).ascii_art(label = lambda x: x+2)) 3 O=<=O---O 3 4 2 """ if node is None: node = self._ascii_art_node ret = " 3\n{}=<={}---{}".format(node(label(1)), node(label(2)), node(label(0))) return ret + "\n{!s:4}{!s:4}{!s:4}".format(label(1), label(2), label(0)) def _default_folded_cartan_type(self): """ Return the default folded Cartan type. EXAMPLES:: sage: CartanType(['G', 2, 1])._default_folded_cartan_type() ['G', 2, 1] as a folding of ['D', 4, 1] """ from sage.combinat.root_system.type_folded import CartanTypeFolded return CartanTypeFolded(self, ['D', 4, 1], [[0], [1, 3, 4], [2]])
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_G_affine.py
0.777469
0.441071
type_G_affine.py
pypi
from .cartan_type import CartanType_standard_untwisted_affine, CartanType_simply_laced class CartanType(CartanType_standard_untwisted_affine): def __init__(self, n): """ EXAMPLES:: sage: ct = CartanType(['A',4,1]) sage: ct ['A', 4, 1] sage: ct._repr_(compact = True) 'A4~' sage: ct.is_irreducible() True sage: ct.is_finite() False sage: ct.is_affine() True sage: ct.is_untwisted_affine() True sage: ct.is_crystallographic() True sage: ct.is_simply_laced() True sage: ct.classical() ['A', 4] sage: ct.dual() ['A', 4, 1] sage: ct = CartanType(['A', 1, 1]) sage: ct.is_simply_laced() False sage: ct.dual() ['A', 1, 1] TESTS:: sage: TestSuite(ct).run() """ assert n >= 1 CartanType_standard_untwisted_affine.__init__(self, "A", n) if n >= 2: self._add_abstract_superclass(CartanType_simply_laced) def _latex_(self): """ Return a latex representation of ``self``. EXAMPLES:: sage: ct = CartanType(['A',4,1]) sage: latex(ct) A_{4}^{(1)} """ return "A_{%s}^{(1)}" % self.n def dynkin_diagram(self): """ Returns the extended Dynkin diagram for affine type A. EXAMPLES:: sage: a = CartanType(['A',3,1]).dynkin_diagram() sage: a 0 O-------+ | | | | O---O---O 1 2 3 A3~ sage: a.edges(sort=True) [(0, 1, 1), (0, 3, 1), (1, 0, 1), (1, 2, 1), (2, 1, 1), (2, 3, 1), (3, 0, 1), (3, 2, 1)] sage: a = DynkinDiagram(['A',1,1]) sage: a O<=>O 0 1 A1~ sage: a.edges(sort=True) [(0, 1, 2), (1, 0, 2)] """ from .dynkin_diagram import DynkinDiagram_class n = self.n g = DynkinDiagram_class(self) if n == 1: g.add_edge(0, 1, 2) g.add_edge(1, 0, 2) else: for i in range(1, n): g.add_edge(i, i+1) g.add_edge(0, 1) g.add_edge(0, n) return g def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['A',4,1])._latex_dynkin_diagram()) \draw (0 cm,0) -- (6 cm,0); \draw (0 cm,0) -- (3.0 cm, 1.2 cm); \draw (3.0 cm, 1.2 cm) -- (6 cm, 0); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; \draw[fill=white] (3.0 cm, 1.2 cm) circle (.25cm) node[anchor=south east]{$0$}; <BLANKLINE> """ if node is None: node = self._latex_draw_node if self.n == 1: ret = "\\draw (0, 0.1 cm) -- +(%s cm,0);\n"%node_dist ret += "\\draw (0, -0.1 cm) -- +(%s cm,0);\n"%node_dist ret += self._latex_draw_arrow_tip(0.33*node_dist-0.2, 0, 180) ret += self._latex_draw_arrow_tip(0.66*node_dist+0.2, 0, 0) ret += node(0, 0, label(0)) ret += node(node_dist, 0, label(1)) return ret rt_most = (self.n-1)*node_dist mid = 0.5 * rt_most ret = "\\draw (0 cm,0) -- (%s cm,0);\n"%rt_most ret += "\\draw (0 cm,0) -- (%s cm, 1.2 cm);\n"%mid ret += "\\draw (%s cm, 1.2 cm) -- (%s cm, 0);\n"%(mid, rt_most) for i in range(self.n): ret += node(i*node_dist, 0, label(i+1)) ret += node(mid, 1.2, label(0), 'anchor=south east') return ret def ascii_art(self, label=lambda i: i, node=None): """ Return an ascii art representation of the extended Dynkin diagram. EXAMPLES:: sage: print(CartanType(['A',3,1]).ascii_art()) 0 O-------+ | | | | O---O---O 1 2 3 sage: print(CartanType(['A',5,1]).ascii_art(label = lambda x: x+2)) 2 O---------------+ | | | | O---O---O---O---O 3 4 5 6 7 sage: print(CartanType(['A',1,1]).ascii_art()) O<=>O 0 1 sage: print(CartanType(['A',1,1]).ascii_art(label = lambda x: x+2)) O<=>O 2 3 """ if node is None: node = self._ascii_art_node n = self.n if n == 1: l0 = label(0) l1 = label(1) return "{}<=>{}\n{!s:4}{}".format(node(l0), node(l1), l0, l1) ret = "{}\n{}".format(label(0), node(label(0))) ret += "----"*(n-2) + "---+\n|" + " "*(n-2) + " |\n|" + " "*(n-2) + " |\n" ret += "---".join(node(label(i)) for i in range(1,n+1)) + "\n" ret += "".join("{!s:4}".format(label(i)) for i in range(1,n+1)) return ret def dual(self): """ Type `A_1^1` is self dual despite not being simply laced. EXAMPLES:: sage: CartanType(['A',1,1]).dual() ['A', 1, 1] """ return self def _default_folded_cartan_type(self): r""" Return the default folded Cartan type. In general, this just returns ``self`` in ``self`` with `\sigma` as the identity map. EXAMPLES:: sage: CartanType(['A',1,1])._default_folded_cartan_type() ['A', 1, 1] as a folding of ['A', 3, 1] sage: CartanType(['A',3,1])._default_folded_cartan_type() ['A', 3, 1] as a folding of ['A', 3, 1] """ from sage.combinat.root_system.type_folded import CartanTypeFolded if self.n == 1: return CartanTypeFolded(self, ['A', 3, 1], [[0,2], [1,3]]) return CartanTypeFolded(self, self, [[i] for i in self.index_set()])
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_A_affine.py
0.782995
0.522689
type_A_affine.py
pypi
from sage.misc.cachefunc import cached_method from sage.combinat.root_system.cartan_type import CartanType_abstract, CartanType_simple, CartanType_finite, CartanType_simply_laced, CartanType_crystallographic from sage.matrix.constructor import block_diagonal_matrix from sage.sets.family import Family from . import ambient_space import sage.combinat.root_system as root_system from sage.structure.sage_object import SageObject from sage.structure.richcmp import richcmp_method, richcmp, rich_to_bool @richcmp_method class CartanType(SageObject, CartanType_abstract): r""" A class for reducible Cartan types. Reducible root systems are ones that can be factored as direct products. Strictly speaking type `D_2` (corresponding to orthogonal groups of degree 4) is reducible since it is isomorphic to `A_1\times A_1`. However type `D_2` is not built using this class for our purposes. INPUT: - ``types`` -- a list of simple Cartan types EXAMPLES:: sage: t1, t2 = [CartanType(x) for x in (['A',1], ['B',2])] sage: CartanType([t1, t2]) A1xB2 sage: t = CartanType("A2xB2") A reducible Cartan type is finite (resp. crystallographic, simply laced) if all its components are:: sage: t.is_finite() True sage: t.is_crystallographic() True sage: t.is_simply_laced() False This is implemented by inserting the appropriate abstract super classes (see :meth:`~sage.combinat.root_system.cartan_type.CartanType_abstract._add_abstract_superclass`):: sage: t.__class__.mro() [<class 'sage.combinat.root_system.type_reducible.CartanType_with_superclass'>, <class 'sage.combinat.root_system.type_reducible.CartanType'>, <class 'sage.structure.sage_object.SageObject'>, <class 'sage.combinat.root_system.cartan_type.CartanType_finite'>, <class 'sage.combinat.root_system.cartan_type.CartanType_crystallographic'>, <class 'sage.combinat.root_system.cartan_type.CartanType_abstract'>, <class 'object'>] The index set of the reducible Cartan type is obtained by relabelling successively the nodes of the Dynkin diagrams of the components by 1,2,...:: sage: t = CartanType(["A",4], ["BC",5,2], ["C",3]) sage: t.index_set() (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) sage: t.dynkin_diagram() O---O---O---O 1 2 3 4 O=<=O---O---O---O=<=O 5 6 7 8 9 10 O---O=<=O 11 12 13 A4xBC5~xC3 """ def __init__(self, types): """ Initialize ``self``. TESTS: Internally, this relabelling is stored as a dictionary:: sage: t = CartanType(["A",4], ["BC",5,2], ["C",3]) sage: sorted(t._index_relabelling.items()) [((0, 1), 1), ((0, 2), 2), ((0, 3), 3), ((0, 4), 4), ((1, 0), 5), ((1, 1), 6), ((1, 2), 7), ((1, 3), 8), ((1, 4), 9), ((1, 5), 10), ((2, 1), 11), ((2, 2), 12), ((2, 3), 13)] Similarly, the attribute `_shifts` specifies by how much the indices of the bases of the ambient spaces of the components are shifted in the ambient space of this Cartan type:: sage: t = CartanType("A2xB2") sage: t._shifts [0, 3, 5] sage: A = t.root_system().ambient_space(); A Ambient space of the Root system of type A2xB2 sage: A.ambient_spaces() [Ambient space of the Root system of type ['A', 2], Ambient space of the Root system of type ['B', 2]] sage: x = A.ambient_spaces()[0]([2,1,0]); x (2, 1, 0) sage: A.inject_weights(0,x) (2, 1, 0, 0, 0) sage: x = A.ambient_spaces()[1]([1,0]); x (1, 0) sage: A.inject_weights(1,x) (0, 0, 0, 1, 0) More tests:: sage: TestSuite(t).run() """ self._types = types self.affine = False indices = (None,) + tuple( (i, j) for i in range(len(types)) for j in types[i].index_set() ) self._indices = indices self._index_relabelling = dict((indices[i], i) for i in range(1, len(indices))) self._spaces = [t.root_system().ambient_space() for t in types] if all(l is not None for l in self._spaces): self._shifts = [sum(l.dimension() for l in self._spaces[:k]) for k in range(len(types)+1)] self.tools = root_system.type_reducible # a direct product of finite Cartan types is again finite; # idem for simply laced and crystallographic. super_classes = tuple( cls for cls in (CartanType_finite, CartanType_simply_laced, CartanType_crystallographic) if all(isinstance(t, cls) for t in types) ) self._add_abstract_superclass(super_classes) def _repr_(self, compact=True): # We should make a consistent choice here """ EXAMPLES:: sage: CartanType("A2","B2") # indirect doctest A2xB2 sage: CartanType("A2",CartanType("F4~").dual()) A2xF4~* """ return "x".join(t._repr_(compact=True) for t in self._types) def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: latex(CartanType("A4","B2","D8")) A_{4} \times B_{2} \times D_{8} """ return " \\times ".join(x._latex_() for x in self.component_types()) def __hash__(self): r""" EXAMPLES:: sage: ct0 = CartanType(['A',1],['B',2]) sage: ct1 = CartanType(['A',2],['B',3]) sage: hash(ct0) != hash(ct1) True """ return hash(repr(self._types)) def __richcmp__(self, other, op): """ Rich comparison. EXAMPLES:: sage: ct1 = CartanType(['A',1],['B',2]) sage: ct2 = CartanType(['B',2],['A',1]) sage: ct3 = CartanType(['A',4]) sage: ct1 == ct1 True sage: ct1 == ct2 False sage: ct1 == ct3 False TESTS: Check that :trac:`20418` is fixed:: sage: ct = CartanType(["A2", "B2"]) sage: ct == (1, 2, 1) False """ if isinstance(other, CartanType_simple): return rich_to_bool(op, 1) if not isinstance(other, CartanType): return NotImplemented return richcmp(self._types, other._types, op) def component_types(self): """ A list of Cartan types making up the reducible type. EXAMPLES:: sage: CartanType(['A',2],['B',2]).component_types() [['A', 2], ['B', 2]] """ return self._types def type(self): """ Returns "reducible" since the type is reducible. EXAMPLES:: sage: CartanType(['A',2],['B',2]).type() 'reducible' """ return "reducible" def rank(self): """ Returns the rank of self. EXAMPLES:: sage: CartanType("A2","A1").rank() 3 """ return sum(t.rank() for t in self._types) @cached_method def index_set(self): r""" Implements :meth:`CartanType_abstract.index_set`. For the moment, the index set is always of the form `\{1, \ldots, n\}`. EXAMPLES:: sage: CartanType("A2","A1").index_set() (1, 2, 3) """ return tuple(range(1, self.rank()+1)) def cartan_matrix(self, subdivide=True): """ Return the Cartan matrix associated with ``self``. By default the Cartan matrix is a subdivided block matrix showing the reducibility but the subdivision can be suppressed with the option ``subdivide = False``. EXAMPLES:: sage: ct = CartanType("A2","B2") sage: ct.cartan_matrix() [ 2 -1| 0 0] [-1 2| 0 0] [-----+-----] [ 0 0| 2 -1] [ 0 0|-2 2] sage: ct.cartan_matrix(subdivide=False) [ 2 -1 0 0] [-1 2 0 0] [ 0 0 2 -1] [ 0 0 -2 2] sage: ct.index_set() == ct.cartan_matrix().index_set() True """ from sage.combinat.root_system.cartan_matrix import CartanMatrix return CartanMatrix(block_diagonal_matrix([t.cartan_matrix() for t in self._types], subdivide=subdivide), cartan_type=self, index_set=self.index_set()) def dynkin_diagram(self): """ Returns a Dynkin diagram for type reducible. EXAMPLES:: sage: dd = CartanType("A2xB2xF4").dynkin_diagram() sage: dd O---O 1 2 O=>=O 3 4 O---O=>=O---O 5 6 7 8 A2xB2xF4 sage: dd.edges(sort=True) [(1, 2, 1), (2, 1, 1), (3, 4, 2), (4, 3, 1), (5, 6, 1), (6, 5, 1), (6, 7, 2), (7, 6, 1), (7, 8, 1), (8, 7, 1)] sage: CartanType("F4xA2").dynkin_diagram() O---O=>=O---O 1 2 3 4 O---O 5 6 F4xA2 """ from .dynkin_diagram import DynkinDiagram_class relabelling = self._index_relabelling g = DynkinDiagram_class(self) for i in range(len(self._types)): for [e1, e2, l] in self._types[i].dynkin_diagram().edges(sort=True): g.add_edge(relabelling[i,e1], relabelling[i,e2], label=l) return g def _latex_dynkin_diagram(self, label=lambda x: x, node=None, node_dist=2): r""" Return a latex representation of the Dynkin diagram. .. NOTE:: The arguments ``label`` and ``dual`` is ignored. EXAMPLES:: sage: print(CartanType("A2","B2")._latex_dynkin_diagram()) { \draw (0 cm,0) -- (2 cm,0); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \pgftransformyshift{-3 cm} \draw (0 cm,0) -- (0 cm,0); \draw (0 cm, 0.1 cm) -- +(2 cm,0); \draw (0 cm, -0.1 cm) -- +(2 cm,0); \draw[shift={(1.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; } """ types = self.component_types() relabelling = self._index_relabelling ret = "{\n" ret += "\\pgftransformyshift{-3 cm}\n".join(types[i]._latex_dynkin_diagram( lambda x: label(relabelling[i,x]), node, node_dist=node_dist) for i in range(len(types))) ret += "}" return ret def ascii_art(self, label=lambda i: i, node=None): """ Return an ascii art representation of this reducible Cartan type. EXAMPLES:: sage: print(CartanType("F4xA2").ascii_art(label = lambda x: x+2)) O---O=>=O---O 3 4 5 6 O---O 7 8 sage: print(CartanType(["BC",5,2], ["A",4]).ascii_art()) O=<=O---O---O---O=<=O 1 2 3 4 5 6 O---O---O---O 7 8 9 10 sage: print(CartanType(["A",4], ["BC",5,2], ["C",3]).ascii_art()) O---O---O---O 1 2 3 4 O=<=O---O---O---O=<=O 5 6 7 8 9 10 O---O=<=O 11 12 13 """ types = self.component_types() relabelling = self._index_relabelling return "\n".join(types[i].ascii_art(lambda x: label(relabelling[i,x]), node) for i in range(len(types))) @cached_method def is_finite(self): """ EXAMPLES:: sage: ct1 = CartanType(['A',2],['B',2]) sage: ct1.is_finite() True sage: ct2 = CartanType(['A',2],['B',2,1]) sage: ct2.is_finite() False TESTS:: sage: isinstance(ct1, sage.combinat.root_system.cartan_type.CartanType_finite) True sage: isinstance(ct2, sage.combinat.root_system.cartan_type.CartanType_finite) False """ return all(t.is_finite() for t in self.component_types()) def is_irreducible(self): """ Report that this Cartan type is not irreducible. EXAMPLES:: sage: ct = CartanType(['A',2],['B',2]) sage: ct.is_irreducible() False """ return False def dual(self): """ EXAMPLES:: sage: CartanType("A2xB2").dual() A2xC2 """ return CartanType([t.dual() for t in self._types]) def is_affine(self): """ Report that this reducible Cartan type is not affine EXAMPLES:: sage: CartanType(['A',2],['B',2]).is_affine() False """ return False @cached_method def coxeter_diagram(self): """ Return the Coxeter diagram for ``self``. EXAMPLES:: sage: cd = CartanType("A2xB2xF4").coxeter_diagram() sage: cd Graph on 8 vertices sage: cd.edges(sort=True) [(1, 2, 3), (3, 4, 4), (5, 6, 3), (6, 7, 4), (7, 8, 3)] sage: CartanType("F4xA2").coxeter_diagram().edges(sort=True) [(1, 2, 3), (2, 3, 4), (3, 4, 3), (5, 6, 3)] sage: cd = CartanType("A1xH3").coxeter_diagram(); cd Graph on 4 vertices sage: cd.edges(sort=True) [(2, 3, 3), (3, 4, 5)] """ from sage.graphs.graph import Graph relabelling = self._index_relabelling g = Graph(multiedges=False) g.add_vertices(self.index_set()) for i,t in enumerate(self._types): for [e1, e2, l] in t.coxeter_diagram().edges(sort=True): g.add_edge(relabelling[i,e1], relabelling[i,e2], label=l) return g class AmbientSpace(ambient_space.AmbientSpace): """ EXAMPLES:: sage: RootSystem("A2xB2").ambient_space() Ambient space of the Root system of type A2xB2 """ def cartan_type(self): """ EXAMPLES:: sage: RootSystem("A2xB2").ambient_space().cartan_type() A2xB2 """ return self.root_system.cartan_type() def component_types(self): """ EXAMPLES:: sage: RootSystem("A2xB2").ambient_space().component_types() [['A', 2], ['B', 2]] """ return self.root_system.cartan_type().component_types() def dimension(self): """ EXAMPLES:: sage: RootSystem("A2xB2").ambient_space().dimension() 5 """ return sum(v.dimension() for v in self.ambient_spaces()) def ambient_spaces(self): """ Returns a list of the irreducible Cartan types of which the given reducible Cartan type is a product. EXAMPLES:: sage: RootSystem("A2xB2").ambient_space().ambient_spaces() [Ambient space of the Root system of type ['A', 2], Ambient space of the Root system of type ['B', 2]] """ return [t.root_system().ambient_space() for t in self.component_types()] def inject_weights(self, i, v): """ Produces the corresponding element of the lattice. INPUT: - ``i`` - an integer in range(self.components) - ``v`` - a vector in the i-th component weight lattice EXAMPLES:: sage: V = RootSystem("A2xB2").ambient_space() sage: [V.inject_weights(i,V.ambient_spaces()[i].fundamental_weights()[1]) for i in range(2)] [(1, 0, 0, 0, 0), (0, 0, 0, 1, 0)] sage: [V.inject_weights(i,V.ambient_spaces()[i].fundamental_weights()[2]) for i in range(2)] [(1, 1, 0, 0, 0), (0, 0, 0, 1/2, 1/2)] """ shift = self.root_system.cartan_type()._shifts[i] return self._from_dict( dict([(shift+k, c) for (k,c) in v ])) @cached_method def simple_root(self, i): """ EXAMPLES:: sage: A = RootSystem("A1xB2").ambient_space() sage: A.simple_root(2) (0, 0, 1, -1) sage: A.simple_roots() Finite family {1: (1, -1, 0, 0), 2: (0, 0, 1, -1), 3: (0, 0, 0, 1)} """ if i not in self.index_set(): raise ValueError("{} is not in the index set".format(i)) (i, j) = self.cartan_type()._indices[i] return self.inject_weights(i, self.ambient_spaces()[i].simple_root(j)) @cached_method def simple_coroot(self, i): """ EXAMPLES:: sage: A = RootSystem("A1xB2").ambient_space() sage: A.simple_coroot(2) (0, 0, 1, -1) sage: A.simple_coroots() Finite family {1: (1, -1, 0, 0), 2: (0, 0, 1, -1), 3: (0, 0, 0, 2)} """ if i not in self.index_set(): raise ValueError("{} is not in the index set".format(i)) (i, j) = self.cartan_type()._indices[i] return self.inject_weights(i, self.ambient_spaces()[i].simple_coroot(j)) def positive_roots(self): """ EXAMPLES:: sage: RootSystem("A1xA2").ambient_space().positive_roots() [(1, -1, 0, 0, 0), (0, 0, 1, -1, 0), (0, 0, 1, 0, -1), (0, 0, 0, 1, -1)] """ res = [] for i, ambient_sp in enumerate(self.ambient_spaces()): res.extend(self.inject_weights(i, v) for v in ambient_sp.positive_roots()) return res def negative_roots(self): """ EXAMPLES:: sage: RootSystem("A1xA2").ambient_space().negative_roots() [(-1, 1, 0, 0, 0), (0, 0, -1, 1, 0), (0, 0, -1, 0, 1), (0, 0, 0, -1, 1)] """ ret = [] for i, ambient_sp in enumerate(self.ambient_spaces()): ret.extend(self.inject_weights(i, v) for v in ambient_sp.negative_roots()) return ret def fundamental_weights(self): """ EXAMPLES:: sage: RootSystem("A2xB2").ambient_space().fundamental_weights() Finite family {1: (1, 0, 0, 0, 0), 2: (1, 1, 0, 0, 0), 3: (0, 0, 0, 1, 0), 4: (0, 0, 0, 1/2, 1/2)} """ fw = [] for i, ambient_sp in enumerate(self.ambient_spaces()): fw.extend(self.inject_weights(i, v) for v in ambient_sp.fundamental_weights()) return Family(dict([i,fw[i-1]] for i in range(1,len(fw)+1))) CartanType.AmbientSpace = AmbientSpace
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_reducible.py
0.903526
0.507873
type_reducible.py
pypi
from sage.structure.unique_representation import UniqueRepresentation from sage.structure.category_object import CategoryObject from sage.categories.modules import Modules from sage.rings.integer_ring import ZZ from sage.misc.cachefunc import cached_method from sage.matrix.constructor import Matrix from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet from sage.combinat.root_system.weyl_characters import WeylCharacterRing # TODO: Make this a proper parent and implement actions class IntegrableRepresentation(UniqueRepresentation, CategoryObject): r""" An irreducible integrable highest weight representation of an affine Lie algebra. INPUT: - ``Lam`` -- a dominant weight in an extended weight lattice of affine type REFERENCES: - [Ka1990]_ .. [KMPS] Kass, Moody, Patera and Slansky, *Affine Lie algebras, weight multiplicities, and branching rules*. Vols. 1, 2. University of California Press, Berkeley, CA, 1990. .. [KacPeterson] Kac and Peterson. *Infinite-dimensional Lie algebras, theta functions and modular forms*. Adv. in Math. 53 (1984), no. 2, 125-264. .. [Carter] Carter, *Lie algebras of finite and affine type*. Cambridge University Press, 2005 If `\Lambda` is a dominant integral weight for an affine root system, there exists a unique integrable representation `V=V_\Lambda` of highest weight `\Lambda`. If `\mu` is another weight, let `m(\mu)` denote the multiplicity of the weight `\mu` in this representation. The set `\operatorname{supp}(V)` of `\mu` such that `m(\mu) > 0` is contained in the paraboloid .. MATH:: (\Lambda+\rho | \Lambda+\rho) - (\mu+\rho | \mu+\rho) \geq 0 where `(\, | \,)` is the invariant inner product on the weight lattice and `\rho` is the Weyl vector. Moreover if `m(\mu)>0` then `\mu\in\operatorname{supp}(V)` differs from `\Lambda` by an element of the root lattice ([Ka1990]_, Propositions 11.3 and 11.4). Let `\delta` be the nullroot, which is the lowest positive imaginary root. Then by [Ka1990]_, Proposition 11.3 or Corollary 11.9, for fixed `\mu` the function `m(\mu - k\delta)` is a monotone increasing function of `k`. It is useful to take `\mu` to be such that this function is nonzero if and only if `k \geq 0`. Therefore we make the following definition. If `\mu` is such that `m(\mu) \neq 0` but `m(\mu + \delta) = 0` then `\mu` is called *maximal*. Since `\delta` is fixed under the action of the affine Weyl group, and since the weight multiplicities are Weyl group invariant, the function `k \mapsto m(\mu - k \delta)` is unchanged if `\mu` is replaced by an equivalent weight. Therefore in tabulating these functions, we may assume that `\mu` is dominant. There are only a finite number of dominant maximal weights. Since every nonzero weight multiplicity appears in the string `\mu - k\delta` for one of the finite number of dominant maximal weights `\mu`, it is important to be able to compute these. We may do this as follows. EXAMPLES:: sage: Lambda = RootSystem(['A',3,1]).weight_lattice(extended=true).fundamental_weights() sage: IntegrableRepresentation(Lambda[1]+Lambda[2]+Lambda[3]).print_strings() 2*Lambda[0] + Lambda[2]: 4 31 161 665 2380 7658 22721 63120 166085 417295 1007601 2349655 Lambda[0] + 2*Lambda[1]: 2 18 99 430 1593 5274 16005 45324 121200 308829 754884 1779570 Lambda[0] + 2*Lambda[3]: 2 18 99 430 1593 5274 16005 45324 121200 308829 754884 1779570 Lambda[1] + Lambda[2] + Lambda[3]: 1 10 60 274 1056 3601 11199 32354 88009 227555 563390 1343178 3*Lambda[2] - delta: 3 21 107 450 1638 5367 16194 45687 121876 310056 757056 1783324 sage: Lambda = RootSystem(['D',4,1]).weight_lattice(extended=true).fundamental_weights() sage: IntegrableRepresentation(Lambda[0]+Lambda[1]).print_strings() # long time Lambda[0] + Lambda[1]: 1 10 62 293 1165 4097 13120 38997 109036 289575 735870 1799620 Lambda[3] + Lambda[4] - delta: 3 25 136 590 2205 7391 22780 65613 178660 463842 1155717 2777795 In this example, we construct the extended weight lattice of Cartan type `A_3^{(1)}`, then define ``Lambda`` to be the fundamental weights `(\Lambda_i)_{i \in I}`. We find there are 5 maximal dominant weights in irreducible representation of highest weight `\Lambda_1 + \Lambda_2 + \Lambda_3`, and we determine their strings. It was shown in [KacPeterson]_ that each string is the set of Fourier coefficients of a modular form. Every weight `\mu` such that the weight multiplicity `m(\mu)` is nonzero has the form .. MATH:: \Lambda - n_0 \alpha_0 - n_1 \alpha_1 - \cdots, where the `n_i` are nonnegative integers. This is represented internally as a tuple `(n_0, n_1, n_2, \ldots)`. If you want an individual multiplicity you use the method :meth:`m` and supply it with this tuple:: sage: Lambda = RootSystem(['C',2,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(2*Lambda[0]); V Integrable representation of ['C', 2, 1] with highest weight 2*Lambda[0] sage: V.m((3,5,3)) 18 The :class:`IntegrableRepresentation` class has methods :meth:`to_weight` and :meth:`from_weight` to convert between this internal representation and the weight lattice:: sage: delta = V.weight_lattice().null_root() sage: V.to_weight((4,3,2)) -3*Lambda[0] + 6*Lambda[1] - Lambda[2] - 4*delta sage: V.from_weight(-3*Lambda[0] + 6*Lambda[1] - Lambda[2] - 4*delta) (4, 3, 2) To get more values, use the depth parameter:: sage: L0 = RootSystem(["A",1,1]).weight_lattice(extended=true).fundamental_weight(0); L0 Lambda[0] sage: IntegrableRepresentation(4*L0).print_strings(depth=20) 4*Lambda[0]: 1 1 3 6 13 23 44 75 131 215 354 561 889 1368 2097 3153 4712 6936 10151 14677 2*Lambda[0] + 2*Lambda[1] - delta: 1 2 5 10 20 36 66 112 190 310 501 788 1230 1880 2850 4256 6303 9222 13396 19262 4*Lambda[1] - 2*delta: 1 2 6 11 23 41 75 126 215 347 561 878 1368 2082 3153 4690 6936 10121 14677 21055 An example in type `C_2^{(1)}`:: sage: Lambda = RootSystem(['C',2,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(2*Lambda[0]) sage: V.print_strings() # long time 2*Lambda[0]: 1 2 9 26 77 194 477 1084 2387 5010 10227 20198 Lambda[0] + Lambda[2] - delta: 1 5 18 55 149 372 872 1941 4141 8523 17005 33019 2*Lambda[1] - delta: 1 4 15 44 122 304 721 1612 3469 7176 14414 28124 2*Lambda[2] - 2*delta: 2 7 26 72 194 467 1084 2367 5010 10191 20198 38907 Examples for twisted affine types:: sage: Lambda = RootSystem(["A",2,2]).weight_lattice(extended=True).fundamental_weights() sage: IntegrableRepresentation(Lambda[0]).strings() {Lambda[0]: [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56]} sage: Lambda = RootSystem(['G',2,1]).dual.weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]+Lambda[1]+Lambda[2]) sage: V.print_strings() # long time 6*Lambdacheck[0]: 4 28 100 320 944 2460 6064 14300 31968 69020 144676 293916 3*Lambdacheck[0] + Lambdacheck[1]: 2 16 58 192 588 1568 3952 9520 21644 47456 100906 207536 4*Lambdacheck[0] + Lambdacheck[2]: 4 22 84 276 800 2124 5288 12470 28116 61056 128304 261972 2*Lambdacheck[1] - deltacheck: 2 8 32 120 354 980 2576 6244 14498 32480 69776 145528 Lambdacheck[0] + Lambdacheck[1] + Lambdacheck[2]: 1 6 26 94 294 832 2184 5388 12634 28390 61488 128976 2*Lambdacheck[0] + 2*Lambdacheck[2]: 2 12 48 164 492 1344 3428 8256 18960 41844 89208 184512 3*Lambdacheck[2] - deltacheck: 4 16 60 208 592 1584 4032 9552 21728 47776 101068 207888 sage: Lambda = RootSystem(['A',6,2]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]+2*Lambda[1]) sage: V.print_strings() # long time 5*Lambda[0]: 3 42 378 2508 13707 64650 272211 1045470 3721815 12425064 39254163 118191378 3*Lambda[0] + Lambda[2]: 1 23 234 1690 9689 47313 204247 800029 2893198 9786257 31262198 95035357 Lambda[0] + 2*Lambda[1]: 1 14 154 1160 6920 34756 153523 612354 2248318 7702198 24875351 76341630 Lambda[0] + Lambda[1] + Lambda[3] - 2*delta: 6 87 751 4779 25060 113971 464842 1736620 6034717 19723537 61152367 181068152 Lambda[0] + 2*Lambda[2] - 2*delta: 3 54 499 3349 18166 84836 353092 1341250 4725259 15625727 48938396 146190544 Lambda[0] + 2*Lambda[3] - 4*delta: 15 195 1539 9186 45804 200073 789201 2866560 9723582 31120281 94724550 275919741 """ def __init__(self, Lam): """ Initialize ``self``. EXAMPLES:: sage: Lambda = RootSystem(['A',3,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[1]+Lambda[2]+Lambda[3]) Some methods required by the category are not implemented:: sage: TestSuite(V).run() # known bug (#21387) """ CategoryObject.__init__(self, base=ZZ, category=Modules(ZZ)) self._Lam = Lam self._P = Lam.parent() self._Q = self._P.root_system.root_lattice() # Store some extra simple computations that appear in tight loops self._Lam_rho = self._Lam + self._P.rho() self._cartan_matrix = self._P.root_system.cartan_matrix() self._cartan_type = self._P.root_system.cartan_type() self._classical_rank = self._cartan_type.classical().rank() self._index_set = self._P.index_set() self._index_set_classical = self._cartan_type.classical().index_set() self._cminv = self._cartan_type.classical().cartan_matrix().inverse() self._ddict = {} self._mdict = {tuple(0 for i in self._index_set): 1} # Coerce a classical root into the root lattice Q from_cl_root = lambda h: self._Q._from_dict(h._monomial_coefficients) self._classical_roots = [from_cl_root(al) for al in self._Q.classical().roots()] self._classical_positive_roots = [from_cl_root(al) for al in self._Q.classical().positive_roots()] self._a = self._cartan_type.a() # This is not cached self._ac = self._cartan_type.dual().a() # This is not cached self._eps = {i: self._a[i] / self._ac[i] for i in self._index_set} E = Matrix.diagonal([self._eps[i] for i in self._index_set_classical]) self._ip = (self._cartan_type.classical().cartan_matrix()*E).inverse() # Extra data for the twisted cases if not self._cartan_type.is_untwisted_affine(): self._classical_short_roots = frozenset(al for al in self._classical_roots if self._inner_qq(al,al) == 2) def highest_weight(self): """ Returns the highest weight of ``self``. EXAMPLES:: sage: Lambda = RootSystem(['D',4,1]).weight_lattice(extended=true).fundamental_weights() sage: IntegrableRepresentation(Lambda[0]+2*Lambda[2]).highest_weight() Lambda[0] + 2*Lambda[2] """ return self._Lam def weight_lattice(self): """ Return the weight lattice associated to ``self``. EXAMPLES:: sage: V=IntegrableRepresentation(RootSystem(['E',6,1]).weight_lattice(extended=true).fundamental_weight(0)) sage: V.weight_lattice() Extended weight lattice of the Root system of type ['E', 6, 1] """ return self._P def root_lattice(self): """ Return the root lattice associated to ``self``. EXAMPLES:: sage: V=IntegrableRepresentation(RootSystem(['F',4,1]).weight_lattice(extended=true).fundamental_weight(0)) sage: V.root_lattice() Root lattice of the Root system of type ['F', 4, 1] """ return self._Q @cached_method def level(self): r""" Return the level of ``self``. The level of a highest weight representation `V_{\Lambda}` is defined as `(\Lambda | \delta)` See [Ka1990]_ section 12.4. EXAMPLES:: sage: Lambda = RootSystem(['G',2,1]).weight_lattice(extended=true).fundamental_weights() sage: [IntegrableRepresentation(Lambda[i]).level() for i in [0,1,2]] [1, 1, 2] """ return ZZ(self._inner_pq(self._Lam, self._Q.null_root())) @cached_method def coxeter_number(self): """ Return the Coxeter number of the Cartan type of ``self``. The Coxeter number is defined in [Ka1990]_ Chapter 6, and commonly denoted `h`. EXAMPLES:: sage: Lambda = RootSystem(['F',4,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]) sage: V.coxeter_number() 12 """ return sum(self._a) @cached_method def dual_coxeter_number(self): r""" Return the dual Coxeter number of the Cartan type of ``self``. The dual Coxeter number is defined in [Ka1990]_ Chapter 6, and commonly denoted `h^{\vee}`. EXAMPLES:: sage: Lambda = RootSystem(['F',4,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]) sage: V.dual_coxeter_number() 9 """ return sum(self._ac) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: Lambda = RootSystem(['F',4,1]).weight_lattice(extended=true).fundamental_weights() sage: IntegrableRepresentation(Lambda[0]) Integrable representation of ['F', 4, 1] with highest weight Lambda[0] """ return "Integrable representation of %s with highest weight %s" % (self._cartan_type, self._Lam) def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: Lambda = RootSystem(['C',3,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]+2*Lambda[3]) sage: latex(V) V_{\Lambda_{0} + 2 \Lambda_{3}} """ return "V_{{{}}}".format(self._Lam._latex_()) def cartan_type(self): """ Return the Cartan type of ``self``. EXAMPLES:: sage: Lambda = RootSystem(['F',4,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]) sage: V.cartan_type() ['F', 4, 1] """ return self._cartan_type def _inner_qq(self, qelt1, qelt2): """ Symmetric form between two elements of the root lattice associated to ``self``. EXAMPLES:: sage: P = RootSystem(['F',4,1]).weight_lattice(extended=true) sage: Lambda = P.fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]) sage: alpha = V.root_lattice().simple_roots() sage: Matrix([[V._inner_qq(alpha[i], alpha[j]) for j in V._index_set] for i in V._index_set]) [ 2 -1 0 0 0] [ -1 2 -1 0 0] [ 0 -1 2 -1 0] [ 0 0 -1 1 -1/2] [ 0 0 0 -1/2 1] .. WARNING:: If ``qelt1`` or ``qelt1`` accidentally gets coerced into the extended weight lattice, this will return an answer, and it will be wrong. To make this code robust, parents should be checked. This is not done since in the application the parents are known, so checking would unnecessarily slow us down. """ mc1 = qelt1.monomial_coefficients() mc2 = qelt2.monomial_coefficients() zero = ZZ.zero() return sum(mc1.get(i, zero) * mc2.get(j, zero) * self._cartan_matrix[i,j] / self._eps[i] for i in self._index_set for j in self._index_set) def _inner_pq(self, pelt, qelt): """ Symmetric form between an element of the weight and root lattices associated to ``self``. .. WARNING:: If ``qelt`` accidentally gets coerced into the extended weight lattice, this will return an answer, and it will be wrong. To make this code robust, parents should be checked. This is not done since in the application the parents are known, so checking would unnecessarily slow us down. EXAMPLES:: sage: P = RootSystem(['F',4,1]).weight_lattice(extended=true) sage: Lambda = P.fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]) sage: alpha = V.root_lattice().simple_roots() sage: Matrix([[V._inner_pq(P(alpha[i]), alpha[j]) for j in V._index_set] for i in V._index_set]) [ 2 -1 0 0 0] [ -1 2 -1 0 0] [ 0 -1 2 -1 0] [ 0 0 -1 1 -1/2] [ 0 0 0 -1/2 1] sage: P = RootSystem(['G',2,1]).weight_lattice(extended=true) sage: P = RootSystem(['G',2,1]).weight_lattice(extended=true) sage: Lambda = P.fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]) sage: alpha = V.root_lattice().simple_roots() sage: Matrix([[V._inner_pq(Lambda[i],alpha[j]) for j in V._index_set] for i in V._index_set]) [ 1 0 0] [ 0 1/3 0] [ 0 0 1] """ mcp = pelt.monomial_coefficients() mcq = qelt.monomial_coefficients() zero = ZZ.zero() return sum(mcp.get(i, zero) * mcq[i] / self._eps[i] for i in mcq) def _inner_pp(self, pelt1, pelt2): """ Symmetric form between an two elements of the weight lattice associated to ``self``. EXAMPLES:: sage: P = RootSystem(['G',2,1]).weight_lattice(extended=true) sage: Lambda = P.fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]) sage: alpha = V.root_lattice().simple_roots() sage: Matrix([[V._inner_pp(Lambda[i],P(alpha[j])) for j in V._index_set] for i in V._index_set]) [ 1 0 0] [ 0 1/3 0] [ 0 0 1] sage: Matrix([[V._inner_pp(Lambda[i],Lambda[j]) for j in V._index_set] for i in V._index_set]) [ 0 0 0] [ 0 2/3 1] [ 0 1 2] """ mc1 = pelt1.monomial_coefficients() mc2 = pelt2.monomial_coefficients() zero = ZZ.zero() mc1d = mc1.get('delta', zero) mc2d = mc2.get('delta', zero) return sum(mc1.get(i,zero) * self._ac[i] * mc2d + mc2.get(i,zero) * self._ac[i] * mc1d for i in self._index_set) \ + sum(mc1.get(i,zero) * mc2.get(j,zero) * self._ip[ii,ij] for ii, i in enumerate(self._index_set_classical) for ij, j in enumerate(self._index_set_classical)) def to_weight(self, n): r""" Return the weight associated to the tuple ``n`` in ``self``. If ``n`` is the tuple `(n_1, n_2, \ldots)`, then the associated weight is `\Lambda - \sum_i n_i \alpha_i`, where `\Lambda` is the weight of the representation. INPUT: - ``n`` -- a tuple representing a weight EXAMPLES:: sage: Lambda = RootSystem(['A',2,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(2*Lambda[2]) sage: V.to_weight((1,0,0)) -2*Lambda[0] + Lambda[1] + 3*Lambda[2] - delta """ alpha = self._P.simple_roots() I = self._index_set return self._Lam - self._P.sum(val * alpha[I[i]] for i,val in enumerate(n)) def _from_weight_helper(self, mu, check=False): r""" Return the coefficients of a tuple of the weight ``mu`` expressed in terms of the simple roots in ``self``. The tuple ``n`` is defined as the tuple `(n_0, n_1, \ldots)` such that `\mu = \sum_{i \in I} n_i \alpha_i`. INPUT: - ``mu`` -- an element in the root lattice .. TODO:: Implement this as a section map of the inverse of the coercion from `Q \to P`. EXAMPLES:: sage: Lambda = RootSystem(['A',2,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(2*Lambda[2]) sage: V.to_weight((1,0,0)) -2*Lambda[0] + Lambda[1] + 3*Lambda[2] - delta sage: delta = V.weight_lattice().null_root() sage: V._from_weight_helper(2*Lambda[0] - Lambda[1] - 1*Lambda[2] + delta) (1, 0, 0) """ mu = self._P(mu) zero = ZZ.zero() n0 = mu.monomial_coefficients().get('delta', zero) mu0 = mu - n0 * self._P.simple_root(self._cartan_type.special_node()) ret = [n0] # This should be in ZZ because it is in the weight lattice mc_mu0 = mu0.monomial_coefficients() for ii, i in enumerate(self._index_set_classical): # -1 for indexing ret.append( sum(self._cminv[ii,ij] * mc_mu0.get(j, zero) for ij, j in enumerate(self._index_set_classical)) ) if check: return all(x in ZZ for x in ret) else: return tuple(ZZ(x) for x in ret) def from_weight(self, mu): r""" Return the tuple `(n_0, n_1, ...)`` such that ``mu`` equals `\Lambda - \sum_{i \in I} n_i \alpha_i` in ``self``, where `\Lambda` is the highest weight of ``self``. EXAMPLES:: sage: Lambda = RootSystem(['A',2,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(2*Lambda[2]) sage: V.to_weight((1,0,0)) -2*Lambda[0] + Lambda[1] + 3*Lambda[2] - delta sage: delta = V.weight_lattice().null_root() sage: V.from_weight(-2*Lambda[0] + Lambda[1] + 3*Lambda[2] - delta) (1, 0, 0) """ return self._from_weight_helper(self._Lam - mu) def s(self, n, i): """ Return the action of the ``i``-th simple reflection on the internal representation of weights by tuples ``n`` in ``self``. EXAMPLES:: sage: V = IntegrableRepresentation(RootSystem(['A',2,1]).weight_lattice(extended=true).fundamental_weight(0)) sage: [V.s((0,0,0),i) for i in V._index_set] [(1, 0, 0), (0, 0, 0), (0, 0, 0)] """ ret = list(n) # This makes a copy ret[i] += self._Lam._monomial_coefficients.get(i, ZZ.zero()) ret[i] -= sum(val * self._cartan_matrix[i,j] for j,val in enumerate(n)) return tuple(ret) def to_dominant(self, n): """ Return the dominant weight in ``self`` equivalent to ``n`` under the affine Weyl group. EXAMPLES:: sage: Lambda = RootSystem(['A',2,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(3*Lambda[0]) sage: n = V.to_dominant((13,11,7)); n (4, 3, 3) sage: V.to_weight(n) Lambda[0] + Lambda[1] + Lambda[2] - 4*delta """ if n in self._ddict: return self._ddict[n] path = [n] alpha = self._P.simple_roots() next = True cur_wt = self.to_weight(n) while next: if path[-1] in self._ddict: path.append( self._ddict[path[-1]] ) break next = False mc = cur_wt.monomial_coefficients() # Most weights are dense over the index set for i in self._index_set: if mc.get(i, 0) < 0: m = self.s(path[-1], i) if m in self._ddict: path.append(self._ddict[m]) else: cur_wt -= (m[i] - path[-1][i]) * alpha[i] path.append(m) next = True break # We don't want any dominant weight to refer to itself in self._ddict # as this leads to an infinite loop with self.m() when the dominant # weight does not have a known multiplicity. v = path.pop() for m in path: self._ddict[m] = v return v def _freudenthal_roots_imaginary(self, nu): r""" Iterate over the set of imaginary roots `\alpha \in \Delta^+` in ``self`` such that `\nu - \alpha \in Q^+`. INPUT: - ``nu`` -- an element in `Q` EXAMPLES:: sage: Lambda = RootSystem(['B',3,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]+Lambda[1]+Lambda[3]) sage: [list(V._freudenthal_roots_imaginary(V.highest_weight() - mw)) ....: for mw in V.dominant_maximal_weights()] [[], [], [], [], []] """ l = self._from_weight_helper(nu) kp = min(l[i] // self._a[i] for i in self._index_set) delta = self._Q.null_root() for u in range(1, kp+1): yield u * delta def _freudenthal_roots_real(self, nu): r""" Iterate over the set of real positive roots `\alpha \in \Delta^+` in ``self`` such that `\nu - \alpha \in Q^+`. See [Ka1990]_ Proposition 6.3 for the way to compute the set of real roots for twisted affine case. INPUT: - ``nu`` -- an element in `Q` EXAMPLES:: sage: Lambda = RootSystem(['B',3,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]+Lambda[1]+Lambda[3]) sage: mw = V.dominant_maximal_weights()[0] sage: sorted(V._freudenthal_roots_real(V.highest_weight() - mw), key=str) [alpha[1], alpha[1] + alpha[2], alpha[1] + alpha[2] + alpha[3], alpha[2], alpha[2] + alpha[3], alpha[3]] """ for al in self._classical_positive_roots: if min(self._from_weight_helper(nu-al)) >= 0: yield al if self._cartan_type.is_untwisted_affine(): # untwisted case for al in self._classical_roots: for ir in self._freudenthal_roots_imaginary(nu-al): yield al + ir elif self._cartan_type.type() == 'BC': #case A^2_{2l} # We have to keep track of the roots we have visited for this case ret = set(self._classical_positive_roots) for al in self._classical_roots: if al in self._classical_short_roots: for ir in self._freudenthal_roots_imaginary(nu-al): ret.add(al + ir) yield al + ir else: fri = list(self._freudenthal_roots_imaginary(nu-al)) friset = set(fri) for ir in fri: if 2*ir in friset: ret.add(al + 2*ir) yield al + 2*ir alpha = self._Q.simple_roots() fri = list(self._freudenthal_roots_imaginary(2*nu-al)) for ir in fri[::2]: rt = sum( val // 2 * alpha[i] for i,val in enumerate(self._from_weight_helper(al+ir)) ) if rt not in ret: ret.add(rt) yield rt elif self._cartan_type.dual().type() == 'G': # case D^3_4 in the Kac notation for al in self._classical_roots: if al in self._classical_short_roots: for ir in self._freudenthal_roots_imaginary(nu-al): yield al + ir else: fri = list(self._freudenthal_roots_imaginary(nu-al)) friset = set(fri) for ir in fri: if 3*ir in friset: yield al + 3*ir elif self._cartan_type.dual().type() in ['B','C','F']: #case A^2_{2l-1} or case D^2_{l+1} or case E^2_6: for al in self._classical_roots: if al in self._classical_short_roots: for ir in self._freudenthal_roots_imaginary(nu-al): yield al + ir else: fri = list(self._freudenthal_roots_imaginary(nu-al)) friset = set(fri) for ir in fri: if 2*ir in friset: yield al + 2*ir def _freudenthal_accum(self, nu, al): """ Helper method for computing the Freudenthal formula in ``self``. EXAMPLES:: sage: Lambda = RootSystem(['B',3,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]+Lambda[1]+Lambda[3]) sage: mw = V.dominant_maximal_weights()[0] sage: F = V._freudenthal_roots_real(V.highest_weight() - mw) sage: sorted([V._freudenthal_accum(mw, al) for al in F]) [3, 3, 3, 4, 4, 4] """ ret = 0 n = list(self._from_weight_helper(self._Lam - nu)) ip = self._inner_pq(nu, al) n_shift = self._from_weight_helper(al) ip_shift = self._inner_qq(al, al) while min(n) >= 0: # Change in data by adding ``al`` to our current weight ip += ip_shift for i,val in enumerate(n_shift): n[i] -= val # Compute the multiplicity ret += 2 * self.m(tuple(n)) * ip return ret def _m_freudenthal(self, n): r""" Compute the weight multiplicity using the Freudenthal multiplicity formula in ``self``. The multiplicities of the imaginary roots for the twisted affine case are different than those for the untwisted case. See [Carter]_ Corollary 18.10 for general type and Corollary 18.15 for `A^2_{2l}` EXAMPLES:: sage: Lambda = RootSystem(['B',3,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]+Lambda[1]+Lambda[3]) sage: D = list(V.dominant_maximal_weights()) sage: D.remove(V.highest_weight()) sage: [V._m_freudenthal(V.from_weight(mw)) for mw in D] [3, 7, 3, 3] """ if min(n) < 0: return 0 mu = self.to_weight(n) I = self._index_set al = self._Q._from_dict({I[i]: val for i,val in enumerate(n) if val}, remove_zeros=False) cr = self._classical_rank num = sum(self._freudenthal_accum(mu, alr) for alr in self._freudenthal_roots_real(self._Lam - mu)) if self._cartan_type.is_untwisted_affine(): num += sum(cr * self._freudenthal_accum(mu, alr) for alr in self._freudenthal_roots_imaginary(self._Lam - mu)) elif self._cartan_type.dual().type() == 'B': # A_{2n-1}^{(2)} val = 1 for rt in self._freudenthal_roots_imaginary(self._Lam - mu): # k-th element (starting from 1) is k*delta num += (cr - val) * self._freudenthal_accum(mu, rt) val = 1 - val elif self._cartan_type.type() == 'BC': # A_{2n}^{(2)} num += sum(cr * self._freudenthal_accum(mu, alr) for alr in self._freudenthal_roots_imaginary(self._Lam - mu)) elif self._cartan_type.dual() == 'C': # D_{n+1}^{(2)} val = 1 for rt in self._freudenthal_roots_imaginary(self._Lam - mu): # k-th element (starting from 1) is k*delta num += (cr - (cr - 1)*val) * self._freudenthal_accum(mu, rt) val = 1 - val elif self._cartan_type.dual().type() == 'F': # E_6^{(2)} val = 1 for rt in self._freudenthal_roots_imaginary(self._Lam - mu): # k-th element (starting from 1) is k*delta num += (4 - 2*val) * self._freudenthal_accum(mu, rt) val = 1 - val elif self._cartan_type.dual().type() == 'G': # D_4^{(3)} (or dual of G_2^{(1)}) for k,rt in enumerate(self._freudenthal_roots_imaginary(self._Lam - mu)): # k-th element (starting from 1) is k*delta if (k+1) % 3 == 0: num += 2 * self._freudenthal_accum(mu, rt) else: num += self._freudenthal_accum(mu, rt) den = 2*self._inner_pq(self._Lam_rho, al) - self._inner_qq(al, al) try: return ZZ(num / den) except TypeError: return None def m(self, n): r""" Return the multiplicity of the weight `\mu` in ``self``, where `\mu = \Lambda - \sum_i n_i \alpha_i`. INPUT: - ``n`` -- a tuple representing a weight `\mu`. EXAMPLES:: sage: Lambda = RootSystem(['E',6,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]) sage: u = V.highest_weight() - V.weight_lattice().null_root() sage: V.from_weight(u) (1, 1, 2, 2, 3, 2, 1) sage: V.m(V.from_weight(u)) 6 """ # TODO: Make this non-recursive by implementing our own stack # The recursion follows: # - m # - _m_freudenthal # - _freudenthal_accum if n in self._mdict: return self._mdict[n] elif n in self._ddict: self._mdict[n] = self.m(self._ddict[n]) m = self.to_dominant(n) if m in self._mdict: return self._mdict[m] ret = self._m_freudenthal(m) assert ret is not None, "m: error - failed to compute m{}".format(n) self._mdict[n] = ret return ret def mult(self, mu): """ Return the weight multiplicity of ``mu``. INPUT: - ``mu`` -- an element of the weight lattice EXAMPLES:: sage: L = RootSystem("B3~").weight_lattice(extended=True) sage: Lambda = L.fundamental_weights() sage: delta = L.null_root() sage: W = L.weyl_group(prefix="s") sage: [s0,s1,s2,s3] = W.simple_reflections() sage: V = IntegrableRepresentation(Lambda[0]) sage: V.mult(Lambda[2]-2*delta) 3 sage: V.mult(Lambda[2]-Lambda[1]) 0 sage: weights = [w.action(Lambda[1]-4*delta) for w in [s1,s2,s0*s1*s2*s3]] sage: weights [-Lambda[1] + Lambda[2] - 4*delta, Lambda[1] - 4*delta, -Lambda[1] + Lambda[2] - 4*delta] sage: [V.mult(mu) for mu in weights] [35, 35, 35] TESTS:: sage: L = RootSystem("B3~").weight_lattice(extended=True) sage: La = L.fundamental_weights() sage: V = IntegrableRepresentation(La[0]) sage: Q = RootSystem("B3~").root_space() sage: al = Q.simple_roots() sage: V.mult(1/2*al[1]) 0 """ try: n = self.from_weight(mu) except TypeError: return ZZ.zero() return self.m(n) @cached_method def dominant_maximal_weights(self): r""" Return the dominant maximal weights of ``self``. A weight `\mu` is *maximal* if it has nonzero multiplicity but `\mu + \delta`` has multiplicity zero. There are a finite number of dominant maximal weights. Indeed, [Ka1990]_ Proposition 12.6 shows that the dominant maximal weights are in bijection with the classical weights in `k \cdot F` where `F` is the fundamental alcove and `k` is the level. The construction used in this method is based on that Proposition. EXAMPLES:: sage: Lambda = RootSystem(['C',3,1]).weight_lattice(extended=true).fundamental_weights() sage: IntegrableRepresentation(2*Lambda[0]).dominant_maximal_weights() (2*Lambda[0], Lambda[0] + Lambda[2] - delta, 2*Lambda[1] - delta, Lambda[1] + Lambda[3] - 2*delta, 2*Lambda[2] - 2*delta, 2*Lambda[3] - 3*delta) """ k = self.level() Lambda = self._P.fundamental_weights() def next_level(wt): return [wt + Lambda[i] for i in self._index_set_classical if (wt + Lambda[i]).level() <= k] R = RecursivelyEnumeratedSet([self._P.zero()], next_level) candidates = [x + (k - x.level())*Lambda[0] for x in list(R)] ret = [] delta = self._Q.null_root() for x in candidates: if self._from_weight_helper(self._Lam-x, check=True): t = 0 while self.m(self.from_weight(x - t*delta)) == 0: t += 1 ret.append(x - t*delta) return tuple(ret) def string(self, max_weight, depth=12): r""" Return the list of multiplicities `m(\Lambda - k \delta)` in ``self``, where `\Lambda` is ``max_weight`` and `k` runs from `0` to ``depth``. INPUT: - ``max_weight`` -- a dominant maximal weight - ``depth`` -- (default: 12) the maximum value of `k` EXAMPLES:: sage: Lambda = RootSystem(['A',2,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(2*Lambda[0]) sage: V.string(2*Lambda[0]) [1, 2, 8, 20, 52, 116, 256, 522, 1045, 1996, 3736, 6780] sage: V.string(Lambda[1] + Lambda[2]) [0, 1, 4, 12, 32, 77, 172, 365, 740, 1445, 2736, 5041] """ ret = [] delta = self._Q.null_root() cur_weight = max_weight for k in range(depth): ret.append(self.m( self.from_weight(cur_weight) )) cur_weight -= delta return ret def strings(self, depth=12): """ Return the set of dominant maximal weights of ``self``, together with the string coefficients for each. OPTIONAL: - ``depth`` -- (default: 12) a parameter indicating how far to push computations EXAMPLES:: sage: Lambda = RootSystem(['A',1,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(2*Lambda[0]) sage: S = V.strings(depth=25) sage: for k in S: ....: print("{}: {}".format(k, ' '.join(str(x) for x in S[k]))) 2*Lambda[0]: 1 1 3 5 10 16 28 43 70 105 161 236 350 501 722 1016 1431 1981 2741 3740 5096 6868 9233 12306 16357 2*Lambda[1] - delta: 1 2 4 7 13 21 35 55 86 130 196 287 420 602 858 1206 1687 2331 3206 4368 5922 7967 10670 14193 18803 """ return {max_weight: self.string(max_weight, depth) for max_weight in self.dominant_maximal_weights()} def print_strings(self, depth=12): """ Print the strings of ``self``. .. SEEALSO:: :meth:`strings` EXAMPLES:: sage: Lambda = RootSystem(['A',1,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(2*Lambda[0]) sage: V.print_strings(depth=25) 2*Lambda[0]: 1 1 3 5 10 16 28 43 70 105 161 236 350 501 722 1016 1431 1981 2741 3740 5096 6868 9233 12306 16357 2*Lambda[1] - delta: 1 2 4 7 13 21 35 55 86 130 196 287 420 602 858 1206 1687 2331 3206 4368 5922 7967 10670 14193 18803 """ S = self.strings(depth=depth) for mw in self.dominant_maximal_weights(): print("{}: {}".format(mw, ' '.join(str(x) for x in S[mw])) ) def modular_characteristic(self, mu=None): r""" Return the modular characteristic of ``self``. The modular characteristic is a rational number introduced by Kac and Peterson [KacPeterson]_, required to interpret the string functions as Fourier coefficients of modular forms. See [Ka1990]_ Section 12.7. Let `k` be the level, and let `h^\vee` be the dual Coxeter number. Then .. MATH:: m_\Lambda = \frac{|\Lambda+\rho|^2}{2(k+h^\vee)} - \frac{|\rho|^2}{2h^\vee} If `\mu` is a weight, then .. MATH:: m_{\Lambda,\mu} = m_\Lambda - \frac{|\mu|^2}{2k}. OPTIONAL: - ``mu`` -- a weight; or alternatively: - ``n`` -- a tuple representing a weight `\mu`. If no optional parameter is specified, this returns `m_\Lambda`. If ``mu`` is specified, it returns `m_{\Lambda,\mu}`. You may use the tuple ``n`` to specify `\mu`. If you do this, `\mu` is `\Lambda - \sum_i n_i \alpha_i`. EXAMPLES:: sage: Lambda = RootSystem(['A',1,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(3*Lambda[0]+2*Lambda[1]) sage: [V.modular_characteristic(x) for x in V.dominant_maximal_weights()] [11/56, -1/280, 111/280] """ if type(mu) is tuple: n = mu else: n = self.from_weight(mu) k = self.level() hd = self.dual_coxeter_number() rho = self._P.rho() m_Lambda = self._inner_pp(self._Lam_rho, self._Lam_rho) / (2*(k+hd)) \ - self._inner_pp(rho, rho) / (2*hd) if n is None: return m_Lambda mu = self.to_weight(n) return m_Lambda - self._inner_pp(mu,mu) / (2*k) def branch(self, i=None, weyl_character_ring=None, sequence=None, depth=5): r""" Return the branching rule on ``self``. Removing any node from the extended Dynkin diagram of the affine Lie algebra results in the Dynkin diagram of a classical Lie algebra, which is therefore a Lie subalgebra. For example removing the `0` node from the Dynkin diagram of type ``[X, r, 1]`` produces the classical Dynkin diagram of ``[X, r]``. Thus for each `i` in the index set, we may restrict ``self`` to the corresponding classical subalgebra. Of course ``self`` is an infinite dimensional representation, but each weight `\mu` is assigned a grading by the number of times the simple root `\alpha_i` appears in `\Lambda-\mu`. Thus the branched representation is graded and we get sequence of finite-dimensional representations which this method is able to compute. OPTIONAL: - ``i`` -- (default: 0) an element of the index set - ``weyl_character_ring`` -- a WeylCharacterRing - ``sequence`` -- a dictionary - ``depth`` -- (default: 5) an upper bound for `k` determining how many terms to give In the default case where `i = 0`, you do not need to specify anything else, though you may want to increase the depth if you need more terms. EXAMPLES:: sage: Lambda = RootSystem(['A',2,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(2*Lambda[0]) sage: b = V.branch(); b [A2(0,0), A2(1,1), A2(0,0) + 2*A2(1,1) + A2(2,2), 2*A2(0,0) + 2*A2(0,3) + 4*A2(1,1) + 2*A2(3,0) + 2*A2(2,2), 4*A2(0,0) + 3*A2(0,3) + 10*A2(1,1) + 3*A2(3,0) + A2(1,4) + 6*A2(2,2) + A2(4,1), 6*A2(0,0) + 9*A2(0,3) + 20*A2(1,1) + 9*A2(3,0) + 3*A2(1,4) + 12*A2(2,2) + 3*A2(4,1) + A2(3,3)] If the parameter ``weyl_character_ring`` is omitted, the ring may be recovered as the parent of one of the branched coefficients:: sage: A2 = b[0].parent(); A2 The Weyl Character Ring of Type A2 with Integer Ring coefficients If `i` is not zero then you should specify the :class:`WeylCharacterRing` that you are branching to. This is determined by the Dynkin diagram:: sage: Lambda = RootSystem(['B',3,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]) sage: V.cartan_type().dynkin_diagram() O 0 | | O---O=>=O 1 2 3 B3~ In this example, we observe that removing the `i=2` node from the Dynkin diagram produces a reducible diagram of type ``A1xA1xA1``. Thus we have a branching to `\mathfrak{sl}(2) \times \mathfrak{sl}(2) \times \mathfrak{sl}(2)`:: sage: A1xA1xA1 = WeylCharacterRing("A1xA1xA1",style="coroots") sage: V.branch(i=2,weyl_character_ring=A1xA1xA1) [A1xA1xA1(1,0,0), A1xA1xA1(0,1,2), A1xA1xA1(1,0,0) + A1xA1xA1(1,2,0) + A1xA1xA1(1,0,2), A1xA1xA1(2,1,2) + A1xA1xA1(0,1,0) + 2*A1xA1xA1(0,1,2), 3*A1xA1xA1(1,0,0) + 2*A1xA1xA1(1,2,0) + A1xA1xA1(1,2,2) + 2*A1xA1xA1(1,0,2) + A1xA1xA1(1,0,4) + A1xA1xA1(3,0,0), A1xA1xA1(2,1,0) + 3*A1xA1xA1(2,1,2) + 2*A1xA1xA1(0,1,0) + 5*A1xA1xA1(0,1,2) + A1xA1xA1(0,1,4) + A1xA1xA1(0,3,2)] If the nodes of the two Dynkin diagrams are not in the same order, you must specify an additional parameter, ``sequence`` which gives a dictionary to the affine Dynkin diagram to the classical one. EXAMPLES:: sage: Lambda = RootSystem(['F',4,1]).weight_lattice(extended=true).fundamental_weights() sage: V = IntegrableRepresentation(Lambda[0]) sage: V.cartan_type().dynkin_diagram() O---O---O=>=O---O 0 1 2 3 4 F4~ sage: A1xC3=WeylCharacterRing("A1xC3",style="coroots") sage: A1xC3.dynkin_diagram() O 1 O---O=<=O 2 3 4 A1xC3 Observe that removing the `i=1` node from the ``F4~`` Dynkin diagram gives the ``A1xC3`` diagram, but the roots are in a different order. The nodes `0, 2, 3, 4` of ``F4~`` correspond to ``1, 4, 3, 2`` of ``A1xC3`` and so we encode this in a dictionary:: sage: V.branch(i=1,weyl_character_ring=A1xC3,sequence={0:1,2:4,3:3,4:2}) # long time [A1xC3(1,0,0,0), A1xC3(0,0,0,1), A1xC3(1,0,0,0) + A1xC3(1,2,0,0), A1xC3(2,0,0,1) + A1xC3(0,0,0,1) + A1xC3(0,1,1,0), 2*A1xC3(1,0,0,0) + A1xC3(1,0,1,0) + 2*A1xC3(1,2,0,0) + A1xC3(1,0,2,0) + A1xC3(3,0,0,0), 2*A1xC3(2,0,0,1) + A1xC3(2,1,1,0) + A1xC3(0,1,0,0) + 3*A1xC3(0,0,0,1) + 2*A1xC3(0,1,1,0) + A1xC3(0,2,0,1)] The branch method gives a way of computing the graded dimension of the integrable representation:: sage: Lambda = RootSystem("A1~").weight_lattice(extended=true).fundamental_weights() sage: V=IntegrableRepresentation(Lambda[0]) sage: r = [x.degree() for x in V.branch(depth=15)]; r [1, 3, 4, 7, 13, 19, 29, 43, 62, 90, 126, 174, 239, 325, 435, 580] sage: oeis(r) # optional -- internet 0: A029552: Expansion of phi(x) / f(-x) in powers of x where phi(), f() are Ramanujan theta functions. """ if i is None: i = self._cartan_type.special_node() if i == self._cartan_type.special_node() or self._cartan_type.type() == 'A': if weyl_character_ring is None: weyl_character_ring = WeylCharacterRing(self._cartan_type.classical(), style="coroots") if weyl_character_ring.cartan_type() != self._cartan_type.classical(): raise ValueError("Cartan type of WeylCharacterRing must be %s" % self.cartan_type().classical()) elif weyl_character_ring is None: raise ValueError("the argument weyl_character_ring cannot be omitted if i != 0") if sequence is None: sequence = {} for j in self._index_set: if j < i: sequence[j] = j+1 elif j > i: sequence[j] = j def next_level(x): ret = [] for j in self._index_set: t = list(x[0]) t[j] += 1 t = tuple(t) m = self.m(t) if m > 0 and t[i] <= depth: ret.append((t,m)) return ret hwv = (tuple([0 for j in self._index_set]), 1) terms = RecursivelyEnumeratedSet([hwv], next_level) fw = weyl_character_ring.fundamental_weights() P = self.weight_lattice() ret = [] for l in range(depth+1): lterms = [x for x in terms if x[0][i] == l] ldict = {} for x in lterms: mc = P(self.to_weight(x[0])).monomial_coefficients() contr = sum(fw[sequence[j]]*mc.get(j,0) for j in self._index_set if j != i).coerce_to_sl() if contr in ldict: ldict[contr] += x[1] else: ldict[contr] = x[1] ret.append(weyl_character_ring.char_from_weights(ldict)) return ret
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/integrable_representations.py
0.762954
0.676039
integrable_representations.py
pypi
from . import ambient_space class AmbientSpace(ambient_space.AmbientSpace): """ EXAMPLES:: sage: e = RootSystem(['C',2]).ambient_space(); e Ambient space of the Root system of type ['C', 2] One cannot construct the ambient lattice because the fundamental coweights have rational coefficients:: sage: e.smallest_base_ring() Rational Field sage: RootSystem(['B',2]).ambient_space().fundamental_weights() Finite family {1: (1, 0), 2: (1/2, 1/2)} TESTS:: sage: TestSuite(e).run() """ def dimension(self): """ EXAMPLES:: sage: e = RootSystem(['C',3]).ambient_space() sage: e.dimension() 3 """ return self.root_system.cartan_type().rank() def root(self, i, j, p1, p2): """ Note that indexing starts at 0. EXAMPLES:: sage: e = RootSystem(['C',3]).ambient_space() sage: e.root(0, 1, 1, 1) (-1, -1, 0) """ return (-1)**p1 * self.monomial(i) + (-1)**p2 * self.monomial(j) def simple_root(self, i): """ EXAMPLES:: sage: RootSystem(['C',3]).ambient_space().simple_roots() Finite family {1: (1, -1, 0), 2: (0, 1, -1), 3: (0, 0, 2)} """ if i not in self.index_set(): raise ValueError("{} is not in the index set".format(i)) return self.root(i-1, i,0,1) if i < self.n else self.root(self.n-1, self.n-1, 0, 0) def positive_roots(self): """ EXAMPLES:: sage: RootSystem(['C',3]).ambient_space().positive_roots() [(1, 1, 0), (1, 0, 1), (0, 1, 1), (1, -1, 0), (1, 0, -1), (0, 1, -1), (2, 0, 0), (0, 2, 0), (0, 0, 2)] """ res = [] for p in [0,1]: for j in range(self.n): res.extend([self.root(i,j,0,p) for i in range(j)]) res.extend([self.root(i,i,0,0) for i in range(self.n)]) return res def negative_roots(self): """ EXAMPLES:: sage: RootSystem(['C',3]).ambient_space().negative_roots() [(-1, 1, 0), (-1, 0, 1), (0, -1, 1), (-1, -1, 0), (-1, 0, -1), (0, -1, -1), (-2, 0, 0), (0, -2, 0), (0, 0, -2)] """ res = [] for p in [0,1]: for j in range(self.n): res.extend( [self.root(i,j,1,p) for i in range(j) ] ) res.extend( [ self.root(i,i,1,1) for i in range(self.n) ] ) return res def fundamental_weight(self, i): """ EXAMPLES:: sage: RootSystem(['C',3]).ambient_space().fundamental_weights() Finite family {1: (1, 0, 0), 2: (1, 1, 0), 3: (1, 1, 1)} """ return self.sum(self.monomial(j) for j in range(i)) from .cartan_type import CartanType_standard_finite, CartanType_simple, CartanType_crystallographic, CartanType_simply_laced class CartanType(CartanType_standard_finite, CartanType_simple, CartanType_crystallographic): def __init__(self, n): """ EXAMPLES:: sage: ct = CartanType(['C',4]) sage: ct ['C', 4] sage: ct._repr_(compact = True) 'C4' sage: ct.is_irreducible() True sage: ct.is_finite() True sage: ct.is_crystallographic() True sage: ct.is_simply_laced() False sage: ct.affine() ['C', 4, 1] sage: ct.dual() ['B', 4] sage: ct = CartanType(['C',1]) sage: ct.is_simply_laced() True sage: ct.affine() ['C', 1, 1] TESTS:: sage: TestSuite(ct).run() """ assert n >= 1 CartanType_standard_finite.__init__(self, "C", n) if n == 1: self._add_abstract_superclass(CartanType_simply_laced) def _latex_(self): """ Return a latex representation of ``self``. EXAMPLES:: sage: latex(CartanType(['C',4])) C_{4} """ return "C_{%s}" % self.n AmbientSpace = AmbientSpace def coxeter_number(self): """ Return the Coxeter number associated with ``self``. EXAMPLES:: sage: CartanType(['C',4]).coxeter_number() 8 """ return 2*self.n def dual_coxeter_number(self): """ Return the dual Coxeter number associated with ``self``. EXAMPLES:: sage: CartanType(['C',4]).dual_coxeter_number() 5 """ return self.n + 1 def dual(self): """ Types B and C are in duality: EXAMPLES:: sage: CartanType(["C", 3]).dual() ['B', 3] """ from . import cartan_type return cartan_type.CartanType(["B", self.n]) def dynkin_diagram(self): """ Returns a Dynkin diagram for type C. EXAMPLES:: sage: c = CartanType(['C',3]).dynkin_diagram() sage: c O---O=<=O 1 2 3 C3 sage: c.edges(sort=True) [(1, 2, 1), (2, 1, 1), (2, 3, 1), (3, 2, 2)] sage: b = CartanType(['C',1]).dynkin_diagram() sage: b O 1 C1 sage: b.edges(sort=True) [] """ return self.dual().dynkin_diagram().dual() def _latex_dynkin_diagram(self, label=lambda x: x, node=None, node_dist=2, dual=False): r""" Return a latex representation of the Dynkin diagram. EXAMPLES:: sage: print(CartanType(['C',4])._latex_dynkin_diagram()) \draw (0 cm,0) -- (4 cm,0); \draw (4 cm, 0.1 cm) -- +(2 cm,0); \draw (4 cm, -0.1 cm) -- +(2 cm,0); \draw[shift={(4.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; <BLANKLINE> When ``dual=True``, the Dynkin diagram for the dual Cartan type `B_n` is returned:: sage: print(CartanType(['C',4])._latex_dynkin_diagram(dual=True)) \draw (0 cm,0) -- (4 cm,0); \draw (4 cm, 0.1 cm) -- +(2 cm,0); \draw (4 cm, -0.1 cm) -- +(2 cm,0); \draw[shift={(5.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm); \draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$}; \draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$}; \draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$}; \draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$}; <BLANKLINE> .. SEEALSO:: - :meth:`sage.combinat.root_system.type_C.CartanType._latex_dynkin_diagram` - :meth:`sage.combinat.root_system.type_BC_affine.CartanType._latex_dynkin_diagram` """ return self.dual()._latex_dynkin_diagram(label=label, node=node, node_dist=node_dist, dual=not dual) def ascii_art(self, label=lambda i: i, node=None): """ Return a ascii art representation of the extended Dynkin diagram. EXAMPLES:: sage: print(CartanType(['C',1]).ascii_art()) O 1 sage: print(CartanType(['C',2]).ascii_art()) O=<=O 1 2 sage: print(CartanType(['C',3]).ascii_art()) O---O=<=O 1 2 3 sage: print(CartanType(['C',5]).ascii_art(label = lambda x: x+2)) O---O---O---O=<=O 3 4 5 6 7 """ return self.dual().ascii_art(label=label, node=node).replace("=>=", "=<=") def _default_folded_cartan_type(self): """ Return the default folded Cartan type. EXAMPLES:: sage: CartanType(['C', 3])._default_folded_cartan_type() ['C', 3] as a folding of ['A', 5] """ from sage.combinat.root_system.type_folded import CartanTypeFolded n = self.n return CartanTypeFolded(self, ['A', 2*n-1], [[i, 2*n-i] for i in range(1, n)] + [[n]]) # For unpickling backward compatibility (Sage <= 4.1) from sage.misc.persist import register_unpickle_override register_unpickle_override('sage.combinat.root_system.type_C', 'ambient_space', AmbientSpace)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/root_system/type_C.py
0.852045
0.584894
type_C.py
pypi
from sage.combinat.posets.posets import Poset, FinitePoset from sage.misc.lazy_attribute import lazy_attribute from .linear_extensions import LinearExtensionsOfMobile class MobilePoset(FinitePoset): r""" A mobile poset. Mobile posets are an extension of d-complete posets which permit a determinant formula for counting linear extensions. They are formed by having a ribbon poset with d-complete posets 'hanging' below it and at most one d-complete poset above it, known as the anchor. See [GGMM2020]_ for the definition. EXAMPLES:: sage: P = posets.MobilePoset(posets.RibbonPoset(7, [1,3]), ....: {1: [posets.YoungDiagramPoset([3, 2], dual=True)], ....: 3: [posets.DoubleTailedDiamond(6)]}, ....: anchor=(4, 2, posets.ChainPoset(6))) sage: len(P._ribbon) 8 sage: P._anchor (4, 5) This example is Example 5.9 in [GGMM2020]_:: sage: P1 = posets.MobilePoset(posets.RibbonPoset(8, [2,3,4]), ....: {4: [posets.ChainPoset(1)]}, ....: anchor=(3, 0, posets.ChainPoset(1))) sage: sorted([P1._element_to_vertex(i) for i in P1._ribbon]) [0, 1, 2, 6, 7, 9] sage: P1._anchor (3, 2) sage: P2 = posets.MobilePoset(posets.RibbonPoset(15, [1,3,5,7,9,11,13]), ....: {}, anchor=(8, 0, posets.ChainPoset(1))) sage: sorted(P2._ribbon) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] sage: P2._anchor (8, (8, 0)) sage: P2.linear_extensions().cardinality() 21399440939 sage: EP = posets.MobilePoset(posets.ChainPoset(0), {}) Traceback (most recent call last): ... ValueError: the empty poset is not a mobile poset """ _lin_ext_type = LinearExtensionsOfMobile _desc = 'Finite mobile poset' def __init__(self, hasse_diagram, elements, category, facade, key, ribbon=None, check=True): r""" Initialize ``self``. EXAMPLES:: sage: P = posets.MobilePoset(posets.RibbonPoset(15, [1,3,5,7,9,11,13]), ....: {}, anchor=(8, 0, posets.ChainPoset(1))) sage: TestSuite(P).run() """ FinitePoset.__init__(self, hasse_diagram=hasse_diagram, elements=elements, category=category, facade=facade, key=key) if not self._hasse_diagram: raise ValueError("the empty poset is not a mobile poset") if ribbon: if check and not self._is_valid_ribbon(ribbon): raise ValueError("invalid ribbon") self._ribbon = ribbon def _is_valid_ribbon(self, ribbon): r""" Return ``True`` if a ribbon has at most one anchor, no vertex has two or more anchors, and every hanging poset is d-complete. INPUT: - ``ribbon`` -- a list of elements that form a ribbon in your poset TESTS:: sage: P = posets.RibbonPoset(5, [2]) sage: P._is_valid_ribbon([0,1,2,3,4]) True sage: P._is_valid_ribbon([2]) False sage: P._is_valid_ribbon([2,3,4]) True sage: P._is_valid_ribbon([2,3]) True """ ribbon = [self._element_to_vertex(x) for x in ribbon] G = self._hasse_diagram G_un = G.to_undirected().copy(immutable=False) R = G.subgraph(ribbon) num_anchors = 0 for r in ribbon: anchor_neighbors = set(G.neighbors_out(r)).difference(set(R.neighbors_out(r))) if len(anchor_neighbors) == 1: num_anchors += 1 elif len(anchor_neighbors) > 1: return False for lc in G.neighbors_in(r): if lc in ribbon: continue G_un.delete_edge(lc, r) P = Poset(G.subgraph(G_un.connected_component_containing_vertex(lc))) if P.top() != lc or not P.is_d_complete(): return False G_un.add_edge(lc, r) return True @lazy_attribute def _anchor(self): r""" The anchor of the mobile poset. TESTS:: sage: from sage.combinat.posets.mobile import MobilePoset sage: M = MobilePoset(DiGraph([[0,1,2,3,4,5,6,7,8], ....: [(1,0),(3,0),(2,1),(2,3),(4,3), (5,4),(5,6),(7,4),(7,8)]])) sage: M._anchor (4, 3) """ ribbon = [self._element_to_vertex(x) for x in self._ribbon] H = self._hasse_diagram R = H.subgraph(ribbon) anchor = None # Find the anchor vertex, if it exists, and return the edge for r in ribbon: anchor_neighbors = set(H.neighbors_out(r)).difference(set(R.neighbors_out(r))) if len(anchor_neighbors) == 1: anchor = (r, anchor_neighbors.pop()) break return (self._vertex_to_element(anchor[0]), self._vertex_to_element(anchor[1])) if anchor is not None else None @lazy_attribute def _ribbon(self): r""" The ribbon of the mobile poset. TESTS:: sage: from sage.combinat.posets.mobile import MobilePoset sage: M = MobilePoset(DiGraph([[0,1,2,3,4,5,6,7,8], ....: [(1,0),(3,0),(2,1),(2,3),(4,3), (5,4),(5,6),(7,4),(7,8)]])) sage: sorted(M._ribbon) [4, 5, 6, 7, 8] sage: M._is_valid_ribbon(M._ribbon) True sage: M2 = MobilePoset(Poset([[0,1,2,3,4,5,6,7,8], ....: [(1,0),(3,0),(2,1),(2,3),(4,3),(5,4),(7,4),(7,8)]])) sage: sorted(M2._ribbon) [4, 7, 8] sage: M2._is_valid_ribbon(M2._ribbon) True """ H = self._hasse_diagram H_un = H.to_undirected() max_elmts = H.sinks() # Compute anchor, ribbon ribbon = [] # In order list of elements on zigzag if len(max_elmts) == 1: return [self._vertex_to_element(max_elmts[0])] # Compute max element tree by merging shortest paths start = max_elmts[0] zigzag_elmts = set() for m in max_elmts[1:]: sp = H_un.shortest_path(start, m) zigzag_elmts.update(sp) max_elmt_graph = H.subgraph(zigzag_elmts) G = max_elmt_graph.to_undirected() if G.is_path(): # Check if there is a anchor by seeing if there is more than one acyclic path to the next max ends = max_elmt_graph.vertices(sort=True, degree=1) # Form ribbon ribbon = G.shortest_path(ends[0], ends[1]) for end_count, end in enumerate(ends): if not (H_un.is_cut_vertex(end) or H_un.degree(end) == 1): traverse_ribbon = ribbon if end_count == 0 else ribbon[::-1] for ind, p in enumerate(traverse_ribbon): if H_un.is_cut_edge(p, traverse_ribbon[ind + 1]): return [self._vertex_to_element(r) for r in G.shortest_path(ends[(end_count + 1) % 2], traverse_ribbon[ind + 1])] return [self._vertex_to_element(r) for r in ribbon] # First check path counts between ends and deg3 vertex # Then check if more than one max elmt on way to degree 3 vertex. # Then check if the edge going to a max element is down from the degree 3 vertex # Arbitrarily choose between ones with just 1 ends = max_elmt_graph.vertices(sort=True, degree=1) deg3 = max_elmt_graph.vertices(sort=True, degree=3)[0] anchoredEnd = None for end in ends: if not (H_un.is_cut_vertex(end) or H_un.degree(end) == 1): anchoredEnd = end break if anchoredEnd is not None: ends.remove(anchoredEnd) return [self._vertex_to_element(r) for r in G.shortest_path(ends[0], ends[1])] possible_anchors = ends[:] for end in ends: path = G.shortest_path(end, deg3) if sum(bool(z in max_elmts) for z in path) != 1: possible_anchors.remove(end) for p in possible_anchors: path = G.shortest_path(p, deg3) if max_elmt_graph.has_edge(path[-2], path[-1]): possible_anchors.remove(p) anchoredEnd = possible_anchors[0] ends.remove(anchoredEnd) return [self._vertex_to_element(r) for r in G.shortest_path(ends[0], ends[1])] def ribbon(self): r""" Return the ribbon of the mobile poset. EXAMPLES:: sage: from sage.combinat.posets.mobile import MobilePoset sage: M3 = MobilePoset(Posets.RibbonPoset(5, [1,2])) sage: sorted(M3.ribbon()) [1, 2, 3, 4] """ return self._ribbon def anchor(self): r""" Return the anchor of the mobile poset. EXAMPLES:: sage: from sage.combinat.posets.mobile import MobilePoset sage: M2 = MobilePoset(Poset([[0,1,2,3,4,5,6,7,8], ....: [(1,0),(3,0),(2,1),(2,3),(4,3),(5,4),(7,4),(7,8)]])) sage: M2.anchor() (4, 3) sage: M3 = MobilePoset(Posets.RibbonPoset(5, [1,2])) sage: M3.anchor() is None True """ return self._anchor
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/posets/mobile.py
0.847463
0.705164
mobile.py
pypi
from sage.sets.cartesian_product import CartesianProduct class CartesianProductPoset(CartesianProduct): r""" A class implementing Cartesian products of posets (and elements thereof). Compared to :class:`CartesianProduct` you are able to specify an order for comparison of the elements. INPUT: - ``sets`` -- a tuple of parents. - ``category`` -- a subcategory of ``Sets().CartesianProducts() & Posets()``. - ``order`` -- a string or function specifying an order less or equal. It can be one of the following: - ``'native'`` -- elements are ordered by their native ordering, i.e., the order the wrapped elements (tuples) provide. - ``'lex'`` -- elements are ordered lexicographically. - ``'product'`` -- an element is less or equal to another element, if less or equal is true for all its components (Cartesian projections). - A function which performs the comparison `\leq`. It takes two input arguments and outputs a boolean. Other keyword arguments (``kwargs``) are passed to the constructor of :class:`CartesianProduct`. EXAMPLES:: sage: P = Poset((srange(3), lambda left, right: left <= right)) sage: Cl = cartesian_product((P, P), order='lex') sage: Cl((1, 1)) <= Cl((2, 0)) True sage: Cp = cartesian_product((P, P), order='product') sage: Cp((1, 1)) <= Cp((2, 0)) False sage: def le_sum(left, right): ....: return (sum(left) < sum(right) or ....: sum(left) == sum(right) and left[0] <= right[0]) sage: Cs = cartesian_product((P, P), order=le_sum) sage: Cs((1, 1)) <= Cs((2, 0)) True TESTS:: sage: Cl.category() Join of Category of finite posets and Category of Cartesian products of finite enumerated sets sage: TestSuite(Cl).run(skip=['_test_construction']) sage: Cp.category() Join of Category of finite posets and Category of Cartesian products of finite enumerated sets sage: TestSuite(Cp).run(skip=['_test_construction']) .. SEEALSO:: :class:`CartesianProduct` """ def __init__(self, sets, category, order=None, **kwargs): r""" See :class:`CartesianProductPoset` for details. TESTS:: sage: P = Poset((srange(3), lambda left, right: left <= right)) sage: C = cartesian_product((P, P), order='notexisting') Traceback (most recent call last): ... ValueError: no order 'notexisting' known sage: C = cartesian_product((P, P), category=(Groups(),)) sage: C.category() Join of Category of groups and Category of posets """ if order is None: self._le_ = self.le_product elif isinstance(order, str): try: self._le_ = getattr(self, 'le_' + order) except AttributeError: raise ValueError("no order '%s' known" % (order,)) else: self._le_ = order from sage.categories.category import Category from sage.categories.posets import Posets if not isinstance(category, tuple): category = (category,) category = Category.join(category + (Posets(),)) super().__init__(sets, category, **kwargs) def le(self, left, right): r""" Test whether ``left`` is less than or equal to ``right``. INPUT: - ``left`` -- an element. - ``right`` -- an element. OUTPUT: A boolean. .. NOTE:: This method uses the order defined on creation of this Cartesian product. See :class:`CartesianProductPoset`. EXAMPLES:: sage: P = posets.ChainPoset(10) sage: def le_sum(left, right): ....: return (sum(left) < sum(right) or ....: sum(left) == sum(right) and left[0] <= right[0]) sage: C = cartesian_product((P, P), order=le_sum) sage: C.le(C((1, 6)), C((6, 1))) True sage: C.le(C((6, 1)), C((1, 6))) False sage: C.le(C((1, 6)), C((6, 6))) True sage: C.le(C((6, 6)), C((1, 6))) False """ return self._le_(left, right) def le_lex(self, left, right): r""" Test whether ``left`` is lexicographically smaller or equal to ``right``. INPUT: - ``left`` -- an element. - ``right`` -- an element. OUTPUT: A boolean. EXAMPLES:: sage: P = Poset((srange(2), lambda left, right: left <= right)) sage: Q = cartesian_product((P, P), order='lex') sage: T = [Q((0, 0)), Q((1, 1)), Q((0, 1)), Q((1, 0))] sage: for a in T: ....: for b in T: ....: assert(Q.le(a, b) == (a <= b)) ....: print('%s <= %s = %s' % (a, b, a <= b)) (0, 0) <= (0, 0) = True (0, 0) <= (1, 1) = True (0, 0) <= (0, 1) = True (0, 0) <= (1, 0) = True (1, 1) <= (0, 0) = False (1, 1) <= (1, 1) = True (1, 1) <= (0, 1) = False (1, 1) <= (1, 0) = False (0, 1) <= (0, 0) = False (0, 1) <= (1, 1) = True (0, 1) <= (0, 1) = True (0, 1) <= (1, 0) = True (1, 0) <= (0, 0) = False (1, 0) <= (1, 1) = True (1, 0) <= (0, 1) = False (1, 0) <= (1, 0) = True TESTS: Check that :trac:`19999` is resolved:: sage: P = Poset((srange(2), lambda left, right: left <= right)) sage: Q = cartesian_product((P, P), order='product') sage: R = cartesian_product((Q, P), order='lex') sage: R(((1, 0), 0)) <= R(((0, 1), 0)) False sage: R(((0, 1), 0)) <= R(((1, 0), 0)) False """ for l, r, S in \ zip(left.value, right.value, self.cartesian_factors()): if l == r: continue if S.le(l, r): return True if S.le(r, l): return False return False # incomparable components return True # equal def le_product(self, left, right): r""" Test whether ``left`` is component-wise smaller or equal to ``right``. INPUT: - ``left`` -- an element. - ``right`` -- an element. OUTPUT: A boolean. The comparison is ``True`` if the result of the comparison in each component is ``True``. EXAMPLES:: sage: P = Poset((srange(2), lambda left, right: left <= right)) sage: Q = cartesian_product((P, P), order='product') sage: T = [Q((0, 0)), Q((1, 1)), Q((0, 1)), Q((1, 0))] sage: for a in T: ....: for b in T: ....: assert(Q.le(a, b) == (a <= b)) ....: print('%s <= %s = %s' % (a, b, a <= b)) (0, 0) <= (0, 0) = True (0, 0) <= (1, 1) = True (0, 0) <= (0, 1) = True (0, 0) <= (1, 0) = True (1, 1) <= (0, 0) = False (1, 1) <= (1, 1) = True (1, 1) <= (0, 1) = False (1, 1) <= (1, 0) = False (0, 1) <= (0, 0) = False (0, 1) <= (1, 1) = True (0, 1) <= (0, 1) = True (0, 1) <= (1, 0) = False (1, 0) <= (0, 0) = False (1, 0) <= (1, 1) = True (1, 0) <= (0, 1) = False (1, 0) <= (1, 0) = True """ return all( S.le(l, r) for l, r, S in zip(left.value, right.value, self.cartesian_factors())) def le_native(self, left, right): r""" Test whether ``left`` is smaller or equal to ``right`` in the order provided by the elements themselves. INPUT: - ``left`` -- an element. - ``right`` -- an element. OUTPUT: A boolean. EXAMPLES:: sage: P = Poset((srange(2), lambda left, right: left <= right)) sage: Q = cartesian_product((P, P), order='native') sage: T = [Q((0, 0)), Q((1, 1)), Q((0, 1)), Q((1, 0))] sage: for a in T: ....: for b in T: ....: assert(Q.le(a, b) == (a <= b)) ....: print('%s <= %s = %s' % (a, b, a <= b)) (0, 0) <= (0, 0) = True (0, 0) <= (1, 1) = True (0, 0) <= (0, 1) = True (0, 0) <= (1, 0) = True (1, 1) <= (0, 0) = False (1, 1) <= (1, 1) = True (1, 1) <= (0, 1) = False (1, 1) <= (1, 0) = False (0, 1) <= (0, 0) = False (0, 1) <= (1, 1) = True (0, 1) <= (0, 1) = True (0, 1) <= (1, 0) = True (1, 0) <= (0, 0) = False (1, 0) <= (1, 1) = True (1, 0) <= (0, 1) = False (1, 0) <= (1, 0) = True """ return left.value <= right.value class Element(CartesianProduct.Element): def _le_(self, other): r""" Return if this element is less or equal to ``other``. INPUT: - ``other`` -- an element. OUTPUT: A boolean. .. NOTE:: This method calls :meth:`CartesianProductPoset.le`. Override it in inherited class to change this. It can be assumed that this element and ``other`` have the same parent. TESTS:: sage: from sage.combinat.posets.cartesian_product import CartesianProductPoset sage: QQ.CartesianProduct = CartesianProductPoset # needed until #19269 is fixed sage: def le_sum(left, right): ....: return (sum(left) < sum(right) or ....: sum(left) == sum(right) and left[0] <= right[0]) sage: C = cartesian_product((QQ, QQ), order=le_sum) sage: C((1/3, 2)) <= C((2, 1/3)) # indirect doctest True sage: C((1/3, 2)) <= C((2, 2)) # indirect doctest True """ return self.parent().le(self, other) def __le__(self, other): r""" Return if this element is less than or equal to ``other``. INPUT: - ``other`` -- an element. OUTPUT: A boolean. .. NOTE:: This method uses the coercion framework to find a suitable common parent. This method can be deleted once :trac:`10130` is fixed and provides these methods automatically. TESTS:: sage: from sage.combinat.posets.cartesian_product import CartesianProductPoset sage: QQ.CartesianProduct = CartesianProductPoset # needed until #19269 is fixed sage: def le_sum(left, right): ....: return (sum(left) < sum(right) or ....: sum(left) == sum(right) and left[0] <= right[0]) sage: C = cartesian_product((QQ, QQ), order=le_sum) sage: C((1/3, 2)) <= C((2, 1/3)) True sage: C((1/3, 2)) <= C((2, 2)) True The following example tests that the coercion gets involved in comparisons; it can be simplified once :trac:`18182` is merged. :: sage: class MyCP(CartesianProductPoset): ....: def _coerce_map_from_(self, S): ....: if isinstance(S, self.__class__): ....: S_factors = S.cartesian_factors() ....: R_factors = self.cartesian_factors() ....: if len(S_factors) == len(R_factors): ....: if all(r.has_coerce_map_from(s) ....: for r,s in zip(R_factors, S_factors)): ....: return True sage: QQ.CartesianProduct = MyCP sage: A = cartesian_product((QQ, ZZ), order=le_sum) sage: B = cartesian_product((QQ, QQ), order=le_sum) sage: A((1/2, 4)) <= B((1/2, 5)) True """ from sage.structure.element import have_same_parent if have_same_parent(self, other): return self._le_(other) from sage.structure.element import get_coercion_model import operator try: return get_coercion_model().bin_op(self, other, operator.le) except TypeError: return False def __ge__(self, other): r""" Return if this element is greater than or equal to ``other``. INPUT: - ``other`` -- an element. OUTPUT: A boolean. .. NOTE:: This method uses the coercion framework to find a suitable common parent. This method can be deleted once :trac:`10130` is fixed and provides these methods automatically. TESTS:: sage: from sage.combinat.posets.cartesian_product import CartesianProductPoset sage: QQ.CartesianProduct = CartesianProductPoset # needed until #19269 is fixed sage: def le_sum(left, right): ....: return (sum(left) < sum(right) or ....: sum(left) == sum(right) and left[0] <= right[0]) sage: C = cartesian_product((QQ, QQ), order=le_sum) sage: C((1/3, 2)) >= C((2, 1/3)) False sage: C((1/3, 2)) >= C((2, 2)) False """ return other <= self def __lt__(self, other): r""" Return if this element is less than ``other``. INPUT: - ``other`` -- an element. OUTPUT: A boolean. .. NOTE:: This method uses the coercion framework to find a suitable common parent. This method can be deleted once :trac:`10130` is fixed and provides these methods automatically. TESTS:: sage: from sage.combinat.posets.cartesian_product import CartesianProductPoset sage: QQ.CartesianProduct = CartesianProductPoset # needed until #19269 is fixed sage: def le_sum(left, right): ....: return (sum(left) < sum(right) or ....: sum(left) == sum(right) and left[0] <= right[0]) sage: C = cartesian_product((QQ, QQ), order=le_sum) sage: C((1/3, 2)) < C((2, 1/3)) True sage: C((1/3, 2)) < C((2, 2)) True """ return not self == other and self <= other def __gt__(self, other): r""" Return if this element is greater than ``other``. INPUT: - ``other`` -- an element. OUTPUT: A boolean. .. NOTE:: This method uses the coercion framework to find a suitable common parent. This method can be deleted once :trac:`10130` is fixed and provides these methods automatically. TESTS:: sage: from sage.combinat.posets.cartesian_product import CartesianProductPoset sage: QQ.CartesianProduct = CartesianProductPoset # needed until #19269 is fixed sage: def le_sum(left, right): ....: return (sum(left) < sum(right) or ....: sum(left) == sum(right) and left[0] <= right[0]) sage: C = cartesian_product((QQ, QQ), order=le_sum) sage: C((1/3, 2)) > C((2, 1/3)) False sage: C((1/3, 2)) > C((2, 2)) False """ return not self == other and other <= self
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/posets/cartesian_product.py
0.934406
0.830319
cartesian_product.py
pypi
r""" Mutually Orthogonal Latin Squares (MOLS) The main function of this module is :func:`mutually_orthogonal_latin_squares` and can be can be used to generate MOLS (or check that they exist):: sage: MOLS = designs.mutually_orthogonal_latin_squares(4,8) For more information on MOLS, see the :wikipedia:`Wikipedia entry on MOLS <Graeco-Latin_square#Mutually_orthogonal_Latin_squares>`. If you are only interested by latin squares, see :mod:`~sage.combinat.matrices.latin`. The functions defined here are .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:`mutually_orthogonal_latin_squares` | Return `k` Mutually Orthogonal `n\times n` Latin Squares. :meth:`are_mutually_orthogonal_latin_squares` | Check that the list ``l`` of matrices in are MOLS. :meth:`latin_square_product` | Return the product of two (or more) latin squares. :meth:`MOLS_table` | Prints the MOLS table. **Table of MOLS** Sage can produce a table of MOLS similar to the one from the Handbook of Combinatorial Designs [DesignHandbook]_ (`available here <http://books.google.fr/books?id=S9FA9rq1BgoC&dq=handbook%20combinatorial%20designs%20MOLS%2010000&pg=PA176>`_). :: sage: from sage.combinat.designs.latin_squares import MOLS_table sage: MOLS_table(600) # long time 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ________________________________________________________________________________ 0| +oo +oo 1 2 3 4 1 6 7 8 2 10 5 12 4 4 15 16 5 18 20| 4 5 3 22 7 24 4 26 5 28 4 30 31 5 4 5 8 36 4 5 40| 7 40 5 42 5 6 4 46 8 48 6 5 5 52 5 6 7 7 5 58 60| 5 60 5 6 63 7 5 66 5 6 6 70 7 72 5 7 6 6 6 78 80| 9 80 8 82 6 6 6 6 7 88 6 7 6 6 6 6 7 96 6 8 100| 8 100 6 102 7 7 6 106 6 108 6 6 13 112 6 7 6 8 6 6 120| 7 120 6 6 6 124 6 126 127 7 6 130 6 7 6 7 7 136 6 138 140| 6 7 6 10 10 7 6 7 6 148 6 150 7 8 8 7 6 156 7 6 160| 9 7 6 162 6 7 6 166 7 168 6 8 6 172 6 6 14 9 6 178 180| 6 180 6 6 7 9 6 10 6 8 6 190 7 192 6 7 6 196 6 198 200| 7 7 6 7 6 8 6 8 14 11 10 210 6 7 6 7 7 8 6 10 220| 6 12 6 222 13 8 6 226 6 228 6 7 7 232 6 7 6 7 6 238 240| 7 240 6 242 6 7 6 12 7 7 6 250 6 12 9 7 255 256 6 12 260| 6 8 8 262 7 8 7 10 7 268 7 270 15 16 6 13 10 276 6 9 280| 7 280 6 282 6 12 6 7 15 288 6 6 6 292 6 6 7 10 10 12 300| 7 7 7 7 15 15 6 306 7 7 7 310 7 312 7 10 7 316 7 10 320| 15 15 6 16 8 12 6 7 7 9 6 330 7 8 7 6 7 336 6 7 340| 6 10 10 342 7 7 6 346 6 348 8 12 18 352 6 9 7 9 6 358 360| 7 360 6 7 7 7 6 366 15 15 7 15 7 372 7 15 7 13 7 378 380| 7 12 7 382 15 15 7 15 7 388 7 16 7 7 7 7 8 396 7 7 400| 15 400 7 15 11 8 7 15 8 408 7 13 8 12 10 9 18 15 7 418 420| 7 420 7 15 7 16 6 7 7 7 6 430 15 432 6 15 6 18 7 438 440| 7 15 7 442 7 13 7 11 15 448 7 15 7 7 7 15 7 456 7 16 460| 7 460 7 462 15 15 7 466 8 8 7 15 7 15 10 18 7 15 6 478 480| 15 15 6 15 8 7 6 486 7 15 6 490 6 16 6 7 15 15 6 498 500| 7 8 9 502 7 15 6 15 7 508 6 15 511 18 7 15 8 12 8 15 520| 8 520 10 522 12 15 8 16 15 528 7 15 8 12 7 15 8 15 10 15 540| 12 540 7 15 18 7 7 546 7 8 7 18 7 7 7 7 7 556 7 12 560| 15 7 7 562 7 7 6 7 7 568 6 570 7 7 15 22 8 576 7 7 580| 7 8 7 10 7 8 7 586 7 18 17 7 15 592 8 15 7 7 8 598 Comparison with the results from the Handbook of Combinatorial Designs (2ed) [DesignHandbook]_:: sage: MOLS_table(600,compare=True) # long time 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ________________________________________________________________________________ 0| + + 20| 40| 60| + 80| 100| 120| 140| 160| 180| 200| - 220| 240| 260| 280| 300| 320| - 340| 360| - - 380| - 400| 420| - 440| 460| 480| 500| - 520| 540| 560| 580| .. TODO:: Look at [ColDin01]_. REFERENCES: .. [Stinson2004] Douglas R. Stinson, *Combinatorial designs: construction and analysis*, Springer, 2004. .. [ColDin01] Charles Colbourn, Jeffrey Dinitz, *Mutually orthogonal latin squares: a brief survey of constructions*, Volume 95, Issues 1-2, Pages 9-48, Journal of Statistical Planning and Inference, Springer, 1 May 2001. Functions --------- """ from itertools import repeat from sage.rings.integer import Integer from sage.categories.sets_cat import EmptySetError from sage.misc.unknown import Unknown from sage.env import COMBINATORIAL_DESIGN_DATA_DIR def are_mutually_orthogonal_latin_squares(l, verbose=False): r""" Check whether the list of matrices in ``l`` form mutually orthogonal latin squares. INPUT: - ``verbose`` - if ``True`` then print why the list of matrices provided are not mutually orthogonal latin squares EXAMPLES:: sage: from sage.combinat.designs.latin_squares import are_mutually_orthogonal_latin_squares sage: m1 = matrix([[0,1,2],[2,0,1],[1,2,0]]) sage: m2 = matrix([[0,1,2],[1,2,0],[2,0,1]]) sage: m3 = matrix([[0,1,2],[2,0,1],[1,2,0]]) sage: are_mutually_orthogonal_latin_squares([m1,m2]) True sage: are_mutually_orthogonal_latin_squares([m1,m3]) False sage: are_mutually_orthogonal_latin_squares([m2,m3]) True sage: are_mutually_orthogonal_latin_squares([m1,m2,m3], verbose=True) Squares 0 and 2 are not orthogonal False sage: m = designs.mutually_orthogonal_latin_squares(7,8) sage: are_mutually_orthogonal_latin_squares(m) True TESTS: Not a latin square:: sage: m1 = matrix([[0,1,0],[2,0,1],[1,2,0]]) sage: m2 = matrix([[0,1,2],[1,2,0],[2,0,1]]) sage: are_mutually_orthogonal_latin_squares([m1,m2], verbose=True) Matrix 0 is not row latin False sage: m1 = matrix([[0,1,2],[1,0,2],[1,2,0]]) sage: are_mutually_orthogonal_latin_squares([m1,m2], verbose=True) Matrix 0 is not column latin False sage: m1 = matrix([[0,0,0],[1,1,1],[2,2,2]]) sage: m2 = matrix([[0,1,2],[0,1,2],[0,1,2]]) sage: are_mutually_orthogonal_latin_squares([m1,m2]) False """ if not l: raise ValueError("the list must be non empty") n = l[0].ncols() k = len(l) if any(M.ncols() != n or M.nrows() != n for M in l): if verbose: print("Not all matrices are square matrices of the same dimensions") return False # Check that all matrices are latin squares for i,M in enumerate(l): if any(len(set(R)) != n for R in M): if verbose: print("Matrix {} is not row latin".format(i)) return False if any(len(set(R)) != n for R in zip(*M)): if verbose: print("Matrix {} is not column latin".format(i)) return False from .designs_pyx import is_orthogonal_array return is_orthogonal_array(list(zip(*[[x for R in M for x in R] for M in l])),k,n, verbose=verbose, terminology="MOLS") def mutually_orthogonal_latin_squares(k, n, partitions=False, check=True): r""" Return `k` Mutually Orthogonal `n\times n` Latin Squares (MOLS). For more information on Mutually Orthogonal Latin Squares, see :mod:`~sage.combinat.designs.latin_squares`. INPUT: - ``k`` (integer) -- number of MOLS. If ``k=None`` it is set to the largest value available. - ``n`` (integer) -- size of the latin square. - ``partitions`` (boolean) -- a Latin Square can be seen as 3 partitions of the `n^2` cells of the array into `n` sets of size `n`, respectively: * The partition of rows * The partition of columns * The partition of number (cells numbered with 0, cells numbered with 1, ...) These partitions have the additional property that any two sets from different partitions intersect on exactly one element. When ``partitions`` is set to ``True``, this function returns a list of `k+2` partitions satisfying this intersection property instead of the `k+2` MOLS (though the data is exactly the same in both cases). - ``check`` -- (boolean) Whether to check that output is correct before returning it. As this is expected to be useless (but we are cautious guys), you may want to disable it whenever you want speed. Set to ``True`` by default. EXAMPLES:: sage: designs.mutually_orthogonal_latin_squares(4,5) [ [0 2 4 1 3] [0 3 1 4 2] [0 4 3 2 1] [0 1 2 3 4] [4 1 3 0 2] [3 1 4 2 0] [2 1 0 4 3] [4 0 1 2 3] [3 0 2 4 1] [1 4 2 0 3] [4 3 2 1 0] [3 4 0 1 2] [2 4 1 3 0] [4 2 0 3 1] [1 0 4 3 2] [2 3 4 0 1] [1 3 0 2 4], [2 0 3 1 4], [3 2 1 0 4], [1 2 3 4 0] ] sage: designs.mutually_orthogonal_latin_squares(3,7) [ [0 2 4 6 1 3 5] [0 3 6 2 5 1 4] [0 4 1 5 2 6 3] [6 1 3 5 0 2 4] [5 1 4 0 3 6 2] [4 1 5 2 6 3 0] [5 0 2 4 6 1 3] [3 6 2 5 1 4 0] [1 5 2 6 3 0 4] [4 6 1 3 5 0 2] [1 4 0 3 6 2 5] [5 2 6 3 0 4 1] [3 5 0 2 4 6 1] [6 2 5 1 4 0 3] [2 6 3 0 4 1 5] [2 4 6 1 3 5 0] [4 0 3 6 2 5 1] [6 3 0 4 1 5 2] [1 3 5 0 2 4 6], [2 5 1 4 0 3 6], [3 0 4 1 5 2 6] ] sage: designs.mutually_orthogonal_latin_squares(2,5,partitions=True) [[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]], [[0, 5, 10, 15, 20], [1, 6, 11, 16, 21], [2, 7, 12, 17, 22], [3, 8, 13, 18, 23], [4, 9, 14, 19, 24]], [[0, 8, 11, 19, 22], [3, 6, 14, 17, 20], [1, 9, 12, 15, 23], [4, 7, 10, 18, 21], [2, 5, 13, 16, 24]], [[0, 9, 13, 17, 21], [2, 6, 10, 19, 23], [4, 8, 12, 16, 20], [1, 5, 14, 18, 22], [3, 7, 11, 15, 24]]] What is the maximum number of MOLS of size 8 that Sage knows how to build?:: sage: designs.orthogonal_arrays.largest_available_k(8)-2 7 If you only want to know if Sage is able to build a given set of MOLS, query the ``orthogonal_arrays.*`` functions:: sage: designs.orthogonal_arrays.is_available(5+2, 5) # 5 MOLS of order 5 False sage: designs.orthogonal_arrays.is_available(4+2,6) # 4 MOLS of order 6 False Sage, however, is not able to prove that the second MOLS do not exist:: sage: designs.orthogonal_arrays.exists(4+2,6) # 4 MOLS of order 6 Unknown If you ask for such a MOLS then you will respectively get an informative ``EmptySetError`` or ``NotImplementedError``:: sage: designs.mutually_orthogonal_latin_squares(5, 5) Traceback (most recent call last): ... EmptySetError: there exist at most n-1 MOLS of size n if n>=2 sage: designs.mutually_orthogonal_latin_squares(4,6) Traceback (most recent call last): ... NotImplementedError: I don't know how to build 4 MOLS of order 6 TESTS: The special case `n=1`:: sage: designs.mutually_orthogonal_latin_squares(3, 1) [[0], [0], [0]] Wrong input for `k`:: sage: designs.mutually_orthogonal_latin_squares(None, 1) Traceback (most recent call last): ... TypeError: k must be a positive integer sage: designs.mutually_orthogonal_latin_squares(-1, 1) Traceback (most recent call last): ... ValueError: k must be positive sage: designs.mutually_orthogonal_latin_squares(2,10) [ [1 8 9 0 2 4 6 3 5 7] [1 7 6 5 0 9 8 2 3 4] [7 2 8 9 0 3 5 4 6 1] [8 2 1 7 6 0 9 3 4 5] [6 1 3 8 9 0 4 5 7 2] [9 8 3 2 1 7 0 4 5 6] [5 7 2 4 8 9 0 6 1 3] [0 9 8 4 3 2 1 5 6 7] [0 6 1 3 5 8 9 7 2 4] [2 0 9 8 5 4 3 6 7 1] [9 0 7 2 4 6 8 1 3 5] [4 3 0 9 8 6 5 7 1 2] [8 9 0 1 3 5 7 2 4 6] [6 5 4 0 9 8 7 1 2 3] [2 3 4 5 6 7 1 8 9 0] [3 4 5 6 7 1 2 8 0 9] [3 4 5 6 7 1 2 0 8 9] [5 6 7 1 2 3 4 0 9 8] [4 5 6 7 1 2 3 9 0 8], [7 1 2 3 4 5 6 9 8 0] ] """ from sage.combinat.designs.orthogonal_arrays import orthogonal_array from sage.matrix.constructor import Matrix from .database import MOLS_constructions if k is None: raise TypeError('k must be a positive integer') try: Integer(k) except TypeError: raise if k < 0: raise ValueError('k must be positive') if n == 1: matrices = [Matrix([[0]])] * k elif k >= n: raise EmptySetError("there exist at most n-1 MOLS of size n if n>=2") elif n in MOLS_constructions and k <= MOLS_constructions[n][0]: _, construction = MOLS_constructions[n] matrices = construction()[:k] elif orthogonal_array(k + 2, n, existence=True) is not Unknown: # Forwarding non-existence results if orthogonal_array(k + 2, n, existence=True): pass else: raise EmptySetError("there does not exist {} MOLS of order {}!".format(k, n)) # make sure that the first two columns are "11, 12, ..., 1n, 21, 22, ..." OA = sorted(orthogonal_array(k + 2, n, check=False)) # We first define matrices as lists of n^2 values matrices = [[] for _ in repeat(None, k)] for L in OA: for i in range(2, k + 2): matrices[i-2].append(L[i]) # The real matrices matrices = [[M[i*n:(i+1)*n] for i in range(n)] for M in matrices] matrices = [Matrix(M) for M in matrices] else: raise NotImplementedError("I don't know how to build {} MOLS of order {}".format(k, n)) if check: assert are_mutually_orthogonal_latin_squares(matrices) # partitions have been requested but have not been computed yet if partitions is True: partitions = [[[i*n+j for j in range(n)] for i in range(n)], [[j*n+i for j in range(n)] for i in range(n)]] for m in matrices: partition = [[] for _ in repeat(None, n)] for i in range(n): for j in range(n): partition[m[i,j]].append(i*n+j) partitions.append(partition) if partitions: return partitions else: return matrices def latin_square_product(M, N, *others): r""" Return the product of two (or more) latin squares. Given two Latin Squares `M,N` of respective sizes `m,n`, the direct product `M\times N` of size `mn` is defined by `(M\times N)((i_1,i_2),(j_1,j_2))=(M(i_1,j_1),N(i_2,j_2))` where `i_1,j_1\in [m], i_2,j_2\in [n]` Each pair of values `(i,j)\in [m]\times [n]` is then relabeled to `in+j`. This is Lemma 6.25 of [Stinson2004]_. INPUT: An arbitrary number of latin squares (greater than 2). EXAMPLES:: sage: from sage.combinat.designs.latin_squares import latin_square_product sage: m=designs.mutually_orthogonal_latin_squares(3,4)[0] sage: latin_square_product(m,m,m) 64 x 64 sparse matrix over Integer Ring (use the '.str()' method to see the entries) """ from sage.matrix.constructor import Matrix m = M.nrows() n = N.nrows() D = {((i,j),(ii,jj)):(M[i,ii],N[j,jj]) for i in range(m) for ii in range(m) for j in range(n) for jj in range(n)} L = lambda i_j: i_j[0] * n + i_j[1] D = {(L(c[0]), L(c[1])): L(v) for c, v in D.items()} P = Matrix(D) if others: return latin_square_product(P, others[0],*others[1:]) else: return P def MOLS_table(start,stop=None,compare=False,width=None): r""" Prints the MOLS table that Sage can produce. INPUT: - ``start,stop`` (integers) -- print the table of MOLS for value of `n` such that ``start<=n<stop``. If only one integer is given as input, it is interpreted as the value of ``stop`` with ``start=0`` (same behaviour as ``range``). - ``compare`` (boolean) -- if sets to ``True`` the MOLS displays with `+` and `-` entries its difference with the table from the Handbook of Combinatorial Designs (2ed). - ``width`` (integer) -- the width of each column of the table. By default, it is computed from range of values determined by the parameters ``start`` and ``stop``. EXAMPLES:: sage: from sage.combinat.designs.latin_squares import MOLS_table sage: MOLS_table(100) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ________________________________________________________________________________ 0| +oo +oo 1 2 3 4 1 6 7 8 2 10 5 12 4 4 15 16 5 18 20| 4 5 3 22 7 24 4 26 5 28 4 30 31 5 4 5 8 36 4 5 40| 7 40 5 42 5 6 4 46 8 48 6 5 5 52 5 6 7 7 5 58 60| 5 60 5 6 63 7 5 66 5 6 6 70 7 72 5 7 6 6 6 78 80| 9 80 8 82 6 6 6 6 7 88 6 7 6 6 6 6 7 96 6 8 sage: MOLS_table(100, width=4) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ____________________________________________________________________________________________________ 0| +oo +oo 1 2 3 4 1 6 7 8 2 10 5 12 4 4 15 16 5 18 20| 4 5 3 22 7 24 4 26 5 28 4 30 31 5 4 5 8 36 4 5 40| 7 40 5 42 5 6 4 46 8 48 6 5 5 52 5 6 7 7 5 58 60| 5 60 5 6 63 7 5 66 5 6 6 70 7 72 5 7 6 6 6 78 80| 9 80 8 82 6 6 6 6 7 88 6 7 6 6 6 6 7 96 6 8 sage: MOLS_table(100, compare=True) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ________________________________________________________________________________ 0| + + 20| 40| 60| + 80| sage: MOLS_table(50, 100, compare=True) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ________________________________________________________________________________ 40| 60| + 80| """ from .orthogonal_arrays import largest_available_k if stop is None: start,stop = 0,start # make start and stop be congruent to 0 mod 20 start = start - (start%20) stop = stop-1 stop = stop + (20-(stop%20)) assert start%20 == 0 and stop%20 == 0 if stop <= start: return if compare: handbook_file = open("{}/MOLS_table.txt".format(COMBINATORIAL_DESIGN_DATA_DIR), 'r') hb = [int(_) for _ in handbook_file.readlines()[9].split(',')] handbook_file.close() # choose an appropriate width (needs to be >= 3 because "+oo" should fit) if width is None: width = max(3, Integer(stop-1).ndigits(10)) print(" " * (width + 2) + " ".join("{i:>{width}}".format(i=i,width=width) for i in range(20))) print(" " * (width + 1) + "_" * ((width + 1) * 20), end="") for i in range(start,stop): if i % 20 == 0: print("\n{:>{width}}|".format(i, width=width), end="") k = largest_available_k(i)-2 if compare: if i < 2 or hb[i] == k: c = "" elif hb[i] < k: c = "+" else: c = "-" else: if i < 2: c = "+oo" else: c = k print(' {:>{width}}'.format(c, width=width), end="")
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/designs/latin_squares.py
0.80038
0.362179
latin_squares.py
pypi
r""" Catalog of designs This module gathers all designs that can be reached through ``designs.<tab>``. Example with the Witt design on 24 points:: sage: designs.WittDesign(24) # optional - gap_packages Incidence structure with 24 points and 759 blocks Or a Steiner Triple System on 19 points:: sage: designs.steiner_triple_system(19) (19,3,1)-Balanced Incomplete Block Design **La Jolla Covering Repository** The La Jolla Covering Repository (LJCR, see [1]_) is an online database of covering designs. As it is frequently updated, it is not included in Sage, but one can query it through :meth:`designs.best_known_covering_design_from_LJCR <sage.combinat.designs.covering_design.best_known_covering_design_www>`:: sage: C = designs.best_known_covering_design_from_LJCR(7, 3, 2) # optional - internet sage: C # optional - internet (7, 3, 2)-covering design of size 7 Lower bound: 7 Method: lex covering Submitted on: 1996-12-01 00:00:00 sage: C.incidence_structure() # optional - internet Incidence structure with 7 points and 7 blocks **Design constructors** This module gathers the following designs: .. csv-table:: :class: contentstable :widths: 100 :delim: | :meth:`~sage.combinat.designs.block_design.ProjectiveGeometryDesign` :meth:`~sage.combinat.designs.block_design.DesarguesianProjectivePlaneDesign` :meth:`~sage.combinat.designs.block_design.HughesPlane` :meth:`~sage.combinat.designs.database.HigmanSimsDesign` :meth:`~sage.combinat.designs.bibd.balanced_incomplete_block_design` :meth:`~sage.combinat.designs.resolvable_bibd.resolvable_balanced_incomplete_block_design` :meth:`~sage.combinat.designs.resolvable_bibd.kirkman_triple_system` :meth:`~sage.combinat.designs.block_design.AffineGeometryDesign` :meth:`~sage.combinat.designs.block_design.CremonaRichmondConfiguration` :meth:`~sage.combinat.designs.block_design.WittDesign` :meth:`~sage.combinat.designs.block_design.HadamardDesign` :meth:`~sage.combinat.designs.block_design.Hadamard3Design` :meth:`~sage.combinat.designs.latin_squares.mutually_orthogonal_latin_squares` :meth:`~sage.combinat.designs.orthogonal_arrays.transversal_design` :meth:`~sage.combinat.designs.orthogonal_arrays.orthogonal_array` :meth:`~sage.combinat.designs.orthogonal_arrays.incomplete_orthogonal_array` :meth:`~sage.combinat.designs.difference_family.difference_family` :meth:`~sage.combinat.designs.difference_matrices.difference_matrix` :meth:`~sage.combinat.designs.bibd.steiner_triple_system` :meth:`~sage.combinat.designs.steiner_quadruple_systems.steiner_quadruple_system` :meth:`~sage.combinat.designs.block_design.projective_plane` :meth:`~sage.combinat.designs.biplane` :meth:`~sage.combinat.designs.gen_quadrangles_with_spread` And the :meth:`designs.best_known_covering_design_from_LJCR <sage.combinat.designs.covering_design.best_known_covering_design_www>` function which queries the LJCR. .. TODO:: Implement DerivedDesign and ComplementaryDesign. REFERENCES: .. [1] La Jolla Covering Repository, https://math.ccrwest.org/cover.html """ from sage.misc.lazy_import import lazy_import lazy_import('sage.combinat.designs.block_design', ('BlockDesign', 'ProjectiveGeometryDesign', 'DesarguesianProjectivePlaneDesign', 'projective_plane', 'AffineGeometryDesign', 'WittDesign', 'HadamardDesign', 'Hadamard3Design', 'HughesPlane', 'CremonaRichmondConfiguration')) lazy_import('sage.combinat.designs.database', 'HigmanSimsDesign') lazy_import('sage.combinat.designs.steiner_quadruple_systems', 'steiner_quadruple_system') lazy_import('sage.combinat.designs.covering_design', 'best_known_covering_design_www', as_='best_known_covering_design_from_LJCR') lazy_import('sage.combinat.designs.latin_squares', 'mutually_orthogonal_latin_squares') lazy_import('sage.combinat.designs.orthogonal_arrays', ('transversal_design', 'incomplete_orthogonal_array')) lazy_import('sage.combinat.designs.difference_family', 'difference_family') lazy_import('sage.combinat.designs.difference_matrices', 'difference_matrix') lazy_import('sage.combinat.designs.bibd', ('balanced_incomplete_block_design', 'steiner_triple_system', 'biplane')) lazy_import('sage.combinat.designs.resolvable_bibd', ('resolvable_balanced_incomplete_block_design', 'kirkman_triple_system')) lazy_import('sage.combinat.designs.group_divisible_designs', 'group_divisible_design') lazy_import('sage.combinat.designs.orthogonal_arrays', 'OAMainFunctions', as_='orthogonal_arrays') lazy_import('sage.combinat.designs.gen_quadrangles_with_spread', ('generalised_quadrangle_with_spread', 'generalised_quadrangle_hermitian_with_ovoid'))
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/designs/design_catalog.py
0.863132
0.612802
design_catalog.py
pypi
r""" Two-graphs A two-graph on `n` points is a family `T \subset \binom {[n]}{3}` of `3`-sets, such that any `4`-set `S\subset [n]` of size four contains an even number of elements of `T`. Any graph `([n],E)` gives rise to a two-graph `T(E)=\{t \in \binom {[n]}{3} : \left| \binom {t}{2} \cap E \right|\ odd \}`, and any two graphs with the same two-graph can be obtained one from the other by :meth:`Seidel switching <Graph.seidel_switching>`. This defines an equivalence relation on the graphs on `[n]`, called Seidel switching equivalence. Conversely, given a two-graph `T`, one can construct a graph `\Gamma` in the corresponding Seidel switching class with an isolated vertex `w`. The graph `\Gamma \setminus w` is called the :meth:`descendant <TwoGraph.descendant>` of `T` w.r.t. `v`. `T` is called regular if each two-subset of `[n]` is contained in the same number alpha of triples of `T`. This module implements a direct construction of a two-graph from a list of triples, construction of descendant graphs, regularity checking, and other things such as constructing the complement two-graph, cf. [BH2012]_. AUTHORS: - Dima Pasechnik (Aug 2015) Index ----- This module's methods are the following: .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:`~TwoGraph.is_regular_twograph` | tests if ``self`` is a regular two-graph, i.e. a 2-design :meth:`~TwoGraph.complement` | returns the complement of ``self`` :meth:`~TwoGraph.descendant` | returns the descendant graph at `w` This module's functions are the following: .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :func:`~taylor_twograph` | constructs Taylor's two-graph for `U_3(q)` :func:`~is_twograph` | checks that the incidence system is a two-graph :func:`~twograph_descendant` | returns the descendant graph w.r.t. a given vertex of the two-graph of a given graph Methods --------- """ from sage.combinat.designs.incidence_structures import IncidenceStructure from itertools import combinations class TwoGraph(IncidenceStructure): r""" Two-graphs class. A two-graph on `n` points is a 3-uniform hypergraph, i.e. a family `T \subset \binom {[n]}{3}` of `3`-sets, such that any `4`-set `S\subset [n]` of size four contains an even number of elements of `T`. For more information, see the documentation of the :mod:`~sage.combinat.designs.twographs` module. """ def __init__(self, points=None, blocks=None, incidence_matrix=None, name=None, check=False, copy=True): r""" Constructor of the class TESTS:: sage: from sage.combinat.designs.twographs import TwoGraph sage: TwoGraph([[1,2]]) Incidence structure with 2 points and 1 blocks sage: TwoGraph([[1,2]], check=True) Traceback (most recent call last): ... AssertionError: the structure is not a 2-graph! sage: p=graphs.PetersenGraph().twograph() sage: TwoGraph(p, check=True) Incidence structure with 10 points and 60 blocks """ IncidenceStructure.__init__(self, points=points, blocks=blocks, incidence_matrix=incidence_matrix, name=name, check=False, copy=copy) if check: # it is a very slow, O(|points|^4), test... assert is_twograph(self), "the structure is not a 2-graph!" def is_regular_twograph(self, alpha=False): r""" Test if the :class:`TwoGraph` is regular, i.e. is a 2-design. Namely, each pair of elements of :meth:`ground_set` is contained in exactly ``alpha`` triples. INPUT: - ``alpha`` -- (optional, default is ``False``) return the value of ``alpha``, if possible. EXAMPLES:: sage: p=graphs.PetersenGraph().twograph() sage: p.is_regular_twograph(alpha=True) 4 sage: p.is_regular_twograph() True sage: p=graphs.PathGraph(5).twograph() sage: p.is_regular_twograph(alpha=True) False sage: p.is_regular_twograph() False """ r, (_, _, _, a) = self.is_t_design(t=2, k=3, return_parameters=True) if r and alpha: return a return r def descendant(self, v): """ The descendant :class:`graph <sage.graphs.graph.Graph>` at ``v`` The :mod:`switching class of graphs <sage.combinat.designs.twographs>` corresponding to ``self`` contains a graph ``D`` with ``v`` its own connected component; removing ``v`` from ``D``, one obtains the descendant graph of ``self`` at ``v``, which is constructed by this method. INPUT: - ``v`` -- an element of :meth:`ground_set` EXAMPLES:: sage: p = graphs.PetersenGraph().twograph().descendant(0) sage: p.is_strongly_regular(parameters=True) (9, 4, 1, 2) """ from sage.graphs.graph import Graph return Graph([[z for z in x if z != v] for x in self.blocks() if v in x]) def complement(self): """ The two-graph which is the complement of ``self`` That is, the two-graph consisting exactly of triples not in ``self``. Note that this is different from :meth:`complement <sage.combinat.designs.incidence_structures.IncidenceStructure.complement>` of the :class:`parent class <sage.combinat.designs.incidence_structures.IncidenceStructure>`. EXAMPLES:: sage: p = graphs.CompleteGraph(8).line_graph().twograph() sage: pc = p.complement(); pc Incidence structure with 28 points and 1260 blocks TESTS:: sage: from sage.combinat.designs.twographs import is_twograph sage: is_twograph(pc) True """ return super().complement(uniform=True) def taylor_twograph(q): r""" constructing Taylor's two-graph for `U_3(q)`, `q` odd prime power The Taylor's two-graph `T` has the `q^3+1` points of the projective plane over `F_{q^2}` singular w.r.t. the non-degenerate Hermitean form `S` preserved by `U_3(q)` as its ground set; the triples are `\{x,y,z\}` satisfying the condition that `S(x,y)S(y,z)S(z,x)` is square (respectively non-square) if `q \cong 1 \mod 4` (respectively if `q \cong 3 \mod 4`). See §7E of [BL1984]_. There is also a `2-(q^3+1,q+1,1)`-design on these `q^3+1` points, known as the unital of order `q`, also invariant under `U_3(q)`. INPUT: - ``q`` -- a power of an odd prime EXAMPLES:: sage: from sage.combinat.designs.twographs import taylor_twograph sage: T=taylor_twograph(3); T Incidence structure with 28 points and 1260 blocks """ from sage.graphs.generators.classical_geometries import TaylorTwographSRG return TaylorTwographSRG(q).twograph() def is_twograph(T): r""" Checks that the incidence system `T` is a two-graph INPUT: - ``T`` -- an :class:`incidence structure <sage.combinat.designs.IncidenceStructure>` EXAMPLES: a two-graph from a graph:: sage: from sage.combinat.designs.twographs import (is_twograph, TwoGraph) sage: p=graphs.PetersenGraph().twograph() sage: is_twograph(p) True a non-regular 2-uniform hypergraph which is a two-graph:: sage: is_twograph(TwoGraph([[1,2,3],[1,2,4]])) True TESTS: wrong size of blocks:: sage: is_twograph(designs.projective_plane(3)) False a triple system which is not a two-graph:: sage: is_twograph(designs.projective_plane(2)) False """ if not T.is_uniform(3): return False # A structure for a fast triple existence check v_to_blocks = {v:set() for v in range(T.num_points())} for B in T._blocks: B = frozenset(B) for x in B: v_to_blocks[x].add(B) def has_triple(x_y_z): x, y, z = x_y_z return bool(v_to_blocks[x] & v_to_blocks[y] & v_to_blocks[z]) # Check that every quadruple contains an even number of triples for quad in combinations(range(T.num_points()),4): if sum(map(has_triple,combinations(quad,3))) % 2 == 1: return False return True def twograph_descendant(G, v, name=None): r""" Return the descendant graph w.r.t. vertex `v` of the two-graph of `G` In the :mod:`switching class <sage.combinat.designs.twographs>` of `G`, construct a graph `\Delta` with `v` an isolated vertex, and return the subgraph `\Delta \setminus v`. It is equivalent to, although much faster than, computing the :meth:`TwoGraph.descendant` of :meth:`two-graph of G <sage.graphs.graph.Graph.twograph>`, as the intermediate two-graph is not constructed. INPUT: - ``G`` -- a :class:`graph <sage.graphs.graph.Graph>` - ``v`` -- a vertex of ``G`` - ``name`` -- (optional) ``None`` - no name, otherwise derive from the construction EXAMPLES: one of s.r.g.'s from the :mod:`database <sage.graphs.strongly_regular_db>`:: sage: from sage.combinat.designs.twographs import twograph_descendant sage: A=graphs.strongly_regular_graph(280,135,70) # optional - gap_packages internet sage: twograph_descendant(A, 0).is_strongly_regular(parameters=True) # optional - gap_packages internet (279, 150, 85, 75) TESTS:: sage: T8 = graphs.CompleteGraph(8).line_graph() sage: v = T8.vertices(sort=True)[0] sage: twograph_descendant(T8, v)==T8.twograph().descendant(v) True sage: twograph_descendant(T8, v).is_strongly_regular(parameters=True) (27, 16, 10, 8) sage: p = graphs.PetersenGraph() sage: twograph_descendant(p,5) Graph on 9 vertices sage: twograph_descendant(p,5,name=True) descendant of Petersen graph at 5: Graph on 9 vertices """ G = G.seidel_switching(G.neighbors(v),inplace=False) G.delete_vertex(v) if name: G.name('descendant of '+G.name()+' at '+str(v)) else: G.name('') return G
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/designs/twographs.py
0.92944
0.951074
twographs.py
pypi
r""" Steiner Quadruple Systems A Steiner Quadruple System on `n` points is a family `SQS_n \subset \binom {[n]} 4` of `4`-sets, such that any set `S\subset [n]` of size three is a subset of exactly one member of `SQS_n`. This module implements Haim Hanani's constructive proof that a Steiner Quadruple System exists if and only if `n\equiv 2,4 \pmod 6`. Hanani's proof consists in 6 different constructions that build a large Steiner Quadruple System from a smaller one, and though it does not give a very clear understanding of why it works (to say the least)... it does ! The constructions have been implemented while reading two papers simultaneously, for one of them sometimes provides the informations that the other one does not. The first one is Haim Hanani's original paper [Han1960]_, and the other one is a paper from Horan and Hurlbert which goes through all constructions [HH2012]_. It can be used through the ``designs`` object:: sage: designs.steiner_quadruple_system(8) Incidence structure with 8 points and 14 blocks AUTHORS: - Nathann Cohen (May 2013, while listening to "*Le Blues Du Pauvre Delahaye*") Index ----- This module's main function is the following: .. csv-table:: :class: contentstable :widths: 15, 20, 65 :delim: | | :func:`steiner_quadruple_system` | Return a Steiner Quadruple System on `n` points This function redistributes its work among 6 constructions: .. csv-table:: :class: contentstable :widths: 15, 20, 65 :delim: | Construction `1` | :func:`two_n` | Return a Steiner Quadruple System on `2n` points Construction `2` | :func:`three_n_minus_two` | Return a Steiner Quadruple System on `3n-2` points Construction `3` | :func:`three_n_minus_eight` | Return a Steiner Quadruple System on `3n-8` points Construction `4` | :func:`three_n_minus_four` | Return a Steiner Quadruple System on `3n-4` points Construction `5` | :func:`four_n_minus_six` | Return a Steiner Quadruple System on `4n-6` points Construction `6` | :func:`twelve_n_minus_ten` | Return a Steiner Quadruple System on `12n-10` points It also defines two specific Steiner Quadruple Systems that the constructions require, i.e. `SQS_{14}` and `SQS_{38}` as well as the systems of pairs `P_{\alpha}(m)` and `\overline P_{\alpha}(m)` (see [Han1960]_). Functions --------- """ from itertools import repeat from sage.misc.cachefunc import cached_function from sage.combinat.designs.incidence_structures import IncidenceStructure # Construction 1 def two_n(B): r""" Return a Steiner Quadruple System on `2n` points. INPUT: - ``B`` -- A Steiner Quadruple System on `n` points. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import two_n sage: for n in range(4, 30): ....: if (n%6) in [2,4]: ....: sqs = designs.steiner_quadruple_system(n) ....: if not two_n(sqs).is_t_design(3,2*n,4,1): ....: print("Something is wrong !") """ n = B.num_points() Y = [] # Line 1 for x,y,z,t in B._blocks: for a in range(2): for b in range(2): for c in range(2): d = (a+b+c)%2 Y.append([x+a*n,y+b*n,z+c*n,t+d*n]) # Line 2 for j in range(n): for jj in range(j+1,n): Y.append([j,jj,n+j,n+jj]) return IncidenceStructure(2*n,Y,check=False,copy=False) # Construction 2 def three_n_minus_two(B): """ Return a Steiner Quadruple System on `3n-2` points. INPUT: - ``B`` -- A Steiner Quadruple System on `n` points. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import three_n_minus_two sage: for n in range(4, 30): ....: if (n%6) in [2,4]: ....: sqs = designs.steiner_quadruple_system(n) ....: if not three_n_minus_two(sqs).is_t_design(3,3*n-2,4,1): ....: print("Something is wrong !") """ n = B.num_points() A = n-1 Y = [] # relabel function r = lambda i,x : (i%3)*(n-1)+x for x,y,z,t in B._blocks: if t == A: # Line 2. for a in range(3): for b in range(3): c = -(a+b)%3 Y.append([r(a,x),r(b,y),r(c,z),3*n-3]) # Line 3. Y.extend([[r(i,x),r(i,y),r(i+1,z),r(i+2,z)] for i in range(3)]) Y.extend([[r(i,x),r(i,z),r(i+1,y),r(i+2,y)] for i in range(3)]) Y.extend([[r(i,y),r(i,z),r(i+1,x),r(i+2,x)] for i in range(3)]) else: # Line 1. for a in range(3): for b in range(3): for c in range(3): d = -(a+b+c)%3 Y.append([r(a,x),r(b,y),r(c,z),r(d,t)]) # Line 4. for j in range(n-1): for jj in range(j+1,n-1): Y.extend([[r(i,j),r(i,jj),r(i+1,j),r(i+1,jj)] for i in range(3)]) # Line 5. for j in range(n-1): Y.append([r(0,j),r(1,j),r(2,j),3*n-3]) return IncidenceStructure(3*n-2,Y,check=False,copy=False) # Construction 3 def three_n_minus_eight(B): r""" Return a Steiner Quadruple System on `3n-8` points. INPUT: - ``B`` -- A Steiner Quadruple System on `n` points. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import three_n_minus_eight sage: for n in range(4, 30): ....: if (n%12) == 2: ....: sqs = designs.steiner_quadruple_system(n) ....: if not three_n_minus_eight(sqs).is_t_design(3,3*n-8,4,1): ....: print("Something is wrong !") """ n = B.num_points() if (n%12) != 2: raise ValueError("n must be equal to 2 mod 12") B = relabel_system(B) r = lambda i,x : (i%3)*(n-4)+(x%(n-4)) # Line 1. Y = [[x+2*(n-4) for x in B._blocks[-1]]] # Line 2. for s in B._blocks[:-1]: for i in range(3): Y.append([r(i,x) if x<= n-5 else x+2*(n-4) for x in s]) # Line 3. for a in range(4): for aa in range(n-4): for aaa in range(n-4): aaaa = -(a+aa+aaa)%(n-4) Y.append([r(0,aa),r(1,aaa), r(2,aaaa),3*(n-4)+a]) # Line 4. k = (n-14) // 12 for i in range(3): for b in range(n-4): for bb in range(n-4): bbb = -(b+bb)%(n-4) for d in range(2*k+1): Y.append([r(i+2,bbb), r(i, b+2*k+1+i*(4*k+2)-d) , r(i, b+2*k+2+i*(4*k+2)+d), r(i+1,bb)]) # Line 5. for i in range(3): for alpha in range(4*k+2, 12*k+9): for ra,sa in P(alpha,6*k+5): for raa,saa in P(alpha,6*k+5): Y.append([r(i,ra),r(i,sa),r(i+1,raa), r(i+1,saa)]) return IncidenceStructure(3*n-8,Y,check=False,copy=False) # Construction 4 def three_n_minus_four(B): r""" Return a Steiner Quadruple System on `3n-4` points. INPUT: - ``B`` -- A Steiner Quadruple System on `n` points where `n\equiv 10\pmod{12}`. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import three_n_minus_four sage: for n in range(4, 30): ....: if n%12 == 10: ....: sqs = designs.steiner_quadruple_system(n) ....: if not three_n_minus_four(sqs).is_t_design(3,3*n-4,4,1): ....: print("Something is wrong !") """ n = B.num_points() if n%12 != 10: raise ValueError("n must be equal to 10 mod 12") B = relabel_system(B) r = lambda i,x : (i%3)*(n-2)+(x%(n-2)) # Line 1/2. Y = [] for s in B._blocks: for i in range(3): Y.append([r(i,x) if x<= n-3 else x+2*(n-2) for x in s]) # Line 3. for a in range(2): for aa in range(n-2): for aaa in range(n-2): aaaa = -(a+aa+aaa) % (n-2) Y.append([r(0,aa),r(1,aaa), r(2,aaaa),3*(n-2)+a]) # Line 4. k = (n-10) // 12 for i in range(3): for b in range(n-2): for bb in range(n-2): bbb = -(b+bb)%(n-2) for d in range(2*k+1): Y.append([r(i+2,bbb), r(i, b+2*k+1+i*(4*k+2)-d) , r(i, b+2*k+2+i*(4*k+2)+d), r(i+1,bb)]) # Line 5. from sage.graphs.graph_coloring import round_robin one_factorization = round_robin(2*(6*k+4)).edges(sort=True) color_classes = [[] for _ in repeat(None, 2*(6*k+4)-1)] for u, v, l in one_factorization: color_classes[l].append((u,v)) for i in range(3): for alpha in range(4*k+2, 12*k+6+1): for ra,sa in P(alpha, 6*k+4): for raa,saa in P(alpha, 6*k+4): Y.append([r(i,ra),r(i,sa),r(i+1,raa), r(i+1,saa)]) return IncidenceStructure(3*n-4,Y,check=False,copy=False) # Construction 5 def four_n_minus_six(B): """ Return a Steiner Quadruple System on `4n-6` points. INPUT: - ``B`` -- A Steiner Quadruple System on `n` points. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import four_n_minus_six sage: for n in range(4, 20): ....: if (n%6) in [2,4]: ....: sqs = designs.steiner_quadruple_system(n) ....: if not four_n_minus_six(sqs).is_t_design(3,4*n-6,4,1): ....: print("Something is wrong !") """ n = B.num_points() f = n-2 r = lambda i,ii,x : (2*(i%2)+(ii%2))*(n-2)+(x)%(n-2) # Line 1. Y = [] for s in B._blocks: for i in range(2): for ii in range(2): Y.append([r(i,ii,x) if x<= n-3 else x+3*(n-2) for x in s]) # Line 2/3/4/5 k = f // 2 for l in range(2): for eps in range(2): for c in range(k): for cc in range(k): ccc = -(c+cc)%k Y.append([4*(n-2)+l, r(0,0,2*c) , r(0,1,2*cc-eps) , r(1,eps,2*ccc+l) ]) Y.append([4*(n-2)+l, r(0,0,2*c+1), r(0,1,2*cc-1-eps), r(1,eps,2*ccc+1-l)]) Y.append([4*(n-2)+l, r(1,0,2*c) , r(1,1,2*cc-eps) , r(0,eps,2*ccc+1-l)]) Y.append([4*(n-2)+l, r(1,0,2*c+1), r(1,1,2*cc-1-eps), r(0,eps,2*ccc+l) ]) # Line 6/7 for h in range(2): for eps in range(2): for ccc in range(k): assert len(barP(ccc,k)) == k-1 for rc,sc in barP(ccc,k): for c in range(k): cc = -(c+ccc)%k Y.append([r(h,0,2*c+eps) , r(h,1,2*cc-eps), r(h+1,0,rc), r(h+1,0,sc)]) Y.append([r(h,0,2*c-1+eps), r(h,1,2*cc-eps), r(h+1,1,rc), r(h+1,1,sc)]) # Line 8/9 for h in range(2): for eps in range(2): for ccc in range(k): for rc,sc in barP(k+ccc,k): for c in range(k): cc = -(c+ccc)%k Y.append([r(h,0,2*c+eps) , r(h,1,2*cc-eps), r(h+1,1,rc), r(h+1,1,sc)]) Y.append([r(h,0,2*c-1+eps), r(h,1,2*cc-eps), r(h+1,0,rc), r(h+1,0,sc)]) # Line 10 for h in range(2): for alpha in range(n-3): for ra,sa in P(alpha,k): for raa,saa in P(alpha,k): Y.append([r(h,0,ra),r(h,0,sa),r(h,1,raa),r(h,1,saa)]) return IncidenceStructure(4*n-6,Y,check=False,copy=False) # Construction 6 def twelve_n_minus_ten(B): """ Return a Steiner Quadruple System on `12n-6` points. INPUT: - ``B`` -- A Steiner Quadruple System on `n` points. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import twelve_n_minus_ten sage: for n in range(4, 15): ....: if (n%6) in [2,4]: ....: sqs = designs.steiner_quadruple_system(n) ....: if not twelve_n_minus_ten(sqs).is_t_design(3,12*n-10,4,1): ....: print("Something is wrong !") """ n = B.num_points() B14 = steiner_quadruple_system(14) r = lambda i,x : i%(n-1)+(x%12)*(n-1) # Line 1. Y = [] for s in B14._blocks: for i in range(n-1): Y.append([r(i,x) if x<= 11 else r(n-2,11)+x-11 for x in s]) for s in B._blocks: if s[-1] == n-1: u,v,w,B = s dd = {0:u,1:v,2:w} d = lambda x:dd[x%3] for b in range(12): for bb in range(12): bbb = -(b+bb)%12 for h in range(2): # Line 2 Y.append([r(n-2,11)+1+h,r(u,b),r(v,bb),r(w,bbb+3*h)]) for i in range(3): # Line 38.3 Y.append([r(d(i),b+4+i), r(d(i),b+7+i), r(d(i+1),bb), r(d(i+2),bbb)]) for j in range(12): for eps in range(2): for i in range(3): # Line 38.4-38.7 Y.append([ r(d(i),j), r(d(i+1),j+6*eps ), r(d(i+2),6*eps-2*j+1), r(d(i+2),6*eps-2*j-1)]) Y.append([ r(d(i),j), r(d(i+1),j+6*eps ), r(d(i+2),6*eps-2*j+2), r(d(i+2),6*eps-2*j-2)]) Y.append([ r(d(i),j), r(d(i+1),j+6*eps-3), r(d(i+2),6*eps-2*j+1), r(d(i+2),6*eps-2*j+2)]) Y.append([ r(d(i),j), r(d(i+1),j+6*eps+3), r(d(i+2),6*eps-2*j-1), r(d(i+2),6*eps-2*j-2)]) for j in range(6): for i in range(3): for eps in range(2): # Line 38.8 Y.append([ r(d(i),j), r(d(i),j+6), r(d(i+1),j+3*eps), r(d(i+1),j+6+3*eps)]) for j in range(12): for i in range(3): for eps in range(4): # Line 38.11 Y.append([ r(d(i),j), r(d(i),j+1), r(d(i+1),j+3*eps), r(d(i+1),j+3*eps+1)]) # Line 38.12 Y.append([ r(d(i),j), r(d(i),j+2), r(d(i+1),j+3*eps), r(d(i+1),j+3*eps+2)]) # Line 38.13 Y.append([ r(d(i),j), r(d(i),j+4), r(d(i+1),j+3*eps), r(d(i+1),j+3*eps+4)]) for alpha in [4,5]: for ra,sa in P(alpha,6): for raa,saa in P(alpha,6): for i in range(3): for ii in range(i+1,3): # Line 38.14 Y.append([ r(d(i),ra), r(d(i),sa), r(d(ii),raa), r(d(ii),saa)]) for g in range(6): for eps in range(2): for i in range(3): for ii in range(3): if i == ii: continue # Line 38.9 Y.append([ r(d(i),2*g+3*eps), r(d(i),2*g+6+3*eps), r(d(ii),2*g+1), r(d(ii),2*g+5)]) # Line 38.10 Y.append([ r(d(i),2*g+3*eps), r(d(i),2*g+6+3*eps), r(d(ii),2*g+2), r(d(ii),2*g+4)]) else: x,y,z,t = s for a in range(12): for aa in range(12): for aaa in range(12): aaaa = -(a+aa+aaa)%12 # Line 3 Y.append([r(x,a), r(y,aa), r(z,aaa), r(t,aaaa)]) return IncidenceStructure(12*n-10,Y,check=False,copy=False) def relabel_system(B): r""" Relabels the set so that `\{n-4, n-3, n-2, n-1\}` is in `B`. INPUT: - ``B`` -- a list of 4-uples on `0,...,n-1`. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import relabel_system sage: SQS8 = designs.steiner_quadruple_system(8) sage: relabel_system(SQS8) Incidence structure with 8 points and 14 blocks """ n = B.num_points() B0 = B._blocks[0] label = { B0[0] : n-4, B0[1] : n-3, B0[2] : n-2, B0[3] : n-1 } def get_label(x): if x in label: return label[x] else: total = len(label)-4 label[x] = total return total B = [[get_label(_) for _ in s] for s in B] return IncidenceStructure(n,B) def P(alpha, m): r""" Return the collection of pairs `P_{\alpha}(m)` For more information on this system, see [Han1960]_. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import P sage: P(3,4) [(0, 5), (2, 7), (4, 1), (6, 3)] """ if alpha >= 2*m-1: raise Exception if m%2==0: if alpha < m: if alpha%2 == 0: b = alpha // 2 return [(2*a, (2*a + 2*b + 1)%(2*m)) for a in range(m)] else: b = (alpha-1) // 2 return [(2*a, (2*a - 2*b - 1)%(2*m)) for a in range(m)] else: y = alpha - m pairs = [(b,(2*y-b)%(2*m)) for b in range(y)] pairs += [(c,(2*m+2*y-c-2)%(2*m)) for c in range(2*y+1,m+y-1)] pairs += [(2*m+int(-1.5-.5*(-1)**y),y),(2*m+int(-1.5+.5*(-1)**y),m+y-1)] return pairs else: if alpha < m-1: if alpha % 2 == 0: b = alpha // 2 return [(2*a,(2*a+2*b+1)%(2*m)) for a in range(m)] else: b = (alpha-1) // 2 return [(2*a,(2*a-2*b-1)%(2*m)) for a in range(m)] else: y = alpha-m+1 pairs = [(b,2*y-b) for b in range(y)] pairs += [(c,2*m+2*y-c) for c in range(2*y+1,m+y)] pairs += [(y,m+y)] return pairs def _missing_pair(n,l): r""" Return the smallest `(x,x+1)` that is not contained in `l`. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import _missing_pair sage: _missing_pair(6, [(0,1), (4,5)]) (2, 3) """ l = set(x for X in l for x in X) for x in range(n): if x not in l: break assert x not in l assert x + 1 not in l return (x, x + 1) def barP(eps, m): r""" Return the collection of pairs `\overline P_{\alpha}(m)` For more information on this system, see [Han1960]_. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import barP sage: barP(3,4) [(0, 4), (3, 5), (1, 2)] """ return barP_system(m)[eps] @cached_function def barP_system(m): r""" Return the 1-factorization of `K_{2m}` `\overline P(m)` For more information on this system, see [Han1960]_. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import barP_system sage: barP_system(3) [[(4, 3), (2, 5)], [(0, 5), (4, 1)], [(0, 2), (1, 3)], [(1, 5), (4, 2), (0, 3)], [(0, 4), (3, 5), (1, 2)], [(0, 1), (2, 3), (4, 5)]] """ isequal = lambda e1,e2 : e1 == e2 or e1 == tuple(reversed(e2)) pairs = [] last = [] if m % 2 == 0: # The first (shorter) collections of pairs, obtained from P by removing # pairs. Those are added to 'last', a new list of pairs last = [] for n in range(1, (m-2)//2+1): pairs.append([p for p in P(2*n,m) if not isequal(p,(2*n,(4*n+1)%(2*m)))]) last.append((2*n,(4*n+1)%(2*m))) pairs.append([p for p in P(2*n-1,m) if not isequal(p,(2*m-2-2*n,2*m-1-4*n))]) last.append((2*m-2-2*n,2*m-1-4*n)) pairs.append([p for p in P(m,m) if not isequal(p,(2*m-2,0))]) last.append((2*m-2,0)) pairs.append([p for p in P(m+1,m) if not isequal(p,(2*m-1,1))]) last.append((2*m-1,1)) assert all(len(pp) == m-1 for pp in pairs) assert len(last) == m # Pairs of normal length pairs.append(P(0,m)) pairs.append(P(m-1,m)) for alpha in range(m+2,2*m-1): pairs.append(P(alpha,m)) pairs.append(last) assert len(pairs) == 2*m # Now the points must be relabeled relabel = {} for n in range(1, (m-2)//2+1): relabel[2*n] = (4*n)%(2*m) relabel[4*n+1] = (4*n+1)%(2*m) relabel[2*m-2-2*n] = (4*n-2)%(2*m) relabel[2*m-1-4*n] = (4*n-1)%(2*m) relabel[2*m-2] = (1)%(2*m) relabel[0] = 0 relabel[2*m-1] = 2*m-1 relabel[1] = 2*m-2 else: # The first (shorter) collections of pairs, obtained from P by removing # pairs. Those are added to 'last', a new list of pairs last = [] for n in range((m - 3) // 2 + 1): pairs.append([p for p in P(2*n,m) if not isequal(p,(2*n,(4*n+1)%(2*m)))]) last.append((2*n,(4*n+1)%(2*m))) pairs.append([p for p in P(2*n+1,m) if not isequal(p,(2*m-2-2*n,2*m-3-4*n))]) last.append((2*m-2-2*n,2*m-3-4*n)) pairs.append([p for p in P(2*m-2,m) if not isequal(p,(m-1,2*m-1))]) last.append((m-1,2*m-1)) assert all(len(pp) == m-1 for pp in pairs) assert len(pairs) == m # Pairs of normal length for alpha in range(m-1,2*m-2): pairs.append(P(alpha,m)) pairs.append(last) assert len(pairs) == 2*m # Now the points must be relabeled relabel = {} for n in range((m - 3) // 2 + 1): relabel[2*n] = (4*n)%(2*m) relabel[4*n+1] = (4*n+1)%(2*m) relabel[2*m-2-2*n] = (4*n+2)%(2*m) relabel[2*m-3-4*n] = (4*n+3)%(2*m) relabel[m-1] = (2*m-2)%(2*m) relabel[2*m-1] = 2*m-1 assert len(relabel) == 2*m assert len(pairs) == 2*m # Relabeling the points pairs = [[(relabel[x],relabel[y]) for x,y in pp] for pp in pairs] # Pairs are sorted first according to their cardinality, then using the # number of the smallest point that they do NOT contain. pairs.sort(key=lambda x: _missing_pair(2*m+1,x)) return pairs @cached_function def steiner_quadruple_system(n, check = False): r""" Return a Steiner Quadruple System on `n` points. INPUT: - ``n`` -- an integer such that `n\equiv 2,4\pmod 6` - ``check`` (boolean) -- whether to check that the system is a Steiner Quadruple System before returning it (`False` by default) EXAMPLES:: sage: sqs4 = designs.steiner_quadruple_system(4) sage: sqs4 Incidence structure with 4 points and 1 blocks sage: sqs4.is_t_design(3,4,4,1) True sage: sqs8 = designs.steiner_quadruple_system(8) sage: sqs8 Incidence structure with 8 points and 14 blocks sage: sqs8.is_t_design(3,8,4,1) True TESTS:: sage: for n in range(4, 100): # long time ....: if (n%6) in [2,4]: # long time ....: sqs = designs.steiner_quadruple_system(n, check=True) # long time """ n = int(n) if not ((n%6) in [2, 4]): raise ValueError("n mod 6 must be equal to 2 or 4") elif n == 4: sqs = IncidenceStructure(4, [[0,1,2,3]], copy = False, check = False) elif n == 14: sqs = IncidenceStructure(14, _SQS14(), copy = False, check = False) elif n == 38: sqs = IncidenceStructure(38, _SQS38(), copy = False, check = False) elif n%12 in [4, 8]: nn = n // 2 sqs = two_n(steiner_quadruple_system(nn, check = False)) elif n%18 in [4,10]: nn = (n+2) // 3 sqs = three_n_minus_two(steiner_quadruple_system(nn, check = False)) elif (n%36) == 34: nn = (n+8) // 3 sqs = three_n_minus_eight(steiner_quadruple_system(nn, check = False)) elif (n%36) == 26: nn = (n+4) // 3 sqs = three_n_minus_four(steiner_quadruple_system(nn, check = False)) elif n%24 in [2, 10]: nn = (n+6) // 4 sqs = four_n_minus_six(steiner_quadruple_system(nn, check = False)) elif n%72 in [14, 38]: nn = (n+10) // 12 sqs = twelve_n_minus_ten(steiner_quadruple_system(nn, check = False)) else: raise ValueError("this should never happen") if check and not sqs.is_t_design(3,n,4,1): raise RuntimeError("something is very very wrong") return sqs def _SQS14(): r""" Return a Steiner Quadruple System on 14 points. Obtained from the La Jolla Covering Repository. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import _SQS14 sage: sqs14 = IncidenceStructure(_SQS14()) sage: sqs14.is_t_design(3,14,4,1) True """ return [[0, 1, 2, 5], [0, 1, 3, 6], [0, 1, 4, 13], [0, 1, 7, 10], [0, 1, 8, 9], [0, 1, 11, 12], [0, 2, 3, 4], [0, 2, 6, 12], [0, 2, 7, 9], [0, 2, 8, 11], [0, 2, 10, 13], [0, 3, 5, 13], [0, 3, 7, 11], [0, 3, 8, 10], [0, 3, 9, 12], [0, 4, 5, 9], [0, 4, 6, 11], [0, 4, 7, 8], [0, 4, 10, 12], [0, 5, 6, 8], [0, 5, 7, 12], [0, 5, 10, 11], [0, 6, 7, 13], [0, 6, 9, 10], [0, 8, 12, 13], [0, 9, 11, 13], [1, 2, 3, 13], [1, 2, 4, 12], [1, 2, 6, 9], [1, 2, 7, 11], [1, 2, 8, 10], [1, 3, 4, 5], [1, 3, 7, 8], [1, 3, 9, 11], [1, 3, 10, 12], [1, 4, 6, 10], [1, 4, 7, 9], [1, 4, 8, 11], [1, 5, 6, 11], [1, 5, 7, 13], [1, 5, 8, 12], [1, 5, 9, 10], [1, 6, 7, 12], [1, 6, 8, 13], [1, 9, 12, 13], [1, 10, 11, 13], [2, 3, 5, 11], [2, 3, 6, 7], [2, 3, 8, 12], [2, 3, 9, 10], [2, 4, 5, 13], [2, 4, 6, 8], [2, 4, 7, 10], [2, 4, 9, 11], [2, 5, 6, 10], [2, 5, 7, 8], [2, 5, 9, 12], [2, 6, 11, 13], [2, 7, 12, 13], [2, 8, 9, 13], [2, 10, 11, 12], [3, 4, 6, 9], [3, 4, 7, 12], [3, 4, 8, 13], [3, 4, 10, 11], [3, 5, 6, 12], [3, 5, 7, 10], [3, 5, 8, 9], [3, 6, 8, 11], [3, 6, 10, 13], [3, 7, 9, 13], [3, 11, 12, 13], [4, 5, 6, 7], [4, 5, 8, 10], [4, 5, 11, 12], [4, 6, 12, 13], [4, 7, 11, 13], [4, 8, 9, 12], [4, 9, 10, 13], [5, 6, 9, 13], [5, 7, 9, 11], [5, 8, 11, 13], [5, 10, 12, 13], [6, 7, 8, 9], [6, 7, 10, 11], [6, 8, 10, 12], [6, 9, 11, 12], [7, 8, 10, 13], [7, 8, 11, 12], [7, 9, 10, 12], [8, 9, 10, 11]] def _SQS38(): r""" Return a Steiner Quadruple System on 14 points. Obtained from the La Jolla Covering Repository. EXAMPLES:: sage: from sage.combinat.designs.steiner_quadruple_systems import _SQS38 sage: sqs38 = IncidenceStructure(_SQS38()) sage: sqs38.is_t_design(3,38,4,1) True """ # From the La Jolla Covering Repository return [[0, 1, 2, 14], [0, 1, 3, 34], [0, 1, 4, 31], [0, 1, 5, 27], [0, 1, 6, 17], [0, 1, 7, 12], [0, 1, 8, 36], [0, 1, 9, 10], [0, 1, 11, 18], [0, 1, 13, 37], [0, 1, 15, 35], [0, 1, 16, 22], [0, 1, 19, 33], [0, 1, 20, 25], [0, 1, 21, 23], [0, 1, 24, 32], [0, 1, 26, 28], [0, 1, 29, 30], [0, 2, 3, 10], [0, 2, 4, 9], [0, 2, 5, 28], [0, 2, 6, 15], [0, 2, 7, 36], [0, 2, 8, 23], [0, 2, 11, 22], [0, 2, 12, 13], [0, 2, 16, 25], [0, 2, 17, 18], [0, 2, 19, 30], [0, 2, 20, 35], [0, 2, 21, 29], [0, 2, 24, 34], [0, 2, 26, 31], [0, 2, 27, 32], [0, 2, 33, 37], [0, 3, 4, 18], [0, 3, 5, 23], [0, 3, 6, 32], [0, 3, 7, 19], [0, 3, 8, 20], [0, 3, 9, 17], [0, 3, 11, 25], [0, 3, 12, 24], [0, 3, 13, 27], [0, 3, 14, 31], [0, 3, 15, 22], [0, 3, 16, 28], [0, 3, 21, 33], [0, 3, 26, 36], [0, 3, 29, 35], [0, 3, 30, 37], [0, 4, 5, 7], [0, 4, 6, 28], [0, 4, 8, 25], [0, 4, 10, 30], [0, 4, 11, 20], [0, 4, 12, 32], [0, 4, 13, 36], [0, 4, 14, 29], [0, 4, 15, 27], [0, 4, 16, 35], [0, 4, 17, 22], [0, 4, 19, 23], [0, 4, 21, 34], [0, 4, 24, 33], [0, 4, 26, 37], [0, 5, 6, 24], [0, 5, 8, 26], [0, 5, 9, 29], [0, 5, 10, 20], [0, 5, 11, 13], [0, 5, 12, 14], [0, 5, 15, 33], [0, 5, 16, 37], [0, 5, 17, 35], [0, 5, 18, 19], [0, 5, 21, 25], [0, 5, 22, 30], [0, 5, 31, 32], [0, 5, 34, 36], [0, 6, 7, 30], [0, 6, 8, 33], [0, 6, 9, 12], [0, 6, 10, 18], [0, 6, 11, 37], [0, 6, 13, 31], [0, 6, 14, 35], [0, 6, 16, 29], [0, 6, 19, 25], [0, 6, 20, 27], [0, 6, 21, 36], [0, 6, 22, 23], [0, 6, 26, 34], [0, 7, 8, 11], [0, 7, 9, 33], [0, 7, 10, 21], [0, 7, 13, 20], [0, 7, 14, 22], [0, 7, 15, 31], [0, 7, 16, 34], [0, 7, 17, 29], [0, 7, 18, 24], [0, 7, 23, 26], [0, 7, 25, 32], [0, 7, 27, 28], [0, 7, 35, 37], [0, 8, 9, 37], [0, 8, 10, 27], [0, 8, 12, 18], [0, 8, 13, 30], [0, 8, 14, 15], [0, 8, 16, 21], [0, 8, 17, 19], [0, 8, 22, 35], [0, 8, 24, 31], [0, 8, 28, 34], [0, 8, 29, 32], [0, 9, 11, 30], [0, 9, 13, 23], [0, 9, 14, 18], [0, 9, 15, 25], [0, 9, 16, 26], [0, 9, 19, 28], [0, 9, 20, 36], [0, 9, 21, 35], [0, 9, 22, 24], [0, 9, 27, 31], [0, 9, 32, 34], [0, 10, 11, 36], [0, 10, 12, 15], [0, 10, 13, 26], [0, 10, 14, 16], [0, 10, 17, 37], [0, 10, 19, 29], [0, 10, 22, 31], [0, 10, 23, 32], [0, 10, 24, 35], [0, 10, 25, 34], [0, 10, 28, 33], [0, 11, 12, 16], [0, 11, 14, 24], [0, 11, 15, 26], [0, 11, 17, 31], [0, 11, 19, 21], [0, 11, 23, 34], [0, 11, 27, 29], [0, 11, 28, 35], [0, 11, 32, 33], [0, 12, 17, 20], [0, 12, 19, 35], [0, 12, 21, 28], [0, 12, 22, 25], [0, 12, 23, 27], [0, 12, 26, 29], [0, 12, 30, 33], [0, 12, 31, 34], [0, 12, 36, 37], [0, 13, 14, 33], [0, 13, 15, 29], [0, 13, 16, 24], [0, 13, 17, 21], [0, 13, 18, 34], [0, 13, 19, 32], [0, 13, 22, 28], [0, 13, 25, 35], [0, 14, 17, 26], [0, 14, 19, 20], [0, 14, 21, 32], [0, 14, 23, 36], [0, 14, 25, 28], [0, 14, 27, 30], [0, 14, 34, 37], [0, 15, 16, 36], [0, 15, 17, 23], [0, 15, 18, 20], [0, 15, 19, 34], [0, 15, 21, 37], [0, 15, 24, 28], [0, 15, 30, 32], [0, 16, 17, 32], [0, 16, 18, 27], [0, 16, 19, 31], [0, 16, 20, 33], [0, 16, 23, 30], [0, 17, 24, 27], [0, 17, 25, 33], [0, 17, 28, 36], [0, 17, 30, 34], [0, 18, 21, 26], [0, 18, 22, 29], [0, 18, 23, 28], [0, 18, 25, 31], [0, 18, 30, 35], [0, 18, 32, 37], [0, 18, 33, 36], [0, 19, 22, 26], [0, 19, 24, 37], [0, 19, 27, 36], [0, 20, 21, 31], [0, 20, 22, 37], [0, 20, 23, 24], [0, 20, 26, 30], [0, 20, 28, 32], [0, 20, 29, 34], [0, 21, 22, 27], [0, 21, 24, 30], [0, 22, 32, 36], [0, 22, 33, 34], [0, 23, 25, 29], [0, 23, 31, 37], [0, 23, 33, 35], [0, 24, 25, 26], [0, 24, 29, 36], [0, 25, 27, 37], [0, 25, 30, 36], [0, 26, 27, 33], [0, 26, 32, 35], [0, 27, 34, 35], [0, 28, 29, 37], [0, 28, 30, 31], [0, 29, 31, 33], [0, 31, 35, 36], [1, 2, 3, 15], [1, 2, 4, 35], [1, 2, 5, 32], [1, 2, 6, 28], [1, 2, 7, 18], [1, 2, 8, 13], [1, 2, 9, 37], [1, 2, 10, 11], [1, 2, 12, 19], [1, 2, 16, 36], [1, 2, 17, 23], [1, 2, 20, 34], [1, 2, 21, 26], [1, 2, 22, 24], [1, 2, 25, 33], [1, 2, 27, 29], [1, 2, 30, 31], [1, 3, 4, 11], [1, 3, 5, 10], [1, 3, 6, 29], [1, 3, 7, 16], [1, 3, 8, 37], [1, 3, 9, 24], [1, 3, 12, 23], [1, 3, 13, 14], [1, 3, 17, 26], [1, 3, 18, 19], [1, 3, 20, 31], [1, 3, 21, 36], [1, 3, 22, 30], [1, 3, 25, 35], [1, 3, 27, 32], [1, 3, 28, 33], [1, 4, 5, 19], [1, 4, 6, 24], [1, 4, 7, 33], [1, 4, 8, 20], [1, 4, 9, 21], [1, 4, 10, 18], [1, 4, 12, 26], [1, 4, 13, 25], [1, 4, 14, 28], [1, 4, 15, 32], [1, 4, 16, 23], [1, 4, 17, 29], [1, 4, 22, 34], [1, 4, 27, 37], [1, 4, 30, 36], [1, 5, 6, 8], [1, 5, 7, 29], [1, 5, 9, 26], [1, 5, 11, 31], [1, 5, 12, 21], [1, 5, 13, 33], [1, 5, 14, 37], [1, 5, 15, 30], [1, 5, 16, 28], [1, 5, 17, 36], [1, 5, 18, 23], [1, 5, 20, 24], [1, 5, 22, 35], [1, 5, 25, 34], [1, 6, 7, 25], [1, 6, 9, 27], [1, 6, 10, 30], [1, 6, 11, 21], [1, 6, 12, 14], [1, 6, 13, 15], [1, 6, 16, 34], [1, 6, 18, 36], [1, 6, 19, 20], [1, 6, 22, 26], [1, 6, 23, 31], [1, 6, 32, 33], [1, 6, 35, 37], [1, 7, 8, 31], [1, 7, 9, 34], [1, 7, 10, 13], [1, 7, 11, 19], [1, 7, 14, 32], [1, 7, 15, 36], [1, 7, 17, 30], [1, 7, 20, 26], [1, 7, 21, 28], [1, 7, 22, 37], [1, 7, 23, 24], [1, 7, 27, 35], [1, 8, 9, 12], [1, 8, 10, 34], [1, 8, 11, 22], [1, 8, 14, 21], [1, 8, 15, 23], [1, 8, 16, 32], [1, 8, 17, 35], [1, 8, 18, 30], [1, 8, 19, 25], [1, 8, 24, 27], [1, 8, 26, 33], [1, 8, 28, 29], [1, 9, 11, 28], [1, 9, 13, 19], [1, 9, 14, 31], [1, 9, 15, 16], [1, 9, 17, 22], [1, 9, 18, 20], [1, 9, 23, 36], [1, 9, 25, 32], [1, 9, 29, 35], [1, 9, 30, 33], [1, 10, 12, 31], [1, 10, 14, 24], [1, 10, 15, 19], [1, 10, 16, 26], [1, 10, 17, 27], [1, 10, 20, 29], [1, 10, 21, 37], [1, 10, 22, 36], [1, 10, 23, 25], [1, 10, 28, 32], [1, 10, 33, 35], [1, 11, 12, 37], [1, 11, 13, 16], [1, 11, 14, 27], [1, 11, 15, 17], [1, 11, 20, 30], [1, 11, 23, 32], [1, 11, 24, 33], [1, 11, 25, 36], [1, 11, 26, 35], [1, 11, 29, 34], [1, 12, 13, 17], [1, 12, 15, 25], [1, 12, 16, 27], [1, 12, 18, 32], [1, 12, 20, 22], [1, 12, 24, 35], [1, 12, 28, 30], [1, 12, 29, 36], [1, 12, 33, 34], [1, 13, 18, 21], [1, 13, 20, 36], [1, 13, 22, 29], [1, 13, 23, 26], [1, 13, 24, 28], [1, 13, 27, 30], [1, 13, 31, 34], [1, 13, 32, 35], [1, 14, 15, 34], [1, 14, 16, 30], [1, 14, 17, 25], [1, 14, 18, 22], [1, 14, 19, 35], [1, 14, 20, 33], [1, 14, 23, 29], [1, 14, 26, 36], [1, 15, 18, 27], [1, 15, 20, 21], [1, 15, 22, 33], [1, 15, 24, 37], [1, 15, 26, 29], [1, 15, 28, 31], [1, 16, 17, 37], [1, 16, 18, 24], [1, 16, 19, 21], [1, 16, 20, 35], [1, 16, 25, 29], [1, 16, 31, 33], [1, 17, 18, 33], [1, 17, 19, 28], [1, 17, 20, 32], [1, 17, 21, 34], [1, 17, 24, 31], [1, 18, 25, 28], [1, 18, 26, 34], [1, 18, 29, 37], [1, 18, 31, 35], [1, 19, 22, 27], [1, 19, 23, 30], [1, 19, 24, 29], [1, 19, 26, 32], [1, 19, 31, 36], [1, 19, 34, 37], [1, 20, 23, 27], [1, 20, 28, 37], [1, 21, 22, 32], [1, 21, 24, 25], [1, 21, 27, 31], [1, 21, 29, 33], [1, 21, 30, 35], [1, 22, 23, 28], [1, 22, 25, 31], [1, 23, 33, 37], [1, 23, 34, 35], [1, 24, 26, 30], [1, 24, 34, 36], [1, 25, 26, 27], [1, 25, 30, 37], [1, 26, 31, 37], [1, 27, 28, 34], [1, 27, 33, 36], [1, 28, 35, 36], [1, 29, 31, 32], [1, 30, 32, 34], [1, 32, 36, 37], [2, 3, 4, 16], [2, 3, 5, 36], [2, 3, 6, 33], [2, 3, 7, 29], [2, 3, 8, 19], [2, 3, 9, 14], [2, 3, 11, 12], [2, 3, 13, 20], [2, 3, 17, 37], [2, 3, 18, 24], [2, 3, 21, 35], [2, 3, 22, 27], [2, 3, 23, 25], [2, 3, 26, 34], [2, 3, 28, 30], [2, 3, 31, 32], [2, 4, 5, 12], [2, 4, 6, 11], [2, 4, 7, 30], [2, 4, 8, 17], [2, 4, 10, 25], [2, 4, 13, 24], [2, 4, 14, 15], [2, 4, 18, 27], [2, 4, 19, 20], [2, 4, 21, 32], [2, 4, 22, 37], [2, 4, 23, 31], [2, 4, 26, 36], [2, 4, 28, 33], [2, 4, 29, 34], [2, 5, 6, 20], [2, 5, 7, 25], [2, 5, 8, 34], [2, 5, 9, 21], [2, 5, 10, 22], [2, 5, 11, 19], [2, 5, 13, 27], [2, 5, 14, 26], [2, 5, 15, 29], [2, 5, 16, 33], [2, 5, 17, 24], [2, 5, 18, 30], [2, 5, 23, 35], [2, 5, 31, 37], [2, 6, 7, 9], [2, 6, 8, 30], [2, 6, 10, 27], [2, 6, 12, 32], [2, 6, 13, 22], [2, 6, 14, 34], [2, 6, 16, 31], [2, 6, 17, 29], [2, 6, 18, 37], [2, 6, 19, 24], [2, 6, 21, 25], [2, 6, 23, 36], [2, 6, 26, 35], [2, 7, 8, 26], [2, 7, 10, 28], [2, 7, 11, 31], [2, 7, 12, 22], [2, 7, 13, 15], [2, 7, 14, 16], [2, 7, 17, 35], [2, 7, 19, 37], [2, 7, 20, 21], [2, 7, 23, 27], [2, 7, 24, 32], [2, 7, 33, 34], [2, 8, 9, 32], [2, 8, 10, 35], [2, 8, 11, 14], [2, 8, 12, 20], [2, 8, 15, 33], [2, 8, 16, 37], [2, 8, 18, 31], [2, 8, 21, 27], [2, 8, 22, 29], [2, 8, 24, 25], [2, 8, 28, 36], [2, 9, 10, 13], [2, 9, 11, 35], [2, 9, 12, 23], [2, 9, 15, 22], [2, 9, 16, 24], [2, 9, 17, 33], [2, 9, 18, 36], [2, 9, 19, 31], [2, 9, 20, 26], [2, 9, 25, 28], [2, 9, 27, 34], [2, 9, 29, 30], [2, 10, 12, 29], [2, 10, 14, 20], [2, 10, 15, 32], [2, 10, 16, 17], [2, 10, 18, 23], [2, 10, 19, 21], [2, 10, 24, 37], [2, 10, 26, 33], [2, 10, 30, 36], [2, 10, 31, 34], [2, 11, 13, 32], [2, 11, 15, 25], [2, 11, 16, 20], [2, 11, 17, 27], [2, 11, 18, 28], [2, 11, 21, 30], [2, 11, 23, 37], [2, 11, 24, 26], [2, 11, 29, 33], [2, 11, 34, 36], [2, 12, 14, 17], [2, 12, 15, 28], [2, 12, 16, 18], [2, 12, 21, 31], [2, 12, 24, 33], [2, 12, 25, 34], [2, 12, 26, 37], [2, 12, 27, 36], [2, 12, 30, 35], [2, 13, 14, 18], [2, 13, 16, 26], [2, 13, 17, 28], [2, 13, 19, 33], [2, 13, 21, 23], [2, 13, 25, 36], [2, 13, 29, 31], [2, 13, 30, 37], [2, 13, 34, 35], [2, 14, 19, 22], [2, 14, 21, 37], [2, 14, 23, 30], [2, 14, 24, 27], [2, 14, 25, 29], [2, 14, 28, 31], [2, 14, 32, 35], [2, 14, 33, 36], [2, 15, 16, 35], [2, 15, 17, 31], [2, 15, 18, 26], [2, 15, 19, 23], [2, 15, 20, 36], [2, 15, 21, 34], [2, 15, 24, 30], [2, 15, 27, 37], [2, 16, 19, 28], [2, 16, 21, 22], [2, 16, 23, 34], [2, 16, 27, 30], [2, 16, 29, 32], [2, 17, 19, 25], [2, 17, 20, 22], [2, 17, 21, 36], [2, 17, 26, 30], [2, 17, 32, 34], [2, 18, 19, 34], [2, 18, 20, 29], [2, 18, 21, 33], [2, 18, 22, 35], [2, 18, 25, 32], [2, 19, 26, 29], [2, 19, 27, 35], [2, 19, 32, 36], [2, 20, 23, 28], [2, 20, 24, 31], [2, 20, 25, 30], [2, 20, 27, 33], [2, 20, 32, 37], [2, 21, 24, 28], [2, 22, 23, 33], [2, 22, 25, 26], [2, 22, 28, 32], [2, 22, 30, 34], [2, 22, 31, 36], [2, 23, 24, 29], [2, 23, 26, 32], [2, 24, 35, 36], [2, 25, 27, 31], [2, 25, 35, 37], [2, 26, 27, 28], [2, 28, 29, 35], [2, 28, 34, 37], [2, 29, 36, 37], [2, 30, 32, 33], [2, 31, 33, 35], [3, 4, 5, 17], [3, 4, 6, 37], [3, 4, 7, 34], [3, 4, 8, 30], [3, 4, 9, 20], [3, 4, 10, 15], [3, 4, 12, 13], [3, 4, 14, 21], [3, 4, 19, 25], [3, 4, 22, 36], [3, 4, 23, 28], [3, 4, 24, 26], [3, 4, 27, 35], [3, 4, 29, 31], [3, 4, 32, 33], [3, 5, 6, 13], [3, 5, 7, 12], [3, 5, 8, 31], [3, 5, 9, 18], [3, 5, 11, 26], [3, 5, 14, 25], [3, 5, 15, 16], [3, 5, 19, 28], [3, 5, 20, 21], [3, 5, 22, 33], [3, 5, 24, 32], [3, 5, 27, 37], [3, 5, 29, 34], [3, 5, 30, 35], [3, 6, 7, 21], [3, 6, 8, 26], [3, 6, 9, 35], [3, 6, 10, 22], [3, 6, 11, 23], [3, 6, 12, 20], [3, 6, 14, 28], [3, 6, 15, 27], [3, 6, 16, 30], [3, 6, 17, 34], [3, 6, 18, 25], [3, 6, 19, 31], [3, 6, 24, 36], [3, 7, 8, 10], [3, 7, 9, 31], [3, 7, 11, 28], [3, 7, 13, 33], [3, 7, 14, 23], [3, 7, 15, 35], [3, 7, 17, 32], [3, 7, 18, 30], [3, 7, 20, 25], [3, 7, 22, 26], [3, 7, 24, 37], [3, 7, 27, 36], [3, 8, 9, 27], [3, 8, 11, 29], [3, 8, 12, 32], [3, 8, 13, 23], [3, 8, 14, 16], [3, 8, 15, 17], [3, 8, 18, 36], [3, 8, 21, 22], [3, 8, 24, 28], [3, 8, 25, 33], [3, 8, 34, 35], [3, 9, 10, 33], [3, 9, 11, 36], [3, 9, 12, 15], [3, 9, 13, 21], [3, 9, 16, 34], [3, 9, 19, 32], [3, 9, 22, 28], [3, 9, 23, 30], [3, 9, 25, 26], [3, 9, 29, 37], [3, 10, 11, 14], [3, 10, 12, 36], [3, 10, 13, 24], [3, 10, 16, 23], [3, 10, 17, 25], [3, 10, 18, 34], [3, 10, 19, 37], [3, 10, 20, 32], [3, 10, 21, 27], [3, 10, 26, 29], [3, 10, 28, 35], [3, 10, 30, 31], [3, 11, 13, 30], [3, 11, 15, 21], [3, 11, 16, 33], [3, 11, 17, 18], [3, 11, 19, 24], [3, 11, 20, 22], [3, 11, 27, 34], [3, 11, 31, 37], [3, 11, 32, 35], [3, 12, 14, 33], [3, 12, 16, 26], [3, 12, 17, 21], [3, 12, 18, 28], [3, 12, 19, 29], [3, 12, 22, 31], [3, 12, 25, 27], [3, 12, 30, 34], [3, 12, 35, 37], [3, 13, 15, 18], [3, 13, 16, 29], [3, 13, 17, 19], [3, 13, 22, 32], [3, 13, 25, 34], [3, 13, 26, 35], [3, 13, 28, 37], [3, 13, 31, 36], [3, 14, 15, 19], [3, 14, 17, 27], [3, 14, 18, 29], [3, 14, 20, 34], [3, 14, 22, 24], [3, 14, 26, 37], [3, 14, 30, 32], [3, 14, 35, 36], [3, 15, 20, 23], [3, 15, 24, 31], [3, 15, 25, 28], [3, 15, 26, 30], [3, 15, 29, 32], [3, 15, 33, 36], [3, 15, 34, 37], [3, 16, 17, 36], [3, 16, 18, 32], [3, 16, 19, 27], [3, 16, 20, 24], [3, 16, 21, 37], [3, 16, 22, 35], [3, 16, 25, 31], [3, 17, 20, 29], [3, 17, 22, 23], [3, 17, 24, 35], [3, 17, 28, 31], [3, 17, 30, 33], [3, 18, 20, 26], [3, 18, 21, 23], [3, 18, 22, 37], [3, 18, 27, 31], [3, 18, 33, 35], [3, 19, 20, 35], [3, 19, 21, 30], [3, 19, 22, 34], [3, 19, 23, 36], [3, 19, 26, 33], [3, 20, 27, 30], [3, 20, 28, 36], [3, 20, 33, 37], [3, 21, 24, 29], [3, 21, 25, 32], [3, 21, 26, 31], [3, 21, 28, 34], [3, 22, 25, 29], [3, 23, 24, 34], [3, 23, 26, 27], [3, 23, 29, 33], [3, 23, 31, 35], [3, 23, 32, 37], [3, 24, 25, 30], [3, 24, 27, 33], [3, 25, 36, 37], [3, 26, 28, 32], [3, 27, 28, 29], [3, 29, 30, 36], [3, 31, 33, 34], [3, 32, 34, 36], [4, 5, 6, 18], [4, 5, 8, 35], [4, 5, 9, 31], [4, 5, 10, 21], [4, 5, 11, 16], [4, 5, 13, 14], [4, 5, 15, 22], [4, 5, 20, 26], [4, 5, 23, 37], [4, 5, 24, 29], [4, 5, 25, 27], [4, 5, 28, 36], [4, 5, 30, 32], [4, 5, 33, 34], [4, 6, 7, 14], [4, 6, 8, 13], [4, 6, 9, 32], [4, 6, 10, 19], [4, 6, 12, 27], [4, 6, 15, 26], [4, 6, 16, 17], [4, 6, 20, 29], [4, 6, 21, 22], [4, 6, 23, 34], [4, 6, 25, 33], [4, 6, 30, 35], [4, 6, 31, 36], [4, 7, 8, 22], [4, 7, 9, 27], [4, 7, 10, 36], [4, 7, 11, 23], [4, 7, 12, 24], [4, 7, 13, 21], [4, 7, 15, 29], [4, 7, 16, 28], [4, 7, 17, 31], [4, 7, 18, 35], [4, 7, 19, 26], [4, 7, 20, 32], [4, 7, 25, 37], [4, 8, 9, 11], [4, 8, 10, 32], [4, 8, 12, 29], [4, 8, 14, 34], [4, 8, 15, 24], [4, 8, 16, 36], [4, 8, 18, 33], [4, 8, 19, 31], [4, 8, 21, 26], [4, 8, 23, 27], [4, 8, 28, 37], [4, 9, 10, 28], [4, 9, 12, 30], [4, 9, 13, 33], [4, 9, 14, 24], [4, 9, 15, 17], [4, 9, 16, 18], [4, 9, 19, 37], [4, 9, 22, 23], [4, 9, 25, 29], [4, 9, 26, 34], [4, 9, 35, 36], [4, 10, 11, 34], [4, 10, 12, 37], [4, 10, 13, 16], [4, 10, 14, 22], [4, 10, 17, 35], [4, 10, 20, 33], [4, 10, 23, 29], [4, 10, 24, 31], [4, 10, 26, 27], [4, 11, 12, 15], [4, 11, 13, 37], [4, 11, 14, 25], [4, 11, 17, 24], [4, 11, 18, 26], [4, 11, 19, 35], [4, 11, 21, 33], [4, 11, 22, 28], [4, 11, 27, 30], [4, 11, 29, 36], [4, 11, 31, 32], [4, 12, 14, 31], [4, 12, 16, 22], [4, 12, 17, 34], [4, 12, 18, 19], [4, 12, 20, 25], [4, 12, 21, 23], [4, 12, 28, 35], [4, 12, 33, 36], [4, 13, 15, 34], [4, 13, 17, 27], [4, 13, 18, 22], [4, 13, 19, 29], [4, 13, 20, 30], [4, 13, 23, 32], [4, 13, 26, 28], [4, 13, 31, 35], [4, 14, 16, 19], [4, 14, 17, 30], [4, 14, 18, 20], [4, 14, 23, 33], [4, 14, 26, 35], [4, 14, 27, 36], [4, 14, 32, 37], [4, 15, 16, 20], [4, 15, 18, 28], [4, 15, 19, 30], [4, 15, 21, 35], [4, 15, 23, 25], [4, 15, 31, 33], [4, 15, 36, 37], [4, 16, 21, 24], [4, 16, 25, 32], [4, 16, 26, 29], [4, 16, 27, 31], [4, 16, 30, 33], [4, 16, 34, 37], [4, 17, 18, 37], [4, 17, 19, 33], [4, 17, 20, 28], [4, 17, 21, 25], [4, 17, 23, 36], [4, 17, 26, 32], [4, 18, 21, 30], [4, 18, 23, 24], [4, 18, 25, 36], [4, 18, 29, 32], [4, 18, 31, 34], [4, 19, 21, 27], [4, 19, 22, 24], [4, 19, 28, 32], [4, 19, 34, 36], [4, 20, 21, 36], [4, 20, 22, 31], [4, 20, 23, 35], [4, 20, 24, 37], [4, 20, 27, 34], [4, 21, 28, 31], [4, 21, 29, 37], [4, 22, 25, 30], [4, 22, 26, 33], [4, 22, 27, 32], [4, 22, 29, 35], [4, 23, 26, 30], [4, 24, 25, 35], [4, 24, 27, 28], [4, 24, 30, 34], [4, 24, 32, 36], [4, 25, 26, 31], [4, 25, 28, 34], [4, 27, 29, 33], [4, 28, 29, 30], [4, 30, 31, 37], [4, 32, 34, 35], [4, 33, 35, 37], [5, 6, 7, 19], [5, 6, 9, 36], [5, 6, 10, 32], [5, 6, 11, 22], [5, 6, 12, 17], [5, 6, 14, 15], [5, 6, 16, 23], [5, 6, 21, 27], [5, 6, 25, 30], [5, 6, 26, 28], [5, 6, 29, 37], [5, 6, 31, 33], [5, 6, 34, 35], [5, 7, 8, 15], [5, 7, 9, 14], [5, 7, 10, 33], [5, 7, 11, 20], [5, 7, 13, 28], [5, 7, 16, 27], [5, 7, 17, 18], [5, 7, 21, 30], [5, 7, 22, 23], [5, 7, 24, 35], [5, 7, 26, 34], [5, 7, 31, 36], [5, 7, 32, 37], [5, 8, 9, 23], [5, 8, 10, 28], [5, 8, 11, 37], [5, 8, 12, 24], [5, 8, 13, 25], [5, 8, 14, 22], [5, 8, 16, 30], [5, 8, 17, 29], [5, 8, 18, 32], [5, 8, 19, 36], [5, 8, 20, 27], [5, 8, 21, 33], [5, 9, 10, 12], [5, 9, 11, 33], [5, 9, 13, 30], [5, 9, 15, 35], [5, 9, 16, 25], [5, 9, 17, 37], [5, 9, 19, 34], [5, 9, 20, 32], [5, 9, 22, 27], [5, 9, 24, 28], [5, 10, 11, 29], [5, 10, 13, 31], [5, 10, 14, 34], [5, 10, 15, 25], [5, 10, 16, 18], [5, 10, 17, 19], [5, 10, 23, 24], [5, 10, 26, 30], [5, 10, 27, 35], [5, 10, 36, 37], [5, 11, 12, 35], [5, 11, 14, 17], [5, 11, 15, 23], [5, 11, 18, 36], [5, 11, 21, 34], [5, 11, 24, 30], [5, 11, 25, 32], [5, 11, 27, 28], [5, 12, 13, 16], [5, 12, 15, 26], [5, 12, 18, 25], [5, 12, 19, 27], [5, 12, 20, 36], [5, 12, 22, 34], [5, 12, 23, 29], [5, 12, 28, 31], [5, 12, 30, 37], [5, 12, 32, 33], [5, 13, 15, 32], [5, 13, 17, 23], [5, 13, 18, 35], [5, 13, 19, 20], [5, 13, 21, 26], [5, 13, 22, 24], [5, 13, 29, 36], [5, 13, 34, 37], [5, 14, 16, 35], [5, 14, 18, 28], [5, 14, 19, 23], [5, 14, 20, 30], [5, 14, 21, 31], [5, 14, 24, 33], [5, 14, 27, 29], [5, 14, 32, 36], [5, 15, 17, 20], [5, 15, 18, 31], [5, 15, 19, 21], [5, 15, 24, 34], [5, 15, 27, 36], [5, 15, 28, 37], [5, 16, 17, 21], [5, 16, 19, 29], [5, 16, 20, 31], [5, 16, 22, 36], [5, 16, 24, 26], [5, 16, 32, 34], [5, 17, 22, 25], [5, 17, 26, 33], [5, 17, 27, 30], [5, 17, 28, 32], [5, 17, 31, 34], [5, 18, 20, 34], [5, 18, 21, 29], [5, 18, 22, 26], [5, 18, 24, 37], [5, 18, 27, 33], [5, 19, 22, 31], [5, 19, 24, 25], [5, 19, 26, 37], [5, 19, 30, 33], [5, 19, 32, 35], [5, 20, 22, 28], [5, 20, 23, 25], [5, 20, 29, 33], [5, 20, 35, 37], [5, 21, 22, 37], [5, 21, 23, 32], [5, 21, 24, 36], [5, 21, 28, 35], [5, 22, 29, 32], [5, 23, 26, 31], [5, 23, 27, 34], [5, 23, 28, 33], [5, 23, 30, 36], [5, 24, 27, 31], [5, 25, 26, 36], [5, 25, 28, 29], [5, 25, 31, 35], [5, 25, 33, 37], [5, 26, 27, 32], [5, 26, 29, 35], [5, 28, 30, 34], [5, 29, 30, 31], [5, 33, 35, 36], [6, 7, 8, 20], [6, 7, 10, 37], [6, 7, 11, 33], [6, 7, 12, 23], [6, 7, 13, 18], [6, 7, 15, 16], [6, 7, 17, 24], [6, 7, 22, 28], [6, 7, 26, 31], [6, 7, 27, 29], [6, 7, 32, 34], [6, 7, 35, 36], [6, 8, 9, 16], [6, 8, 10, 15], [6, 8, 11, 34], [6, 8, 12, 21], [6, 8, 14, 29], [6, 8, 17, 28], [6, 8, 18, 19], [6, 8, 22, 31], [6, 8, 23, 24], [6, 8, 25, 36], [6, 8, 27, 35], [6, 8, 32, 37], [6, 9, 10, 24], [6, 9, 11, 29], [6, 9, 13, 25], [6, 9, 14, 26], [6, 9, 15, 23], [6, 9, 17, 31], [6, 9, 18, 30], [6, 9, 19, 33], [6, 9, 20, 37], [6, 9, 21, 28], [6, 9, 22, 34], [6, 10, 11, 13], [6, 10, 12, 34], [6, 10, 14, 31], [6, 10, 16, 36], [6, 10, 17, 26], [6, 10, 20, 35], [6, 10, 21, 33], [6, 10, 23, 28], [6, 10, 25, 29], [6, 11, 12, 30], [6, 11, 14, 32], [6, 11, 15, 35], [6, 11, 16, 26], [6, 11, 17, 19], [6, 11, 18, 20], [6, 11, 24, 25], [6, 11, 27, 31], [6, 11, 28, 36], [6, 12, 13, 36], [6, 12, 15, 18], [6, 12, 16, 24], [6, 12, 19, 37], [6, 12, 22, 35], [6, 12, 25, 31], [6, 12, 26, 33], [6, 12, 28, 29], [6, 13, 14, 17], [6, 13, 16, 27], [6, 13, 19, 26], [6, 13, 20, 28], [6, 13, 21, 37], [6, 13, 23, 35], [6, 13, 24, 30], [6, 13, 29, 32], [6, 13, 33, 34], [6, 14, 16, 33], [6, 14, 18, 24], [6, 14, 19, 36], [6, 14, 20, 21], [6, 14, 22, 27], [6, 14, 23, 25], [6, 14, 30, 37], [6, 15, 17, 36], [6, 15, 19, 29], [6, 15, 20, 24], [6, 15, 21, 31], [6, 15, 22, 32], [6, 15, 25, 34], [6, 15, 28, 30], [6, 15, 33, 37], [6, 16, 18, 21], [6, 16, 19, 32], [6, 16, 20, 22], [6, 16, 25, 35], [6, 16, 28, 37], [6, 17, 18, 22], [6, 17, 20, 30], [6, 17, 21, 32], [6, 17, 23, 37], [6, 17, 25, 27], [6, 17, 33, 35], [6, 18, 23, 26], [6, 18, 27, 34], [6, 18, 28, 31], [6, 18, 29, 33], [6, 18, 32, 35], [6, 19, 21, 35], [6, 19, 22, 30], [6, 19, 23, 27], [6, 19, 28, 34], [6, 20, 23, 32], [6, 20, 25, 26], [6, 20, 31, 34], [6, 20, 33, 36], [6, 21, 23, 29], [6, 21, 24, 26], [6, 21, 30, 34], [6, 22, 24, 33], [6, 22, 25, 37], [6, 22, 29, 36], [6, 23, 30, 33], [6, 24, 27, 32], [6, 24, 28, 35], [6, 24, 29, 34], [6, 24, 31, 37], [6, 25, 28, 32], [6, 26, 27, 37], [6, 26, 29, 30], [6, 26, 32, 36], [6, 27, 28, 33], [6, 27, 30, 36], [6, 29, 31, 35], [6, 30, 31, 32], [6, 34, 36, 37], [7, 8, 9, 21], [7, 8, 12, 34], [7, 8, 13, 24], [7, 8, 14, 19], [7, 8, 16, 17], [7, 8, 18, 25], [7, 8, 23, 29], [7, 8, 27, 32], [7, 8, 28, 30], [7, 8, 33, 35], [7, 8, 36, 37], [7, 9, 10, 17], [7, 9, 11, 16], [7, 9, 12, 35], [7, 9, 13, 22], [7, 9, 15, 30], [7, 9, 18, 29], [7, 9, 19, 20], [7, 9, 23, 32], [7, 9, 24, 25], [7, 9, 26, 37], [7, 9, 28, 36], [7, 10, 11, 25], [7, 10, 12, 30], [7, 10, 14, 26], [7, 10, 15, 27], [7, 10, 16, 24], [7, 10, 18, 32], [7, 10, 19, 31], [7, 10, 20, 34], [7, 10, 22, 29], [7, 10, 23, 35], [7, 11, 12, 14], [7, 11, 13, 35], [7, 11, 15, 32], [7, 11, 17, 37], [7, 11, 18, 27], [7, 11, 21, 36], [7, 11, 22, 34], [7, 11, 24, 29], [7, 11, 26, 30], [7, 12, 13, 31], [7, 12, 15, 33], [7, 12, 16, 36], [7, 12, 17, 27], [7, 12, 18, 20], [7, 12, 19, 21], [7, 12, 25, 26], [7, 12, 28, 32], [7, 12, 29, 37], [7, 13, 14, 37], [7, 13, 16, 19], [7, 13, 17, 25], [7, 13, 23, 36], [7, 13, 26, 32], [7, 13, 27, 34], [7, 13, 29, 30], [7, 14, 15, 18], [7, 14, 17, 28], [7, 14, 20, 27], [7, 14, 21, 29], [7, 14, 24, 36], [7, 14, 25, 31], [7, 14, 30, 33], [7, 14, 34, 35], [7, 15, 17, 34], [7, 15, 19, 25], [7, 15, 20, 37], [7, 15, 21, 22], [7, 15, 23, 28], [7, 15, 24, 26], [7, 16, 18, 37], [7, 16, 20, 30], [7, 16, 21, 25], [7, 16, 22, 32], [7, 16, 23, 33], [7, 16, 26, 35], [7, 16, 29, 31], [7, 17, 19, 22], [7, 17, 20, 33], [7, 17, 21, 23], [7, 17, 26, 36], [7, 18, 19, 23], [7, 18, 21, 31], [7, 18, 22, 33], [7, 18, 26, 28], [7, 18, 34, 36], [7, 19, 24, 27], [7, 19, 28, 35], [7, 19, 29, 32], [7, 19, 30, 34], [7, 19, 33, 36], [7, 20, 22, 36], [7, 20, 23, 31], [7, 20, 24, 28], [7, 20, 29, 35], [7, 21, 24, 33], [7, 21, 26, 27], [7, 21, 32, 35], [7, 21, 34, 37], [7, 22, 24, 30], [7, 22, 25, 27], [7, 22, 31, 35], [7, 23, 25, 34], [7, 23, 30, 37], [7, 24, 31, 34], [7, 25, 28, 33], [7, 25, 29, 36], [7, 25, 30, 35], [7, 26, 29, 33], [7, 27, 30, 31], [7, 27, 33, 37], [7, 28, 29, 34], [7, 28, 31, 37], [7, 30, 32, 36], [7, 31, 32, 33], [8, 9, 10, 22], [8, 9, 13, 35], [8, 9, 14, 25], [8, 9, 15, 20], [8, 9, 17, 18], [8, 9, 19, 26], [8, 9, 24, 30], [8, 9, 28, 33], [8, 9, 29, 31], [8, 9, 34, 36], [8, 10, 11, 18], [8, 10, 12, 17], [8, 10, 13, 36], [8, 10, 14, 23], [8, 10, 16, 31], [8, 10, 19, 30], [8, 10, 20, 21], [8, 10, 24, 33], [8, 10, 25, 26], [8, 10, 29, 37], [8, 11, 12, 26], [8, 11, 13, 31], [8, 11, 15, 27], [8, 11, 16, 28], [8, 11, 17, 25], [8, 11, 19, 33], [8, 11, 20, 32], [8, 11, 21, 35], [8, 11, 23, 30], [8, 11, 24, 36], [8, 12, 13, 15], [8, 12, 14, 36], [8, 12, 16, 33], [8, 12, 19, 28], [8, 12, 22, 37], [8, 12, 23, 35], [8, 12, 25, 30], [8, 12, 27, 31], [8, 13, 14, 32], [8, 13, 16, 34], [8, 13, 17, 37], [8, 13, 18, 28], [8, 13, 19, 21], [8, 13, 20, 22], [8, 13, 26, 27], [8, 13, 29, 33], [8, 14, 17, 20], [8, 14, 18, 26], [8, 14, 24, 37], [8, 14, 27, 33], [8, 14, 28, 35], [8, 14, 30, 31], [8, 15, 16, 19], [8, 15, 18, 29], [8, 15, 21, 28], [8, 15, 22, 30], [8, 15, 25, 37], [8, 15, 26, 32], [8, 15, 31, 34], [8, 15, 35, 36], [8, 16, 18, 35], [8, 16, 20, 26], [8, 16, 22, 23], [8, 16, 24, 29], [8, 16, 25, 27], [8, 17, 21, 31], [8, 17, 22, 26], [8, 17, 23, 33], [8, 17, 24, 34], [8, 17, 27, 36], [8, 17, 30, 32], [8, 18, 20, 23], [8, 18, 21, 34], [8, 18, 22, 24], [8, 18, 27, 37], [8, 19, 20, 24], [8, 19, 22, 32], [8, 19, 23, 34], [8, 19, 27, 29], [8, 19, 35, 37], [8, 20, 25, 28], [8, 20, 29, 36], [8, 20, 30, 33], [8, 20, 31, 35], [8, 20, 34, 37], [8, 21, 23, 37], [8, 21, 24, 32], [8, 21, 25, 29], [8, 21, 30, 36], [8, 22, 25, 34], [8, 22, 27, 28], [8, 22, 33, 36], [8, 23, 25, 31], [8, 23, 26, 28], [8, 23, 32, 36], [8, 24, 26, 35], [8, 25, 32, 35], [8, 26, 29, 34], [8, 26, 30, 37], [8, 26, 31, 36], [8, 27, 30, 34], [8, 28, 31, 32], [8, 29, 30, 35], [8, 31, 33, 37], [8, 32, 33, 34], [9, 10, 11, 23], [9, 10, 14, 36], [9, 10, 15, 26], [9, 10, 16, 21], [9, 10, 18, 19], [9, 10, 20, 27], [9, 10, 25, 31], [9, 10, 29, 34], [9, 10, 30, 32], [9, 10, 35, 37], [9, 11, 12, 19], [9, 11, 13, 18], [9, 11, 14, 37], [9, 11, 15, 24], [9, 11, 17, 32], [9, 11, 20, 31], [9, 11, 21, 22], [9, 11, 25, 34], [9, 11, 26, 27], [9, 12, 13, 27], [9, 12, 14, 32], [9, 12, 16, 28], [9, 12, 17, 29], [9, 12, 18, 26], [9, 12, 20, 34], [9, 12, 21, 33], [9, 12, 22, 36], [9, 12, 24, 31], [9, 12, 25, 37], [9, 13, 14, 16], [9, 13, 15, 37], [9, 13, 17, 34], [9, 13, 20, 29], [9, 13, 24, 36], [9, 13, 26, 31], [9, 13, 28, 32], [9, 14, 15, 33], [9, 14, 17, 35], [9, 14, 19, 29], [9, 14, 20, 22], [9, 14, 21, 23], [9, 14, 27, 28], [9, 14, 30, 34], [9, 15, 18, 21], [9, 15, 19, 27], [9, 15, 28, 34], [9, 15, 29, 36], [9, 15, 31, 32], [9, 16, 17, 20], [9, 16, 19, 30], [9, 16, 22, 29], [9, 16, 23, 31], [9, 16, 27, 33], [9, 16, 32, 35], [9, 16, 36, 37], [9, 17, 19, 36], [9, 17, 21, 27], [9, 17, 23, 24], [9, 17, 25, 30], [9, 17, 26, 28], [9, 18, 22, 32], [9, 18, 23, 27], [9, 18, 24, 34], [9, 18, 25, 35], [9, 18, 28, 37], [9, 18, 31, 33], [9, 19, 21, 24], [9, 19, 22, 35], [9, 19, 23, 25], [9, 20, 21, 25], [9, 20, 23, 33], [9, 20, 24, 35], [9, 20, 28, 30], [9, 21, 26, 29], [9, 21, 30, 37], [9, 21, 31, 34], [9, 21, 32, 36], [9, 22, 25, 33], [9, 22, 26, 30], [9, 22, 31, 37], [9, 23, 26, 35], [9, 23, 28, 29], [9, 23, 34, 37], [9, 24, 26, 32], [9, 24, 27, 29], [9, 24, 33, 37], [9, 25, 27, 36], [9, 26, 33, 36], [9, 27, 30, 35], [9, 27, 32, 37], [9, 28, 31, 35], [9, 29, 32, 33], [9, 30, 31, 36], [9, 33, 34, 35], [10, 11, 12, 24], [10, 11, 15, 37], [10, 11, 16, 27], [10, 11, 17, 22], [10, 11, 19, 20], [10, 11, 21, 28], [10, 11, 26, 32], [10, 11, 30, 35], [10, 11, 31, 33], [10, 12, 13, 20], [10, 12, 14, 19], [10, 12, 16, 25], [10, 12, 18, 33], [10, 12, 21, 32], [10, 12, 22, 23], [10, 12, 26, 35], [10, 12, 27, 28], [10, 13, 14, 28], [10, 13, 15, 33], [10, 13, 17, 29], [10, 13, 18, 30], [10, 13, 19, 27], [10, 13, 21, 35], [10, 13, 22, 34], [10, 13, 23, 37], [10, 13, 25, 32], [10, 14, 15, 17], [10, 14, 18, 35], [10, 14, 21, 30], [10, 14, 25, 37], [10, 14, 27, 32], [10, 14, 29, 33], [10, 15, 16, 34], [10, 15, 18, 36], [10, 15, 20, 30], [10, 15, 21, 23], [10, 15, 22, 24], [10, 15, 28, 29], [10, 15, 31, 35], [10, 16, 19, 22], [10, 16, 20, 28], [10, 16, 29, 35], [10, 16, 30, 37], [10, 16, 32, 33], [10, 17, 18, 21], [10, 17, 20, 31], [10, 17, 23, 30], [10, 17, 24, 32], [10, 17, 28, 34], [10, 17, 33, 36], [10, 18, 20, 37], [10, 18, 22, 28], [10, 18, 24, 25], [10, 18, 26, 31], [10, 18, 27, 29], [10, 19, 23, 33], [10, 19, 24, 28], [10, 19, 25, 35], [10, 19, 26, 36], [10, 19, 32, 34], [10, 20, 22, 25], [10, 20, 23, 36], [10, 20, 24, 26], [10, 21, 22, 26], [10, 21, 24, 34], [10, 21, 25, 36], [10, 21, 29, 31], [10, 22, 27, 30], [10, 22, 32, 35], [10, 22, 33, 37], [10, 23, 26, 34], [10, 23, 27, 31], [10, 24, 27, 36], [10, 24, 29, 30], [10, 25, 27, 33], [10, 25, 28, 30], [10, 26, 28, 37], [10, 27, 34, 37], [10, 28, 31, 36], [10, 29, 32, 36], [10, 30, 33, 34], [10, 31, 32, 37], [10, 34, 35, 36], [11, 12, 13, 25], [11, 12, 17, 28], [11, 12, 18, 23], [11, 12, 20, 21], [11, 12, 22, 29], [11, 12, 27, 33], [11, 12, 31, 36], [11, 12, 32, 34], [11, 13, 14, 21], [11, 13, 15, 20], [11, 13, 17, 26], [11, 13, 19, 34], [11, 13, 22, 33], [11, 13, 23, 24], [11, 13, 27, 36], [11, 13, 28, 29], [11, 14, 15, 29], [11, 14, 16, 34], [11, 14, 18, 30], [11, 14, 19, 31], [11, 14, 20, 28], [11, 14, 22, 36], [11, 14, 23, 35], [11, 14, 26, 33], [11, 15, 16, 18], [11, 15, 19, 36], [11, 15, 22, 31], [11, 15, 28, 33], [11, 15, 30, 34], [11, 16, 17, 35], [11, 16, 19, 37], [11, 16, 21, 31], [11, 16, 22, 24], [11, 16, 23, 25], [11, 16, 29, 30], [11, 16, 32, 36], [11, 17, 20, 23], [11, 17, 21, 29], [11, 17, 30, 36], [11, 17, 33, 34], [11, 18, 19, 22], [11, 18, 21, 32], [11, 18, 24, 31], [11, 18, 25, 33], [11, 18, 29, 35], [11, 18, 34, 37], [11, 19, 23, 29], [11, 19, 25, 26], [11, 19, 27, 32], [11, 19, 28, 30], [11, 20, 24, 34], [11, 20, 25, 29], [11, 20, 26, 36], [11, 20, 27, 37], [11, 20, 33, 35], [11, 21, 23, 26], [11, 21, 24, 37], [11, 21, 25, 27], [11, 22, 23, 27], [11, 22, 25, 35], [11, 22, 26, 37], [11, 22, 30, 32], [11, 23, 28, 31], [11, 23, 33, 36], [11, 24, 27, 35], [11, 24, 28, 32], [11, 25, 28, 37], [11, 25, 30, 31], [11, 26, 28, 34], [11, 26, 29, 31], [11, 29, 32, 37], [11, 30, 33, 37], [11, 31, 34, 35], [11, 35, 36, 37], [12, 13, 14, 26], [12, 13, 18, 29], [12, 13, 19, 24], [12, 13, 21, 22], [12, 13, 23, 30], [12, 13, 28, 34], [12, 13, 32, 37], [12, 13, 33, 35], [12, 14, 15, 22], [12, 14, 16, 21], [12, 14, 18, 27], [12, 14, 20, 35], [12, 14, 23, 34], [12, 14, 24, 25], [12, 14, 28, 37], [12, 14, 29, 30], [12, 15, 16, 30], [12, 15, 17, 35], [12, 15, 19, 31], [12, 15, 20, 32], [12, 15, 21, 29], [12, 15, 23, 37], [12, 15, 24, 36], [12, 15, 27, 34], [12, 16, 17, 19], [12, 16, 20, 37], [12, 16, 23, 32], [12, 16, 29, 34], [12, 16, 31, 35], [12, 17, 18, 36], [12, 17, 22, 32], [12, 17, 23, 25], [12, 17, 24, 26], [12, 17, 30, 31], [12, 17, 33, 37], [12, 18, 21, 24], [12, 18, 22, 30], [12, 18, 31, 37], [12, 18, 34, 35], [12, 19, 20, 23], [12, 19, 22, 33], [12, 19, 25, 32], [12, 19, 26, 34], [12, 19, 30, 36], [12, 20, 24, 30], [12, 20, 26, 27], [12, 20, 28, 33], [12, 20, 29, 31], [12, 21, 25, 35], [12, 21, 26, 30], [12, 21, 27, 37], [12, 21, 34, 36], [12, 22, 24, 27], [12, 22, 26, 28], [12, 23, 24, 28], [12, 23, 26, 36], [12, 23, 31, 33], [12, 24, 29, 32], [12, 24, 34, 37], [12, 25, 28, 36], [12, 25, 29, 33], [12, 26, 31, 32], [12, 27, 29, 35], [12, 27, 30, 32], [12, 32, 35, 36], [13, 14, 15, 27], [13, 14, 19, 30], [13, 14, 20, 25], [13, 14, 22, 23], [13, 14, 24, 31], [13, 14, 29, 35], [13, 14, 34, 36], [13, 15, 16, 23], [13, 15, 17, 22], [13, 15, 19, 28], [13, 15, 21, 36], [13, 15, 24, 35], [13, 15, 25, 26], [13, 15, 30, 31], [13, 16, 17, 31], [13, 16, 18, 36], [13, 16, 20, 32], [13, 16, 21, 33], [13, 16, 22, 30], [13, 16, 25, 37], [13, 16, 28, 35], [13, 17, 18, 20], [13, 17, 24, 33], [13, 17, 30, 35], [13, 17, 32, 36], [13, 18, 19, 37], [13, 18, 23, 33], [13, 18, 24, 26], [13, 18, 25, 27], [13, 18, 31, 32], [13, 19, 22, 25], [13, 19, 23, 31], [13, 19, 35, 36], [13, 20, 21, 24], [13, 20, 23, 34], [13, 20, 26, 33], [13, 20, 27, 35], [13, 20, 31, 37], [13, 21, 25, 31], [13, 21, 27, 28], [13, 21, 29, 34], [13, 21, 30, 32], [13, 22, 26, 36], [13, 22, 27, 31], [13, 22, 35, 37], [13, 23, 25, 28], [13, 23, 27, 29], [13, 24, 25, 29], [13, 24, 27, 37], [13, 24, 32, 34], [13, 25, 30, 33], [13, 26, 29, 37], [13, 26, 30, 34], [13, 27, 32, 33], [13, 28, 30, 36], [13, 28, 31, 33], [13, 33, 36, 37], [14, 15, 16, 28], [14, 15, 20, 31], [14, 15, 21, 26], [14, 15, 23, 24], [14, 15, 25, 32], [14, 15, 30, 36], [14, 15, 35, 37], [14, 16, 17, 24], [14, 16, 18, 23], [14, 16, 20, 29], [14, 16, 22, 37], [14, 16, 25, 36], [14, 16, 26, 27], [14, 16, 31, 32], [14, 17, 18, 32], [14, 17, 19, 37], [14, 17, 21, 33], [14, 17, 22, 34], [14, 17, 23, 31], [14, 17, 29, 36], [14, 18, 19, 21], [14, 18, 25, 34], [14, 18, 31, 36], [14, 18, 33, 37], [14, 19, 24, 34], [14, 19, 25, 27], [14, 19, 26, 28], [14, 19, 32, 33], [14, 20, 23, 26], [14, 20, 24, 32], [14, 20, 36, 37], [14, 21, 22, 25], [14, 21, 24, 35], [14, 21, 27, 34], [14, 21, 28, 36], [14, 22, 26, 32], [14, 22, 28, 29], [14, 22, 30, 35], [14, 22, 31, 33], [14, 23, 27, 37], [14, 23, 28, 32], [14, 24, 26, 29], [14, 24, 28, 30], [14, 25, 26, 30], [14, 25, 33, 35], [14, 26, 31, 34], [14, 27, 31, 35], [14, 28, 33, 34], [14, 29, 31, 37], [14, 29, 32, 34], [15, 16, 17, 29], [15, 16, 21, 32], [15, 16, 22, 27], [15, 16, 24, 25], [15, 16, 26, 33], [15, 16, 31, 37], [15, 17, 18, 25], [15, 17, 19, 24], [15, 17, 21, 30], [15, 17, 26, 37], [15, 17, 27, 28], [15, 17, 32, 33], [15, 18, 19, 33], [15, 18, 22, 34], [15, 18, 23, 35], [15, 18, 24, 32], [15, 18, 30, 37], [15, 19, 20, 22], [15, 19, 26, 35], [15, 19, 32, 37], [15, 20, 25, 35], [15, 20, 26, 28], [15, 20, 27, 29], [15, 20, 33, 34], [15, 21, 24, 27], [15, 21, 25, 33], [15, 22, 23, 26], [15, 22, 25, 36], [15, 22, 28, 35], [15, 22, 29, 37], [15, 23, 27, 33], [15, 23, 29, 30], [15, 23, 31, 36], [15, 23, 32, 34], [15, 24, 29, 33], [15, 25, 27, 30], [15, 25, 29, 31], [15, 26, 27, 31], [15, 26, 34, 36], [15, 27, 32, 35], [15, 28, 32, 36], [15, 29, 34, 35], [15, 30, 33, 35], [16, 17, 18, 30], [16, 17, 22, 33], [16, 17, 23, 28], [16, 17, 25, 26], [16, 17, 27, 34], [16, 18, 19, 26], [16, 18, 20, 25], [16, 18, 22, 31], [16, 18, 28, 29], [16, 18, 33, 34], [16, 19, 20, 34], [16, 19, 23, 35], [16, 19, 24, 36], [16, 19, 25, 33], [16, 20, 21, 23], [16, 20, 27, 36], [16, 21, 26, 36], [16, 21, 27, 29], [16, 21, 28, 30], [16, 21, 34, 35], [16, 22, 25, 28], [16, 22, 26, 34], [16, 23, 24, 27], [16, 23, 26, 37], [16, 23, 29, 36], [16, 24, 28, 34], [16, 24, 30, 31], [16, 24, 32, 37], [16, 24, 33, 35], [16, 25, 30, 34], [16, 26, 28, 31], [16, 26, 30, 32], [16, 27, 28, 32], [16, 27, 35, 37], [16, 28, 33, 36], [16, 29, 33, 37], [16, 30, 35, 36], [16, 31, 34, 36], [17, 18, 19, 31], [17, 18, 23, 34], [17, 18, 24, 29], [17, 18, 26, 27], [17, 18, 28, 35], [17, 19, 20, 27], [17, 19, 21, 26], [17, 19, 23, 32], [17, 19, 29, 30], [17, 19, 34, 35], [17, 20, 21, 35], [17, 20, 24, 36], [17, 20, 25, 37], [17, 20, 26, 34], [17, 21, 22, 24], [17, 21, 28, 37], [17, 22, 27, 37], [17, 22, 28, 30], [17, 22, 29, 31], [17, 22, 35, 36], [17, 23, 26, 29], [17, 23, 27, 35], [17, 24, 25, 28], [17, 24, 30, 37], [17, 25, 29, 35], [17, 25, 31, 32], [17, 25, 34, 36], [17, 26, 31, 35], [17, 27, 29, 32], [17, 27, 31, 33], [17, 28, 29, 33], [17, 29, 34, 37], [17, 31, 36, 37], [17, 32, 35, 37], [18, 19, 20, 32], [18, 19, 24, 35], [18, 19, 25, 30], [18, 19, 27, 28], [18, 19, 29, 36], [18, 20, 21, 28], [18, 20, 22, 27], [18, 20, 24, 33], [18, 20, 30, 31], [18, 20, 35, 36], [18, 21, 22, 36], [18, 21, 25, 37], [18, 21, 27, 35], [18, 22, 23, 25], [18, 23, 29, 31], [18, 23, 30, 32], [18, 23, 36, 37], [18, 24, 27, 30], [18, 24, 28, 36], [18, 25, 26, 29], [18, 26, 30, 36], [18, 26, 32, 33], [18, 26, 35, 37], [18, 27, 32, 36], [18, 28, 30, 33], [18, 28, 32, 34], [18, 29, 30, 34], [19, 20, 21, 33], [19, 20, 25, 36], [19, 20, 26, 31], [19, 20, 28, 29], [19, 20, 30, 37], [19, 21, 22, 29], [19, 21, 23, 28], [19, 21, 25, 34], [19, 21, 31, 32], [19, 21, 36, 37], [19, 22, 23, 37], [19, 22, 28, 36], [19, 23, 24, 26], [19, 24, 30, 32], [19, 24, 31, 33], [19, 25, 28, 31], [19, 25, 29, 37], [19, 26, 27, 30], [19, 27, 31, 37], [19, 27, 33, 34], [19, 28, 33, 37], [19, 29, 31, 34], [19, 29, 33, 35], [19, 30, 31, 35], [20, 21, 22, 34], [20, 21, 26, 37], [20, 21, 27, 32], [20, 21, 29, 30], [20, 22, 23, 30], [20, 22, 24, 29], [20, 22, 26, 35], [20, 22, 32, 33], [20, 23, 29, 37], [20, 24, 25, 27], [20, 25, 31, 33], [20, 25, 32, 34], [20, 26, 29, 32], [20, 27, 28, 31], [20, 28, 34, 35], [20, 30, 32, 35], [20, 30, 34, 36], [20, 31, 32, 36], [21, 22, 23, 35], [21, 22, 28, 33], [21, 22, 30, 31], [21, 23, 24, 31], [21, 23, 25, 30], [21, 23, 27, 36], [21, 23, 33, 34], [21, 25, 26, 28], [21, 26, 32, 34], [21, 26, 33, 35], [21, 27, 30, 33], [21, 28, 29, 32], [21, 29, 35, 36], [21, 31, 33, 36], [21, 31, 35, 37], [21, 32, 33, 37], [22, 23, 24, 36], [22, 23, 29, 34], [22, 23, 31, 32], [22, 24, 25, 32], [22, 24, 26, 31], [22, 24, 28, 37], [22, 24, 34, 35], [22, 26, 27, 29], [22, 27, 33, 35], [22, 27, 34, 36], [22, 28, 31, 34], [22, 29, 30, 33], [22, 30, 36, 37], [22, 32, 34, 37], [23, 24, 25, 37], [23, 24, 30, 35], [23, 24, 32, 33], [23, 25, 26, 33], [23, 25, 27, 32], [23, 25, 35, 36], [23, 27, 28, 30], [23, 28, 34, 36], [23, 28, 35, 37], [23, 29, 32, 35], [23, 30, 31, 34], [24, 25, 31, 36], [24, 25, 33, 34], [24, 26, 27, 34], [24, 26, 28, 33], [24, 26, 36, 37], [24, 28, 29, 31], [24, 29, 35, 37], [24, 30, 33, 36], [24, 31, 32, 35], [25, 26, 32, 37], [25, 26, 34, 35], [25, 27, 28, 35], [25, 27, 29, 34], [25, 29, 30, 32], [25, 31, 34, 37], [25, 32, 33, 36], [26, 27, 35, 36], [26, 28, 29, 36], [26, 28, 30, 35], [26, 30, 31, 33], [26, 33, 34, 37], [27, 28, 36, 37], [27, 29, 30, 37], [27, 29, 31, 36], [27, 31, 32, 34], [28, 30, 32, 37], [28, 32, 33, 35], [29, 33, 34, 36], [30, 34, 35, 37]]
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/designs/steiner_quadruple_systems.py
0.86891
0.863334
steiner_quadruple_systems.py
pypi
import ipywidgets as widgets from sage.misc.latex import latex from sage.repl.rich_output.pretty_print import pretty_print from IPython.display import clear_output def cluster_interact(self, fig_size=1, circular=True, kind='seed'): r""" Start an interactive window for cluster seed mutations. Only in *Jupyter notebook mode*. Not to be called directly. Use the interact methods of ClusterSeed and ClusterQuiver instead. INPUT: - ``fig_size`` -- (default: 1) factor by which the size of the plot is multiplied. - ``circular`` -- (default: ``True``) if ``True``, the circular plot is chosen, otherwise >>spring<< is used. - ``kind`` -- either ``"seed"`` (default) or ``"quiver"`` TESTS:: sage: S = ClusterSeed(['A',4]) sage: S.interact() # indirect doctest ...VBox(children=... """ if kind not in ['seed', 'quiver']: raise ValueError('kind must be "seed" or "quiver"') show_seq = widgets.Checkbox(value=True, description="Display mutation sequence") show_vars = widgets.Checkbox(value=True, description="Display cluster variables") show_matrix = widgets.Checkbox(value=True, description="Display B-matrix") show_lastmutation = widgets.Checkbox(value=True, description="Show last mutation vertex") mut_buttons = widgets.ToggleButtons(options=list(range(self._n)), style={'button_width':'initial'}, description='Mutate at: ') which_plot = widgets.Dropdown(options=['circular', 'spring'], value='circular' if circular else "spring", description='Display style:') out = widgets.Output() seq = [] def print_data(): if show_seq.value: pretty_print("Mutation sequence: ", seq) if show_vars.value and kind == 'seed': pretty_print("Cluster variables:") table = "\\begin{align*}\n" for i in range(self._n): table += "\tv_{%s} &= " % i + latex(self.cluster_variable(i)) + "\\\\ \\\\\n" table += "\\end{align*}" pretty_print(table) if show_matrix.value: pretty_print("B-Matrix: ", self._M) def refresh(w): k = mut_buttons.value circular = bool(which_plot.value == "circular") with out: clear_output(wait=True) if show_lastmutation.value: self.show(fig_size=fig_size, circular=circular, mark=k) else: self.show(fig_size=fig_size, circular=circular) print_data() def do_mutation(*args, **kwds): k = mut_buttons.value circular = bool(which_plot.value == "circular") self.mutate(k) if seq and seq[-1] == k: seq.pop() else: seq.append(k) with out: clear_output(wait=True) if show_lastmutation.value: self.show(fig_size=fig_size, circular=circular, mark=k) else: self.show(fig_size=fig_size, circular=circular) print_data() mut_buttons.on_msg(do_mutation) show_seq.observe(refresh, 'value') if kind == 'seed': show_vars.observe(refresh, 'value') show_matrix.observe(refresh, 'value') show_lastmutation.observe(refresh, 'value') which_plot.observe(refresh, 'value') mut_buttons.on_widget_constructed(refresh) if kind == 'seed': top = widgets.HBox([show_seq, show_vars]) else: top = widgets.HBox([show_seq]) return widgets.VBox([which_plot, top, widgets.HBox([show_matrix, show_lastmutation]), mut_buttons, out])
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/combinat/cluster_algebra_quiver/interact.py
0.617974
0.542015
interact.py
pypi
r""" Functions for reading/building graphs/digraphs This module gathers functions needed to build a graph from any other data. .. NOTE:: This is an **internal** module of Sage. All features implemented here are made available to end-users through the constructors of :class:`Graph` and :class:`DiGraph`. Note that because they are called by the constructors of :class:`Graph` and :class:`DiGraph`, most of these functions modify a graph inplace. {INDEX_OF_FUNCTIONS} Functions --------- """ from sage.cpython.string import bytes_to_str from sage.misc.rest_index_of_methods import gen_rest_table_index import sys def from_graph6(G, g6_string): r""" Fill ``G`` with the data of a graph6 string. INPUT: - ``G`` -- a graph - ``g6_string`` -- a graph6 string EXAMPLES:: sage: from sage.graphs.graph_input import from_graph6 sage: g = Graph() sage: from_graph6(g, 'IheA@GUAo') sage: g.is_isomorphic(graphs.PetersenGraph()) True """ from .generic_graph_pyx import length_and_string_from_graph6, binary_string_from_graph6 if isinstance(g6_string, bytes): g6_string = bytes_to_str(g6_string) elif not isinstance(g6_string, str): raise ValueError('if input format is graph6, then g6_string must be a string') n = g6_string.find('\n') if n == -1: n = len(g6_string) ss = g6_string[:n] n, s = length_and_string_from_graph6(ss) m = binary_string_from_graph6(s, n) expected = n * (n - 1) // 2 + (6 - n * (n - 1) // 2) % 6 if len(m) > expected: raise RuntimeError("the string (%s) seems corrupt: for n = %d, the string is too long" % (ss, n)) elif len(m) < expected: raise RuntimeError("the string (%s) seems corrupt: for n = %d, the string is too short" % (ss, n)) G.add_vertices(range(n)) k = 0 for i in range(n): for j in range(i): if m[k] == '1': G._backend.add_edge(i, j, None, False) k += 1 def from_sparse6(G, g6_string): r""" Fill ``G`` with the data of a sparse6 string. INPUT: - ``G`` -- a graph - ``g6_string`` -- a sparse6 string EXAMPLES:: sage: from sage.graphs.graph_input import from_sparse6 sage: g = Graph() sage: from_sparse6(g, ':I`ES@obGkqegW~') sage: g.is_isomorphic(graphs.PetersenGraph()) True """ from .generic_graph_pyx import length_and_string_from_graph6, int_to_binary_string if isinstance(g6_string, bytes): g6_string = bytes_to_str(g6_string) elif not isinstance(g6_string, str): raise ValueError('if input format is graph6, then g6_string must be a string') n = g6_string.find('\n') if n == -1: n = len(g6_string) s = g6_string[:n] n, s = length_and_string_from_graph6(s[1:]) if not n: edges = [] else: from sage.rings.integer_ring import ZZ k = int((ZZ(n) - 1).nbits()) ords = [ord(i) for i in s] if any(o > 126 or o < 63 for o in ords): raise RuntimeError("the string seems corrupt: valid characters are \n" + ''.join([chr(i) for i in range(63, 127)])) bits = ''.join([int_to_binary_string(o-63).zfill(6) for o in ords]) if not k: b = [int(x) for x in bits] x = [0] * len(b) else: b = [] x = [] for i in range(0, len(bits)-k, k+1): b.append(int(bits[i:i+1], 2)) x.append(int(bits[i+1:i+k+1], 2)) v = 0 edges = [] for i in range(len(b)): v += b[i] # +1 if b[i] == 1 else 0 if x[i] > v: v = x[i] else: if v < n: edges.append((x[i], v)) G.add_vertices(range(n)) G.add_edges(edges) def from_dig6(G, dig6_string): r""" Fill ``G`` with the data of a dig6 string. INPUT: - ``G`` -- a graph - ``dig6_string`` -- a dig6 string EXAMPLES:: sage: from sage.graphs.graph_input import from_dig6 sage: g = DiGraph() sage: from_dig6(g, digraphs.Circuit(10).dig6_string()) sage: g.is_isomorphic(digraphs.Circuit(10)) True """ from .generic_graph_pyx import length_and_string_from_graph6, binary_string_from_dig6 if isinstance(dig6_string, bytes): dig6_string = bytes_to_str(dig6_string) elif not isinstance(dig6_string, str): raise ValueError('if input format is dig6, then dig6_string must be a string') n = dig6_string.find('\n') if n == -1: n = len(dig6_string) ss = dig6_string[:n] n, s = length_and_string_from_graph6(ss) m = binary_string_from_dig6(s, n) expected = n**2 if len(m) > expected: raise RuntimeError("the string (%s) seems corrupt: for n = %d, the string is too long" % (ss, n)) elif len(m) < expected: raise RuntimeError("the string (%s) seems corrupt: for n = %d, the string is too short" % (ss, n)) G.add_vertices(range(n)) k = 0 for i in range(n): for j in range(n): if m[k] == '1': G._backend.add_edge(i, j, None, True) k += 1 def from_seidel_adjacency_matrix(G, M): r""" Fill ``G`` with the data of a Seidel adjacency matrix. INPUT: - ``G`` -- a graph - ``M`` -- a Seidel adjacency matrix EXAMPLES:: sage: from sage.graphs.graph_input import from_seidel_adjacency_matrix sage: g = Graph() sage: from_seidel_adjacency_matrix(g, graphs.PetersenGraph().seidel_adjacency_matrix()) sage: g.is_isomorphic(graphs.PetersenGraph()) True """ from sage.structure.element import is_Matrix from sage.rings.integer_ring import ZZ assert is_Matrix(M) if M.base_ring() != ZZ: try: M = M.change_ring(ZZ) except TypeError: raise ValueError("the adjacency matrix of a Seidel graph must" + " have only 0,1,-1 integer entries") if M.is_sparse(): entries = set(M[i, j] for i, j in M.nonzero_positions()) else: entries = set(M.list()) if any(e < -1 or e > 1 for e in entries): raise ValueError("the adjacency matrix of a Seidel graph must" + " have only 0,1,-1 integer entries") if any(i == j for i, j in M.nonzero_positions()): raise ValueError("the adjacency matrix of a Seidel graph must" + " have 0s on the main diagonal") if not M.is_symmetric(): raise ValueError("the adjacency matrix of a Seidel graph must be symmetric") G.add_vertices(range(M.nrows())) G.add_edges((i, j) for i, j in M.nonzero_positions() if i <= j and M[i, j] < 0) def from_adjacency_matrix(G, M, loops=False, multiedges=False, weighted=False): r""" Fill ``G`` with the data of an adjacency matrix. INPUT: - ``G`` -- a :class:`Graph` or :class:`DiGraph` - ``M`` -- an adjacency matrix - ``loops``, ``multiedges``, ``weighted`` -- booleans (default: ``False``); whether to consider the graph as having loops, multiple edges, or weights EXAMPLES:: sage: from sage.graphs.graph_input import from_adjacency_matrix sage: g = Graph() sage: from_adjacency_matrix(g, graphs.PetersenGraph().adjacency_matrix()) sage: g.is_isomorphic(graphs.PetersenGraph()) True """ from sage.structure.element import is_Matrix from sage.rings.integer_ring import ZZ assert is_Matrix(M) # note: the adjacency matrix might be weighted and hence not # necessarily consists of integers if not weighted and M.base_ring() != ZZ: try: M = M.change_ring(ZZ) except TypeError: if weighted is False: raise ValueError("the adjacency matrix of a non-weighted graph" + " must have only nonnegative integer entries") weighted = True if M.is_sparse(): entries = set(M[i, j] for i, j in M.nonzero_positions()) else: entries = set(M.list()) if not weighted and any(e < 0 for e in entries): if weighted is False: raise ValueError("the adjacency matrix of a non-weighted graph" + " must have only nonnegative integer entries") weighted = True if multiedges is None: multiedges = False if weighted is None: weighted = False if multiedges is None: multiedges = ((not weighted) and any(e != 0 and e != 1 for e in entries)) if not loops and any(M[i, i] for i in range(M.nrows())): if loops is False: raise ValueError("the adjacency matrix of a non-weighted graph" + " must have zeroes on the diagonal") loops = True if loops is None: loops = False G.allow_loops(loops, check=False) G.allow_multiple_edges(multiedges, check=False) G.add_vertices(range(M.nrows())) if G.is_directed(): pairs = M.nonzero_positions() else: pairs = ((i, j) for i, j in M.nonzero_positions() if i <= j) if weighted: G.add_edges((i, j, M[i][j]) for i, j in pairs) elif multiedges: G.add_edges((i, j) for i, j in pairs for _ in range(int(M[i][j]))) else: G.add_edges((i, j) for i, j in pairs) G._weighted = weighted def from_incidence_matrix(G, M, loops=False, multiedges=False, weighted=False): r""" Fill ``G`` with the data of an incidence matrix. INPUT: - ``G`` -- a graph - ``M`` -- an incidence matrix - ``loops``, ``multiedges``, ``weighted`` -- booleans (default: ``False``); whether to consider the graph as having loops, multiple edges, or weights EXAMPLES:: sage: from sage.graphs.graph_input import from_incidence_matrix sage: g = Graph() sage: from_incidence_matrix(g, graphs.PetersenGraph().incidence_matrix()) sage: g.is_isomorphic(graphs.PetersenGraph()) True """ from sage.structure.element import is_Matrix assert is_Matrix(M) oriented = any(M[pos] < 0 for pos in M.nonzero_positions(copy=False)) positions = [] for i in range(M.ncols()): NZ = M.nonzero_positions_in_column(i) if len(NZ) == 1: if oriented: raise ValueError("column {} of the (oriented) incidence " "matrix contains only one nonzero value".format(i)) elif M[NZ[0], i] != 2: raise ValueError("each column of a non-oriented incidence " "matrix must sum to 2, but column {} does not".format(i)) if loops is None: loops = True positions.append((NZ[0], NZ[0])) elif (len(NZ) != 2 or (oriented and not ((M[NZ[0], i] == +1 and M[NZ[1], i] == -1) or (M[NZ[0], i] == -1 and M[NZ[1], i] == +1))) or (not oriented and (M[NZ[0], i] != 1 or M[NZ[1], i] != 1))): msg = "there must be one or two nonzero entries per column in an incidence matrix, " msg += "got entries {} in column {}".format([M[j, i] for j in NZ], i) raise ValueError(msg) else: positions.append(tuple(NZ)) if weighted is None: G._weighted = False if multiedges is None: total = len(positions) multiedges = len(set(positions)) < total G.allow_loops(False if loops is None else loops, check=False) G.allow_multiple_edges(multiedges, check=False) G.add_vertices(range(M.nrows())) G.add_edges(positions) def from_oriented_incidence_matrix(G, M, loops=False, multiedges=False, weighted=False): r""" Fill ``G`` with the data of an *oriented* incidence matrix. An oriented incidence matrix is the incidence matrix of a directed graph, in which each non-loop edge corresponds to a `+1` and a `-1`, indicating its source and destination. INPUT: - ``G`` -- a :class:`DiGraph` - ``M`` -- an incidence matrix - ``loops``, ``multiedges``, ``weighted`` -- booleans (default: ``False``); whether to consider the graph as having loops, multiple edges, or weights .. NOTE:: ``weighted`` is currently ignored. EXAMPLES:: sage: from sage.graphs.graph_input import from_oriented_incidence_matrix sage: g = DiGraph() sage: from_oriented_incidence_matrix(g, digraphs.Circuit(10).incidence_matrix()) sage: g.is_isomorphic(digraphs.Circuit(10)) True TESTS: Fix bug reported in :trac:`22985`:: sage: DiGraph(matrix ([[1,0,0,1],[0,0,1,1],[0,0,1,1]]).transpose()) Traceback (most recent call last): ... ValueError: each column represents an edge: -1 goes to 1 Handle incidence matrix containing a column with only zeros (:trac:`29275`):: sage: m = Matrix([[0,1],[0,-1],[0,0]]) sage: m [ 0 1] [ 0 -1] [ 0 0] sage: G = DiGraph(m,format='incidence_matrix') sage: list(G.edges(sort=True, labels=False)) [(1, 0)] Handle incidence matrix [[1],[-1]] (:trac:`29275`):: sage: m = Matrix([[1],[-1]]) sage: m [ 1] [-1] sage: G = DiGraph(m,format='incidence_matrix') sage: list(G.edges(sort=True, labels=False)) [(1, 0)] """ from sage.structure.element import is_Matrix assert is_Matrix(M) positions = [] for c in M.columns(): NZ = c.nonzero_positions() if not NZ: continue if len(NZ) != 2: raise ValueError("there must be two nonzero entries (-1 & 1) per column") L = sorted([c[i] for i in NZ]) if L != [-1, 1]: raise ValueError("each column represents an edge: -1 goes to 1") if c[NZ[0]] == -1: positions.append(tuple(NZ)) else: positions.append((NZ[1], NZ[0])) if multiedges is None: total = len(positions) multiedges = len(set(positions)) < total G.allow_loops(bool(loops), check=False) G.allow_multiple_edges(multiedges, check=False) G.add_vertices(range(M.nrows())) G.add_edges(positions) def from_dict_of_dicts(G, M, loops=False, multiedges=False, weighted=False, convert_empty_dict_labels_to_None=False): r""" Fill ``G`` with the data of a dictionary of dictionaries. INPUT: - ``G`` -- a graph - ``M`` -- a dictionary of dictionaries - ``loops``, ``multiedges``, ``weighted`` -- booleans (default: ``False``); whether to consider the graph as having loops, multiple edges, or weights - ``convert_empty_dict_labels_to_None`` -- booleans (default: ``False``); whether to adjust for empty dicts instead of ``None`` in NetworkX default edge labels EXAMPLES:: sage: from sage.graphs.graph_input import from_dict_of_dicts sage: g = Graph() sage: from_dict_of_dicts(g, graphs.PetersenGraph().to_dictionary(edge_labels=True)) sage: g.is_isomorphic(graphs.PetersenGraph()) True TESTS: :trac:`32831` is fixed:: sage: DiGraph({0: {}, 1: {}, 2: {}, 3: {}, 4: {}}) Digraph on 5 vertices """ if any(not isinstance(M[u], dict) for u in M): raise ValueError("input dict must be a consistent format") if not loops: if any(u in neighb for u, neighb in M.items()): if loops is False: u = next(u for u, neighb in M.items() if u in neighb) raise ValueError("the graph was built with loops=False but input M has a loop at {}".format(u)) loops = True if loops is None: loops = False if weighted is None: G._weighted = False input_multiedges = multiedges if multiedges is not False: if not all(isinstance(M[u][v], list) for u in M for v in M[u]): if multiedges: raise ValueError("dict of dicts for multigraph must be in the format {v: {u: list}}") multiedges = False if multiedges is None and M: multiedges = True G.allow_loops(loops, check=False) G.allow_multiple_edges(multiedges, check=False) verts = set().union(M.keys(), *M.values()) G.add_vertices(verts) if convert_empty_dict_labels_to_None: def relabel(x): return x if x != {} else None else: def relabel(x): return x is_directed = G.is_directed() if not is_directed and multiedges: v_to_id = {v: i for i, v in enumerate(verts)} for u in M: for v in M[u]: if v_to_id[u] <= v_to_id[v] or v not in M or u not in M[v] or u == v: for label in M[u][v]: G._backend.add_edge(u, v, relabel(label), False) elif multiedges: for u in M: for v in M[u]: for label in M[u][v]: G._backend.add_edge(u, v, relabel(label), is_directed) else: for u in M: for v in M[u]: G._backend.add_edge(u, v, relabel(M[u][v]), is_directed) if not G.size() and input_multiedges is not True: G.allow_multiple_edges(False, check=False) def from_dict_of_lists(G, D, loops=False, multiedges=False, weighted=False): r""" Fill ``G`` with the data of a dictionary of lists. INPUT: - ``G`` -- a :class:`Graph` or :class:`DiGraph` - ``D`` -- a dictionary of lists - ``loops``, ``multiedges``, ``weighted`` -- booleans (default: ``False``); whether to consider the graph as having loops, multiple edges, or weights EXAMPLES:: sage: from sage.graphs.graph_input import from_dict_of_lists sage: g = Graph() sage: from_dict_of_lists(g, graphs.PetersenGraph().to_dictionary()) sage: g.is_isomorphic(graphs.PetersenGraph()) True """ verts = set().union(D.keys(), *D.values()) if not loops: if any(u in neighb for u, neighb in D.items()): if loops is False: u = next(u for u, neighb in D.items() if u in neighb) raise ValueError("the graph was built with loops=False but input D has a loop at {}".format(u)) loops = True if loops is None: loops = False if weighted is None: G._weighted = False if not multiedges: for u in D: if len(set(D[u])) != len(D[u]): if multiedges is False: v = next((v for v in D[u] if D[u].count(v) > 1)) raise ValueError("non-multigraph got several edges (%s, %s)" % (u, v)) multiedges = True break if multiedges is None: multiedges = False G.allow_loops(loops, check=False) G.allow_multiple_edges(multiedges, check=False) G.add_vertices(verts) is_directed = G.is_directed() if not is_directed and multiedges: v_to_id = {v: i for i, v in enumerate(verts)} for u in D: for v in D[u]: if (v_to_id[u] <= v_to_id[v] or v not in D or u not in D[v] or u == v): G._backend.add_edge(u, v, None, False) else: for u in D: for v in D[u]: G._backend.add_edge(u, v, None, is_directed) def from_networkx_graph(G, gnx, weighted=None, loops=None, multiedges=None, convert_empty_dict_labels_to_None=None): r""" Fill `G` with the data of a NetworkX (di)graph. INPUT: - ``G`` -- a :class:`Graph` or :class:`DiGraph` - ``gnx`` -- a NetworkX ``Graph``, ``MultiGraph``, ``DiGraph`` or ``MultiDiGraph`` - ``weighted`` -- boolean (default: ``None``); whether graph thinks of itself as weighted or not. See :meth:`~sage.graphs.generic_graph.GenericGraph.weighted`. - ``loops`` -- boolean (default: ``None``); whether to allow loops - ``multiedges`` -- boolean (default: ``None``); whether to allow multiple edges - ``convert_empty_dict_labels_to_None`` -- boolean (default: ``None``); whether to replace the default edge labels used by NetworkX (empty dictionaries) by ``None``, the default Sage edge label. When set to ``False``, empty dictionaries are not converted to ``None``. EXAMPLES: Feeding a :class:`Graph` with a NetworkX ``Graph``:: sage: from sage.graphs.graph_input import from_networkx_graph sage: import networkx sage: G = Graph() sage: _ = gnx = networkx.Graph() sage: _ = gnx.add_edge(0, 1) sage: _ = gnx.add_edge(1, 2) sage: from_networkx_graph(G, gnx) sage: G.edges(sort=True, labels=False) [(0, 1), (1, 2)] Feeding a :class:`Graph` with a NetworkX ``MultiGraph``:: sage: G = Graph() sage: gnx = networkx.MultiGraph() sage: _ = gnx.add_edge(0, 1) sage: _ = gnx.add_edge(0, 1) sage: from_networkx_graph(G, gnx) sage: G.edges(sort=True, labels=False) [(0, 1), (0, 1)] sage: G = Graph() sage: from_networkx_graph(G, gnx, multiedges=False) sage: G.edges(sort=True, labels=False) [(0, 1)] When feeding a :class:`Graph` `G` with a NetworkX ``DiGraph`` `D`, `G` has one edge `(u, v)` whenever `D` has arc `(u, v)` or `(v, u)` or both:: sage: G = Graph() sage: D = networkx.DiGraph() sage: _ = D.add_edge(0, 1) sage: from_networkx_graph(G, D) sage: G.edges(sort=True, labels=False) [(0, 1)] sage: G = Graph() sage: _ = D.add_edge(1, 0) sage: from_networkx_graph(G, D) sage: G.edges(sort=True, labels=False) [(0, 1)] When feeding a :class:`Graph` `G` with a NetworkX ``MultiDiGraph`` `D`, the number of edges between `u` and `v` in `G` is the maximum between the number of arcs `(u, v)` and the number of arcs `(v, u)` in D`:: sage: G = Graph() sage: D = networkx.MultiDiGraph() sage: _ = D.add_edge(0, 1) sage: _ = D.add_edge(1, 0) sage: _ = D.add_edge(1, 0) sage: D.edges() OutMultiEdgeDataView([(0, 1), (1, 0), (1, 0)]) sage: from_networkx_graph(G, D) sage: G.edges(sort=True, labels=False) [(0, 1), (0, 1)] Feeding a :class:`DiGraph` with a NetworkX ``DiGraph``:: sage: from sage.graphs.graph_input import from_networkx_graph sage: import networkx sage: G = DiGraph() sage: _ = gnx = networkx.DiGraph() sage: _ = gnx.add_edge(0, 1) sage: _ = gnx.add_edge(1, 2) sage: from_networkx_graph(G, gnx) sage: G.edges(sort=True, labels=False) [(0, 1), (1, 2)] Feeding a :class:`DiGraph` with a NetworkX ``MultiDiGraph``:: sage: G = DiGraph() sage: gnx = networkx.MultiDiGraph() sage: _ = gnx.add_edge(0, 1) sage: _ = gnx.add_edge(0, 1) sage: from_networkx_graph(G, gnx) sage: G.edges(sort=True, labels=False) [(0, 1), (0, 1)] sage: G = DiGraph() sage: from_networkx_graph(G, gnx, multiedges=False) sage: G.edges(sort=True, labels=False) [(0, 1)] When feeding a :class:`DiGraph` `G` with a NetworkX ``Graph`` `H`, `G` has both arcs `(u, v)` and `(v, u)` if `G` has edge `(u, v)`:: sage: G = DiGraph() sage: H = networkx.Graph() sage: _ = H.add_edge(0, 1) sage: from_networkx_graph(G, H) sage: G.edges(labels=False, sort=True) [(0, 1), (1, 0)] When feeding a :class:`DiGraph` `G` with a NetworkX ``MultiGraph`` `H`, `G` has `k` arcs `(u, v)` and `k` arcs `(v, u)` if `H` has `k` edges `(u, v)`, unless parameter ``multiedges`` is set to ``False``:: sage: G = DiGraph() sage: H = networkx.MultiGraph() sage: _ = H.add_edge(0, 1) sage: _ = H.add_edge(0, 1) sage: _ = H.add_edge(0, 1) sage: H.edges() MultiEdgeDataView([(0, 1), (0, 1), (0, 1)]) sage: from_networkx_graph(G, H) sage: G.edges(labels=False, sort=True) [(0, 1), (0, 1), (0, 1), (1, 0), (1, 0), (1, 0)] sage: G = DiGraph() sage: from_networkx_graph(G, H, multiedges=False) sage: G.edges(labels=False, sort=True) [(0, 1), (1, 0)] TESTS: The first parameter must be a :class:`Graph` or :class:`DiGraph`:: sage: from sage.graphs.graph_input import from_networkx_graph sage: from_networkx_graph("foo", "bar") Traceback (most recent call last): ... ValueError: the first parameter must a Sage Graph or DiGraph The second parameter must be a NetworkX ``Graph``, ``MultiGraph``, ``DiGraph`` or ``MultiDiGraph``:: sage: from sage.graphs.graph_input import from_networkx_graph sage: from_networkx_graph(Graph(), "bar") Traceback (most recent call last): ... ValueError: the second parameter must be a NetworkX (Multi)(Di)Graph """ from sage.graphs.graph import Graph from sage.graphs.digraph import DiGraph if not isinstance(G, (Graph, DiGraph)): raise ValueError("the first parameter must a Sage Graph or DiGraph") import networkx if not isinstance(gnx, (networkx.Graph, networkx.DiGraph)): raise ValueError("the second parameter must be a NetworkX (Multi)(Di)Graph") if G.is_directed() != gnx.is_directed(): if gnx.is_directed(): gnx = gnx.to_undirected() else: gnx = gnx.to_directed() if weighted is None: if multiedges is None: multiedges = gnx.is_multigraph() if loops is None: loops = any(u == v for u, v in gnx.edges()) G.allow_loops(loops, check=False) G.allow_multiple_edges(multiedges, check=False) G.add_vertices(gnx.nodes()) G.set_vertices(gnx.nodes(data=True)) if convert_empty_dict_labels_to_None is not False: def r(label): return None if label == {} else label G.add_edges((u, v, r(ll)) for u, v, ll in gnx.edges(data=True)) else: G.add_edges(gnx.edges(data=True)) __doc__ = __doc__.format(INDEX_OF_FUNCTIONS=gen_rest_table_index(sys.modules[__name__]))
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/graphs/graph_input.py
0.695545
0.702352
graph_input.py
pypi
r""" Lovász theta-function of graphs AUTHORS: - Dima Pasechnik (2015-06-30): Initial version REFERENCE: [Lov1979]_ Functions --------- """ def lovasz_theta(graph): r""" Return the value of Lovász theta-function of graph. For a graph `G` this function is denoted by `\theta(G)`, and it can be computed in polynomial time. Mathematically, its most important property is the following: .. MATH:: \alpha(G)\leq\theta(G)\leq\chi(\overline{G}) with `\alpha(G)` and `\chi(\overline{G})` being, respectively, the maximum size of an :meth:`independent set <sage.graphs.graph.Graph.independent_set>` set of `G` and the :meth:`chromatic number <sage.graphs.graph.Graph.chromatic_number>` of the :meth:`complement <sage.graphs.generic_graph.GenericGraph.complement>` `\overline{G}` of `G`. For more information, see the :wikipedia:`Lovász_number`. .. NOTE:: - Implemented for undirected graphs only. Use ``to_undirected`` to convert a digraph to an undirected graph. - This function requires the optional package ``csdp``, which you can install with ``sage -i csdp``. EXAMPLES:: sage: C = graphs.PetersenGraph() sage: C.lovasz_theta() # optional csdp 4.0 sage: graphs.CycleGraph(5).lovasz_theta() # optional csdp 2.236068 TESTS:: sage: g = Graph() sage: g.lovasz_theta() # indirect doctest 0 """ n = graph.order() if not n: return 0 from networkx import write_edgelist from sage.misc.temporary_file import tmp_filename import subprocess from sage.features.csdp import CSDP CSDP().require() g = graph.relabel(inplace=False, perm=range(1, n + 1)).networkx_graph() tf_name = tmp_filename() with open(tf_name, 'wb') as tf: tf.write("{}\n{}\n".format(n, g.number_of_edges()).encode()) write_edgelist(g, tf, data=False) lines = subprocess.check_output(['theta', tf_name]) return float(lines.split()[-1])
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/graphs/lovasz_theta.py
0.911515
0.8415
lovasz_theta.py
pypi
r""" Hypergraph generators This module implements generators of hypergraphs. All hypergraphs can be built through the ``hypergraphs`` object. For instance, to build a complete 3-uniform hypergraph on 5 points, one can do:: sage: H = hypergraphs.CompleteUniform(5, 3) To enumerate hypergraphs with certain properties up to isomorphism, one can use method :meth:`~nauty`, which calls Brendan McKay's Nauty (`<http://cs.anu.edu.au/~bdm/nauty/>`_):: sage: list(hypergraphs.nauty(2, 2, connected=True)) [((0,), (0, 1))] **This module contains the following hypergraph generators** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:`~HypergraphGenerators.nauty` | Enumerate hypergraphs up to isomorphism using Nauty. :meth:`~HypergraphGenerators.CompleteUniform` | Return the complete `k`-uniform hypergraph on `n` points. :meth:`~HypergraphGenerators.UniformRandomUniform` | Return a uniformly sampled `k`-uniform hypergraph on `n` points with `m` hyperedges. Functions and methods --------------------- """ class HypergraphGenerators(): r""" A class consisting of constructors for common hypergraphs. """ def nauty(self, number_of_sets, number_of_vertices, multiple_sets=False, vertex_min_degree=None, vertex_max_degree=None, set_max_size=None, set_min_size=None, regular=False, uniform=False, max_intersection=None, connected=False, debug=False, options=""): r""" Enumerate hypergraphs up to isomorphism using Nauty. INPUT: - ``number_of_sets`` -- integer, at most 64 minus ``number_of_vertices`` - ``number_of_vertices`` -- integer, at most 30 - ``multiple_sets`` -- boolean (default: ``False``); whether to allow several sets of the hypergraph to be equal. - ``vertex_min_degree``, ``vertex_max_degree`` -- integers (default: ``None``); define the maximum and minimum degree of an element from the ground set (i.e. the number of sets which contain it). - ``set_min_size``, ``set_max_size`` -- integers (default: ``None``); define the maximum and minimum size of a set. - ``regular`` -- integers (default: ``False``); if set to an integer value `k`, requires the hypergraphs to be `k`-regular. It is actually a shortcut for the corresponding min/max values. - ``uniform`` -- integers (default: ``False``); if set to an integer value `k`, requires the hypergraphs to be `k`-uniform. It is actually a shortcut for the corresponding min/max values. - ``max_intersection`` -- integers (default: ``None``); constraints the maximum cardinality of the intersection of two sets from the hypergraphs. - ``connected`` -- boolean (default: ``False``); whether to require the hypergraphs to be connected. - ``debug`` -- boolean (default: ``False``); if ``True`` the first line of genbgL's output to standard error is captured and the first call to the generator's ``next()`` function will return this line as a string. A line leading with ">A" indicates a successful initiation of the program with some information on the arguments, while a line beginning with ">E" indicates an error with the input. - ``options`` -- string (default: ``""``) -- anything else that should be forwarded as input to Nauty's genbgL. See its documentation for more information : `<http://cs.anu.edu.au/~bdm/nauty/>`_. .. NOTE:: For genbgL the *first class* elements are vertices, and *second class* elements are the hypergraph's sets. OUTPUT: A tuple of tuples. EXAMPLES: Small hypergraphs:: sage: list(hypergraphs.nauty(4, 2)) [((), (0,), (1,), (0, 1))] Only connected ones:: sage: list(hypergraphs.nauty(2, 2, connected=True)) [((0,), (0, 1))] Non-empty sets only:: sage: list(hypergraphs.nauty(3, 2, set_min_size=1)) [((0,), (1,), (0, 1))] The Fano Plane, as the only 3-uniform hypergraph with 7 sets and 7 vertices:: sage: fano = next(hypergraphs.nauty(7, 7, uniform=3, max_intersection=1)) sage: print(fano) ((0, 1, 2), (0, 3, 4), (0, 5, 6), (1, 3, 5), (2, 4, 5), (2, 3, 6), (1, 4, 6)) The Fano Plane, as the only 3-regular hypergraph with 7 sets and 7 vertices:: sage: fano = next(hypergraphs.nauty(7, 7, regular=3, max_intersection=1)) sage: print(fano) ((0, 1, 2), (0, 3, 4), (0, 5, 6), (1, 3, 5), (2, 4, 5), (2, 3, 6), (1, 4, 6)) TESTS:: sage: len(list(hypergraphs.nauty(20, 20, uniform=2, regular=2,max_intersection=1))) 49 sage: list(hypergraphs.nauty(40, 40, uniform=2, regular=2,max_intersection=1)) Traceback (most recent call last): ... ValueError: cannot have more than 30 vertices sage: list(hypergraphs.nauty(40, 30, uniform=2, regular=2,max_intersection=1)) Traceback (most recent call last): ... ValueError: cannot have more than 64 sets+vertices """ if number_of_vertices > 30: raise ValueError("cannot have more than 30 vertices") if number_of_sets + number_of_vertices > 64: raise ValueError("cannot have more than 64 sets+vertices") import subprocess import shlex from sage.features.nauty import NautyExecutable genbgL_path = NautyExecutable("genbgL").absolute_filename() nauty_input = options if connected: nauty_input += " -c" if not multiple_sets: nauty_input += " -z" if max_intersection is not None: nauty_input += " -Z" + str(max_intersection) # degrees and sizes if regular is not False: vertex_max_degree = vertex_min_degree = regular if vertex_max_degree is None: vertex_max_degree = number_of_sets if vertex_min_degree is None: vertex_min_degree = 0 if uniform is not False: set_max_size = set_min_size = uniform if set_max_size is None: set_max_size = number_of_vertices if set_min_size is None: set_min_size = 0 nauty_input += " -d" + str(vertex_min_degree) + ":" + str(set_min_size) nauty_input += " -D" + str(vertex_max_degree) + ":" + str(set_max_size) nauty_input += " " + str(number_of_vertices) + " " + str(number_of_sets) + " " sp = subprocess.Popen(shlex.quote(genbgL_path) + " {0}".format(nauty_input), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) if debug: yield sp.stderr.readline() gen = sp.stdout total = number_of_sets + number_of_vertices from sage.graphs.graph import Graph while True: try: s = next(gen) except StopIteration: # Exhausted list of graphs from nauty geng return G = Graph(s[:-1], format='graph6') yield tuple(tuple(G.neighbor_iterator(v)) for v in range(number_of_vertices, total)) def CompleteUniform(self, n, k): r""" Return the complete `k`-uniform hypergraph on `n` points. INPUT: - ``k,n`` -- nonnegative integers with `k\leq n` EXAMPLES:: sage: h = hypergraphs.CompleteUniform(5, 2); h Incidence structure with 5 points and 10 blocks sage: len(h.packing()) 2 """ from sage.combinat.designs.incidence_structures import IncidenceStructure from itertools import combinations return IncidenceStructure(points=n, blocks=list(combinations(range(n), k))) def UniformRandomUniform(self, n, k, m): r""" Return a uniformly sampled `k`-uniform hypergraph on `n` points with `m` hyperedges. - ``n`` -- number of nodes of the graph - ``k`` -- uniformity - ``m`` -- number of edges EXAMPLES:: sage: H = hypergraphs.UniformRandomUniform(52, 3, 17) sage: H Incidence structure with 52 points and 17 blocks sage: H.is_connected() False TESTS:: sage: hypergraphs.UniformRandomUniform(-52, 3, 17) Traceback (most recent call last): ... ValueError: number of vertices should be non-negative sage: hypergraphs.UniformRandomUniform(52.9, 3, 17) Traceback (most recent call last): ... ValueError: number of vertices should be an integer sage: hypergraphs.UniformRandomUniform(52, -3, 17) Traceback (most recent call last): ... ValueError: the uniformity should be non-negative sage: hypergraphs.UniformRandomUniform(52, I, 17) Traceback (most recent call last): ... ValueError: the uniformity should be an integer """ from sage.rings.integer import Integer from sage.combinat.subset import Subsets from sage.misc.prandom import sample # Construct the vertex set if n < 0: raise ValueError("number of vertices should be non-negative") try: nverts = Integer(n) except TypeError: raise ValueError("number of vertices should be an integer") vertices = list(range(nverts)) # Construct the edge set if k < 0: raise ValueError("the uniformity should be non-negative") try: uniformity = Integer(k) except TypeError: raise ValueError("the uniformity should be an integer") all_edges = Subsets(vertices, uniformity) try: edges = [all_edges[t] for t in sample(range(len(all_edges)), m)] except OverflowError: raise OverflowError("binomial({}, {}) too large to be treated".format(n, k)) except ValueError: raise ValueError("number of edges m must be between 0 and binomial({}, {})".format(n, k)) from sage.combinat.designs.incidence_structures import IncidenceStructure return IncidenceStructure(points=vertices, blocks=edges) def BinomialRandomUniform(self, n, k, p): r""" Return a random `k`-uniform hypergraph on `n` points, in which each edge is inserted independently with probability `p`. - ``n`` -- number of nodes of the graph - ``k`` -- uniformity - ``p`` -- probability of an edge EXAMPLES:: sage: hypergraphs.BinomialRandomUniform(50, 3, 1).num_blocks() 19600 sage: hypergraphs.BinomialRandomUniform(50, 3, 0).num_blocks() 0 TESTS:: sage: hypergraphs.BinomialRandomUniform(50, 3, -0.1) Traceback (most recent call last): ... ValueError: edge probability should be in [0,1] sage: hypergraphs.BinomialRandomUniform(50, 3, 1.1) Traceback (most recent call last): ... ValueError: edge probability should be in [0,1] sage: hypergraphs.BinomialRandomUniform(-50, 3, 0.17) Traceback (most recent call last): ... ValueError: number of vertices should be non-negative sage: hypergraphs.BinomialRandomUniform(50.9, 3, 0.17) Traceback (most recent call last): ... ValueError: number of vertices should be an integer sage: hypergraphs.BinomialRandomUniform(50, -3, 0.17) Traceback (most recent call last): ... ValueError: the uniformity should be non-negative sage: hypergraphs.BinomialRandomUniform(50, I, 0.17) Traceback (most recent call last): ... ValueError: the uniformity should be an integer """ from sage.rings.integer import Integer if n < 0: raise ValueError("number of vertices should be non-negative") try: nverts = Integer(n) except TypeError: raise ValueError("number of vertices should be an integer") if k < 0: raise ValueError("the uniformity should be non-negative") try: uniformity = Integer(k) except TypeError: raise ValueError("the uniformity should be an integer") if not 0 <= p <= 1: raise ValueError("edge probability should be in [0,1]") import numpy.random as nrn from sage.functions.other import binomial m = nrn.binomial(binomial(nverts, uniformity), p) return hypergraphs.UniformRandomUniform(n, k, m) hypergraphs = HypergraphGenerators()
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/graphs/hypergraph_generators.py
0.904326
0.776029
hypergraph_generators.py
pypi
r""" Overview of (di)graph data structures This module contains no code, and describes Sage's data structures for graphs and digraphs. They can be used directly at Cython/C level, or through the :class:`Graph` and :class:`DiGraph` classes (except one) Data structures --------------- Four data structures are natively available for (di)graphs in Sage: - :mod:`~sage.graphs.base.sparse_graph` (default) -- for sparse (di)graphs, with a `\log(n)` edge test, and easy enumeration of neighbors. It is the most general-purpose data structure, though it can have a high memory cost in practice. - Supports: Addition/removal of edges/vertices, multiple edges, edge labels and loops. - :mod:`~sage.graphs.base.dense_graph` -- for dense (di)graphs, with a `O(1)` edge test, and slow enumeration of neighbors. - Supports: addition/removal of edges/vertices, and loops. - Does not support: multiple edges and edge labels. - :mod:`~sage.graphs.base.static_sparse_graph` -- for sparse (di)graphs and very intensive computations (at C-level). It is faster than :mod:`~sage.graphs.base.sparse_graph` in practice and *much* lighter in memory. - Supports: multiple edges, edge labels and loops - Does not support: addition/removal of edges/vertices. - :mod:`~sage.graphs.base.static_dense_graph` -- for dense (di)graphs and very intensive computations (at C-level). It is mostly a wrapper over bitsets. - Supports: addition/removal of edges/vertices, and loops. - Does not support: multiple edges and edge labels. For more information, see the data structures' respective pages. The backends ------------ The :class:`Graph` and :class:`DiGraph` objects delegate the storage of vertices and edges to other objects: the :mod:`graph backends <sage.graphs.base.graph_backends>`:: sage: Graph()._backend <sage.graphs.base.sparse_graph.SparseGraphBackend object at ...> A (di)graph backend is a simpler (di)graph class having only the most elementary methods (e.g.: add/remove vertices/edges). Its vertices can be arbitrary hashable objects. The only backend available in Sage is :class:`~sage.graphs.base.c_graph.CGraphBackend`. CGraph and CGraphBackend ------------------------ :class:`~sage.graphs.base.c_graph.CGraphBackend` is the backend of all native data structures that can be used by :class:`Graph` and :class:`DiGraph`. It is extended by: - :class:`~sage.graphs.base.dense_graph.DenseGraphBackend` - :class:`~sage.graphs.base.sparse_graph.SparseGraphBackend` - :class:`~sage.graphs.base.static_sparse_backend.StaticSparseBackend` While a :class:`~sage.graphs.base.c_graph.CGraphBackend` deals with arbitrary (hashable) vertices, it contains a ``._cg`` attribute of type :class:`~sage.graphs.base.c_graph.CGraph` which only deals with integer vertices. The :class:`~sage.graphs.base.c_graph.CGraph` data structures available in Sage are: - :class:`~sage.graphs.base.dense_graph.DenseGraph` - :class:`~sage.graphs.base.sparse_graph.SparseGraph` - :class:`~sage.graphs.base.static_sparse_backend.StaticSparseCGraph` See the :mod:`~sage.graphs.base.c_graph` module for more information. """
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/graphs/base/overview.py
0.933325
0.81409
overview.py
pypi
from sage.rings.integer_ring import ZZ from sage.symbolic.constants import NaN from sage.misc.functional import sqrt from sage.misc.superseded import deprecation def mean(v): """ Return the mean of the elements of `v`. We define the mean of the empty list to be the (symbolic) NaN, following the convention of MATLAB, Scipy, and R. This function is deprecated. Use ``numpy.mean`` or ``numpy.nanmean`` instead. INPUT: - `v` -- a list of numbers OUTPUT: - a number EXAMPLES:: sage: mean([pi, e]) doctest:warning... DeprecationWarning: sage.stats.basic_stats.mean is deprecated; use numpy.mean or numpy.nanmean instead See https://trac.sagemath.org/29662 for details. 1/2*pi + 1/2*e sage: mean([]) NaN sage: mean([I, sqrt(2), 3/5]) 1/3*sqrt(2) + 1/3*I + 1/5 sage: mean([RIF(1.0103,1.0103), RIF(2)]) 1.5051500000000000? sage: mean(range(4)) 3/2 sage: v = stats.TimeSeries([1..100]) sage: mean(v) 50.5 """ deprecation(29662, 'sage.stats.basic_stats.mean is deprecated; use numpy.mean or numpy.nanmean instead') if hasattr(v, 'mean'): return v.mean() if not v: return NaN s = sum(v) if isinstance(s, int): # python integers are stupid. return s / ZZ(len(v)) return s / len(v) def mode(v): """ Return the mode of `v`. The mode is the list of the most frequently occurring elements in `v`. If `n` is the most times that any element occurs in `v`, then the mode is the list of elements of `v` that occur `n` times. The list is sorted if possible. This function is deprecated. Use ``scipy.stats.mode`` or ``statistics.mode`` instead. .. NOTE:: The elements of `v` must be hashable. INPUT: - `v` -- a list OUTPUT: - a list (sorted if possible) EXAMPLES:: sage: v = [1,2,4,1,6,2,6,7,1] sage: mode(v) doctest:warning... DeprecationWarning: sage.stats.basic_stats.mode is deprecated; use scipy.stats.mode or statistics.mode instead See https://trac.sagemath.org/29662 for details. [1] sage: v.count(1) 3 sage: mode([]) [] sage: mode([1,2,3,4,5]) [1, 2, 3, 4, 5] sage: mode([3,1,2,1,2,3]) [1, 2, 3] sage: mode([0, 2, 7, 7, 13, 20, 2, 13]) [2, 7, 13] sage: mode(['sage', 'four', 'I', 'three', 'sage', 'pi']) ['sage'] sage: class MyClass: ....: def mode(self): ....: return [1] sage: stats.mode(MyClass()) [1] """ deprecation(29662, 'sage.stats.basic_stats.mode is deprecated; use scipy.stats.mode or statistics.mode instead') if hasattr(v, 'mode'): return v.mode() if not v: return v freq = {} for i in v: if i in freq: freq[i] += 1 else: freq[i] = 1 n = max(freq.values()) try: return sorted(u for u, f in freq.items() if f == n) except TypeError: return [u for u, f in freq.items() if f == n] def std(v, bias=False): """ Return the standard deviation of the elements of `v`. We define the standard deviation of the empty list to be NaN, following the convention of MATLAB, Scipy, and R. This function is deprecated. Use ``numpy.std`` or ``numpy.nanstd`` instead. INPUT: - `v` -- a list of numbers - ``bias`` -- bool (default: False); if False, divide by len(v) - 1 instead of len(v) to give a less biased estimator (sample) for the standard deviation. OUTPUT: - a number EXAMPLES:: sage: std([1..6], bias=True) doctest:warning... DeprecationWarning: sage.stats.basic_stats.std is deprecated; use numpy.std or numpy.nanstd instead See https://trac.sagemath.org/29662 for details. doctest:warning... DeprecationWarning: sage.stats.basic_stats.variance is deprecated; use numpy.var or numpy.nanvar instead See https://trac.sagemath.org/29662 for details. doctest:warning... DeprecationWarning: sage.stats.basic_stats.mean is deprecated; use numpy.mean or numpy.nanmean instead See https://trac.sagemath.org/29662 for details. 1/2*sqrt(35/3) sage: std([1..6], bias=False) sqrt(7/2) sage: std([e, pi]) sqrt(1/2)*abs(pi - e) sage: std([]) NaN sage: std([I, sqrt(2), 3/5]) 1/15*sqrt(1/2)*sqrt((10*sqrt(2) - 5*I - 3)^2 + (5*sqrt(2) - 10*I + 3)^2 + (5*sqrt(2) + 5*I - 6)^2) sage: std([RIF(1.0103, 1.0103), RIF(2)]) 0.6998235813403261? sage: import numpy sage: x = numpy.array([1,2,3,4,5]) sage: std(x, bias=False) 1.5811388300841898 sage: x = stats.TimeSeries([1..100]) sage: std(x) 29.011491975882016 TESTS:: sage: data = [random() for i in [1 .. 20]] sage: std(data) # random 0.29487771726609185 """ deprecation(29662, 'sage.stats.basic_stats.std is deprecated; use numpy.std or numpy.nanstd instead') # NOTE: in R bias = False by default, and in Scipy bias=True by # default, and R is more popular. if hasattr(v, 'standard_deviation'): return v.standard_deviation(bias=bias) import numpy if isinstance(v, numpy.ndarray): # accounts for numpy arrays if bias: return v.std() else: return v.std(ddof=1) if not v: # standard deviation of empty set defined as NaN return NaN return sqrt(variance(v, bias=bias)) def variance(v, bias=False): """ Return the variance of the elements of `v`. We define the variance of the empty list to be NaN, following the convention of MATLAB, Scipy, and R. This function is deprecated. Use ``numpy.var`` or ``numpy.nanvar`` instead. INPUT: - `v` -- a list of numbers - ``bias`` -- bool (default: False); if False, divide by len(v) - 1 instead of len(v) to give a less biased estimator (sample) for the standard deviation. OUTPUT: - a number EXAMPLES:: sage: variance([1..6]) doctest:warning... DeprecationWarning: sage.stats.basic_stats.variance is deprecated; use numpy.var or numpy.nanvar instead See https://trac.sagemath.org/29662 for details. 7/2 sage: variance([1..6], bias=True) 35/12 sage: variance([e, pi]) 1/2*(pi - e)^2 sage: variance([]) NaN sage: variance([I, sqrt(2), 3/5]) 1/450*(10*sqrt(2) - 5*I - 3)^2 + 1/450*(5*sqrt(2) - 10*I + 3)^2 + 1/450*(5*sqrt(2) + 5*I - 6)^2 sage: variance([RIF(1.0103, 1.0103), RIF(2)]) 0.4897530450000000? sage: import numpy sage: x = numpy.array([1,2,3,4,5]) sage: variance(x, bias=False) 2.5 sage: x = stats.TimeSeries([1..100]) sage: variance(x) 841.6666666666666 sage: variance(x, bias=True) 833.25 sage: class MyClass: ....: def variance(self, bias = False): ....: return 1 sage: stats.variance(MyClass()) 1 sage: class SillyPythonList: ....: def __init__(self): ....: self.__list = [2, 4] ....: def __len__(self): ....: return len(self.__list) ....: def __iter__(self): ....: return self.__list.__iter__() ....: def mean(self): ....: return 3 sage: R = SillyPythonList() sage: variance(R) 2 sage: variance(R, bias=True) 1 TESTS: The performance issue from :trac:`10019` is solved:: sage: variance([1] * 2^18) 0 """ deprecation(29662, 'sage.stats.basic_stats.variance is deprecated; use numpy.var or numpy.nanvar instead') if hasattr(v, 'variance'): return v.variance(bias=bias) import numpy x = 0 if isinstance(v, numpy.ndarray): # accounts for numpy arrays if bias: return v.var() else: return v.var(ddof=1) if not v: # variance of empty set defined as NaN return NaN mu = mean(v) for vi in v: x += (vi - mu)**2 if bias: # population variance if isinstance(x, int): return x / ZZ(len(v)) return x / len(v) else: # sample variance if isinstance(x, int): return x / ZZ(len(v)-1) return x / (len(v)-1) def median(v): """ Return the median (middle value) of the elements of `v` If `v` is empty, we define the median to be NaN, which is consistent with NumPy (note that R returns NULL). If `v` is comprised of strings, TypeError occurs. For elements other than numbers, the median is a result of ``sorted()``. This function is deprecated. Use ``numpy.median`` or ``numpy.nanmedian`` instead. INPUT: - `v` -- a list OUTPUT: - median element of `v` EXAMPLES:: sage: median([1,2,3,4,5]) doctest:warning... DeprecationWarning: sage.stats.basic_stats.median is deprecated; use numpy.median or numpy.nanmedian instead See https://trac.sagemath.org/29662 for details. 3 sage: median([e, pi]) 1/2*pi + 1/2*e sage: median(['sage', 'linux', 'python']) 'python' sage: median([]) NaN sage: class MyClass: ....: def median(self): ....: return 1 sage: stats.median(MyClass()) 1 """ deprecation(29662, 'sage.stats.basic_stats.median is deprecated; use numpy.median or numpy.nanmedian instead') if hasattr(v, 'median'): return v.median() if not v: # Median of empty set defined as NaN return NaN values = sorted(v) if len(values) % 2: return values[((len(values))+1)//2-1] else: lower = values[(len(values)+1)//2-1] upper = values[len(values)//2] return (lower + upper) / ZZ(2) def moving_average(v, n): """ Return the moving average of a list `v`. The moving average of a list is often used to smooth out noisy data. If `v` is empty, we define the entries of the moving average to be NaN. This method is deprecated. Use ``pandas.Series.rolling`` instead. INPUT: - `v` -- a list - `n` -- the number of values used in computing each average. OUTPUT: - a list of length ``len(v)-n+1``, since we do not fabric any values EXAMPLES:: sage: moving_average([1..10], 1) doctest:warning... DeprecationWarning: sage.stats.basic_stats.moving_average is deprecated; use pandas.Series.rolling instead See https://trac.sagemath.org/29662 for details. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sage: moving_average([1..10], 4) [5/2, 7/2, 9/2, 11/2, 13/2, 15/2, 17/2] sage: moving_average([], 1) [] sage: moving_average([pi, e, I, sqrt(2), 3/5], 2) [1/2*pi + 1/2*e, 1/2*e + 1/2*I, 1/2*sqrt(2) + 1/2*I, 1/2*sqrt(2) + 3/10] We check if the input is a time series, and if so use the optimized ``simple_moving_average`` method, but with (slightly different) meaning as defined above (the point is that the ``simple_moving_average`` on time series returns `n` values:: sage: a = stats.TimeSeries([1..10]) sage: stats.moving_average(a, 3) [2.0000, 3.0000, 4.0000, 5.0000, 6.0000, 7.0000, 8.0000, 9.0000] sage: stats.moving_average(list(a), 3) [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] """ deprecation(29662, 'sage.stats.basic_stats.moving_average is deprecated; use pandas.Series.rolling instead') if not v: return v from .time_series import TimeSeries if isinstance(v, TimeSeries): return v.simple_moving_average(n)[n - 1:] n = int(n) if n <= 0: raise ValueError("n must be positive") nn = ZZ(n) s = sum(v[:n]) ans = [s / nn] for i in range(n, len(v)): # add in the i-th value in v to our running sum, # and remove the value n places back. s += v[i] - v[i - n] ans.append(s / nn) return ans
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/stats/basic_stats.py
0.897367
0.709651
basic_stats.py
pypi
from sage.sandpiles.sandpile import Sandpile from sage.graphs.graph_generators import graphs class SandpileExamples(): """ Some examples of sandpiles. Here are the available examples; you can also type ``sandpiles.`` and hit tab to get a list: - :meth:`Complete` - :meth:`Cycle` - :meth:`Diamond` - :meth:`Grid` - :meth:`House` EXAMPLES:: sage: s = sandpiles.Complete(4) sage: s.invariant_factors() [1, 4, 4] sage: s.laplacian() [ 3 -1 -1 -1] [-1 3 -1 -1] [-1 -1 3 -1] [-1 -1 -1 3] """ def __call__(self): r""" If sandpiles() is executed, return a helpful message. INPUT: None OUTPUT: None EXAMPLES:: sage: sandpiles() Try sandpiles.FOO() where FOO is in the list: <BLANKLINE> Complete, Cycle, Diamond, Fan, Grid, House, Wheel """ print('Try sandpiles.FOO() where FOO is in the list:\n') print(" " + ", ".join(str(i) for i in dir(sandpiles) if i[0] != '_')) def Complete(self, n): """ The complete sandpile graph with `n` vertices. INPUT: - ``n`` -- positive integer OUTPUT: - Sandpile EXAMPLES:: sage: s = sandpiles.Complete(4) sage: s.group_order() 16 sage: sandpiles.Complete(3) == sandpiles.Cycle(3) True """ return Sandpile(graphs.CompleteGraph(n),0) def Cycle(self, n): """ Sandpile on the cycle graph with `n` vertices. INPUT: - ``n`` -- a non-negative integer OUTPUT: - Sandpile EXAMPLES:: sage: s = sandpiles.Cycle(4) sage: s.edges(sort=True) [(0, 1, 1), (0, 3, 1), (1, 0, 1), (1, 2, 1), (2, 1, 1), (2, 3, 1), (3, 0, 1), (3, 2, 1)] """ return Sandpile(graphs.CycleGraph(n),0) def Diamond(self): """ Sandpile on the diamond graph. INPUT: None OUTPUT: - Sandpile EXAMPLES:: sage: s = sandpiles.Diamond() sage: s.invariant_factors() [1, 1, 8] """ return Sandpile(graphs.DiamondGraph(),0) def Fan(self, n, deg_three_verts=False): """ Sandpile on the Fan graph with a total of `n` vertices. INPUT: - ``n`` -- a non-negative integer OUTPUT: - Sandpile EXAMPLES:: sage: f = sandpiles.Fan(10) sage: f.group_order() == fibonacci(18) True sage: f = sandpiles.Fan(10,True) # all nonsink vertices have deg 3 sage: f.group_order() == fibonacci(20) True """ f = graphs.WheelGraph(n) if n>2: f.delete_edge(1,n-1) if deg_three_verts: f.allow_multiple_edges(True) f.add_edges([(0,1),(0,n-1)]) return Sandpile(f,0) elif n==1: return Sandpile(f,0) elif n==2: if deg_three_verts: return Sandpile({0:{1:3}, 1:{0:3}}) else: return Sandpile(f,0) def Grid(self, m, n): """ Sandpile on the diamond graph. INPUT: - ``m``, ``n`` -- negative integers OUTPUT: - Sandpile EXAMPLES:: sage: s = sandpiles.Grid(2,3) sage: s.vertices(sort=True) [(0, 0), (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)] sage: s.invariant_factors() [1, 1, 1, 1, 1, 2415] sage: s = sandpiles.Grid(1,1) sage: s.dict() {(0, 0): {(1, 1): 4}, (1, 1): {(0, 0): 4}} """ G = graphs.Grid2dGraph(m+2,n+2) G.allow_multiple_edges(True) # to ensure each vertex ends up with degree 4 V = [(i,j) for i in [0,m+1] for j in range(n+2)] + [(i,j) for j in [0,n+1] for i in range(m+2)] G.merge_vertices(V) return Sandpile(G, (0,0)) def House(self): """ Sandpile on the House graph. INPUT: None OUTPUT: - Sandpile EXAMPLES:: sage: s = sandpiles.House() sage: s.invariant_factors() [1, 1, 1, 11] """ return Sandpile(graphs.HouseGraph(),0) def Wheel(self, n): """ Sandpile on the wheel graph with a total of `n` vertices. INPUT: - ``n`` -- a non-negative integer OUTPUT: - Sandpile EXAMPLES:: sage: w = sandpiles.Wheel(6) sage: w.invariant_factors() [1, 1, 1, 11, 11] """ return Sandpile(graphs.WheelGraph(n),0) sandpiles = SandpileExamples()
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/sandpiles/examples.py
0.786254
0.744865
examples.py
pypi
__author__ = "Gustavo Niemeyer <gustavo@niemeyer.net>" __license__ = "PSF License" import datetime __all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] EASTER_JULIAN = 1 EASTER_ORTHODOX = 2 EASTER_WESTERN = 3 def easter(year, algorithm=EASTER_WESTERN): """ This function was ported from the work done by GM Arts, on top of the algorithm by Claus Tondering, which was based in part on the algorithm of Ouding (1940), as quoted in "Explanatory Supplement to the Astronomical Almanac", P. Kenneth Seidelmann, editor. This function implements three different easter calculation algorithms: 1 - Original calculation in Julian calendar, valid in dates after 326 AD 2 - Original algorithm, with date converted to Gregorian calendar, valid in years 1583 to 4099 3 - Revised algorithm, in Gregorian calendar, valid in years 1583 to 4099 as well These algorithms are represented by the constants: EASTER_JULIAN = 1 EASTER_ORTHODOX = 2 EASTER_WESTERN = 3 The default algorithm is algorithm 3. More about the algorithm may be found at: http://users.chariot.net.au/~gmarts/eastalg.htm and https://www.tondering.dk/claus/calendar.html EXAMPLES:: sage: import sage.finance.easter doctest:warning... DeprecationWarning: the package sage.finance is deprecated... sage: sage.finance.easter.easter(2009, 1) datetime.date(2009, 4, 6) sage: sage.finance.easter.easter(2009, 2) datetime.date(2009, 4, 19) sage: sage.finance.easter.easter(2009, 3) datetime.date(2009, 4, 12) sage: sage.finance.easter.easter(2010, 1) datetime.date(2010, 3, 22) sage: sage.finance.easter.easter(2010, 2) datetime.date(2010, 4, 4) sage: sage.finance.easter.easter(2010, 3) datetime.date(2010, 4, 4) AUTHORS: - Gustavo Niemeyer (author of function) - Phaedon Sinis (adapted code for sage) """ year = int(year) algorithm = int(algorithm) if not (1 <= algorithm <= 3): raise ValueError("invalid algorithm") # g - Golden year - 1 # c - Century # h - (23 - Epact) mod 30 # i - Number of days from March 21 to Paschal Full Moon # j - Weekday for PFM (0=Sunday, etc) # p - Number of days from March 21 to Sunday on or before PFM # (-6 to 28 algorithms 1 & 3, to 56 for algorithm 2) # e - Extra days to add for algorithm 2 (converting Julian # date to Gregorian date) y = year g = y % 19 e = 0 if algorithm < 3: # Old algorithm i = (19*g+15)%30 j = (y+y//4+i)%7 if algorithm == 2: # Extra dates to convert Julian to Gregorian date e = 10 if y > 1600: e = e+y//100-16-(y//100-16)//4 else: # New algorithm c = y//100 h = (c-c//4-(8*c+13)//25+19*g+15)%30 i = h-(h//28)*(1-(h//28)*(29//(h+1))*((21-g)//11)) j = (y+y//4+i+2-c+c//4)%7 # p can be from -6 to 56 corresponding to dates 22 March to 23 May # (later dates apply to algorithm 2, although 23 May never actually occurs) p = i-j+e d = 1+(p+27+(p+6)//40)%31 m = 3+(p+26)//30 return datetime.date(y, m, d)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/finance/easter.py
0.560854
0.39528
easter.py
pypi
r""" Stock Market Price Series This module's main class is :class:`Stock`. It defines the following methods: .. csv-table:: :class: contentstable :widths: 20,80 :delim: | :meth:`~sage.finance.stock.Stock.market_value` | Return the current market value of this stock. :meth:`~sage.finance.stock.Stock.current_price_data` | Get Yahoo current price data for this stock. :meth:`~sage.finance.stock.Stock.history` | Return an immutable sequence of historical price data for this stock :meth:`~sage.finance.stock.Stock.open` | Return a time series containing historical opening prices for this stock. :meth:`~sage.finance.stock.Stock.close` | Return the time series of all historical closing prices for this stock. :meth:`~sage.finance.stock.Stock.load_from_file` | Load historical data from a local csv formatted data file. .. WARNING:: The `Stock` class is currently broken due to the change in the Yahoo interface. See :trac:`25473`. AUTHORS: - William Stein, 2008 - Brett Nakayama, 2008 - Chris Swierczewski, 2008 TESTS:: sage: from sage.finance.stock import OHLC doctest:warning... DeprecationWarning: the package sage.finance is deprecated... sage: ohlc = OHLC('18-Aug-04', 100.01, 104.06, 95.96, 100.34, 22353092) sage: loads(dumps(ohlc)) == ohlc True Classes and methods ------------------- """ from sage.structure.all import Sequence from datetime import date from urllib.request import urlopen class OHLC: def __init__(self, timestamp, open, high, low, close, volume): """ Open, high, low, and close information for a stock. Also stores a timestamp for that data along with the volume. INPUT: - ``timestamp`` -- string - ``open``, ``high``, ``low``, ``close`` -- float - ``volume`` -- int EXAMPLES:: sage: from sage.finance.stock import OHLC sage: OHLC('18-Aug-04', 100.01, 104.06, 95.96, 100.34, 22353092) 18-Aug-04 100.01 104.06 95.96 100.34 22353092 """ self.timestamp = timestamp self.open = float(open) self.high = float(high) self.low = float(low) self.close = float(close) self.volume = int(volume) def __repr__(self): """ Return string representation of stock OHLC data. EXAMPLES:: sage: from sage.finance.stock import OHLC sage: OHLC('18-Aug-04', 100.01, 104.06, 95.96, 100.34, 22353092).__repr__() ' 18-Aug-04 100.01 104.06 95.96 100.34 22353092' """ return '%10s %4.2f %4.2f %4.2f %4.2f %10d' % (self.timestamp, self.open, self.high, self.low, self.close, self.volume) def __eq__(self, other): """ Compare ``self`` and ``other``. EXAMPLES:: sage: from sage.finance.stock import OHLC sage: ohlc = OHLC('18-Aug-04', 100.01, 104.06, 95.96, 100.34, 22353092) sage: ohlc2 = OHLC('18-Aug-04', 101.01, 104.06, 95.96, 100.34, 22353092) sage: ohlc == ohlc2 False """ if not isinstance(other, OHLC): return False return (self.timestamp == other.timestamp and self.open == other.open and self.high == other.high and self.low == other.low and self.close == other.close and self.volume == other.volume) def __hash__(self): """ Return the hash of ``self``. EXAMPLES:: sage: from sage.finance.stock import OHLC sage: ohlc = OHLC('18-Aug-04', 100.01, 104.06, 95.96, 100.34, 22353092) sage: H = hash(ohlc) """ return hash((self.timestamp, self.open, self.high, self.low, self.close , self.volume)) def __ne__(self, other): """ Compare ``self`` and ``other``. EXAMPLES:: sage: from sage.finance.stock import OHLC sage: ohlc = OHLC('18-Aug-04', 100.01, 104.06, 95.96, 100.34, 22353092) sage: ohlc2 = OHLC('18-Aug-04', 101.01, 104.06, 95.96, 100.34, 22353092) sage: ohlc != ohlc2 True """ return not (self == other) class Stock: """ Class for retrieval of stock market information. """ def __init__(self, symbol, cid=''): """ Create a ``Stock`` object. Optional initialization by ``cid``: an identifier for each equity used by Google Finance. INPUT: - ``symbol`` -- string, a ticker symbol (with or without market). Format: ``"MARKET:SYMBOL"`` or ``"SYMBOL"``. If you don't supply the market, it is assumed to be NYSE or NASDAQ. e.g. "goog" or "OTC:NTDOY" - ``cid`` -- Integer, a Google contract ID (optional). .. NOTE:: Currently, the symbol and cid do not have to match. When using :meth:`history`, the cid will take precedence. EXAMPLES:: sage: S = finance.Stock('ibm') # optional -- internet doctest:warning... DeprecationWarning: Importing finance from here is deprecated... sage: S # optional -- internet # known bug IBM (...) """ self.symbol = symbol.upper() self.cid = cid def __repr__(self): """ Return string representation of this stock. EXAMPLES:: sage: finance.Stock('ibm').__repr__() # optional -- internet # known bug 'IBM (...)' """ return "%s (%s)" % (self.symbol, self.market_value()) def market_value(self): """ Return the current market value of this stock. OUTPUT: A Python float. EXAMPLES:: sage: finance.Stock('goog').market_value() # random; optional - internet # known bug 575.83000000000004 """ return float(self.current_price_data()['price']) def current_price_data(self): r""" Get Yahoo current price data for this stock. This method returns a dictionary with the following keys: .. csv-table:: :class: contentstable :widths: 25,25,25,25 :delim: | ``'price'`` | ``'change'`` | ``'volume'`` | ``'avg_daily_volume'`` ``'stock_exchange'`` | ``'market_cap'`` | ``'book_value'`` | ``'ebitda'`` ``'dividend_per_share'`` | ``'dividend_yield'`` | ``'earnings_per_share'`` | ``'52_week_high'`` ``'52_week_low'`` | ``'50day_moving_avg'`` | ``'200day_moving_avg'`` | ``'price_earnings_ratio'`` ``'price_earnings_growth_ratio'`` | ``'price_sales_ratio'`` | ``'price_book_ratio'`` | ``'short_ratio'``. EXAMPLES:: sage: finance.Stock('GOOG').current_price_data() # random; optional - internet # known bug {'200day_moving_avg': '536.57', '50day_moving_avg': '546.01', '52_week_high': '599.65', '52_week_low': '487.56', 'avg_daily_volume': '1826450', 'book_value': '153.64', 'change': '+0.56', 'dividend_per_share': 'N/A', 'dividend_yield': 'N/A', 'earnings_per_share': '20.99', 'ebitda': '21.48B', 'market_cap': '366.11B', 'price': '537.90', 'price_book_ratio': '3.50', 'price_earnings_growth_ratio': '0.00', 'price_earnings_ratio': '25.62', 'price_sales_ratio': '5.54', 'short_ratio': '1.50', 'stock_exchange': '"NMS"', 'volume': '1768181'} TESTS:: sage: finance.Stock('GOOG').current_price_data() # optional -- internet # known bug {'200day_moving_avg': ..., '50day_moving_avg': ..., '52_week_high': ..., '52_week_low': ..., 'avg_daily_volume': ..., 'book_value': ..., 'change': ..., 'dividend_per_share': ..., 'dividend_yield': ..., 'earnings_per_share': ..., 'ebitda': ..., 'market_cap': ..., 'price': ..., 'price_book_ratio': ..., 'price_earnings_growth_ratio': ..., 'price_earnings_ratio': ..., 'price_sales_ratio': ..., 'short_ratio': ..., 'stock_exchange': ..., 'volume': ...} """ url = 'http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s' % (self.symbol, 'l1c1va2xj1b4j4dyekjm3m4rr5p5p6s7') values = urlopen(url).read().strip().strip('"').split(',') data = {} data['price'] = values[0] data['change'] = values[1] data['volume'] = values[2] data['avg_daily_volume'] = values[3] data['stock_exchange'] = values[4] data['market_cap'] = values[5] data['book_value'] = values[6] data['ebitda'] = values[7] data['dividend_per_share'] = values[8] data['dividend_yield'] = values[9] data['earnings_per_share'] = values[10] data['52_week_high'] = values[11] data['52_week_low'] = values[12] data['50day_moving_avg'] = values[13] data['200day_moving_avg'] = values[14] data['price_earnings_ratio'] = values[15] data['price_earnings_growth_ratio'] = values[16] data['price_sales_ratio'] = values[17] data['price_book_ratio'] = values[18] data['short_ratio'] = values[19] return data def history(self, startdate='Jan+1,+1900', enddate=None, histperiod='daily'): """ Return an immutable sequence of historical price data for this stock, obtained from Google. OHLC data is stored internally as well. By default, returns the past year's daily OHLC data. Dates ``startdate`` and ``enddate`` should be formatted ``'Mon+d,+yyyy'``, where ``'Mon'`` is a three character abbreviation of the month's name. .. NOTE:: Google Finance returns the past year's financial data by default when ``startdate`` is set too low from the equity's date of going public. By default, this function only looks at the NASDAQ and NYSE markets. However, if you specified the market during initialization of the stock (i.e. ``finance.Stock("OTC:NTDOY")``), this method will give correct results. INPUT: - ``startdate`` -- string, (default: ``'Jan+1,+1900'``) - ``enddate`` -- string, (default: current date) - ``histperiod`` -- string, (``'daily'`` or ``'weekly'``) OUTPUT: A sequence. EXAMPLES: We get the first five days of VMware's stock history:: sage: finance.Stock('vmw').history('Aug+13,+2007')[:5] # optional -- internet # known bug [ 14-Aug-07 50.00 55.50 48.00 51.00 38262850, 15-Aug-07 52.11 59.87 51.50 57.71 10689100, 16-Aug-07 60.99 61.49 52.71 56.99 6919500, 17-Aug-07 59.00 59.00 54.45 55.55 3087000, 20-Aug-07 56.05 57.50 55.61 57.33 2141900 ] sage: finance.Stock('F').history('Aug+20,+1992', 'Jul+7,+2008')[:5] # optional -- internet # known bug [ 20-Aug-92 0.00 7.90 7.73 7.83 5492698, 21-Aug-92 0.00 7.92 7.66 7.68 5345999, 24-Aug-92 0.00 7.59 7.33 7.35 11056299, 25-Aug-92 0.00 7.66 7.38 7.61 8875299, 26-Aug-92 0.00 7.73 7.64 7.68 6447201 ] Note that when ``startdate`` is too far prior to a stock's actual start date, Google Finance defaults to a year's worth of stock history leading up to the specified end date. For example, Apple's (AAPL) stock history only dates back to September 7, 1984:: sage: finance.Stock('AAPL').history('Sep+1,+1900', 'Jan+1,+2000')[0:5] # optional -- internet # known bug [ 4-Jan-99 0.00 1.51 1.43 1.47 238221200, 5-Jan-99 0.00 1.57 1.48 1.55 352522800, 6-Jan-99 0.00 1.58 1.46 1.49 337125600, 7-Jan-99 0.00 1.61 1.50 1.61 357254800, 8-Jan-99 0.00 1.67 1.57 1.61 169680000 ] Here is an example where we create and get the history of a stock that is not in NASDAQ or NYSE:: sage: finance.Stock("OTC:NTDOY").history(startdate="Jan+1,+2007", enddate="Jan+1,+2008")[:5] # optional -- internet # known bug [ 3-Jan-07 32.44 32.75 32.30 32.44 156283, 4-Jan-07 31.70 32.40 31.20 31.70 222643, 5-Jan-07 30.15 30.50 30.15 30.15 65670, 8-Jan-07 30.10 30.50 30.00 30.10 130765, 9-Jan-07 29.90 30.05 29.60 29.90 103338 ] Here, we create a stock by cid, and get historical data. Note that when using historical, if a cid is specified, it will take precedence over the stock's symbol. So, if the symbol and cid do not match, the history based on the contract id will be returned. :: sage: sage.finance.stock.Stock("AAPL", 22144).history(startdate='Jan+1,+1990')[:5] #optional -- internet # known bug [ 8-Jun-99 0.00 1.74 1.70 1.70 78414000, 9-Jun-99 0.00 1.73 1.69 1.73 88446400, 10-Jun-99 0.00 1.72 1.69 1.72 79262400, 11-Jun-99 0.00 1.73 1.65 1.66 46261600, 14-Jun-99 0.00 1.67 1.61 1.62 39270000 ] """ if enddate is None: enddate = date.today().strftime("%b+%d,+%Y") symbol = self.symbol if self.cid == '': if ':' in symbol: R = self._get_data('', startdate, enddate, histperiod) else: try: R = self._get_data('NASDAQ:', startdate, enddate, histperiod) except RuntimeError: R = self._get_data("NYSE:", startdate, enddate, histperiod) else: R = self._get_data('', startdate, enddate, histperiod) self.__historical = [] self.__historical = self._load_from_csv(R) return self.__historical def open(self, *args, **kwds): r""" Return a time series containing historical opening prices for this stock. If no arguments are given, will return last acquired historical data. Otherwise, data will be gotten from Google Finance. INPUT: - ``startdate`` -- string, (default: ``'Jan+1,+1900'``) - ``enddate`` -- string, (default: current date) - ``histperiod`` -- string, (``'daily'`` or ``'weekly'``) OUTPUT: A time series -- close price data. EXAMPLES: You can directly obtain Open data as so:: sage: finance.Stock('vmw').open(startdate='Jan+1,+2008', enddate='Feb+1,+2008') # optional -- internet # known bug [85.4900, 84.9000, 82.0000, 81.2500, ... 82.0000, 58.2700, 54.4900, 55.6000, 56.9800] Or, you can initialize stock data first and then extract the Open data:: sage: c = finance.Stock('vmw') # optional -- internet # known bug sage: c.history(startdate='Feb+1,+2008', enddate='Mar+1,+2008')[:5] # optional -- internet # known bug [ 1-Feb-08 56.98 58.14 55.06 57.85 2490481, 4-Feb-08 58.00 60.47 56.91 58.05 1840709, 5-Feb-08 57.60 59.30 57.17 59.30 1712179, 6-Feb-08 60.32 62.00 59.50 61.52 2211775, 7-Feb-08 60.50 62.75 59.56 60.80 1521651 ] sage: c.open() # optional -- internet # known bug [56.9800, 58.0000, 57.6000, 60.3200, ... 56.5500, 59.3000, 60.0000, 59.7900, 59.2600] Otherwise, :meth:`history` will be called with the default arguments returning a year's worth of data:: sage: finance.Stock('vmw').open() # random; optional -- internet # known bug [52.1100, 60.9900, 59.0000, 56.0500, 57.2500, ... 83.0500, 85.4900, 84.9000, 82.0000, 81.2500] """ from .time_series import TimeSeries if len(args) != 0: return TimeSeries([x.open for x in self.history(*args, **kwds)]) try: return TimeSeries([x.open for x in self.__historical]) except AttributeError: pass return TimeSeries([x.open for x in self.history(*args, **kwds)]) def close(self, *args, **kwds): r""" Return the time series of all historical closing prices for this stock. If no arguments are given, will return last acquired historical data. Otherwise, data will be gotten from Google Finance. INPUT: - ``startdate`` -- string, (default: ``'Jan+1,+1900'``) - ``enddate`` -- string, (default: current date) - ``histperiod`` -- string, (``'daily'`` or ``'weekly'``) OUTPUT: A time series -- close price data. EXAMPLES: You can directly obtain close data as so:: sage: finance.Stock('vmw').close(startdate='Jan+1,+2008', enddate='Feb+1,+2008') # optional -- internet # known bug [84.6000, 83.9500, 80.4900, 72.9900, ... 83.0000, 54.8700, 56.4200, 56.6700, 57.8500] Or, you can initialize stock data first and then extract the Close data:: sage: c = finance.Stock('vmw') # optional -- internet # known bug sage: c.history(startdate='Feb+1,+2008', enddate='Mar+1,+2008')[:5] # optional -- internet # known bug [ 1-Feb-08 56.98 58.14 55.06 57.85 2490481, 4-Feb-08 58.00 60.47 56.91 58.05 1840709, 5-Feb-08 57.60 59.30 57.17 59.30 1712179, 6-Feb-08 60.32 62.00 59.50 61.52 2211775, 7-Feb-08 60.50 62.75 59.56 60.80 1521651 ] sage: c.close() # optional -- internet # known bug [57.8500, 58.0500, 59.3000, 61.5200, ... 58.2900, 60.1800, 59.8600, 59.9500, 58.6700] Otherwise, :meth:`history` will be called with the default arguments returning a year's worth of data:: sage: finance.Stock('vmw').close() # random; optional -- internet # known bug [57.7100, 56.9900, 55.5500, 57.3300, 65.9900 ... 84.9900, 84.6000, 83.9500, 80.4900, 72.9900] """ from .time_series import TimeSeries if args: return TimeSeries([x.close for x in self.history(*args, **kwds)]) try: return TimeSeries([x.close for x in self.__historical]) except AttributeError: pass return TimeSeries([x.close for x in self.history(*args, **kwds)]) def load_from_file(self, file): r""" Load historical data from a local csv formatted data file. Note that no symbol data is included in Google Finance's csv data. The csv file must be formatted in the following way, just as on Google Finance:: Timestamp,Open,High,Low,Close,Volume INPUT: - ``file`` -- local file with Google Finance formatted OHLC data. OUTPUT: A sequence -- OHLC data. EXAMPLES: Suppose you have a file in your home directory containing Apple stock OHLC data, such as that from Google Finance, called ``AAPL-minutely.csv``. One can load this information into a Stock object like so. Note that the path must be explicit:: sage: filename = tmp_filename(ext='.csv') sage: with open(filename, 'w') as fobj: ....: _ = fobj.write("Date,Open,High,Low,Close,Volume\n1212405780,187.80,187.80,187.80,187.80,100\n1212407640,187.75,188.00,187.75,188.00,2000\n1212407700,188.00,188.00,188.00,188.00,1000\n1212408000,188.00,188.11,188.00,188.00,2877\n1212408060,188.00,188.00,188.00,188.00,687") sage: finance.Stock('aapl').load_from_file(filename)[:5] ... 1212408060 188.00 188.00 188.00 188.00 687, 1212408000 188.00 188.11 188.00 188.00 2877, 1212407700 188.00 188.00 188.00 188.00 1000, 1212407640 187.75 188.00 187.75 188.00 2000, 1212405780 187.80 187.80 187.80 187.80 100 ] Note that since the source file doesn't contain information on which equity the information comes from, the symbol designated at initialization of Stock need not match the source of the data. For example, we can initialize a Stock object with the symbol ``'goog'``, but load data from ``'aapl'`` stock prices:: sage: finance.Stock('goog').load_from_file(filename)[:5] [ 1212408060 188.00 188.00 188.00 188.00 687, 1212408000 188.00 188.11 188.00 188.00 2877, 1212407700 188.00 188.00 188.00 188.00 1000, 1212407640 187.75 188.00 187.75 188.00 2000, 1212405780 187.80 187.80 187.80 187.80 100 ] """ with open(file) as file_obj: R = file_obj.read() self.__historical = self._load_from_csv(R) return self.__historical def _load_from_csv(self, R): r""" EXAMPLES: This indirectly tests ``_load_from_csv()``:: sage: filename = tmp_filename(ext='.csv') sage: with open(filename,'w') as fobj: ....: _ = fobj.write("Date,Open,High,Low,Close,Volume\n1212405780,187.80,187.80,187.80,187.80,100\n1212407640,187.75,188.00,187.75,188.00,2000\n1212407700,188.00,188.00,188.00,188.00,1000\n1212408000,188.00,188.11,188.00,188.00,2877\n1212408060,188.00,188.00,188.00,188.00,687") sage: finance.Stock('aapl').load_from_file(filename) [ 1212408060 188.00 188.00 188.00 188.00 687, 1212408000 188.00 188.11 188.00 188.00 2877, 1212407700 188.00 188.00 188.00 188.00 1000, 1212407640 187.75 188.00 187.75 188.00 2000, 1212405780 187.80 187.80 187.80 187.80 100 ] """ R = R.splitlines() hist_data = [] for x in reversed(R[1:]): try: timestamp, opn, high, low, close, volume = x.split(',') ohlc = OHLC(timestamp, opn, high, low, close, volume) hist_data.append(ohlc) except ValueError: pass hist_data = Sequence(hist_data,cr=True,universe=lambda x:x, immutable=True) return hist_data def _get_data(self, exchange, startdate, enddate, histperiod='daily'): """ This function is used internally. EXAMPLES: This indirectly tests the use of ``_get_data()``:: sage: finance.Stock('aapl').history(startdate='Jan+1,+1990',enddate='Jan+1,+1991')[:2] # optional -- internet # known bug [ 2-Jan-90 0.00 1.34 1.25 1.33 45799600, 3-Jan-90 0.00 1.36 1.34 1.34 51998800 ] TESTS:: sage: finance.Stock('whatever').history() # optional -- internet # known bug Traceback (most recent call last): ... RuntimeError: Google reported a wrong request (did you specify a cid?) """ symbol = self.symbol cid = self.cid if cid == '': url = 'http://finance.google.com/finance/historical?q=%s%s&startdate=%s&enddate=%s&histperiod=%s&output=csv' % (exchange, symbol.upper(), startdate, enddate, histperiod) else: url = 'http://finance.google.com/finance/historical?cid=%s&startdate=%s&enddate=%s&histperiod=%s&output=csv' % (cid, startdate, enddate, histperiod) data = urlopen(url).read() if "Bad Request" in data or "The requested URL was not found on this server." in data: raise RuntimeError("Google reported a wrong request (did you specify a cid?)") return data
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/finance/stock.py
0.894306
0.561515
stock.py
pypi
from sage.monoids.string_monoid import BinaryStrings from sage.arith.all import is_prime, lcm, primes, random_prime from sage.rings.integer import Integer from sage.rings.finite_rings.integer_mod import Mod as mod from sage.misc.lazy_import import lazy_import lazy_import('sage.arith.misc', ('carmichael_lambda'), deprecation=34719) def ascii_integer(B): r""" Return the ASCII integer corresponding to the binary string ``B``. INPUT: - ``B`` -- a non-empty binary string or a non-empty list of bits. The number of bits in ``B`` must be 8. OUTPUT: - The ASCII integer corresponding to the 8-bit block ``B``. EXAMPLES: The ASCII integers of some binary strings:: sage: from sage.crypto.util import ascii_integer sage: bin = BinaryStrings() sage: B = bin.encoding("A"); B 01000001 sage: ascii_integer(B) 65 sage: B = bin.encoding("C"); list(B) [0, 1, 0, 0, 0, 0, 1, 1] sage: ascii_integer(list(B)) 67 sage: ascii_integer("01000100") 68 sage: ascii_integer([0, 1, 0, 0, 0, 1, 0, 1]) 69 TESTS: The input ``B`` must be a non-empty string or a non-empty list of bits:: sage: from sage.crypto.util import ascii_integer sage: ascii_integer("") Traceback (most recent call last): ... ValueError: B must consist of 8 bits. sage: ascii_integer([]) Traceback (most recent call last): ... ValueError: B must consist of 8 bits. The input ``B`` must be an 8-bit string or a list of 8 bits:: sage: from sage.crypto.util import ascii_integer sage: ascii_integer("101") Traceback (most recent call last): ... ValueError: B must consist of 8 bits. sage: ascii_integer([1, 0, 1, 1]) Traceback (most recent call last): ... ValueError: B must consist of 8 bits. """ if len(B) != 8: raise ValueError("B must consist of 8 bits.") L = [int(str(x)) for x in list(B)] return sum([L[7], L[6]*2, L[5]*4, L[4]*8, L[3]*16, L[2]*32, L[1]*64, L[0]*128]) def ascii_to_bin(A): r""" Return the binary representation of the ASCII string ``A``. INPUT: - ``A`` -- a string or list of ASCII characters. OUTPUT: - The binary representation of ``A``. ALGORITHM: Let `A = a_0 a_1 \cdots a_{n-1}` be an ASCII string, where each `a_i` is an ASCII character. Let `c_i` be the ASCII integer corresponding to `a_i` and let `b_i` be the binary representation of `c_i`. The binary representation `B` of `A` is `B = b_0 b_1 \cdots b_{n-1}`. EXAMPLES: The binary representation of some ASCII strings:: sage: from sage.crypto.util import ascii_to_bin sage: ascii_to_bin("A") 01000001 sage: ascii_to_bin("Abc123") 010000010110001001100011001100010011001000110011 The empty string is different from the string with one space character. For the empty string and the empty list, this function returns the same result:: sage: from sage.crypto.util import ascii_to_bin sage: ascii_to_bin("") <BLANKLINE> sage: ascii_to_bin(" ") 00100000 sage: ascii_to_bin([]) <BLANKLINE> This function also accepts a list of ASCII characters. You can also pass in a list of strings:: sage: from sage.crypto.util import ascii_to_bin sage: ascii_to_bin(["A", "b", "c", "1", "2", "3"]) 010000010110001001100011001100010011001000110011 sage: ascii_to_bin(["A", "bc", "1", "23"]) 010000010110001001100011001100010011001000110011 TESTS: For a list of ASCII characters or strings, do not mix characters or strings with integers:: sage: from sage.crypto.util import ascii_to_bin sage: ascii_to_bin(["A", "b", "c", 1, 2, 3]) Traceback (most recent call last): ... TypeError: sequence item 3: expected str..., sage.rings.integer.Integer found sage: ascii_to_bin(["Abc", 1, 2, 3]) Traceback (most recent call last): ... TypeError: sequence item 1: expected str..., sage.rings.integer.Integer found """ bin = BinaryStrings() return bin.encoding("".join(list(A))) def bin_to_ascii(B): r""" Return the ASCII representation of the binary string ``B``. INPUT: - ``B`` -- a non-empty binary string or a non-empty list of bits. The number of bits in ``B`` must be a multiple of 8. OUTPUT: - The ASCII string corresponding to ``B``. ALGORITHM: Consider a block of bits `B = b_0 b_1 \cdots b_{n-1}` where each sub-block `b_i` is a binary string of length 8. Then the total number of bits is a multiple of 8 and is given by `8n`. Let `c_i` be the integer representation of `b_i`. We can consider `c_i` as the integer representation of an ASCII character. Then the ASCII representation `A` of `B` is `A = a_0 a_1 \cdots a_{n-1}`. EXAMPLES: Convert some ASCII strings to their binary representations and recover the ASCII strings from the binary representations:: sage: from sage.crypto.util import ascii_to_bin sage: from sage.crypto.util import bin_to_ascii sage: A = "Abc" sage: B = ascii_to_bin(A); B 010000010110001001100011 sage: bin_to_ascii(B) 'Abc' sage: bin_to_ascii(B) == A True :: sage: A = "123 \" #" sage: B = ascii_to_bin(A); B 00110001001100100011001100100000001000100010000000100011 sage: bin_to_ascii(B) '123 " #' sage: bin_to_ascii(B) == A True This function also accepts strings and lists of bits:: sage: from sage.crypto.util import bin_to_ascii sage: bin_to_ascii("010000010110001001100011") 'Abc' sage: bin_to_ascii([0, 1, 0, 0, 0, 0, 0, 1]) 'A' TESTS: The number of bits in ``B`` must be non-empty and a multiple of 8:: sage: from sage.crypto.util import bin_to_ascii sage: bin_to_ascii("") Traceback (most recent call last): ... ValueError: B must be a non-empty binary string. sage: bin_to_ascii([]) Traceback (most recent call last): ... ValueError: B must be a non-empty binary string. sage: bin_to_ascii(" ") Traceback (most recent call last): ... ValueError: The number of bits in B must be a multiple of 8. sage: bin_to_ascii("101") Traceback (most recent call last): ... ValueError: The number of bits in B must be a multiple of 8. sage: bin_to_ascii([1, 0, 1]) Traceback (most recent call last): ... ValueError: The number of bits in B must be a multiple of 8. """ # sanity checks n = len(B) if n == 0: raise ValueError("B must be a non-empty binary string.") if mod(n, 8) != 0: raise ValueError("The number of bits in B must be a multiple of 8.") # perform conversion to ASCII string b = [int(str(x)) for x in list(B)] A = [] # the number of 8-bit blocks k = n // 8 for i in range(k): # Convert from 8-bit string to ASCII integer. Then convert the # ASCII integer to the corresponding ASCII character. A.append(chr(ascii_integer(b[8*i: 8*(i+1)]))) return "".join(A) def has_blum_prime(lbound, ubound): r""" Determine whether or not there is a Blum prime within the specified closed interval. INPUT: - ``lbound`` -- positive integer; the lower bound on how small a Blum prime can be. The lower bound must be distinct from the upper bound. - ``ubound`` -- positive integer; the upper bound on how large a Blum prime can be. The lower bound must be distinct from the upper bound. OUTPUT: - ``True`` if there is a Blum prime ``p`` such that ``lbound <= p <= ubound``. ``False`` otherwise. ALGORITHM: Let `L` and `U` be distinct positive integers. Let `P` be the set of all odd primes `p` such that `L \leq p \leq U`. Our main focus is on Blum primes, i.e. odd primes that are congruent to 3 modulo 4, so we assume that the lower bound `L > 2`. The closed interval `[L, U]` has a Blum prime if and only if the set `P` has a Blum prime. EXAMPLES: Testing for the presence of Blum primes within some closed intervals. The interval `[4, 100]` has a Blum prime, the smallest such prime being 7. The interval `[24, 28]` has no primes, hence no Blum primes. :: sage: from sage.crypto.util import has_blum_prime sage: from sage.crypto.util import is_blum_prime sage: has_blum_prime(4, 100) True sage: for n in range(4, 100): ....: if is_blum_prime(n): ....: print(n) ....: break 7 sage: has_blum_prime(24, 28) False TESTS: Both the lower and upper bounds must be greater than 2:: sage: from sage.crypto.util import has_blum_prime sage: has_blum_prime(2, 3) Traceback (most recent call last): ... ValueError: Both the lower and upper bounds must be > 2. sage: has_blum_prime(3, 2) Traceback (most recent call last): ... ValueError: Both the lower and upper bounds must be > 2. sage: has_blum_prime(2, 2) Traceback (most recent call last): ... ValueError: Both the lower and upper bounds must be > 2. The lower and upper bounds must be distinct from each other:: sage: has_blum_prime(3, 3) Traceback (most recent call last): ... ValueError: The lower and upper bounds must be distinct. The lower bound must be less than the upper bound:: sage: has_blum_prime(4, 3) Traceback (most recent call last): ... ValueError: The lower bound must be less than the upper bound. """ # sanity checks if (lbound < 3) or (ubound < 3): raise ValueError("Both the lower and upper bounds must be > 2.") if lbound == ubound: raise ValueError("The lower and upper bounds must be distinct.") if lbound > ubound: raise ValueError("The lower bound must be less than the upper bound.") # now test for presence of a Blum prime for p in primes(lbound, ubound + 1): if mod(p, 4).lift() == 3: return True return False def is_blum_prime(n): r""" Determine whether or not ``n`` is a Blum prime. INPUT: - ``n`` a positive prime. OUTPUT: - ``True`` if ``n`` is a Blum prime; ``False`` otherwise. Let `n` be a positive prime. Then `n` is a Blum prime if `n` is congruent to 3 modulo 4, i.e. `n \equiv 3 \pmod{4}`. EXAMPLES: Testing some integers to see if they are Blum primes:: sage: from sage.crypto.util import is_blum_prime sage: from sage.crypto.util import random_blum_prime sage: is_blum_prime(101) False sage: is_blum_prime(7) True sage: p = random_blum_prime(10**3, 10**5) sage: is_blum_prime(p) True """ if n < 0: return False if is_prime(n): if mod(n, 4).lift() == 3: return True else: return False else: return False def least_significant_bits(n, k): r""" Return the ``k`` least significant bits of ``n``. INPUT: - ``n`` -- an integer. - ``k`` -- a positive integer. OUTPUT: - The ``k`` least significant bits of the integer ``n``. If ``k=1``, then return the parity bit of the integer ``n``. Let `b` be the binary representation of ``n``, where `m` is the length of the binary string `b`. If `k \geq m`, then return the binary representation of ``n``. EXAMPLES: Obtain the parity bits of some integers:: sage: from sage.crypto.util import least_significant_bits sage: least_significant_bits(0, 1) [0] sage: least_significant_bits(2, 1) [0] sage: least_significant_bits(3, 1) [1] sage: least_significant_bits(-2, 1) [0] sage: least_significant_bits(-3, 1) [1] Obtain the 4 least significant bits of some integers:: sage: least_significant_bits(101, 4) [0, 1, 0, 1] sage: least_significant_bits(-101, 4) [0, 1, 0, 1] sage: least_significant_bits(124, 4) [1, 1, 0, 0] sage: least_significant_bits(-124, 4) [1, 1, 0, 0] The binary representation of 123:: sage: n = 123; b = n.binary(); b '1111011' sage: least_significant_bits(n, len(b)) [1, 1, 1, 1, 0, 1, 1] """ return [int(_) for _ in list(n.binary()[-k:])] def random_blum_prime(lbound, ubound, ntries=100): r""" A random Blum prime within the specified bounds. Let `p` be a positive prime. Then `p` is a Blum prime if `p` is congruent to 3 modulo 4, i.e. `p \equiv 3 \pmod{4}`. INPUT: - ``lbound`` -- positive integer; the lower bound on how small a random Blum prime `p` can be. So we have ``0 < lbound <= p <= ubound``. The lower bound must be distinct from the upper bound. - ``ubound`` -- positive integer; the upper bound on how large a random Blum prime `p` can be. So we have ``0 < lbound <= p <= ubound``. The lower bound must be distinct from the upper bound. - ``ntries`` -- (default: ``100``) the number of attempts to generate a random Blum prime. If ``ntries`` is a positive integer, then perform that many attempts at generating a random Blum prime. This might or might not result in a Blum prime. OUTPUT: - A random Blum prime within the specified lower and upper bounds. .. NOTE:: Beware that there might not be any primes between the lower and upper bounds. So make sure that these two bounds are "sufficiently" far apart from each other for there to be primes congruent to 3 modulo 4. In particular, there should be at least two distinct Blum primes within the specified bounds. EXAMPLES: Choose a random prime and check that it is a Blum prime:: sage: from sage.crypto.util import random_blum_prime sage: p = random_blum_prime(10**4, 10**5) sage: is_prime(p) True sage: mod(p, 4) == 3 True TESTS: Make sure that there is at least one Blum prime between the lower and upper bounds. In the following example, we have ``lbound=24`` and ``ubound=30`` with 29 being the only prime within those bounds. But 29 is not a Blum prime. :: sage: from sage.crypto.util import random_blum_prime sage: random_blum_prime(24, 30, ntries=10) Traceback (most recent call last): ... ValueError: No Blum primes within the specified closed interval. sage: random_blum_prime(24, 28) Traceback (most recent call last): ... ValueError: No Blum primes within the specified closed interval. """ # sanity check if not has_blum_prime(lbound, ubound): raise ValueError("No Blum primes within the specified closed interval.") # Now we know that there is a Blum prime within the closed interval # [lbound, ubound]. Pick one such prime at random. p = random_prime(ubound, lbound=lbound, proof=True) n = 1 while mod(p, 4) != 3: p = random_prime(ubound, lbound=lbound, proof=True) n += 1 if n > ntries: raise ValueError("Maximum number of attempts exceeded.") return p
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/crypto/util.py
0.910361
0.498413
util.py
pypi
from sage.rings.polynomial.polynomial_ring import is_PolynomialRing def gen_lattice(type='modular', n=4, m=8, q=11, seed=None, quotient=None, dual=False, ntl=False, lattice=False): r""" This function generates different types of integral lattice bases of row vectors relevant in cryptography. Randomness can be set either with ``seed``, or by using :func:`sage.misc.randstate.set_random_seed`. INPUT: - ``type`` -- one of the following strings - ``'modular'`` (default) -- A class of lattices for which asymptotic worst-case to average-case connections hold. For more refer to [Aj1996]_. - ``'random'`` -- Special case of modular (n=1). A dense class of lattice used for testing basis reduction algorithms proposed by Goldstein and Mayer [GM2002]_. - ``'ideal'`` -- Special case of modular. Allows for a more compact representation proposed by [LM2006]_. - ``'cyclotomic'`` -- Special case of ideal. Allows for efficient processing proposed by [LM2006]_. - ``n`` -- Determinant size, primal:`det(L) = q^n`, dual:`det(L) = q^{m-n}`. For ideal lattices this is also the degree of the quotient polynomial. - ``m`` -- Lattice dimension, `L \subseteq Z^m`. - ``q`` -- Coefficient size, `q-Z^m \subseteq L`. - ``seed`` -- Randomness seed. - ``quotient`` -- For the type ideal, this determines the quotient polynomial. Ignored for all other types. - ``dual`` -- Set this flag if you want a basis for `q-dual(L)`, for example for Regev's LWE bases [Reg2005]_. - ``ntl`` -- Set this flag if you want the lattice basis in NTL readable format. - ``lattice`` -- Set this flag if you want a :class:`FreeModule_submodule_with_basis_integer` object instead of an integer matrix representing the basis. OUTPUT: ``B`` a unique size-reduced triangular (primal: lower_left, dual: lower_right) basis of row vectors for the lattice in question. EXAMPLES: Modular basis:: sage: sage.crypto.gen_lattice(m=10, seed=42) [11 0 0 0 0 0 0 0 0 0] [ 0 11 0 0 0 0 0 0 0 0] [ 0 0 11 0 0 0 0 0 0 0] [ 0 0 0 11 0 0 0 0 0 0] [ 2 4 3 5 1 0 0 0 0 0] [ 1 -5 -4 2 0 1 0 0 0 0] [-4 3 -1 1 0 0 1 0 0 0] [-2 -3 -4 -1 0 0 0 1 0 0] [-5 -5 3 3 0 0 0 0 1 0] [-4 -3 2 -5 0 0 0 0 0 1] Random basis:: sage: sage.crypto.gen_lattice(type='random', n=1, m=10, q=11^4, seed=42) [14641 0 0 0 0 0 0 0 0 0] [ 431 1 0 0 0 0 0 0 0 0] [-4792 0 1 0 0 0 0 0 0 0] [ 1015 0 0 1 0 0 0 0 0 0] [-3086 0 0 0 1 0 0 0 0 0] [-5378 0 0 0 0 1 0 0 0 0] [ 4769 0 0 0 0 0 1 0 0 0] [-1159 0 0 0 0 0 0 1 0 0] [ 3082 0 0 0 0 0 0 0 1 0] [-4580 0 0 0 0 0 0 0 0 1] Ideal bases with quotient x^n-1, m=2*n are NTRU bases:: sage: sage.crypto.gen_lattice(type='ideal', seed=42, quotient=x^4-1) [11 0 0 0 0 0 0 0] [ 0 11 0 0 0 0 0 0] [ 0 0 11 0 0 0 0 0] [ 0 0 0 11 0 0 0 0] [-2 -3 -3 4 1 0 0 0] [ 4 -2 -3 -3 0 1 0 0] [-3 4 -2 -3 0 0 1 0] [-3 -3 4 -2 0 0 0 1] Ideal bases also work with polynomials:: sage: R.<t> = PolynomialRing(ZZ) sage: sage.crypto.gen_lattice(type='ideal', seed=1234, quotient=t^4-1) [11 0 0 0 0 0 0 0] [ 0 11 0 0 0 0 0 0] [ 0 0 11 0 0 0 0 0] [ 0 0 0 11 0 0 0 0] [ 1 4 -3 3 1 0 0 0] [ 3 1 4 -3 0 1 0 0] [-3 3 1 4 0 0 1 0] [ 4 -3 3 1 0 0 0 1] Cyclotomic bases with n=2^k are SWIFFT bases:: sage: sage.crypto.gen_lattice(type='cyclotomic', seed=42) [11 0 0 0 0 0 0 0] [ 0 11 0 0 0 0 0 0] [ 0 0 11 0 0 0 0 0] [ 0 0 0 11 0 0 0 0] [-2 -3 -3 4 1 0 0 0] [-4 -2 -3 -3 0 1 0 0] [ 3 -4 -2 -3 0 0 1 0] [ 3 3 -4 -2 0 0 0 1] Dual modular bases are related to Regev's famous public-key encryption [Reg2005]_:: sage: sage.crypto.gen_lattice(type='modular', m=10, seed=42, dual=True) [ 0 0 0 0 0 0 0 0 0 11] [ 0 0 0 0 0 0 0 0 11 0] [ 0 0 0 0 0 0 0 11 0 0] [ 0 0 0 0 0 0 11 0 0 0] [ 0 0 0 0 0 11 0 0 0 0] [ 0 0 0 0 11 0 0 0 0 0] [ 0 0 0 1 -5 -2 -1 1 -3 5] [ 0 0 1 0 -3 4 1 4 -3 -2] [ 0 1 0 0 -4 5 -3 3 5 3] [ 1 0 0 0 -2 -1 4 2 5 4] Relation of primal and dual bases:: sage: B_primal=sage.crypto.gen_lattice(m=10, q=11, seed=42) sage: B_dual=sage.crypto.gen_lattice(m=10, q=11, seed=42, dual=True) sage: B_dual_alt=transpose(11*B_primal.inverse()).change_ring(ZZ) sage: B_dual_alt.hermite_form() == B_dual.hermite_form() True TESTS: Test some bad quotient polynomials:: sage: sage.crypto.gen_lattice(type='ideal', seed=1234, quotient=cos(x)) Traceback (most recent call last): ... TypeError: self must be a numeric expression sage: sage.crypto.gen_lattice(type='ideal', seed=1234, quotient=x^23-1) Traceback (most recent call last): ... ValueError: ideal basis requires n = quotient.degree() sage: R.<u,v> = ZZ[] sage: sage.crypto.gen_lattice(type='ideal', seed=1234, quotient=u+v) Traceback (most recent call last): ... TypeError: quotient should be a univariate polynomial We are testing output format choices:: sage: sage.crypto.gen_lattice(m=10, q=11, seed=42) [11 0 0 0 0 0 0 0 0 0] [ 0 11 0 0 0 0 0 0 0 0] [ 0 0 11 0 0 0 0 0 0 0] [ 0 0 0 11 0 0 0 0 0 0] [ 2 4 3 5 1 0 0 0 0 0] [ 1 -5 -4 2 0 1 0 0 0 0] [-4 3 -1 1 0 0 1 0 0 0] [-2 -3 -4 -1 0 0 0 1 0 0] [-5 -5 3 3 0 0 0 0 1 0] [-4 -3 2 -5 0 0 0 0 0 1] sage: sage.crypto.gen_lattice(m=10, q=11, seed=42, ntl=True) [ [11 0 0 0 0 0 0 0 0 0] [0 11 0 0 0 0 0 0 0 0] [0 0 11 0 0 0 0 0 0 0] [0 0 0 11 0 0 0 0 0 0] [2 4 3 5 1 0 0 0 0 0] [1 -5 -4 2 0 1 0 0 0 0] [-4 3 -1 1 0 0 1 0 0 0] [-2 -3 -4 -1 0 0 0 1 0 0] [-5 -5 3 3 0 0 0 0 1 0] [-4 -3 2 -5 0 0 0 0 0 1] ] sage: sage.crypto.gen_lattice(m=10, q=11, seed=42, lattice=True) Free module of degree 10 and rank 10 over Integer Ring User basis matrix: [ 0 0 1 1 0 -1 -1 -1 1 0] [-1 1 0 1 0 1 1 0 1 1] [-1 0 0 0 -1 1 1 -2 0 0] [-1 -1 0 1 1 0 0 1 1 -1] [ 1 0 -1 0 0 0 -2 -2 0 0] [ 2 -1 0 0 1 0 1 0 0 -1] [-1 1 -1 0 1 -1 1 0 -1 -2] [ 0 0 -1 3 0 0 0 -1 -1 -1] [ 0 -1 0 -1 2 0 -1 0 0 2] [ 0 1 1 0 1 1 -2 1 -1 -2] """ from sage.rings.finite_rings.integer_mod_ring import IntegerModRing from sage.matrix.constructor import identity_matrix, block_matrix from sage.matrix.matrix_space import MatrixSpace from sage.rings.integer_ring import IntegerRing if seed is not None: from sage.misc.randstate import set_random_seed set_random_seed(seed) if type == 'random': if n != 1: raise ValueError('random bases require n = 1') ZZ = IntegerRing() ZZ_q = IntegerModRing(q) A = identity_matrix(ZZ_q, n) if type == 'random' or type == 'modular': R = MatrixSpace(ZZ_q, m-n, n) A = A.stack(R.random_element()) elif type == 'ideal': if quotient is None: raise ValueError('ideal bases require a quotient polynomial') try: quotient = quotient.change_ring(ZZ_q) except (AttributeError, TypeError): quotient = quotient.polynomial(base_ring=ZZ_q) P = quotient.parent() # P should be a univariate polynomial ring over ZZ_q if not is_PolynomialRing(P): raise TypeError("quotient should be a univariate polynomial") assert P.base_ring() is ZZ_q if quotient.degree() != n: raise ValueError('ideal basis requires n = quotient.degree()') R = P.quotient(quotient) for i in range(m//n): A = A.stack(R.random_element().matrix()) elif type == 'cyclotomic': from sage.arith.all import euler_phi from sage.misc.functional import cyclotomic_polynomial # we assume that n+1 <= min( euler_phi^{-1}(n) ) <= 2*n found = False for k in range(2*n,n,-1): if euler_phi(k) == n: found = True break if not found: raise ValueError("cyclotomic bases require that n " "is an image of Euler's totient function") R = ZZ_q['x'].quotient(cyclotomic_polynomial(k, 'x'), 'x') for i in range(m//n): A = A.stack(R.random_element().matrix()) # switch from representatives 0,...,(q-1) to (1-q)/2,....,(q-1)/2 def minrep(a): if abs(a-q) < abs(a): return a-q else: return a A_prime = A[n:m].lift().apply_map(minrep) if not dual: B = block_matrix([[ZZ(q), ZZ.zero()], [A_prime, ZZ.one()] ], subdivide=False) else: B = block_matrix([[ZZ.one(), -A_prime.transpose()], [ZZ.zero(), ZZ(q)]], subdivide=False) for i in range(m//2): B.swap_rows(i,m-i-1) if ntl and lattice: raise ValueError("Cannot specify ntl=True and lattice=True " "at the same time") if ntl: return B._ntl_() elif lattice: from sage.modules.free_module_integer import IntegerLattice return IntegerLattice(B) else: return B
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/crypto/lattice.py
0.917718
0.582164
lattice.py
pypi
from sage.functions.log import log from sage.functions.other import floor, ceil from sage.misc.functional import sqrt from sage.misc.functional import cyclotomic_polynomial, round from sage.misc.randstate import set_random_seed from sage.misc.prandom import randint from sage.modules.free_module import FreeModule from sage.modules.free_module_element import random_vector, vector from sage.numerical.optimize import find_root from sage.rings.all import ZZ, IntegerModRing, RR from sage.arith.all import next_prime, euler_phi from sage.structure.element import parent from sage.structure.sage_object import SageObject from sage.symbolic.constants import pi from sage.symbolic.ring import SR from sage.stats.distributions.discrete_gaussian_integer import DiscreteGaussianDistributionIntegerSampler from sage.stats.distributions.discrete_gaussian_polynomial import DiscreteGaussianDistributionPolynomialSampler class UniformSampler(SageObject): """ Uniform sampling in a range of integers. EXAMPLES:: sage: from sage.crypto.lwe import UniformSampler sage: sampler = UniformSampler(-2, 2); sampler UniformSampler(-2, 2) sage: sampler() in range(-2, 3) True .. automethod:: __init__ .. automethod:: __call__ """ def __init__(self, lower_bound, upper_bound): """ Construct a uniform sampler with bounds ``lower_bound`` and ``upper_bound`` (both endpoints inclusive). INPUT: - ``lower_bound`` - integer - ``upper_bound`` - integer EXAMPLES:: sage: from sage.crypto.lwe import UniformSampler sage: UniformSampler(-2, 2) UniformSampler(-2, 2) """ if lower_bound > upper_bound: raise TypeError("lower bound must be <= upper bound.") self.lower_bound = ZZ(lower_bound) self.upper_bound = ZZ(upper_bound) def __call__(self): """ Return a new sample. EXAMPLES:: sage: from sage.crypto.lwe import UniformSampler sage: sampler = UniformSampler(-12, 12) sage: sampler() in range(-12, 13) True """ return randint(self.lower_bound, self.upper_bound) def _repr_(self): """ EXAMPLES:: sage: from sage.crypto.lwe import UniformSampler sage: UniformSampler(-2, 2) UniformSampler(-2, 2) """ return "UniformSampler(%d, %d)"%(self.lower_bound, self.upper_bound) class UniformPolynomialSampler(SageObject): """ Uniform sampler for polynomials. EXAMPLES:: sage: from sage.crypto.lwe import UniformPolynomialSampler sage: UniformPolynomialSampler(ZZ['x'], 8, -2, 2)().parent() Univariate Polynomial Ring in x over Integer Ring .. automethod:: __init__ .. automethod:: __call__ """ def __init__(self, P, n, lower_bound, upper_bound): """ Construct a sampler for univariate polynomials of degree ``n-1`` where coefficients are drawn uniformly at random between ``lower_bound`` and ``upper_bound`` (both endpoints inclusive). INPUT: - ``P`` - a univariate polynomial ring over the Integers - ``n`` - number of coefficients to be sampled - ``lower_bound`` - integer - ``upper_bound`` - integer EXAMPLES:: sage: from sage.crypto.lwe import UniformPolynomialSampler sage: UniformPolynomialSampler(ZZ['x'], 10, -10, 10) UniformPolynomialSampler(10, -10, 10) """ self.n = ZZ(n) self.P = P if lower_bound > upper_bound: raise TypeError("lower bound must be <= upper bound.") self.lower_bound = ZZ(lower_bound) self.upper_bound = ZZ(upper_bound) self.D = UniformSampler(self.lower_bound, self.upper_bound) def __call__(self): """ Return a new sample. EXAMPLES:: sage: from sage.crypto.lwe import UniformPolynomialSampler sage: sampler = UniformPolynomialSampler(ZZ['x'], 8, -12, 12) sage: sampler().parent() Univariate Polynomial Ring in x over Integer Ring """ coeff = [self.D() for _ in range(self.n)] f = self.P(coeff) return f def _repr_(self): """ EXAMPLES:: sage: from sage.crypto.lwe import UniformPolynomialSampler sage: UniformPolynomialSampler(ZZ['x'], 8, -3, 3) UniformPolynomialSampler(8, -3, 3) """ return "UniformPolynomialSampler(%d, %d, %d)"%(self.n, self.lower_bound, self.upper_bound) class LWE(SageObject): """ Learning with Errors (LWE) oracle. .. automethod:: __init__ .. automethod:: __call__ """ def __init__(self, n, q, D, secret_dist='uniform', m=None): r""" Construct an LWE oracle in dimension ``n`` over a ring of order ``q`` with noise distribution ``D``. INPUT: - ``n`` - dimension (integer > 0) - ``q`` - modulus typically > n (integer > 0) - ``D`` - an error distribution such as an instance of :class:`DiscreteGaussianDistributionIntegerSampler` or :class:`UniformSampler` - ``secret_dist`` - distribution of the secret (default: 'uniform'); one of - "uniform" - secret follows the uniform distribution in `\Zmod{q}` - "noise" - secret follows the noise distribution - ``(lb,ub)`` - the secret is chosen uniformly from ``[lb,...,ub]`` including both endpoints - ``m`` - number of allowed samples or ``None`` if no such limit exists (default: ``None``) EXAMPLES: First, we construct a noise distribution with standard deviation 3.0:: sage: from sage.stats.distributions.discrete_gaussian_integer import DiscreteGaussianDistributionIntegerSampler sage: D = DiscreteGaussianDistributionIntegerSampler(3.0) Next, we construct our oracle:: sage: from sage.crypto.lwe import LWE sage: lwe = LWE(n=20, q=next_prime(400), D=D); lwe LWE(20, 401, Discrete Gaussian sampler over the Integers with sigma = 3.000000 and c = 0.000000, 'uniform', None) and sample 1000 samples:: sage: L = [] sage: def add_samples(): ....: global L ....: L += [lwe() for _ in range(1000)] sage: add_samples() To test the oracle, we use the internal secret to evaluate the samples in the secret:: sage: S = lambda : [ZZ(a.dot_product(lwe._LWE__s) - c) for (a,c) in L] However, while Sage represents finite field elements between 0 and q-1 we rely on a balanced representation of those elements here. Hence, we fix the representation and recover the correct standard deviation of the noise:: sage: from numpy import std sage: while abs(std([e if e <= 200 else e-401 for e in S()]) - 3.0) > 0.01: ....: add_samples() If ``m`` is not ``None`` the number of available samples is restricted:: sage: from sage.crypto.lwe import LWE sage: lwe = LWE(n=20, q=next_prime(400), D=D, m=30) sage: _ = [lwe() for _ in range(30)] sage: lwe() # 31 Traceback (most recent call last): ... IndexError: Number of available samples exhausted. """ self.n = ZZ(n) self.m = m self.__i = 0 self.K = IntegerModRing(q) self.FM = FreeModule(self.K, n) self.D = D self.secret_dist = secret_dist if secret_dist == 'uniform': self.__s = random_vector(self.K, self.n) elif secret_dist == 'noise': self.__s = vector(self.K, self.n, [self.D() for _ in range(n)]) else: try: lb, ub = map(ZZ, secret_dist) self.__s = vector(self.K, self.n, [randint(lb,ub) for _ in range(n)]) except (IndexError, TypeError): raise TypeError("Parameter secret_dist=%s not understood."%(secret_dist)) def _repr_(self): """ EXAMPLES:: sage: from sage.stats.distributions.discrete_gaussian_integer import DiscreteGaussianDistributionIntegerSampler sage: from sage.crypto.lwe import LWE sage: D = DiscreteGaussianDistributionIntegerSampler(3.0) sage: lwe = LWE(n=20, q=next_prime(400), D=D); lwe LWE(20, 401, Discrete Gaussian sampler over the Integers with sigma = 3.000000 and c = 0.000000, 'uniform', None) sage: lwe = LWE(n=20, q=next_prime(400), D=D, secret_dist=(-3, 3)); lwe LWE(20, 401, Discrete Gaussian sampler over the Integers with sigma = 3.000000 and c = 0.000000, (-3, 3), None) """ if isinstance(self.secret_dist, str): return "LWE(%d, %d, %s, '%s', %s)"%(self.n,self.K.order(),self.D,self.secret_dist, self.m) else: return "LWE(%d, %d, %s, %s, %s)"%(self.n,self.K.order(),self.D,self.secret_dist, self.m) def __call__(self): """ EXAMPLES:: sage: from sage.crypto.lwe import DiscreteGaussianDistributionIntegerSampler, LWE sage: LWE(10, 401, DiscreteGaussianDistributionIntegerSampler(3))()[0].parent() Vector space of dimension 10 over Ring of integers modulo 401 sage: LWE(10, 401, DiscreteGaussianDistributionIntegerSampler(3))()[1].parent() Ring of integers modulo 401 """ if self.m is not None: if self.__i >= self.m: raise IndexError("Number of available samples exhausted.") self.__i+=1 a = self.FM.random_element() return a, a.dot_product(self.__s) + self.K(self.D()) class Regev(LWE): """ LWE oracle with parameters as in [Reg09]_. .. automethod:: __init__ """ def __init__(self, n, secret_dist='uniform', m=None): """ Construct LWE instance parameterised by security parameter ``n`` where the modulus ``q`` and the ``stddev`` of the noise are chosen as in [Reg09]_. INPUT: - ``n`` - security parameter (integer > 0) - ``secret_dist`` - distribution of the secret. See documentation of :class:`LWE` for details (default='uniform') - ``m`` - number of allowed samples or ``None`` if no such limit exists (default: ``None``) EXAMPLES:: sage: from sage.crypto.lwe import Regev sage: Regev(n=20) LWE(20, 401, Discrete Gaussian sampler over the Integers with sigma = 1.915069 and c = 401.000000, 'uniform', None) """ q = ZZ(next_prime(n**2)) s = RR(1/(RR(n).sqrt() * log(n, 2)**2) * q) D = DiscreteGaussianDistributionIntegerSampler(s/sqrt(2*pi.n()), q) LWE.__init__(self, n=n, q=q, D=D, secret_dist=secret_dist, m=m) class LindnerPeikert(LWE): """ LWE oracle with parameters as in [LP2011]_. .. automethod:: __init__ """ def __init__(self, n, delta=0.01, m=None): """ Construct LWE instance parameterised by security parameter ``n`` where the modulus ``q`` and the ``stddev`` of the noise is chosen as in [LP2011]_. INPUT: - ``n`` - security parameter (integer > 0) - ``delta`` - error probability per symbol (default: 0.01) - ``m`` - number of allowed samples or ``None`` in which case ``m=2*n + 128`` as in [LP2011]_ (default: ``None``) EXAMPLES:: sage: from sage.crypto.lwe import LindnerPeikert sage: LindnerPeikert(n=20) LWE(20, 2053, Discrete Gaussian sampler over the Integers with sigma = 3.600954 and c = 0.000000, 'noise', 168) """ if m is None: m = 2*n + 128 # Find c>=1 such that c*exp((1-c**2)/2))**(2*n) == 2**-40 # (c*exp((1-c**2)/2))**(2*n) == 2**-40 # log((c*exp((1-c**2)/2))**(2*n)) == -40*log(2) # (2*n)*log(c*exp((1-c**2)/2)) == -40*log(2) # 2*n*(log(c)+log(exp((1-c**2)/2))) == -40*log(2) # 2*n*(log(c)+(1-c**2)/2) == -40*log(2) # 2*n*log(c)+n*(1-c**2) == -40*log(2) # 2*n*log(c)+n*(1-c**2) + 40*log(2) == 0 c = SR.var('c') c = find_root(2*n*log(c)+n*(1-c**2) + 40*log(2) == 0, 1, 10) # Upper bound on s**2/t s_t_bound = (sqrt(2) * pi / c / sqrt(2*n*log(2/delta))).n() # Interpretation of "choose q just large enough to allow for a Gaussian parameter s>=8" in [LP2011]_ q = next_prime(floor(2**round(log(256 / s_t_bound, 2)))) # Gaussian parameter as defined in [LP2011]_ s = sqrt(s_t_bound*floor(q/4)) # Transform s into stddev stddev = s/sqrt(2*pi.n()) D = DiscreteGaussianDistributionIntegerSampler(stddev) LWE.__init__(self, n=n, q=q, D=D, secret_dist='noise', m=m) class UniformNoiseLWE(LWE): """ LWE oracle with uniform secret with parameters as in [CGW2013]_. .. automethod:: __init__ """ def __init__(self, n, instance='key', m=None): """ Construct LWE instance parameterised by security parameter ``n`` where all other parameters are chosen as in [CGW2013]_. INPUT: - ``n`` - security parameter (integer >= 89) - ``instance`` - one of - "key" - the LWE-instance that hides the secret key is generated - "encrypt" - the LWE-instance that hides the message is generated (default: ``key``) - ``m`` - number of allowed samples or ``None`` in which case ``m`` is chosen as in [CGW2013]_. (default: ``None``) EXAMPLES:: sage: from sage.crypto.lwe import UniformNoiseLWE sage: UniformNoiseLWE(89) LWE(89, 64311834871, UniformSampler(0, 6577), 'noise', 131) sage: UniformNoiseLWE(89, instance='encrypt') LWE(131, 64311834871, UniformSampler(0, 11109), 'noise', 181) """ if n<89: raise TypeError("Parameter too small") n2 = n C = 4/sqrt(2*pi) kk = floor((n2-2*log(n2, 2)**2)/5) n1 = (3*n2-5*kk) // 2 ke = floor((n1-2*log(n1, 2)**2)/5) l = (3*n1-5*ke) // 2 - n2 sk = ceil((C*(n1+n2))**(ZZ(3)/2)) se = ceil((C*(n1+n2+l))**(ZZ(3)/2)) q = next_prime(max(ceil((4*sk)**(ZZ(n1+n2)/n1)), ceil((4*se)**(ZZ(n1+n2+l)/(n2+l))), ceil(4*(n1+n2)*se*sk+4*se+1))) if kk <= 0: raise TypeError("Parameter too small") if instance == 'key': D = UniformSampler(0, sk-1) if m is None: m = n1 LWE.__init__(self, n=n2, q=q, D=D, secret_dist='noise', m=m) elif instance == 'encrypt': D = UniformSampler(0, se-1) if m is None: m = n2+l LWE.__init__(self, n=n1, q=q, D=D, secret_dist='noise', m=m) else: raise TypeError("Parameter instance=%s not understood."%(instance)) class RingLWE(SageObject): """ Ring Learning with Errors oracle. .. automethod:: __init__ .. automethod:: __call__ """ def __init__(self, N, q, D, poly=None, secret_dist='uniform', m=None): """ Construct a Ring-LWE oracle in dimension ``n=phi(N)`` over a ring of order ``q`` with noise distribution ``D``. INPUT: - ``N`` - index of cyclotomic polynomial (integer > 0, must be power of 2) - ``q`` - modulus typically > N (integer > 0) - ``D`` - an error distribution such as an instance of :class:`DiscreteGaussianDistributionPolynomialSampler` or :class:`UniformSampler` - ``poly`` - a polynomial of degree ``phi(N)``. If ``None`` the cyclotomic polynomial used (default: ``None``). - ``secret_dist`` - distribution of the secret. See documentation of :class:`LWE` for details (default='uniform') - ``m`` - number of allowed samples or ``None`` if no such limit exists (default: ``None``) EXAMPLES:: sage: from sage.crypto.lwe import RingLWE sage: from sage.stats.distributions.discrete_gaussian_polynomial import DiscreteGaussianDistributionPolynomialSampler sage: D = DiscreteGaussianDistributionPolynomialSampler(ZZ['x'], n=euler_phi(20), sigma=3.0) sage: RingLWE(N=20, q=next_prime(800), D=D) RingLWE(20, 809, Discrete Gaussian sampler for polynomials of degree < 8 with σ=3.000000 in each component, x^8 - x^6 + x^4 - x^2 + 1, 'uniform', None) """ self.N = ZZ(N) self.n = euler_phi(N) self.m = m self.__i = 0 self.K = IntegerModRing(q) if self.n != D.n: raise ValueError("Noise distribution has dimensions %d != %d"%(D.n, self.n)) self.D = D self.q = q if poly is not None: self.poly = poly else: self.poly = cyclotomic_polynomial(self.N, 'x') self.R_q = self.K['x'].quotient(self.poly, 'x') self.secret_dist = secret_dist if secret_dist == 'uniform': self.__s = self.R_q.random_element() # uniform sampling of secret elif secret_dist == 'noise': self.__s = self.D() else: raise TypeError("Parameter secret_dist=%s not understood."%(secret_dist)) def _repr_(self): """ EXAMPLES:: sage: from sage.crypto.lwe import DiscreteGaussianDistributionPolynomialSampler, RingLWE sage: D = DiscreteGaussianDistributionPolynomialSampler(ZZ['x'], n=8, sigma=3.0) sage: RingLWE(N=16, q=next_prime(400), D=D) RingLWE(16, 401, Discrete Gaussian sampler for polynomials of degree < 8 with σ=3.000000 in each component, x^8 + 1, 'uniform', None) """ if isinstance(self.secret_dist, str): return "RingLWE(%d, %d, %s, %s, '%s', %s)"%(self.N, self.K.order(), self.D, self.poly, self.secret_dist, self.m) else: return "RingLWE(%d, %d, %s, %s, %s, %s)"%(self.N, self.K.order(), self.D, self.poly, self.secret_dist, self.m) def __call__(self): """ EXAMPLES:: sage: from sage.crypto.lwe import DiscreteGaussianDistributionPolynomialSampler, RingLWE sage: N = 16 sage: n = euler_phi(N) sage: D = DiscreteGaussianDistributionPolynomialSampler(ZZ['x'], n, 5) sage: ringlwe = RingLWE(N, 257, D, secret_dist='uniform') sage: ringlwe()[0].parent() Vector space of dimension 8 over Ring of integers modulo 257 sage: ringlwe()[1].parent() Vector space of dimension 8 over Ring of integers modulo 257 """ if self.m is not None: if self.__i >= self.m: raise IndexError("Number of available samples exhausted.") self.__i+=1 a = self.R_q.random_element() return vector(a), vector(a * (self.__s) + self.D()) class RingLindnerPeikert(RingLWE): """ Ring-LWE oracle with parameters as in [LP2011]_. .. automethod:: __init__ """ def __init__(self, N, delta=0.01, m=None): """ Construct a Ring-LWE oracle in dimension ``n=phi(N)`` where the modulus ``q`` and the ``stddev`` of the noise is chosen as in [LP2011]_. INPUT: - ``N`` - index of cyclotomic polynomial (integer > 0, must be power of 2) - ``delta`` - error probability per symbol (default: 0.01) - ``m`` - number of allowed samples or ``None`` in which case ``3*n`` is used (default: ``None``) EXAMPLES:: sage: from sage.crypto.lwe import RingLindnerPeikert sage: RingLindnerPeikert(N=16) RingLWE(16, 1031, Discrete Gaussian sampler for polynomials of degree < 8 with σ=2.803372 in each component, x^8 + 1, 'noise', 24) """ n = euler_phi(N) if m is None: m = 3*n # Find c>=1 such that c*exp((1-c**2)/2))**(2*n) == 2**-40 # i.e c>=1 such that 2*n*log(c)+n*(1-c**2) + 40*log(2) == 0 c = SR.var('c') c = find_root(2*n*log(c)+n*(1-c**2) + 40*log(2) == 0, 1, 10) # Upper bound on s**2/t s_t_bound = (sqrt(2) * pi / c / sqrt(2*n*log(2/delta))).n() # Interpretation of "choose q just large enough to allow for a Gaussian parameter s>=8" in [LP2011]_ q = next_prime(floor(2**round(log(256 / s_t_bound, 2)))) # Gaussian parameter as defined in [LP2011]_ s = sqrt(s_t_bound*floor(q/4)) # Transform s into stddev stddev = s/sqrt(2*pi.n()) D = DiscreteGaussianDistributionPolynomialSampler(ZZ['x'], n, stddev) RingLWE.__init__(self, N=N, q=q, D=D, poly=None, secret_dist='noise', m=m) class RingLWEConverter(SageObject): """ Wrapper callable to convert Ring-LWE oracles into LWE oracles by disregarding the additional structure. .. automethod:: __init__ .. automethod:: __call__ """ def __init__(self, ringlwe): """ INPUT: - ``ringlwe`` - an instance of a :class:`RingLWE` EXAMPLES:: sage: from sage.crypto.lwe import DiscreteGaussianDistributionPolynomialSampler, RingLWE, RingLWEConverter sage: D = DiscreteGaussianDistributionPolynomialSampler(ZZ['x'], euler_phi(16), 5) sage: lwe = RingLWEConverter(RingLWE(16, 257, D, secret_dist='uniform')) sage: set_random_seed(1337) sage: lwe() ((32, 216, 3, 125, 58, 197, 171, 43), ...) """ self.ringlwe = ringlwe self._i = 0 self._ac = None self.n = self.ringlwe.n def __call__(self): """ EXAMPLES:: sage: from sage.crypto.lwe import DiscreteGaussianDistributionPolynomialSampler, RingLWE, RingLWEConverter sage: D = DiscreteGaussianDistributionPolynomialSampler(ZZ['x'], euler_phi(16), 5) sage: lwe = RingLWEConverter(RingLWE(16, 257, D, secret_dist='uniform')) sage: set_random_seed(1337) sage: lwe() ((32, 216, 3, 125, 58, 197, 171, 43), ...) """ R_q = self.ringlwe.R_q if (self._i % self.n) == 0: self._ac = self.ringlwe() a, c = self._ac x = R_q.gen() r = vector((x**(self._i % self.n) * R_q(a.list())).list()), c[self._i % self.n] self._i += 1 return r def _repr_(self): """ EXAMPLES:: sage: from sage.crypto.lwe import DiscreteGaussianDistributionPolynomialSampler, RingLWE, RingLWEConverter sage: D = DiscreteGaussianDistributionPolynomialSampler(ZZ['x'], euler_phi(20), 5) sage: rlwe = RingLWE(20, 257, D) sage: lwe = RingLWEConverter(rlwe) sage: lwe RingLWEConverter(RingLWE(20, 257, Discrete Gaussian sampler for polynomials of degree < 8 with σ=5.000000 in each component, x^8 - x^6 + x^4 - x^2 + 1, 'uniform', None)) """ return "RingLWEConverter(%s)"%str(self.ringlwe) def samples(m, n, lwe, seed=None, balanced=False, **kwds): """ Return ``m`` LWE samples. INPUT: - ``m`` - the number of samples (integer > 0) - ``n`` - the security parameter (integer > 0) - ``lwe`` - either - a subclass of :class:`LWE` such as :class:`Regev` or :class:`LindnerPeikert` - an instance of :class:`LWE` or any subclass - the name of any such class (e.g., "Regev", "LindnerPeikert") - ``seed`` - seed to be used for generation or ``None`` if no specific seed shall be set (default: ``None``) - ``balanced`` - use function :func:`balance_sample` to return balanced representations of finite field elements (default: ``False``) - ``**kwds`` - passed through to LWE constructor EXAMPLES:: sage: from sage.crypto.lwe import samples, Regev sage: samples(2, 20, Regev, seed=1337) [((199, 388, 337, 53, 200, 284, 336, 215, 75, 14, 274, 234, 97, 255, 246, 153, 268, 218, 396, 351), 15), ((365, 227, 333, 165, 76, 328, 288, 206, 286, 42, 175, 155, 190, 275, 114, 280, 45, 218, 304, 386), 143)] sage: from sage.crypto.lwe import samples, Regev sage: samples(2, 20, Regev, balanced=True, seed=1337) [((199, -13, -64, 53, 200, -117, -65, -186, 75, 14, -127, -167, 97, -146, -155, 153, -133, -183, -5, -50), 15), ((-36, -174, -68, 165, 76, -73, -113, -195, -115, 42, 175, 155, 190, -126, 114, -121, 45, -183, -97, -15), 143)] sage: from sage.crypto.lwe import samples sage: samples(2, 20, 'LindnerPeikert') [((506, 1205, 398, 0, 337, 106, 836, 75, 1242, 642, 840, 262, 1823, 1798, 1831, 1658, 1084, 915, 1994, 163), 1447), ((463, 250, 1226, 1906, 330, 933, 1014, 1061, 1322, 2035, 1849, 285, 1993, 1975, 864, 1341, 41, 1955, 1818, 1357), 312)] """ if seed is not None: set_random_seed(seed) if isinstance(lwe, str): lwe = eval(lwe) if isinstance(lwe, type): lwe = lwe(n, m=m, **kwds) else: if lwe.n != n: raise ValueError("Passed LWE instance has n=%d, but n=%d was passed to this function." % (lwe.n, n)) if balanced is False: f = lambda a_c: a_c else: f = balance_sample return [f(lwe()) for _ in range(m)] def balance_sample(s, q=None): r""" Given ``(a,c) = s`` return a tuple ``(a',c')`` where ``a'`` is an integer vector with entries between -q//2 and q//2 and ``c`` is also within these bounds. If ``q`` is given ``(a,c) = s`` may live in the integers. If ``q`` is not given, then ``(a,c)`` are assumed to live in `\Zmod{q}`. INPUT: - ``s`` - sample of the form (a,c) where a is a vector and c is a scalar - ``q`` - modulus (default: ``None``) EXAMPLES:: sage: from sage.crypto.lwe import balance_sample, samples, Regev sage: for s in samples(10, 5, Regev): ....: b = balance_sample(s) ....: assert all(-29//2 <= c <= 29//2 for c in b[0]) ....: assert -29//2 <= b[1] <= 29//2 ....: assert all(s[0][j] == b[0][j] % 29 for j in range(5)) ....: assert s[1] == b[1] % 29 sage: from sage.crypto.lwe import balance_sample, DiscreteGaussianDistributionPolynomialSampler, RingLWE, samples sage: D = DiscreteGaussianDistributionPolynomialSampler(ZZ['x'], 8, 5) sage: rlwe = RingLWE(20, 257, D) sage: for s in samples(10, 8, rlwe): ....: b = balance_sample(s) ....: assert all(-257//2 <= c <= 257//2 for bi in b for c in bi) ....: assert all(s[i][j] == b[i][j] % 257 for i in range(2) for j in range(8)) .. note:: This function is useful to convert between Sage's standard representation of elements in `\Zmod{q}` as integers between 0 and q-1 and the usual representation of such elements in lattice cryptography as integers between -q//2 and q//2. """ a, c = s try: c[0] scalar = False except TypeError: c = vector(c.parent(),[c]) scalar = True if q is None: q = parent(c[0]).order() a = a.change_ring(ZZ) c = c.change_ring(ZZ) else: K = IntegerModRing(q) a = a.change_ring(K).change_ring(ZZ) c = c.change_ring(K).change_ring(ZZ) q2 = q//2 if scalar: return vector(ZZ, len(a), [e if e <= q2 else e-q for e in a]), c[0] if c[0] <= q2 else c[0]-q else: return vector(ZZ, len(a), [e if e <= q2 else e-q for e in a]), vector(ZZ, len(c), [e if e <= q2 else e-q for e in c])
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/crypto/lwe.py
0.929688
0.445349
lwe.py
pypi
r""" S-Boxes used in cryptographic schemes This module provides the following SBoxes: constructions - BrackenLeander ([BraLea2008]_) - CarletTangTangLiao ([CTTL2014]_) - Gold ([Gol1968]_) - Kasami ([Kas1971]_) - Niho ([Dob1999a]_) - Welch ([Dob1999b]_) 9 bit to 9 bit - DryGASCON256 ([Rio2019]_) 8 bit to 8 bit - AES (FlexAEAD [NX2019]_) ([DR2002]_) - Anubis ([BR2000a]_) - ARIA_s2 ([KKPSSSYYLLCHH2004]_) - BelT ([Bel2011]_) - Camellia ([AIKMMNT2001]_) - CMEA ([WSK1997]_) - Chiasmus ([STW2013]_) - CLEFIA_S0, CLEFIA_S1 ([SSAMI2007]_) - Crypton_0_5 ([Lim]_) - Crypton_1_0_S0, ..., Crypton_1_0_S3 ([Lim2001]_) - CS_cipher ([SV2000]_) - CSA ([WW2005]_) - CSS ([BD2004]_) - DBlock ([WZY2015]_) - E2 ([KMAUTOM2000]_) - Enocoro ([WFYTP2008]_) - Fantomas ([GLSV2014]_) - FLY ([KG2016]_) - Fox ([VJ2004]_) - Iceberg ([SPRQL2004]_) - Iraqi (:wikipedia:`Iraqi_block_cipher`) - iScream ([GLSVJGK2014]_) - Kalyna_pi0, ..., Kalyna_pi3 ([OGKRKGBDDP2015]_) - Khazad ([BR2000b]_) - Kuznyechik (Kuznechik, Streebog, Stribog) ([Fed2015]_) - Lilliput-AE ([ABCFHLLMRT2019]_) - MD2 ([Kal1992]_) - newDES ([Sco1985]_) - Picaro ([PRC2012]_) - Safer ([Mas1994]_) - Scream ([CDL2015]_,[GLSVJGK2014]_) - SEED_S0, SEED_S1 ([LLYCL2005]_) - SKINNY_8 (ForkSkinny_8 [ALPRRV2019]_, Remus_8 [IKMP2019A]_, Romulus [IKMP2019B]_) ([BJKLMPSSS2016]_) - Skipjack ([U.S1998]_) - SNOW_3G_sq ([ETS2006a]_) - SMS4 ([Ltd06]_) - Turing ([RH2003b]_) - Twofish_p0, Twofish_p1 ([SKWWHF1998]_) - Whirlpool ([BR2000c]_) - Zorro ([GGNS2013]_) - ZUC_S0, ZUC_S1 ([ETS2011]_) 7 bit to 7 bit - Wage ([AAGMRZ2019]_) 6 bit to 6 bit - Fides_6 ([BBKMW2013]_) - APN_6 ([BDMW2010]_) - SC2000_6 ([SYYTIYTT2002]_) 5 bit to 5 bit - Ascon (ISAP [DEMMMPU2019]_) ([DEMS2016]_) - DryGASCON128 ([Rio2019]_) - Fides_5 ([BBKMW2013]_) - SC2000_5 ([SYYTIYTT2002]_) - Shamash ([PM2019]) - SYCON ([SMS2019]_) 4 bit to 4 bit - Elephant ([BCDM2019]_) - KNOT ([ZDYBXJZ2019]_) - Pyjamask_4 ([GJKPRSS2019]_) - SATURNIN_0, SATURNIN_1 ([CDLNPPS2019]_) - Spook (Clyde, Shadow) ([BBBCDGLLLMPPSW2019]_) - TRIFLE ([DGMPPS2019]_) - Yarara, Coral ([MP2019]_) - DES_S1_1, ..., DES_S1_4, ..., DES_S8_4 ([U.S1999]_) - Lucifer_S0, Lucifer_S1 ([Sor1984]_) - GOST_1, ..., GOST_8 (http://www.cypherpunks.ru/pygost/) - GOST2_1, GOST2_2 (http://www.cypherpunks.ru/pygost/) - Magma_1, ..., Magma_8 ([Fed2015]_) - GOST_IETF_1, ..., GOST_IETF_8 (http://www.cypherpunks.ru/pygost/) - Hummingbird_2_S1, ..., Hummingbird_2_S4 ([ESSS2011]_) - LBlock_0, ..., LBlock_9 ([WZ2011]_) - SERPENT_S0, ..., SERPENT_S7 ([BAK1998]_) - KLEIN ([GNL2011]_) - MIBS ([ISSK2009)] - Midori_Sb0 (MANTIS, CRAFT), Midori_Sb1 ([BBISHAR2015]_) - Noekeon ([DPVAR2000]_) - Piccolo ([SIHMAS2011]_) - Panda ([YWHWXSW2014]_) - PRESENT (CiliPadi [ZJRRS2019]_, PHOTON [BCDGNPY2019]_, ORANGE [CN2019]_) ([BKLPPRSV2007]_) - GIFT (Fountain_1, HYENA [CDJN2019]_, TGIF [IKMPSSS2019]_) ([BPPSST2017]_) - Fountain_1, Fountain_2, Fountain_3, Fountain_4 ([Zha2019]_) - Pride ([ADKLPY2014]_) - PRINCE ([BCGKKKLNPRRTY2012]_) - Prost ([KLLRSY2014]_) - Qarma_sigma0, Qarma_sigma1 (Qameleon [ABBDHR2019]_), Qarma_sigma2 ([Ava2017]_) - REC_0 (earlier version of [ZBLRYV2015]_) - Rectangle ([ZBLRYV2015]_) - SC2000_4 ([SYYTIYTT2002]_) - SKINNY_4 (ForkSkinny_4 [ALPRRV2019]_, Remus_4 [IKMP2019A]_) ([BJKLMPSSS2016]_) - TWINE ([SMMK2013]_) - Luffa_v1 ([DCSW2008]_) - Luffa ([DCSW2008]_) - BLAKE_1, ..., BLAKE_9 ([AHMP2008]_) - JH_S0, JH_S1 ([Wu2009]_) - SMASH_256_S1, ..., SMASH_256_S3 ([Knu2005]_) - Anubis_S0, Anubis_S1 ([BR2000a]_) - CLEFIA_SS0, ..., CLEFIA_SS3 ([SSAMI2007]_) - Enocoro_S4 ([WFYTP2008]_) - Iceberg_S0, Iceberg_S1 ([SPRQL2004]_) - Khazad_P, Khazad_Q ([BR2000b]_) - Whirlpool_E, Whirlpool_R ([BR2000c]_) - CS_cipher_F, CS_cipher_G ([SV2000]_) - Fox_S1, ..., Fox_S3 ([VJ2004]_) - Twofish_Q0_T0, ..., Twofish_Q0_T3, Twofish_Q1_T0, ..., Twofish_Q1_T3 ([SKWWHF1998]_) - Kuznyechik_nu0, Kuznyechik_nu1, Kuznyechik_sigma, Kuznyechik_phi ([BPU2016]_) - UDCIKMP11 ([UDCIKMP2011]_) - Optimal_S0, ..., Optimal_S15 ([LP2007]_) - Serpent_type_S0, ..., Serpent_type_S19 ([LP2007]_) - Golden_S0, ..., Golden_S3 ([Saa2011]_) - representatives for all 302 affine equivalence classes ([dCa2007]_) 3 bit to 3 bit - SEA ([SPGQ2006]_) - PRINTcipher ([KLPR2010]_) - Pyjamask_3 ([GJKPRSS2019]_) Additionally this modules offers a dictionary `sboxes` of all implemented above S-boxes for the purpose of easy iteration over all available S-boxes. EXAMPLES: We can print the S-Boxes with differential uniformity 2:: sage: from sage.crypto.sboxes import sboxes sage: sorted(name for name, s in sboxes.items() ....: if s.differential_uniformity() == 2) ['APN_6', 'Fides_5', 'Fides_6', 'PRINTcipher', 'Pyjamask_3', 'SC2000_5', 'SEA', 'Shamash'] AUTHOR: - Leo Perrin: initial collection of sboxes - Friedrich Wiemer (2017-05-12): refactored list for inclusion in Sage - Lukas Stennes (2019-06-25): added NIST LWC round 1 candidates """ import sys from sage.crypto.sbox import SBox from sage.misc.functional import is_odd, is_even def bracken_leander(n): r""" Return the Bracken-Leander construction. For n = 4*k and odd k, the construction is `x \mapsto x^{2^{2k} + 2^k + 1}` over `\GF{2^n}` INPUT: - ``n`` -- size of the S-Box EXAMPLES:: sage: from sage.crypto.sboxes import bracken_leander sage: sbox = bracken_leander(12); [sbox(i) for i in range(8)] [0, 1, 2742, 4035, 1264, 408, 1473, 1327] """ if n % 4 == 1 or is_even(n / 4): raise TypeError("Bracken-Leander functions are only defined for n = 4k with k odd") k = n / 4 e = 2**(2*k) + 2**k + 1 return monomial_function(n, e) def carlet_tang_tang_liao(n, c=None, bf=None): r""" Return the Carlet-Tang-Tang-Liao construction. See [CTTL2014]_ for its definition. INPUT: - ``n`` -- integer, the bit length of inputs and outputs, has to be even and >= 6 - ``c`` -- element of `\GF{2^{n-1}}` used in the construction (default: random element) - ``f`` -- Function from `\GF{2^n} \to \GF{2}` or BooleanFunction on `n-1` bits (default: ``x -> (1/(x+1)).trace())`` EXAMPLES:: sage: from sage.crypto.sboxes import carlet_tang_tang_liao as cttl sage: cttl(6).differential_uniformity() in [4, 64] True """ from sage.crypto.boolean_function import BooleanFunction from sage.rings.finite_rings.finite_field_constructor import GF if n < 6 or n % 2: raise TypeError("n >= 6 has to be even") K = GF(2**(n-1)) L = GF(2**n) if c is None: c = K.random_element() while c.trace() == 0 or (1/c).trace() == 0: c = K.random_element() elif c.trace() == 0 or (1/c).trace() == 0: raise TypeError("c.trace() and (1/c).trace() have to be 1") if bf is None: def bf(x): if x == 1: return 0 return (1/(x+1)).trace() elif isinstance(bf, (BooleanFunction,)): bf_f2 = bf def bf(x): xprime = map(int, x.polynomial().list()) xprime += [0]*(n-1 - len(xprime)) return int(bf_f2(xprime)) def f(x): xs = x.polynomial().list() xs += [0]*(n - len(xs)) xprime = K(xs[:n-1]) if xprime == 0: res = [0]*(n-1), bf(xprime/c) + xs[-1] elif xs[-1] == 0: res = (1/xprime).polynomial().list(), bf(xprime) else: res = (c/xprime).polynomial().list(), bf(xprime/c) + 1 res = res[0] + [0]*(n-1-len(res[0])) + [res[1]] return L(res) return SBox([f(L(x)) for x in GF(2)**n]) def gold(n, i): r""" Return the Gold function defined by `x \mapsto x^{2^i + 1}` over `\GF{2^n}`. INPUT: - ``n`` -- size of the S-Box - ``i`` -- a positive integer EXAMPLES:: sage: from sage.crypto.sboxes import gold sage: gold(3, 1) (0, 1, 3, 4, 5, 6, 7, 2) sage: gold(3, 1).differential_uniformity() 2 sage: gold(4, 2) (0, 1, 6, 6, 7, 7, 7, 6, 1, 7, 1, 6, 1, 6, 7, 1) """ e = 2**i + 1 return monomial_function(n, e) def kasami(n, i): r""" Return the Kasami function defined by `x \mapsto x^{2^{2i} - 2^i + 1}` over `\GF{2^n}`. INPUT: - ``n`` -- size of the S-Box - ``i`` -- a positive integer EXAMPLES:: sage: from sage.crypto.sboxes import kasami sage: kasami(3, 1) (0, 1, 3, 4, 5, 6, 7, 2) sage: from sage.crypto.sboxes import gold sage: kasami(3, 1) == gold(3, 1) True sage: kasami(4, 2) (0, 1, 13, 11, 14, 9, 6, 7, 10, 4, 15, 2, 8, 3, 5, 12) sage: kasami(4, 2) != gold(4, 2) True """ e = 2**(2*i) - 2**i + 1 return monomial_function(n, e) def niho(n): r""" Return the Niho function over `\GF{2^n}`. It is defined by `x \mapsto x^{2^t + 2^s - 1}` with `s = t/2` if t is even or `s = (3t+1)/2` if t is odd. INPUT: - ``n`` -- size of the S-Box EXAMPLES:: sage: from sage.crypto.sboxes import niho sage: niho(3) (0, 1, 7, 2, 3, 4, 5, 6) sage: niho(3).differential_uniformity() 2 """ if not is_odd(n): raise TypeError("Niho functions are only defined for n odd") t = (n - 1) / 2 if is_even(t): e = 2**t + 2**(t/2) - 1 else: e = 2**t + 2**((3*t+1)/2) - 1 return monomial_function(n, e) def welch(n): r""" Return the Welch function defined by `x \mapsto x^{2^{(n-1)/2} + 3}` over `\GF{2^n}`. INPUT: - ``n`` -- size of the S-Box EXAMPLES:: sage: from sage.crypto.sboxes import welch sage: welch(3) (0, 1, 7, 2, 3, 4, 5, 6) sage: welch(3).differential_uniformity() 2 """ if not is_odd(n): raise TypeError("Welch functions are only defined for odd n") t = (n - 1) / 2 e = 2**t + 3 return monomial_function(n, e) def monomial_function(n, e): r""" Return an S-Box as a function `x^e` defined over `\GF{2^n}`. INPUT: - ``n`` -- size of the S-Box (i.e. the degree of the finite field extension) - ``e`` -- exponent of the monomial function EXAMPLES:: sage: from sage.crypto.sboxes import monomial_function sage: S = monomial_function(7, 3) sage: S.differential_uniformity() 2 sage: S.input_size() 7 sage: S.is_permutation() True """ from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.finite_rings.finite_field_constructor import GF base_ring = GF(2**n, name='x') R = PolynomialRing(base_ring, name='X') X = R.gen() return SBox(X**e) # Bijective S-Boxes mapping 9 bits to 9 # ===================================== DryGASCON256 = SBox([ 0x10, 0x93, 0x11f, 0x9d, 0x1f, 0x9c, 0x113, 0x91, 0x2a, 0xa9, 0x127, 0xa5, 0x27, 0xa4, 0x129, 0xab, 0x2c, 0xaf, 0x123, 0xa1, 0x23, 0xa0, 0x12f, 0xad, 0x1a, 0x99, 0x117, 0x95, 0x17, 0x94, 0x119, 0x9b, 0xf8, 0x7b, 0x1f7, 0x75, 0xf7, 0x74, 0x1fb, 0x79, 0xca, 0x49, 0x1c7, 0x45, 0xc7, 0x44, 0x1c9, 0x4b, 0xcc, 0x4f, 0x1c3, 0x41, 0xc3, 0x40, 0x1cf, 0x4d, 0xf2, 0x71, 0x1ff, 0x7d, 0xff, 0x7c, 0x1f1, 0x73, 0xe0, 0x63, 0x1ef, 0x6d, 0xef, 0x6c, 0x1e3, 0x61, 0xda, 0x59, 0x1d7, 0x55, 0xd7, 0x54, 0x1d9, 0x5b, 0xdc, 0x5f, 0x1d3, 0x51, 0xd3, 0x50, 0x1df, 0x5d, 0xea, 0x69, 0x1e7, 0x65, 0xe7, 0x64, 0x1e9, 0x6b, 0x38, 0xbb, 0x137, 0xb5, 0x37, 0xb4, 0x13b, 0xb9, 0x0a, 0x89, 0x107, 0x85, 0x07, 0x84, 0x109, 0x8b, 0x0c, 0x8f, 0x103, 0x81, 0x03, 0x80, 0x10f, 0x8d, 0x32, 0xb1, 0x13f, 0xbd, 0x3f, 0xbc, 0x131, 0xb3, 0x1b1, 0x1b2, 0xbe, 0x1bc, 0x1be, 0x1bd, 0xb2, 0x1b0, 0x18b, 0x188, 0x86, 0x184, 0x186, 0x185, 0x88, 0x18a, 0x18d, 0x18e, 0x82, 0x180, 0x182, 0x181, 0x8e, 0x18c, 0x1bb, 0x1b8, 0xb6, 0x1b4, 0x1b6, 0x1b5, 0xb8, 0x1ba, 0x179, 0x17a, 0x76, 0x174, 0x176, 0x175, 0x7a, 0x178, 0x14b, 0x148, 0x46, 0x144, 0x146, 0x145, 0x48, 0x14a, 0x14d, 0x14e, 0x42, 0x140, 0x142, 0x141, 0x4e, 0x14c, 0x173, 0x170, 0x7e, 0x17c, 0x17e, 0x17d, 0x70, 0x172, 0x161, 0x162, 0x6e, 0x16c, 0x16e, 0x16d, 0x62, 0x160, 0x15b, 0x158, 0x56, 0x154, 0x156, 0x155, 0x58, 0x15a, 0x15d, 0x15e, 0x52, 0x150, 0x152, 0x151, 0x5e, 0x15c, 0x16b, 0x168, 0x66, 0x164, 0x166, 0x165, 0x68, 0x16a, 0x199, 0x19a, 0x96, 0x194, 0x196, 0x195, 0x9a, 0x198, 0x1ab, 0x1a8, 0xa6, 0x1a4, 0x1a6, 0x1a5, 0xa8, 0x1aa, 0x1ad, 0x1ae, 0xa2, 0x1a0, 0x1a2, 0x1a1, 0xae, 0x1ac, 0x193, 0x190, 0x9e, 0x19c, 0x19e, 0x19d, 0x90, 0x192, 0x1d2, 0x1d1, 0x1d, 0xde, 0x1dd, 0x1de, 0x1d, 0xd2, 0x1e8, 0x1eb, 0x1e, 0xe6, 0x1e5, 0x1e6, 0x1e, 0xe8, 0x1ee, 0x1ed, 0x1e, 0xe2, 0x1e1, 0x1e2, 0x1e, 0xee, 0x1d8, 0x1db, 0x1d, 0xd6, 0x1d5, 0x1d6, 0x1d, 0xd8, 0x13a, 0x139, 0x13, 0x36, 0x135, 0x136, 0x13, 0x3a, 0x108, 0x10b, 0x10, 0x06, 0x105, 0x106, 0x10, 0x08, 0x10e, 0x10d, 0x10, 0x02, 0x101, 0x102, 0x10, 0x0e, 0x130, 0x133, 0x13, 0x3e, 0x13d, 0x13e, 0x13, 0x30, 0x122, 0x121, 0x12, 0x2e, 0x12d, 0x12e, 0x12, 0x22, 0x118, 0x11b, 0x11, 0x16, 0x115, 0x116, 0x11, 0x18, 0x11e, 0x11d, 0x11, 0x12, 0x111, 0x112, 0x11, 0x1e, 0x128, 0x12b, 0x12, 0x26, 0x125, 0x126, 0x12, 0x28, 0x1fa, 0x1f9, 0x1f, 0xf6, 0x1f5, 0x1f6, 0x1f, 0xfa, 0x1c8, 0x1cb, 0x1c, 0xc6, 0x1c5, 0x1c6, 0x1c, 0xc8, 0x1ce, 0x1cd, 0x1c, 0xc2, 0x1c1, 0x1c2, 0x1c, 0xce, 0x1f0, 0x1f3, 0x1f, 0xfe, 0x1fd, 0x1fe, 0x1f, 0xf0, 0x33, 0xb0, 0x3d, 0x1bf, 0x3c, 0xbf, 0x31, 0x1b3, 0x09, 0x8a, 0x05, 0x187, 0x04, 0x87, 0x0b, 0x189, 0x0f, 0x8c, 0x01, 0x183, 0x00, 0x83, 0x0d, 0x18f, 0x39, 0xba, 0x35, 0x1b7, 0x34, 0xb7, 0x3b, 0x1b9, 0xfb, 0x78, 0xf5, 0x177, 0xf4, 0x77, 0xf9, 0x17b, 0xc9, 0x4a, 0xc5, 0x147, 0xc4, 0x47, 0xcb, 0x149, 0xcf, 0x4c, 0xc1, 0x143, 0xc0, 0x43, 0xcd, 0x14f, 0xf1, 0x72, 0xfd, 0x17f, 0xfc, 0x7f, 0xf3, 0x171, 0xe3, 0x60, 0xed, 0x16f, 0xec, 0x6f, 0xe1, 0x163, 0xd9, 0x5a, 0xd5, 0x157, 0xd4, 0x57, 0xdb, 0x159, 0xdf, 0x5c, 0xd1, 0x153, 0xd0, 0x53, 0xdd, 0x15f, 0xe9, 0x6a, 0xe5, 0x167, 0xe4, 0x67, 0xeb, 0x169, 0x1b, 0x98, 0x15, 0x197, 0x14, 0x97, 0x19, 0x19b, 0x29, 0xaa, 0x25, 0x1a7, 0x24, 0xa7, 0x2b, 0x1a9, 0x2f, 0xac, 0x21, 0x1a3, 0x20, 0xa3, 0x2d, 0x1af, 0x11, 0x92, 0x1d, 0x19f, 0x1c, 0x9f, 0x13, 0x191]) # Bijective S-Boxes mapping 8 bits to 8 # ===================================== AES = SBox([ 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15, 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75, 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84, 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf, 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8, 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2, 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08, 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a, 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e, 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16]) FlexAEAD = AES Anubis = SBox([ 0xa7,0xd3,0xe6,0x71,0xd0,0xac,0x4d,0x79,0x3a,0xc9,0x91,0xfc,0x1e,0x47,0x54,0xbd, 0x8c,0xa5,0x7a,0xfb,0x63,0xb8,0xdd,0xd4,0xe5,0xb3,0xc5,0xbe,0xa9,0x88,0x0c,0xa2, 0x39,0xdf,0x29,0xda,0x2b,0xa8,0xcb,0x4c,0x4b,0x22,0xaa,0x24,0x41,0x70,0xa6,0xf9, 0x5a,0xe2,0xb0,0x36,0x7d,0xe4,0x33,0xff,0x60,0x20,0x08,0x8b,0x5e,0xab,0x7f,0x78, 0x7c,0x2c,0x57,0xd2,0xdc,0x6d,0x7e,0x0d,0x53,0x94,0xc3,0x28,0x27,0x06,0x5f,0xad, 0x67,0x5c,0x55,0x48,0x0e,0x52,0xea,0x42,0x5b,0x5d,0x30,0x58,0x51,0x59,0x3c,0x4e, 0x38,0x8a,0x72,0x14,0xe7,0xc6,0xde,0x50,0x8e,0x92,0xd1,0x77,0x93,0x45,0x9a,0xce, 0x2d,0x03,0x62,0xb6,0xb9,0xbf,0x96,0x6b,0x3f,0x07,0x12,0xae,0x40,0x34,0x46,0x3e, 0xdb,0xcf,0xec,0xcc,0xc1,0xa1,0xc0,0xd6,0x1d,0xf4,0x61,0x3b,0x10,0xd8,0x68,0xa0, 0xb1,0x0a,0x69,0x6c,0x49,0xfa,0x76,0xc4,0x9e,0x9b,0x6e,0x99,0xc2,0xb7,0x98,0xbc, 0x8f,0x85,0x1f,0xb4,0xf8,0x11,0x2e,0x00,0x25,0x1c,0x2a,0x3d,0x05,0x4f,0x7b,0xb2, 0x32,0x90,0xaf,0x19,0xa3,0xf7,0x73,0x9d,0x15,0x74,0xee,0xca,0x9f,0x0f,0x1b,0x75, 0x86,0x84,0x9c,0x4a,0x97,0x1a,0x65,0xf6,0xed,0x09,0xbb,0x26,0x83,0xeb,0x6f,0x81, 0x04,0x6a,0x43,0x01,0x17,0xe1,0x87,0xf5,0x8d,0xe3,0x23,0x80,0x44,0x16,0x66,0x21, 0xfe,0xd5,0x31,0xd9,0x35,0x18,0x02,0x64,0xf2,0xf1,0x56,0xcd,0x82,0xc8,0xba,0xf0, 0xef,0xe9,0xe8,0xfd,0x89,0xd7,0xc7,0xb5,0xa4,0x2f,0x95,0x13,0x0b,0xf3,0xe0,0x37]) ARIA_s2 = SBox([ 0xe2,0x4e,0x54,0xfc,0x94,0xc2,0x4a,0xcc,0x62,0x0d,0x6a,0x46,0x3c,0x4d,0x8b,0xd1, 0x5e,0xfa,0x64,0xcb,0xb4,0x97,0xbe,0x2b,0xbc,0x77,0x2e,0x03,0xd3,0x19,0x59,0xc1, 0x1d,0x06,0x41,0x6b,0x55,0xf0,0x99,0x69,0xea,0x9c,0x18,0xae,0x63,0xdf,0xe7,0xbb, 0x00,0x73,0x66,0xfb,0x96,0x4c,0x85,0xe4,0x3a,0x09,0x45,0xaa,0x0f,0xee,0x10,0xeb, 0x2d,0x7f,0xf4,0x29,0xac,0xcf,0xad,0x91,0x8d,0x78,0xc8,0x95,0xf9,0x2f,0xce,0xcd, 0x08,0x7a,0x88,0x38,0x5c,0x83,0x2a,0x28,0x47,0xdb,0xb8,0xc7,0x93,0xa4,0x12,0x53, 0xff,0x87,0x0e,0x31,0x36,0x21,0x58,0x48,0x01,0x8e,0x37,0x74,0x32,0xca,0xe9,0xb1, 0xb7,0xab,0x0c,0xd7,0xc4,0x56,0x42,0x26,0x07,0x98,0x60,0xd9,0xb6,0xb9,0x11,0x40, 0xec,0x20,0x8c,0xbd,0xa0,0xc9,0x84,0x04,0x49,0x23,0xf1,0x4f,0x50,0x1f,0x13,0xdc, 0xd8,0xc0,0x9e,0x57,0xe3,0xc3,0x7b,0x65,0x3b,0x02,0x8f,0x3e,0xe8,0x25,0x92,0xe5, 0x15,0xdd,0xfd,0x17,0xa9,0xbf,0xd4,0x9a,0x7e,0xc5,0x39,0x67,0xfe,0x76,0x9d,0x43, 0xa7,0xe1,0xd0,0xf5,0x68,0xf2,0x1b,0x34,0x70,0x05,0xa3,0x8a,0xd5,0x79,0x86,0xa8, 0x30,0xc6,0x51,0x4b,0x1e,0xa6,0x27,0xf6,0x35,0xd2,0x6e,0x24,0x16,0x82,0x5f,0xda, 0xe6,0x75,0xa2,0xef,0x2c,0xb2,0x1c,0x9f,0x5d,0x6f,0x80,0x0a,0x72,0x44,0x9b,0x6c, 0x90,0x0b,0x5b,0x33,0x7d,0x5a,0x52,0xf3,0x61,0xa1,0xf7,0xb0,0xd6,0x3f,0x7c,0x6d, 0xed,0x14,0xe0,0xa5,0x3d,0x22,0xb3,0xf8,0x89,0xde,0x71,0x1a,0xaf,0xba,0xb5,0x81]) BelT = SBox([ 0xb1,0x94,0xba,0xc8,0x0a,0x08,0xf5,0x3b,0x36,0x6d,0x00,0x8e,0x58,0x4a,0x5d,0xe4, 0x85,0x04,0xfa,0x9d,0x1b,0xb6,0xc7,0xac,0x25,0x2e,0x72,0xc2,0x02,0xfd,0xce,0x0d, 0x5b,0xe3,0xd6,0x12,0x17,0xb9,0x61,0x81,0xfe,0x67,0x86,0xad,0x71,0x6b,0x89,0x0b, 0x5c,0xb0,0xc0,0xff,0x33,0xc3,0x56,0xb8,0x35,0xc4,0x05,0xae,0xd8,0xe0,0x7f,0x99, 0xe1,0x2b,0xdc,0x1a,0xe2,0x82,0x57,0xec,0x70,0x3f,0xcc,0xf0,0x95,0xee,0x8d,0xf1, 0xc1,0xab,0x76,0x38,0x9f,0xe6,0x78,0xca,0xf7,0xc6,0xf8,0x60,0xd5,0xbb,0x9c,0x4f, 0xf3,0x3c,0x65,0x7b,0x63,0x7c,0x30,0x6a,0xdd,0x4e,0xa7,0x79,0x9e,0xb2,0x3d,0x31, 0x3e,0x98,0xb5,0x6e,0x27,0xd3,0xbc,0xcf,0x59,0x1e,0x18,0x1f,0x4c,0x5a,0xb7,0x93, 0xe9,0xde,0xe7,0x2c,0x8f,0x0c,0x0f,0xa6,0x2d,0xdb,0x49,0xf4,0x6f,0x73,0x96,0x47, 0x06,0x07,0x53,0x16,0xed,0x24,0x7a,0x37,0x39,0xcb,0xa3,0x83,0x03,0xa9,0x8b,0xf6, 0x92,0xbd,0x9b,0x1c,0xe5,0xd1,0x41,0x01,0x54,0x45,0xfb,0xc9,0x5e,0x4d,0x0e,0xf2, 0x68,0x20,0x80,0xaa,0x22,0x7d,0x64,0x2f,0x26,0x87,0xf9,0x34,0x90,0x40,0x55,0x11, 0xbe,0x32,0x97,0x13,0x43,0xfc,0x9a,0x48,0xa0,0x2a,0x88,0x5f,0x19,0x4b,0x09,0xa1, 0x7e,0xcd,0xa4,0xd0,0x15,0x44,0xaf,0x8c,0xa5,0x84,0x50,0xbf,0x66,0xd2,0xe8,0x8a, 0xa2,0xd7,0x46,0x52,0x42,0xa8,0xdf,0xb3,0x69,0x74,0xc5,0x51,0xeb,0x23,0x29,0x21, 0xd4,0xef,0xd9,0xb4,0x3a,0x62,0x28,0x75,0x91,0x14,0x10,0xea,0x77,0x6c,0xda,0x1d]) Camellia = SBox([ 112,130, 44,236,179, 39,192,229,228,133, 87, 53,234, 12,174, 65, 35,239,107,147, 69, 25,165, 33,237, 14, 79, 78, 29,101,146,189, 134,184,175,143,124,235, 31,206, 62, 48,220, 95, 94,197, 11, 26, 166,225, 57,202,213, 71, 93, 61,217, 1, 90,214, 81, 86,108, 77, 139, 13,154,102,251,204,176, 45,116, 18, 43, 32,240,177,132,153, 223, 76,203,194, 52,126,118, 5,109,183,169, 49,209, 23, 4,215, 20, 88, 58, 97,222, 27, 17, 28, 50, 15,156, 22, 83, 24,242, 34, 254, 68,207,178,195,181,122,145, 36, 8,232,168, 96,252,105, 80, 170,208,160,125,161,137, 98,151, 84, 91, 30,149,224,255,100,210, 16,196, 0, 72,163,247,117,219,138, 3,230,218, 9, 63,221,148, 135, 92,131, 2,205, 74,144, 51,115,103,246,243,157,127,191,226, 82,155,216, 38,200, 55,198, 59,129,150,111, 75, 19,190, 99, 46, 233,121,167,140,159,110,188,142, 41,245,249,182, 47,253,180, 89, 120,152, 6,106,231, 70,113,186,212, 37,171, 66,136,162,141,250, 114, 7,185, 85,248,238,172, 10, 54, 73, 42,104, 60, 56,241,164, 64, 40,211,123,187,201, 67,193, 21,227,173,244,119,199,128,158]) # source: https://www.schneier.com/academic/paperfiles/paper-cmea.pdf CMEA = SBox([ 0xd9,0x23,0x5f,0xe6,0xca,0x68,0x97,0xb0,0x7b,0xf2,0x0c,0x34,0x11,0xa5,0x8d,0x4e, 0x0a,0x46,0x77,0x8d,0x10,0x9f,0x5e,0x62,0xf1,0x34,0xec,0xa5,0xc9,0xb3,0xd8,0x2b, 0x59,0x47,0xe3,0xd2,0xff,0xae,0x64,0xca,0x15,0x8b,0x7d,0x38,0x21,0xbc,0x96,0x00, 0x49,0x56,0x23,0x15,0x97,0xe4,0xcb,0x6f,0xf2,0x70,0x3c,0x88,0xba,0xd1,0x0d,0xae, 0xe2,0x38,0xba,0x44,0x9f,0x83,0x5d,0x1c,0xde,0xab,0xc7,0x65,0xf1,0x76,0x09,0x20, 0x86,0xbd,0x0a,0xf1,0x3c,0xa7,0x29,0x93,0xcb,0x45,0x5f,0xe8,0x10,0x74,0x62,0xde, 0xb8,0x77,0x80,0xd1,0x12,0x26,0xac,0x6d,0xe9,0xcf,0xf3,0x54,0x3a,0x0b,0x95,0x4e, 0xb1,0x30,0xa4,0x96,0xf8,0x57,0x49,0x8e,0x05,0x1f,0x62,0x7c,0xc3,0x2b,0xda,0xed, 0xbb,0x86,0x0d,0x7a,0x97,0x13,0x6c,0x4e,0x51,0x30,0xe5,0xf2,0x2f,0xd8,0xc4,0xa9, 0x91,0x76,0xf0,0x17,0x43,0x38,0x29,0x84,0xa2,0xdb,0xef,0x65,0x5e,0xca,0x0d,0xbc, 0xe7,0xfa,0xd8,0x81,0x6f,0x00,0x14,0x42,0x25,0x7c,0x5d,0xc9,0x9e,0xb6,0x33,0xab, 0x5a,0x6f,0x9b,0xd9,0xfe,0x71,0x44,0xc5,0x37,0xa2,0x88,0x2d,0x00,0xb6,0x13,0xec, 0x4e,0x96,0xa8,0x5a,0xb5,0xd7,0xc3,0x8d,0x3f,0xf2,0xec,0x04,0x60,0x71,0x1b,0x29, 0x04,0x79,0xe3,0xc7,0x1b,0x66,0x81,0x4a,0x25,0x9d,0xdc,0x5f,0x3e,0xb0,0xf8,0xa2, 0x91,0x34,0xf6,0x5c,0x67,0x89,0x73,0x05,0x22,0xaa,0xcb,0xee,0xbf,0x18,0xd0,0x4d, 0xf5,0x36,0xae,0x01,0x2f,0x94,0xc3,0x49,0x8b,0xbd,0x58,0x12,0xe0,0x77,0x6c,0xda]) Chiasmus = SBox([ 0x65,0x33,0xcf,0xb9,0x37,0x64,0xcd,0xf3,0x26,0x3a,0xc1,0xa2,0x72,0x8a,0x8f,0xe3, 0xfd,0x56,0xb3,0x0f,0x10,0x2b,0x3e,0xa0,0xbd,0x1e,0xab,0x1d,0x9c,0xe2,0x87,0x98, 0xa8,0xd3,0xb4,0xdf,0x92,0x75,0x3b,0x39,0x20,0xa5,0xfa,0x1b,0xbe,0x90,0xf6,0x09, 0xe5,0x61,0xc4,0xc9,0x06,0xc2,0xa6,0x1c,0xf9,0x94,0x7b,0x53,0x73,0x01,0x25,0x9a, 0x1a,0xff,0xe9,0x5a,0x76,0x13,0x4b,0x95,0xac,0x0b,0xc7,0xb2,0xb8,0xd6,0x17,0xa9, 0x27,0xeb,0xd1,0x5C,0xc3,0x9b,0x22,0x15,0x8e,0x40,0x11,0x5e,0x57,0x16,0xd0,0xb0, 0x5d,0x79,0x31,0xbb,0xea,0x4f,0xd9,0xde,0x00,0x0a,0xd7,0xad,0x3f,0x99,0x68,0x34, 0x66,0xf0,0x44,0x35,0x89,0x54,0x81,0xb1,0x84,0x2a,0x8b,0x6f,0xc0,0x43,0xfe,0x96, 0x48,0x82,0x0c,0xda,0x74,0xbc,0x21,0xf1,0x67,0x2e,0xdb,0x49,0xe4,0xd5,0x71,0x59, 0x29,0xe0,0xa1,0x30,0xdd,0x91,0x6b,0xb7,0xb6,0x69,0xc5,0x80,0xaa,0x6d,0xa3,0x2c, 0x05,0x78,0xba,0x51,0x14,0x07,0xd4,0xec,0x7e,0xcc,0x24,0x62,0x9e,0xdc,0x8c,0xd8, 0x1f,0x46,0xe8,0x9f,0x4e,0xa4,0x85,0x32,0xce,0xa7,0xfc,0xe1,0x97,0xae,0x2d,0x52, 0x7d,0x0e,0x6c,0x83,0x5f,0xbf,0x18,0x7c,0x36,0x63,0x0d,0xef,0xc8,0x5b,0x55,0x12, 0x4a,0xf2,0x70,0x38,0xf8,0xaf,0x86,0x77,0x47,0x04,0x23,0x02,0x6e,0x4c,0x58,0x03, 0x50,0x7a,0x3d,0x28,0xf5,0xe7,0x41,0xf4,0x45,0x60,0x6a,0x08,0x88,0x7f,0x9d,0x93, 0x4d,0xd2,0x2f,0xee,0xe6,0xcb,0xed,0xfb,0xca,0xf7,0x19,0xb5,0x42,0x8d,0xc6,0x3c]) CLEFIA_S0 = SBox([ 0x57,0x49,0xd1,0xc6,0x2f,0x33,0x74,0xfb,0x95,0x6d,0x82,0xea,0x0e,0xb0,0xa8,0x1c, 0x28,0xd0,0x4b,0x92,0x5c,0xee,0x85,0xb1,0xc4,0x0a,0x76,0x3d,0x63,0xf9,0x17,0xaf, 0xbf,0xa1,0x19,0x65,0xf7,0x7a,0x32,0x20,0x06,0xce,0xe4,0x83,0x9d,0x5b,0x4c,0xd8, 0x42,0x5d,0x2e,0xe8,0xd4,0x9b,0x0f,0x13,0x3c,0x89,0x67,0xc0,0x71,0xaa,0xb6,0xf5, 0xa4,0xbe,0xfd,0x8c,0x12,0x00,0x97,0xda,0x78,0xe1,0xcf,0x6b,0x39,0x43,0x55,0x26, 0x30,0x98,0xcc,0xdd,0xeb,0x54,0xb3,0x8f,0x4e,0x16,0xfa,0x22,0xa5,0x77,0x09,0x61, 0xd6,0x2a,0x53,0x37,0x45,0xc1,0x6c,0xae,0xef,0x70,0x08,0x99,0x8b,0x1d,0xf2,0xb4, 0xe9,0xc7,0x9f,0x4a,0x31,0x25,0xfe,0x7c,0xd3,0xa2,0xbd,0x56,0x14,0x88,0x60,0x0b, 0xcd,0xe2,0x34,0x50,0x9e,0xdc,0x11,0x05,0x2b,0xb7,0xa9,0x48,0xff,0x66,0x8a,0x73, 0x03,0x75,0x86,0xf1,0x6a,0xa7,0x40,0xc2,0xb9,0x2c,0xdb,0x1f,0x58,0x94,0x3e,0xed, 0xfc,0x1b,0xa0,0x04,0xb8,0x8d,0xe6,0x59,0x62,0x93,0x35,0x7e,0xca,0x21,0xdf,0x47, 0x15,0xf3,0xba,0x7f,0xa6,0x69,0xc8,0x4d,0x87,0x3b,0x9c,0x01,0xe0,0xde,0x24,0x52, 0x7b,0x0c,0x68,0x1e,0x80,0xb2,0x5a,0xe7,0xad,0xd5,0x23,0xf4,0x46,0x3f,0x91,0xc9, 0x6e,0x84,0x72,0xbb,0x0d,0x18,0xd9,0x96,0xf0,0x5f,0x41,0xac,0x27,0xc5,0xe3,0x3a, 0x81,0x6f,0x07,0xa3,0x79,0xf6,0x2d,0x38,0x1a,0x44,0x5e,0xb5,0xd2,0xec,0xcb,0x90, 0x9a,0x36,0xe5,0x29,0xc3,0x4f,0xab,0x64,0x51,0xf8,0x10,0xd7,0xbc,0x02,0x7d,0x8e]) CLEFIA_S1 = SBox([ 0x6c,0xda,0xc3,0xe9,0x4e,0x9d,0x0a,0x3d,0xb8,0x36,0xb4,0x38,0x13,0x34,0x0c,0xd9, 0xbf,0x74,0x94,0x8f,0xb7,0x9c,0xe5,0xdc,0x9e,0x07,0x49,0x4f,0x98,0x2c,0xb0,0x93, 0x12,0xeb,0xcd,0xb3,0x92,0xe7,0x41,0x60,0xe3,0x21,0x27,0x3b,0xe6,0x19,0xd2,0x0e, 0x91,0x11,0xc7,0x3f,0x2a,0x8e,0xa1,0xbc,0x2b,0xc8,0xc5,0x0f,0x5b,0xf3,0x87,0x8b, 0xfb,0xf5,0xde,0x20,0xc6,0xa7,0x84,0xce,0xd8,0x65,0x51,0xc9,0xa4,0xef,0x43,0x53, 0x25,0x5d,0x9b,0x31,0xe8,0x3e,0x0d,0xd7,0x80,0xff,0x69,0x8a,0xba,0x0b,0x73,0x5c, 0x6e,0x54,0x15,0x62,0xf6,0x35,0x30,0x52,0xa3,0x16,0xd3,0x28,0x32,0xfa,0xaa,0x5e, 0xcf,0xea,0xed,0x78,0x33,0x58,0x09,0x7b,0x63,0xc0,0xc1,0x46,0x1e,0xdf,0xa9,0x99, 0x55,0x04,0xc4,0x86,0x39,0x77,0x82,0xec,0x40,0x18,0x90,0x97,0x59,0xdd,0x83,0x1f, 0x9a,0x37,0x06,0x24,0x64,0x7c,0xa5,0x56,0x48,0x08,0x85,0xd0,0x61,0x26,0xca,0x6f, 0x7e,0x6a,0xb6,0x71,0xa0,0x70,0x05,0xd1,0x45,0x8c,0x23,0x1c,0xf0,0xee,0x89,0xad, 0x7a,0x4b,0xc2,0x2f,0xdb,0x5a,0x4d,0x76,0x67,0x17,0x2d,0xf4,0xcb,0xb1,0x4a,0xa8, 0xb5,0x22,0x47,0x3a,0xd5,0x10,0x4c,0x72,0xcc,0x00,0xf9,0xe0,0xfd,0xe2,0xfe,0xae, 0xf8,0x5f,0xab,0xf1,0x1b,0x42,0x81,0xd6,0xbe,0x44,0x29,0xa6,0x57,0xb9,0xaf,0xf2, 0xd4,0x75,0x66,0xbb,0x68,0x9f,0x50,0x02,0x01,0x3c,0x7f,0x8d,0x1a,0x88,0xbd,0xac, 0xf7,0xe4,0x79,0x96,0xa2,0xfc,0x6d,0xb2,0x6b,0x03,0xe1,0x2e,0x7d,0x14,0x95,0x1d]) Crypton_0_5 = SBox([ 0xf0,0x12,0x4c,0x7a,0x47,0x16,0x03,0x3a,0xe6,0x9d,0x44,0x77,0x53,0xca,0x3b,0x0f, 0x9b,0x98,0x54,0x90,0x3d,0xac,0x74,0x56,0x9e,0xde,0x5c,0xf3,0x86,0x39,0x7c,0xc4, 0x91,0xa9,0x97,0x5f,0x9c,0x0d,0x78,0xcc,0xfd,0x43,0xbf,0x02,0x4b,0x92,0x60,0x3e, 0x7d,0x1d,0x50,0xcb,0xb8,0xb9,0x70,0x27,0xaa,0x96,0x48,0x88,0x38,0xd7,0x68,0x42, 0xa8,0xd0,0xa6,0x2e,0x25,0xf4,0x2c,0x6e,0x0c,0xb7,0xce,0xe0,0xbe,0x0b,0x24,0x67, 0x8c,0xec,0xc5,0x52,0xd9,0xd8,0x09,0xb4,0xcf,0x8f,0x8d,0x8b,0x59,0x23,0x51,0xe3, 0xd3,0xb1,0x18,0xf8,0xd4,0x05,0xa2,0xdb,0x82,0x6c,0x00,0x46,0x8a,0xaf,0xda,0xbc, 0x99,0x1a,0xad,0xb3,0x1f,0x0e,0x71,0x4f,0xc7,0x2b,0xe5,0x2a,0xe2,0x58,0x29,0x06, 0xf6,0xfe,0xf9,0x19,0x6b,0xea,0xbb,0xc2,0xa3,0x55,0xa1,0xdf,0x6f,0x45,0x83,0x69, 0x8e,0x7b,0x72,0x3c,0xee,0xff,0x07,0xa5,0xe8,0xf1,0x0a,0x1c,0x75,0xe1,0x2f,0x21, 0xd2,0xb6,0x3f,0xf7,0x73,0xb2,0x5d,0x79,0x35,0x80,0x17,0x41,0x94,0x7e,0x15,0xed, 0xb5,0xd5,0x93,0x14,0x20,0x61,0x76,0x31,0xc9,0x6a,0xab,0x34,0xa0,0xa4,0x1e,0xba, 0xe7,0x13,0x4e,0xc6,0xd6,0x87,0x7f,0xbd,0x84,0x62,0x26,0x95,0x6d,0x4d,0x57,0x28, 0x04,0x64,0x4a,0x11,0x01,0x40,0x65,0x08,0xb0,0xe9,0x32,0xcd,0x81,0x66,0x2d,0x5b, 0xef,0xa7,0xfb,0xdd,0xf2,0x33,0x5a,0x63,0xc1,0xe4,0xc3,0xae,0xdc,0xfc,0x22,0x10, 0xfa,0x9f,0xd1,0x85,0x9a,0x1b,0x5e,0x30,0xeb,0xc8,0x89,0x49,0x37,0xc0,0x36,0xf5]) Crypton_1_0_S0 = SBox([ 0x63,0xec,0x59,0xaa,0xdb,0x8e,0x66,0xc0,0x37,0x3c,0x14,0xff,0x13,0x44,0xa9,0x91, 0x3b,0x78,0x8d,0xef,0xc2,0x2a,0xf0,0xd7,0x61,0x9e,0xa5,0xbc,0x48,0x15,0x12,0x47, 0xed,0x42,0x1a,0x33,0x38,0xc8,0x17,0x90,0xa6,0xd5,0x5d,0x65,0x6a,0xfe,0x8f,0xa1, 0x93,0xca,0x2f,0x0c,0x68,0x58,0xdf,0xf4,0x45,0x11,0xa0,0xa7,0x22,0x96,0xfb,0x7d, 0x1d,0xb4,0x84,0xe0,0xbf,0x57,0xe9,0x0a,0x4e,0x83,0xcc,0x7a,0x71,0x39,0xc7,0x32, 0x74,0x3d,0xde,0x50,0x85,0x06,0x6f,0x53,0xe8,0xad,0x82,0x19,0xe1,0xba,0x36,0xcb, 0x0e,0x28,0xf3,0x9b,0x4a,0x62,0x94,0x1f,0xbd,0xf6,0x67,0x41,0xd8,0xd1,0x2d,0xa4, 0x86,0xb7,0x01,0xc5,0xb0,0x75,0x02,0xf9,0x2c,0x29,0x6e,0xd2,0x5f,0x8b,0xfc,0x5a, 0xe4,0x7f,0xdd,0x07,0x55,0xb1,0x2b,0x89,0x72,0x18,0x3a,0x4c,0xb6,0xe3,0x80,0xce, 0x49,0xcf,0x6b,0xb9,0xf2,0x0d,0xdc,0x64,0x95,0x46,0xf7,0x10,0x9a,0x20,0xa2,0x3f, 0xd6,0x87,0x70,0x3e,0x21,0xfd,0x4d,0x7b,0xc3,0xae,0x09,0x8a,0x04,0xb3,0x54,0xf8, 0x30,0x00,0x56,0xd4,0xe7,0x25,0xbb,0xac,0x98,0x73,0xea,0xc9,0x9d,0x4f,0x7e,0x03, 0xab,0x92,0xa8,0x43,0x0f,0xfa,0x24,0x5c,0x1e,0x60,0x31,0x97,0xcd,0xc6,0x79,0xf5, 0x5e,0xe5,0x34,0x76,0x1c,0x81,0xb2,0xaf,0x0b,0x5b,0xd9,0xe2,0x27,0x6d,0xd0,0x88, 0xc1,0x51,0xe6,0x9c,0x77,0xbe,0x99,0x23,0xda,0xeb,0x52,0x2e,0xb5,0x08,0x05,0x6c, 0xb8,0x1b,0xa3,0x69,0x8c,0xd3,0x40,0x26,0xf1,0xc4,0x9f,0x35,0xee,0x7c,0x4b,0x16]) Crypton_1_0_S1 = SBox([ 0x8d,0xb3,0x65,0xaa,0x6f,0x3a,0x99,0x03,0xdc,0xf0,0x50,0xff,0x4c,0x11,0xa6,0x46, 0xec,0xe1,0x36,0xbf,0x0b,0xa8,0xc3,0x5f,0x85,0x7a,0x96,0xf2,0x21,0x54,0x48,0x1d, 0xb7,0x09,0x68,0xcc,0xe0,0x23,0x5c,0x42,0x9a,0x57,0x75,0x95,0xa9,0xfb,0x3e,0x86, 0x4e,0x2b,0xbc,0x30,0xa1,0x61,0x7f,0xd3,0x15,0x44,0x82,0x9e,0x88,0x5a,0xef,0xf5, 0x74,0xd2,0x12,0x83,0xfe,0x5d,0xa7,0x28,0x39,0x0e,0x33,0xe9,0xc5,0xe4,0x1f,0xc8, 0xd1,0xf4,0x7b,0x41,0x16,0x18,0xbd,0x4d,0xa3,0xb6,0x0a,0x64,0x87,0xea,0xd8,0x2f, 0x38,0xa0,0xcf,0x6e,0x29,0x89,0x52,0x7c,0xf6,0xdb,0x9d,0x05,0x63,0x47,0xb4,0x92, 0x1a,0xde,0x04,0x17,0xc2,0xd5,0x08,0xe7,0xb0,0xa4,0xb9,0x4b,0x7d,0x2e,0xf3,0x69, 0x93,0xfd,0x77,0x1c,0x55,0xc6,0xac,0x26,0xc9,0x60,0xe8,0x31,0xda,0x8f,0x02,0x3b, 0x25,0x3f,0xad,0xe6,0xcb,0x34,0x73,0x91,0x56,0x19,0xdf,0x40,0x6a,0x80,0x8a,0xfc, 0x5b,0x1e,0xc1,0xf8,0x84,0xf7,0x35,0xed,0x0f,0xba,0x24,0x2a,0x10,0xce,0x51,0xe3, 0xc0,0x00,0x59,0x53,0x9f,0x94,0xee,0xb2,0x62,0xcd,0xab,0x27,0x76,0x3d,0xf9,0x0c, 0xae,0x4a,0xa2,0x0d,0x3c,0xeb,0x90,0x71,0x78,0x81,0xc4,0x5e,0x37,0x1b,0xe5,0xd7, 0x79,0x97,0xd0,0xd9,0x70,0x06,0xca,0xbe,0x2c,0x6d,0x67,0x8b,0x9c,0xb5,0x43,0x22, 0x07,0x45,0x9b,0x72,0xdd,0xfa,0x66,0x8c,0x6b,0xaf,0x49,0xb8,0xd6,0x20,0x14,0xb1, 0xe2,0x6c,0x8e,0xa5,0x32,0x4f,0x01,0x98,0xc7,0x13,0x7e,0xd4,0xbb,0xf1,0x2d,0x58]) Crypton_1_0_S2 = SBox([ 0xb1,0x72,0x76,0xbf,0xac,0xee,0x55,0x83,0xed,0xaa,0x47,0xd8,0x33,0x95,0x60,0xc4, 0x9b,0x39,0x1e,0x0c,0x0a,0x1d,0xff,0x26,0x89,0x5b,0x22,0xf1,0xd4,0x40,0xc8,0x67, 0x9d,0xa4,0x3c,0xe7,0xc6,0xb5,0xf7,0xdc,0x61,0x79,0x15,0x86,0x78,0x6e,0xeb,0x32, 0xb0,0xca,0x4f,0x23,0xd2,0xfb,0x5e,0x08,0x24,0x4d,0x8a,0x10,0x09,0x51,0xa3,0x9f, 0xf6,0x6b,0x21,0xc3,0x0d,0x38,0x99,0x1f,0x1c,0x90,0x64,0xfe,0x8b,0xa6,0x48,0xbd, 0x53,0xe1,0xea,0x57,0xae,0x84,0xb2,0x45,0x35,0x02,0x7f,0xd9,0xc7,0x2a,0xd0,0x7c, 0xc9,0x18,0x65,0x00,0x97,0x2b,0x06,0x6a,0x34,0xf3,0x2c,0x92,0xef,0xdd,0x7a,0x56, 0xa2,0x4c,0x88,0xb9,0x50,0x75,0xd3,0xe4,0x11,0xce,0x4b,0xa7,0xfd,0x3f,0xbe,0x81, 0x8e,0xd5,0x5a,0x49,0x42,0x54,0x70,0xa1,0xdf,0x87,0xab,0x7d,0xf4,0x12,0x05,0x2e, 0x27,0x0f,0xc1,0x30,0x66,0x98,0x3d,0xcb,0xb8,0xe6,0x9c,0x63,0xe3,0xbc,0x19,0xfa, 0x3a,0x2f,0x9e,0xf2,0x6f,0x1a,0x28,0x3b,0xc2,0x0e,0x03,0xc0,0xb7,0x59,0xa9,0xd7, 0x74,0x85,0xd6,0xad,0x41,0xec,0x8c,0x71,0xf0,0x93,0x5d,0xb6,0x1b,0x68,0xe5,0x44, 0x07,0xe0,0x14,0xa8,0xf9,0x73,0xcd,0x4e,0x25,0xbb,0x31,0x5f,0x4a,0xcc,0x8f,0x91, 0xde,0x6d,0x7b,0xf5,0xb3,0x29,0xa0,0x17,0x6c,0xda,0xe8,0x04,0x96,0x82,0x52,0x36, 0x43,0x5c,0xdb,0x8d,0x80,0xd1,0xe2,0xb4,0x58,0x46,0xba,0xe9,0x01,0x20,0xfc,0x13, 0x16,0xf8,0x94,0x62,0x37,0xcf,0x69,0x9a,0xaf,0x77,0xc5,0x3e,0x7e,0xa5,0x2d,0x0b]) Crypton_1_0_S3 = SBox([ 0xb1,0xf6,0x8e,0x07,0x72,0x6b,0xd5,0xe0,0x76,0x21,0x5a,0x14,0xbf,0xc3,0x49,0xa8, 0xac,0x0d,0x42,0xf9,0xee,0x38,0x54,0x73,0x55,0x99,0x70,0xcd,0x83,0x1f,0xa1,0x4e, 0xed,0x1c,0xdf,0x25,0xaa,0x90,0x87,0xbb,0x47,0x64,0xab,0x31,0xd8,0xfe,0x7d,0x5f, 0x33,0x8b,0xf4,0x4a,0x95,0xa6,0x12,0xcc,0x60,0x48,0x05,0x8f,0xc4,0xbd,0x2e,0x91, 0x9b,0x53,0x27,0xde,0x39,0xe1,0x0f,0x6d,0x1e,0xea,0xc1,0x7b,0x0c,0x57,0x30,0xf5, 0x0a,0xae,0x66,0xb3,0x1d,0x84,0x98,0x29,0xff,0xb2,0x3d,0xa0,0x26,0x45,0xcb,0x17, 0x89,0x35,0xb8,0x6c,0x5b,0x02,0xe6,0xda,0x22,0x7f,0x9c,0xe8,0xf1,0xd9,0x63,0x04, 0xd4,0xc7,0xe3,0x96,0x40,0x2a,0xbc,0x82,0xc8,0xd0,0x19,0x52,0x67,0x7c,0xfa,0x36, 0x9d,0xc9,0x3a,0x43,0xa4,0x18,0x2f,0x5c,0x3c,0x65,0x9e,0xdb,0xe7,0x00,0xf2,0x8d, 0xc6,0x97,0x6f,0x80,0xb5,0x2b,0x1a,0xd1,0xf7,0x06,0x28,0xe2,0xdc,0x6a,0x3b,0xb4, 0x61,0x34,0xc2,0x58,0x79,0xf3,0x0e,0x46,0x15,0x2c,0x03,0xba,0x86,0x92,0xc0,0xe9, 0x78,0xef,0xb7,0x01,0x6e,0xdd,0x59,0x20,0xeb,0x7a,0xa9,0xfc,0x32,0x56,0xd7,0x13, 0xb0,0xa2,0x74,0x16,0xca,0x4c,0x85,0xf8,0x4f,0x88,0xd6,0x94,0x23,0xb9,0xad,0x62, 0xd2,0x50,0x41,0x37,0xfb,0x75,0xec,0xcf,0x5e,0xd3,0x8c,0x69,0x08,0xe4,0x71,0x9a, 0x24,0x11,0xf0,0xaf,0x4d,0xce,0x93,0x77,0x8a,0x4b,0x5d,0xc5,0x10,0xa7,0xb6,0x3e, 0x09,0xfd,0x1b,0x7e,0x51,0x3f,0x68,0xa5,0xa3,0xbe,0xe5,0x2d,0x9f,0x81,0x44,0x0b]) CS_cipher = SBox([ 0x29,0xd,0x61,0x40,0x9c,0xeb,0x9e,0x8f,0x1f,0x85,0x5f,0x58,0x5b,0x1,0x39,0x86, 0x97,0x2e,0xd7,0xd6,0x35,0xae,0x17,0x16,0x21,0xb6,0x69,0x4e,0xa5,0x72,0x87,0x8, 0x3c,0x18,0xe6,0xe7,0xfa,0xad,0xb8,0x89,0xb7,0x0,0xf7,0x6f,0x73,0x84,0x11,0x63, 0x3f,0x96,0x7f,0x6e,0xbf,0x14,0x9d,0xac,0xa4,0xe,0x7e,0xf6,0x20,0x4a,0x62,0x30, 0x3,0xc5,0x4b,0x5a,0x46,0xa3,0x44,0x65,0x7d,0x4d,0x3d,0x42,0x79,0x49,0x1b,0x5c, 0xf5,0x6c,0xb5,0x94,0x54,0xff,0x56,0x57,0xb,0xf4,0x43,0xc,0x4f,0x70,0x6d,0xa, 0xe4,0x2,0x3e,0x2f,0xa2,0x47,0xe0,0xc1,0xd5,0x1a,0x95,0xa7,0x51,0x5e,0x33,0x2b, 0x5d,0xd4,0x1d,0x2c,0xee,0x75,0xec,0xdd,0x7c,0x4c,0xa6,0xb4,0x78,0x48,0x3a,0x32, 0x98,0xaf,0xc0,0xe1,0x2d,0x9,0xf,0x1e,0xb9,0x27,0x8a,0xe9,0xbd,0xe3,0x9f,0x7, 0xb1,0xea,0x92,0x93,0x53,0x6a,0x31,0x10,0x80,0xf2,0xd8,0x9b,0x4,0x36,0x6,0x8e, 0xbe,0xa9,0x64,0x45,0x38,0x1c,0x7a,0x6b,0xf3,0xa1,0xf0,0xcd,0x37,0x25,0x15,0x81, 0xfb,0x90,0xe8,0xd9,0x7b,0x52,0x19,0x28,0x26,0x88,0xfc,0xd1,0xe2,0x8c,0xa0,0x34, 0x82,0x67,0xda,0xcb,0xc7,0x41,0xe5,0xc4,0xc8,0xef,0xdb,0xc3,0xcc,0xab,0xce,0xed, 0xd0,0xbb,0xd3,0xd2,0x71,0x68,0x13,0x12,0x9a,0xb3,0xc2,0xca,0xde,0x77,0xdc,0xdf, 0x66,0x83,0xbc,0x8d,0x60,0xc6,0x22,0x23,0xb2,0x8b,0x91,0x5,0x76,0xcf,0x74,0xc9, 0xaa,0xf1,0x99,0xa8,0x59,0x50,0x3b,0x2a,0xfe,0xf9,0x24,0xb0,0xba,0xfd,0xf8,0x55]) CSA = SBox([ 0x3a,0xea,0x68,0xfe,0x33,0xe9,0x88,0x1a,0x83,0xcf,0xe1,0x7f,0xba,0xe2,0x38,0x12, 0xe8,0x27,0x61,0x95,0x0c,0x36,0xe5,0x70,0xa2,0x06,0x82,0x7c,0x17,0xa3,0x26,0x49, 0xbe,0x7a,0x6d,0x47,0xc1,0x51,0x8f,0xf3,0xcc,0x5b,0x67,0xbd,0xcd,0x18,0x08,0xc9, 0xff,0x69,0xef,0x03,0x4e,0x48,0x4a,0x84,0x3f,0xb4,0x10,0x04,0xdc,0xf5,0x5c,0xc6, 0x16,0xab,0xac,0x4c,0xf1,0x6a,0x2f,0x3c,0x3b,0xd4,0xd5,0x94,0xd0,0xc4,0x63,0x62, 0x71,0xa1,0xf9,0x4f,0x2e,0xaa,0xc5,0x56,0xe3,0x39,0x93,0xce,0x65,0x64,0xe4,0x58, 0x6c,0x19,0x42,0x79,0xdd,0xee,0x96,0xf6,0x8a,0xec,0x1e,0x85,0x53,0x45,0xde,0xbb, 0x7e,0x0a,0x9a,0x13,0x2a,0x9d,0xc2,0x5e,0x5a,0x1f,0x32,0x35,0x9c,0xa8,0x73,0x30, 0x29,0x3d,0xe7,0x92,0x87,0x1b,0x2b,0x4b,0xa5,0x57,0x97,0x40,0x15,0xe6,0xbc,0x0e, 0xeb,0xc3,0x34,0x2d,0xb8,0x44,0x25,0xa4,0x1c,0xc7,0x23,0xed,0x90,0x6e,0x50,0x00, 0x99,0x9e,0x4d,0xd9,0xda,0x8d,0x6f,0x5f,0x3e,0xd7,0x21,0x74,0x86,0xdf,0x6b,0x05, 0x8e,0x5d,0x37,0x11,0xd2,0x28,0x75,0xd6,0xa7,0x77,0x24,0xbf,0xf0,0xb0,0x02,0xb7, 0xf8,0xfc,0x81,0x09,0xb1,0x01,0x76,0x91,0x7d,0x0f,0xc8,0xa0,0xf2,0xcb,0x78,0x60, 0xd1,0xf7,0xe0,0xb5,0x98,0x22,0xb3,0x20,0x1d,0xa6,0xdb,0x7b,0x59,0x9f,0xae,0x31, 0xfb,0xd3,0xb6,0xca,0x43,0x72,0x07,0xf4,0xd8,0x41,0x14,0x55,0x0d,0x54,0x8b,0xb9, 0xad,0x46,0x0b,0xaf,0x80,0x52,0x2c,0xfa,0x8c,0x89,0x66,0xfd,0xb2,0xa9,0x9b,0xc0]) # source: http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=3672D97255B2446765DA47DA97960CDF?doi=10.1.1.118.6103&rep=rep1&type=pdf CSS = SBox([ 0x33,0x73,0x3b,0x26,0x63,0x23,0x6b,0x76,0x3e,0x7e,0x36,0x2b,0x6e,0x2e,0x66,0x7b, 0xd3,0x93,0xdb,0x06,0x43,0x03,0x4b,0x96,0xde,0x9e,0xd6,0x0b,0x4e,0x0e,0x46,0x9b, 0x57,0x17,0x5f,0x82,0xc7,0x87,0xcf,0x12,0x5a,0x1a,0x52,0x8f,0xca,0x8a,0xc2,0x1f, 0xd9,0x99,0xd1,0x00,0x49,0x09,0x41,0x90,0xd8,0x98,0xd0,0x01,0x48,0x08,0x40,0x91, 0x3d,0x7d,0x35,0x24,0x6d,0x2d,0x65,0x74,0x3c,0x7c,0x34,0x25,0x6c,0x2c,0x64,0x75, 0xdd,0x9d,0xd5,0x04,0x4d,0x0d,0x45,0x94,0xdc,0x9c,0xd4,0x05,0x4c,0x0c,0x44,0x95, 0x59,0x19,0x51,0x80,0xc9,0x89,0xc1,0x10,0x58,0x18,0x50,0x81,0xc8,0x88,0xc0,0x11, 0xd7,0x97,0xdf,0x02,0x47,0x07,0x4f,0x92,0xda,0x9a,0xd2,0x0f,0x4a,0x0a,0x42,0x9f, 0x53,0x13,0x5b,0x86,0xc3,0x83,0xcb,0x16,0x5e,0x1e,0x56,0x8b,0xce,0x8e,0xc6,0x1b, 0xb3,0xf3,0xbb,0xa6,0xe3,0xa3,0xeb,0xf6,0xbe,0xfe,0xb6,0xab,0xee,0xae,0xe6,0xfb, 0x37,0x77,0x3f,0x22,0x67,0x27,0x6f,0x72,0x3a,0x7a,0x32,0x2f,0x6a,0x2a,0x62,0x7f, 0xb9,0xf9,0xb1,0xa0,0xe9,0xa9,0xe1,0xf0,0xb8,0xf8,0xb0,0xa1,0xe8,0xa8,0xe0,0xf1, 0x5d,0x1d,0x55,0x84,0xcd,0x8d,0xc5,0x14,0x5c,0x1c,0x54,0x85,0xcc,0x8c,0xc4,0x15, 0xbd,0xfd,0xb5,0xa4,0xed,0xad,0xe5,0xf4,0xbc,0xfc,0xb4,0xa5,0xec,0xac,0xe4,0xf5, 0x39,0x79,0x31,0x20,0x69,0x29,0x61,0x70,0x38,0x78,0x30,0x21,0x68,0x28,0x60,0x71, 0xb7,0xf7,0xbf,0xa2,0xe7,0xa7,0xef,0xf2,0xba,0xfa,0xb2,0xaf,0xea,0xaa,0xe2,0xff]) DBlock = SBox([ 0x51,0x36,0x93,0x53,0xd9,0x4a,0xfc,0x58,0xe4,0x2e,0x0d,0x14,0xda,0x9d,0x91,0x69, 0xef,0x72,0x03,0xc6,0x15,0x8d,0x5c,0x62,0x3f,0xb9,0x45,0x70,0x13,0xa3,0x95,0x6f, 0x84,0xdb,0xb8,0x89,0x8a,0x6e,0xd4,0x7b,0x40,0xdc,0x9b,0x0c,0x50,0x8e,0xee,0x6a, 0x88,0x3b,0x0f,0x6b,0x85,0xd3,0x54,0xa8,0x20,0xdf,0xb5,0x1b,0x32,0x7c,0x56,0x64, 0x74,0xfa,0xc7,0x2d,0x96,0x17,0xae,0xcd,0xb4,0xf5,0x57,0x8c,0xf1,0xbc,0xd8,0xfe, 0x27,0x06,0xe1,0xa9,0x1a,0x0e,0x5b,0x08,0xf4,0x9f,0x4b,0xed,0x73,0xb7,0xac,0x76, 0x23,0xca,0x16,0xba,0xa7,0x00,0x8b,0x46,0x41,0xd5,0x7e,0xf2,0x05,0xf6,0x63,0x67, 0x61,0x8f,0x3d,0xc8,0x1c,0x5a,0xb0,0x79,0x38,0x81,0xaa,0x33,0x97,0xe6,0x2c,0x01, 0x22,0x87,0x4f,0xbe,0x24,0x71,0x35,0x9c,0xb1,0xad,0xc5,0x1d,0x80,0x3e,0x75,0xb3, 0x28,0x68,0x2a,0xa0,0xbf,0x2f,0xb2,0xc4,0xce,0x19,0xd7,0xcf,0xaf,0x02,0xa4,0xa5, 0x7a,0x39,0xd2,0x04,0xab,0xf7,0x60,0x2b,0x4c,0xec,0x4d,0x10,0x90,0x12,0xfb,0x78, 0x82,0x4e,0x37,0x47,0xd6,0xa2,0xd1,0x86,0xb6,0xc1,0xe9,0xdd,0xa1,0xf8,0x55,0xde, 0x98,0x7d,0xe5,0x30,0xfd,0xe2,0xcc,0x3a,0xea,0xd0,0x0a,0x29,0xe8,0xe3,0xeb,0xf0, 0x9a,0x5d,0x3c,0x21,0xc0,0x48,0x6d,0x1e,0xe7,0x1f,0xc9,0x44,0x34,0x18,0x83,0xf9, 0x59,0x5f,0x42,0x92,0x6c,0x11,0xa6,0x52,0xff,0x9e,0x49,0x26,0x07,0x43,0xbd,0xc3, 0x99,0xf3,0x77,0x0b,0x5e,0xcb,0x09,0x31,0xe0,0xc2,0x65,0x7f,0x25,0x94,0xbb,0x66]) E2 = SBox([ 0xe1,0x42,0x3e,0x81,0x4e,0x17,0x9e,0xfd,0xb4,0x3f,0x2c,0xda,0x31,0x1e,0xe0,0x41, 0xcc,0xf3,0x82,0x7d,0x7c,0x12,0x8e,0xbb,0xe4,0x58,0x15,0xd5,0x6f,0xe9,0x4c,0x4b, 0x35,0x7b,0x5a,0x9a,0x90,0x45,0xbc,0xf8,0x79,0xd6,0x1b,0x88,0x02,0xab,0xcf,0x64, 0x09,0x0c,0xf0,0x01,0xa4,0xb0,0xf6,0x93,0x43,0x63,0x86,0xdc,0x11,0xa5,0x83,0x8b, 0xc9,0xd0,0x19,0x95,0x6a,0xa1,0x5c,0x24,0x6e,0x50,0x21,0x80,0x2f,0xe7,0x53,0x0f, 0x91,0x22,0x04,0xed,0xa6,0x48,0x49,0x67,0xec,0xf7,0xc0,0x39,0xce,0xf2,0x2d,0xbe, 0x5d,0x1c,0xe3,0x87,0x07,0x0d,0x7a,0xf4,0xfb,0x32,0xf5,0x8c,0xdb,0x8f,0x25,0x96, 0xa8,0xea,0xcd,0x33,0x65,0x54,0x06,0x8d,0x89,0x0a,0x5e,0xd9,0x16,0x0e,0x71,0x6c, 0x0b,0xff,0x60,0xd2,0x2e,0xd3,0xc8,0x55,0xc2,0x23,0xb7,0x74,0xe2,0x9b,0xdf,0x77, 0x2b,0xb9,0x3c,0x62,0x13,0xe5,0x94,0x34,0xb1,0x27,0x84,0x9f,0xd7,0x51,0x00,0x61, 0xad,0x85,0x73,0x03,0x08,0x40,0xef,0x68,0xfe,0x97,0x1f,0xde,0xaf,0x66,0xe8,0xb8, 0xae,0xbd,0xb3,0xeb,0xc6,0x6b,0x47,0xa9,0xd8,0xa7,0x72,0xee,0x1d,0x7e,0xaa,0xb6, 0x75,0xcb,0xd4,0x30,0x69,0x20,0x7f,0x37,0x5b,0x9d,0x78,0xa3,0xf1,0x76,0xfa,0x05, 0x3d,0x3a,0x44,0x57,0x3b,0xca,0xc7,0x8a,0x18,0x46,0x9c,0xbf,0xba,0x38,0x56,0x1a, 0x92,0x4d,0x26,0x29,0xa2,0x98,0x10,0x99,0x70,0xa0,0xc5,0x28,0xc1,0x6d,0x14,0xac, 0xf9,0x5f,0x4f,0xc4,0xc3,0xd1,0xfc,0xdd,0xb2,0x59,0xe6,0xb5,0x36,0x52,0x4a,0x2a]) Enocoro = SBox([ 99,82,26,223,138,246,174,85,137,231,208,45,189,1,36,120, 27,217,227,84,200,164,236,126,171,0,156,46,145,103,55,83, 78,107,108,17,178,192,130,253,57,69,254,155,52,215,167,8, 184,154,51,198,76,29,105,161,110,62,197,10,87,244,241,131, 245,71,31,122,165,41,60,66,214,115,141,240,142,24,170,193, 32,191,230,147,81,14,247,152,221,186,106,5,72,35,109,212, 30,96,117,67,151,42,49,219,132,25,175,188,204,243,232,70, 136,172,139,228,123,213,88,54,2,177,7,114,225,220,95,47, 93,229,209,12,38,153,181,111,224,74,59,222,162,104,146,23, 202,238,169,182,3,94,211,37,251,157,97,89,6,144,116,44, 39,149,160,185,124,237,4,210,80,226,73,119,203,58,15,158, 112,22,92,239,33,179,159,13,166,201,34,148,250,75,216,101, 133,61,150,40,20,91,102,234,127,206,249,64,19,173,195,176, 242,194,56,128,207,113,11,135,77,53,86,233,100,190,28,187, 183,48,196,43,255,98,65,168,21,140,18,199,121,143,90,252, 205,9,79,125,248,134,218,16,50,118,180,163,63,68,129,235]) Fantomas = SBox([ 0x1e,0x75,0x5f,0xe1,0x99,0xfc,0x89,0x2f,0x86,0xee,0xf1,0x7b,0x23,0x52,0x10,0x94, 0x0c,0xb7,0x4d,0x67,0xd8,0x42,0xc8,0xd6,0xc4,0x6b,0xaa,0xba,0x3d,0xa5,0x00,0x33, 0x53,0x2d,0x0b,0xb8,0xda,0xa8,0xc5,0x6c,0xca,0xb6,0xa4,0x22,0x60,0x07,0x5d,0xd7, 0x4f,0xf4,0x15,0x32,0x81,0x1b,0x9c,0x8e,0x91,0x3f,0xe6,0xf9,0x70,0xe9,0x43,0x7e, 0x8d,0xf3,0xcc,0x65,0x08,0x7a,0x18,0xab,0x16,0x6a,0x77,0xfd,0xa7,0xc0,0x82,0x04, 0x9f,0x31,0xde,0xe3,0x49,0xd0,0x59,0x46,0x54,0xef,0x2e,0x3c,0xbb,0x21,0x92,0xb5, 0x55,0x3e,0x0f,0xa9,0xdc,0xb9,0xc1,0x7f,0xce,0xa6,0xb4,0x30,0x72,0x03,0x5b,0xd1, 0x4b,0xe4,0x13,0x20,0x85,0x1d,0x9a,0x8a,0x97,0x2c,0xf6,0xe8,0x62,0xf8,0x47,0x6d, 0x29,0x41,0x68,0xd5,0xac,0xcb,0xbe,0x1a,0xb0,0xdb,0xc7,0x4e,0x17,0x64,0x26,0xa0, 0x39,0x83,0x78,0x51,0xed,0x76,0xff,0xe2,0xf2,0x5c,0x9d,0x8f,0x0a,0x93,0x34,0x05, 0x25,0x58,0x7c,0xcd,0xaf,0xdf,0xb3,0x19,0xbd,0xc2,0xd2,0x56,0x14,0x71,0x2a,0xa3, 0x3a,0x80,0x61,0x44,0xf5,0x6e,0xeb,0xfb,0xe7,0x48,0x90,0x8c,0x06,0x9e,0x37,0x09, 0x98,0xe5,0xd9,0x73,0x1f,0x6f,0x0d,0xbc,0x02,0x7d,0x63,0xea,0xb1,0xd4,0x96,0x12, 0x88,0x27,0xc9,0xf7,0x5e,0xc6,0x4c,0x50,0x40,0xfa,0x3b,0x2b,0xae,0x35,0x84,0xa1, 0x01,0x69,0x5a,0xfe,0x8b,0xec,0x95,0x28,0x9b,0xf0,0xe0,0x66,0x24,0x57,0x0e,0x87, 0x1c,0xb2,0x45,0x74,0xd3,0x4a,0xcf,0xdd,0xc3,0x79,0xa2,0xbf,0x36,0xad,0x11,0x38]) FLY = SBox([ 0x00,0x9b,0xc2,0x15,0x5d,0x84,0x4c,0xd1,0x67,0x38,0xef,0xb0,0x7e,0x2b,0xf6,0xa3, 0xb9,0xaa,0x36,0x78,0x2f,0x6e,0xe3,0xf7,0x12,0x5c,0x9a,0xd4,0x89,0xcd,0x01,0x45, 0x2c,0x63,0x44,0xde,0x02,0x96,0x39,0x70,0xba,0xe4,0x18,0x57,0xa1,0xf5,0x8b,0xce, 0x51,0x87,0xed,0xff,0xb5,0xa8,0xca,0x1b,0xdf,0x90,0x6c,0x32,0x46,0x03,0x7d,0x29, 0xd5,0xf2,0x20,0x5b,0xcc,0x31,0x04,0xbd,0xa6,0x41,0x8e,0x79,0xea,0x9f,0x68,0x1c, 0x48,0xe6,0x69,0x8a,0x13,0x77,0x9e,0xaf,0xf3,0x05,0xcb,0x2d,0xb4,0xd0,0x37,0x52, 0xc4,0x3e,0x93,0xac,0x40,0xe9,0x22,0x56,0x7b,0x8d,0xf1,0x06,0x17,0x62,0xbf,0xda, 0x1d,0x7f,0x07,0xb1,0xdb,0xfa,0x65,0x88,0x2e,0xc9,0xa5,0x43,0x58,0x3c,0xe0,0x94, 0x76,0x21,0xab,0xfd,0x6a,0x3f,0xb7,0xe2,0xdd,0x4f,0x53,0x8c,0xc0,0x19,0x95,0x08, 0x83,0xc5,0x4e,0x09,0x14,0x50,0xd8,0x9c,0xf4,0xee,0x27,0x61,0x3b,0x7a,0xa2,0xb6, 0xfe,0xa9,0x81,0xc6,0xe8,0xbc,0x1f,0x5a,0x35,0x72,0x99,0x0a,0xd3,0x47,0x24,0x6d, 0x0b,0x4d,0x75,0x23,0x97,0xd2,0x60,0x34,0xc8,0x16,0xa0,0xbb,0xfc,0xe1,0x5e,0x8f, 0xe7,0x98,0x1a,0x64,0xae,0x4b,0x71,0x85,0x0c,0xb3,0x3d,0xcf,0x55,0x28,0xd9,0xf0, 0xb2,0xdc,0x5f,0x30,0xf9,0x0d,0x26,0xc3,0x91,0xa7,0x74,0x1e,0x82,0x66,0x4a,0xeb, 0x6f,0x10,0xb8,0xd7,0x86,0x73,0xfb,0x0e,0x59,0x2a,0x42,0xe5,0x9d,0xa4,0x33,0xc7, 0x3a,0x54,0xec,0x92,0xc1,0x25,0xad,0x49,0x80,0x6b,0xd6,0xf8,0x0f,0xbe,0x7c,0x11]) Fox = SBox([ 0x5D,0xDE,0x00,0xB7,0xD3,0xCA,0x3C,0x0D,0xC3,0xF8,0xCB,0x8D,0x76,0x89,0xAA,0x12, 0x88,0x22,0x4F,0xDB,0x6D,0x47,0xE4,0x4C,0x78,0x9A,0x49,0x93,0xC4,0xC0,0x86,0x13, 0xA9,0x20,0x53,0x1C,0x4E,0xCF,0x35,0x39,0xB4,0xA1,0x54,0x64,0x03,0xC7,0x85,0x5C, 0x5B,0xCD,0xD8,0x72,0x96,0x42,0xB8,0xE1,0xA2,0x60,0xEF,0xBD,0x02,0xAF,0x8C,0x73, 0x7C,0x7F,0x5E,0xF9,0x65,0xE6,0xEB,0xAD,0x5A,0xA5,0x79,0x8E,0x15,0x30,0xEC,0xA4, 0xC2,0x3E,0xE0,0x74,0x51,0xFB,0x2D,0x6E,0x94,0x4D,0x55,0x34,0xAE,0x52,0x7E,0x9D, 0x4A,0xF7,0x80,0xF0,0xD0,0x90,0xA7,0xE8,0x9F,0x50,0xD5,0xD1,0x98,0xCC,0xA0,0x17, 0xF4,0xB6,0xC1,0x28,0x5F,0x26,0x01,0xAB,0x25,0x38,0x82,0x7D,0x48,0xFC,0x1B,0xCE, 0x3F,0x6B,0xE2,0x67,0x66,0x43,0x59,0x19,0x84,0x3D,0xF5,0x2F,0xC9,0xBC,0xD9,0x95, 0x29,0x41,0xDA,0x1A,0xB0,0xE9,0x69,0xD2,0x7B,0xD7,0x11,0x9B,0x33,0x8A,0x23,0x09, 0xD4,0x71,0x44,0x68,0x6F,0xF2,0x0E,0xDF,0x87,0xDC,0x83,0x18,0x6A,0xEE,0x99,0x81, 0x62,0x36,0x2E,0x7A,0xFE,0x45,0x9C,0x75,0x91,0x0C,0x0F,0xE7,0xF6,0x14,0x63,0x1D, 0x0B,0x8B,0xB3,0xF3,0xB2,0x3B,0x08,0x4B,0x10,0xA6,0x32,0xB9,0xA8,0x92,0xF1,0x56, 0xDD,0x21,0xBF,0x04,0xBE,0xD6,0xFD,0x77,0xEA,0x3A,0xC8,0x8F,0x57,0x1E,0xFA,0x2B, 0x58,0xC5,0x27,0xAC,0xE3,0xED,0x97,0xBB,0x46,0x05,0x40,0x31,0xE5,0x37,0x2C,0x9E, 0x0A,0xB1,0xB5,0x06,0x6C,0x1F,0xA3,0x2A,0x70,0xFF,0xBA,0x07,0x24,0x16,0xC6,0x61]) Iceberg = SBox([ 0x24,0xc1,0x38,0x30,0xe7,0x57,0xdf,0x20,0x3e,0x99,0x1a,0x34,0xca,0xd6,0x52,0xfd, 0x40,0x6c,0xd3,0x3d,0x4a,0x59,0xf8,0x77,0xfb,0x61,0x0a,0x56,0xb9,0xd2,0xfc,0xf1, 0x07,0xf5,0x93,0xcd,0x00,0xb6,0x62,0xa7,0x63,0xfe,0x44,0xbd,0x5f,0x92,0x6b,0x68, 0x03,0x4e,0xa2,0x97,0x0b,0x60,0x83,0xa3,0x02,0xe5,0x45,0x67,0xf4,0x13,0x08,0x8b, 0x10,0xce,0xbe,0xb4,0x2a,0x3a,0x96,0x84,0xc8,0x9f,0x14,0xc0,0xc4,0x6f,0x31,0xd9, 0xab,0xae,0x0e,0x64,0x7c,0xda,0x1b,0x05,0xa8,0x15,0xa5,0x90,0x94,0x85,0x71,0x2c, 0x35,0x19,0x26,0x28,0x53,0xe2,0x7f,0x3b,0x2f,0xa9,0xcc,0x2e,0x11,0x76,0xed,0x4d, 0x87,0x5e,0xc2,0xc7,0x80,0xb0,0x6d,0x17,0xb2,0xff,0xe4,0xb7,0x54,0x9d,0xb8,0x66, 0x74,0x9c,0xdb,0x36,0x47,0x5d,0xde,0x70,0xd5,0x91,0xaa,0x3f,0xc9,0xd8,0xf3,0xf2, 0x5b,0x89,0x2d,0x22,0x5c,0xe1,0x46,0x33,0xe6,0x09,0xbc,0xe8,0x81,0x7d,0xe9,0x49, 0xe0,0xb1,0x32,0x37,0xea,0x5a,0xf6,0x27,0x58,0x69,0x8a,0x50,0xba,0xdd,0x51,0xf9, 0x75,0xa1,0x78,0xd0,0x43,0xf7,0x25,0x7b,0x7e,0x1c,0xac,0xd4,0x9a,0x2b,0x42,0xe3, 0x4b,0x01,0x72,0xd7,0x4c,0xfa,0xeb,0x73,0x48,0x8c,0x0c,0xf0,0x6a,0x23,0x41,0xec, 0xb3,0xef,0x1d,0x12,0xbb,0x88,0x0d,0xc3,0x8d,0x4f,0x55,0x82,0xee,0xad,0x86,0x06, 0xa0,0x95,0x65,0xbf,0x7a,0x39,0x98,0x04,0x9b,0x9e,0xa4,0xc6,0xcf,0x6e,0xdc,0xd1, 0xcb,0x1f,0x8f,0x8e,0x3c,0x21,0xa6,0xb5,0x16,0xaf,0xc5,0x18,0x1e,0x0f,0x29,0x79]) Iraqi = SBox([ 173,84,240,67,1,53,254,36,41,172,115,109,223,199,152,189,90,46, 149,193,218,130,250,40,203,4,35,237,236,246,213,143,169,176,48, 23,61,206,69,34,97,155,4,109,183,220,42,64,21,123,29,233,253, 105,183,209,1,191,113,12,46,7,8,183,166,199,166,7,78,37,135, 252,174,84,140,164,152,94,22,185,59,68,181,60,176,67,51,25,28, 190,138,198,44,90,92,221,149,175,186,25,49,210,50,237,41,207, 31,226,114,121,230,15,58,25,142,58,98,232,59,3,189,28,8,116, 131,185,78,250,239,33,116,173,94,45,104,62,122,179,18,150,246, 250,17,8,79,157,225,238,47,10,133,58,8,126,82,68,153,141,2,158, 204,50,130,53,59,32,243,160,172,35,24,107,35,115,228,143,28, 224,77,55,25,28,120,89,186,152,49,84,117,180,30,138,134,77,182, 157,61,230,22,149,54,15,110,32,213,155,106,78,16,23,89,140,158, 169,96,136,186,104,30,199,67,35,218,159,210,109,28,238,33,150, 173,180,247,201,83,150,105,164,228,59,207,101,221,99,52,120, 199,31,6,144,202,215,209,49,42,195]) iScream = SBox([ 0x00,0x85,0x65,0xD2,0x5B,0xFF,0x7A,0xCE,0x4D,0xE2,0x2C,0x36,0x92,0x15,0xBD,0xAD, 0x57,0xF3,0x37,0x2D,0x88,0x0D,0xAC,0xBC,0x18,0x9F,0x7E,0xCA,0x41,0xEE,0x61,0xD6, 0x59,0xEC,0x78,0xD4,0x47,0xF9,0x26,0xA3,0x90,0x8B,0xBF,0x30,0x0A,0x13,0x6F,0xC0, 0x2B,0xAE,0x91,0x8A,0xD8,0x74,0x0B,0x12,0xCC,0x63,0xFD,0x43,0xB2,0x3D,0xE8,0x5D, 0xB6,0x1C,0x83,0x3B,0xC8,0x45,0x9D,0x24,0x52,0xDD,0xE4,0xF4,0xAB,0x08,0x77,0x6D, 0xF5,0xE5,0x48,0xC5,0x6C,0x76,0xBA,0x10,0x99,0x20,0xA7,0x04,0x87,0x3F,0xD0,0x5F, 0xA5,0x1E,0x9B,0x39,0xB0,0x02,0xEA,0x67,0xC6,0xDF,0x71,0xF6,0x54,0x4F,0x8D,0x2E, 0xE7,0x6A,0xC7,0xDE,0x35,0x97,0x55,0x4E,0x22,0x81,0x06,0xB4,0x7C,0xFB,0x1A,0xA1, 0xD5,0x79,0xFC,0x42,0x84,0x01,0xE9,0x5C,0x14,0x93,0x33,0x29,0xC1,0x6E,0xA8,0xB8, 0x28,0x32,0x0C,0x89,0xB9,0xA9,0xD9,0x75,0xED,0x58,0xCD,0x62,0xF8,0x46,0x9E,0x19, 0xCB,0x7F,0xA2,0x27,0xD7,0x60,0xFE,0x5A,0x8E,0x95,0xE3,0x4C,0x16,0x0F,0x31,0xBE, 0x64,0xD3,0x3C,0xB3,0x7B,0xCF,0x40,0xEF,0x8F,0x94,0x56,0xF2,0x17,0x0E,0xAF,0x2A, 0x2F,0x8C,0xF1,0xE1,0xDC,0x53,0x68,0x72,0x44,0xC9,0x1B,0xA0,0x38,0x9A,0x07,0xB5, 0x5E,0xD1,0x03,0xB1,0x23,0x80,0x1F,0xA4,0x34,0x96,0xE0,0xF0,0xC4,0x49,0x73,0x69, 0xDA,0xC3,0x09,0xAA,0x4A,0x51,0xF7,0x70,0x3E,0x86,0x66,0xEB,0x21,0x98,0x1D,0xB7, 0xDB,0xC2,0xBB,0x11,0x4B,0x50,0x6B,0xE6,0x9C,0x25,0xFA,0x7D,0x82,0x3A,0xA6,0x05]) Kalyna_pi0 = SBox([ 0xa8,0x43,0x5f,0x6,0x6b,0x75,0x6c,0x59,0x71,0xdf,0x87,0x95,0x17,0xf0,0xd8,0x9, 0x6d,0xf3,0x1d,0xcb,0xc9,0x4d,0x2c,0xaf,0x79,0xe0,0x97,0xfd,0x6f,0x4b,0x45,0x39, 0x3e,0xdd,0xa3,0x4f,0xb4,0xb6,0x9a,0xe,0x1f,0xbf,0x15,0xe1,0x49,0xd2,0x93,0xc6, 0x92,0x72,0x9e,0x61,0xd1,0x63,0xfa,0xee,0xf4,0x19,0xd5,0xad,0x58,0xa4,0xbb,0xa1, 0xdc,0xf2,0x83,0x37,0x42,0xe4,0x7a,0x32,0x9c,0xcc,0xab,0x4a,0x8f,0x6e,0x4,0x27, 0x2e,0xe7,0xe2,0x5a,0x96,0x16,0x23,0x2b,0xc2,0x65,0x66,0xf,0xbc,0xa9,0x47,0x41, 0x34,0x48,0xfc,0xb7,0x6a,0x88,0xa5,0x53,0x86,0xf9,0x5b,0xdb,0x38,0x7b,0xc3,0x1e, 0x22,0x33,0x24,0x28,0x36,0xc7,0xb2,0x3b,0x8e,0x77,0xba,0xf5,0x14,0x9f,0x8,0x55, 0x9b,0x4c,0xfe,0x60,0x5c,0xda,0x18,0x46,0xcd,0x7d,0x21,0xb0,0x3f,0x1b,0x89,0xff, 0xeb,0x84,0x69,0x3a,0x9d,0xd7,0xd3,0x70,0x67,0x40,0xb5,0xde,0x5d,0x30,0x91,0xb1, 0x78,0x11,0x1,0xe5,0x0,0x68,0x98,0xa0,0xc5,0x2,0xa6,0x74,0x2d,0xb,0xa2,0x76, 0xb3,0xbe,0xce,0xbd,0xae,0xe9,0x8a,0x31,0x1c,0xec,0xf1,0x99,0x94,0xaa,0xf6,0x26, 0x2f,0xef,0xe8,0x8c,0x35,0x3,0xd4,0x7f,0xfb,0x5,0xc1,0x5e,0x90,0x20,0x3d,0x82, 0xf7,0xea,0xa,0xd,0x7e,0xf8,0x50,0x1a,0xc4,0x7,0x57,0xb8,0x3c,0x62,0xe3,0xc8, 0xac,0x52,0x64,0x10,0xd0,0xd9,0x13,0xc,0x12,0x29,0x51,0xb9,0xcf,0xd6,0x73,0x8d, 0x81,0x54,0xc0,0xed,0x4e,0x44,0xa7,0x2a,0x85,0x25,0xe6,0xca,0x7c,0x8b,0x56,0x80]) Kalyna_pi1 = SBox([ 0xce,0xbb,0xeb,0x92,0xea,0xcb,0x13,0xc1,0xe9,0x3a,0xd6,0xb2,0xd2,0x90,0x17,0xf8, 0x42,0x15,0x56,0xb4,0x65,0x1c,0x88,0x43,0xc5,0x5c,0x36,0xba,0xf5,0x57,0x67,0x8d, 0x31,0xf6,0x64,0x58,0x9e,0xf4,0x22,0xaa,0x75,0xf,0x2,0xb1,0xdf,0x6d,0x73,0x4d, 0x7c,0x26,0x2e,0xf7,0x8,0x5d,0x44,0x3e,0x9f,0x14,0xc8,0xae,0x54,0x10,0xd8,0xbc, 0x1a,0x6b,0x69,0xf3,0xbd,0x33,0xab,0xfa,0xd1,0x9b,0x68,0x4e,0x16,0x95,0x91,0xee, 0x4c,0x63,0x8e,0x5b,0xcc,0x3c,0x19,0xa1,0x81,0x49,0x7b,0xd9,0x6f,0x37,0x60,0xca, 0xe7,0x2b,0x48,0xfd,0x96,0x45,0xfc,0x41,0x12,0xd,0x79,0xe5,0x89,0x8c,0xe3,0x20, 0x30,0xdc,0xb7,0x6c,0x4a,0xb5,0x3f,0x97,0xd4,0x62,0x2d,0x6,0xa4,0xa5,0x83,0x5f, 0x2a,0xda,0xc9,0x0,0x7e,0xa2,0x55,0xbf,0x11,0xd5,0x9c,0xcf,0xe,0xa,0x3d,0x51, 0x7d,0x93,0x1b,0xfe,0xc4,0x47,0x9,0x86,0xb,0x8f,0x9d,0x6a,0x7,0xb9,0xb0,0x98, 0x18,0x32,0x71,0x4b,0xef,0x3b,0x70,0xa0,0xe4,0x40,0xff,0xc3,0xa9,0xe6,0x78,0xf9, 0x8b,0x46,0x80,0x1e,0x38,0xe1,0xb8,0xa8,0xe0,0xc,0x23,0x76,0x1d,0x25,0x24,0x5, 0xf1,0x6e,0x94,0x28,0x9a,0x84,0xe8,0xa3,0x4f,0x77,0xd3,0x85,0xe2,0x52,0xf2,0x82, 0x50,0x7a,0x2f,0x74,0x53,0xb3,0x61,0xaf,0x39,0x35,0xde,0xcd,0x1f,0x99,0xac,0xad, 0x72,0x2c,0xdd,0xd0,0x87,0xbe,0x5e,0xa6,0xec,0x4,0xc6,0x3,0x34,0xfb,0xdb,0x59, 0xb6,0xc2,0x1,0xf0,0x5a,0xed,0xa7,0x66,0x21,0x7f,0x8a,0x27,0xc7,0xc0,0x29,0xd7]) Kalyna_pi2 = SBox([ 0x93,0xd9,0x9a,0xb5,0x98,0x22,0x45,0xfc,0xba,0x6a,0xdf,0x2,0x9f,0xdc,0x51,0x59, 0x4a,0x17,0x2b,0xc2,0x94,0xf4,0xbb,0xa3,0x62,0xe4,0x71,0xd4,0xcd,0x70,0x16,0xe1, 0x49,0x3c,0xc0,0xd8,0x5c,0x9b,0xad,0x85,0x53,0xa1,0x7a,0xc8,0x2d,0xe0,0xd1,0x72, 0xa6,0x2c,0xc4,0xe3,0x76,0x78,0xb7,0xb4,0x9,0x3b,0xe,0x41,0x4c,0xde,0xb2,0x90, 0x25,0xa5,0xd7,0x3,0x11,0x0,0xc3,0x2e,0x92,0xef,0x4e,0x12,0x9d,0x7d,0xcb,0x35, 0x10,0xd5,0x4f,0x9e,0x4d,0xa9,0x55,0xc6,0xd0,0x7b,0x18,0x97,0xd3,0x36,0xe6,0x48, 0x56,0x81,0x8f,0x77,0xcc,0x9c,0xb9,0xe2,0xac,0xb8,0x2f,0x15,0xa4,0x7c,0xda,0x38, 0x1e,0xb,0x5,0xd6,0x14,0x6e,0x6c,0x7e,0x66,0xfd,0xb1,0xe5,0x60,0xaf,0x5e,0x33, 0x87,0xc9,0xf0,0x5d,0x6d,0x3f,0x88,0x8d,0xc7,0xf7,0x1d,0xe9,0xec,0xed,0x80,0x29, 0x27,0xcf,0x99,0xa8,0x50,0xf,0x37,0x24,0x28,0x30,0x95,0xd2,0x3e,0x5b,0x40,0x83, 0xb3,0x69,0x57,0x1f,0x7,0x1c,0x8a,0xbc,0x20,0xeb,0xce,0x8e,0xab,0xee,0x31,0xa2, 0x73,0xf9,0xca,0x3a,0x1a,0xfb,0xd,0xc1,0xfe,0xfa,0xf2,0x6f,0xbd,0x96,0xdd,0x43, 0x52,0xb6,0x8,0xf3,0xae,0xbe,0x19,0x89,0x32,0x26,0xb0,0xea,0x4b,0x64,0x84,0x82, 0x6b,0xf5,0x79,0xbf,0x1,0x5f,0x75,0x63,0x1b,0x23,0x3d,0x68,0x2a,0x65,0xe8,0x91, 0xf6,0xff,0x13,0x58,0xf1,0x47,0xa,0x7f,0xc5,0xa7,0xe7,0x61,0x5a,0x6,0x46,0x44, 0x42,0x4,0xa0,0xdb,0x39,0x86,0x54,0xaa,0x8c,0x34,0x21,0x8b,0xf8,0xc,0x74,0x67]) Kalyna_pi3 = SBox([ 0x68,0x8d,0xca,0x4d,0x73,0x4b,0x4e,0x2a,0xd4,0x52,0x26,0xb3,0x54,0x1e,0x19,0x1f, 0x22,0x3,0x46,0x3d,0x2d,0x4a,0x53,0x83,0x13,0x8a,0xb7,0xd5,0x25,0x79,0xf5,0xbd, 0x58,0x2f,0xd,0x2,0xed,0x51,0x9e,0x11,0xf2,0x3e,0x55,0x5e,0xd1,0x16,0x3c,0x66, 0x70,0x5d,0xf3,0x45,0x40,0xcc,0xe8,0x94,0x56,0x8,0xce,0x1a,0x3a,0xd2,0xe1,0xdf, 0xb5,0x38,0x6e,0xe,0xe5,0xf4,0xf9,0x86,0xe9,0x4f,0xd6,0x85,0x23,0xcf,0x32,0x99, 0x31,0x14,0xae,0xee,0xc8,0x48,0xd3,0x30,0xa1,0x92,0x41,0xb1,0x18,0xc4,0x2c,0x71, 0x72,0x44,0x15,0xfd,0x37,0xbe,0x5f,0xaa,0x9b,0x88,0xd8,0xab,0x89,0x9c,0xfa,0x60, 0xea,0xbc,0x62,0xc,0x24,0xa6,0xa8,0xec,0x67,0x20,0xdb,0x7c,0x28,0xdd,0xac,0x5b, 0x34,0x7e,0x10,0xf1,0x7b,0x8f,0x63,0xa0,0x5,0x9a,0x43,0x77,0x21,0xbf,0x27,0x9, 0xc3,0x9f,0xb6,0xd7,0x29,0xc2,0xeb,0xc0,0xa4,0x8b,0x8c,0x1d,0xfb,0xff,0xc1,0xb2, 0x97,0x2e,0xf8,0x65,0xf6,0x75,0x7,0x4,0x49,0x33,0xe4,0xd9,0xb9,0xd0,0x42,0xc7, 0x6c,0x90,0x0,0x8e,0x6f,0x50,0x1,0xc5,0xda,0x47,0x3f,0xcd,0x69,0xa2,0xe2,0x7a, 0xa7,0xc6,0x93,0xf,0xa,0x6,0xe6,0x2b,0x96,0xa3,0x1c,0xaf,0x6a,0x12,0x84,0x39, 0xe7,0xb0,0x82,0xf7,0xfe,0x9d,0x87,0x5c,0x81,0x35,0xde,0xb4,0xa5,0xfc,0x80,0xef, 0xcb,0xbb,0x6b,0x76,0xba,0x5a,0x7d,0x78,0xb,0x95,0xe3,0xad,0x74,0x98,0x3b,0x36, 0x64,0x6d,0xdc,0xf0,0x59,0xa9,0x4c,0x17,0x7f,0x91,0xb8,0xc9,0x57,0x1b,0xe0,0x61]) Khazad = SBox([ 0xba,0x54,0x2f,0x74,0x53,0xd3,0xd2,0x4d,0x50,0xac,0x8d,0xbf,0x70,0x52,0x9a,0x4c, 0xea,0xd5,0x97,0xd1,0x33,0x51,0x5b,0xa6,0xde,0x48,0xa8,0x99,0xdb,0x32,0xb7,0xfc, 0xe3,0x9e,0x91,0x9b,0xe2,0xbb,0x41,0x6e,0xa5,0xcb,0x6b,0x95,0xa1,0xf3,0xb1,0x02, 0xcc,0xc4,0x1d,0x14,0xc3,0x63,0xda,0x5d,0x5f,0xdc,0x7d,0xcd,0x7f,0x5a,0x6c,0x5c, 0xf7,0x26,0xff,0xed,0xe8,0x9d,0x6f,0x8e,0x19,0xa0,0xf0,0x89,0x0f,0x07,0xaf,0xfb, 0x08,0x15,0x0d,0x04,0x01,0x64,0xdf,0x76,0x79,0xdd,0x3d,0x16,0x3f,0x37,0x6d,0x38, 0xb9,0x73,0xe9,0x35,0x55,0x71,0x7b,0x8c,0x72,0x88,0xf6,0x2a,0x3e,0x5e,0x27,0x46, 0x0c,0x65,0x68,0x61,0x03,0xc1,0x57,0xd6,0xd9,0x58,0xd8,0x66,0xd7,0x3a,0xc8,0x3c, 0xfa,0x96,0xa7,0x98,0xec,0xb8,0xc7,0xae,0x69,0x4b,0xab,0xa9,0x67,0x0a,0x47,0xf2, 0xb5,0x22,0xe5,0xee,0xbe,0x2b,0x81,0x12,0x83,0x1b,0x0e,0x23,0xf5,0x45,0x21,0xce, 0x49,0x2c,0xf9,0xe6,0xb6,0x28,0x17,0x82,0x1a,0x8b,0xfe,0x8a,0x09,0xc9,0x87,0x4e, 0xe1,0x2e,0xe4,0xe0,0xeb,0x90,0xa4,0x1e,0x85,0x60,0x00,0x25,0xf4,0xf1,0x94,0x0b, 0xe7,0x75,0xef,0x34,0x31,0xd4,0xd0,0x86,0x7e,0xad,0xfd,0x29,0x30,0x3b,0x9f,0xf8, 0xc6,0x13,0x06,0x05,0xc5,0x11,0x77,0x7c,0x7a,0x78,0x36,0x1c,0x39,0x59,0x18,0x56, 0xb3,0xb0,0x24,0x20,0xb2,0x92,0xa3,0xc0,0x44,0x62,0x10,0xb4,0x84,0x43,0x93,0xc2, 0x4a,0xbd,0x8f,0x2d,0xbc,0x9c,0x6a,0x40,0xcf,0xa2,0x80,0x4f,0x1f,0xca,0xaa,0x42]) Kuznyechik = SBox([ 0xFC,0xEE,0xDD,0x11,0xCF,0x6E,0x31,0x16,0xFB,0xC4,0xFA,0xDA,0x23,0xC5,0x04,0x4D, 0xE9,0x77,0xF0,0xDB,0x93,0x2E,0x99,0xBA,0x17,0x36,0xF1,0xBB,0x14,0xCD,0x5F,0xC1, 0xF9,0x18,0x65,0x5A,0xE2,0x5C,0xEF,0x21,0x81,0x1C,0x3C,0x42,0x8B,0x01,0x8E,0x4F, 0x05,0x84,0x02,0xAE,0xE3,0x6A,0x8F,0xA0,0x06,0x0B,0xED,0x98,0x7F,0xD4,0xD3,0x1F, 0xEB,0x34,0x2C,0x51,0xEA,0xC8,0x48,0xAB,0xF2,0x2A,0x68,0xA2,0xFD,0x3A,0xCE,0xCC, 0xB5,0x70,0x0E,0x56,0x08,0x0C,0x76,0x12,0xBF,0x72,0x13,0x47,0x9C,0xB7,0x5D,0x87, 0x15,0xA1,0x96,0x29,0x10,0x7B,0x9A,0xC7,0xF3,0x91,0x78,0x6F,0x9D,0x9E,0xB2,0xB1, 0x32,0x75,0x19,0x3D,0xFF,0x35,0x8A,0x7E,0x6D,0x54,0xC6,0x80,0xC3,0xBD,0x0D,0x57, 0xDF,0xF5,0x24,0xA9,0x3E,0xA8,0x43,0xC9,0xD7,0x79,0xD6,0xF6,0x7C,0x22,0xB9,0x03, 0xE0,0x0F,0xEC,0xDE,0x7A,0x94,0xB0,0xBC,0xDC,0xE8,0x28,0x50,0x4E,0x33,0x0A,0x4A, 0xA7,0x97,0x60,0x73,0x1E,0x00,0x62,0x44,0x1A,0xB8,0x38,0x82,0x64,0x9F,0x26,0x41, 0xAD,0x45,0x46,0x92,0x27,0x5E,0x55,0x2F,0x8C,0xA3,0xA5,0x7D,0x69,0xD5,0x95,0x3B, 0x07,0x58,0xB3,0x40,0x86,0xAC,0x1D,0xF7,0x30,0x37,0x6B,0xE4,0x88,0xD9,0xE7,0x89, 0xE1,0x1B,0x83,0x49,0x4C,0x3F,0xF8,0xFE,0x8D,0x53,0xAA,0x90,0xCA,0xD8,0x85,0x61, 0x20,0x71,0x67,0xA4,0x2D,0x2B,0x09,0x5B,0xCB,0x9B,0x25,0xD0,0xBE,0xE5,0x6C,0x52, 0x59,0xA6,0x74,0xD2,0xE6,0xF4,0xB4,0xC0,0xD1,0x66,0xAF,0xC2,0x39,0x4B,0x63,0xB6]) Kuznechik = Kuznyechik Streebog = Kuznyechik Stribog = Kuznyechik Lilliput_AE = SBox([ 0x20, 0x00, 0xB2, 0x85, 0x3B, 0x35, 0xA6, 0xA4, 0x30, 0xE4, 0x6A, 0x2C, 0xFF, 0x59, 0xE2, 0x0E, 0xF8, 0x1E, 0x7A, 0x80, 0x15, 0xBD, 0x3E, 0xB1, 0xE8, 0xF3, 0xA2, 0xC2, 0xDA, 0x51, 0x2A, 0x10, 0x21, 0x01, 0x23, 0x78, 0x5C, 0x24, 0x27, 0xB5, 0x37, 0xC7, 0x2B, 0x1F, 0xAE, 0x0A, 0x77, 0x5F, 0x6F, 0x09, 0x9D, 0x81, 0x04, 0x5A, 0x29, 0xDC, 0x39, 0x9C, 0x05, 0x57, 0x97, 0x74, 0x79, 0x17, 0x44, 0xC6, 0xE6, 0xE9, 0xDD, 0x41, 0xF2, 0x8A, 0x54, 0xCA, 0x6E, 0x4A, 0xE1, 0xAD, 0xB6, 0x88, 0x1C, 0x98, 0x7E, 0xCE, 0x63, 0x49, 0x3A, 0x5D, 0x0C, 0xEF, 0xF6, 0x34, 0x56, 0x25, 0x2E, 0xD6, 0x67, 0x75, 0x55, 0x76, 0xB8, 0xD2, 0x61, 0xD9, 0x71, 0x8B, 0xCD, 0x0B, 0x72, 0x6C, 0x31, 0x4B, 0x69, 0xFD, 0x7B, 0x6D, 0x60, 0x3C, 0x2F, 0x62, 0x3F, 0x22, 0x73, 0x13, 0xC9, 0x82, 0x7F, 0x53, 0x32, 0x12, 0xA0, 0x7C, 0x02, 0x87, 0x84, 0x86, 0x93, 0x4E, 0x68, 0x46, 0x8D, 0xC3, 0xDB, 0xEC, 0x9B, 0xB7, 0x89, 0x92, 0xA7, 0xBE, 0x3D, 0xD8, 0xEA, 0x50, 0x91, 0xF1, 0x33, 0x38, 0xE0, 0xA9, 0xA3, 0x83, 0xA1, 0x1B, 0xCF, 0x06, 0x95, 0x07, 0x9E, 0xED, 0xB9, 0xF5, 0x4C, 0xC0, 0xF4, 0x2D, 0x16, 0xFA, 0xB4, 0x03, 0x26, 0xB3, 0x90, 0x4F, 0xAB, 0x65, 0xFC, 0xFE, 0x14, 0xF7, 0xE3, 0x94, 0xEE, 0xAC, 0x8C, 0x1A, 0xDE, 0xCB, 0x28, 0x40, 0x7D, 0xC8, 0xC4, 0x48, 0x6B, 0xDF, 0xA5, 0x52, 0xE5, 0xFB, 0xD7, 0x64, 0xF9, 0xF0, 0xD3, 0x5E, 0x66, 0x96, 0x8F, 0x1D, 0x45, 0x36, 0xCC, 0xC5, 0x4D, 0x9F, 0xBF, 0x0F, 0xD1, 0x08, 0xEB, 0x43, 0x42, 0x19, 0xE7, 0x99, 0xA8, 0x8E, 0x58, 0xC1, 0x9A, 0xD4, 0x18, 0x47, 0xAA, 0xAF, 0xBC, 0x5B, 0xD5, 0x11, 0xD0, 0xB0, 0x70, 0xBB, 0x0D, 0xBA]) #source: https://crypto.stackexchange.com/questions/11935/how-is-the-md2-hash-function-s-table-constructed-from-pi # structure: pseudo-random, derived from the digits of pi MD2 = SBox([ 0x29,0x2E,0x43,0xC9,0xA2,0xD8,0x7C,0x01,0x3D,0x36,0x54,0xA1,0xEC,0xF0,0x06,0x13, 0x62,0xA7,0x05,0xF3,0xC0,0xC7,0x73,0x8C,0x98,0x93,0x2B,0xD9,0xBC,0x4C,0x82,0xCA, 0x1E,0x9B,0x57,0x3C,0xFD,0xD4,0xE0,0x16,0x67,0x42,0x6F,0x18,0x8A,0x17,0xE5,0x12, 0xBE,0x4E,0xC4,0xD6,0xDA,0x9E,0xDE,0x49,0xA0,0xFB,0xF5,0x8E,0xBB,0x2F,0xEE,0x7A, 0xA9,0x68,0x79,0x91,0x15,0xB2,0x07,0x3F,0x94,0xC2,0x10,0x89,0x0B,0x22,0x5F,0x21, 0x80,0x7F,0x5D,0x9A,0x5A,0x90,0x32,0x27,0x35,0x3E,0xCC,0xE7,0xBF,0xF7,0x97,0x03, 0xFF,0x19,0x30,0xB3,0x48,0xA5,0xB5,0xD1,0xD7,0x5E,0x92,0x2A,0xAC,0x56,0xAA,0xC6, 0x4F,0xB8,0x38,0xD2,0x96,0xA4,0x7D,0xB6,0x76,0xFC,0x6B,0xE2,0x9C,0x74,0x04,0xF1, 0x45,0x9D,0x70,0x59,0x64,0x71,0x87,0x20,0x86,0x5B,0xCF,0x65,0xE6,0x2D,0xA8,0x02, 0x1B,0x60,0x25,0xAD,0xAE,0xB0,0xB9,0xF6,0x1C,0x46,0x61,0x69,0x34,0x40,0x7E,0x0F, 0x55,0x47,0xA3,0x23,0xDD,0x51,0xAF,0x3A,0xC3,0x5C,0xF9,0xCE,0xBA,0xC5,0xEA,0x26, 0x2C,0x53,0x0D,0x6E,0x85,0x28,0x84,0x09,0xD3,0xDF,0xCD,0xF4,0x41,0x81,0x4D,0x52, 0x6A,0xDC,0x37,0xC8,0x6C,0xC1,0xAB,0xFA,0x24,0xE1,0x7B,0x08,0x0C,0xBD,0xB1,0x4A, 0x78,0x88,0x95,0x8B,0xE3,0x63,0xE8,0x6D,0xE9,0xCB,0xD5,0xFE,0x3B,0x00,0x1D,0x39, 0xF2,0xEF,0xB7,0x0E,0x66,0x58,0xD0,0xE4,0xA6,0x77,0x72,0xF8,0xEB,0x75,0x4B,0x0A, 0x31,0x44,0x50,0xB4,0x8F,0xED,0x1F,0x1A,0xDB,0x99,0x8D,0x33,0x9F,0x11,0x83,0x14]) newDES = SBox([ 32,137,239,188,102,125,221, 72,212, 68, 81, 37, 86,237,147,149, 70,229, 17,124,115,207, 33, 20,122,143, 25,215, 51,183,138,142, 146,211,110,173, 1,228,189, 14,103, 78,162, 36,253,167,116,255, 158, 45,185, 50, 98,168,250,235, 54,141,195,247,240, 63,148, 2, 224,169,214,180, 62, 22,117,108, 19,172,161,159,160, 47, 43,171, 194,175,178, 56,196,112, 23,220, 89, 21,164,130,157, 8, 85,251, 216, 44, 94,179,226, 38, 90,119, 40,202, 34,206, 35, 69,231,246, 29,109, 74, 71,176, 6, 60,145, 65, 13, 77,151, 12,127, 95,199, 57,101, 5,232,150,210,129, 24,181, 10,121,187, 48,193,139,252, 219, 64, 88,233, 96,128, 80, 53,191,144,218, 11,106,132,155,104, 91,136, 31, 42,243, 66,126,135, 30, 26, 87,186,182,154,242,123, 82,166,208, 39,152,190,113,205,114,105,225, 84, 73,163, 99,111, 204, 61,200,217,170, 15,198, 28,192,254,134,234,222, 7,236,248, 201, 41,177,156, 92,131, 67,249,245,184,203, 9,241, 0, 27, 46, 133,174, 75, 18, 93,209,100,120, 76,213, 16, 83, 4,107,140, 52, 58, 55, 3,244, 97,197,238,227,118, 49, 79,230,223,165,153, 59]) Picaro = SBox([ 0x08,0x0c,0x03,0x06,0x06,0x04,0x05,0x06,0x05,0x04,0x0c,0x0c,0x04,0x03,0x05,0x03, 0x0a,0x1f,0x29,0x3b,0x4b,0x55,0x62,0x7b,0x82,0x95,0xaf,0xbf,0xc5,0xd9,0xe2,0xf9, 0x01,0x2d,0x45,0x6a,0x8a,0xac,0xcf,0xea,0x9f,0xbc,0xdd,0xfd,0x1c,0x35,0x5f,0x75, 0x0f,0x34,0x61,0x52,0xc2,0xfb,0xa3,0x92,0x13,0x2b,0x74,0x44,0xdb,0xe1,0xb3,0x81, 0x0f,0x44,0x81,0xc2,0x92,0xdb,0x13,0x52,0xb3,0xfb,0x34,0x74,0x2b,0x61,0xa3,0xe1, 0x0e,0x59,0xa4,0xf8,0xd8,0x87,0x7c,0x28,0x3c,0x67,0x99,0xc9,0xe7,0xb4,0x4c,0x14, 0x02,0x63,0xca,0xad,0x1d,0x71,0xd7,0xbd,0x27,0x41,0xe3,0x83,0x31,0x5a,0xf7,0x9a, 0x0f,0x74,0xe1,0x92,0x52,0x2b,0xb3,0xc2,0xa3,0xdb,0x44,0x34,0xfb,0x81,0x13,0x61, 0x02,0x83,0x9a,0x1d,0xbd,0x31,0x27,0xad,0xf7,0x71,0x63,0xe3,0x41,0xca,0xd7,0x5a, 0x0e,0x99,0xb4,0x28,0xf8,0x67,0x4c,0xd8,0x7c,0xe7,0xc9,0x59,0x87,0x14,0x3c,0xa4, 0x0a,0xaf,0xd9,0x7b,0x3b,0x95,0xe2,0x4b,0x62,0xc5,0xbf,0x1f,0x55,0xf9,0x82,0x29, 0x0a,0xbf,0xf9,0x4b,0x7b,0xc5,0x82,0x3b,0xe2,0x55,0x1f,0xaf,0x95,0x29,0x62,0xd9, 0x0e,0xc9,0x14,0xd8,0x28,0xe7,0x3c,0xf8,0x4c,0x87,0x59,0x99,0x67,0xa4,0x7c,0xb4, 0x01,0xdd,0x35,0xea,0x6a,0xbc,0x5f,0x8a,0xcf,0x1c,0xfd,0x2d,0xac,0x75,0x9f,0x45, 0x02,0xe3,0x5a,0xbd,0xad,0x41,0xf7,0x1d,0xd7,0x31,0x83,0x63,0x71,0x9a,0x27,0xca, 0x01,0xfd,0x75,0x8a,0xea,0x1c,0x9f,0x6a,0x5f,0xac,0x2d,0xdd,0xbc,0x45,0xcf,0x35]) Safer = SBox([ 1, 45, 226, 147, 190, 69, 21, 174, 120, 3, 135, 164, 184, 56, 207, 63, 8, 103, 9, 148, 235, 38, 168, 107, 189, 24, 52, 27, 187, 191, 114, 247, 64, 53, 72, 156, 81, 47, 59, 85, 227, 192, 159, 216, 211, 243, 141, 177, 255, 167, 62, 220, 134, 119, 215, 166, 17, 251, 244, 186, 146, 145, 100, 131, 241, 51, 239, 218, 44, 181, 178, 43, 136, 209, 153, 203, 140, 132, 29, 20, 129, 151, 113, 202, 95, 163, 139, 87, 60, 130, 196, 82, 92, 28, 232, 160, 4, 180, 133, 74, 246, 19, 84, 182, 223, 12, 26, 142, 222, 224, 57, 252, 32, 155, 36, 78, 169, 152, 158, 171, 242, 96, 208, 108, 234, 250, 199, 217, 0, 212, 31, 110, 67, 188, 236, 83, 137, 254, 122, 93, 73, 201, 50, 194, 249, 154, 248, 109, 22, 219, 89, 150, 68, 233, 205, 230, 70, 66, 143, 10, 193, 204, 185, 101, 176, 210, 198, 172, 30, 65, 98, 41, 46, 14, 116, 80, 2, 90, 195, 37, 123, 138, 42, 91, 240, 6, 13, 71, 111, 112, 157, 126, 16, 206, 18, 39, 213, 76, 79, 214, 121, 48, 104, 54, 117, 125, 228, 237, 128, 106, 144, 55, 162, 94, 118, 170, 197, 127, 61, 175, 165, 229, 25, 97, 253, 77, 124, 183, 11, 238, 173, 75, 34, 245, 231, 115, 35, 33, 200, 5, 225, 102, 221, 179, 88, 105, 99, 86, 15, 161, 49, 149, 23, 7, 58, 40]) Scream = SBox([ 0x20,0x8D,0xB2,0xDA,0x33,0x35,0xA6,0xFF,0x7A,0x52,0x6A,0xC6,0xA4,0xA8,0x51,0x23, 0xA2,0x96,0x30,0xAB,0xC8,0x17,0x14,0x9E,0xE8,0xF3,0xF8,0xDD,0x85,0xE2,0x4B,0xD8, 0x6C,0x01,0x0E,0x3D,0xB6,0x39,0x4A,0x83,0x6F,0xAA,0x86,0x6E,0x68,0x40,0x98,0x5F, 0x37,0x13,0x05,0x87,0x04,0x82,0x31,0x89,0x24,0x38,0x9D,0x54,0x22,0x7B,0x63,0xBD, 0x75,0x2C,0x47,0xE9,0xC2,0x60,0x43,0xAC,0x57,0xA1,0x1F,0x27,0xE7,0xAD,0x5C,0xD2, 0x0F,0x77,0xFD,0x08,0x79,0x3A,0x49,0x5D,0xED,0x90,0x65,0x7C,0x56,0x4F,0x2E,0x69, 0xCD,0x44,0x3F,0x62,0x5B,0x88,0x6B,0xC4,0x5E,0x2D,0x67,0x0B,0x9F,0x21,0x29,0x2A, 0xD6,0x7E,0x74,0xE0,0x41,0x73,0x50,0x76,0x55,0x97,0x3C,0x09,0x7D,0x5A,0x92,0x70, 0x84,0xB9,0x26,0x34,0x1D,0x81,0x32,0x2B,0x36,0x64,0xAE,0xC0,0x00,0xEE,0x8F,0xA7, 0xBE,0x58,0xDC,0x7F,0xEC,0x9B,0x78,0x10,0xCC,0x2F,0x94,0xF1,0x3B,0x9C,0x6D,0x16, 0x48,0xB5,0xCA,0x11,0xFA,0x0D,0x8E,0x07,0xB1,0x0C,0x12,0x28,0x4C,0x46,0xF4,0x8B, 0xA9,0xCF,0xBB,0x03,0xA0,0xFC,0xEF,0x25,0x80,0xF6,0xB3,0xBA,0x3E,0xF7,0xD5,0x91, 0xC3,0x8A,0xC1,0x45,0xDE,0x66,0xF5,0x0A,0xC9,0x15,0xD9,0xA3,0x61,0x99,0xB0,0xE4, 0xD1,0xFB,0xD3,0x4E,0xBF,0xD4,0xD7,0x71,0xCB,0x1E,0xDB,0x02,0x1A,0x93,0xEA,0xC5, 0xEB,0x72,0xF9,0x1C,0xE5,0xCE,0x4D,0xF2,0x42,0x19,0xE1,0xDF,0x59,0x95,0xB7,0x8C, 0x9A,0xF0,0x18,0xE6,0xC7,0xAF,0xBC,0xB8,0xE3,0x1B,0xD0,0xA5,0x53,0xB4,0x06,0xFE]) # Source: https://tools.ietf.org/html/rfc4269 SEED_S0 = SBox([ 0xA9,0x85,0xD6,0xD3,0x54,0x1D,0xAC,0x25,0x5D,0x43,0x18,0x1E,0x51,0xFC,0xCA,0x63, 0x28,0x44,0x20,0x9D,0xE0,0xE2,0xC8,0x17,0xA5,0x8F,0x03,0x7B,0xBB,0x13,0xD2,0xEE, 0x70,0x8C,0x3F,0xA8,0x32,0xDD,0xF6,0x74,0xEC,0x95,0x0B,0x57,0x5C,0x5B,0xBD,0x01, 0x24,0x1C,0x73,0x98,0x10,0xCC,0xF2,0xD9,0x2C,0xE7,0x72,0x83,0x9B,0xD1,0x86,0xC9, 0x60,0x50,0xA3,0xEB,0x0D,0xB6,0x9E,0x4F,0xB7,0x5A,0xC6,0x78,0xA6,0x12,0xAF,0xD5, 0x61,0xC3,0xB4,0x41,0x52,0x7D,0x8D,0x08,0x1F,0x99,0x00,0x19,0x04,0x53,0xF7,0xE1, 0xFD,0x76,0x2F,0x27,0xB0,0x8B,0x0E,0xAB,0xA2,0x6E,0x93,0x4D,0x69,0x7C,0x09,0x0A, 0xBF,0xEF,0xF3,0xC5,0x87,0x14,0xFE,0x64,0xDE,0x2E,0x4B,0x1A,0x06,0x21,0x6B,0x66, 0x02,0xF5,0x92,0x8A,0x0C,0xB3,0x7E,0xD0,0x7A,0x47,0x96,0xE5,0x26,0x80,0xAD,0xDF, 0xA1,0x30,0x37,0xAE,0x36,0x15,0x22,0x38,0xF4,0xA7,0x45,0x4C,0x81,0xE9,0x84,0x97, 0x35,0xCB,0xCE,0x3C,0x71,0x11,0xC7,0x89,0x75,0xFB,0xDA,0xF8,0x94,0x59,0x82,0xC4, 0xFF,0x49,0x39,0x67,0xC0,0xCF,0xD7,0xB8,0x0F,0x8E,0x42,0x23,0x91,0x6C,0xDB,0xA4, 0x34,0xF1,0x48,0xC2,0x6F,0x3D,0x2D,0x40,0xBE,0x3E,0xBC,0xC1,0xAA,0xBA,0x4E,0x55, 0x3B,0xDC,0x68,0x7F,0x9C,0xD8,0x4A,0x56,0x77,0xA0,0xED,0x46,0xB5,0x2B,0x65,0xFA, 0xE3,0xB9,0xB1,0x9F,0x5E,0xF9,0xE6,0xB2,0x31,0xEA,0x6D,0x5F,0xE4,0xF0,0xCD,0x88, 0x16,0x3A,0x58,0xD4,0x62,0x29,0x07,0x33,0xE8,0x1B,0x05,0x79,0x90,0x6A,0x2A,0x9A]) SEED_S1 = SBox([ 0x38,0xE8,0x2D,0xA6,0xCF,0xDE,0xB3,0xB8,0xAF,0x60,0x55,0xC7,0x44,0x6F,0x6B,0x5B, 0xC3,0x62,0x33,0xB5,0x29,0xA0,0xE2,0xA7,0xD3,0x91,0x11,0x06,0x1C,0xBC,0x36,0x4B, 0xEF,0x88,0x6C,0xA8,0x17,0xC4,0x16,0xF4,0xC2,0x45,0xE1,0xD6,0x3F,0x3D,0x8E,0x98, 0x28,0x4E,0xF6,0x3E,0xA5,0xF9,0x0D,0xDF,0xD8,0x2B,0x66,0x7A,0x27,0x2F,0xF1,0x72, 0x42,0xD4,0x41,0xC0,0x73,0x67,0xAC,0x8B,0xF7,0xAD,0x80,0x1F,0xCA,0x2C,0xAA,0x34, 0xD2,0x0B,0xEE,0xE9,0x5D,0x94,0x18,0xF8,0x57,0xAE,0x08,0xC5,0x13,0xCD,0x86,0xB9, 0xFF,0x7D,0xC1,0x31,0xF5,0x8A,0x6A,0xB1,0xD1,0x20,0xD7,0x02,0x22,0x04,0x68,0x71, 0x07,0xDB,0x9D,0x99,0x61,0xBE,0xE6,0x59,0xDD,0x51,0x90,0xDC,0x9A,0xA3,0xAB,0xD0, 0x81,0x0F,0x47,0x1A,0xE3,0xEC,0x8D,0xBF,0x96,0x7B,0x5C,0xA2,0xA1,0x63,0x23,0x4D, 0xC8,0x9E,0x9C,0x3A,0x0C,0x2E,0xBA,0x6E,0x9F,0x5A,0xF2,0x92,0xF3,0x49,0x78,0xCC, 0x15,0xFB,0x70,0x75,0x7F,0x35,0x10,0x03,0x64,0x6D,0xC6,0x74,0xD5,0xB4,0xEA,0x09, 0x76,0x19,0xFE,0x40,0x12,0xE0,0xBD,0x05,0xFA,0x01,0xF0,0x2A,0x5E,0xA9,0x56,0x43, 0x85,0x14,0x89,0x9B,0xB0,0xE5,0x48,0x79,0x97,0xFC,0x1E,0x82,0x21,0x8C,0x1B,0x5F, 0x77,0x54,0xB2,0x1D,0x25,0x4F,0x00,0x46,0xED,0x58,0x52,0xEB,0x7E,0xDA,0xC9,0xFD, 0x30,0x95,0x65,0x3C,0xB6,0xE4,0xBB,0x7C,0x0E,0x50,0x39,0x26,0x32,0x84,0x69,0x93, 0x37,0xE7,0x24,0xA4,0xCB,0x53,0x0A,0x87,0xD9,0x4C,0x83,0x8F,0xCE,0x3B,0x4A,0xB7]) SKINNY_8 = SBox([ 0x65,0x4c,0x6a,0x42,0x4b,0x63,0x43,0x6b,0x55,0x75,0x5a,0x7a,0x53,0x73,0x5b,0x7b, 0x35,0x8c,0x3a,0x81,0x89,0x33,0x80,0x3b,0x95,0x25,0x98,0x2a,0x90,0x23,0x99,0x2b, 0xe5,0xcc,0xe8,0xc1,0xc9,0xe0,0xc0,0xe9,0xd5,0xf5,0xd8,0xf8,0xd0,0xf0,0xd9,0xf9, 0xa5,0x1c,0xa8,0x12,0x1b,0xa0,0x13,0xa9,0x05,0xb5,0x0a,0xb8,0x03,0xb0,0x0b,0xb9, 0x32,0x88,0x3c,0x85,0x8d,0x34,0x84,0x3d,0x91,0x22,0x9c,0x2c,0x94,0x24,0x9d,0x2d, 0x62,0x4a,0x6c,0x45,0x4d,0x64,0x44,0x6d,0x52,0x72,0x5c,0x7c,0x54,0x74,0x5d,0x7d, 0xa1,0x1a,0xac,0x15,0x1d,0xa4,0x14,0xad,0x02,0xb1,0x0c,0xbc,0x04,0xb4,0x0d,0xbd, 0xe1,0xc8,0xec,0xc5,0xcd,0xe4,0xc4,0xed,0xd1,0xf1,0xdc,0xfc,0xd4,0xf4,0xdd,0xfd, 0x36,0x8e,0x38,0x82,0x8b,0x30,0x83,0x39,0x96,0x26,0x9a,0x28,0x93,0x20,0x9b,0x29, 0x66,0x4e,0x68,0x41,0x49,0x60,0x40,0x69,0x56,0x76,0x58,0x78,0x50,0x70,0x59,0x79, 0xa6,0x1e,0xaa,0x11,0x19,0xa3,0x10,0xab,0x06,0xb6,0x08,0xba,0x00,0xb3,0x09,0xbb, 0xe6,0xce,0xea,0xc2,0xcb,0xe3,0xc3,0xeb,0xd6,0xf6,0xda,0xfa,0xd3,0xf3,0xdb,0xfb, 0x31,0x8a,0x3e,0x86,0x8f,0x37,0x87,0x3f,0x92,0x21,0x9e,0x2e,0x97,0x27,0x9f,0x2f, 0x61,0x48,0x6e,0x46,0x4f,0x67,0x47,0x6f,0x51,0x71,0x5e,0x7e,0x57,0x77,0x5f,0x7f, 0xa2,0x18,0xae,0x16,0x1f,0xa7,0x17,0xaf,0x01,0xb2,0x0e,0xbe,0x07,0xb7,0x0f,0xbf, 0xe2,0xca,0xee,0xc6,0xcf,0xe7,0xc7,0xef,0xd2,0xf2,0xde,0xfe,0xd7,0xf7,0xdf,0xff]) ForkSkinny_8 = SKINNY_8 Remus_8 = SKINNY_8 Romulus = SKINNY_8 Skipjack = SBox([ 0xa3,0xd7,0x09,0x83,0xf8,0x48,0xf6,0xf4,0xb3,0x21,0x15,0x78,0x99,0xb1,0xaf,0xf9, 0xe7,0x2d,0x4d,0x8a,0xce,0x4c,0xca,0x2e,0x52,0x95,0xd9,0x1e,0x4e,0x38,0x44,0x28, 0x0a,0xdf,0x02,0xa0,0x17,0xf1,0x60,0x68,0x12,0xb7,0x7a,0xc3,0xe9,0xfa,0x3d,0x53, 0x96,0x84,0x6b,0xba,0xf2,0x63,0x9a,0x19,0x7c,0xae,0xe5,0xf5,0xf7,0x16,0x6a,0xa2, 0x39,0xb6,0x7b,0x0f,0xc1,0x93,0x81,0x1b,0xee,0xb4,0x1a,0xea,0xd0,0x91,0x2f,0xb8, 0x55,0xb9,0xda,0x85,0x3f,0x41,0xbf,0xe0,0x5a,0x58,0x80,0x5f,0x66,0x0b,0xd8,0x90, 0x35,0xd5,0xc0,0xa7,0x33,0x06,0x65,0x69,0x45,0x00,0x94,0x56,0x6d,0x98,0x9b,0x76, 0x97,0xfc,0xb2,0xc2,0xb0,0xfe,0xdb,0x20,0xe1,0xeb,0xd6,0xe4,0xdd,0x47,0x4a,0x1d, 0x42,0xed,0x9e,0x6e,0x49,0x3c,0xcd,0x43,0x27,0xd2,0x07,0xd4,0xde,0xc7,0x67,0x18, 0x89,0xcb,0x30,0x1f,0x8d,0xc6,0x8f,0xaa,0xc8,0x74,0xdc,0xc9,0x5d,0x5c,0x31,0xa4, 0x70,0x88,0x61,0x2c,0x9f,0x0d,0x2b,0x87,0x50,0x82,0x54,0x64,0x26,0x7d,0x03,0x40, 0x34,0x4b,0x1c,0x73,0xd1,0xc4,0xfd,0x3b,0xcc,0xfb,0x7f,0xab,0xe6,0x3e,0x5b,0xa5, 0xad,0x04,0x23,0x9c,0x14,0x51,0x22,0xf0,0x29,0x79,0x71,0x7e,0xff,0x8c,0x0e,0xe2, 0x0c,0xef,0xbc,0x72,0x75,0x6f,0x37,0xa1,0xec,0xd3,0x8e,0x62,0x8b,0x86,0x10,0xe8, 0x08,0x77,0x11,0xbe,0x92,0x4f,0x24,0xc5,0x32,0x36,0x9d,0xcf,0xf3,0xa6,0xbb,0xac, 0x5e,0x6c,0xa9,0x13,0x57,0x25,0xb5,0xe3,0xbd,0xa8,0x3a,0x01,0x05,0x59,0x2a,0x46]) # source: www.gsma.com/aboutus/wp-content/uploads/2014/12/snow3gspec.doc SNOW_3G_sq = SBox([ 0x25,0x24,0x73,0x67,0xD7,0xAE,0x5C,0x30,0xA4,0xEE,0x6E,0xCB,0x7D,0xB5,0x82,0xDB, 0xE4,0x8E,0x48,0x49,0x4F,0x5D,0x6A,0x78,0x70,0x88,0xE8,0x5F,0x5E,0x84,0x65,0xE2, 0xD8,0xE9,0xCC,0xED,0x40,0x2F,0x11,0x28,0x57,0xD2,0xAC,0xE3,0x4A,0x15,0x1B,0xB9, 0xB2,0x80,0x85,0xA6,0x2E,0x02,0x47,0x29,0x07,0x4B,0x0E,0xC1,0x51,0xAA,0x89,0xD4, 0xCA,0x01,0x46,0xB3,0xEF,0xDD,0x44,0x7B,0xC2,0x7F,0xBE,0xC3,0x9F,0x20,0x4C,0x64, 0x83,0xA2,0x68,0x42,0x13,0xB4,0x41,0xCD,0xBA,0xC6,0xBB,0x6D,0x4D,0x71,0x21,0xF4, 0x8D,0xB0,0xE5,0x93,0xFE,0x8F,0xE6,0xCF,0x43,0x45,0x31,0x22,0x37,0x36,0x96,0xFA, 0xBC,0x0F,0x08,0x52,0x1D,0x55,0x1A,0xC5,0x4E,0x23,0x69,0x7A,0x92,0xFF,0x5B,0x5A, 0xEB,0x9A,0x1C,0xA9,0xD1,0x7E,0x0D,0xFC,0x50,0x8A,0xB6,0x62,0xF5,0x0A,0xF8,0xDC, 0x03,0x3C,0x0C,0x39,0xF1,0xB8,0xF3,0x3D,0xF2,0xD5,0x97,0x66,0x81,0x32,0xA0,0x00, 0x06,0xCE,0xF6,0xEA,0xB7,0x17,0xF7,0x8C,0x79,0xD6,0xA7,0xBF,0x8B,0x3F,0x1F,0x53, 0x63,0x75,0x35,0x2C,0x60,0xFD,0x27,0xD3,0x94,0xA5,0x7C,0xA1,0x05,0x58,0x2D,0xBD, 0xD9,0xC7,0xAF,0x6B,0x54,0x0B,0xE0,0x38,0x04,0xC8,0x9D,0xE7,0x14,0xB1,0x87,0x9C, 0xDF,0x6F,0xF9,0xDA,0x2A,0xC4,0x59,0x16,0x74,0x91,0xAB,0x26,0x61,0x76,0x34,0x2B, 0xAD,0x99,0xFB,0x72,0xEC,0x33,0x12,0xDE,0x98,0x3B,0xC0,0x9B,0x3E,0x18,0x10,0x3A, 0x56,0xE1,0x77,0xC9,0x1E,0x9E,0x95,0xA3,0x90,0x19,0xA8,0x6C,0x09,0xD0,0xF0,0x86]) SMS4 = SBox([ 0xd6,0x90,0xe9,0xfe,0xcc,0xe1,0x3d,0xb7,0x16,0xb6,0x14,0xc2,0x28,0xfb,0x2c,0x05, 0x2b,0x67,0x9a,0x76,0x2a,0xbe,0x04,0xc3,0xaa,0x44,0x13,0x26,0x49,0x86,0x06,0x99, 0x9c,0x42,0x50,0xf4,0x91,0xef,0x98,0x7a,0x33,0x54,0x0b,0x43,0xed,0xcf,0xac,0x62, 0xe4,0xb3,0x1c,0xa9,0xc9,0x08,0xe8,0x95,0x80,0xdf,0x94,0xfa,0x75,0x8f,0x3f,0xa6, 0x47,0x07,0xa7,0xfc,0xf3,0x73,0x17,0xba,0x83,0x59,0x3c,0x19,0xe6,0x85,0x4f,0xa8, 0x68,0x6b,0x81,0xb2,0x71,0x64,0xda,0x8b,0xf8,0xeb,0x0f,0x4b,0x70,0x56,0x9d,0x35, 0x1e,0x24,0x0e,0x5e,0x63,0x58,0xd1,0xa2,0x25,0x22,0x7c,0x3b,0x01,0x21,0x78,0x87, 0xd4,0x00,0x46,0x57,0x9f,0xd3,0x27,0x52,0x4c,0x36,0x02,0xe7,0xa0,0xc4,0xc8,0x9e, 0xea,0xbf,0x8a,0xd2,0x40,0xc7,0x38,0xb5,0xa3,0xf7,0xf2,0xce,0xf9,0x61,0x15,0xa1, 0xe0,0xae,0x5d,0xa4,0x9b,0x34,0x1a,0x55,0xad,0x93,0x32,0x30,0xf5,0x8c,0xb1,0xe3, 0x1d,0xf6,0xe2,0x2e,0x82,0x66,0xca,0x60,0xc0,0x29,0x23,0xab,0x0d,0x53,0x4e,0x6f, 0xd5,0xdb,0x37,0x45,0xde,0xfd,0x8e,0x2f,0x03,0xff,0x6a,0x72,0x6d,0x6c,0x5b,0x51, 0x8d,0x1b,0xaf,0x92,0xbb,0xdd,0xbc,0x7f,0x11,0xd9,0x5c,0x41,0x1f,0x10,0x5a,0xd8, 0x0a,0xc1,0x31,0x88,0xa5,0xcd,0x7b,0xbd,0x2d,0x74,0xd0,0x12,0xb8,0xe5,0xb4,0xb0, 0x89,0x69,0x97,0x4a,0x0c,0x96,0x77,0x7e,0x65,0xb9,0xf1,0x09,0xc5,0x6e,0xc6,0x84, 0x18,0xf0,0x7d,0xec,0x3a,0xdc,0x4d,0x20,0x79,0xee,0x5f,0x3e,0xd7,0xcb,0x39,0x48]) # source: https://www.iacr.org/archive/fse2003/28870306/28870306.pdf # structure: random, obtained from RC4 Turing = SBox([ 0x61,0x51,0xeb,0x19,0xb9,0x5d,0x60,0x38,0x7c,0xb2,0x06,0x12,0xc4,0x5b,0x16,0x3b, 0x2b,0x18,0x83,0xb0,0x7f,0x75,0xfa,0xa0,0xe9,0xdd,0x6d,0x7a,0x6b,0x68,0x2d,0x49, 0xb5,0x1c,0x90,0xf7,0xed,0x9f,0xe8,0xce,0xae,0x77,0xc2,0x13,0xfd,0xcd,0x3e,0xcf, 0x37,0x6a,0xd4,0xdb,0x8e,0x65,0x1f,0x1a,0x87,0xcb,0x40,0x15,0x88,0x0d,0x35,0xb3, 0x11,0x0f,0xd0,0x30,0x48,0xf9,0xa8,0xac,0x85,0x27,0x0e,0x8a,0xe0,0x50,0x64,0xa7, 0xcc,0xe4,0xf1,0x98,0xff,0xa1,0x04,0xda,0xd5,0xbc,0x1b,0xbb,0xd1,0xfe,0x31,0xca, 0xba,0xd9,0x2e,0xf3,0x1d,0x47,0x4a,0x3d,0x71,0x4c,0xab,0x7d,0x8d,0xc7,0x59,0xb8, 0xc1,0x96,0x1e,0xfc,0x44,0xc8,0x7b,0xdc,0x5c,0x78,0x2a,0x9d,0xa5,0xf0,0x73,0x22, 0x89,0x05,0xf4,0x07,0x21,0x52,0xa6,0x28,0x9a,0x92,0x69,0x8f,0xc5,0xc3,0xf5,0xe1, 0xde,0xec,0x09,0xf2,0xd3,0xaf,0x34,0x23,0xaa,0xdf,0x7e,0x82,0x29,0xc0,0x24,0x14, 0x03,0x32,0x4e,0x39,0x6f,0xc6,0xb1,0x9b,0xea,0x72,0x79,0x41,0xd8,0x26,0x6c,0x5e, 0x2c,0xb4,0xa2,0x53,0x57,0xe2,0x9c,0x86,0x54,0x95,0xb6,0x80,0x8c,0x36,0x67,0xbd, 0x08,0x93,0x2f,0x99,0x5a,0xf8,0x3a,0xd7,0x56,0x84,0xd2,0x01,0xf6,0x66,0x4d,0x55, 0x8b,0x0c,0x0b,0x46,0xb7,0x3c,0x45,0x91,0xa4,0xe3,0x70,0xd6,0xfb,0xe6,0x10,0xa9, 0xc9,0x00,0x9e,0xe7,0x4f,0x76,0x25,0x3f,0x5f,0xa3,0x33,0x20,0x02,0xef,0x62,0x74, 0xee,0x17,0x81,0x42,0x58,0x0a,0x4b,0x63,0xe5,0xbe,0x6e,0xad,0xbf,0x43,0x94,0x97]) # source: https://www.schneier.com/cryptography/paperfiles/paper-twofish-paper.pdf # structure: ASAS, the 4 bit S-Boxes q0 ti for i=0..3 are provided below Twofish_p0 = SBox([ 0xA9,0x67,0xB3,0xE8,0x04,0xFD,0xA3,0x76,0x9A,0x92,0x80,0x78,0xE4,0xDD,0xD1,0x38, 0x0D,0xC6,0x35,0x98,0x18,0xF7,0xEC,0x6C,0x43,0x75,0x37,0x26,0xFA,0x13,0x94,0x48, 0xF2,0xD0,0x8B,0x30,0x84,0x54,0xDF,0x23,0x19,0x5B,0x3D,0x59,0xF3,0xAE,0xA2,0x82, 0x63,0x01,0x83,0x2E,0xD9,0x51,0x9B,0x7C,0xA6,0xEB,0xA5,0xBE,0x16,0x0C,0xE3,0x61, 0xC0,0x8C,0x3A,0xF5,0x73,0x2C,0x25,0x0B,0xBB,0x4E,0x89,0x6B,0x53,0x6A,0xB4,0xF1, 0xE1,0xE6,0xBD,0x45,0xE2,0xF4,0xB6,0x66,0xCC,0x95,0x03,0x56,0xD4,0x1C,0x1E,0xD7, 0xFB,0xC3,0x8E,0xB5,0xE9,0xCF,0xBF,0xBA,0xEA,0x77,0x39,0xAF,0x33,0xC9,0x62,0x71, 0x81,0x79,0x09,0xAD,0x24,0xCD,0xF9,0xD8,0xE5,0xC5,0xB9,0x4D,0x44,0x08,0x86,0xE7, 0xA1,0x1D,0xAA,0xED,0x06,0x70,0xB2,0xD2,0x41,0x7B,0xA0,0x11,0x31,0xC2,0x27,0x90, 0x20,0xF6,0x60,0xFF,0x96,0x5C,0xB1,0xAB,0x9E,0x9C,0x52,0x1B,0x5F,0x93,0x0A,0xEF, 0x91,0x85,0x49,0xEE,0x2D,0x4F,0x8F,0x3B,0x47,0x87,0x6D,0x46,0xD6,0x3E,0x69,0x64, 0x2A,0xCE,0xCB,0x2F,0xFC,0x97,0x05,0x7A,0xAC,0x7F,0xD5,0x1A,0x4B,0x0E,0xA7,0x5A, 0x28,0x14,0x3F,0x29,0x88,0x3C,0x4C,0x02,0xB8,0xDA,0xB0,0x17,0x55,0x1F,0x8A,0x7D, 0x57,0xC7,0x8D,0x74,0xB7,0xC4,0x9F,0x72,0x7E,0x15,0x22,0x12,0x58,0x07,0x99,0x34, 0x6E,0x50,0xDE,0x68,0x65,0xBC,0xDB,0xF8,0xC8,0xA8,0x2B,0x40,0xDC,0xFE,0x32,0xA4, 0xCA,0x10,0x21,0xF0,0xD3,0x5D,0x0F,0x00,0x6F,0x9D,0x36,0x42,0x4A,0x5E,0xC1,0xE0]) # source: https://www.schneier.com/cryptography/paperfiles/paper-twofish-paper.pdf # structure: ASAS, the 4 bit S-Boxes q1 ti for i=0..3 are provided below Twofish_p1 = SBox([ 0x75,0xF3,0xC6,0xF4,0xDB,0x7B,0xFB,0xC8,0x4A,0xD3,0xE6,0x6B,0x45,0x7D,0xE8,0x4B, 0xD6,0x32,0xD8,0xFD,0x37,0x71,0xF1,0xE1,0x30,0x0F,0xF8,0x1B,0x87,0xFA,0x06,0x3F, 0x5E,0xBA,0xAE,0x5B,0x8A,0x00,0xBC,0x9D,0x6D,0xC1,0xB1,0x0E,0x80,0x5D,0xD2,0xD5, 0xA0,0x84,0x07,0x14,0xB5,0x90,0x2C,0xA3,0xB2,0x73,0x4C,0x54,0x92,0x74,0x36,0x51, 0x38,0xB0,0xBD,0x5A,0xFC,0x60,0x62,0x96,0x6C,0x42,0xF7,0x10,0x7C,0x28,0x27,0x8C, 0x13,0x95,0x9C,0xC7,0x24,0x46,0x3B,0x70,0xCA,0xE3,0x85,0xCB,0x11,0xD0,0x93,0xB8, 0xA6,0x83,0x20,0xFF,0x9F,0x77,0xC3,0xCC,0x03,0x6F,0x08,0xBF,0x40,0xE7,0x2B,0xE2, 0x79,0x0C,0xAA,0x82,0x41,0x3A,0xEA,0xB9,0xE4,0x9A,0xA4,0x97,0x7E,0xDA,0x7A,0x17, 0x66,0x94,0xA1,0x1D,0x3D,0xF0,0xDE,0xB3,0x0B,0x72,0xA7,0x1C,0xEF,0xD1,0x53,0x3E, 0x8F,0x33,0x26,0x5F,0xEC,0x76,0x2A,0x49,0x81,0x88,0xEE,0x21,0xC4,0x1A,0xEB,0xD9, 0xC5,0x39,0x99,0xCD,0xAD,0x31,0x8B,0x01,0x18,0x23,0xDD,0x1F,0x4E,0x2D,0xF9,0x48, 0x4F,0xF2,0x65,0x8E,0x78,0x5C,0x58,0x19,0x8D,0xE5,0x98,0x57,0x67,0x7F,0x05,0x64, 0xAF,0x63,0xB6,0xFE,0xF5,0xB7,0x3C,0xA5,0xCE,0xE9,0x68,0x44,0xE0,0x4D,0x43,0x69, 0x29,0x2E,0xAC,0x15,0x59,0xA8,0x0A,0x9E,0x6E,0x47,0xDF,0x34,0x35,0x6A,0xCF,0xDC, 0x22,0xC9,0xC0,0x9B,0x89,0xD4,0xED,0xAB,0x12,0xA2,0x0D,0x52,0xBB,0x02,0x2F,0xA9, 0xD7,0x61,0x1E,0xB4,0x50,0x04,0xF6,0xC2,0x16,0x25,0x86,0x56,0x55,0x09,0xBE,0x91]) Whirlpool = SBox([ 0x18,0x23,0xc6,0xE8,0x87,0xB8,0x01,0x4F,0x36,0xA6,0xd2,0xF5,0x79,0x6F,0x91,0x52, 0x60,0xBc,0x9B,0x8E,0xA3,0x0c,0x7B,0x35,0x1d,0xE0,0xd7,0xc2,0x2E,0x4B,0xFE,0x57, 0x15,0x77,0x37,0xE5,0x9F,0xF0,0x4A,0xdA,0x58,0xc9,0x29,0x0A,0xB1,0xA0,0x6B,0x85, 0xBd,0x5d,0x10,0xF4,0xcB,0x3E,0x05,0x67,0xE4,0x27,0x41,0x8B,0xA7,0x7d,0x95,0xd8, 0xFB,0xEE,0x7c,0x66,0xdd,0x17,0x47,0x9E,0xcA,0x2d,0xBF,0x07,0xAd,0x5A,0x83,0x33, 0x63,0x02,0xAA,0x71,0xc8,0x19,0x49,0xd9,0xF2,0xE3,0x5B,0x88,0x9A,0x26,0x32,0xB0, 0xE9,0x0F,0xd5,0x80,0xBE,0xcd,0x34,0x48,0xFF,0x7A,0x90,0x5F,0x20,0x68,0x1A,0xAE, 0xB4,0x54,0x93,0x22,0x64,0xF1,0x73,0x12,0x40,0x08,0xc3,0xEc,0xdB,0xA1,0x8d,0x3d, 0x97,0x00,0xcF,0x2B,0x76,0x82,0xd6,0x1B,0xB5,0xAF,0x6A,0x50,0x45,0xF3,0x30,0xEF, 0x3F,0x55,0xA2,0xEA,0x65,0xBA,0x2F,0xc0,0xdE,0x1c,0xFd,0x4d,0x92,0x75,0x06,0x8A, 0xB2,0xE6,0x0E,0x1F,0x62,0xd4,0xA8,0x96,0xF9,0xc5,0x25,0x59,0x84,0x72,0x39,0x4c, 0x5E,0x78,0x38,0x8c,0xd1,0xA5,0xE2,0x61,0xB3,0x21,0x9c,0x1E,0x43,0xc7,0xFc,0x04, 0x51,0x99,0x6d,0x0d,0xFA,0xdF,0x7E,0x24,0x3B,0xAB,0xcE,0x11,0x8F,0x4E,0xB7,0xEB, 0x3c,0x81,0x94,0xF7,0xB9,0x13,0x2c,0xd3,0xE7,0x6E,0xc4,0x03,0x56,0x44,0x7F,0xA9, 0x2A,0xBB,0xc1,0x53,0xdc,0x0B,0x9d,0x6c,0x31,0x74,0xF6,0x46,0xAc,0x89,0x14,0xE1, 0x16,0x3A,0x69,0x09,0x70,0xB6,0xd0,0xEd,0xcc,0x42,0x98,0xA4,0x28,0x5c,0xF8,0x86]) Zorro = SBox([ 0xB2,0xE5,0x5E,0xFD,0x5F,0xC5,0x50,0xBC,0xDC,0x4A,0xFA,0x88,0x28,0xD8,0xE0,0xD1, 0xB5,0xD0,0x3C,0xB0,0x99,0xC1,0xE8,0xE2,0x13,0x59,0xA7,0xFB,0x71,0x34,0x31,0xF1, 0x9F,0x3A,0xCE,0x6E,0xA8,0xA4,0xB4,0x7E,0x1F,0xB7,0x51,0x1D,0x38,0x9D,0x46,0x69, 0x53,0xE,0x42,0x1B,0xF,0x11,0x68,0xCA,0xAA,0x6,0xF0,0xBD,0x26,0x6F,0x0,0xD9, 0x62,0xF3,0x15,0x60,0xF2,0x3D,0x7F,0x35,0x63,0x2D,0x67,0x93,0x1C,0x91,0xF9,0x9C, 0x66,0x2A,0x81,0x20,0x95,0xF8,0xE3,0x4D,0x5A,0x6D,0x24,0x7B,0xB9,0xEF,0xDF,0xDA, 0x58,0xA9,0x92,0x76,0x2E,0xB3,0x39,0xC,0x29,0xCD,0x43,0xFE,0xAB,0xF5,0x94,0x23, 0x16,0x80,0xC0,0x12,0x4C,0xE9,0x48,0x19,0x8,0xAE,0x41,0x70,0x84,0x14,0xA2,0xD5, 0xB8,0x33,0x65,0xBA,0xED,0x17,0xCF,0x96,0x1E,0x3B,0xB,0xC2,0xC8,0xB6,0xBB,0x8B, 0xA1,0x54,0x75,0xC4,0x10,0x5D,0xD6,0x25,0x97,0xE6,0xFC,0x49,0xF7,0x52,0x18,0x86, 0x8D,0xCB,0xE1,0xBF,0xD7,0x8E,0x37,0xBE,0x82,0xCC,0x64,0x90,0x7C,0x32,0x8F,0x4B, 0xAC,0x1A,0xEA,0xD3,0xF4,0x6B,0x2C,0xFF,0x55,0xA,0x45,0x9,0x89,0x1,0x30,0x2B, 0xD2,0x77,0x87,0x72,0xEB,0x36,0xDE,0x9E,0x8C,0xDB,0x6C,0x9B,0x5,0x2,0x4E,0xAF, 0x4,0xAD,0x74,0xC3,0xEE,0xA6,0xF6,0xC7,0x7D,0x40,0xD4,0xD,0x3E,0x5B,0xEC,0x78, 0xA0,0xB1,0x44,0x73,0x47,0x5C,0x98,0x21,0x22,0x61,0x3F,0xC6,0x7A,0x56,0xDD,0xE7, 0x85,0xC9,0x8A,0x57,0x27,0x7,0x9A,0x3,0xA3,0x83,0xE4,0x6A,0xA5,0x2F,0x79,0x4F]) ZUC_S0 = SBox([ 0x3e,0x72,0x5b,0x47,0xca,0xe0,0x00,0x33,0x04,0xd1,0x54,0x98,0x09,0xb9,0x6d,0xcb, 0x7b,0x1b,0xf9,0x32,0xaf,0x9d,0x6a,0xa5,0xb8,0x2d,0xfc,0x1d,0x08,0x53,0x03,0x90, 0x4d,0x4e,0x84,0x99,0xe4,0xce,0xd9,0x91,0xdd,0xb6,0x85,0x48,0x8b,0x29,0x6e,0xac, 0xcd,0xc1,0xf8,0x1e,0x73,0x43,0x69,0xc6,0xb5,0xbd,0xfd,0x39,0x63,0x20,0xd4,0x38, 0x76,0x7d,0xb2,0xa7,0xcf,0xed,0x57,0xc5,0xf3,0x2c,0xbb,0x14,0x21,0x06,0x55,0x9b, 0xe3,0xef,0x5e,0x31,0x4f,0x7f,0x5a,0xa4,0x0d,0x82,0x51,0x49,0x5f,0xba,0x58,0x1c, 0x4a,0x16,0xd5,0x17,0xa8,0x92,0x24,0x1f,0x8c,0xff,0xd8,0xae,0x2e,0x01,0xd3,0xad, 0x3b,0x4b,0xda,0x46,0xeb,0xc9,0xde,0x9a,0x8f,0x87,0xd7,0x3a,0x80,0x6f,0x2f,0xc8, 0xb1,0xb4,0x37,0xf7,0x0a,0x22,0x13,0x28,0x7c,0xcc,0x3c,0x89,0xc7,0xc3,0x96,0x56, 0x07,0xbf,0x7e,0xf0,0x0b,0x2b,0x97,0x52,0x35,0x41,0x79,0x61,0xa6,0x4c,0x10,0xfe, 0xbc,0x26,0x95,0x88,0x8a,0xb0,0xa3,0xfb,0xc0,0x18,0x94,0xf2,0xe1,0xe5,0xe9,0x5d, 0xd0,0xdc,0x11,0x66,0x64,0x5c,0xec,0x59,0x42,0x75,0x12,0xf5,0x74,0x9c,0xaa,0x23, 0x0e,0x86,0xab,0xbe,0x2a,0x02,0xe7,0x67,0xe6,0x44,0xa2,0x6c,0xc2,0x93,0x9f,0xf1, 0xf6,0xfa,0x36,0xd2,0x50,0x68,0x9e,0x62,0x71,0x15,0x3d,0xd6,0x40,0xc4,0xe2,0x0f, 0x8e,0x83,0x77,0x6b,0x25,0x05,0x3f,0x0c,0x30,0xea,0x70,0xb7,0xa1,0xe8,0xa9,0x65, 0x8d,0x27,0x1a,0xdb,0x81,0xb3,0xa0,0xf4,0x45,0x7a,0x19,0xdf,0xee,0x78,0x34,0x60]) ZUC_S1 = SBox([ 0x55,0xc2,0x63,0x71,0x3b,0xc8,0x47,0x86,0x9f,0x3c,0xda,0x5b,0x29,0xaa,0xfd,0x77, 0x8c,0xc5,0x94,0x0c,0xa6,0x1a,0x13,0x00,0xe3,0xa8,0x16,0x72,0x40,0xf9,0xf8,0x42, 0x44,0x26,0x68,0x96,0x81,0xd9,0x45,0x3e,0x10,0x76,0xc6,0xa7,0x8b,0x39,0x43,0xe1, 0x3a,0xb5,0x56,0x2a,0xc0,0x6d,0xb3,0x05,0x22,0x66,0xbf,0xdc,0x0b,0xfa,0x62,0x48, 0xdd,0x20,0x11,0x06,0x36,0xc9,0xc1,0xcf,0xf6,0x27,0x52,0xbb,0x69,0xf5,0xd4,0x87, 0x7f,0x84,0x4c,0xd2,0x9c,0x57,0xa4,0xbc,0x4f,0x9a,0xdf,0xfe,0xd6,0x8d,0x7a,0xeb, 0x2b,0x53,0xd8,0x5c,0xa1,0x14,0x17,0xfb,0x23,0xd5,0x7d,0x30,0x67,0x73,0x08,0x09, 0xee,0xb7,0x70,0x3f,0x61,0xb2,0x19,0x8e,0x4e,0xe5,0x4b,0x93,0x8f,0x5d,0xdb,0xa9, 0xad,0xf1,0xae,0x2e,0xcb,0x0d,0xfc,0xf4,0x2d,0x46,0x6e,0x1d,0x97,0xe8,0xd1,0xe9, 0x4d,0x37,0xa5,0x75,0x5e,0x83,0x9e,0xab,0x82,0x9d,0xb9,0x1c,0xe0,0xcd,0x49,0x89, 0x01,0xb6,0xbd,0x58,0x24,0xa2,0x5f,0x38,0x78,0x99,0x15,0x90,0x50,0xb8,0x95,0xe4, 0xd0,0x91,0xc7,0xce,0xed,0x0f,0xb4,0x6f,0xa0,0xcc,0xf0,0x02,0x4a,0x79,0xc3,0xde, 0xa3,0xef,0xea,0x51,0xe6,0x6b,0x18,0xec,0x1b,0x2c,0x80,0xf7,0x74,0xe7,0xff,0x21, 0x5a,0x6a,0x54,0x1e,0x41,0x31,0x92,0x35,0xc4,0x33,0x07,0x0a,0xba,0x7e,0x0e,0x34, 0x88,0xb1,0x98,0x7c,0xf3,0x3d,0x60,0x6c,0x7b,0xca,0xd3,0x1f,0x32,0x65,0x04,0x28, 0x64,0xbe,0x85,0x9b,0x2f,0x59,0x8a,0xd7,0xb0,0x25,0xac,0xaf,0x12,0x03,0xe2,0xf2]) # Bijective S-Boxes mapping 7 bits to 7 # ===================================== WAGE = SBox([ 0x2e, 0x1c, 0x6d, 0x2b, 0x35, 0x07, 0x7f, 0x3b, 0x28, 0x08, 0x0b, 0x5f, 0x31, 0x11, 0x1b, 0x4d, 0x6e, 0x54, 0x0d, 0x09, 0x1f, 0x45, 0x75, 0x53, 0x6a, 0x5d, 0x61, 0x00, 0x04, 0x78, 0x06, 0x1e, 0x37, 0x6f, 0x2f, 0x49, 0x64, 0x34, 0x7d, 0x19, 0x39, 0x33, 0x43, 0x57, 0x60, 0x62, 0x13, 0x05, 0x77, 0x47, 0x4f, 0x4b, 0x1d, 0x2d, 0x24, 0x48, 0x74, 0x58, 0x25, 0x5e, 0x5a, 0x76, 0x41, 0x42, 0x27, 0x3e, 0x6c, 0x01, 0x2c, 0x3c, 0x4e, 0x1a, 0x21, 0x2a, 0x0a, 0x55, 0x3a, 0x38, 0x18, 0x7e, 0x0c, 0x63, 0x67, 0x56, 0x50, 0x7c, 0x32, 0x7a, 0x68, 0x02, 0x6b, 0x17, 0x7b, 0x59, 0x71, 0x0f, 0x30, 0x10, 0x22, 0x3d, 0x40, 0x69, 0x52, 0x14, 0x36, 0x44, 0x46, 0x03, 0x16, 0x65, 0x66, 0x72, 0x12, 0x0e, 0x29, 0x4a, 0x4c, 0x70, 0x15, 0x26, 0x79, 0x51, 0x23, 0x3f, 0x73, 0x5b, 0x20, 0x5c]) # Bijective S-Boxes mapping 6 bits to 6 # ===================================== Fides_6 = SBox([ 0x36,0x00,0x30,0x0d,0x0f,0x12,0x23,0x35,0x3f,0x19,0x2d,0x34,0x03,0x14,0x21,0x29, 0x08,0x0a,0x39,0x25,0x3b,0x24,0x22,0x02,0x1a,0x32,0x3a,0x18,0x3c,0x13,0x0e,0x2a, 0x2e,0x3d,0x05,0x31,0x1f,0x0b,0x1c,0x04,0x0c,0x1e,0x37,0x16,0x09,0x06,0x20,0x17, 0x1b,0x27,0x15,0x11,0x10,0x1d,0x3e,0x01,0x28,0x2f,0x33,0x38,0x07,0x2b,0x26,0x2c]) APN_6 = SBox([ 0x0,0x36,0x30,0xd,0xf,0x12,0x35,0x23,0x19,0x3f,0x2d,0x34,0x3,0x14,0x29,0x21, 0x3b,0x24,0x2,0x22,0xa,0x8,0x39,0x25,0x3c,0x13,0x2a,0xe,0x32,0x1a,0x3a,0x18, 0x27,0x1b,0x15,0x11,0x10,0x1d,0x1,0x3e,0x2f,0x28,0x33,0x38,0x7,0x2b,0x2c,0x26, 0x1f,0xb,0x4,0x1c,0x3d,0x2e,0x5,0x31,0x9,0x6,0x17,0x20,0x1e,0xc,0x37,0x16]) SC2000_6 = SBox([ 47,59,25,42,15,23,28,39,26,38,36,19,60,24,29,56, 37,63,20,61,55,2,30,44,9,10,6,22,53,48,51,11, 62,52,35,18,14,46,0,54,17,40,27,4,31,8,5,12, 3,16,41,34,33,7,45,49,50,58,1,21,43,57,32,13]) # Bijective S-Boxes mapping 5 bits to 5 # ===================================== Ascon = SBox([ 0x04,0x0b,0x1f,0x14,0x1a,0x15,0x09,0x02,0x1b,0x05,0x08,0x12,0x1d,0x03,0x06,0x1c, 0x1e,0x13,0x07,0x0e,0x00,0x0d,0x11,0x18,0x10,0x0c,0x01,0x19,0x16,0x0a,0x0f,0x17]) ISAP = Ascon DryGASCON128 = SBox([0x04, 0x0f, 0x1b, 0x01, 0x0b, 0x00, 0x17, 0x0d, 0x1f, 0x1c, 0x02, 0x10, 0x12, 0x11, 0x0c, 0x1e, 0x1a, 0x19, 0x14, 0x06, 0x15, 0x16, 0x18, 0x0a, 0x05, 0x0e, 0x09, 0x13, 0x08, 0x03, 0x07, 0x1d]) Fides_5 = SBox([ 0x01,0x00,0x19,0x1a,0x11,0x1d,0x15,0x1b,0x14,0x05,0x04,0x17,0x0e,0x12,0x02,0x1c, 0x0f,0x08,0x06,0x03,0x0d,0x07,0x18,0x10,0x1e,0x09,0x1f,0x0a,0x16,0x0c,0x0b,0x13]) SC2000_5 = SBox([ 20,26,7,31,19,12,10,15,22,30,13,14,4,24,9, 18,27,11,1,21,6,16,2,28,23,5,8,3,0,17,29,25]) Shamash = SBox([16, 14, 13, 2, 11, 17, 21, 30, 7, 24, 18, 28, 26, 1, 12, 6, 31, 25, 0, 23, 20, 22, 8, 27, 4, 3, 19, 5, 9, 10, 29, 15]) SYCON = SBox([8, 19, 30, 7, 6, 25, 16, 13, 22, 15, 3, 24, 17, 12, 4, 27, 11, 0, 29, 20, 1, 14, 23, 26, 28, 21, 9, 2, 31, 18, 10, 5]) # Bijective S-Boxes mapping 4 bits to 4 # ===================================== Elephant = SBox([0xE, 0xD, 0xB, 0x0, 0x2, 0x1, 0x4, 0xF, 0x7, 0xA, 0x8, 0x5, 0x9, 0xC, 0x3, 0x6]) KNOT = SBox([0x4, 0x0, 0xA, 0x7, 0xB, 0xE, 0x1, 0xD, 0x9, 0xF, 0x6, 0x8, 0x5, 0x2, 0xC, 0x3]) Pyjamask_4 = SBox([0x2, 0xd, 0x3, 0x9, 0x7, 0xb, 0xa, 0x6, 0xe, 0x0, 0xf, 0x4, 0x8, 0x5, 0x1, 0xc]) SATURNIN_0 = SBox([0x0, 0x6, 0xE, 0x1, 0xF, 0x4, 0x7, 0xD, 0x9, 0x8, 0xC, 0x5, 0x2, 0xA, 0x3, 0xB]) SATURNIN_1 = SBox([0x0, 0x9, 0xD, 0x2, 0xF, 0x1, 0xB, 0x7, 0x6, 0x4, 0x5, 0x3, 0x8, 0xC, 0xA, 0xE]) Spook = SBox([0x0, 0x8, 0x1, 0xF, 0x2, 0xA, 0x7, 0x9, 0x4, 0xD, 0x5, 0x6, 0xE, 0x3, 0xB, 0xC]) Clyde = Spook Shadow = Spook TRIFLE = SBox([0x0, 0xC, 0x9, 0x7, 0x3, 0x5, 0xE, 0x4, 0x6, 0xB, 0xA, 0x2, 0xD, 0x1, 0x8, 0xF]) Yarara = SBox([0x4, 0x7, 0x1, 0xC, 0x2, 0x8, 0xF, 0x3, 0xD, 0xA, 0xe, 0x9, 0xB, 0x6, 0x5, 0x0]) Coral = Yarara # DES DES_S1_1 = SBox([14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7]) DES_S1_2 = SBox([0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8]) DES_S1_3 = SBox([4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0]) DES_S1_4 = SBox([15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13]) DES_S2_1 = SBox([15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10]) DES_S2_2 = SBox([3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5]) DES_S2_3 = SBox([0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15]) DES_S2_4 = SBox([13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9]) DES_S3_1 = SBox([10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8]) DES_S3_2 = SBox([13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1]) DES_S3_3 = SBox([13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7]) DES_S3_4 = SBox([1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12]) DES_S4_1 = SBox([7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15]) DES_S4_2 = SBox([13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9]) DES_S4_3 = SBox([10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4]) DES_S4_4 = SBox([3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14]) DES_S5_1 = SBox([2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9]) DES_S5_2 = SBox([14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6]) DES_S5_3 = SBox([4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14]) DES_S5_4 = SBox([11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3]) DES_S6_1 = SBox([12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11]) DES_S6_2 = SBox([10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8]) DES_S6_3 = SBox([9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6]) DES_S6_4 = SBox([4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13]) DES_S7_1 = SBox([4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1]) DES_S7_2 = SBox([13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6]) DES_S7_3 = SBox([1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2]) DES_S7_4 = SBox([6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12]) DES_S8_1 = SBox([13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7]) DES_S8_2 = SBox([1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2]) DES_S8_3 = SBox([7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8]) DES_S8_4 = SBox([2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11]) # source: http://www.quadibloc.com/crypto/co0401.htm Lucifer_S0 = SBox([12,15,7,10,14,13,11,0,2,6,3,1,9,4,5,8]) Lucifer_S1 = SBox([7,2,14,9,3,11,0,4,12,13,1,10,6,15,8,5]) # First GOST block cipher and its modification. # ref: https://en.wikipedia.org/wiki/GOST_28147-89 GOST_1 = SBox([0x4,0xa,0x9,0x2,0xd,0x8,0x0,0xe,0x6,0xb,0x1,0xc,0x7,0xf,0x5,0x3]) GOST_2 = SBox([0xe,0xb,0x4,0xc,0x6,0xd,0xf,0xa,0x2,0x3,0x8,0x1,0x0,0x7,0x5,0x9]) GOST_3 = SBox([0x5,0x8,0x1,0xd,0xa,0x3,0x4,0x2,0xe,0xf,0xc,0x7,0x6,0x0,0x9,0xb]) GOST_4 = SBox([0x7,0xd,0xa,0x1,0x0,0x8,0x9,0xf,0xe,0x4,0x6,0xc,0xb,0x2,0x5,0x3]) GOST_5 = SBox([0x6,0xc,0x7,0x1,0x5,0xf,0xd,0x8,0x4,0xa,0x9,0xe,0x0,0x3,0xb,0x2]) GOST_6 = SBox([0x4,0xb,0xa,0x0,0x7,0x2,0x1,0xd,0x3,0x6,0x8,0x5,0x9,0xc,0xf,0xe]) GOST_7 = SBox([0xd,0xb,0x4,0x1,0x3,0xf,0x5,0x9,0x0,0xa,0xe,0x7,0x6,0x8,0x2,0xc]) GOST_8 = SBox([0x1,0xf,0xd,0x0,0x5,0x7,0xa,0x4,0x9,0x2,0x3,0xe,0x6,0xb,0x8,0xc]) # ref: https://eprint.iacr.org/2015/065.pdf GOST2_1 = SBox([0x6,0xA,0xF,0x4,0x3,0x8,0x5,0x0,0xD,0xE,0x7,0x1,0x2,0xB,0xC,0x9]) GOST2_2 = SBox([0xE,0x0,0x8,0x1,0x7,0xA,0x5,0x6,0xD,0x2,0x4,0x9,0x3,0xF,0xC,0xB]) Magma_1 = SBox([0xC,0x4,0x6,0x2,0xA,0x5,0xB,0x9,0xE,0x8,0xD,0x7,0x0,0x3,0xF,0x1]) Magma_2 = SBox([0x6,0x8,0x2,0x3,0x9,0xA,0x5,0xC,0x1,0xE,0x4,0x7,0xB,0xD,0x0,0xF]) Magma_3 = SBox([0xB,0x3,0x5,0x8,0x2,0xF,0xA,0xD,0xE,0x1,0x7,0x4,0xC,0x9,0x6,0x0]) Magma_4 = SBox([0xC,0x8,0x2,0x1,0xD,0x4,0xF,0x6,0x7,0x0,0xA,0x5,0x3,0xE,0x9,0xB]) Magma_5 = SBox([0x7,0xF,0x5,0xA,0x8,0x1,0x6,0xD,0x0,0x9,0x3,0xE,0xB,0x4,0x2,0xC]) Magma_6 = SBox([0x5,0xD,0xF,0x6,0x9,0x2,0xC,0xA,0xB,0x7,0x8,0x1,0x4,0x3,0xE,0x0]) Magma_7 = SBox([0x8,0xE,0x2,0x5,0x6,0x9,0x1,0xC,0xF,0x4,0xB,0x0,0xD,0xA,0x3,0x7]) Magma_8 = SBox([0x1,0x7,0xE,0xD,0x0,0x5,0x8,0x3,0x4,0xF,0xA,0x6,0x9,0xC,0xB,0x2]) GOST_IETF_1 = SBox([0x9,0x6,0x3,0x2,0x8,0xb,0x1,0x7,0xa,0x4,0xe,0xf,0xc,0x0,0xd,0x5]) GOST_IETF_2 = SBox([0x3,0x7,0xe,0x9,0x8,0xa,0xf,0x0,0x5,0x2,0x6,0xc,0xb,0x4,0xd,0x1]) GOST_IETF_3 = SBox([0xe,0x4,0x6,0x2,0xb,0x3,0xd,0x8,0xc,0xf,0x5,0xa,0x0,0x7,0x1,0x9]) GOST_IETF_4 = SBox([0xe,0x7,0xa,0xc,0xd,0x1,0x3,0x9,0x0,0x2,0xb,0x4,0xf,0x8,0x5,0x6]) GOST_IETF_5 = SBox([0xb,0x5,0x1,0x9,0x8,0xd,0xf,0x0,0xe,0x4,0x2,0x3,0xc,0x7,0xa,0x6]) GOST_IETF_6 = SBox([0x3,0xa,0xd,0xc,0x1,0x2,0x0,0xb,0x7,0x5,0x9,0x4,0x8,0xf,0xe,0x6]) GOST_IETF_7 = SBox([0x1,0xd,0x2,0x9,0x7,0xa,0x6,0x0,0x8,0xc,0x4,0x5,0xf,0x3,0xb,0xe]) GOST_IETF_8 = SBox([0xb,0xa,0xf,0x5,0x0,0xc,0xe,0x8,0x6,0x2,0x3,0x9,0x1,0x7,0xd,0x4]) # Hummingbird-2 Hummingbird_2_S1 = SBox([7,12,14,9,2,1,5,15,11,6,13,0,4,8,10,3]) Hummingbird_2_S2 = SBox([4,10,1,6,8,15,7,12,3,0,14,13,5,9,11,2]) Hummingbird_2_S3 = SBox([2,15,12,1,5,6,10,13,14,8,3,4,0,11,9,7]) Hummingbird_2_S4 = SBox([15,4,5,8,9,7,2,1,10,3,0,14,6,12,13,11]) # LBlock LBlock_0 = SBox([14, 9, 15, 0, 13, 4, 10, 11, 1, 2, 8, 3, 7, 6, 12, 5]) LBlock_1 = SBox([4, 11, 14, 9, 15, 13, 0, 10, 7, 12, 5, 6, 2, 8, 1, 3]) LBlock_2 = SBox([1, 14, 7, 12, 15, 13, 0, 6, 11, 5, 9, 3, 2, 4, 8, 10]) LBlock_3 = SBox([7, 6, 8, 11, 0, 15, 3, 14, 9, 10, 12, 13, 5, 2, 4, 1]) LBlock_4 = SBox([14, 5, 15, 0, 7, 2, 12, 13, 1, 8, 4, 9, 11, 10, 6, 3]) LBlock_5 = SBox([2, 13, 11, 12, 15, 14, 0, 9, 7, 10, 6, 3, 1, 8, 4, 5]) LBlock_6 = SBox([11, 9, 4, 14, 0, 15, 10, 13, 6, 12, 5, 7, 3, 8, 1, 2]) LBlock_7 = SBox([13, 10, 15, 0, 14, 4, 9, 11, 2, 1, 8, 3, 7, 5, 12, 6]) LBlock_8 = SBox([8, 7, 14, 5, 15, 13, 0, 6, 11, 12, 9, 10, 2, 4, 1, 3]) LBlock_9 = SBox([11, 5, 15, 0, 7, 2, 9, 13, 4, 8, 1, 12, 14, 10, 3, 6]) # SERPENT SERPENT_S0 = SBox([3,8,15,1,10,6,5,11,14,13,4,2,7,0,9,12]) SERPENT_S1 = SBox([15,12,2,7,9,0,5,10,1,11,14,8,6,13,3,4]) SERPENT_S2 = SBox([8,6,7,9,3,12,10,15,13,1,14,4,0,11,5,2]) SERPENT_S3 = SBox([0,15,11,8,12,9,6,3,13,1,2,4,10,7,5,14]) SERPENT_S4 = SBox([1,15,8,3,12,0,11,6,2,5,4,10,9,14,7,13]) SERPENT_S5 = SBox([15,5,2,11,4,10,9,12,0,3,14,8,13,6,7,1]) SERPENT_S6 = SBox([7,2,12,5,8,4,6,11,14,9,1,15,13,3,10,0]) SERPENT_S7 = SBox([1,13,15,0,14,8,2,11,7,4,12,10,9,3,5,6]) # Other Block ciphers KLEIN = SBox([0x7,0x4,0xA,0x9,0x1,0xF,0xB,0x0,0xC,0x3,0x2,0x6,0x8,0xE,0xD,0x5]) MIBS = SBox([4,15,3,8,13,10,12,0,11,5,7,14,2,6,1,9]) Midori_Sb0 = SBox([0xc,0xa,0xd,0x3,0xe,0xb,0xf,0x7,0x8,0x9,0x1,0x5,0x0,0x2,0x4,0x6]) MANTIS = Midori_Sb0 CRAFT = Midori_Sb0 Midori_Sb1 = SBox([0x1,0x0,0x5,0x3,0xe,0x2,0xf,0x7,0xd,0xa,0x9,0xb,0xc,0x8,0x4,0x6]) Noekeon = SBox([0x7,0xA,0x2,0xC,0x4,0x8,0xF,0x0,0x5,0x9,0x1,0xE,0x3,0xD,0xB,0x6]) Piccolo = SBox([0xe,0x4,0xb,0x2,0x3,0x8,0x0,0x9,0x1,0xa,0x7,0xf,0x6,0xc,0x5,0xd]) Panda = SBox([0x0,0x1,0x3,0x2,0xf,0xc,0x9,0xb,0xa,0x6,0x8,0x7,0x5,0xe,0xd,0x4]) PRESENT = SBox([0xC,0x5,0x6,0xB,0x9,0x0,0xA,0xD,0x3,0xE,0xF,0x8,0x4,0x7,0x1,0x2]) CiliPadi = PRESENT PHOTON = PRESENT ORANGE = PHOTON GIFT = SBox([0x1,0xa,0x4,0xc,0x6,0xf,0x3,0x9,0x2,0xd,0xb,0x7,0x5,0x0,0x8,0xe]) HYENA = GIFT Fountain_1 = GIFT TGIF = GIFT Fountain_2 = SBox([0x9, 0x5, 0x6, 0xD, 0x8, 0xA, 0x7, 0x2, 0xE, 0x4, 0xC, 0x1, 0xF, 0x0, 0xB, 0x3]) Fountain_3 = SBox([0x9, 0xD, 0xE, 0x5, 0x8, 0xA, 0xF, 0x2, 0x6, 0xC, 0x4, 0x1, 0x7, 0x0, 0xB, 0x3]) Fountain_4 = SBox([0xB, 0xF, 0xE, 0x8, 0x7, 0xA, 0x2, 0xD, 0x9, 0x3, 0x4, 0xC, 0x5, 0x0, 0x6, 0x1]) Pride = SBox([0x0,0x4,0x8,0xf,0x1,0x5,0xe,0x9,0x2,0x7,0xa,0xc,0xb,0xd,0x6,0x3]) PRINCE = SBox([0xB,0xF,0x3,0x2,0xA,0xC,0x9,0x1,0x6,0x7,0x8,0x0,0xE,0x5,0xD,0x4]) Prost = Pride Qarma_sigma0 = SBox([0, 14, 2, 10, 9, 15, 8, 11, 6, 4, 3, 7, 13, 12, 1, 5]) Qarma_sigma1 = SBox([10, 13, 14, 6, 15, 7, 3, 5, 9, 8, 0, 12, 11, 1, 2, 4]) Qameleon = Qarma_sigma1 Qarma_sigma2 = SBox([11, 6, 8, 15, 12, 0, 9, 14, 3, 7, 4, 5, 13, 2, 1, 10]) REC_0 = SBox([0x9,0x4,0xF,0xA,0xE,0x1,0x0,0x6,0xC,0x7,0x3,0x8,0x2,0xB,0x5,0xD]) Rectangle = SBox([0x6,0x5,0xC,0xA,0x1,0xE,0x7,0x9,0xB,0x0,0x3,0xD,0x8,0xF,0x4,0x2]) SC2000_4 = SBox([2,5,10,12,7,15,1,11,13,6,0,9,4,8,3,14]) SKINNY_4 = SBox([0xc,0x6,0x9,0x0,0x1,0xa,0x2,0xb,0x3,0x8,0x5,0xd,0x4,0xe,0x7,0xf]) ForkSkinny_4 = SKINNY_4 Remus_4 = SKINNY_4 TWINE = SBox([0xC,0x0,0xF,0xA,0x2,0xB,0x9,0x5,0x8,0x3,0xD,0x7,0x1,0xE,0x6,0x4]) # Sub-components of hash functions Luffa_v1 = SBox([0x7,0xd,0xb,0xa,0xc,0x4,0x8,0x3,0x5,0xf,0x6,0x0,0x9,0x1,0x2,0xe]) Luffa = SBox([0xd,0xe,0x0,0x1,0x5,0xa,0x7,0x6,0xb,0x3,0x9,0xc,0xf,0x8,0x2,0x4]) BLAKE_1 = SBox([14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3]) BLAKE_2 = SBox([11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4]) BLAKE_3 = SBox([7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8]) BLAKE_4 = SBox([9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13]) BLAKE_5 = SBox([2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]) BLAKE_6 = SBox([12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11]) BLAKE_7 = SBox([13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10]) BLAKE_8 = SBox([6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5]) BLAKE_9 = SBox([10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]) JH_S0 = SBox([9,0,4,11,13,12,3,15,1,10,2,6,7,5,8,14]) JH_S1 = SBox([3,12,6,13,5,7,1,9,15,2,0,4,11,10,14,8]) SMASH_256_S1 = SBox([6,13,12,7,15,1,3,10,8,11,5,0,2,4,14,9]) SMASH_256_S2 = SBox([1,11,6,0,14,13,5,10,12,2,9,7,3,8,15,4]) SMASH_256_S3 = SBox([4,2,9,12,8,1,14,7,15,5,0,11,6,10,3,13]) # Sub-components of larger S-Boxes Anubis_S0 = SBox([0xd,0x7,0x3,0x2,0x9,0xa,0xc,0x1,0xf,0x4,0x5,0xe,0x6,0x0,0xb,0x8]) Anubis_S1 = SBox([0x4,0xa,0xf,0xc,0x0,0xd,0x9,0xb,0xe,0x6,0x1,0x7,0x3,0x5,0x8,0x2]) CLEFIA_SS0 = SBox([0xe,0x6,0xc,0xa,0x8,0x7,0x2,0xf,0xb,0x1,0x4,0x0,0x5,0x9,0xd,0x3]) CLEFIA_SS1 = SBox([0x6,0x4,0x0,0xd,0x2,0xb,0xa,0x3,0x9,0xc,0xe,0xf,0x8,0x7,0x5,0x1]) CLEFIA_SS2 = SBox([0xb,0x8,0x5,0xe,0xa,0x6,0x4,0xc,0xf,0x7,0x2,0x3,0x1,0x0,0xd,0x9]) CLEFIA_SS3 = SBox([0xa,0x2,0x6,0xd,0x3,0x4,0x5,0xe,0x0,0x7,0x8,0x9,0xb,0xf,0xc,0x1]) Enocoro_S4 = SBox([1,3,9,10,5,14,7,2,13,0,12,15,4,8,6,11]) Iceberg_S0 = Anubis_S0 Iceberg_S1 = Anubis_S1 Khazad_P = SBox([0x3,0xF,0xE,0x0,0x5,0x4,0xB,0xC,0xD,0xA,0x9,0x6,0x7,0x8,0x2,0x1]) Khazad_Q = SBox([0x9,0xE,0x5,0x6,0xA,0x2,0x3,0xC,0xF,0x0,0x4,0xD,0x7,0xB,0x1,0x8]) Whirlpool_E = SBox([0x1,0xB,0x9,0xC,0xD,0x6,0xF,0x3,0xE,0x8,0x7,0x4,0xA,0x2,0x5,0x0]) Whirlpool_R = SBox([0x7,0xC,0xB,0xD,0xE,0x4,0x9,0xF,0x6,0x3,0x8,0xA,0x2,0x5,0x1,0x0]) CS_cipher_F = SBox([0xf,0xd,0xb,0xb,0x7,0x5,0x7,0x7,0xe,0xd,0xa,0xb,0xe,0xd,0xe,0xf]) CS_cipher_G = SBox([0xa,0x6,0x0,0x2,0xb,0xe,0x1,0x8,0xd,0x4,0x5,0x3,0xf,0xc,0x7,0x9]) Fox_S1 = SBox([0x2,0x5,0x1,0x9,0xE,0xA,0xC,0x8,0x6,0x4,0x7,0xF,0xD,0xB,0x0,0x3]) Fox_S2 = SBox([0xB,0x4,0x1,0xF,0x0,0x3,0xE,0xD,0xA,0x8,0x7,0x5,0xC,0x2,0x9,0x6]) Fox_S3 = SBox([0xD,0xA,0xB,0x1,0x4,0x3,0x8,0x9,0x5,0x7,0x2,0xC,0xF,0x0,0x6,0xE]) Twofish_Q0_T0 = SBox([0x8,0x1,0x7,0xD,0x6,0xF,0x3,0x2,0x0,0xB,0x5,0x9,0xE,0xC,0xA,0x4]) Twofish_Q0_T1 = SBox([0xE,0xC,0xB,0x8,0x1,0x2,0x3,0x5,0xF,0x4,0xA,0x6,0x7,0x0,0x9,0xD]) Twofish_Q0_T2 = SBox([0xB,0xA,0x5,0xE,0x6,0xD,0x9,0x0,0xC,0x8,0xF,0x3,0x2,0x4,0x7,0x1]) Twofish_Q0_T3 = SBox([0xD,0x7,0xF,0x4,0x1,0x2,0x6,0xE,0x9,0xB,0x3,0x0,0x8,0x5,0xC,0xA]) Twofish_Q1_T0 = SBox([0x2,0x8,0xB,0xD,0xF,0x7,0x6,0xE,0x3,0x1,0x9,0x4,0x0,0xA,0xC,0x5]) Twofish_Q1_T1 = SBox([0x1,0xE,0x2,0xB,0x4,0xC,0x3,0x7,0x6,0xD,0xA,0x5,0xF,0x9,0x0,0x8]) Twofish_Q1_T2 = SBox([0x4,0xC,0x7,0x5,0x1,0x6,0x9,0xA,0x0,0xE,0xD,0x8,0x2,0xB,0x3,0xF]) Twofish_Q1_T3 = SBox([0xB,0x9,0x5,0x1,0xC,0x3,0xD,0xE,0x6,0x4,0x7,0xF,0x2,0x0,0x8,0xA]) Kuznyechik_nu0 = SBox([0x2,0x5,0x3,0xb,0x6,0x9,0xe,0xa,0x0,0x4,0xf,0x1,0x8,0xd,0xc,0x7]) Kuznyechik_nu1 = SBox([0x7,0x6,0xc,0x9,0x0,0xf,0x8,0x1,0x4,0x5,0xb,0xe,0xd,0x2,0x3,0xa]) Kuznyechik_sigma = SBox([0xc,0xd,0x0,0x4,0x8,0xb,0xa,0xe,0x3,0x9,0x5,0x2,0xf,0x1,0x6,0x7]) Kuznyechik_phi = SBox([0xb,0x2,0xb,0x8,0xc,0x4,0x1,0xc,0x6,0x3,0x5,0x8,0xe,0x3,0x6,0xb]) Optimal_S0 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 11, 12, 9, 3, 14, 10, 5]) Optimal_S1 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 11, 14, 3, 5, 9, 10, 12]) Optimal_S2 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 11, 14, 3, 10, 12, 5, 9]) Optimal_S3 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 12, 5, 3, 10, 14, 11, 9]) Optimal_S4 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 12, 9, 11, 10, 14, 5, 3]) Optimal_S5 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 12, 11, 9, 10, 14, 3, 5]) Optimal_S6 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 12, 11, 9, 10, 14, 5, 3]) Optimal_S7 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 12, 14, 11, 10, 9, 3, 5]) Optimal_S8 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 14, 9, 5, 10, 11, 3, 12]) Optimal_S9 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 14, 11, 3, 5, 9, 10, 12]) Optimal_S10 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 14, 11, 5, 10, 9, 3, 12]) Optimal_S11 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 14, 11, 10, 5, 9, 12, 3]) Optimal_S12 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 14, 11, 10, 9, 3, 12, 5]) Optimal_S13 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 14, 12, 9, 5, 11, 10, 3]) Optimal_S14 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 14, 12, 11, 3, 9, 5, 10]) Optimal_S15 = SBox([0, 1, 2, 13, 4, 7, 15, 6, 8, 14, 12, 11, 9, 3, 10, 5]) Serpent_type_S0 = SBox([0, 3, 5, 6, 7, 10, 11, 12, 13, 4, 14, 9, 8, 1, 2, 15]) Serpent_type_S1 = SBox([0, 3, 5, 8, 6, 9, 10, 7, 11, 12, 14, 2, 1, 15, 13, 4]) Serpent_type_S2 = SBox([0, 3, 5, 8, 6, 9, 11, 2, 13, 4, 14, 1, 10, 15, 7, 12]) Serpent_type_S3 = SBox([0, 3, 5, 8, 6, 10, 15, 4, 14, 13, 9, 2, 1, 7, 12, 11]) Serpent_type_S4 = SBox([0, 3, 5, 8, 6, 12, 11, 7, 9, 14, 10, 13, 15, 2, 1, 4]) Serpent_type_S5 = SBox([0, 3, 5, 8, 6, 12, 11, 7, 10, 4, 9, 14, 15, 1, 2, 13]) Serpent_type_S6 = SBox([0, 3, 5, 8, 6, 12, 11, 7, 10, 13, 9, 14, 15, 1, 2, 4]) Serpent_type_S7 = SBox([0, 3, 5, 8, 6, 12, 11, 7, 13, 10, 14, 4, 1, 15, 2, 9]) Serpent_type_S8 = SBox([0, 3, 5, 8, 6, 12, 15, 1, 10, 4, 9, 14, 13, 11, 2, 7]) Serpent_type_S9 = SBox([0, 3, 5, 8, 6, 12, 15, 2, 14, 9, 11, 7, 13, 10, 4, 1]) Serpent_type_S10 = SBox([0, 3, 5, 8, 6, 13, 15, 1, 9, 12, 2, 11, 10, 7, 4, 14]) Serpent_type_S11 = SBox([0, 3, 5, 8, 6, 13, 15, 2, 7, 4, 14, 11, 10, 1, 9, 12]) Serpent_type_S12 = SBox([0, 3, 5, 8, 6, 13, 15, 2, 12, 9, 10, 4, 11, 14, 1, 7]) Serpent_type_S13 = SBox([0, 3, 5, 8, 6, 15, 10, 1, 7, 9, 14, 4, 11, 12, 13, 2]) Serpent_type_S14 = SBox([0, 3, 5, 8, 7, 4, 9, 14, 15, 6, 2, 11, 10, 13, 12, 1]) Serpent_type_S15 = SBox([0, 3, 5, 8, 7, 9, 11, 14, 10, 13, 15, 4, 12, 2, 6, 1]) Serpent_type_S16 = SBox([0, 3, 5, 8, 9, 12, 14, 7, 10, 13, 15, 4, 6, 11, 1, 2]) Serpent_type_S17 = SBox([0, 3, 5, 8, 10, 13, 9, 4, 15, 6, 2, 1, 12, 11, 7, 14]) Serpent_type_S18 = SBox([0, 3, 5, 8, 11, 12, 6, 15, 14, 9, 2, 7, 4, 10, 13, 1]) Serpent_type_S19 = SBox([0, 3, 5, 10, 7, 12, 11, 6, 13, 4, 2, 9, 14, 1, 8, 15]) Golden_S0 = SBox([0, 3, 5, 8, 6, 9, 12, 7, 13, 10, 14, 4, 1, 15, 11, 2]) Golden_S1 = Serpent_type_S4 Golden_S2 = Serpent_type_S3 Golden_S3 = Serpent_type_S5 # S-Boxes from the literature on Boolean functions # Ullrich, Markus, et al. "Finding optimal bitsliced implementations # of 4x4-bit S-boxes." SKEW 2011 Symmetric Key Encryption Workshop, # Copenhagen, Denmark. 2011. UDCIKMP11 = SBox([0x0,0x8,0x6,0xD,0x5,0xF,0x7,0xC,0x4,0xE,0x2,0x3,0x9,0x1,0xB,0xA]) # Bijective S-Boxes mapping 3 bits to 3 # ===================================== SEA = SBox([0x0,0x5,0x6,0x7,0x4,0x3,0x1,0x2]) PRINTcipher = SBox([0x0, 0x1, 0x3, 0x6, 0x7, 0x4, 0x5, 0x2]) Pyjamask_3 = SBox([0x1, 0x3, 0x6, 0x5, 0x2, 0x4, 0x7, 0x0]) affine_equiv_classes = {} # affine equivalent classes for 4 bit affine_equiv_classes[4] = [ SBox([0x4, 0x0, 0x1, 0xF, 0x2, 0xB, 0x6, 0x7, 0x3, 0x9, 0xA, 0x5, 0xC, 0xD, 0xE, 0x8]), SBox([0x8, 0x0, 0x1, 0xC, 0x2, 0x5, 0x6, 0x9, 0x4, 0x3, 0xA, 0xB, 0x7, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xC, 0xF, 0x5, 0x6, 0x7, 0x4, 0x3, 0xA, 0xB, 0x9, 0xD, 0xE, 0x2]), SBox([0x2, 0x0, 0x1, 0x8, 0x3, 0xD, 0x6, 0x7, 0x4, 0x9, 0xA, 0x5, 0xC, 0xB, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x8, 0x3, 0xF, 0x6, 0x7, 0x4, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xA]), SBox([0x2, 0x0, 0x1, 0x8, 0x3, 0xB, 0x6, 0x7, 0x4, 0x9, 0xA, 0xF, 0xC, 0xD, 0xE, 0x5]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0xB, 0x6, 0x7, 0x0, 0x9, 0xA, 0xE, 0xC, 0xD, 0x5, 0xF]), SBox([0x8, 0x0, 0x1, 0x9, 0x2, 0x5, 0xD, 0x7, 0x4, 0x6, 0xA, 0xB, 0xC, 0x3, 0xE, 0xF]), SBox([0x8, 0xE, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0xC, 0xA, 0xB, 0x9, 0xD, 0x0, 0xF]), SBox([0x8, 0xE, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xF, 0xB, 0xC, 0xD, 0x0, 0xA]), SBox([0x8, 0xF, 0x1, 0x2, 0x3, 0x5, 0xC, 0x7, 0x4, 0x9, 0xA, 0xB, 0x6, 0xD, 0xE, 0x0]), SBox([0x8, 0xF, 0x1, 0x2, 0x3, 0x5, 0x6, 0xD, 0x4, 0x9, 0xA, 0xB, 0xC, 0x7, 0xE, 0x0]), SBox([0xC, 0x0, 0x1, 0x9, 0x3, 0x5, 0x4, 0x7, 0x6, 0x2, 0xA, 0xB, 0x8, 0xD, 0xE, 0xF]), SBox([0xC, 0xB, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0x0, 0x8, 0xD, 0xE, 0xF]), SBox([0xC, 0x9, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x0, 0xA, 0xB, 0x8, 0xD, 0xE, 0xF]), SBox([0x8, 0xE, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0x0, 0xC, 0xD, 0xB, 0xF]), SBox([0x8, 0xA, 0x1, 0x2, 0x3, 0xB, 0x6, 0x7, 0x4, 0x9, 0x0, 0x5, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0xC, 0x3, 0x7, 0x6, 0x9, 0xA, 0xB, 0x5, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0x3, 0xB, 0x6, 0x9, 0xA, 0x7, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0x3, 0xE, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0x7, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0x3, 0x5, 0x4, 0xB, 0x0, 0x9, 0xA, 0x7, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x9, 0x3, 0x7, 0x6, 0x5, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0xF, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0x0, 0xB, 0xC, 0xD, 0xE, 0xA]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0xF, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x3]), SBox([0xD, 0x0, 0x1, 0x2, 0x3, 0x5, 0xE, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0x8, 0x4, 0xF]), SBox([0xC, 0xA, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0x0, 0xB, 0x8, 0xD, 0xE, 0xF]), SBox([0xC, 0x0, 0x1, 0x2, 0x3, 0x5, 0xF, 0x7, 0x6, 0x9, 0xA, 0xB, 0x8, 0xD, 0xE, 0x4]), SBox([0x8, 0xA, 0x1, 0x2, 0x3, 0x0, 0x4, 0x7, 0x6, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0xD, 0x1, 0x2, 0x3, 0x0, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0x5, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0xE, 0x3, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0xD, 0x2, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0xA, 0x7, 0x6, 0x9, 0x3, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0xC, 0x0, 0xA, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0x1, 0xB, 0x8, 0xD, 0xE, 0xF]), SBox([0xD, 0x0, 0xA, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0x1, 0xB, 0xC, 0x8, 0xE, 0xF]), SBox([0x8, 0xF, 0x1, 0x2, 0x3, 0xC, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0x5, 0xD, 0xE, 0x0]), SBox([0x8, 0x0, 0x1, 0xC, 0x2, 0x5, 0xB, 0x7, 0x4, 0x9, 0xA, 0x6, 0x3, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xC, 0x2, 0x5, 0xD, 0x7, 0x4, 0x9, 0xA, 0xB, 0x3, 0x6, 0xE, 0xF]), SBox([0xC, 0x0, 0x1, 0x2, 0x3, 0xF, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0x8, 0xD, 0xE, 0x5]), SBox([0xC, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0xD, 0x4, 0x9, 0xA, 0xB, 0x8, 0x7, 0xE, 0xF]), SBox([0x8, 0xA, 0x1, 0x2, 0x3, 0x5, 0x6, 0x9, 0x4, 0x7, 0x0, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xC, 0x2, 0xE, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0x3, 0xD, 0x5, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0xD, 0x3, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0x5, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0xA, 0x3, 0x7, 0x6, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0x3, 0x5, 0x4, 0xC, 0x0, 0x9, 0xA, 0xB, 0x7, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0x3, 0x5, 0x4, 0xD, 0x0, 0x9, 0xA, 0xB, 0xC, 0x7, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0x3, 0x5, 0x4, 0x9, 0x0, 0x7, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0xD, 0xA, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0x0, 0xB, 0xC, 0x8, 0xE, 0xF]), SBox([0xE, 0x0, 0x1, 0xA, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0x2, 0xB, 0xC, 0xD, 0x8, 0xF]), SBox([0x8, 0xA, 0x1, 0x2, 0x3, 0x5, 0x9, 0x7, 0x4, 0x6, 0x0, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xD, 0x2, 0x5, 0x6, 0x7, 0x4, 0x9, 0x3, 0xB, 0xC, 0xA, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x6, 0x2, 0x5, 0xD, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0x3, 0xE, 0xF]), SBox([0x8, 0xC, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0x0, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0xD, 0x2, 0x3, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0x1, 0xE, 0xF]), SBox([0x6, 0x8, 0xE, 0x2, 0x3, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0xD, 0x1, 0xF]), SBox([0x4, 0x0, 0x1, 0xF, 0x2, 0x5, 0x3, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x8]), SBox([0x4, 0x0, 0x1, 0xA, 0x2, 0x8, 0x6, 0x7, 0x3, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0xA, 0x2, 0x5, 0x6, 0x8, 0x3, 0x9, 0x7, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x0, 0x8, 0xF, 0x3, 0x5, 0x4, 0x7, 0x1, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x2]), SBox([0x6, 0x0, 0x8, 0xC, 0x3, 0x5, 0x4, 0x7, 0x1, 0x9, 0xA, 0xB, 0x2, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0xC, 0x3, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0x2, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0xD, 0x3, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0x2, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xC, 0x2, 0x5, 0x6, 0x7, 0x4, 0x3, 0xA, 0xB, 0x9, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xA, 0x2, 0x5, 0x6, 0x3, 0x4, 0x9, 0x7, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xD, 0x2, 0x5, 0x3, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0x6, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xA, 0x2, 0x5, 0x6, 0x7, 0x4, 0x9, 0xD, 0xB, 0xC, 0x3, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xE, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0x2, 0xF]), SBox([0x6, 0x0, 0x1, 0x8, 0xD, 0x5, 0x4, 0x7, 0x2, 0x9, 0xA, 0xB, 0xC, 0x3, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0xF, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x3]), SBox([0x6, 0x8, 0x1, 0x2, 0x3, 0xA, 0x4, 0x7, 0x0, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x3, 0x2, 0xA, 0x6, 0x7, 0x4, 0x9, 0xF, 0xB, 0xC, 0xD, 0xE, 0x5]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0xB, 0x7, 0x6, 0x9, 0xA, 0x3, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x6, 0x2, 0x5, 0xC, 0x7, 0x4, 0x9, 0xA, 0xB, 0x3, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x7, 0x2, 0x5, 0x6, 0xC, 0x4, 0x9, 0xA, 0xB, 0x3, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0x9, 0x7, 0x6, 0x3, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0x3, 0x9, 0x4, 0x7, 0x0, 0x5, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x9, 0x3, 0x5, 0x4, 0x7, 0x0, 0x2, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x9, 0x2, 0x5, 0x3, 0x7, 0x4, 0x6, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xC, 0x2, 0x5, 0x3, 0x7, 0x4, 0x9, 0xA, 0xB, 0x6, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x3, 0x2, 0xF, 0x6, 0x7, 0x4, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xA]), SBox([0x6, 0xD, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0x8, 0xE, 0xF]), SBox([0x8, 0xB, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0x0, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0xD, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0x0, 0xE, 0xF]), SBox([0x6, 0x8, 0xF, 0x2, 0x3, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x1]), SBox([0x6, 0x8, 0xC, 0x2, 0x3, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0x1, 0xD, 0xE, 0xF]), SBox([0x8, 0x5, 0x1, 0x2, 0x3, 0x0, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0xA, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0x0, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0x3, 0x5, 0xA, 0x7, 0x0, 0x9, 0x4, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0xA, 0x1, 0xC, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0x0, 0xB, 0x2, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xC, 0x2, 0x5, 0x6, 0x3, 0x4, 0x9, 0xA, 0xB, 0x7, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x8, 0x3, 0xB, 0x6, 0x7, 0x4, 0x9, 0xA, 0x5, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0xB, 0x6, 0x7, 0x0, 0x9, 0xA, 0x5, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0x6, 0x9, 0x0, 0x7, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x6, 0x1, 0x2, 0x9, 0x5, 0x0, 0x7, 0x4, 0x3, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0x3, 0xB, 0x4, 0x7, 0x0, 0x9, 0xA, 0x5, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0x3, 0xE, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0xD, 0x5, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0x3, 0xF, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x5]), SBox([0xF, 0x0, 0x1, 0x3, 0x2, 0xC, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0x5, 0xD, 0xE, 0x8]), SBox([0x8, 0xD, 0x1, 0x2, 0x3, 0x5, 0x0, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0x6, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0xE, 0x2, 0x5, 0x6, 0x7, 0x3, 0x9, 0x8, 0xB, 0xC, 0xD, 0xA, 0xF]), SBox([0x8, 0x0, 0x1, 0xF, 0x2, 0x5, 0x3, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x6]), SBox([0x2, 0x0, 0x1, 0x3, 0xF, 0xA, 0x6, 0x7, 0x4, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0x8]), SBox([0x2, 0x0, 0x1, 0x8, 0x3, 0xA, 0x6, 0x7, 0x4, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x8, 0x3, 0xD, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0x5, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0xB, 0x6, 0x7, 0x3, 0x9, 0xA, 0x5, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0xC, 0x6, 0x7, 0x3, 0x9, 0xA, 0xB, 0x5, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x8, 0x3, 0x5, 0x6, 0x7, 0x4, 0xC, 0xA, 0xB, 0x9, 0xD, 0xE, 0xF]), SBox([0x8, 0xF, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x0]), SBox([0x8, 0x0, 0x1, 0xD, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0x2, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0xC, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0x3, 0xD, 0xE, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0xE, 0x6, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0xD, 0x5, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0xB, 0x6, 0x7, 0x4, 0x9, 0xA, 0x5, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0x3, 0x5, 0xE, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0xD, 0x4, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0x6, 0xD, 0x0, 0x9, 0xA, 0xB, 0xC, 0x7, 0xE, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x0, 0xF, 0xA, 0xB, 0xC, 0xD, 0xE, 0x9]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x0, 0x9, 0xA, 0xE, 0xC, 0xD, 0xB, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x9, 0x4, 0x7, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0xF, 0x0, 0x1, 0xA, 0x2, 0x5, 0x6, 0x7, 0x4, 0x9, 0x3, 0xB, 0xC, 0xD, 0xE, 0x8]), SBox([0x2, 0x0, 0x1, 0x8, 0x3, 0xF, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x5]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0xF, 0x7, 0x3, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x6]), SBox([0x6, 0x8, 0x1, 0xB, 0x3, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0x2, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0xA, 0x6, 0x7, 0x0, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0xF, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x5]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0xB, 0x7, 0x0, 0x9, 0xA, 0x6, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0xD, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0x6, 0xE, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0x6, 0xA, 0x0, 0x9, 0x7, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0xD, 0x4, 0x9, 0xA, 0xB, 0xC, 0x7, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0xC, 0xA, 0xB, 0x9, 0xD, 0xE, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x0, 0x9, 0xF, 0xB, 0xC, 0xD, 0xE, 0xA]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0x9, 0x7, 0x0, 0x6, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xE, 0xC, 0xD, 0xB, 0xF]), SBox([0x4, 0x0, 0x1, 0xA, 0x2, 0x5, 0x3, 0x7, 0x6, 0x9, 0x8, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0xA, 0x7, 0x0, 0x9, 0x6, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0xB, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0x1, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0xB, 0x7, 0x6, 0x9, 0xA, 0x4, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0xC, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0x1, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0xD, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0x1, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0xE, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0x3, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0xF, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x3]), SBox([0x6, 0x0, 0x8, 0x2, 0x3, 0x5, 0xB, 0x7, 0x1, 0x9, 0xA, 0x4, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0xC, 0x7, 0x4, 0x9, 0xA, 0xB, 0x6, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x9, 0x6, 0x7, 0x3, 0x5, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xF, 0xB, 0xC, 0xD, 0xE, 0xA]), SBox([0xC, 0x0, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0x8, 0xD, 0xE, 0xF]), SBox([0xD, 0x0, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0x8, 0xE, 0xF]), SBox([0x8, 0xE, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0x0, 0xF]), SBox([0x8, 0x0, 0x1, 0xF, 0x2, 0x5, 0x6, 0x7, 0x4, 0x9, 0x3, 0xB, 0xC, 0xD, 0xE, 0xA]), SBox([0x8, 0x0, 0x1, 0xB, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0x2, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xC, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0x2, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0xB, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0x3, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0xD, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0x3, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0xF, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x4]), SBox([0x8, 0x0, 0x1, 0x6, 0x2, 0x5, 0xF, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x3]), SBox([0x4, 0x0, 0x8, 0x2, 0x3, 0x5, 0x6, 0xB, 0x1, 0x9, 0xA, 0x7, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x0, 0x9, 0xA, 0xB, 0xE, 0xD, 0xC, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0xF, 0xE, 0xD]), SBox([0x8, 0x0, 0xF, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x1]), SBox([0x8, 0x0, 0x1, 0x9, 0x2, 0x5, 0x6, 0x7, 0x4, 0xF, 0xA, 0xB, 0xC, 0xD, 0xE, 0x3]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0x6, 0x7, 0x3, 0x9, 0xD, 0xB, 0xC, 0xA, 0xE, 0xF]), SBox([0xB, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xD, 0xC, 0x8, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x8, 0x3, 0xC, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0x5, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0xA, 0x6, 0x7, 0x3, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x8, 0x3, 0x5, 0x6, 0x7, 0x4, 0xD, 0xA, 0xB, 0xC, 0x9, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0x9, 0x7, 0x3, 0x6, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x8, 0x2, 0x3, 0xB, 0x6, 0x7, 0x1, 0x9, 0xA, 0x5, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0xE, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0x5, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x8, 0x4, 0x6, 0xE, 0x5, 0x9, 0xA, 0xB, 0xC, 0xD, 0x7, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0xC, 0x4, 0x9, 0xA, 0xB, 0x7, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0x6, 0x7, 0x3, 0xC, 0xA, 0xB, 0x9, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0xD, 0xA, 0xB, 0xC, 0x9, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0x6, 0x7, 0x3, 0x9, 0xA, 0xE, 0xC, 0xD, 0xB, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xF, 0xC, 0xD, 0xE, 0xB]), SBox([0x4, 0x0, 0x1, 0xF, 0x2, 0x5, 0x6, 0x7, 0x3, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x8]), SBox([0x8, 0xE, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0x0, 0xF]), SBox([0x8, 0xF, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x0]), SBox([0x4, 0x0, 0x1, 0xD, 0x2, 0x5, 0x6, 0x7, 0x3, 0x9, 0xA, 0xB, 0xC, 0x8, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xD, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0x2, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0xC, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0x5, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0xE, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0x7, 0xF]), SBox([0x4, 0x8, 0xE, 0x2, 0x3, 0x5, 0x6, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0xD, 0x1, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0xA, 0x6, 0x7, 0x4, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x8, 0x2, 0x3, 0x5, 0xB, 0x7, 0x1, 0x9, 0xA, 0x6, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x9, 0x7, 0x4, 0x6, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0xB, 0x7, 0x4, 0x9, 0xA, 0x6, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x6, 0x1, 0xD, 0x3, 0x5, 0x0, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0x2, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x8, 0x4, 0xD, 0x7, 0x5, 0x9, 0xA, 0xB, 0xC, 0x6, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0xA, 0x7, 0x3, 0x9, 0x6, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0xD, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0x6, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0x6, 0x7, 0x3, 0x9, 0xA, 0xB, 0xE, 0xD, 0xC, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xE, 0xB, 0xC, 0xD, 0xA, 0xF]), SBox([0x8, 0xA, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0x0, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0xA, 0x2, 0x5, 0x6, 0x7, 0x3, 0x9, 0x8, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0x3, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x0, 0x1, 0x8, 0x3, 0x5, 0x4, 0x7, 0x2, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x8, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0xF, 0xB, 0x6, 0x7, 0x4, 0x9, 0xA, 0x5, 0xC, 0xD, 0xE, 0x8]), SBox([0x1, 0x0, 0x4, 0x8, 0x2, 0x5, 0xF, 0x7, 0x3, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x6]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0x6, 0x7, 0x3, 0xE, 0xA, 0xB, 0xC, 0xD, 0x9, 0xF]), SBox([0x8, 0x0, 0x1, 0x3, 0x2, 0xA, 0x6, 0x7, 0x4, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xC, 0x2, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0x3, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xD, 0x2, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0x3, 0xE, 0xF]), SBox([0x1, 0x0, 0x4, 0x8, 0x2, 0xA, 0x6, 0x7, 0x3, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x3, 0x0, 0x1, 0x2, 0x8, 0xC, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0x5, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x8, 0x4, 0xE, 0x7, 0x5, 0x9, 0xA, 0xB, 0xC, 0xD, 0x6, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x8, 0x4, 0xF, 0x7, 0x5, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x6]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0x6, 0x7, 0x3, 0x9, 0xA, 0xB, 0xC, 0xF, 0xE, 0xD]), SBox([0xD, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0x8, 0xE, 0xF]), SBox([0xE, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0x8, 0xF]), SBox([0x8, 0xD, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0x0, 0xE, 0xF]), SBox([0x8, 0x0, 0xC, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0x1, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0xC, 0x2, 0x5, 0x6, 0x7, 0x3, 0x9, 0xA, 0xB, 0x8, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0xE, 0x2, 0x5, 0x6, 0x7, 0x3, 0x9, 0xA, 0xB, 0xC, 0xD, 0x8, 0xF]), SBox([0x8, 0x0, 0x1, 0x3, 0x2, 0xF, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x5]), SBox([0x8, 0x6, 0x1, 0x2, 0x3, 0x5, 0x0, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xA, 0x2, 0x5, 0x6, 0x7, 0x4, 0x9, 0x3, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x6, 0x2, 0x5, 0x3, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0xC, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0x3, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0xD, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0x3, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x8, 0xE, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0x5, 0xF]), SBox([0xC, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0x8, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0xD, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0x1, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x4, 0x3, 0x8, 0x6, 0x7, 0x5, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x8, 0x7, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x8, 0x6, 0x7, 0x5, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0xF, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x8]), SBox([0x2, 0x0, 0x1, 0x3, 0xF, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x8]), SBox([0x2, 0x0, 0x1, 0x3, 0x8, 0xC, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0x5, 0xD, 0xE, 0xF]), SBox([0x7, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x8, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0xF, 0x2, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x3]), SBox([0x2, 0x0, 0x1, 0x8, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x8, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x0, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x8, 0x2, 0x5, 0x6, 0x7, 0x3, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x8, 0x2, 0x3, 0x5, 0xA, 0x7, 0x1, 0x9, 0x6, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x8, 0x2, 0x3, 0x5, 0x6, 0x7, 0x1, 0x9, 0xA, 0xB, 0xE, 0xD, 0xC, 0xF]), SBox([0x6, 0x0, 0x8, 0x2, 0x3, 0x5, 0xA, 0x7, 0x1, 0x9, 0x4, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x0, 0x8, 0x2, 0x3, 0x5, 0x4, 0x7, 0x1, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x8, 0x4, 0xC, 0x7, 0x5, 0x9, 0xA, 0xB, 0x6, 0xD, 0xE, 0xF]), SBox([0x3, 0x0, 0x1, 0x2, 0x8, 0x5, 0xC, 0x7, 0x4, 0x9, 0xA, 0xB, 0x6, 0xD, 0xE, 0xF]), SBox([0x3, 0x0, 0x1, 0x2, 0xC, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0x8, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x6, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x8, 0x2, 0x3, 0x5, 0x6, 0x7, 0x1, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0xA, 0x2, 0x3, 0x5, 0x4, 0x7, 0x6, 0x9, 0x1, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0x6, 0x2, 0x3, 0x5, 0x1, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0xE, 0x8, 0xA, 0x9, 0xC, 0xD, 0xB, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0xD, 0x9, 0x8, 0xB, 0xC, 0xA, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0xA, 0xC, 0x8, 0xB, 0x9, 0xD, 0xE, 0xF]), SBox([0x3, 0x0, 0x1, 0x2, 0x8, 0xB, 0x6, 0x7, 0x4, 0x9, 0xA, 0x5, 0xC, 0xD, 0xE, 0xF]), SBox([0x1, 0x0, 0x4, 0x8, 0x2, 0x5, 0xA, 0x7, 0x3, 0x9, 0x6, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0xE, 0x9, 0x8, 0xB, 0xC, 0xD, 0xA, 0xF]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0xF, 0x9, 0x8, 0xB, 0xC, 0xD, 0xE, 0xA]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0xA, 0xF, 0x9, 0xB, 0xC, 0xD, 0xE, 0x8]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0xC, 0x9, 0x8, 0xB, 0xA, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0xD, 0x9, 0x8, 0xB, 0xC, 0xA, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0xA, 0xD, 0x9, 0xB, 0xC, 0x8, 0xE, 0xF]), SBox([0x6, 0x0, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0xC, 0x9, 0xA, 0xB, 0x8, 0xD, 0xE, 0xF]), SBox([0x6, 0x0, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0xD, 0x9, 0xA, 0xB, 0xC, 0x8, 0xE, 0xF]), SBox([0x6, 0x5, 0x1, 0x2, 0x3, 0x0, 0x4, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x8, 0xA, 0x6, 0x7, 0x4, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x4, 0x3, 0x5, 0x6, 0x7, 0xC, 0x9, 0xA, 0xB, 0x8, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0xD, 0x9, 0xA, 0xB, 0xC, 0x8, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0xE, 0x9, 0xA, 0xB, 0xC, 0xD, 0x8, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0xE, 0x8, 0xA, 0xB, 0xC, 0xD, 0x9, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0xB, 0x8, 0xA, 0x9, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0xF, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x8]), SBox([0x2, 0x0, 0x1, 0x3, 0x5, 0x4, 0x6, 0x7, 0xE, 0x9, 0xA, 0xB, 0xC, 0xD, 0x8, 0xF]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0xC, 0x9, 0xA, 0xB, 0x8, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0xF, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x8]), SBox([0x1, 0x0, 0x4, 0x6, 0x2, 0x5, 0x3, 0x7, 0xA, 0x9, 0x8, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0xD, 0x8, 0x9, 0xB, 0xC, 0xA, 0xE, 0xF]), SBox([0x3, 0x0, 0x1, 0x2, 0x8, 0xA, 0x6, 0x7, 0x4, 0x9, 0x5, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0xA, 0x9, 0x8, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x8, 0x4, 0x6, 0x7, 0x5, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x1, 0x0, 0x4, 0x8, 0x2, 0x5, 0x6, 0x7, 0x3, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x8, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x6, 0x1, 0x2, 0x3, 0x5, 0x0, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x6, 0x2, 0x5, 0x3, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0x9, 0x8, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x1, 0x0, 0x4, 0x6, 0x2, 0x5, 0x3, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x4, 0x3, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0xA, 0x9, 0x8, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0xA, 0x8, 0x9, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x6, 0x0, 0x1, 0x2, 0x3, 0x5, 0x4, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x3, 0x0, 0x1, 0x2, 0x8, 0x5, 0x6, 0x7, 0x4, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x2, 0x3, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x1, 0x0, 0x4, 0x3, 0x2, 0x5, 0x6, 0x7, 0xF, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0x8]), SBox([0x2, 0x0, 0x1, 0x3, 0x5, 0x4, 0x6, 0x7, 0xA, 0x9, 0x8, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x7, 0x4, 0x6, 0x5, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x1, 0x0, 0x4, 0x3, 0x2, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x5, 0x4, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x8, 0x0, 0xA, 0x2, 0x3, 0x5, 0x1, 0x7, 0x4, 0x9, 0x6, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x1, 0x3, 0x2, 0x5, 0x6, 0x7, 0xC, 0x8, 0x9, 0xB, 0xA, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x6, 0x2, 0x3, 0x5, 0x1, 0x7, 0xA, 0x9, 0x8, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x4, 0x0, 0x6, 0x2, 0x3, 0x5, 0x1, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x2, 0x0, 0x1, 0x3, 0x6, 0x4, 0x5, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x3, 0x0, 0x1, 0x2, 0x6, 0x5, 0x4, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x3, 0x0, 0x1, 0x2, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x1, 0x0, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x1, 0x0, 0x3, 0x2, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]), SBox([0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF]) ] # Dictionary of all available SBoxes sboxes = {} for k in dir(sys.modules[__name__]): v = getattr(sys.modules[__name__], k) if isinstance(v, SBox): sboxes[k] = v
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/crypto/sboxes.py
0.608129
0.4081
sboxes.py
pypi
from .lfsr import lfsr_sequence from .cipher import SymmetricKeyCipher from sage.monoids.string_monoid_element import StringMonoidElement class LFSRCipher(SymmetricKeyCipher): def __init__(self, parent, poly, IS): """ Create a linear feedback shift register (LFSR) cipher. INPUT: - ``parent`` - parent - ``poly`` - connection polynomial - ``IS`` - initial state EXAMPLES:: sage: FF = FiniteField(2) sage: P.<x> = PolynomialRing(FF) sage: E = LFSRCryptosystem(FF) sage: E LFSR cryptosystem over Finite Field of size 2 sage: IS = [ FF(a) for a in [0,1,1,1,0,1,1] ] sage: g = x^7 + x + 1 sage: e = E((g,IS)) sage: B = BinaryStrings() sage: m = B.encoding("THECATINTHEHAT") sage: e(m) 0010001101111010111010101010001100000000110100010101011100001011110010010000011111100100100011001101101000001111 sage: FF = FiniteField(2) sage: P.<x> = PolynomialRing(FF) sage: LFSR = LFSRCryptosystem(FF) sage: e = LFSR((x^2+x+1,[FF(0),FF(1)])) sage: B = e.domain() sage: m = B.encoding("The cat in the hat.") sage: e(m) 00111001110111101011111001001101110101011011101000011001100101101011001000000011100101101010111100000101110100111111101100000101110101111010111101000011 sage: m == e(e(m)) True TESTS:: sage: FF = FiniteField(2) sage: P.<x> = PolynomialRing(FF) sage: E = LFSRCryptosystem(FF) sage: E == loads(dumps(E)) True """ SymmetricKeyCipher.__init__(self, parent, key = (poly, IS)) def __call__(self, M, mode = "ECB"): r""" Generate key stream from the binary string ``M``. INPUT: - ``M`` - a StringMonoidElement - ``mode`` - ignored (default: 'ECB') EXAMPLES:: sage: k = GF(2) sage: P.<x> = PolynomialRing( k ) sage: LFSR = LFSRCryptosystem( k ) sage: e = LFSR((x^2+x+1,[k(0), k(1)])) sage: B = e.domain() sage: m = B.encoding('The cat in the hat.') sage: e(m) 00111001110111101011111001001101110101011011101000011001100101101011001000000011100101101010111100000101110100111111101100000101110101111010111101000011 """ B = self.domain() # = plaintext_space = ciphertext_space if not isinstance(M, StringMonoidElement) and M.parent() == B: raise TypeError("Argument M (= %s) must be a string in the plaintext space." % M) (poly, IS) = self.key() n = B.ngens() # two for binary strings N = len(M) Melt = M._element_list Kelt = lfsr_sequence(poly.list(), IS, N) return B([ (Melt[i]+int(Kelt[i]))%n for i in range(N) ]) def _repr_(self): r""" Return the string representation of this LFSR cipher. EXAMPLES:: sage: FF = FiniteField(2) sage: P.<x> = PolynomialRing(FF) sage: LFSR = LFSRCryptosystem(FF) sage: IS_1 = [ FF(a) for a in [0,1,0,1,0,0,0] ] sage: e1 = LFSR((x^7 + x + 1,IS_1)) sage: IS_2 = [ FF(a) for a in [0,0,1,0,0,0,1,0,1] ] sage: e2 = LFSR((x^9 + x^3 + 1,IS_2)) sage: E = ShrinkingGeneratorCryptosystem() sage: e = E((e1,e2)) sage: e.keystream_cipher() LFSR cipher on Free binary string monoid """ return "LFSR cipher on %s" % self.domain() def connection_polynomial(self): """ The connection polynomial defining the LFSR of the cipher. EXAMPLES:: sage: k = GF(2) sage: P.<x> = PolynomialRing( k ) sage: LFSR = LFSRCryptosystem( k ) sage: e = LFSR((x^2+x+1,[k(0), k(1)])) sage: e.connection_polynomial() x^2 + x + 1 """ return self.key()[0] def initial_state(self): """ The initial state of the LFSR cipher. EXAMPLES:: sage: k = GF(2) sage: P.<x> = PolynomialRing( k ) sage: LFSR = LFSRCryptosystem( k ) sage: e = LFSR((x^2+x+1,[k(0), k(1)])) sage: e.initial_state() [0, 1] """ return self.key()[1] class ShrinkingGeneratorCipher(SymmetricKeyCipher): def __init__(self, parent, e1, e2): """ Create a shrinking generator cipher. INPUT: - ``parent`` - parent - ``poly`` - connection polynomial - ``IS`` - initial state EXAMPLES:: sage: FF = FiniteField(2) sage: P.<x> = PolynomialRing(FF) sage: LFSR = LFSRCryptosystem(FF) sage: IS_1 = [ FF(a) for a in [0,1,0,1,0,0,0] ] sage: e1 = LFSR((x^7 + x + 1,IS_1)) sage: IS_2 = [ FF(a) for a in [0,0,1,0,0,0,1,0,1] ] sage: e2 = LFSR((x^9 + x^3 + 1,IS_2)) sage: E = ShrinkingGeneratorCryptosystem() sage: e = E((e1,e2)) sage: e Shrinking generator cipher on Free binary string monoid """ if not isinstance(e1, LFSRCipher): raise TypeError("Argument e1 (= %s) must be a LFSR cipher." % e1) if not isinstance(e2, LFSRCipher): raise TypeError("Argument e2 (= %s) must be a LFSR cipher." % e2) SymmetricKeyCipher.__init__(self, parent, key = (e1, e2)) def keystream_cipher(self): """ The LFSR cipher generating the output key stream. EXAMPLES:: sage: FF = FiniteField(2) sage: P.<x> = PolynomialRing(FF) sage: LFSR = LFSRCryptosystem(FF) sage: IS_1 = [ FF(a) for a in [0,1,0,1,0,0,0] ] sage: e1 = LFSR((x^7 + x + 1,IS_1)) sage: IS_2 = [ FF(a) for a in [0,0,1,0,0,0,1,0,1] ] sage: e2 = LFSR((x^9 + x^3 + 1,IS_2)) sage: E = ShrinkingGeneratorCryptosystem() sage: e = E((e1,e2)) sage: e.keystream_cipher() LFSR cipher on Free binary string monoid """ return self.key()[0] def decimating_cipher(self): """ The LFSR cipher generating the decimating key stream. EXAMPLES:: sage: FF = FiniteField(2) sage: P.<x> = PolynomialRing(FF) sage: LFSR = LFSRCryptosystem(FF) sage: IS_1 = [ FF(a) for a in [0,1,0,1,0,0,0] ] sage: e1 = LFSR((x^7 + x + 1,IS_1)) sage: IS_2 = [ FF(a) for a in [0,0,1,0,0,0,1,0,1] ] sage: e2 = LFSR((x^9 + x^3 + 1,IS_2)) sage: E = ShrinkingGeneratorCryptosystem() sage: e = E((e1,e2)) sage: e.decimating_cipher() LFSR cipher on Free binary string monoid """ return self.key()[1] def __call__(self, M, mode = "ECB"): r""" INPUT: - ``M`` - a StringMonoidElement - ``mode`` - ignored (default: 'ECB') EXAMPLES:: sage: FF = FiniteField(2) sage: P.<x> = PolynomialRing(FF) sage: LFSR = LFSRCryptosystem(FF) sage: IS_1 = [ FF(a) for a in [0,1,0,1,0,0,0] ] sage: e1 = LFSR((x^7 + x + 1,IS_1)) sage: IS_2 = [ FF(a) for a in [0,0,1,0,0,0,1,0,1] ] sage: e2 = LFSR((x^9 + x^3 + 1,IS_2)) sage: E = ShrinkingGeneratorCryptosystem() sage: e = E((e1,e2)) sage: B = BinaryStrings() sage: m = B.encoding("THECATINTHEHAT") sage: c = e(m) sage: c.decoding() "t\xb6\xc1'\x83\x17\xae\xc9ZO\x84V\x7fX" sage: e(e(m)) == m True sage: m.decoding() 'THECATINTHEHAT' """ B = self.domain() # = plaintext_space = ciphertext_space if not isinstance(M, StringMonoidElement) and M.parent() == B: raise TypeError("Argument M (= %s) must be a string in the plaintext space." % M) (e1, e2) = self.key() MStream = M._element_list g1 = e1.connection_polynomial() n1 = g1.degree() IS_1 = e1.initial_state() g2 = e2.connection_polynomial() n2 = g2.degree() IS_2 = e2.initial_state() k = 0 N = len(M) n = max(n1, n2) CStream = [] while k < N: r = max(N-k,2*n) KStream = lfsr_sequence(g1.list(), IS_1, r) DStream = lfsr_sequence(g2.list(), IS_2, r) for i in range(r - n): if DStream[i] != 0: CStream.append(int(MStream[k] + KStream[i])) k += 1 if k == N: break IS_1 = KStream[r-n-1:r-n+n1] IS_2 = DStream[r-n-1:r-n+n2] return B(CStream) def _repr_(self): r""" Return the string representation of this shrinking generator cipher. EXAMPLES:: sage: FF = FiniteField(2) sage: P.<x> = PolynomialRing(FF) sage: LFSR = LFSRCryptosystem(FF) sage: IS_1 = [ FF(a) for a in [0,1,0,1,0,0,0] ] sage: e1 = LFSR((x^7 + x + 1,IS_1)) sage: IS_2 = [ FF(a) for a in [0,0,1,0,0,0,1,0,1] ] sage: e2 = LFSR((x^9 + x^3 + 1,IS_2)) sage: E = ShrinkingGeneratorCryptosystem() sage: e = E((e1,e2)); e Shrinking generator cipher on Free binary string monoid """ return "Shrinking generator cipher on %s" % self.domain()
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/crypto/stream_cipher.py
0.698329
0.378775
stream_cipher.py
pypi
from sage.structure.sage_object import SageObject class MPolynomialSystemGenerator(SageObject): """ Abstract base class for generators of polynomial systems. """ def __getattr__(self, attr): """ EXAMPLES:: sage: from sage.crypto.mq.mpolynomialsystemgenerator import MPolynomialSystemGenerator sage: msg = MPolynomialSystemGenerator() sage: msg.R Traceback (most recent call last): ... NotImplementedError """ if attr == "R": self.R = self.ring() return self.R raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__,attr)) def varformatstr(self, name): """ Return format string for a given name 'name' which is understood by print et al. Such a format string is used to construct variable names. Typically those format strings are somewhat like 'name%02d%02d' such that rounds and offset in a block can be encoded. INPUT: name -- string EXAMPLES:: sage: from sage.crypto.mq.mpolynomialsystemgenerator import MPolynomialSystemGenerator sage: msg = MPolynomialSystemGenerator() sage: msg.varformatstr('K') Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def varstrs(self, name, round): """ Return a list of variable names given a name 'name' and an index 'round'. This function is typically used by self._vars. INPUT: name -- string round -- integer index EXAMPLES:: sage: from sage.crypto.mq.mpolynomialsystemgenerator import MPolynomialSystemGenerator sage: msg = MPolynomialSystemGenerator() sage: msg.varstrs('K', i) Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def vars(self, name, round): """ Return a list of variables given a name 'name' and an index 'round'. INPUT: name -- string round -- integer index EXAMPLES:: sage: from sage.crypto.mq.mpolynomialsystemgenerator import MPolynomialSystemGenerator sage: msg = MPolynomialSystemGenerator() sage: msg.vars('K',0) Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def ring(self): """ Return the ring in which the system is defined. EXAMPLES:: sage: from sage.crypto.mq.mpolynomialsystemgenerator import MPolynomialSystemGenerator sage: msg = MPolynomialSystemGenerator() sage: msg.ring() Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def block_order(self): """ Return a block term ordering for the equation systems generated by self. EXAMPLES:: sage: from sage.crypto.mq.mpolynomialsystemgenerator import MPolynomialSystemGenerator sage: msg = MPolynomialSystemGenerator() sage: msg.block_order() Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def __call__(self, P, K): """ Encrypt plaintext P using the key K. INPUT: P -- plaintext (vector, list) K -- key (vector, list) EXAMPLES:: sage: from sage.crypto.mq.mpolynomialsystemgenerator import MPolynomialSystemGenerator sage: msg = MPolynomialSystemGenerator() sage: msg(None, None) Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def sbox(self): """ Return SBox object for self. EXAMPLES:: sage: from sage.crypto.mq.mpolynomialsystemgenerator import MPolynomialSystemGenerator sage: msg = MPolynomialSystemGenerator() sage: msg.sbox() Traceback (most recent call last): ... AttributeError: '<class 'sage.crypto.mq.mpolynomialsystemgenerator.MPolynomialSystemGenerator'>' object has no attribute '_sbox' """ return self._sbox def polynomial_system(self, P=None, K=None): """ Return a tuple F,s for plaintext P and key K where F is an polynomial system and s a dictionary which maps key variables to their solutions. INPUT: P -- plaintext (vector, list) K -- key (vector, list) EXAMPLES:: sage: from sage.crypto.mq.mpolynomialsystemgenerator import MPolynomialSystemGenerator sage: msg = MPolynomialSystemGenerator() sage: msg.polynomial_system() Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def random_element(self): """ Return random element. Usually this is a list of elements in the base field of length 'blocksize'. EXAMPLES:: sage: from sage.crypto.mq.mpolynomialsystemgenerator import MPolynomialSystemGenerator sage: msg = MPolynomialSystemGenerator() sage: msg.random_element() Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/crypto/mq/mpolynomialsystemgenerator.py
0.907732
0.437403
mpolynomialsystemgenerator.py
pypi
from sage.rings.integer_ring import ZZ from sage.matrix.constructor import column_matrix, matrix from sage.geometry.cone import Cone class FanNotIsomorphicError(Exception): """ Exception to return if there is no fan isomorphism """ pass def fan_isomorphic_necessary_conditions(fan1, fan2): """ Check necessary (but not sufficient) conditions for the fans to be isomorphic. INPUT: - ``fan1``, ``fan2`` -- two fans. OUTPUT: Boolean. ``False`` if the two fans cannot be isomorphic. ``True`` if the two fans may be isomorphic. EXAMPLES:: sage: fan1 = toric_varieties.P2().fan() # optional - palp sage: fan2 = toric_varieties.dP8().fan() # optional - palp sage: from sage.geometry.fan_isomorphism import fan_isomorphic_necessary_conditions sage: fan_isomorphic_necessary_conditions(fan1, fan2) # optional - palp False """ if fan1.lattice_dim() != fan2.lattice_dim(): return False if fan1.dim() != fan2.dim(): return False if fan1.nrays() != fan2.nrays(): return False if fan1.ngenerating_cones() != fan2.ngenerating_cones(): return False if fan1.is_complete() != fan2.is_complete(): return False return True def fan_isomorphism_generator(fan1, fan2): """ Iterate over the isomorphisms from ``fan1`` to ``fan2``. ALGORITHM: The :meth:`sage.geometry.fan.Fan.vertex_graph` of the two fans is compared. For each graph isomorphism, we attempt to lift it to an actual isomorphism of fans. INPUT: - ``fan1``, ``fan2`` -- two fans. OUTPUT: Yields the fan isomorphisms as matrices acting from the right on rays. EXAMPLES:: sage: fan = toric_varieties.P2().fan() # optional - palp sage: from sage.geometry.fan_isomorphism import fan_isomorphism_generator sage: sorted(fan_isomorphism_generator(fan, fan)) # optional - palp [ [-1 -1] [-1 -1] [ 0 1] [0 1] [ 1 0] [1 0] [ 0 1], [ 1 0], [-1 -1], [1 0], [-1 -1], [0 1] ] sage: m1 = matrix([(1, 0), (0, -5), (-3, 4)]) sage: m2 = matrix([(3, 0), (1, 0), (-2, 1)]) sage: m1.elementary_divisors() == m2.elementary_divisors() == [1,1,0] True sage: fan1 = Fan([Cone([m1*vector([23, 14]), m1*vector([ 3,100])]), ....: Cone([m1*vector([-1,-14]), m1*vector([-100, -5])])]) sage: fan2 = Fan([Cone([m2*vector([23, 14]), m2*vector([ 3,100])]), ....: Cone([m2*vector([-1,-14]), m2*vector([-100, -5])])]) sage: sorted(fan_isomorphism_generator(fan1, fan2)) [ [-12 1 -5] [ -4 0 -1] [ -5 0 -1] ] sage: m0 = identity_matrix(ZZ, 2) sage: m1 = matrix([(1, 0), (0, -5), (-3, 4)]) sage: m2 = matrix([(3, 0), (1, 0), (-2, 1)]) sage: m1.elementary_divisors() == m2.elementary_divisors() == [1,1,0] True sage: fan0 = Fan([Cone([m0*vector([1,0]), m0*vector([1,1])]), ....: Cone([m0*vector([1,1]), m0*vector([0,1])])]) sage: fan1 = Fan([Cone([m1*vector([1,0]), m1*vector([1,1])]), ....: Cone([m1*vector([1,1]), m1*vector([0,1])])]) sage: fan2 = Fan([Cone([m2*vector([1,0]), m2*vector([1,1])]), ....: Cone([m2*vector([1,1]), m2*vector([0,1])])]) sage: sorted(fan_isomorphism_generator(fan0, fan0)) [ [0 1] [1 0] [1 0], [0 1] ] sage: sorted(fan_isomorphism_generator(fan1, fan1)) [ [ -3 -20 28] [1 0 0] [ -1 -4 7] [0 1 0] [ -1 -5 8], [0 0 1] ] sage: sorted(fan_isomorphism_generator(fan1, fan2)) [ [-24 -3 7] [-12 1 -5] [ -7 -1 2] [ -4 0 -1] [ -8 -1 2], [ -5 0 -1] ] sage: sorted(fan_isomorphism_generator(fan2, fan1)) [ [ 0 1 -1] [ 0 1 -1] [ 1 -13 8] [ 2 -8 1] [ 0 -5 4], [ 1 0 -3] ] """ if not fan_isomorphic_necessary_conditions(fan1, fan2): return graph1 = fan1.vertex_graph() graph2 = fan2.vertex_graph() graph_iso = graph1.is_isomorphic(graph2, edge_labels=True, certificate=True) if not graph_iso[0]: return graph_iso = graph_iso[1] # Pick a basis of rays in fan1 max_cone = fan1(fan1.dim())[0] fan1_pivot_rays = max_cone.rays() fan1_basis = fan1_pivot_rays + fan1.virtual_rays() # A QQ-basis for N_1 fan1_pivot_cones = [ fan1.embed(Cone([r])) for r in fan1_pivot_rays ] # The fan2 cones as set(set(ray indices)) fan2_cones = frozenset( frozenset(cone.ambient_ray_indices()) for cone in fan2.generating_cones() ) # iterate over all graph isomorphisms graph1 -> graph2 for perm in graph2.automorphism_group(edge_labels=True): # find a candidate m that maps fan1_basis to the image rays under the graph isomorphism fan2_pivot_cones = [ perm(graph_iso[c]) for c in fan1_pivot_cones ] fan2_pivot_rays = fan2.rays([ c.ambient_ray_indices()[0] for c in fan2_pivot_cones ]) fan2_basis = fan2_pivot_rays + fan2.virtual_rays() try: m = matrix(ZZ, fan1_basis).solve_right(matrix(ZZ, fan2_basis)) m = m.change_ring(ZZ) except (ValueError, TypeError): continue # no solution # check that the candidate m lifts the vertex graph homomorphism graph_image_ray_indices = [ perm(graph_iso[c]).ambient_ray_indices()[0] for c in fan1(1) ] try: matrix_image_ray_indices = [ fan2.rays().index(r*m) for r in fan1.rays() ] except ValueError: continue if graph_image_ray_indices != matrix_image_ray_indices: continue # check that the candidate m maps generating cone to generating cone image_cones = frozenset( # The image(fan1) cones as set(set(integers) frozenset(graph_image_ray_indices[i] for i in cone.ambient_ray_indices()) for cone in fan1.generating_cones() ) if image_cones == fan2_cones: m.set_immutable() yield m def find_isomorphism(fan1, fan2, check=False): """ Find an isomorphism of the two fans. INPUT: - ``fan1``, ``fan2`` -- two fans. - ``check`` -- boolean (default: False). Passed to the fan morphism constructor, see :func:`~sage.geometry.fan_morphism.FanMorphism`. OUTPUT: A fan isomorphism. If the fans are not isomorphic, a :class:`FanNotIsomorphicError` is raised. EXAMPLES:: sage: rays = ((1, 1), (0, 1), (-1, -1), (3, 1)) sage: cones = [(0,1), (1,2), (2,3), (3,0)] sage: fan1 = Fan(cones, rays) sage: m = matrix([[-2,3],[1,-1]]) sage: m.det() == -1 True sage: fan2 = Fan(cones, [vector(r)*m for r in rays]) sage: from sage.geometry.fan_isomorphism import find_isomorphism sage: find_isomorphism(fan1, fan2, check=True) Fan morphism defined by the matrix [-2 3] [ 1 -1] Domain fan: Rational polyhedral fan in 2-d lattice N Codomain fan: Rational polyhedral fan in 2-d lattice N sage: find_isomorphism(fan1, toric_varieties.P2().fan()) # optional - palp Traceback (most recent call last): ... FanNotIsomorphicError sage: fan1 = Fan(cones=[[1,3,4,5],[0,1,2,3],[2,3,4],[0,1,5]], ....: rays=[(-1,-1,0),(-1,-1,3),(-1,1,-1),(-1,3,-1),(0,2,-1),(1,-1,1)]) sage: fan2 = Fan(cones=[[0,2,3,5],[0,1,4,5],[0,1,2],[3,4,5]], ....: rays=[(-1,-1,-1),(-1,-1,0),(-1,1,-1),(0,2,-1),(1,-1,1),(3,-1,-1)]) sage: fan1.is_isomorphic(fan2) True """ generator = fan_isomorphism_generator(fan1, fan2) try: m = next(generator) except StopIteration: raise FanNotIsomorphicError from sage.geometry.fan_morphism import FanMorphism return FanMorphism(m, domain_fan=fan1, codomain=fan2, check=check) def fan_2d_cyclically_ordered_rays(fan): """ Return the rays of a 2-dimensional ``fan`` in cyclic order. INPUT: - ``fan`` -- a 2-dimensional fan. OUTPUT: A :class:`~sage.geometry.point_collection.PointCollection` containing the rays in one particular cyclic order. EXAMPLES:: sage: rays = ((1, 1), (-1, -1), (-1, 1), (1, -1)) sage: cones = [(0,2), (2,1), (1,3), (3,0)] sage: fan = Fan(cones, rays) sage: fan.rays() N( 1, 1), N(-1, -1), N(-1, 1), N( 1, -1) in 2-d lattice N sage: from sage.geometry.fan_isomorphism import fan_2d_cyclically_ordered_rays sage: fan_2d_cyclically_ordered_rays(fan) N(-1, -1), N(-1, 1), N( 1, 1), N( 1, -1) in 2-d lattice N TESTS:: sage: fan = Fan(cones=[], rays=[], lattice=ZZ^2) sage: from sage.geometry.fan_isomorphism import fan_2d_cyclically_ordered_rays sage: fan_2d_cyclically_ordered_rays(fan) Empty collection in Ambient free module of rank 2 over the principal ideal domain Integer Ring """ assert fan.lattice_dim() == 2 import math rays = [ (math.atan2(r[0],r[1]), r) for r in fan.rays() ] rays = [ r[1] for r in sorted(rays) ] from sage.geometry.point_collection import PointCollection return PointCollection(rays, fan.lattice()) def fan_2d_echelon_forms(fan): """ Return echelon forms of all cyclically ordered ray matrices. Note that the echelon form of the ordered ray matrices are unique up to different cyclic orderings. INPUT: - ``fan`` -- a fan. OUTPUT: A set of matrices. The set of all echelon forms for all different cyclic orderings. EXAMPLES:: sage: fan = toric_varieties.P2().fan() # optional - palp sage: from sage.geometry.fan_isomorphism import fan_2d_echelon_forms sage: fan_2d_echelon_forms(fan) # optional - palp frozenset({[ 1 0 -1] [ 0 1 -1]}) sage: fan = toric_varieties.dP7().fan() # optional - palp sage: sorted(fan_2d_echelon_forms(fan)) # optional - palp [ [ 1 0 -1 -1 0] [ 1 0 -1 -1 0] [ 1 0 -1 -1 1] [ 1 0 -1 0 1] [ 0 1 0 -1 -1], [ 0 1 1 0 -1], [ 0 1 1 0 -1], [ 0 1 0 -1 -1], <BLANKLINE> [ 1 0 -1 0 1] [ 0 1 1 -1 -1] ] TESTS:: sage: rays = [(1, 1), (-1, -1), (-1, 1), (1, -1)] sage: cones = [(0,2), (2,1), (1,3), (3,0)] sage: fan1 = Fan(cones, rays) sage: from sage.geometry.fan_isomorphism import fan_2d_echelon_form, fan_2d_echelon_forms sage: echelon_forms = fan_2d_echelon_forms(fan1) sage: S4 = CyclicPermutationGroup(4) sage: rays.reverse() sage: cones = [(3,1), (1,2), (2,0), (0,3)] sage: for i in range(100): ....: m = random_matrix(ZZ,2,2) ....: if abs(det(m)) != 1: continue ....: perm = S4.random_element() ....: perm_cones = [ (perm(c[0]+1)-1, perm(c[1]+1)-1) for c in cones ] ....: perm_rays = [ rays[perm(i+1)-1] for i in range(len(rays)) ] ....: fan2 = Fan(perm_cones, rays=[m*vector(r) for r in perm_rays]) ....: assert fan_2d_echelon_form(fan2) in echelon_forms The trivial case was fixed in :trac:`18613`:: sage: fan = Fan([], lattice=ToricLattice(2)) sage: fan_2d_echelon_forms(fan) frozenset({[]}) sage: parent(list(_)[0]) Full MatrixSpace of 2 by 0 dense matrices over Integer Ring """ if fan.nrays() == 0: return frozenset([fan_2d_echelon_form(fan)]) rays = list(fan_2d_cyclically_ordered_rays(fan)) echelon_forms = [] for i in range(2): for j in range(len(rays)): echelon_forms.append(column_matrix(rays).echelon_form()) first = rays.pop(0) rays.append(first) rays.reverse() return frozenset(echelon_forms) def fan_2d_echelon_form(fan): """ Return echelon form of a cyclically ordered ray matrix. INPUT: - ``fan`` -- a fan. OUTPUT: A matrix. The echelon form of the rays in one particular cyclic order. EXAMPLES:: sage: fan = toric_varieties.P2().fan() # optional - palp sage: from sage.geometry.fan_isomorphism import fan_2d_echelon_form sage: fan_2d_echelon_form(fan) # optional - palp [ 1 0 -1] [ 0 1 -1] """ ray_matrix = fan_2d_cyclically_ordered_rays(fan).column_matrix() return ray_matrix.echelon_form()
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/geometry/fan_isomorphism.py
0.70912
0.621254
fan_isomorphism.py
pypi
from sage.graphs.digraph import DiGraph from sage.combinat.posets.lattices import FiniteLatticePoset def lattice_from_incidences(atom_to_coatoms, coatom_to_atoms, face_constructor=None, required_atoms=None, key=None, **kwds): r""" Compute an atomic and coatomic lattice from the incidence between atoms and coatoms. INPUT: - ``atom_to_coatoms`` -- list, ``atom_to_coatom[i]`` should list all coatoms over the ``i``-th atom; - ``coatom_to_atoms`` -- list, ``coatom_to_atom[i]`` should list all atoms under the ``i``-th coatom; - ``face_constructor`` -- function or class taking as the first two arguments sorted :class:`tuple` of integers and any keyword arguments. It will be called to construct a face over atoms passed as the first argument and under coatoms passed as the second argument. Default implementation will just return these two tuples as a tuple; - ``required_atoms`` -- list of atoms (default:None). Each non-empty "face" requires at least one of the specified atoms present. Used to ensure that each face has a vertex. - ``key`` -- any hashable value (default: None). It is passed down to :class:`~sage.combinat.posets.posets.FinitePoset`. - all other keyword arguments will be passed to ``face_constructor`` on each call. OUTPUT: - :class:`finite poset <sage.combinat.posets.posets.FinitePoset>` with elements constructed by ``face_constructor``. .. NOTE:: In addition to the specified partial order, finite posets in Sage have internal total linear order of elements which extends the partial one. This function will try to make this internal order to start with the bottom and atoms in the order corresponding to ``atom_to_coatoms`` and to finish with coatoms in the order corresponding to ``coatom_to_atoms`` and the top. This may not be possible if atoms and coatoms are the same, in which case the preference is given to the first list. ALGORITHM: The detailed description of the used algorithm is given in [KP2002]_. The code of this function follows the pseudo-code description in the section 2.5 of the paper, although it is mostly based on frozen sets instead of sorted lists - this makes the implementation easier and should not cost a big performance penalty. (If one wants to make this function faster, it should be probably written in Cython.) While the title of the paper mentions only polytopes, the algorithm (and the implementation provided here) is applicable to any atomic and coatomic lattice if both incidences are given, see Section 3.4. In particular, this function can be used for strictly convex cones and complete fans. REFERENCES: [KP2002]_ AUTHORS: - Andrey Novoseltsev (2010-05-13) with thanks to Marshall Hampton for the reference. EXAMPLES: Let us construct the lattice of subsets of {0, 1, 2}. Our atoms are {0}, {1}, and {2}, while our coatoms are {0,1}, {0,2}, and {1,2}. Then incidences are :: sage: atom_to_coatoms = [(0,1), (0,2), (1,2)] sage: coatom_to_atoms = [(0,1), (0,2), (1,2)] and we can compute the lattice as :: sage: from sage.geometry.cone import lattice_from_incidences sage: L = lattice_from_incidences( ....: atom_to_coatoms, coatom_to_atoms) sage: L Finite lattice containing 8 elements with distinguished linear extension sage: for level in L.level_sets(): print(level) [((), (0, 1, 2))] [((0,), (0, 1)), ((1,), (0, 2)), ((2,), (1, 2))] [((0, 1), (0,)), ((0, 2), (1,)), ((1, 2), (2,))] [((0, 1, 2), ())] For more involved examples see the *source code* of :meth:`sage.geometry.cone.ConvexRationalPolyhedralCone.face_lattice` and :meth:`sage.geometry.fan.RationalPolyhedralFan._compute_cone_lattice`. """ def default_face_constructor(atoms, coatoms, **kwds): return (atoms, coatoms) if face_constructor is None: face_constructor = default_face_constructor atom_to_coatoms = [frozenset(atc) for atc in atom_to_coatoms] A = frozenset(range(len(atom_to_coatoms))) # All atoms coatom_to_atoms = [frozenset(cta) for cta in coatom_to_atoms] C = frozenset(range(len(coatom_to_atoms))) # All coatoms # Comments with numbers correspond to steps in Section 2.5 of the article L = DiGraph(1) # 3: initialize L faces = {} atoms = frozenset() coatoms = C faces[atoms, coatoms] = 0 next_index = 1 Q = [(atoms, coatoms)] # 4: initialize Q with the empty face while Q: # 5 q_atoms, q_coatoms = Q.pop() # 6: remove some q from Q q = faces[q_atoms, q_coatoms] # 7: compute H = {closure(q+atom) : atom not in atoms of q} H = {} candidates = set(A.difference(q_atoms)) for atom in candidates: coatoms = q_coatoms.intersection(atom_to_coatoms[atom]) atoms = A for coatom in coatoms: atoms = atoms.intersection(coatom_to_atoms[coatom]) H[atom] = (atoms, coatoms) # 8: compute the set G of minimal sets in H minimals = set([]) while candidates: candidate = candidates.pop() atoms = H[candidate][0] if atoms.isdisjoint(candidates) and atoms.isdisjoint(minimals): minimals.add(candidate) # Now G == {H[atom] : atom in minimals} for atom in minimals: # 9: for g in G: g_atoms, g_coatoms = H[atom] if required_atoms is not None: if g_atoms.isdisjoint(required_atoms): continue if (g_atoms, g_coatoms) in faces: g = faces[g_atoms, g_coatoms] else: # 11: if g was newly created g = next_index faces[g_atoms, g_coatoms] = g next_index += 1 Q.append((g_atoms, g_coatoms)) # 12 L.add_edge(q, g) # 14 # End of algorithm, now construct a FiniteLatticePoset. # In principle, it is recommended to use Poset or in this case perhaps # even LatticePoset, but it seems to take several times more time # than the above computation, makes unnecessary copies, and crashes. # So for now we will mimic the relevant code from Poset. # Enumeration of graph vertices must be a linear extension of the poset new_order = L.topological_sort() # Make sure that coatoms are in the end in proper order tail = [faces[atomes, frozenset([coatom])] for coatom, atomes in enumerate(coatom_to_atoms)] tail.append(faces[A, frozenset()]) new_order = [n for n in new_order if n not in tail] + tail # Make sure that atoms are in the beginning in proper order head = [0] # We know that the empty face has index 0 head.extend(faces[frozenset([atom]), coatoms] for atom, coatoms in enumerate(atom_to_coatoms) if required_atoms is None or atom in required_atoms) new_order = head + [n for n in new_order if n not in head] # "Invert" this list to a dictionary labels = {} for new, old in enumerate(new_order): labels[old] = new L.relabel(labels) # Construct the actual poset elements elements = [None] * next_index for face, index in faces.items(): atoms, coatoms = face elements[labels[index]] = face_constructor( tuple(sorted(atoms)), tuple(sorted(coatoms)), **kwds) D = {i: f for i, f in enumerate(elements)} L.relabel(D) return FiniteLatticePoset(L, elements, key=key)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/geometry/hasse_diagram.py
0.902524
0.766687
hasse_diagram.py
pypi
from sage.structure.parent import Parent from sage.structure.richcmp import richcmp from sage.structure.element import ModuleElement from sage.structure.unique_representation import UniqueRepresentation from sage.misc.cachefunc import cached_method class LinearExpression(ModuleElement): """ A linear expression. A linear expression is just a linear polynomial in some (fixed) variables. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: m = L([1, 2, 3], 4); m x + 2*y + 3*z + 4 sage: m2 = L([(1, 2, 3), 4]); m2 x + 2*y + 3*z + 4 sage: m3 = L([4, 1, 2, 3]); m3 # note: constant is first in single-tuple notation x + 2*y + 3*z + 4 sage: m == m2 True sage: m2 == m3 True sage: L.zero() 0*x + 0*y + 0*z + 0 sage: a = L([12, 2/3, -1], -2) sage: a - m 11*x - 4/3*y - 4*z - 6 sage: LZ.<x,y,z> = LinearExpressionModule(ZZ) sage: a - LZ([2, -1, 3], 1) 10*x + 5/3*y - 4*z - 3 """ def __init__(self, parent, coefficients, constant, check=True): """ Initialize ``self``. TESTS:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: linear = L([1, 2, 3], 4) # indirect doctest sage: linear.parent() is L True sage: TestSuite(linear).run() """ super().__init__(parent) self._coeffs = coefficients self._const = constant if check: if self._coeffs.parent() is not self.parent().ambient_module(): raise ValueError("coefficients are not in the ambient module") if not self._coeffs.is_immutable(): raise ValueError("coefficients are not immutable") if self._const.parent() is not self.parent().base_ring(): raise ValueError("the constant is not in the base ring") def A(self): """ Return the coefficient vector. OUTPUT: The coefficient vector of the linear expression. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: linear = L([1, 2, 3], 4); linear x + 2*y + 3*z + 4 sage: linear.A() (1, 2, 3) sage: linear.b() 4 """ return self._coeffs def b(self): """ Return the constant term. OUTPUT: The constant term of the linear expression. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: linear = L([1, 2, 3], 4); linear x + 2*y + 3*z + 4 sage: linear.A() (1, 2, 3) sage: linear.b() 4 """ return self._const constant_term = b def coefficients(self): """ Return all coefficients. OUTPUT: The constant (as first entry) and coefficients of the linear terms (as subsequent entries) in a list. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: linear = L([1, 2, 3], 4); linear x + 2*y + 3*z + 4 sage: linear.coefficients() [4, 1, 2, 3] """ return [self._const] + list(self._coeffs) dense_coefficient_list = coefficients def monomial_coefficients(self, copy=True): """ Return a dictionary whose keys are indices of basis elements in the support of ``self`` and whose values are the corresponding coefficients. INPUT: - ``copy`` -- ignored EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: linear = L([1, 2, 3], 4) sage: sorted(linear.monomial_coefficients().items(), key=lambda x: str(x[0])) [(0, 1), (1, 2), (2, 3), ('b', 4)] """ zero = self.parent().base_ring().zero() d = {i: v for i, v in enumerate(self._coeffs) if v != zero} if self._const != zero: d['b'] = self._const return d def _repr_vector(self, variable='x'): """ Return a string representation. INPUT: - ``variable`` -- string; the name of the variable vector EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: L([1, 2, 3], 4)._repr_vector() '(1, 2, 3) x + 4 = 0' sage: L([-1, -2, -3], -4)._repr_vector('u') '(-1, -2, -3) u - 4 = 0' """ atomic_repr = self.parent().base_ring()._repr_option('element_is_atomic') constant = repr(self._const) if not atomic_repr: constant = '({0})'.format(constant) constant = '+ {0}'.format(constant).replace('+ -', '- ') return '{0} {1} {2} = 0'.format(repr(self._coeffs), variable, constant) def _repr_linear(self, include_zero=True, include_constant=True, multiplication='*'): """ Return a representation as a linear polynomial. INPUT: - ``include_zero`` -- whether to include terms with zero coefficient - ``include_constant`` -- whether to include the constant term - ``multiplication`` -- string (optional, default: ``*``); the multiplication symbol to use OUTPUT: A string. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: L([1, 2, 3], 4)._repr_linear() 'x + 2*y + 3*z + 4' sage: L([-1, -2, -3], -4)._repr_linear() '-x - 2*y - 3*z - 4' sage: L([0, 0, 0], 1)._repr_linear() '0*x + 0*y + 0*z + 1' sage: L([0, 0, 0], 0)._repr_linear() '0*x + 0*y + 0*z + 0' sage: R.<u,v> = QQ[] sage: L.<x,y,z> = LinearExpressionModule(R) sage: L([-u+v+1, -3*u-2, 3], -4*u+v)._repr_linear() '(-u + v + 1)*x + (-3*u - 2)*y + 3*z - 4*u + v' sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: L([1, 0, 3], 0)._repr_linear() 'x + 0*y + 3*z + 0' sage: L([1, 0, 3], 0)._repr_linear(include_zero=False) 'x + 3*z' sage: L([1, 0, 3], 1)._repr_linear(include_constant=False, multiplication='.') 'x + 0.y + 3.z' sage: L([1, 0, 3], 1)._repr_linear(include_zero=False, include_constant=False) 'x + 3*z' sage: L([0, 0, 0], 0)._repr_linear(include_zero=False) '0' """ atomic_repr = self.parent().base_ring()._repr_option('element_is_atomic') names = [multiplication + n for n in self.parent()._names] terms = list(zip(self._coeffs, names)) if include_constant: terms += [(self._const, '')] if not include_zero: terms = [t for t in terms if t[0] != 0] if len(terms) == 0: return '0' summands = [] for coeff, name in terms: coeff = str(coeff) if not atomic_repr and name != '' and any(c in coeff for c in ['+', '-']): coeff = '({0})'.format(coeff) summands.append(coeff + name) s = ' ' + ' + '.join(summands) s = s.replace(' + -', ' - ') s = s.replace(' 1' + multiplication, ' ') s = s.replace(' -1' + multiplication, ' -') return s[1:] _repr_ = _repr_linear def _add_(self, other): """ Add two linear expressions. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: a = L([1, 2, 3], 4) sage: b = L([-1, 3, -3], 0) sage: a + b 0*x + 5*y + 0*z + 4 sage: a - b 2*x - y + 6*z + 4 """ const = self._const + other._const coeffs = self._coeffs + other._coeffs coeffs.set_immutable() return self.__class__(self.parent(), coeffs, const) def _lmul_(self, scalar): """ Multiply a linear expression by a scalar. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: a = L([1, 2, 3], 4); a x + 2*y + 3*z + 4 sage: 2 * a 2*x + 4*y + 6*z + 8 sage: a * 2 2*x + 4*y + 6*z + 8 sage: -a -x - 2*y - 3*z - 4 sage: RDF(1) * a 1.0*x + 2.0*y + 3.0*z + 4.0 TESTS:: sage: a._lmul_(2) 2*x + 4*y + 6*z + 8 """ const = scalar * self._const coeffs = scalar * self._coeffs coeffs.set_immutable() return self.__class__(self.parent(), coeffs, const) def _acted_upon_(self, scalar, self_on_left): """ Action by scalars that do not live in the base ring. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: a = x + 2*y + 3*z + 4 sage: a * RDF(3) 3.0*x + 6.0*y + 9.0*z + 12.0 """ base_ring = scalar.base_ring() parent = self.parent().change_ring(base_ring) changed = parent(self) return changed._rmul_(scalar) def change_ring(self, base_ring): """ Change the base ring of this linear expression. INPUT: - ``base_ring`` -- a ring; the new base ring OUTPUT: A new linear expression over the new base ring. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: a = x + 2*y + 3*z + 4; a x + 2*y + 3*z + 4 sage: a.change_ring(RDF) 1.0*x + 2.0*y + 3.0*z + 4.0 """ P = self.parent() if P.base_ring() is base_ring: return self return P.change_ring(base_ring)(self) def __hash__(self): r""" TESTS:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x> = LinearExpressionModule(QQ) sage: hash(L([0,1])) == hash((1,)) True """ return hash(self._coeffs) ^ hash(self._const) def _richcmp_(self, other, op): """ Compare two linear expressions. INPUT: - ``other`` -- another linear expression (will be enforced by the coercion framework) EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x> = LinearExpressionModule(QQ) sage: x == L([0, 1]) True sage: x == x + 1 False sage: M.<x> = LinearExpressionModule(ZZ) sage: L.gen(0) == M.gen(0) # because there is a conversion True sage: L.gen(0) == L(M.gen(0)) # this is the conversion True sage: x == 'test' False """ return richcmp((self._coeffs, self._const), (other._coeffs, other._const), op) def evaluate(self, point): """ Evaluate the linear expression. INPUT: - ``point`` -- list/tuple/iterable of coordinates; the coordinates of a point OUTPUT: The linear expression `Ax + b` evaluated at the point `x`. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y> = LinearExpressionModule(QQ) sage: ex = 2*x + 3* y + 4 sage: ex.evaluate([1,1]) 9 sage: ex([1,1]) # syntactic sugar 9 sage: ex([pi, e]) 2*pi + 3*e + 4 """ try: point = self.parent().ambient_module()(point) except TypeError: from sage.matrix.constructor import vector point = vector(point) return self._coeffs * point + self._const __call__ = evaluate class LinearExpressionModule(Parent, UniqueRepresentation): """ The module of linear expressions. This is the module of linear polynomials which is the parent for linear expressions. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: L Module of linear expressions in variables x, y, z over Rational Field sage: L.an_element() x + 0*y + 0*z + 0 """ Element = LinearExpression def __init__(self, base_ring, names=tuple()): """ Initialize ``self``. TESTS:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: type(L) <class 'sage.geometry.linear_expression.LinearExpressionModule_with_category'> sage: L.base_ring() Rational Field sage: TestSuite(L).run() sage: L = LinearExpressionModule(QQ) sage: TestSuite(L).run() """ from sage.categories.modules import Modules super().__init__(base_ring, category=Modules(base_ring).WithBasis().FiniteDimensional()) self._names = names @cached_method def basis(self): """ Return a basis of ``self``. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: list(L.basis()) [x + 0*y + 0*z + 0, 0*x + y + 0*z + 0, 0*x + 0*y + z + 0, 0*x + 0*y + 0*z + 1] """ from sage.sets.family import Family gens = self.gens() d = {i: g for i, g in enumerate(gens)} d['b'] = self.element_class(self, self.ambient_module().zero(), self.base_ring().one()) return Family(list(range(len(gens))) + ['b'], lambda i: d[i]) @cached_method def ngens(self): """ Return the number of linear variables. OUTPUT: An integer. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: L.ngens() 3 """ return len(self._names) @cached_method def gens(self): """ Return the generators of ``self``. OUTPUT: A tuple of linear expressions, one for each linear variable. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: L.gens() (x + 0*y + 0*z + 0, 0*x + y + 0*z + 0, 0*x + 0*y + z + 0) """ from sage.matrix.constructor import identity_matrix identity = identity_matrix(self.base_ring(), self.ngens()) return tuple(self(e, 0) for e in identity.rows()) def gen(self, i): """ Return the `i`-th generator. INPUT: - ``i`` -- integer OUTPUT: A linear expression. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: L.gen(0) x + 0*y + 0*z + 0 """ return self.gens()[i] def _element_constructor_(self, arg0, arg1=None): """ The element constructor. This is part of the Sage parent/element framework. TESTS:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) Construct from coefficients and constant term:: sage: L._element_constructor_([1, 2, 3], 4) x + 2*y + 3*z + 4 sage: L._element_constructor_(vector(ZZ, [1, 2, 3]), 4) x + 2*y + 3*z + 4 Construct constant linear expression term:: sage: L._element_constructor_(4) 0*x + 0*y + 0*z + 4 Construct from list/tuple/iterable:: sage: L._element_constructor_(vector([4, 1, 2, 3])) x + 2*y + 3*z + 4 Construct from a pair ``(coefficients, constant)``:: sage: L([(1, 2, 3), 4]) x + 2*y + 3*z + 4 Construct from linear expression:: sage: M = LinearExpressionModule(ZZ, ('u', 'v', 'w')) sage: m = M([1, 2, 3], 4) sage: L._element_constructor_(m) x + 2*y + 3*z + 4 """ R = self.base_ring() if arg1 is None: if arg0 in R: const = arg0 coeffs = self.ambient_module().zero() elif isinstance(arg0, LinearExpression): # Construct from linear expression const = arg0.b() coeffs = arg0.A() elif isinstance(arg0, (list, tuple)) and len(arg0) == 2 and isinstance(arg0[0], (list, tuple)): # Construct from pair coeffs = arg0[0] const = arg0[1] else: # Construct from list/tuple/iterable:: try: arg0 = arg0.dense_coefficient_list() except AttributeError: arg0 = list(arg0) const = arg0[0] coeffs = arg0[1:] else: # arg1 is not None, construct from coefficients and constant term coeffs = list(arg0) const = arg1 coeffs = self.ambient_module()(coeffs) coeffs.set_immutable() const = R(const) return self.element_class(self, coeffs, const) def random_element(self): """ Return a random element. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: L.random_element() in L True """ A = self.ambient_module().random_element() b = self.base_ring().random_element() return self(A, b) @cached_method def ambient_module(self): """ Return the ambient module. .. SEEALSO:: :meth:`ambient_vector_space` OUTPUT: The domain of the linear expressions as a free module over the base ring. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: L.ambient_module() Vector space of dimension 3 over Rational Field sage: M = LinearExpressionModule(ZZ, ('r', 's')) sage: M.ambient_module() Ambient free module of rank 2 over the principal ideal domain Integer Ring sage: M.ambient_vector_space() Vector space of dimension 2 over Rational Field """ from sage.modules.free_module import FreeModule return FreeModule(self.base_ring(), self.ngens()) @cached_method def ambient_vector_space(self): """ Return the ambient vector space. .. SEEALSO:: :meth:`ambient_module` OUTPUT: The vector space (over the fraction field of the base ring) where the linear expressions live. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: L.ambient_vector_space() Vector space of dimension 3 over Rational Field sage: M = LinearExpressionModule(ZZ, ('r', 's')) sage: M.ambient_module() Ambient free module of rank 2 over the principal ideal domain Integer Ring sage: M.ambient_vector_space() Vector space of dimension 2 over Rational Field """ from sage.modules.free_module import VectorSpace field = self.base_ring().fraction_field() return VectorSpace(field, self.ngens()) def _coerce_map_from_(self, P): """ Return whether there is a coercion. TESTS:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x> = LinearExpressionModule(QQ) sage: M.<y> = LinearExpressionModule(ZZ) sage: L.coerce_map_from(M) Coercion map: From: Module of linear expressions in variable y over Integer Ring To: Module of linear expressions in variable x over Rational Field sage: M.coerce_map_from(L) sage: M.coerce_map_from(ZZ) Coercion map: From: Integer Ring To: Module of linear expressions in variable y over Integer Ring sage: M.coerce_map_from(QQ) """ if self.base().has_coerce_map_from(P): return True try: return self.ngens() == P.ngens() and \ self.base().has_coerce_map_from(P.base()) except AttributeError: pass return super()._coerce_map_from_(P) def _repr_(self): """ Return a string representation. OUTPUT: A string. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x> = LinearExpressionModule(QQ); L Module of linear expressions in variable x over Rational Field """ return 'Module of linear expressions in variable{2} {0} over {1}'.format( ', '.join(self._names), self.base_ring(), 's' if self.ngens() > 1 else '') def change_ring(self, base_ring): """ Return a new module with a changed base ring. INPUT: - ``base_ring`` -- a ring; the new base ring OUTPUT: A new linear expression over the new base ring. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: M.<y> = LinearExpressionModule(ZZ) sage: L = M.change_ring(QQ); L Module of linear expressions in variable y over Rational Field TESTS:: sage: L.change_ring(QQ) is L True """ return LinearExpressionModule(base_ring, self._names)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/geometry/linear_expression.py
0.921247
0.703091
linear_expression.py
pypi
from sage.structure.unique_representation import UniqueRepresentation from sage.structure.parent import Parent from sage.structure.element import Element from sage.structure.richcmp import op_EQ, op_NE, op_LE, op_GE, op_LT from sage.misc.cachefunc import cached_method from sage.rings.infinity import Infinity from sage.geometry.polyhedron.constructor import Polyhedron from sage.geometry.polyhedron.base import is_Polyhedron class NewtonPolygon_element(Element): """ Class for infinite Newton polygons with last slope. """ def __init__(self, polyhedron, parent): """ Initialize a Newton polygon. INPUT: - polyhedron -- a polyhedron defining the Newton polygon TESTS: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NewtonPolygon([ (0,0), (1,1), (3,5) ]) Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 5) sage: NewtonPolygon([ (0,0), (1,1), (2,8), (3,5) ], last_slope=3) Infinite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 5) ending by an infinite line of slope 3 :: sage: TestSuite(NewtonPolygon).run() """ Element.__init__(self, parent) self._polyhedron = polyhedron self._vertices = None if polyhedron.is_mutable(): polyhedron._add_dependent_object(self) def _repr_(self): """ Return a string representation of this Newton polygon. EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,5) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 5) sage: NP._repr_() 'Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 5)' """ vertices = self.vertices() length = len(vertices) if self.last_slope() is Infinity: if length == 0: return "Empty Newton polygon" elif length == 1: return "Finite Newton polygon with 1 vertex: %s" % str(vertices[0]) else: return "Finite Newton polygon with %s vertices: %s" % (length, str(vertices)[1:-1]) else: if length == 1: return "Newton Polygon consisting of a unique infinite line of slope %s starting at %s" % (self.last_slope(), str(vertices[0])) else: return "Infinite Newton polygon with %s vertices: %s ending by an infinite line of slope %s" % (length, str(vertices)[1:-1], self.last_slope()) def vertices(self, copy=True): """ Returns the list of vertices of this Newton polygon INPUT: - ``copy`` -- a boolean (default: ``True``) OUTPUT: The list of vertices of this Newton polygon (or a copy of it if ``copy`` is set to True) EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,5) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 5) sage: v = NP.vertices(); v [(0, 0), (1, 1), (2, 5)] TESTS: sage: del v[0] sage: v [(1, 1), (2, 5)] sage: NP.vertices() [(0, 0), (1, 1), (2, 5)] """ if self._vertices is None: self._vertices = [ tuple(v) for v in self._polyhedron.vertices() ] self._vertices.sort() if copy: return list(self._vertices) else: return self._vertices @cached_method def last_slope(self): """ Returns the last (infinite) slope of this Newton polygon if it is infinite and ``+Infinity`` otherwise. EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP1 = NewtonPolygon([ (0,0), (1,1), (2,8), (3,5) ], last_slope=3) sage: NP1.last_slope() 3 sage: NP2 = NewtonPolygon([ (0,0), (1,1), (2,5) ]) sage: NP2.last_slope() +Infinity We check that the last slope of a sum (resp. a product) is the minimum of the last slopes of the summands (resp. the factors):: sage: (NP1 + NP2).last_slope() 3 sage: (NP1 * NP2).last_slope() 3 """ rays = self._polyhedron.rays() for r in rays: if r[0] > 0: return r[1]/r[0] return Infinity def slopes(self, repetition=True): """ Returns the slopes of this Newton polygon INPUT: - ``repetition`` -- a boolean (default: ``True``) OUTPUT: The consecutive slopes (not including the last slope if the polygon is infinity) of this Newton polygon. If ``repetition`` is True, each slope is repeated a number of times equal to its length. Otherwise, it appears only one time. EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (3,6) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 6) sage: NP.slopes() [1, 5/2, 5/2] sage: NP.slopes(repetition=False) [1, 5/2] """ slopes = [ ] vertices = self.vertices(copy=False) for i in range(1,len(vertices)): dx = vertices[i][0] - vertices[i-1][0] dy = vertices[i][1] - vertices[i-1][1] slope = dy/dx if repetition: slopes.extend(dx * [slope]) else: slopes.append(slope) return slopes def _add_(self, other): """ Returns the convex hull of ``self`` and ``other`` INPUT: - ``other`` -- a Newton polygon OUTPUT: The Newton polygon, which is the convex hull of this Newton polygon and ``other`` EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP1 = NewtonPolygon([ (0,0), (1,1), (2,6) ]); NP1 Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 6) sage: NP2 = NewtonPolygon([ (0,0), (1,3/2) ], last_slope=2); NP2 Infinite Newton polygon with 2 vertices: (0, 0), (1, 3/2) ending by an infinite line of slope 2 sage: NP1 + NP2 Infinite Newton polygon with 2 vertices: (0, 0), (1, 1) ending by an infinite line of slope 2 """ polyhedron = self._polyhedron.convex_hull(other._polyhedron) return self.parent()(polyhedron) def _mul_(self, other): """ Returns the Minkowski sum of ``self`` and ``other`` INPUT: - ``other`` -- a Newton polygon OUTPUT: The Newton polygon, which is the Minkowski sum of this Newton polygon and ``other``. .. NOTE:: If ``self`` and ``other`` are respective Newton polygons of some polynomials `f` and `g` the self*other is the Newton polygon of the product `fg` EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP1 = NewtonPolygon([ (0,0), (1,1), (2,6) ]); NP1 Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 6) sage: NP2 = NewtonPolygon([ (0,0), (1,3/2) ], last_slope=2); NP2 Infinite Newton polygon with 2 vertices: (0, 0), (1, 3/2) ending by an infinite line of slope 2 sage: NP = NP1 * NP2; NP Infinite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 5/2) ending by an infinite line of slope 2 The slopes of ``NP`` is the union of those of ``NP1`` and those of ``NP2`` which are less than the last slope:: sage: NP1.slopes() [1, 5] sage: NP2.slopes() [3/2] sage: NP.slopes() [1, 3/2] """ polyhedron = self._polyhedron.minkowski_sum(other._polyhedron) return self.parent()(polyhedron) def __pow__(self, exp, ignored=None): """ Returns ``self`` dilated by ``exp`` INPUT: - ``exp`` -- a positive integer OUTPUT: This Newton polygon scaled by a factor ``exp``. .. NOTE:: If ``self`` is the Newton polygon of a polynomial `f`, then ``self^exp`` is the Newton polygon of `f^{exp}`. EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,6) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 6) sage: NP^10 Finite Newton polygon with 3 vertices: (0, 0), (10, 10), (20, 60) """ polyhedron = self._polyhedron.dilation(exp) return self.parent()(polyhedron) def __lshift__(self, i): """ Returns ``self`` shifted by `(0,i)` INPUT: - ``i`` -- a rational number OUTPUT: This Newton polygon shifted by the vector `(0,i)` EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,6) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 6) sage: NP << 2 Finite Newton polygon with 3 vertices: (0, 2), (1, 3), (2, 8) """ polyhedron = self._polyhedron.translation((0,i)) return self.parent()(polyhedron) def __rshift__(self, i): """ Returns ``self`` shifted by `(0,-i)` INPUT: - ``i`` -- a rational number OUTPUT: This Newton polygon shifted by the vector `(0,-i)` EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,6) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 6) sage: NP >> 2 Finite Newton polygon with 3 vertices: (0, -2), (1, -1), (2, 4) """ polyhedron = self._polyhedron.translation((0,-i)) return self.parent()(polyhedron) def __call__(self, x): """ Returns `self(x)` INPUT: - ``x`` -- a real number OUTPUT: The value of this Newton polygon at abscissa `x` EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (3,6) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 6) sage: [ NP(i) for i in range(4) ] [0, 1, 7/2, 6] """ # complexity: O(log(n)) vertices = self.vertices() lastslope = self.last_slope() if len(vertices) == 0 or x < vertices[0][0]: return Infinity if x == vertices[0][0]: return vertices[0][1] if x == vertices[-1][0]: return vertices[-1][1] if x > vertices[-1][0]: return vertices[-1][1] + lastslope * (x - vertices[-1][0]) a = 0 b = len(vertices) while b - a > 1: c = (a + b) // 2 if vertices[c][0] < x: a = c else: b = c xg, yg = vertices[a] xd, yd = vertices[b] return ((x-xg)*yd + (xd-x)*yg) / (xd-xg) def _richcmp_(self, other, op): r""" Comparisons of two Newton polygons. TESTS:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP1 = NewtonPolygon([ (0,0), (1,1), (3,6) ]) sage: NP2 = NewtonPolygon([ (0,0), (1,1), (2,6), (3,6) ]) sage: NP1 == NP2 True sage: NP1 != NP2 False sage: NP1 >= NP1 and NP2 >= NP2 True sage: NP1 > NP1 or NP2 > NP2 False sage: NP1 = NewtonPolygon([ (0,0), (1,1), (2,6) ]) sage: NP2 = NewtonPolygon([ (0,0), (1,3/2) ], last_slope=2) sage: NP3 = NP1 + NP2 sage: NP1 <= NP2 False sage: NP3 <= NP1 True sage: NP3 <= NP2 True sage: NP1 < NP1 False sage: NP1 < NP2 False sage: NP1 >= NP2 False sage: NP1 >= NP3 True sage: NP1 > NP1 False sage: NP1 > NP2 False sage: NP1 >= NP3 and NP2 >= NP3 and NP3 <= NP1 and NP3 <= NP2 True sage: NP1 > NP3 and NP2 > NP3 True sage: NP3 < NP2 and NP3 < NP1 True """ if self._polyhedron == other._polyhedron: return op == op_EQ or op == op_LE or op == op_GE elif op == op_NE: return True elif op == op_EQ: return False if op == op_LT or op == op_LE: if self.last_slope() > other.last_slope(): return False return all(v in self._polyhedron for v in other.vertices()) else: if self.last_slope() < other.last_slope(): return False return all(v in other._polyhedron for v in self.vertices()) def plot(self, **kwargs): """ Plot this Newton polygon. .. NOTE:: All usual rendering options (color, thickness, etc.) are available. EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,6) ]) sage: polygon = NP.plot() # optional - sage.plot """ vertices = self.vertices() if len(vertices) == 0: from sage.plot.graphics import Graphics return Graphics() else: from sage.plot.line import line (xstart,ystart) = vertices[0] (xend,yend) = vertices[-1] if self.last_slope() is Infinity: return line([(xstart, ystart+1), (xstart,ystart+0.5)], linestyle="--", **kwargs) \ + line([(xstart, ystart+0.5)] + vertices + [(xend, yend+0.5)], **kwargs) \ + line([(xend, yend+0.5), (xend, yend+1)], linestyle="--", **kwargs) else: return line([(xstart, ystart+1), (xstart,ystart+0.5)], linestyle="--", **kwargs) \ + line([(xstart, ystart+0.5)] + vertices + [(xend+0.5, yend + 0.5*self.last_slope())], **kwargs) \ + line([(xend+0.5, yend + 0.5*self.last_slope()), (xend+1, yend+self.last_slope())], linestyle="--", **kwargs) def reverse(self, degree=None): r""" Returns the symmetric of ``self`` INPUT: - ``degree`` -- an integer (default: the top right abscissa of this Newton polygon) OUTPUT: The image this Newton polygon under the symmetry '(x,y) \mapsto (degree-x, y)` EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,5) ]) sage: NP2 = NP.reverse(); NP2 Finite Newton polygon with 3 vertices: (0, 5), (1, 1), (2, 0) We check that the slopes of the symmetric Newton polygon are the opposites of the slopes of the original Newton polygon:: sage: NP.slopes() [1, 4] sage: NP2.slopes() [-4, -1] """ if self.last_slope() is not Infinity: raise ValueError("Can only reverse *finite* Newton polygons") if degree is None: degree = self.vertices()[-1][0] vertices = [ (degree-x,y) for (x,y) in self.vertices() ] vertices.reverse() parent = self.parent() polyhedron = Polyhedron(base_ring=parent.base_ring(), vertices=vertices, rays=[(0,1)]) return parent(polyhedron) class ParentNewtonPolygon(Parent, UniqueRepresentation): r""" Construct a Newton polygon. INPUT: - ``arg`` -- a list/tuple/iterable of vertices or of slopes. Currently, slopes must be rational numbers. - ``sort_slopes`` -- boolean (default: ``True``). Specifying whether slopes must be first sorted - ``last_slope`` -- rational or infinity (default: ``Infinity``). The last slope of the Newton polygon OUTPUT: The corresponding Newton polygon. .. note:: By convention, a Newton polygon always contains the point at infinity `(0, \infty)`. These polygons are attached to polynomials or series over discrete valuation rings (e.g. padics). EXAMPLES: We specify here a Newton polygon by its vertices:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NewtonPolygon([ (0,0), (1,1), (3,5) ]) Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 5) We note that the convex hull of the vertices is automatically computed:: sage: NewtonPolygon([ (0,0), (1,1), (2,8), (3,5) ]) Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 5) Note that the value ``+Infinity`` is allowed as the second coordinate of a vertex:: sage: NewtonPolygon([ (0,0), (1,Infinity), (2,8), (3,5) ]) Finite Newton polygon with 2 vertices: (0, 0), (3, 5) If last_slope is set, the returned Newton polygon is infinite and ends with an infinite line having the specified slope:: sage: NewtonPolygon([ (0,0), (1,1), (2,8), (3,5) ], last_slope=3) Infinite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 5) ending by an infinite line of slope 3 Specifying a last slope may discard some vertices:: sage: NewtonPolygon([ (0,0), (1,1), (2,8), (3,5) ], last_slope=3/2) Infinite Newton polygon with 2 vertices: (0, 0), (1, 1) ending by an infinite line of slope 3/2 Next, we define a Newton polygon by its slopes:: sage: NP = NewtonPolygon([0, 1/2, 1/2, 2/3, 2/3, 2/3, 1, 1]) sage: NP Finite Newton polygon with 5 vertices: (0, 0), (1, 0), (3, 1), (6, 3), (8, 5) sage: NP.slopes() [0, 1/2, 1/2, 2/3, 2/3, 2/3, 1, 1] By default, slopes are automatically sorted:: sage: NP2 = NewtonPolygon([0, 1, 1/2, 2/3, 1/2, 2/3, 1, 2/3]) sage: NP2 Finite Newton polygon with 5 vertices: (0, 0), (1, 0), (3, 1), (6, 3), (8, 5) sage: NP == NP2 True except if the contrary is explicitly mentioned:: sage: NewtonPolygon([0, 1, 1/2, 2/3, 1/2, 2/3, 1, 2/3], sort_slopes=False) Finite Newton polygon with 4 vertices: (0, 0), (1, 0), (6, 10/3), (8, 5) Slopes greater that or equal last_slope (if specified) are discarded:: sage: NP = NewtonPolygon([0, 1/2, 1/2, 2/3, 2/3, 2/3, 1, 1], last_slope=2/3) sage: NP Infinite Newton polygon with 3 vertices: (0, 0), (1, 0), (3, 1) ending by an infinite line of slope 2/3 sage: NP.slopes() [0, 1/2, 1/2] Be careful, do not confuse Newton polygons provided by this class with Newton polytopes. Compare:: sage: NP = NewtonPolygon([ (0,0), (1,45), (3,6) ]); NP Finite Newton polygon with 2 vertices: (0, 0), (3, 6) sage: x, y = polygen(QQ,'x, y') sage: p = 1 + x*y**45 + x**3*y**6 sage: p.newton_polytope() A 2-dimensional polyhedron in ZZ^2 defined as the convex hull of 3 vertices sage: p.newton_polytope().vertices() (A vertex at (0, 0), A vertex at (1, 45), A vertex at (3, 6)) """ Element = NewtonPolygon_element def __init__(self): """ Parent class for all Newton polygons. sage: from sage.geometry.newton_polygon import ParentNewtonPolygon sage: ParentNewtonPolygon() Parent for Newton polygons TESTS: This class is a singleton. sage: ParentNewtonPolygon() is ParentNewtonPolygon() True :: sage: TestSuite(ParentNewtonPolygon()).run() """ from sage.categories.semirings import Semirings from sage.rings.rational_field import QQ Parent.__init__(self, category=Semirings(), base=QQ) def _repr_(self): """ Returns the string representation of this parent, which is ``Parent for Newton polygons`` TESTS: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NewtonPolygon Parent for Newton polygons sage: NewtonPolygon._repr_() 'Parent for Newton polygons' """ return "Parent for Newton polygons" def _an_element_(self): """ Returns a Newton polygon (which is the empty one) TESTS: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NewtonPolygon._an_element_() Empty Newton polygon """ return self(Polyhedron(base_ring=self.base_ring(), ambient_dim=2)) def _element_constructor_(self, arg, sort_slopes=True, last_slope=Infinity): r""" INPUT: - ``arg`` -- an argument describing the Newton polygon - ``sort_slopes`` -- boolean (default: ``True``). Specifying whether slopes must be first sorted - ``last_slope`` -- rational or infinity (default: ``Infinity``). The last slope of the Newton polygon The first argument ``arg`` can be either: - a polyhedron in `\QQ^2` - the element ``0`` (corresponding to the empty Newton polygon) - the element ``1`` (corresponding to the Newton polygon of the constant polynomial equal to 1) - a list/tuple/iterable of vertices - a list/tuple/iterable of slopes OUTPUT: The corresponding Newton polygon. For more informations, see :class:`ParentNewtonPolygon`. TESTS: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NewtonPolygon(0) Empty Newton polygon sage: NewtonPolygon(1) Finite Newton polygon with 1 vertex: (0, 0) """ if is_Polyhedron(arg): return self.element_class(arg, parent=self) if arg == 0: polyhedron = Polyhedron(base_ring=self.base_ring(), ambient_dim=2) return self.element_class(polyhedron, parent=self) if arg == 1: polyhedron = Polyhedron(base_ring=self.base_ring(), vertices=[(0, 0)], rays=[(0, 1)]) return self.element_class(polyhedron, parent=self) if not isinstance(arg, list): try: arg = list(arg) except TypeError: raise TypeError("argument must be a list of coordinates or a list of (rational) slopes") if arg and arg[0] in self.base_ring(): if sort_slopes: arg.sort() x = y = 0 vertices = [(x, y)] for slope in arg: if slope not in self.base_ring(): raise TypeError("argument must be a list of coordinates or a list of (rational) slopes") x += 1 y += slope vertices.append((x, y)) else: vertices = [(x, y) for (x, y) in arg if y is not Infinity] if len(vertices) == 0: polyhedron = Polyhedron(base_ring=self.base_ring(), ambient_dim=2) else: rays = [(0, 1)] if last_slope is not Infinity: rays.append((1, last_slope)) polyhedron = Polyhedron(base_ring=self.base_ring(), vertices=vertices, rays=rays) return self.element_class(polyhedron, parent=self) NewtonPolygon = ParentNewtonPolygon()
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/geometry/newton_polygon.py
0.944836
0.541227
newton_polygon.py
pypi
from sage.structure.sage_object import SageObject from sage.matrix.constructor import vector class AffineSubspace(SageObject): """ An affine subspace. INPUT: - ``p`` -- list/tuple/iterable representing a point on the affine space - ``V`` -- vector subspace OUTPUT: Affine subspace parallel to ``V`` and passing through ``p``. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0,0], VectorSpace(QQ,4)) sage: a Affine space p + W where: p = (1, 0, 0, 0) W = Vector space of dimension 4 over Rational Field """ def __init__(self, p, V): r""" Construct an :class:`AffineSubspace`. TESTS:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0,0], VectorSpace(QQ,4)) sage: TestSuite(a).run() sage: AffineSubspace(0, VectorSpace(QQ,4)).point() (0, 0, 0, 0) """ R = V.base_ring() from sage.categories.fields import Fields if R not in Fields(): R = R.fraction_field() V = V.change_ring(R) self._base_ring = R self._linear_part = V p = V.ambient_vector_space()(p) p.set_immutable() self._point = p def __hash__(self): """ Return a hash value. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0,0], VectorSpace(QQ,4)) sage: a.__hash__() # random output -3713096828371451969 """ # note that the point is not canonically chosen, but the linear part is return hash(self._linear_part) def _repr_(self): r""" String representation for an :class:`AffineSubspace`. OUTPUT: A string. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0,0],VectorSpace(QQ,4)) sage: a Affine space p + W where: p = (1, 0, 0, 0) W = Vector space of dimension 4 over Rational Field """ return "Affine space p + W where:\n p = "+str(self._point)+"\n W = "+str(self._linear_part) def __eq__(self, other): r""" Test whether ``self`` is equal to ``other``. INPUT: - ``other`` -- an :class:`AffineSubspace` OUTPUT: A boolean. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0], matrix([[1,0,0]]).right_kernel()) sage: b = AffineSubspace([2,0,0], matrix([[1,0,0]]).right_kernel()) sage: c = AffineSubspace([1,1,0], matrix([[1,0,0]]).right_kernel()) sage: a == b False sage: a == c True """ V = self._linear_part W = other._linear_part return V == W and self._point - other._point in V def __ne__(self, other): r""" Test whether ``self`` is not equal to ``other``. INPUT: - ``other`` -- an :class:`AffineSubspace` OUTPUT: A boolean. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0],matrix([[1,0,0]]).right_kernel()) sage: b = AffineSubspace([2,0,0],matrix([[1,0,0]]).right_kernel()) sage: a == b False sage: a != b True sage: a != a False """ return not self == other def __le__(self, other): r""" Test whether ``self`` is an affine subspace of ``other``. INPUT: - ``other`` -- an :class:`AffineSubspace` OUTPUT: A boolean. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: V = VectorSpace(QQ, 3) sage: W1 = V.subspace([[1,0,0],[0,1,0]]) sage: W2 = V.subspace([[1,0,0]]) sage: a = AffineSubspace([1,2,3], W1) sage: b = AffineSubspace([1,2,3], W2) sage: a <= b False sage: a <= a True sage: b <= a True """ V = self._linear_part W = other._linear_part return V.is_subspace(W) and self._point-other._point in W def __lt__(self, other): r""" Test whether ``self`` is a proper affine subspace of ``other``. INPUT: - ``other`` -- an :class:`AffineSubspace` OUTPUT: A boolean. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: V = VectorSpace(QQ, 3) sage: W1 = V.subspace([[1,0,0], [0,1,0]]) sage: W2 = V.subspace([[1,0,0]]) sage: a = AffineSubspace([1,2,3], W1) sage: b = AffineSubspace([1,2,3], W2) sage: a < b False sage: a < a False sage: b < a True """ if self._linear_part == other._linear_part: return False return self <= other def __contains__(self, q): r""" Test whether the point ``q`` is in the affine space. INPUT: - ``q`` -- point as a list/tuple/iterable OUTPUT: A boolean. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0], matrix([[1,0,0]]).right_kernel()) sage: (1,1,0) in a True sage: (0,0,0) in a False """ q = vector(self._base_ring, q) return self._point - q in self._linear_part def linear_part(self): r""" Return the linear part of the affine space. OUTPUT: A vector subspace of the ambient space. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: A = AffineSubspace([2,3,1], matrix(QQ, [[1,2,3]]).right_kernel()) sage: A.linear_part() Vector space of degree 3 and dimension 2 over Rational Field Basis matrix: [ 1 0 -1/3] [ 0 1 -2/3] sage: A.linear_part().ambient_vector_space() Vector space of dimension 3 over Rational Field """ return self._linear_part def point(self): r""" Return a point ``p`` in the affine space. OUTPUT: A point of the affine space as a vector in the ambient space. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: A = AffineSubspace([2,3,1], VectorSpace(QQ,3)) sage: A.point() (2, 3, 1) """ return self._point def dimension(self): r""" Return the dimension of the affine space. OUTPUT: An integer. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0,0],VectorSpace(QQ,4)) sage: a.dimension() 4 """ return self.linear_part().dimension() def intersection(self, other): r""" Return the intersection of ``self`` with ``other``. INPUT: - ``other`` -- an :class:`AffineSubspace` OUTPUT: A new affine subspace, (or ``None`` if the intersection is empty). EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: V = VectorSpace(QQ,3) sage: U = V.subspace([(1,0,0), (0,1,0)]) sage: W = V.subspace([(0,1,0), (0,0,1)]) sage: A = AffineSubspace((0,0,0), U) sage: B = AffineSubspace((1,1,1), W) sage: A.intersection(B) Affine space p + W where: p = (1, 1, 0) W = Vector space of degree 3 and dimension 1 over Rational Field Basis matrix: [0 1 0] sage: C = AffineSubspace((0,0,1), U) sage: A.intersection(C) sage: C = AffineSubspace((7,8,9), U.complement()) sage: A.intersection(C) Affine space p + W where: p = (7, 8, 0) W = Vector space of degree 3 and dimension 0 over Rational Field Basis matrix: [] sage: A.intersection(C).intersection(B) sage: D = AffineSubspace([1,2,3], VectorSpace(GF(5),3)) sage: E = AffineSubspace([3,4,5], VectorSpace(GF(5),3)) sage: D.intersection(E) Affine space p + W where: p = (3, 4, 0) W = Vector space of dimension 3 over Finite Field of size 5 """ if self.linear_part().ambient_vector_space() != \ other.linear_part().ambient_vector_space(): raise ValueError('incompatible ambient vector spaces') m = self.linear_part().matrix() n = other.linear_part().matrix() p = self.point() q = other.point() M = m.stack(n) v = q - p try: t = M.solve_left(v) except ValueError: return None # empty intersection new_p = p + t[:m.nrows()]*m new_V = self.linear_part().intersection(other._linear_part) return AffineSubspace(new_p, new_V)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/geometry/hyperplane_arrangement/affine_subspace.py
0.943426
0.696313
affine_subspace.py
pypi
from copy import copy from colorsys import hsv_to_rgb from sage.misc.lazy_import import lazy_import lazy_import("sage.plot.plot3d.parametric_plot3d", "parametric_plot3d") lazy_import("sage.plot.plot3d.shapes2", "text3d") lazy_import("sage.plot.graphics", "Graphics") lazy_import("sage.plot.line", "line") lazy_import("sage.plot.text", "text") lazy_import("sage.plot.point", "point") lazy_import("sage.plot.plot", "parametric_plot") from sage.symbolic.ring import SR def plot(hyperplane_arrangement, **kwds): r""" Return a plot of the hyperplane arrangement. If the arrangement is in 4 dimensions but inessential, a plot of the essentialization is returned. .. NOTE:: This function is available as the :meth:`~sage.geometry.hyperplane_arrangement.arrangement.HyperplaneArrangementElement.plot` method of hyperplane arrangements. You should not call this function directly, only through the method. INPUT: - ``hyperplane_arrangement`` -- the hyperplane arrangement to plot - ``**kwds`` -- plot options: see :mod:`sage.geometry.hyperplane_arrangement.plot`. OUTPUT: A graphics object of the plot. EXAMPLES:: sage: B = hyperplane_arrangements.semiorder(4) sage: B.plot() # optional - sage.plot Displaying the essentialization. Graphics3d Object """ N = len(hyperplane_arrangement) dim = hyperplane_arrangement.dimension() if hyperplane_arrangement.base_ring().characteristic() != 0: raise NotImplementedError('must be a field of characteristic 0') elif dim == 4: if not hyperplane_arrangement.is_essential(): print('Displaying the essentialization.') hyperplane_arrangement = hyperplane_arrangement.essentialization() elif dim not in [1,2,3]: # revise to handle 4d return # silently # handle extra keywords if 'hyperplane_colors' in kwds: hyp_colors = kwds.pop('hyperplane_colors') if not isinstance(hyp_colors, list): # we assume its a single color then hyp_colors = [hyp_colors] * N else: HSV_tuples = [(i*1.0/N, 0.8, 0.9) for i in range(N)] hyp_colors = [hsv_to_rgb(*x) for x in HSV_tuples] if 'hyperplane_labels' in kwds: hyp_labels = kwds.pop('hyperplane_labels') has_hyp_label = True if not isinstance(hyp_labels, list): # we assume its a boolean then hyp_labels = [hyp_labels] * N relabeled = [] for i in range(N): if hyp_labels[i] in [True,'long']: relabeled.append(True) else: relabeled.append(str(i)) hyp_labels = relabeled else: has_hyp_label = False if 'label_colors' in kwds: label_colors = kwds.pop('label_colors') has_label_color = True if not isinstance(label_colors, list): # we assume its a single color then label_colors = [label_colors] * N else: has_label_color = False if 'label_fontsize' in kwds: label_fontsize = kwds.pop('label_fontsize') has_label_fontsize = True if not isinstance(label_fontsize, list): # we assume its a single size then label_fontsize = [label_fontsize] * N else: has_label_fontsize = False if 'label_offsets' in kwds: has_offsets = True offsets = kwds.pop('label_offsets') else: has_offsets = False # give default values below hyperplane_legend = kwds.pop('hyperplane_legend', 'long' if dim < 3 else False) if 'hyperplane_opacities' in kwds: hyperplane_opacities = kwds.pop('hyperplane_opacities') has_opacity = True if not isinstance(hyperplane_opacities, list): # we assume a single number then hyperplane_opacities = [hyperplane_opacities] * N else: has_opacity = False point_sizes = kwds.pop('point_sizes', 50) if not isinstance(point_sizes, list): point_sizes = [point_sizes] * N if 'ranges' in kwds: ranges_set = True ranges = kwds.pop('ranges') if not type(ranges) in [list,tuple]: # ranges is a single number ranges = [ranges] * N # So ranges is some type of list. elif dim == 2: # arrangement of lines in the plane if not type(ranges[0]) in [list,tuple]: # a single interval ranges = [ranges] * N elif dim == 3: # arrangement of planes in 3-space if not type(ranges[0][0]) in [list,tuple]: ranges = [ranges] * N elif dim not in [2,3]: # ranges is not an option unless dim is 2 or 3 ranges_set = False else: # a list of intervals, one for each hyperplane is given pass # ranges does not need to be modified else: ranges_set = False # give default values below # the extra keywords have now been handled # now handle the legend if dim in [1,2]: # points on a line or lines in the plane if hyperplane_legend in [True,'long']: hyps = hyperplane_arrangement.hyperplanes() legend_labels = [hyps[i]._latex_() for i in range(N)] elif hyperplane_legend == 'short' : legend_labels = [str(i) for i in range(N)] else: # dim==3, arrangement of planes in 3-space if hyperplane_legend in [True, 'long']: legend3d = legend_3d(hyperplane_arrangement, hyp_colors, 'long') elif hyperplane_legend == 'short': legend3d = legend_3d(hyperplane_arrangement, hyp_colors, 'short') ## done handling the legend ## now create the plot p = Graphics() for i in range(N): newk = copy(kwds) if has_hyp_label: newk['hyperplane_label'] = hyp_labels[i] if has_offsets: if not isinstance(offsets, list): newk['label_offset'] = offsets else: newk['label_offset'] = offsets[i] else: newk['hyperplane_label'] = False if has_label_color: newk['label_color'] = label_colors[i] if has_label_fontsize: newk['label_fontsize'] = label_fontsize[i] if has_opacity: newk['opacity'] = hyperplane_opacities[i] if dim == 1: newk['point_size'] = point_sizes[i] if dim in [1,2] and hyperplane_legend: # more options than T/F newk['legend_label'] = legend_labels[i] if ranges_set: newk['ranges'] = ranges[i] p += plot_hyperplane(hyperplane_arrangement[i], rgbcolor=hyp_colors[i], **newk) if dim == 1: if hyperplane_legend: # there are more options than T/F p.legend(True) return p elif dim == 2: if hyperplane_legend: # there are more options than T/F p.legend(True) return p else: # dim==3 if hyperplane_legend: # there are more options than T/F return p, legend3d else: return p def plot_hyperplane(hyperplane, **kwds): r""" Return the plot of a single hyperplane. INPUT: - ``**kwds`` -- plot options: see below OUTPUT: A graphics object of the plot. .. RUBRIC:: Plot Options Beside the usual plot options (enter ``plot?``), the plot command for hyperplanes includes the following: - ``hyperplane_label`` -- Boolean value or string (default: ``True``). If ``True``, the hyperplane is labeled with its equation, if a string, it is labeled by that string, otherwise it is not labeled. - ``label_color`` -- (Default: ``'black'``) Color for hyperplane_label. - ``label_fontsize`` -- Size for ``hyperplane_label`` font (default: 14) (does not work in 3d, yet). - ``label_offset`` -- (Default: 0-dim: 0.1, 1-dim: (0,1), 2-dim: (0,0,0.2)) Amount by which label is offset from ``hyperplane.point()``. - ``point_size`` -- (Default: 50) Size of points in a zero-dimensional arrangement or of an arrangement over a finite field. - ``ranges`` -- Range for the parameters for the parametric plot of the hyperplane. If a single positive number ``r`` is given for the value of ``ranges``, then the ranges for all parameters are set to `[-r, r]`. Otherwise, for a line in the plane, ``ranges`` has the form ``[a, b]`` (default: [-3,3]), and for a plane in 3-space, the ``ranges`` has the form ``[[a, b], [c, d]]`` (default: [[-3,3],[-3,3]]). (The ranges are centered around ``hyperplane.point()``.) EXAMPLES:: sage: H1.<x> = HyperplaneArrangements(QQ) sage: a = 3*x + 4 sage: a.plot() # indirect doctest # optional - sage.plot Graphics object consisting of 3 graphics primitives sage: a.plot(point_size=100,hyperplane_label='hello') # optional - sage.plot Graphics object consisting of 3 graphics primitives sage: H2.<x,y> = HyperplaneArrangements(QQ) sage: b = 3*x + 4*y + 5 sage: b.plot() # optional - sage.plot Graphics object consisting of 2 graphics primitives sage: b.plot(ranges=(1,5),label_offset=(2,-1)) # optional - sage.plot Graphics object consisting of 2 graphics primitives sage: opts = {'hyperplane_label':True, 'label_color':'green', ....: 'label_fontsize':24, 'label_offset':(0,1.5)} sage: b.plot(**opts) # optional - sage.plot Graphics object consisting of 2 graphics primitives sage: H3.<x,y,z> = HyperplaneArrangements(QQ) sage: c = 2*x + 3*y + 4*z + 5 sage: c.plot() # optional - sage.plot Graphics3d Object sage: c.plot(label_offset=(1,0,1), color='green', label_color='red', frame=False) # optional - sage.plot Graphics3d Object sage: d = -3*x + 2*y + 2*z + 3 sage: d.plot(opacity=0.8) # optional - sage.plot Graphics3d Object sage: e = 4*x + 2*z + 3 sage: e.plot(ranges=[[-1,1],[0,8]], label_offset=(2,2,1), aspect_ratio=1) # optional - sage.plot Graphics3d Object """ if hyperplane.base_ring().characteristic(): raise NotImplementedError('base field must have characteristic zero') elif hyperplane.dimension() not in [0, 1, 2]: # dimension of hyperplane, not ambient space raise ValueError('can only plot hyperplanes in dimensions 1, 2, 3') # handle extra keywords if 'hyperplane_label' in kwds: hyp_label = kwds.pop('hyperplane_label') if not hyp_label: has_hyp_label = False else: has_hyp_label = True else: # default hyp_label = True has_hyp_label = True if has_hyp_label: if hyp_label: # then label hyperplane with its equation if hyperplane.dimension() == 2: # jmol does not like latex label = hyperplane._repr_linear(include_zero=False) else: label = hyperplane._latex_() else: label = hyp_label # a string if 'label_color' in kwds: label_color = kwds.pop('label_color') else: label_color = 'black' if 'label_fontsize' in kwds: label_fontsize = kwds.pop('label_fontsize') else: label_fontsize = 14 if 'label_offset' in kwds: has_offset = True label_offset = kwds.pop('label_offset') else: has_offset = False # give default values below if 'point_size' in kwds: pt_size = kwds.pop('point_size') else: pt_size = 50 if 'ranges' in kwds: ranges_set = True ranges = kwds.pop('ranges') else: ranges_set = False # give default values below # the extra keywords have now been handled # now create the plot if hyperplane.dimension() == 0: # a point on a line x, = hyperplane.A() d = hyperplane.b() p = point((d/x,0), size=pt_size, **kwds) if has_hyp_label: if not has_offset: label_offset = 0.1 p += text(label, (d/x,label_offset), color=label_color,fontsize=label_fontsize) p += text('',(d/x,label_offset+0.4)) # add space at top if 'ymax' not in kwds: kwds['ymax'] = 0.5 elif hyperplane.dimension() == 1: # a line in the plane pnt = hyperplane.point() w = hyperplane.linear_part().matrix() t = SR.var('t') if ranges_set: if isinstance(ranges, (list, tuple)): t0, t1 = ranges else: # ranges should be a single positive number t0, t1 = -ranges, ranges else: # default t0, t1 = -3, 3 p = parametric_plot(pnt + t * w[0], (t, t0, t1), **kwds) if has_hyp_label: if has_offset: b0, b1 = label_offset else: b0, b1 = 0, 0.2 label = text(label,(pnt[0] + b0, pnt[1] + b1), color=label_color,fontsize=label_fontsize) p += label elif hyperplane.dimension() == 2: # a plane in 3-space pnt = hyperplane.point() w = hyperplane.linear_part().matrix() s, t = SR.var('s t') if ranges_set: if isinstance(ranges, (list, tuple)): s0, s1 = ranges[0] t0, t1 = ranges[1] else: # ranges should be a single positive integers s0, s1 = -ranges, ranges t0, t1 = -ranges, ranges else: # default s0, s1 = -3, 3 t0, t1 = -3, 3 p = parametric_plot3d(pnt+s*w[0]+t*w[1], (s,s0,s1), (t,t0,t1), **kwds) if has_hyp_label: if has_offset: b0, b1, b2 = label_offset else: b0, b1, b2 = 0, 0, 0 label = text3d(label,(pnt[0]+b0, pnt[1]+b1, pnt[2]+b2), color=label_color, fontsize=label_fontsize) p += label return p def legend_3d(hyperplane_arrangement, hyperplane_colors, length): r""" Create plot of a 3d legend for an arrangement of planes in 3-space. The ``length`` parameter determines whether short or long labels are used in the legend. INPUT: - ``hyperplane_arrangement`` -- a hyperplane arrangement - ``hyperplane_colors`` -- list of colors - ``length`` -- either ``'short'`` or ``'long'`` OUTPUT: - A graphics object. EXAMPLES:: sage: a = hyperplane_arrangements.semiorder(3) sage: from sage.geometry.hyperplane_arrangement.plot import legend_3d sage: legend_3d(a, list(colors.values())[:6],length='long') Graphics object consisting of 6 graphics primitives sage: b = hyperplane_arrangements.semiorder(4) sage: c = b.essentialization() sage: legend_3d(c, list(colors.values())[:12], length='long') Graphics object consisting of 12 graphics primitives sage: legend_3d(c, list(colors.values())[:12], length='short') Graphics object consisting of 12 graphics primitives sage: p = legend_3d(c, list(colors.values())[:12], length='short') sage: p.set_legend_options(ncol=4) sage: type(p) <class 'sage.plot.graphics.Graphics'> """ if hyperplane_arrangement.dimension() != 3: raise ValueError('arrangements must be in 3-space') hyps = hyperplane_arrangement.hyperplanes() N = len(hyperplane_arrangement) if length == 'short': labels = [' ' + str(i) for i in range(N)] else: labels = [' ' + hyps[i]._repr_linear(include_zero=False) for i in range(N)] p = Graphics() for i in range(N): p += line([(0,0),(0,0)], color=hyperplane_colors[i], thickness=8, legend_label=labels[i], axes=False) p.set_legend_options(title='Hyperplanes', loc='center', labelspacing=0.4, fancybox=True, font_size='x-large', ncol=2) p.legend(True) return p
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/geometry/hyperplane_arrangement/plot.py
0.680772
0.397763
plot.py
pypi
from itertools import product from sage.structure.sage_object import SageObject from sage.modules.free_module_element import vector from sage.matrix.constructor import matrix from sage.calculus.functional import diff from sage.misc.functional import sqrt from sage.misc.cachefunc import cached_method from sage.symbolic.ring import SR from sage.symbolic.constants import pi def _simplify_full_rad(f): """ Helper function to conveniently call :meth:`simplify_full` and :meth:`canonicalize_radical` in succession. INPUT: - ``f`` - a symbolic expression. EXAMPLES:: sage: from sage.geometry.riemannian_manifolds.parametrized_surface3d import _simplify_full_rad sage: _simplify_full_rad(sqrt(x^2)/x) 1 """ return f.simplify_full().canonicalize_radical() class ParametrizedSurface3D(SageObject): r""" Class representing a parametrized two-dimensional surface in Euclidian three-space. Provides methods for calculating the main geometrical objects related to such a surface, such as the first and the second fundamental form, the total (Gaussian) and the mean curvature, the geodesic curves, parallel transport, etc. INPUT: - ``surface_equation`` -- a 3-tuple of functions specifying a parametric representation of the surface. - ``variables`` -- a 2-tuple of intrinsic coordinates `(u, v)` on the surface, with `u` and `v` symbolic variables, or a 2-tuple of triples `(u, u_{min}, u_{max})`, `(v, v_{min}, v_{max})` when the parameter range for the coordinates is known. - ``name`` -- name of the surface (optional). .. note:: Throughout the documentation, we use the Einstein summation convention: whenever an index appears twice, once as a subscript, and once as a superscript, summation over that index is implied. For instance, `g_{ij} g^{jk}` stands for `\sum_j g_{ij}g^{jk}`. EXAMPLES: We give several examples of standard surfaces in differential geometry. First, let's construct an elliptic paraboloid by explicitly specifying its parametric equation:: sage: u, v = var('u,v', domain='real') sage: eparaboloid = ParametrizedSurface3D((u, v, u^2 + v^2), (u, v),'elliptic paraboloid'); eparaboloid Parametrized surface ('elliptic paraboloid') with equation (u, v, u^2 + v^2) When the ranges for the intrinsic coordinates are known, they can be specified explicitly. This is mainly useful for plotting. Here we construct half of an ellipsoid:: sage: u1, u2 = var ('u1, u2', domain='real') sage: coords = ((u1, -pi/2, pi/2), (u2, 0, pi)) sage: ellipsoid_eq = (cos(u1)*cos(u2), 2*sin(u1)*cos(u2), 3*sin(u2)) sage: ellipsoid = ParametrizedSurface3D(ellipsoid_eq, coords, 'ellipsoid'); ellipsoid Parametrized surface ('ellipsoid') with equation (cos(u1)*cos(u2), 2*cos(u2)*sin(u1), 3*sin(u2)) sage: ellipsoid.plot() # optional - sage.plot Graphics3d Object Standard surfaces can be constructed using the ``surfaces`` generator:: sage: klein = surfaces.Klein(); klein Parametrized surface ('Klein bottle') with equation (-(sin(1/2*u)*sin(2*v) - cos(1/2*u)*sin(v) - 1)*cos(u), -(sin(1/2*u)*sin(2*v) - cos(1/2*u)*sin(v) - 1)*sin(u), cos(1/2*u)*sin(2*v) + sin(1/2*u)*sin(v)) Latex representation of the surfaces:: sage: u, v = var('u, v', domain='real') sage: sphere = ParametrizedSurface3D((cos(u)*cos(v), sin(u)*cos(v), sin(v)), (u, v), 'sphere') sage: print(latex(sphere)) \left(\cos\left(u\right) \cos\left(v\right), \cos\left(v\right) \sin\left(u\right), \sin\left(v\right)\right) sage: print(sphere._latex_()) \left(\cos\left(u\right) \cos\left(v\right), \cos\left(v\right) \sin\left(u\right), \sin\left(v\right)\right) sage: print(sphere) Parametrized surface ('sphere') with equation (cos(u)*cos(v), cos(v)*sin(u), sin(v)) To plot a parametric surface, use the :meth:`plot` member function:: sage: enneper = surfaces.Enneper(); enneper Parametrized surface ('Enneper's surface') with equation (-1/9*(u^2 - 3*v^2 - 3)*u, -1/9*(3*u^2 - v^2 + 3)*v, 1/3*u^2 - 1/3*v^2) sage: enneper.plot(aspect_ratio='automatic') # optional - sage.plot Graphics3d Object We construct an ellipsoid whose axes are given by symbolic variables `a`, `b` and `c`, and find the natural frame of tangent vectors, expressed in intrinsic coordinates. Note that the result is a dictionary of vector fields:: sage: a, b, c = var('a, b, c', domain='real') sage: u1, u2 = var('u1, u2', domain='real') sage: ellipsoid_eq = (a*cos(u1)*cos(u2), b*sin(u1)*cos(u2), c*sin(u2)) sage: ellipsoid = ParametrizedSurface3D(ellipsoid_eq, (u1, u2), 'Symbolic ellipsoid'); ellipsoid Parametrized surface ('Symbolic ellipsoid') with equation (a*cos(u1)*cos(u2), b*cos(u2)*sin(u1), c*sin(u2)) sage: ellipsoid.natural_frame() {1: (-a*cos(u2)*sin(u1), b*cos(u1)*cos(u2), 0), 2: (-a*cos(u1)*sin(u2), -b*sin(u1)*sin(u2), c*cos(u2))} We find the normal vector field to the surface. The normal vector field is the vector product of the vectors of the natural frame, and is given by:: sage: ellipsoid.normal_vector() (b*c*cos(u1)*cos(u2)^2, a*c*cos(u2)^2*sin(u1), a*b*cos(u2)*sin(u2)) By default, the normal vector field is not normalized. To obtain the unit normal vector field of the elliptic paraboloid, we put:: sage: u, v = var('u,v', domain='real') sage: eparaboloid = ParametrizedSurface3D([u,v,u^2+v^2],[u,v],'elliptic paraboloid') sage: eparaboloid.normal_vector(normalized=True) (-2*u/sqrt(4*u^2 + 4*v^2 + 1), -2*v/sqrt(4*u^2 + 4*v^2 + 1), 1/sqrt(4*u^2 + 4*v^2 + 1)) Now let us compute the coefficients of the first fundamental form of the torus:: sage: u, v = var('u, v', domain='real') sage: a, b = var('a, b', domain='real') sage: torus = ParametrizedSurface3D(((a + b*cos(u))*cos(v),(a + b*cos(u))*sin(v), b*sin(u)),[u,v],'torus') sage: torus.first_fundamental_form_coefficients() {(1, 1): b^2, (1, 2): 0, (2, 1): 0, (2, 2): b^2*cos(u)^2 + 2*a*b*cos(u) + a^2} The first fundamental form can be used to compute the length of a curve on the surface. For example, let us find the length of the curve `u^1 = t`, `u^2 = t`, `t \in [0,2\pi]`, on the ellipsoid with axes `a=1`, `b=1.5` and `c=1`. So we take the curve:: sage: t = var('t', domain='real') sage: u1 = t sage: u2 = t Then find the tangent vector:: sage: du1 = diff(u1,t) sage: du2 = diff(u2,t) sage: du = vector([du1, du2]); du (1, 1) Once we specify numerical values for the axes of the ellipsoid, we can determine the numerical value of the length integral:: sage: L = sqrt(ellipsoid.first_fundamental_form(du, du).substitute(u1=u1,u2=u2)) sage: numerical_integral(L.substitute(a=2, b=1.5, c=1),0,1)[0] # rel tol 1e-11 2.00127905972 We find the area of the sphere of radius `R`:: sage: R = var('R', domain='real') sage: u, v = var('u,v', domain='real') sage: assume(R>0) sage: assume(cos(v)>0) sage: sphere = ParametrizedSurface3D([R*cos(u)*cos(v),R*sin(u)*cos(v),R*sin(v)],[u,v],'sphere') sage: integral(integral(sphere.area_form(),u,0,2*pi),v,-pi/2,pi/2) 4*pi*R^2 We can find an orthonormal frame field `\{e_1, e_2\}` of a surface and calculate its structure functions. Let us first determine the orthonormal frame field for the elliptic paraboloid:: sage: u, v = var('u,v', domain='real') sage: eparaboloid = ParametrizedSurface3D([u,v,u^2+v^2],[u,v],'elliptic paraboloid') sage: eparaboloid.orthonormal_frame() {1: (1/sqrt(4*u^2 + 1), 0, 2*u/sqrt(4*u^2 + 1)), 2: (-4*u*v/(sqrt(4*u^2 + 4*v^2 + 1)*sqrt(4*u^2 + 1)), sqrt(4*u^2 + 1)/sqrt(4*u^2 + 4*v^2 + 1), 2*v/(sqrt(4*u^2 + 4*v^2 + 1)*sqrt(4*u^2 + 1)))} We can express the orthogonal frame field both in exterior coordinates (i.e. expressed as vector field fields in the ambient space `\RR^3`, the default) or in intrinsic coordinates (with respect to the natural frame). Here we use intrinsic coordinates:: sage: eparaboloid.orthonormal_frame(coordinates='int') {1: (1/sqrt(4*u^2 + 1), 0), 2: (-4*u*v/(sqrt(4*u^2 + 4*v^2 + 1)*sqrt(4*u^2 + 1)), sqrt(4*u^2 + 1)/sqrt(4*u^2 + 4*v^2 + 1))} Using the orthonormal frame in interior coordinates, we can calculate the structure functions `c^k_{ij}` of the surface, defined by `[e_i,e_j] = c^k_{ij} e_k`, where `[e_i, e_j]` represents the Lie bracket of two frame vector fields `e_i, e_j`. For the elliptic paraboloid, we get:: sage: EE = eparaboloid.orthonormal_frame(coordinates='int') sage: E1 = EE[1]; E2 = EE[2] sage: CC = eparaboloid.frame_structure_functions(E1,E2) sage: CC[1,2,1].simplify_full() 4*sqrt(4*u^2 + 4*v^2 + 1)*v/((16*u^4 + 4*(4*u^2 + 1)*v^2 + 8*u^2 + 1)*sqrt(4*u^2 + 1)) We compute the Gaussian and mean curvatures of the sphere:: sage: sphere = surfaces.Sphere(); sphere Parametrized surface ('Sphere') with equation (cos(u)*cos(v), cos(v)*sin(u), sin(v)) sage: K = sphere.gauss_curvature(); K # Not tested -- see trac 12737 1 sage: H = sphere.mean_curvature(); H # Not tested -- see trac 12737 -1 We can easily generate a color plot of the Gaussian curvature of a surface. Here we deal with the ellipsoid:: sage: u1, u2 = var('u1,u2', domain='real') sage: u = [u1,u2] sage: ellipsoid_equation(u1,u2) = [2*cos(u1)*cos(u2),1.5*cos(u1)*sin(u2),sin(u1)] sage: ellipsoid = ParametrizedSurface3D(ellipsoid_equation(u1,u2), [u1, u2],'ellipsoid') sage: # set intervals for variables and the number of division points sage: u1min, u1max = -1.5, 1.5 sage: u2min, u2max = 0, 6.28 sage: u1num, u2num = 10, 20 sage: # make the arguments array sage: from numpy import linspace sage: u1_array = linspace(u1min, u1max, u1num) sage: u2_array = linspace(u2min, u2max, u2num) sage: u_array = [ (uu1,uu2) for uu1 in u1_array for uu2 in u2_array] sage: # Find the gaussian curvature sage: K(u1,u2) = ellipsoid.gauss_curvature() sage: # Make array of K values sage: K_array = [K(uu[0],uu[1]) for uu in u_array] sage: # Find minimum and max of the Gauss curvature sage: K_max = max(K_array) sage: K_min = min(K_array) sage: # Make the array of color coefficients sage: cc_array = [ (ccc - K_min)/(K_max - K_min) for ccc in K_array ] sage: points_array = [ellipsoid_equation(u_array[counter][0],u_array[counter][1]) for counter in range(0,len(u_array)) ] sage: curvature_ellipsoid_plot = sum( point([xx for xx in points_array[counter]],color=hue(cc_array[counter]/2)) for counter in range(0,len(u_array)) ) sage: curvature_ellipsoid_plot.show(aspect_ratio=1) We can find the principal curvatures and principal directions of the elliptic paraboloid:: sage: u, v = var('u, v', domain='real') sage: eparaboloid = ParametrizedSurface3D([u, v, u^2+v^2], [u, v], 'elliptic paraboloid') sage: pd = eparaboloid.principal_directions(); pd [(2*sqrt(4*u^2 + 4*v^2 + 1)/(16*u^4 + 16*v^4 + 8*(4*u^2 + 1)*v^2 + 8*u^2 + 1), [(1, v/u)], 1), (2/sqrt(4*u^2 + 4*v^2 + 1), [(1, -u/v)], 1)] We extract the principal curvatures:: sage: k1 = pd[0][0].simplify_full() sage: k1 2*sqrt(4*u^2 + 4*v^2 + 1)/(16*u^4 + 16*v^4 + 8*(4*u^2 + 1)*v^2 + 8*u^2 + 1) sage: k2 = pd[1][0].simplify_full() sage: k2 2/sqrt(4*u^2 + 4*v^2 + 1) and check them by comparison with the Gaussian and mean curvature expressed in terms of the principal curvatures:: sage: K = eparaboloid.gauss_curvature().simplify_full() sage: K 4/(16*u^4 + 16*v^4 + 8*(4*u^2 + 1)*v^2 + 8*u^2 + 1) sage: H = eparaboloid.mean_curvature().simplify_full() sage: H 2*(2*u^2 + 2*v^2 + 1)/(4*u^2 + 4*v^2 + 1)^(3/2) sage: (K - k1*k2).simplify_full() 0 sage: (2*H - k1 - k2).simplify_full() 0 We can find the intrinsic (local coordinates) of the principal directions:: sage: pd[0][1] [(1, v/u)] sage: pd[1][1] [(1, -u/v)] The ParametrizedSurface3D class also contains functionality to compute the coefficients of the second fundamental form, the shape operator, the rotation on the surface at a given angle, the connection coefficients. One can also calculate numerically the geodesics and the parallel translation along a curve. Here we compute a number of geodesics on the sphere emanating from the point ``(1, 0, 0)``, in various directions. The geodesics intersect again in the antipodal point ``(-1, 0, 0)``, indicating that these points are conjugate:: sage: S = surfaces.Sphere() sage: g1 = [c[-1] for c in S.geodesics_numerical((0,0),(1,0),(0,2*pi,100))] sage: g2 = [c[-1] for c in S.geodesics_numerical((0,0),(cos(pi/3),sin(pi/3)),(0,2*pi,100))] sage: g3 = [c[-1] for c in S.geodesics_numerical((0,0),(cos(2*pi/3),sin(2*pi/3)),(0,2*pi,100))] sage: (S.plot(opacity=0.3) + line3d(g1,color='red') + line3d(g2,color='red') + line3d(g3,color='red')).show() # optional - sage.plot """ def __init__(self, equation, variables, name=None): r""" See ``ParametrizedSurface3D`` for full documentation. .. note:: The orientation of the surface is determined by the parametrization, that is, the natural frame with positive orientation is given by `\partial_1 \vec r`, `\partial_2 \vec r`. EXAMPLES:: sage: u, v = var('u,v', domain='real') sage: eq = (3*u + 3*u*v^2 - u^3, 3*v + 3*u^2*v - v^3, 3*(u^2-v^2)) sage: enneper = ParametrizedSurface3D(eq, (u, v),'Enneper Surface'); enneper Parametrized surface ('Enneper Surface') with equation (-u^3 + 3*u*v^2 + 3*u, 3*u^2*v - v^3 + 3*v, 3*u^2 - 3*v^2) """ self.equation = tuple(equation) if isinstance(variables[0], (list, tuple)): self.variables_range = (variables[0][1:3], variables[1][1:3]) self.variables_list = (variables[0][0], variables[1][0]) else: self.variables_range = None self.variables_list = variables self.variables = {1:self.variables_list[0], 2:self.variables_list[1]} self.name = name def _latex_(self): r""" Return the LaTeX representation of this parametrized surface. EXAMPLES:: sage: u, v = var('u, v') sage: sphere = ParametrizedSurface3D((cos(u)*cos(v), sin(u)*cos(v), sin(v)), (u, v),'sphere') sage: latex(sphere) \left(\cos\left(u\right) \cos\left(v\right), \cos\left(v\right) \sin\left(u\right), \sin\left(v\right)\right) sage: sphere._latex_() \left(\cos\left(u\right) \cos\left(v\right), \cos\left(v\right) \sin\left(u\right), \sin\left(v\right)\right) """ from sage.misc.latex import latex return latex(self.equation) def _repr_(self): r""" Returns the string representation of this parametrized surface. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: eq = (3*u + 3*u*v^2 - u^3, 3*v + 3*u^2*v - v^3, 3*(u^2-v^2)) sage: enneper = ParametrizedSurface3D(eq,[u,v],'enneper_surface') sage: print(enneper) Parametrized surface ('enneper_surface') with equation (-u^3 + 3*u*v^2 + 3*u, 3*u^2*v - v^3 + 3*v, 3*u^2 - 3*v^2) sage: enneper._repr_() "Parametrized surface ('enneper_surface') with equation (-u^3 + 3*u*v^2 + 3*u, 3*u^2*v - v^3 + 3*v, 3*u^2 - 3*v^2)" """ name = 'Parametrized surface' if self.name is not None: name += " ('%s')" % self.name s ='%(designation)s with equation %(eq)s' % \ {'designation': name, 'eq': str(self.equation)} return s def point(self, coords): r""" Returns a point on the surface given its intrinsic coordinates. INPUT: - ``coords`` - 2-tuple specifying the intrinsic coordinates ``(u, v)`` of the point. OUTPUT: - 3-vector specifying the coordinates in `\RR^3` of the point. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: torus = ParametrizedSurface3D(((2 + cos(u))*cos(v),(2 + cos(u))*sin(v), sin(u)),[u,v],'torus') sage: torus.point((0, pi/2)) (0, 3, 0) sage: torus.point((pi/2, pi)) (-2, 0, 1) sage: torus.point((pi, pi/2)) (0, 1, 0) """ d = dict(zip(self.variables_list, coords)) return vector([f.subs(d) for f in self.equation]) def tangent_vector(self, coords, components): r""" Returns the components of a tangent vector given the intrinsic coordinates of the base point and the components of the vector in the intrinsic frame. INPUT: - ``coords`` - 2-tuple specifying the intrinsic coordinates ``(u, v)`` of the point. - ``components`` - 2-tuple specifying the components of the tangent vector in the intrinsic coordinate frame. OUTPUT: - 3-vector specifying the components in `\RR^3` of the vector. EXAMPLES: We compute two tangent vectors to Enneper's surface along the coordinate lines and check that their cross product gives the normal vector:: sage: u, v = var('u,v', domain='real') sage: eq = (3*u + 3*u*v^2 - u^3, 3*v + 3*u^2*v - v^3, 3*(u^2-v^2)) sage: e = ParametrizedSurface3D(eq, (u, v),'Enneper Surface') sage: w1 = e.tangent_vector((1, 2), (1, 0)); w1 (12, 12, 6) sage: w2 = e.tangent_vector((1, 2), (0, 1)); w2 (12, -6, -12) sage: w1.cross_product(w2) (-108, 216, -216) sage: n = e.normal_vector().subs({u: 1, v: 2}); n (-108, 216, -216) sage: n == w1.cross_product(w2) True """ components = vector(components) d = dict(zip(self.variables_list, coords)) jacobian = matrix([[f.diff(u).subs(d) for u in self.variables_list] for f in self.equation]) return jacobian * components def plot(self, urange=None, vrange=None, **kwds): r""" Enable easy plotting directly from the surface class. The optional keywords ``urange`` and ``vrange`` specify the range for the surface parameters `u` and `v`. If either of these parameters is ``None``, the method checks whether a parameter range was specified when the surface was created. If not, the default of `(0, 2 \pi)` is used. INPUT: - ``urange`` - 2-tuple specifying the parameter range for `u`. - ``vrange`` - 2-tuple specifying the parameter range for `v`. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: eq = (3*u + 3*u*v^2 - u^3, 3*v + 3*u^2*v - v^3, 3*(u^2-v^2)) sage: enneper = ParametrizedSurface3D(eq, (u, v), 'Enneper Surface') sage: enneper.plot((-5, 5), (-5, 5)) # optional - sage.plot Graphics3d Object """ from sage.plot.plot3d.parametric_plot3d import parametric_plot3d if self.variables_range is None: if urange is None: urange = (0, 2*pi) if vrange is None: vrange = (0, 2*pi) else: if urange is None: urange = self.variables_range[0] if vrange is None: vrange = self.variables_range[1] urange3 = (self.variables[1],) + tuple(urange) vrange3 = (self.variables[2],) + tuple(vrange) P = parametric_plot3d(self.equation, urange3, vrange3, **kwds) return P @cached_method def natural_frame(self): """ Returns the natural tangent frame on the parametrized surface. The vectors of this frame are tangent to the coordinate lines on the surface. OUTPUT: - The natural frame as a dictionary. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: eparaboloid = ParametrizedSurface3D((u, v, u^2+v^2), (u, v), 'elliptic paraboloid') sage: eparaboloid.natural_frame() {1: (1, 0, 2*u), 2: (0, 1, 2*v)} """ dr1 = \ vector([_simplify_full_rad( diff(f,self.variables[1]) ) for f in self.equation]) dr2 = \ vector([_simplify_full_rad( diff(f,self.variables[2]) ) for f in self.equation]) return {1:dr1, 2:dr2} @cached_method def normal_vector(self, normalized=False): """ Returns the normal vector field of the parametrized surface. INPUT: - ``normalized`` - default ``False`` - specifies whether the normal vector should be normalized. OUTPUT: - Normal vector field. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: eparaboloid = ParametrizedSurface3D((u, v, u^2 + v^2), (u, v), 'elliptic paraboloid') sage: eparaboloid.normal_vector(normalized=False) (-2*u, -2*v, 1) sage: eparaboloid.normal_vector(normalized=True) (-2*u/sqrt(4*u^2 + 4*v^2 + 1), -2*v/sqrt(4*u^2 + 4*v^2 + 1), 1/sqrt(4*u^2 + 4*v^2 + 1)) """ dr = self.natural_frame() normal = dr[1].cross_product(dr[2]) if normalized: normal /= normal.norm() return _simplify_full_rad(normal) @cached_method def _compute_first_fundamental_form_coefficient(self, index): """ Helper function to compute coefficients of the first fundamental form. Do not call this method directly; instead use ``first_fundamental_form_coefficient``. This method is cached, and expects its argument to be a list. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: eparaboloid = ParametrizedSurface3D((u, v, u^2+v^2), (u, v)) sage: eparaboloid._compute_first_fundamental_form_coefficient((1,2)) 4*u*v """ dr = self.natural_frame() return _simplify_full_rad(dr[index[0]]*dr[index[1]]) def first_fundamental_form_coefficient(self, index): r""" Compute a single component `g_{ij}` of the first fundamental form. If the parametric representation of the surface is given by the vector function `\vec r(u^i)`, where `u^i`, `i = 1, 2` are curvilinear coordinates, then `g_{ij} = \frac{\partial \vec r}{\partial u^i} \cdot \frac{\partial \vec r}{\partial u^j}`. INPUT: - ``index`` - tuple ``(i, j)`` specifying the index of the component `g_{ij}`. OUTPUT: - Component `g_{ij}` of the first fundamental form EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: eparaboloid = ParametrizedSurface3D((u, v, u^2+v^2), (u, v)) sage: eparaboloid.first_fundamental_form_coefficient((1,2)) 4*u*v When the index is invalid, an error is raised:: sage: u, v = var('u, v', domain='real') sage: eparaboloid = ParametrizedSurface3D((u, v, u^2+v^2), (u, v)) sage: eparaboloid.first_fundamental_form_coefficient((1,5)) Traceback (most recent call last): ... ValueError: Index (1, 5) out of bounds. """ index = tuple(sorted(index)) if len(index) == 2 and all(i == 1 or i == 2 for i in index): return self._compute_first_fundamental_form_coefficient(index) else: raise ValueError("Index %s out of bounds." % str(index)) def first_fundamental_form_coefficients(self): r""" Returns the coefficients of the first fundamental form as a dictionary. The keys are tuples `(i, j)`, where `i` and `j` range over `1, 2`, while the values are the corresponding coefficients `g_{ij}`. OUTPUT: - Dictionary of first fundamental form coefficients. EXAMPLES:: sage: u, v = var('u,v', domain='real') sage: sphere = ParametrizedSurface3D((cos(u)*cos(v), sin(u)*cos(v), sin(v)), (u, v), 'sphere') sage: sphere.first_fundamental_form_coefficients() {(1, 1): cos(v)^2, (1, 2): 0, (2, 1): 0, (2, 2): 1} """ coefficients = {} for index in product((1, 2), repeat=2): coefficients[index] = \ self._compute_first_fundamental_form_coefficient(index) return coefficients def first_fundamental_form(self, vector1, vector2): r""" Evaluate the first fundamental form on two vectors expressed with respect to the natural coordinate frame on the surface. In other words, if the vectors are `v = (v^1, v^2)` and `w = (w^1, w^2)`, calculate `g_{11} v^1 w^1 + g_{12}(v^1 w^2 + v^2 w^1) + g_{22} v^2 w^2`, with `g_{ij}` the coefficients of the first fundamental form. INPUT: - ``vector1``, ``vector2`` - vectors on the surface. OUTPUT: - First fundamental form evaluated on the input vectors. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: v1, v2, w1, w2 = var('v1, v2, w1, w2', domain='real') sage: sphere = ParametrizedSurface3D((cos(u)*cos(v), sin(u)*cos(v), sin(v)), (u, v),'sphere') sage: sphere.first_fundamental_form(vector([v1,v2]),vector([w1,w2])) v1*w1*cos(v)^2 + v2*w2 sage: vv = vector([1,2]) sage: sphere.first_fundamental_form(vv,vv) cos(v)^2 + 4 sage: sphere.first_fundamental_form([1,1],[2,1]) 2*cos(v)^2 + 1 """ gamma = self.first_fundamental_form_coefficients() return sum(gamma[(i,j)] * vector1[i - 1] * vector2[j - 1] for i, j in product((1, 2), repeat=2)) def area_form_squared(self): """ Returns the square of the coefficient of the area form on the surface. In terms of the coefficients `g_{ij}` (where `i, j = 1, 2`) of the first fundamental form, this invariant is given by `A^2 = g_{11}g_{22} - g_{12}^2`. See also :meth:`.area_form`. OUTPUT: - Square of the area form EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: sphere = ParametrizedSurface3D([cos(u)*cos(v),sin(u)*cos(v),sin(v)],[u,v],'sphere') sage: sphere.area_form_squared() cos(v)^2 """ gamma = self.first_fundamental_form_coefficients() sq = gamma[(1,1)] * gamma[(2,2)] - gamma[(1,2)]**2 return _simplify_full_rad(sq) def area_form(self): r""" Returns the coefficient of the area form on the surface. In terms of the coefficients `g_{ij}` (where `i, j = 1, 2`) of the first fundamental form, the coefficient of the area form is given by `A = \sqrt{g_{11}g_{22} - g_{12}^2}`. See also :meth:`.area_form_squared`. OUTPUT: - Coefficient of the area form EXAMPLES:: sage: u, v = var('u,v', domain='real') sage: sphere = ParametrizedSurface3D([cos(u)*cos(v),sin(u)*cos(v),sin(v)],[u,v],'sphere') sage: sphere.area_form() cos(v) """ f = abs(sqrt(self.area_form_squared())) return _simplify_full_rad(f) def first_fundamental_form_inverse_coefficients(self): r""" Returns the coefficients `g^{ij}` of the inverse of the fundamental form, as a dictionary. The inverse coefficients are defined by `g^{ij} g_{jk} = \delta^i_k` with `\delta^i_k` the Kronecker delta. OUTPUT: - Dictionary of the inverse coefficients. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: sphere = ParametrizedSurface3D([cos(u)*cos(v),sin(u)*cos(v),sin(v)],[u,v],'sphere') sage: sphere.first_fundamental_form_inverse_coefficients() {(1, 1): cos(v)^(-2), (1, 2): 0, (2, 1): 0, (2, 2): 1} """ g = self.first_fundamental_form_coefficients() D = g[(1,1)] * g[(2,2)] - g[(1,2)]**2 gi11 = _simplify_full_rad(g[(2,2)]/D) gi12 = _simplify_full_rad(-g[(1,2)]/D) gi21 = gi12 gi22 = _simplify_full_rad(g[(1,1)]/D) return {(1,1): gi11, (1,2): gi12, (2,1): gi21, (2,2): gi22} def first_fundamental_form_inverse_coefficient(self, index): r""" Returns a specific component `g^{ij}` of the inverse of the fundamental form. INPUT: - ``index`` - tuple ``(i, j)`` specifying the index of the component `g^{ij}`. OUTPUT: - Component of the inverse of the fundamental form. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: sphere = ParametrizedSurface3D([cos(u)*cos(v),sin(u)*cos(v),sin(v)],[u,v],'sphere') sage: sphere.first_fundamental_form_inverse_coefficient((1, 2)) 0 sage: sphere.first_fundamental_form_inverse_coefficient((1, 1)) cos(v)^(-2) """ index = tuple(sorted(index)) if len(index) == 2 and all(i == 1 or i == 2 for i in index): return self.first_fundamental_form_inverse_coefficients()[index] else: raise ValueError("Index %s out of bounds." % str(index)) @cached_method def rotation(self,theta): r""" Gives the matrix of the rotation operator over a given angle `\theta` with respect to the natural frame. INPUT: - ``theta`` - rotation angle OUTPUT: - Rotation matrix with respect to the natural frame. ALGORITHM: The operator of rotation over `\pi/2` is `J^i_j = g^{ik}\omega_{jk}`, where `\omega` is the area form. The operator of rotation over an angle `\theta` is `\cos(\theta) I + \sin(\theta) J`. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: assume(cos(v)>0) sage: sphere = ParametrizedSurface3D([cos(u)*cos(v),sin(u)*cos(v),sin(v)],[u,v],'sphere') We first compute the matrix of rotation over `\pi/3`:: sage: rotation = sphere.rotation(pi/3); rotation [ 1/2 -1/2*sqrt(3)/cos(v)] [ 1/2*sqrt(3)*cos(v) 1/2] We verify that three successive rotations over `\pi/3` yield minus the identity:: sage: rotation^3 [-1 0] [ 0 -1] """ from sage.functions.trig import sin, cos gi = self.first_fundamental_form_inverse_coefficients() w12 = self.area_form() R11 = (cos(theta) + sin(theta)*gi[1,2]*w12).simplify_full() R12 = (- sin(theta)*gi[1,1]*w12).simplify_full() R21 = (sin(theta)*gi[2,2]*w12).simplify_full() R22 = (cos(theta) - sin(theta)*gi[2,1]*w12).simplify_full() return matrix([[R11,R12],[R21,R22]]) @cached_method def orthonormal_frame(self, coordinates='ext'): r""" Returns the orthonormal frame field on the surface, expressed either in exterior coordinates (i.e. expressed as vector fields in the ambient space `\mathbb{R}^3`, the default) or interior coordinates (with respect to the natural frame) INPUT: - ``coordinates`` - either ``ext`` (default) or ``int``. OUTPUT: - Orthogonal frame field as a dictionary. ALGORITHM: We normalize the first vector `\vec e_1` of the natural frame and then get the second frame vector as `\vec e_2 = [\vec n, \vec e_1]`, where `\vec n` is the unit normal to the surface. EXAMPLES:: sage: u, v = var('u,v', domain='real') sage: assume(cos(v)>0) sage: sphere = ParametrizedSurface3D([cos(u)*cos(v), sin(u)*cos(v), sin(v)], [u, v],'sphere') sage: frame = sphere.orthonormal_frame(); frame {1: (-sin(u), cos(u), 0), 2: (-cos(u)*sin(v), -sin(u)*sin(v), cos(v))} sage: (frame[1]*frame[1]).simplify_full() 1 sage: (frame[1]*frame[2]).simplify_full() 0 sage: frame[1] == sphere.orthonormal_frame_vector(1) True We compute the orthonormal frame with respect to the natural frame on the surface:: sage: frame_int = sphere.orthonormal_frame(coordinates='int'); frame_int {1: (1/cos(v), 0), 2: (0, 1)} sage: sphere.first_fundamental_form(frame_int[1], frame_int[1]) 1 sage: sphere.first_fundamental_form(frame_int[1], frame_int[2]) 0 sage: sphere.first_fundamental_form(frame_int[2], frame_int[2]) 1 """ from sage.symbolic.constants import pi if coordinates not in ['ext', 'int']: raise ValueError("Coordinate system must be exterior ('ext') " "or interior ('int').") c = self.first_fundamental_form_coefficient([1,1]) if coordinates == 'ext': f1 = self.natural_frame()[1] E1 = _simplify_full_rad(f1/sqrt(c)) E2 = _simplify_full_rad( self.normal_vector(normalized=True).cross_product(E1)) else: E1 = vector([_simplify_full_rad(1/sqrt(c)), 0]) E2 = (self.rotation(pi/2)*E1).simplify_full() return {1:E1, 2:E2} def orthonormal_frame_vector(self, index, coordinates='ext'): r""" Returns a specific basis vector field of the orthonormal frame field on the surface, expressed in exterior or interior coordinates. See :meth:`orthogonal_frame` for more details. INPUT: - ``index`` - index of the basis vector; - ``coordinates`` - either ``ext`` (default) or ``int``. OUTPUT: - Orthonormal frame vector field. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: assume(cos(v)>0) sage: sphere = ParametrizedSurface3D([cos(u)*cos(v),sin(u)*cos(v),sin(v)],[u,v],'sphere') sage: V1 = sphere.orthonormal_frame_vector(1); V1 (-sin(u), cos(u), 0) sage: V2 = sphere.orthonormal_frame_vector(2); V2 (-cos(u)*sin(v), -sin(u)*sin(v), cos(v)) sage: (V1*V1).simplify_full() 1 sage: (V1*V2).simplify_full() 0 sage: n = sphere.normal_vector(normalized=True) sage: (V1.cross_product(V2) - n).simplify_full() (0, 0, 0) """ return self.orthonormal_frame(coordinates)[index] def lie_bracket(self, v, w): r""" Returns the Lie bracket of two vector fields that are tangent to the surface. The vector fields should be given in intrinsic coordinates, i.e. with respect to the natural frame. INPUT: - ``v`` and ``w`` - vector fields on the surface, expressed as pairs of functions or as vectors of length 2. OUTPUT: - The Lie bracket `[v, w]`. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: assume(cos(v)>0) sage: sphere = ParametrizedSurface3D([cos(u)*cos(v),sin(u)*cos(v),sin(v)],[u,v],'sphere') sage: sphere.lie_bracket([u,v],[-v,u]) (0, 0) sage: EE_int = sphere.orthonormal_frame(coordinates='int') sage: sphere.lie_bracket(EE_int[1],EE_int[2]) (sin(v)/cos(v)^2, 0) """ v = vector(SR, v) w = vector(SR, w) variables = self.variables_list Dv = matrix([[_simplify_full_rad(diff(component, u)) for u in variables] for component in v]) Dw = matrix([[_simplify_full_rad(diff(component, u)) for u in variables] for component in w]) return vector(Dv*w - Dw*v).simplify_full() def frame_structure_functions(self, e1, e2): r""" Returns the structure functions `c^k_{ij}` for a frame field `e_1, e_2`, i.e. a pair of vector fields on the surface which are linearly independent at each point. The structure functions are defined using the Lie bracket by `[e_i,e_j] = c^k_{ij}e_k`. INPUT: - ``e1``, ``e2`` - vector fields in intrinsic coordinates on the surface, expressed as pairs of functions, or as vectors of length 2. OUTPUT: - Dictionary of structure functions, where the key ``(i, j, k)`` refers to the structure function `c_{i,j}^k`. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: assume(cos(v) > 0) sage: sphere = ParametrizedSurface3D([cos(u)*cos(v), sin(u)*cos(v), sin(v)], [u, v], 'sphere') sage: sphere.frame_structure_functions([u, v], [-v, u]) {(1, 1, 1): 0, (1, 1, 2): 0, (1, 2, 1): 0, (1, 2, 2): 0, (2, 1, 1): 0, (2, 1, 2): 0, (2, 2, 1): 0, (2, 2, 2): 0} We construct the structure functions of the orthonormal frame on the surface:: sage: EE_int = sphere.orthonormal_frame(coordinates='int') sage: CC = sphere.frame_structure_functions(EE_int[1],EE_int[2]); CC {(1, 1, 1): 0, (1, 1, 2): 0, (1, 2, 1): sin(v)/cos(v), (1, 2, 2): 0, (2, 1, 1): -sin(v)/cos(v), (2, 1, 2): 0, (2, 2, 1): 0, (2, 2, 2): 0} sage: sphere.lie_bracket(EE_int[1],EE_int[2]) - CC[(1,2,1)]*EE_int[1] - CC[(1,2,2)]*EE_int[2] (0, 0) """ e1 = vector(SR, e1) e2 = vector(SR, e2) lie_bracket = self.lie_bracket(e1, e2).simplify_full() transformation = matrix(SR, [e1, e2]).transpose() w = (transformation.inverse()*lie_bracket).simplify_full() return {(1,1,1): 0, (1,1,2): 0, (1,2,1): w[0], (1,2,2): w[1], (2,1,1): -w[0], (2,1,2): -w[1], (2,2,1): 0, (2,2,2): 0} @cached_method def _compute_second_order_frame_element(self, index): """ Compute an element of the second order frame of the surface. See :meth:`second_order_natural_frame` for more details. This method expects its arguments in tuple form for caching. As it does no input checking, it should not be called directly. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: paraboloid = ParametrizedSurface3D([u, v, u^2 + v^2], [u,v], 'paraboloid') sage: paraboloid._compute_second_order_frame_element((1, 2)) (0, 0, 0) sage: paraboloid._compute_second_order_frame_element((2, 2)) (0, 0, 2) """ variables = [self.variables[i] for i in index] ddr_element = vector([_simplify_full_rad(diff(f, variables)) for f in self.equation]) return ddr_element def second_order_natural_frame(self): r""" Returns the second-order frame of the surface, i.e. computes the second-order derivatives (with respect to the parameters on the surface) of the parametric expression `\vec r = \vec r(u^1,u^2)` of the surface. OUTPUT: - Dictionary where the keys are 2-tuples ``(i, j)`` and the values are the corresponding derivatives `r_{ij}`. EXAMPLES: We compute the second-order natural frame of the sphere:: sage: u, v = var('u, v', domain='real') sage: sphere = ParametrizedSurface3D([cos(u)*cos(v),sin(u)*cos(v),sin(v)],[u,v],'sphere') sage: sphere.second_order_natural_frame() {(1, 1): (-cos(u)*cos(v), -cos(v)*sin(u), 0), (1, 2): (sin(u)*sin(v), -cos(u)*sin(v), 0), (2, 1): (sin(u)*sin(v), -cos(u)*sin(v), 0), (2, 2): (-cos(u)*cos(v), -cos(v)*sin(u), -sin(v))} """ vectors = {} for index in product((1, 2), repeat=2): sorted_index = tuple(sorted(index)) vectors[index] = \ self._compute_second_order_frame_element(sorted_index) return vectors def second_order_natural_frame_element(self, index): r""" Returns a vector in the second-order frame of the surface, i.e. computes the second-order derivatives of the parametric expression `\vec{r}` of the surface with respect to the parameters listed in the argument. INPUT: - ``index`` - a 2-tuple ``(i, j)`` specifying the element of the second-order frame. OUTPUT: - The second-order derivative `r_{ij}`. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: sphere = ParametrizedSurface3D([cos(u)*cos(v),sin(u)*cos(v),sin(v)],[u,v],'sphere') sage: sphere.second_order_natural_frame_element((1, 2)) (sin(u)*sin(v), -cos(u)*sin(v), 0) """ index = tuple(sorted(index)) if len(index) == 2 and all(i == 1 or i == 2 for i in index): return self._compute_second_order_frame_element(index) else: raise ValueError("Index %s out of bounds." % str(index)) @cached_method def _compute_second_fundamental_form_coefficient(self, index): """ Compute a coefficient of the second fundamental form of the surface. See ``second_fundamental_form_coefficient`` for more details. This method expects its arguments in tuple form for caching. As it does no input checking, it should not be called directly. EXAMPLES:: sage: u, v = var('u,v', domain='real') sage: paraboloid = ParametrizedSurface3D([u, v, u^2+v^2], [u, v], 'paraboloid') sage: paraboloid._compute_second_fundamental_form_coefficient((1,1)) 2/sqrt(4*u^2 + 4*v^2 + 1) """ N = self.normal_vector(normalized=True) v = self.second_order_natural_frame_element(index) return _simplify_full_rad(v*N) def second_fundamental_form_coefficient(self, index): r""" Returns the coefficient `h_{ij}` of the second fundamental form corresponding to the index `(i, j)`. If the equation of the surface is `\vec{r}(u^1, u^2)`, then `h_{ij} = \vec{r}_{u^i u^j} \cdot \vec{n}`, where `\vec{n}` is the unit normal. INPUT: - ``index`` - a 2-tuple ``(i, j)`` OUTPUT: - Component `h_{ij}` of the second fundamental form. EXAMPLES:: sage: u, v = var('u,v', domain='real') sage: assume(cos(v)>0) sage: sphere = ParametrizedSurface3D([cos(u)*cos(v),sin(u)*cos(v),sin(v)],[u,v],'sphere') sage: sphere.second_fundamental_form_coefficient((1, 1)) -cos(v)^2 sage: sphere.second_fundamental_form_coefficient((2, 1)) 0 """ index = tuple(index) if len(index) == 2 and all(i == 1 or i == 2 for i in index): return self._compute_second_fundamental_form_coefficient(index) else: raise ValueError("Index %s out of bounds." % str(index)) def second_fundamental_form_coefficients(self): """ Returns the coefficients `h_{ij}` of the second fundamental form as a dictionary, where the keys are the indices `(i, j)` and the values are the corresponding components `h_{ij}`. When only one component is needed, consider instead the function :meth:`second_fundamental_form_coefficient`. OUTPUT: Dictionary of second fundamental form coefficients. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: assume(cos(v)>0) sage: sphere = ParametrizedSurface3D([cos(u)*cos(v),sin(u)*cos(v),sin(v)],[u,v],'sphere') sage: sphere.second_fundamental_form_coefficients() {(1, 1): -cos(v)^2, (1, 2): 0, (2, 1): 0, (2, 2): -1} """ coefficients = {} for index in product((1, 2), repeat=2): coefficients[index] = \ self._compute_second_fundamental_form_coefficient(index) return coefficients def second_fundamental_form(self,vector1,vector2): r""" Evaluates the second fundamental form on two vectors on the surface. If the vectors are given by `v=(v^1,v^2)` and `w=(w^1,w^2)`, the result of this function is `h_{11} v^1 w^1 + h_{12}(v^1 w^2 + v^2 w^1) + h_{22} v^2 w^2`. INPUT: - ``vector1``, ``vector2`` - 2-tuples representing the input vectors. OUTPUT: - Value of the second fundamental form evaluated on the given vectors. EXAMPLES: We evaluate the second fundamental form on two symbolic vectors:: sage: u, v = var('u, v', domain='real') sage: v1, v2, w1, w2 = var('v1, v2, w1, w2', domain='real') sage: assume(cos(v) > 0) sage: sphere = ParametrizedSurface3D([cos(u)*cos(v),sin(u)*cos(v),sin(v)],[u,v],'sphere') sage: sphere.second_fundamental_form(vector([v1, v2]), vector([w1, w2])) -v1*w1*cos(v)^2 - v2*w2 We evaluate the second fundamental form on vectors with numerical components:: sage: vect = vector([1,2]) sage: sphere.second_fundamental_form(vect, vect) -cos(v)^2 - 4 sage: sphere.second_fundamental_form([1,1], [2,1]) -2*cos(v)^2 - 1 """ hh = self.second_fundamental_form_coefficients() return sum(hh[(i, j)] * vector1[i - 1] * vector2[j - 1] for (i, j) in product((1, 2), repeat=2)) def gauss_curvature(self): r""" Finds the gaussian curvature of the surface, given by `K = \frac{h_{11}h_{22} - h_{12}^2}{g_{11}g_{22} - g_{12}^2}`, where `g_{ij}` and `h_{ij}` are the coefficients of the first and second fundamental form, respectively. OUTPUT: - Gaussian curvature of the surface. EXAMPLES:: sage: R = var('R') sage: assume(R>0) sage: u, v = var('u,v', domain='real') sage: assume(cos(v)>0) sage: sphere = ParametrizedSurface3D([R*cos(u)*cos(v),R*sin(u)*cos(v),R*sin(v)],[u,v],'sphere') sage: sphere.gauss_curvature() R^(-2) """ hh = self.second_fundamental_form_coefficients() return _simplify_full_rad( (hh[(1,1)] * hh[(2,2)] - hh[(1,2)]**2)/self.area_form_squared()) def mean_curvature(self): r""" Finds the mean curvature of the surface, given by `H = \frac{1}{2}\frac{g_{22}h_{11} - 2g_{12}h_{12} + g_{11}h_{22}}{g_{11}g_{22} - g_{12}^2}`, where `g_{ij}` and `h_{ij}` are the components of the first and second fundamental forms, respectively. OUTPUT: - Mean curvature of the surface EXAMPLES:: sage: R = var('R') sage: assume(R>0) sage: u, v = var('u,v', domain='real') sage: assume(cos(v)>0) sage: sphere = ParametrizedSurface3D([R*cos(u)*cos(v),R*sin(u)*cos(v),R*sin(v)],[u,v],'sphere') sage: sphere.mean_curvature() -1/R """ gg = self.first_fundamental_form_coefficients() hh = self.second_fundamental_form_coefficients() denom = 2*self.area_form_squared() numer = (gg[(2,2)]*hh[(1,1)] - 2*gg[(1,2)]*hh[(1,2)] + gg[(1,1)]*hh[(2,2)]).simplify_full() return _simplify_full_rad(numer/denom) @cached_method def shape_operator_coefficients(self): r""" Returns the components of the shape operator of the surface as a dictionary. See ``shape_operator`` for more information. OUTPUT: - Dictionary where the keys are two-tuples ``(i, j)``, with values the corresponding component of the shape operator. EXAMPLES:: sage: R = var('R') sage: u, v = var('u,v', domain='real') sage: assume(cos(v)>0) sage: sphere = ParametrizedSurface3D([R*cos(u)*cos(v),R*sin(u)*cos(v),R*sin(v)],[u,v],'sphere') sage: sphere.shape_operator_coefficients() {(1, 1): -1/R, (1, 2): 0, (2, 1): 0, (2, 2): -1/R} """ gi = self.first_fundamental_form_inverse_coefficients() hh = self.second_fundamental_form_coefficients() sh_op11 = _simplify_full_rad(gi[(1,1)]*hh[(1,1)] + gi[(1,2)]*hh[(1,2)]) sh_op12 = _simplify_full_rad(gi[(1,1)]*hh[(2,1)] + gi[(1,2)]*hh[(2,2)]) sh_op21 = _simplify_full_rad(gi[(2,1)]*hh[(1,1)] + gi[(2,2)]*hh[(1,2)]) sh_op22 = _simplify_full_rad(gi[(2,1)]*hh[(2,1)] + gi[(2,2)]*hh[(2,2)]) return {(1,1): sh_op11, (1,2): sh_op12, (2,1): sh_op21, (2,2): sh_op22} def shape_operator(self): r""" Returns the shape operator of the surface as a matrix. The shape operator is defined as the derivative of the Gauss map, and is computed here in terms of the first and second fundamental form by means of the Weingarten equations. OUTPUT: - Matrix of the shape operator EXAMPLES:: sage: R = var('R') sage: assume(R>0) sage: u, v = var('u,v', domain='real') sage: assume(cos(v)>0) sage: sphere = ParametrizedSurface3D([R*cos(u)*cos(v),R*sin(u)*cos(v),R*sin(v)],[u,v],'sphere') sage: S = sphere.shape_operator(); S [-1/R 0] [ 0 -1/R] The eigenvalues of the shape operator are the principal curvatures of the surface:: sage: u, v = var('u,v', domain='real') sage: paraboloid = ParametrizedSurface3D([u, v, u^2+v^2], [u, v], 'paraboloid') sage: S = paraboloid.shape_operator(); S [2*(4*v^2 + 1)/(4*u^2 + 4*v^2 + 1)^(3/2) -8*u*v/(4*u^2 + 4*v^2 + 1)^(3/2)] [ -8*u*v/(4*u^2 + 4*v^2 + 1)^(3/2) 2*(4*u^2 + 1)/(4*u^2 + 4*v^2 + 1)^(3/2)] sage: S.eigenvalues() [2*sqrt(4*u^2 + 4*v^2 + 1)/(16*u^4 + 16*v^4 + 8*(4*u^2 + 1)*v^2 + 8*u^2 + 1), 2/sqrt(4*u^2 + 4*v^2 + 1)] """ shop = self.shape_operator_coefficients() shop_matrix=matrix([[shop[(1,1)],shop[(1,2)]], [shop[(2,1)],shop[(2,2)]]]) return shop_matrix def principal_directions(self): r""" Finds the principal curvatures and principal directions of the surface OUTPUT: For each principal curvature, returns a list of the form `(\rho, V, n)`, where `\rho` is the principal curvature, `V` is the corresponding principal direction, and `n` is the multiplicity. EXAMPLES:: sage: u, v = var('u, v', domain='real') sage: R, r = var('R,r', domain='real') sage: assume(R>r,r>0) sage: torus = ParametrizedSurface3D([(R+r*cos(v))*cos(u),(R+r*cos(v))*sin(u),r*sin(v)],[u,v],'torus') sage: torus.principal_directions() [(-cos(v)/(r*cos(v) + R), [(1, 0)], 1), (-1/r, [(0, 1)], 1)] :: sage: u, v = var('u, v', domain='real') sage: V = vector([u*cos(u+v), u*sin(u+v), u+v]) sage: helicoid = ParametrizedSurface3D(V, (u, v)) sage: helicoid.principal_directions() [(-1/(u^2 + 1), [(1, -(u^2 - sqrt(u^2 + 1) + 1)/(u^2 + 1))], 1), (1/(u^2 + 1), [(1, -(u^2 + sqrt(u^2 + 1) + 1)/(u^2 + 1))], 1)] """ return self.shape_operator().eigenvectors_right() @cached_method def connection_coefficients(self): r""" Computes the connection coefficients or Christoffel symbols `\Gamma^k_{ij}` of the surface. If the coefficients of the first fundamental form are given by `g_{ij}` (where `i, j = 1, 2`), then `\Gamma^k_{ij} = \frac{1}{2} g^{kl} \left( \frac{\partial g_{li}}{\partial x^j} - \frac{\partial g_{ij}}{\partial x^l} + \frac{\partial g_{lj}}{\partial x^i} \right)`. Here, `(g^{kl})` is the inverse of the matrix `(g_{ij})`, with `i, j = 1, 2`. OUTPUT: Dictionary of connection coefficients, where the keys are 3-tuples `(i,j,k)` and the values are the corresponding coefficients `\Gamma^k_{ij}`. EXAMPLES:: sage: r = var('r') sage: assume(r > 0) sage: u, v = var('u,v', domain='real') sage: assume(cos(v)>0) sage: sphere = ParametrizedSurface3D([r*cos(u)*cos(v),r*sin(u)*cos(v),r*sin(v)],[u,v],'sphere') sage: sphere.connection_coefficients() {(1, 1, 1): 0, (1, 1, 2): cos(v)*sin(v), (1, 2, 1): -sin(v)/cos(v), (1, 2, 2): 0, (2, 1, 1): -sin(v)/cos(v), (2, 1, 2): 0, (2, 2, 1): 0, (2, 2, 2): 0} """ x = self.variables gg = self.first_fundamental_form_coefficients() gi = self.first_fundamental_form_inverse_coefficients() dg = {} for i,j,k in product((1, 2), repeat=3): dg[(i,j,k)] = _simplify_full_rad(gg[(j,k)].differentiate(x[i])) structfun={} for i,j,k in product((1, 2), repeat=3): structfun[(i,j,k)] = sum(gi[(k,s)]*(dg[(i,j,s)] + dg[(j,i,s)] -dg[(s,i,j)])/2 for s in (1,2)) structfun[(i,j,k)] = _simplify_full_rad(structfun[(i,j,k)]) return structfun @cached_method def _create_geodesic_ode_system(self): r""" Helper method to create a fast floating-point version of the geodesic equations, used by :meth:`geodesics_numerical`. EXAMPLES:: sage: p, q = var('p,q', domain='real') sage: sphere = ParametrizedSurface3D([cos(q)*cos(p),sin(q)*cos(p),sin(p)],[p,q],'sphere') sage: ode = sphere._create_geodesic_ode_system() sage: ode.function(0.0, (1.0, 0.0, 1.0, 1.0)) [1.00000000000000, 1.00000000000000, -0.4546487134128409, 3.114815449309804] """ from sage.ext.fast_eval import fast_float from sage.calculus.ode import ode_solver u1 = self.variables[1] u2 = self.variables[2] C = self.connection_coefficients() with SR.temp_var(domain='real') as v1: with SR.temp_var(domain='real') as v2: dv1 = - C[(1,1,1)]*v1**2 - 2*C[(1,2,1)]*v1*v2 - C[(2,2,1)]*v2**2 dv2 = - C[(1,1,2)]*v1**2 - 2*C[(1,2,2)]*v1*v2 - C[(2,2,2)]*v2**2 fun1 = fast_float(dv1, str(u1), str(u2), str(v1), str(v2)) fun2 = fast_float(dv2, str(u1), str(u2), str(v1), str(v2)) geodesic_ode = ode_solver() geodesic_ode.function = ( lambda t, u1_u2_v1_v2: [u1_u2_v1_v2[2], u1_u2_v1_v2[3], fun1(*u1_u2_v1_v2), fun2(*u1_u2_v1_v2)]) return geodesic_ode def geodesics_numerical(self, p0, v0, tinterval): r""" Numerical integration of the geodesic equations. Explicitly, the geodesic equations are given by `\frac{d^2 u^i}{dt^2} + \Gamma^i_{jk} \frac{d u^j}{dt} \frac{d u^k}{dt} = 0`. Solving these equations gives the coordinates `(u^1, u^2)` of the geodesic on the surface. The coordinates in space can then be found by substituting `(u^1, u^2)` into the vector `\vec{r}(u^1, u^2)` representing the surface. ALGORITHM: The geodesic equations are integrated forward in time using the ode solvers from ``sage.calculus.ode``. See the member function ``_create_geodesic_ode_system`` for more details. INPUT: - ``p0`` - 2-tuple with coordinates of the initial point. - ``v0`` - 2-tuple with components of the initial tangent vector to the geodesic. - ``tinterval`` - List ``[a, b, M]``, where ``(a,b)`` is the domain of the geodesic and ``M`` is the number of subdivision points used when returning the solution. OUTPUT: List of lists ``[t, [u1(t), u2(t)], [v1(t), v2(t)], [x1(t), x2(t), x3(t)]]``, where - ``t`` is a subdivision point; - ``[u1(t), u2(t)]`` are the intrinsic coordinates of the geodesic point; - ``[v1(t), v2(t)]`` are the intrinsic coordinates of the tangent vector to the geodesic; - ``[x1(t), x2(t), x3(t)]`` are the coordinates of the geodesic point in the three-dimensional space. EXAMPLES:: sage: p, q = var('p,q', domain='real') sage: assume(cos(q)>0) sage: sphere = ParametrizedSurface3D([cos(q)*cos(p),sin(q)*cos(p),sin(p)],[p,q],'sphere') sage: geodesic = sphere.geodesics_numerical([0.0,0.0],[1.0,1.0],[0,2*pi,5]) sage: times, points, tangent_vectors, ext_points = zip(*geodesic) sage: round4 = lambda vec: [N(x, digits=4) for x in vec] # helper function to round to 4 digits sage: round4(times) [0.0000, 1.257, 2.513, 3.770, 5.027, 6.283] sage: [round4(p) for p in points] [[0.0000, 0.0000], [0.7644, 1.859], [-0.2876, 3.442], [-0.6137, 5.502], [0.5464, 6.937], [0.3714, 9.025]] sage: [round4(p) for p in ext_points] [[1.000, 0.0000, 0.0000], [-0.2049, 0.6921, 0.6921], [-0.9160, -0.2836, -0.2836], [0.5803, -0.5759, -0.5759], [0.6782, 0.5196, 0.5196], [-0.8582, 0.3629, 0.3629]] """ solver = self._create_geodesic_ode_system() t_interval, n = tinterval[0:2], tinterval[2] solver.y_0 = [p0[0], p0[1], v0[0], v0[1]] solver.ode_solve(t_span=t_interval, num_points=n) parsed_solution = \ [[vec[0], vec[1][0:2], vec[1][2:], self.point(vec[1])] for vec in solver.solution] return parsed_solution @cached_method def _create_pt_ode_system(self, curve, t): """ Helper method to create a fast floating-point version of the parallel transport equations, used by ``parallel_translation_numerical``. INPUT: - ``curve`` - curve in intrinsic coordinates along which to do parallel transport. - ``t`` - curve parameter EXAMPLES:: sage: p, q = var('p,q', domain='real') sage: sphere = ParametrizedSurface3D([cos(q)*cos(p),sin(q)*cos(p),sin(p)],[p,q],'sphere') sage: s = var('s') sage: ode = sphere._create_pt_ode_system((s, s), s) sage: ode.function(0.0, (1.0, 1.0)) [-0.0, 0.0] """ from sage.ext.fast_eval import fast_float from sage.calculus.ode import ode_solver u1 = self.variables[1] u2 = self.variables[2] du1 = diff(curve[0], t) du2 = diff(curve[1], t) C = self.connection_coefficients() for coef in C: C[coef] = C[coef].subs({u1: curve[0], u2: curve[1]}) with SR.temp_var(domain='real') as v1: with SR.temp_var(domain='real') as v2: dv1 = - C[(1,1,1)]*v1*du1 - C[(1,2,1)]*(du1*v2 + du2*v1) - \ C[(2,2,1)]*du2*v2 dv2 = - C[(1,1,2)]*v1*du1 - C[(1,2,2)]*(du1*v2 + du2*v1) - \ C[(2,2,2)]*du2*v2 fun1 = fast_float(dv1, str(t), str(v1), str(v2)) fun2 = fast_float(dv2, str(t), str(v1), str(v2)) pt_ode = ode_solver() pt_ode.function = lambda t, v1_v2: [fun1(t, v1_v2[0], v1_v2[1]), fun2(t, v1_v2[0], v1_v2[1])] return pt_ode def parallel_translation_numerical(self,curve,t,v0,tinterval): r""" Numerically solves the equations for parallel translation of a vector along a curve on the surface. Explicitly, the equations for parallel translation are given by `\frac{d u^i}{dt} + u^j \frac{d c^k}{dt} \Gamma^i_{jk} = 0`, where `\Gamma^i_{jk}` are the connection coefficients of the surface, the vector to be transported has components `u^j` and the curve along which to transport has components `c^k`. ALGORITHM: The parallel transport equations are integrated forward in time using the ode solvers from ``sage.calculus.ode``. See :meth:`_create_pt_ode_system` for more details. INPUT: - ``curve`` - 2-tuple of functions which determine the curve with respect to the local coordinate system; - ``t`` - symbolic variable denoting the curve parameter; - ``v0`` - 2-tuple representing the initial vector; - ``tinterval`` - list ``[a, b, N]``, where ``(a, b)`` is the domain of the curve and ``N`` is the number of subdivision points. OUTPUT: The list consisting of lists ``[t, [v1(t), v2(t)]]``, where - ``t`` is a subdivision point; - ``[v1(t), v2(t)]`` is the list of coordinates of the vector parallel translated along the curve. EXAMPLES:: sage: p, q = var('p,q', domain='real') sage: v = [p,q] sage: assume(cos(q)>0) sage: sphere = ParametrizedSurface3D([cos(q)*cos(p),sin(q)*cos(p),sin(p)],v,'sphere') sage: s = var('s') sage: vector_field = sphere.parallel_translation_numerical([s,s],s,[1.0,1.0],[0.0, pi/4, 5]) sage: times, components = zip(*vector_field) sage: round4 = lambda vec: [N(x, digits=4) for x in vec] # helper function to round to 4 digits sage: round4(times) [0.0000, 0.1571, 0.3142, 0.4712, 0.6283, 0.7854] sage: [round4(v) for v in components] [[1.000, 1.000], [0.9876, 1.025], [0.9499, 1.102], [0.8853, 1.238], [0.7920, 1.448], [0.6687, 1.762]] """ solver = self._create_pt_ode_system(tuple(curve), t) t_interval, n = tinterval[0:2], tinterval[2] solver.y_0 = v0 solver.ode_solve(t_span=t_interval, num_points=n) return solver.solution
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/geometry/riemannian_manifolds/parametrized_surface3d.py
0.917284
0.657982
parametrized_surface3d.py
pypi
r""" Base class for mutable polyhedra. Just like vectors and matrices they can be set immutable. The constructor does this by default. """ from sage.misc.abstract_method import abstract_method from .base import Polyhedron_base class Polyhedron_mutable(Polyhedron_base): """ Base class for polyhedra that allow mutability. This should not be used directly. """ def __hash__(self): r""" TESTS:: sage: p = Polyhedron([[1, 1]], mutable=True) sage: set([p]) Traceback (most recent call last): ... TypeError: mutable polyhedra are unhashable sage: p.set_immutable() sage: set([p]) {A 0-dimensional polyhedron in ZZ^2 defined as the convex hull of 1 vertex} """ if self._is_mutable: raise TypeError("mutable polyhedra are unhashable") return Polyhedron_base.__hash__(self) def _clear_cache(self): r""" Clear the Vrepresentation and Hrepresentation data of ``self``. TESTS:: sage: p = polytopes.permutahedron(4) sage: P = p.parent() sage: q = P._element_constructor_(p, mutable=True) sage: TestSuite(q).run() sage: q._clear_cache() sage: TestSuite(q).run() :: sage: q.set_immutable() sage: q._clear_cache() Traceback (most recent call last): ... TypeError: cannot clear cache of immutable polyhedra """ if not self._is_mutable: raise TypeError("cannot clear cache of immutable polyhedra") # Invalidate object pointing towards this polyhedron (faces etc.). for ob in self._dependent_objects: ob._polyhedron = None backend_object = self.__dict__["_" + self._backend_object_name] del self.__dict__ self.__dict__["_" + self._backend_object_name] = backend_object self._is_mutable = True self._dependent_objects = [] def _add_dependent_object(self, ob): r""" Add an object that has ``self`` has attribute ``_polyhedron``. When ``self`` is modified, we delete this attribute to invalidate those objects. EXAMPLES:: sage: p = Polyhedron([[1, 1]], mutable=True) sage: class foo: ....: def __init__(self, p): ....: self._polyhedron = p ....: sage: a = foo(p) sage: a.__dict__ {'_polyhedron': A 0-dimensional polyhedron in ZZ^2 defined as the convex hull of 1 vertex} sage: p._add_dependent_object(a) sage: p._clear_cache() sage: a.__dict__ {'_polyhedron': None} TESTS:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: p = Polyhedron([[1, 1]], mutable=True) sage: n = NewtonPolygon(p) sage: n Finite Newton polygon with 1 vertex: (1, 1) sage: n = NewtonPolygon(p) sage: p._clear_cache() sage: n <repr(<sage.geometry.newton_polygon.ParentNewtonPolygon_with_category.element_class at ...>) failed: AttributeError: 'NoneType' object has no attribute 'vertices'> :: sage: f = p.faces(0)[0]; f A 0-dimensional face of a Polyhedron in ZZ^2 defined as the convex hull of 1 vertex sage: p._clear_cache() sage: f <repr(<sage.geometry.polyhedron.face.PolyhedronFace at ...>) failed: AttributeError: 'NoneType' object has no attribute 'parent'> :: sage: v = p.vertices()[0] sage: p = Polyhedron([[1, 1]], mutable=True) sage: v = p.Vrepresentation(0); v A vertex at (1, 1) sage: h = p.Hrepresentation(0); h An equation (0, 1) x - 1 == 0 sage: p._clear_cache() sage: v.polyhedron() is None True sage: h.polyhedron() is None True :: sage: p = Polyhedron([[1, 0], [0, 1]], mutable=True) sage: r = p.relative_interior() sage: p._clear_cache() sage: r Relative interior of None """ if ob._polyhedron is not self: raise ValueError self._dependent_objects.append(ob) def is_mutable(self): r""" Return True if the polyhedron is mutable, i.e. it can be modified in place. EXAMPLES:: sage: p = Polyhedron([[1, 1]], mutable=True) sage: p.is_mutable() True sage: p = Polyhedron([[1, 1]], mutable=False) sage: p.is_mutable() False """ return self._is_mutable def is_immutable(self): r""" Return True if the polyhedron is immutable, i.e. it cannot be modified in place. EXAMPLES:: sage: p = Polyhedron([[1, 1]], mutable=True) sage: p.is_immutable() False sage: p = Polyhedron([[1, 1]], mutable=False) sage: p.is_immutable() True """ return not self._is_mutable @abstract_method def set_immutable(self): r""" Make this polyhedron immutable. This operation cannot be undone. TESTS:: sage: from sage.geometry.polyhedron.base_mutable import Polyhedron_mutable sage: p = polytopes.cube() sage: Polyhedron_mutable.set_immutable(p) Traceback (most recent call last): ... TypeError: 'AbstractMethod' object is not callable """ @abstract_method def Vrepresentation(self): r""" A derived class must overwrite such that it restores Vrepresentation after clearing it. TESTS:: sage: from sage.geometry.polyhedron.base_mutable import Polyhedron_mutable sage: p = polytopes.cube() sage: Polyhedron_mutable.Vrepresentation(p) Traceback (most recent call last): ... TypeError: 'AbstractMethod' object is not callable """ # A derived class must implemented it to recalculate, if necessary. @abstract_method def Hrepresentation(self): r""" A derived class must overwrite such that it restores Hrepresentation after clearing it. TESTS:: sage: from sage.geometry.polyhedron.base_mutable import Polyhedron_mutable sage: p = polytopes.cube() sage: Polyhedron_mutable.Hrepresentation(p) Traceback (most recent call last): ... TypeError: 'AbstractMethod' object is not callable """ # A derived class must implemented it to recalculate, if necessary.
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/geometry/polyhedron/base_mutable.py
0.889283
0.547404
base_mutable.py
pypi
from .base import Polyhedron_base class Polyhedron_field(Polyhedron_base): """ Polyhedra over all fields supported by Sage INPUT: - ``Vrep`` -- a list ``[vertices, rays, lines]`` or ``None``. - ``Hrep`` -- a list ``[ieqs, eqns]`` or ``None``. EXAMPLES:: sage: p = Polyhedron(vertices=[(0,0),(AA(2).sqrt(),0),(0,AA(3).sqrt())], # optional - sage.rings.number_field ....: rays=[(1,1)], lines=[], backend='field', base_ring=AA) sage: TestSuite(p).run() # optional - sage.rings.number_field TESTS:: sage: K.<sqrt3> = QuadraticField(3) # optional - sage.rings.number_field sage: p = Polyhedron([(0,0), (1,0), (1/2, sqrt3/2)]) # optional - sage.rings.number_field sage: TestSuite(p).run() # optional - sage.rings.number_field Check that :trac:`19013` is fixed:: sage: K.<phi> = NumberField(x^2-x-1, embedding=1.618) # optional - sage.rings.number_field sage: P1 = Polyhedron([[0,1],[1,1],[1,-phi+1]]) # optional - sage.rings.number_field sage: P2 = Polyhedron(ieqs=[[-1,-phi,0]]) # optional - sage.rings.number_field sage: P1.intersection(P2) # optional - sage.rings.number_field The empty polyhedron in (Number Field in phi with defining polynomial x^2 - x - 1 with phi = 1.618033988749895?)^2 Check that :trac:`28654` is fixed:: sage: Polyhedron(lines=[[1]], backend='field') A 1-dimensional polyhedron in QQ^1 defined as the convex hull of 1 vertex and 1 line """ def _is_zero(self, x): """ Test whether ``x`` is zero. INPUT: - ``x`` -- a number in the base ring. OUTPUT: Boolean. EXAMPLES:: sage: p = Polyhedron([(sqrt(3),sqrt(2))], base_ring=AA) # optional - sage.rings.number_field sage: p._is_zero(0) # optional - sage.rings.number_field True sage: p._is_zero(1/100000) # optional - sage.rings.number_field False """ return x == 0 def _is_nonneg(self, x): """ Test whether ``x`` is nonnegative. INPUT: - ``x`` -- a number in the base ring. OUTPUT: Boolean. EXAMPLES:: sage: p = Polyhedron([(sqrt(3),sqrt(2))], base_ring=AA) # optional - sage.rings.number_field sage: p._is_nonneg(1) # optional - sage.rings.number_field True sage: p._is_nonneg(-1/100000) # optional - sage.rings.number_field False """ return x >= 0 def _is_positive(self, x): """ Test whether ``x`` is positive. INPUT: - ``x`` -- a number in the base ring. OUTPUT: Boolean. EXAMPLES:: sage: p = Polyhedron([(sqrt(3),sqrt(2))], base_ring=AA) # optional - sage.rings.number_field sage: p._is_positive(1) # optional - sage.rings.number_field True sage: p._is_positive(0) # optional - sage.rings.number_field False """ return x > 0 def _init_from_Vrepresentation_and_Hrepresentation(self, Vrep, Hrep): """ Construct polyhedron from V-representation and H-representation data. See :class:`Polyhedron_base` for a description of ``Vrep`` and ``Hrep``. .. WARNING:: The representation is assumed to be correct. It is not checked. EXAMPLES:: sage: from sage.geometry.polyhedron.parent import Polyhedra_field sage: from sage.geometry.polyhedron.backend_field import Polyhedron_field sage: parent = Polyhedra_field(AA, 1, 'field') # optional - sage.rings.number_field sage: Vrep = [[[0], [1]], [], []] sage: Hrep = [[[0, 1], [1, -1]], []] sage: p = Polyhedron_field(parent, Vrep, Hrep, # indirect doctest # optional - sage.rings.number_field ....: Vrep_minimal=True, Hrep_minimal=True) sage: p # optional - sage.rings.number_field A 1-dimensional polyhedron in AA^1 defined as the convex hull of 2 vertices """ self._init_Vrepresentation(*Vrep) self._init_Hrepresentation(*Hrep) def _init_from_Vrepresentation(self, vertices, rays, lines, minimize=True, verbose=False, internal_base_ring=None): """ Construct polyhedron from V-representation data. INPUT: - ``vertices`` -- list of points. Each point can be specified as any iterable container of ``internal_base_ring`` elements. - ``rays`` -- list of rays. Each ray can be specified as any iterable container of ``internal_base_ring`` elements. - ``lines`` -- list of lines. Each line can be specified asinternal_base_ring any iterable container of ``internal_base_ring`` elements. - ``verbose`` -- boolean (default: ``False``). Whether to print verbose output for debugging purposes. - ``internal_base_ring`` -- the base ring of the generators' components. Default is ``None``, in which case, it is set to :meth:`~sage.geometry.polyhedron.base.base_ring`. EXAMPLES:: sage: p = Polyhedron(ambient_dim=2, backend='field') sage: from sage.geometry.polyhedron.backend_field import Polyhedron_field sage: Polyhedron_field._init_from_Vrepresentation(p, [(0,0)], [], []) """ if internal_base_ring is None: internal_base_ring = self.base_ring() from sage.geometry.polyhedron.double_description_inhomogeneous import Hrep2Vrep, Vrep2Hrep H = Vrep2Hrep(internal_base_ring, self.ambient_dim(), vertices, rays, lines) V = Hrep2Vrep(internal_base_ring, self.ambient_dim(), H.inequalities, H.equations) self._init_Vrepresentation_backend(V) self._init_Hrepresentation_backend(H) def _init_from_Hrepresentation(self, ieqs, eqns, minimize=True, verbose=False, internal_base_ring=None): """ Construct polyhedron from H-representation data. INPUT: - ``ieqs`` -- list of inequalities. Each line can be specified as any iterable container of ``internal_base_ring`` elements. - ``eqns`` -- list of equalities. Each line can be specified as any iterable container of ``internal_base_ring`` elements. - ``verbose`` -- boolean (default: ``False``). Whether to print verbose output for debugging purposes. - ``internal_base_ring`` -- the base ring of the generators' components. Default is ``None``, in which case, it is set to :meth:`~sage.geometry.polyhedron.base.base_ring`. TESTS:: sage: p = Polyhedron(ambient_dim=2, backend='field') sage: from sage.geometry.polyhedron.backend_field import Polyhedron_field sage: Polyhedron_field._init_from_Hrepresentation(p, [(1, 2, 3)], []) """ if internal_base_ring is None: internal_base_ring = self.base_ring() from sage.geometry.polyhedron.double_description_inhomogeneous import Hrep2Vrep, Vrep2Hrep V = Hrep2Vrep(internal_base_ring, self.ambient_dim(), ieqs, eqns) H = Vrep2Hrep(internal_base_ring, self.ambient_dim(), V.vertices, V.rays, V.lines) self._init_Vrepresentation_backend(V) self._init_Hrepresentation_backend(H) def _init_Vrepresentation(self, vertices, rays, lines): """ Create the Vrepresentation objects from the given minimal data. EXAMPLES:: sage: from sage.geometry.polyhedron.parent import Polyhedra_field sage: from sage.geometry.polyhedron.backend_field import Polyhedron_field sage: parent = Polyhedra_field(AA, 1, 'field') # optional - sage.rings.number_field sage: Vrep = [[[0], [1]], [], []] sage: Hrep = [[[0, 1], [1, -1]], []] sage: p = Polyhedron_field(parent, Vrep, Hrep, # indirect doctest # optional - sage.rings.number_field ....: Vrep_minimal=True, Hrep_minimal=True) sage: p.vertices_list() # optional - sage.rings.number_field [[0], [1]] """ self._Vrepresentation = [] parent = self.parent() for v in vertices: parent._make_Vertex(self, v) for r in rays: parent._make_Ray(self, r) for l in lines: parent._make_Line(self, l) self._Vrepresentation = tuple(self._Vrepresentation) def _init_Vrepresentation_backend(self, Vrep): """ Create the V-representation objects from the double description. EXAMPLES:: sage: p = Polyhedron(vertices=[(0,1/sqrt(2)),(sqrt(2),0),(4,sqrt(5)/6)], # optional - sage.rings.number_field ....: base_ring=AA, backend='field') # indirect doctest sage: p.Hrepresentation() # optional - sage.rings.number_field (An inequality (-0.1582178750233332?, 1.097777812326429?) x + 0.2237538646678492? >= 0, An inequality (-0.1419794359520263?, -1.698172434277148?) x + 1.200789243901438? >= 0, An inequality (0.3001973109753594?, 0.600394621950719?) x - 0.4245431085692869? >= 0) sage: p.Vrepresentation() # optional - sage.rings.number_field (A vertex at (0.?e-16, 0.7071067811865475?), A vertex at (1.414213562373095?, 0), A vertex at (4.000000000000000?, 0.372677996249965?)) """ self._init_Vrepresentation(Vrep.vertices, Vrep.rays, Vrep.lines) def _init_Hrepresentation(self, inequalities, equations): """ Create the Vrepresentation objects from the given minimal data. EXAMPLES:: sage: from sage.geometry.polyhedron.parent import Polyhedra_field sage: from sage.geometry.polyhedron.backend_field import Polyhedron_field sage: parent = Polyhedra_field(AA, 1, 'field') # optional - sage.rings.number_field sage: Vrep = [[[0], [1]], [], []] sage: Hrep = [[[0, 1], [1, -1]], []] sage: p = Polyhedron_field(parent, Vrep, Hrep, # indirect doctest # optional - sage.rings.number_field ....: Vrep_minimal=True, Hrep_minimal=True) sage: p.inequalities_list() # optional - sage.rings.number_field [[0, 1], [1, -1]] """ self._Hrepresentation = [] parent = self.parent() for ieq in inequalities: parent._make_Inequality(self, ieq) for eqn in equations: parent._make_Equation(self, eqn) self._Hrepresentation = tuple(self._Hrepresentation) def _init_Hrepresentation_backend(self, Hrep): """ Create the H-representation objects from the double description. EXAMPLES:: sage: p = Polyhedron(vertices=[(0,1/sqrt(2)),(sqrt(2),0),(4,sqrt(5)/6)], # optional - sage.rings.number_field ....: base_ring=AA, backend='field') # indirect doctest sage: p.Hrepresentation() # optional - sage.rings.number_field (An inequality (-0.1582178750233332?, 1.097777812326429?) x + 0.2237538646678492? >= 0, An inequality (-0.1419794359520263?, -1.698172434277148?) x + 1.200789243901438? >= 0, An inequality (0.3001973109753594?, 0.600394621950719?) x - 0.4245431085692869? >= 0) sage: p.Vrepresentation() # optional - sage.rings.number_field (A vertex at (0.?e-16, 0.7071067811865475?), A vertex at (1.414213562373095?, 0), A vertex at (4.000000000000000?, 0.372677996249965?)) """ self._init_Hrepresentation(Hrep.inequalities, Hrep.equations) def _init_empty_polyhedron(self): """ Initializes an empty polyhedron. TESTS:: sage: empty = Polyhedron(backend='field', base_ring=AA); empty # optional - sage.rings.number_field The empty polyhedron in AA^0 sage: empty.Vrepresentation() # optional - sage.rings.number_field () sage: empty.Hrepresentation() # optional - sage.rings.number_field (An equation -1 == 0,) sage: Polyhedron(vertices=[], backend='field') The empty polyhedron in QQ^0 sage: Polyhedron(backend='field')._init_empty_polyhedron() """ super()._init_empty_polyhedron()
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/geometry/polyhedron/backend_field.py
0.948058
0.537223
backend_field.py
pypi
class LibSingularGBDefaultContext: def __init__(self): """ EXAMPLES:: sage: from sage.libs.singular.standard_options import LibSingularGBDefaultContext sage: from sage.libs.singular.option import opt sage: P.<a,b,c> = PolynomialRing(QQ, 3, order='lex') sage: I = sage.rings.ideal.Katsura(P, 3) sage: I.gens() [a + 2*b + 2*c - 1, a^2 - a + 2*b^2 + 2*c^2, 2*a*b + 2*b*c - b] sage: opt['red_tail'] = False sage: opt['red_sb'] = False sage: import sage.libs.singular.function_factory sage: groebner = sage.libs.singular.function_factory.ff.groebner sage: rgb = groebner(I) sage: rgb [84*c^4 - 40*c^3 + c^2 + c, 7*b + 210*c^3 - 79*c^2 + 3*c, a + 2*b + 2*c - 1] sage: with LibSingularGBDefaultContext(): rgb = groebner(I) sage: rgb [84*c^4 - 40*c^3 + c^2 + c, 7*b + 210*c^3 - 79*c^2 + 3*c, 7*a - 420*c^3 + 158*c^2 + 8*c - 7] """ from sage.libs.singular.option import opt_ctx self.libsingular_option_context = opt_ctx def __enter__(self): """ EXAMPLES:: sage: from sage.libs.singular.standard_options import LibSingularGBDefaultContext sage: from sage.libs.singular.option import opt sage: P.<a,b,c,d> = PolynomialRing(QQ, 4, order='lex') sage: I = sage.rings.ideal.Katsura(P, 4) sage: I.gens() [a + 2*b + 2*c + 2*d - 1, a^2 - a + 2*b^2 + 2*c^2 + 2*d^2, 2*a*b + 2*b*c - b + 2*c*d, 2*a*c + b^2 + 2*b*d - c] sage: opt['red_tail'] = False sage: opt['red_sb'] = False sage: import sage.libs.singular.function_factory sage: groebner = sage.libs.singular.function_factory.ff.groebner sage: rgb = groebner(I) sage: rgb [128304*d^8 - 93312*d^7 + 15552*d^6 + 3144*d^5 - 1120*d^4 + 36*d^3 + 15*d^2 - d, 5913075*c + 371438283744*d^7 - 237550027104*d^6 + 22645939824*d^5 + 11520686172*d^4 - 2024910556*d^3 - 132524276*d^2 + 30947828*d, 1044*b + 10976*c^3 + 67914*c^2*d - 9709*c^2 + 100296*c*d^2 - 32862*c*d + 2412*c + 64302*d^3 - 29483*d^2 + 2683*d, a + 2*b + 2*c + 2*d - 1] sage: with LibSingularGBDefaultContext(): rgb = groebner(I) sage: rgb [128304*d^8 - 93312*d^7 + 15552*d^6 + 3144*d^5 - 1120*d^4 + 36*d^3 + 15*d^2 - d, 5913075*c + 371438283744*d^7 - 237550027104*d^6 + 22645939824*d^5 + 11520686172*d^4 - 2024910556*d^3 - 132524276*d^2 + 30947828*d, 1971025*b - 97197721632*d^7 + 73975630752*d^6 - 12121915032*d^5 - 2760941496*d^4 + 814792828*d^3 - 1678512*d^2 - 9158924*d, 5913075*a - 159690237696*d^7 + 31246269696*d^6 + 27439610544*d^5 - 6475723368*d^4 - 838935856*d^3 + 275119624*d^2 + 4884038*d - 5913075] """ self.libsingular_option_context.__enter__() self.libsingular_option_context.opt.reset_default() self.libsingular_option_context.opt['red_sb'] = True self.libsingular_option_context.opt['red_tail'] = True self.libsingular_option_context.opt['deg_bound'] = 0 self.libsingular_option_context.opt['mult_bound'] = 0 def __exit__(self, typ, value, tb): """ EXAMPLES:: sage: from sage.libs.singular.standard_options import LibSingularGBDefaultContext sage: from sage.libs.singular.option import opt sage: P.<a,b,c,d> = PolynomialRing(GF(7), 4, order='lex') sage: I = sage.rings.ideal.Katsura(P, 4) sage: I.gens() [a + 2*b + 2*c + 2*d - 1, a^2 - a + 2*b^2 + 2*c^2 + 2*d^2, 2*a*b + 2*b*c - b + 2*c*d, 2*a*c + b^2 + 2*b*d - c] sage: opt['red_tail'] = False sage: opt['red_sb'] = False sage: import sage.libs.singular.function_factory sage: groebner = sage.libs.singular.function_factory.ff.groebner sage: rgb = groebner(I) sage: rgb [d^7 + 3*d^6 - d^5 + 3*d^4 + d^3 - d^2 + 3*d, c - 3*d^6 + 3*d^5 - d^4 + d^3 - 2*d, b + 3*c*d - 3*c + d^2 + 2*d, a + 2*b + 2*c + 2*d - 1] sage: with LibSingularGBDefaultContext(): rgb = groebner(I) sage: rgb [d^7 + 3*d^6 - d^5 + 3*d^4 + d^3 - d^2 + 3*d, c - 3*d^6 + 3*d^5 - d^4 + d^3 - 2*d, b - 3*d^6 + 2*d^4 + d^3 + 2*d^2 - 3*d, a - 2*d^6 + d^5 - 2*d^4 + 3*d^3 + 3*d^2 - 2*d - 1] """ self.libsingular_option_context.__exit__(typ,value,tb) def libsingular_gb_standard_options(func): r""" Decorator to force a reduced Singular groebner basis. TESTS:: sage: P.<a,b,c,d,e> = PolynomialRing(GF(127)) sage: J = sage.rings.ideal.Cyclic(P).homogenize() sage: from sage.misc.sageinspect import sage_getsource sage: "basis.reduced" in sage_getsource(J.interreduced_basis) True The following tests against a bug that was fixed in :trac:`11298`:: sage: from sage.misc.sageinspect import sage_getsourcelines, sage_getargspec sage: P.<x,y> = QQ[] sage: I = P*[x,y] sage: sage_getargspec(I.interreduced_basis) FullArgSpec(args=['self'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={}) sage: sage_getsourcelines(I.interreduced_basis) ([' @handle_AA_and_QQbar\n', ' @singular_gb_standard_options\n', ' @libsingular_gb_standard_options\n', ' def interreduced_basis(self):\n', ... ' return self.basis.reduced()\n'], ...) .. note:: This decorator is used automatically internally so the user does not need to use it manually. """ from sage.misc.decorators import sage_wraps @sage_wraps(func) def wrapper(*args, **kwds): """ Execute function in ``LibSingularGBDefaultContext``. """ with LibSingularGBDefaultContext(): return func(*args, **kwds) return wrapper
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/libs/singular/standard_options.py
0.636805
0.483831
standard_options.py
pypi
"Cremona modular symbols" def CremonaModularSymbols(level, sign=0, cuspidal=False, verbose=0): """ Return the space of Cremona modular symbols with given level, sign, etc. INPUT: - ``level`` -- an integer >= 2 (at least 2, not just positive!) - ``sign`` -- an integer either 0 (the default) or 1 or -1. - ``cuspidal`` -- (default: False); if True, compute only the cuspidal subspace - ``verbose`` -- (default: False): if True, print verbose information while creating space EXAMPLES:: sage: M = CremonaModularSymbols(43); M Cremona Modular Symbols space of dimension 7 for Gamma_0(43) of weight 2 with sign 0 sage: M = CremonaModularSymbols(43, sign=1); M Cremona Modular Symbols space of dimension 4 for Gamma_0(43) of weight 2 with sign 1 sage: M = CremonaModularSymbols(43, cuspidal=True); M Cremona Cuspidal Modular Symbols space of dimension 6 for Gamma_0(43) of weight 2 with sign 0 sage: M = CremonaModularSymbols(43, cuspidal=True, sign=1); M Cremona Cuspidal Modular Symbols space of dimension 3 for Gamma_0(43) of weight 2 with sign 1 When run interactively, the following command will display verbose output:: sage: M = CremonaModularSymbols(43, verbose=1) After 2-term relations, ngens = 22 ngens = 22 maxnumrel = 32 relation matrix has = 704 entries... Finished 3-term relations: numrel = 16 ( maxnumrel = 32) relmat has 42 nonzero entries (density = 0.0596591) Computing kernel... time to compute kernel = (... seconds) rk = 7 Number of cusps is 2 ncusps = 2 About to compute matrix of delta delta matrix done: size 2x7. About to compute kernel of delta done Finished constructing homspace. sage: M Cremona Modular Symbols space of dimension 7 for Gamma_0(43) of weight 2 with sign 0 The input must be valid or a ValueError is raised:: sage: M = CremonaModularSymbols(-1) Traceback (most recent call last): ... ValueError: the level (= -1) must be at least 2 sage: M = CremonaModularSymbols(0) Traceback (most recent call last): ... ValueError: the level (= 0) must be at least 2 The sign can only be 0 or 1 or -1:: sage: M = CremonaModularSymbols(10, sign = -2) Traceback (most recent call last): ... ValueError: sign (= -2) is not supported; use 0, +1 or -1 We do allow -1 as a sign (see :trac:`9476`):: sage: CremonaModularSymbols(10, sign = -1) Cremona Modular Symbols space of dimension 0 for Gamma_0(10) of weight 2 with sign -1 """ from .homspace import ModularSymbols return ModularSymbols(level=level, sign=sign, cuspidal=cuspidal, verbose=verbose)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/libs/eclib/constructor.py
0.853547
0.410579
constructor.py
pypi
import re import string from sage.structure.sage_object import SageObject from sage.libs.gap.libgap import libgap Length = libgap.function_factory('Length') FlagsType = libgap.function_factory('FlagsType') TypeObj = libgap.function_factory('TypeObj') IS_SUBSET_FLAGS = libgap.function_factory('IS_SUBSET_FLAGS') GET_OPER_FLAGS = libgap.function_factory('GET_OPER_FLAGS') OPERATIONS = libgap.get_global('OPERATIONS') NameFunction = libgap.function_factory('NameFunction') NAME_RE = re.compile(r'(Setter|Getter|Tester)\((.*)\)') class OperationInspector(SageObject): def __init__(self, libgap_element): """ Information about operations that can act on a given LibGAP element INPUT: - ``libgap_element`` -- libgap element. EXAMPLES:: sage: from sage.libs.gap.operations import OperationInspector sage: OperationInspector(libgap(123)) Operations on 123 """ self._obj = libgap_element self.flags = FlagsType(TypeObj(self.obj)) def _repr_(self): """ Return the string representation OUTPUT: String EXAMPLES:: sage: from sage.libs.gap.operations import OperationInspector sage: opr = OperationInspector(libgap(123)) sage: opr._repr_() 'Operations on 123' """ return 'Operations on {0}'.format(repr(self._obj)) @property def obj(self): """ The first argument for the operations OUTPUT: A Libgap object. EXAMPLES:: sage: from sage.libs.gap.operations import OperationInspector sage: x = OperationInspector(libgap(123)) sage: print(x.obj) 123 """ return self._obj def operations(self): """ Return the GAP operations for :meth:`obj` OUTPUT: List of GAP operations EXAMPLES:: sage: from sage.libs.gap.operations import OperationInspector sage: x = OperationInspector(libgap(123)) sage: Unknown = libgap.function_factory('Unknown') sage: Unknown in x.operations() True """ def mfi(o): filts = GET_OPER_FLAGS(o) return any(all(IS_SUBSET_FLAGS(self.flags, fl) for fl in fls) for fls in filts) return (op for op in OPERATIONS if mfi(op)) def op_names(self): """ Return the names of the operations OUTPUT: List of strings EXAMPLES:: sage: from sage.libs.gap.operations import OperationInspector sage: x = OperationInspector(libgap(123)) sage: 'Sqrt' in x.op_names() True """ result = set() for f in self.operations(): name = NameFunction(f).sage() if name[0] not in string.ascii_letters: continue match = NAME_RE.match(name) if match: result.add(match.groups()[1]) else: result.add(name) return sorted(result)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/libs/gap/operations.py
0.70416
0.179999
operations.py
pypi
from sage.misc.misc import walltime, cputime def count_noun(number, noun, plural=None, pad_number=False, pad_noun=False): """ EXAMPLES:: sage: from sage.doctest.util import count_noun sage: count_noun(1, "apple") '1 apple' sage: count_noun(1, "apple", pad_noun=True) '1 apple ' sage: count_noun(1, "apple", pad_number=3) ' 1 apple' sage: count_noun(2, "orange") '2 oranges' sage: count_noun(3, "peach", "peaches") '3 peaches' sage: count_noun(1, "peach", plural="peaches", pad_noun=True) '1 peach ' """ if plural is None: plural = noun + "s" if pad_noun: # We assume that the plural is never shorter than the noun.... pad_noun = " " * (len(plural) - len(noun)) else: pad_noun = "" if pad_number: number_str = ("%%%sd"%pad_number)%number else: number_str = "%d"%number if number == 1: return "%s %s%s"%(number_str, noun, pad_noun) else: return "%s %s"%(number_str, plural) def dict_difference(self, other): """ Return a dict with all key-value pairs occurring in ``self`` but not in ``other``. EXAMPLES:: sage: from sage.doctest.util import dict_difference sage: d1 = {1: 'a', 2: 'b', 3: 'c'} sage: d2 = {1: 'a', 2: 'x', 4: 'c'} sage: dict_difference(d2, d1) {2: 'x', 4: 'c'} :: sage: from sage.doctest.control import DocTestDefaults sage: D1 = DocTestDefaults() sage: D2 = DocTestDefaults(foobar="hello", timeout=100) sage: dict_difference(D2.__dict__, D1.__dict__) {'foobar': 'hello', 'timeout': 100} """ D = dict() for k, v in self.items(): try: if other[k] == v: continue except KeyError: pass D[k] = v return D class Timer: """ A simple timer. EXAMPLES:: sage: from sage.doctest.util import Timer sage: Timer() {} sage: TestSuite(Timer()).run() """ def start(self): """ Start the timer. Can be called multiple times to reset the timer. EXAMPLES:: sage: from sage.doctest.util import Timer sage: Timer().start() {'cputime': ..., 'walltime': ...} """ self.cputime = cputime() self.walltime = walltime() return self def stop(self): """ Stops the timer, recording the time that has passed since it was started. EXAMPLES:: sage: from sage.doctest.util import Timer sage: import time sage: timer = Timer().start() sage: time.sleep(float(0.5)) sage: timer.stop() {'cputime': ..., 'walltime': ...} """ self.cputime = cputime(self.cputime) self.walltime = walltime(self.walltime) return self def annotate(self, object): """ Annotates the given object with the cputime and walltime stored in this timer. EXAMPLES:: sage: from sage.doctest.util import Timer sage: Timer().start().annotate(EllipticCurve) sage: EllipticCurve.cputime # random 2.817255 sage: EllipticCurve.walltime # random 1332649288.410404 """ object.cputime = self.cputime object.walltime = self.walltime def __repr__(self): """ String representation is from the dictionary. EXAMPLES:: sage: from sage.doctest.util import Timer sage: repr(Timer().start()) # indirect doctest "{'cputime': ..., 'walltime': ...}" """ return str(self) def __str__(self): """ String representation is from the dictionary. EXAMPLES:: sage: from sage.doctest.util import Timer sage: str(Timer().start()) # indirect doctest "{'cputime': ..., 'walltime': ...}" """ return str(self.__dict__) def __eq__(self, other): """ Comparison. EXAMPLES:: sage: from sage.doctest.util import Timer sage: Timer() == Timer() True sage: t = Timer().start() sage: loads(dumps(t)) == t True """ if not isinstance(other, Timer): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Test for non-equality EXAMPLES:: sage: from sage.doctest.util import Timer sage: Timer() == Timer() True sage: t = Timer().start() sage: loads(dumps(t)) != t False """ return not (self == other) # Inheritance rather then delegation as globals() must be a dict class RecordingDict(dict): """ This dictionary is used for tracking the dependencies of an example. This feature allows examples in different doctests to be grouped for better timing data. It's obtained by recording whenever anything is set or retrieved from this dictionary. EXAMPLES:: sage: from sage.doctest.util import RecordingDict sage: D = RecordingDict(test=17) sage: D.got set() sage: D['test'] 17 sage: D.got {'test'} sage: D.set set() sage: D['a'] = 1 sage: D['a'] 1 sage: D.set {'a'} sage: D.got {'test'} TESTS:: sage: TestSuite(D).run() """ def __init__(self, *args, **kwds): """ Initialization arguments are the same as for a normal dictionary. EXAMPLES:: sage: from sage.doctest.util import RecordingDict sage: D = RecordingDict(d = 42) sage: D.got set() """ dict.__init__(self, *args, **kwds) self.start() def start(self): """ We track which variables have been set or retrieved. This function initializes these lists to be empty. EXAMPLES:: sage: from sage.doctest.util import RecordingDict sage: D = RecordingDict(d = 42) sage: D.set set() sage: D['a'] = 4 sage: D.set {'a'} sage: D.start(); D.set set() """ self.set = set([]) self.got = set([]) def __getitem__(self, name): """ EXAMPLES:: sage: from sage.doctest.util import RecordingDict sage: D = RecordingDict(d = 42) sage: D['a'] = 4 sage: D.got set() sage: D['a'] # indirect doctest 4 sage: D.got set() sage: D['d'] 42 sage: D.got {'d'} """ if name not in self.set: self.got.add(name) return dict.__getitem__(self, name) def __setitem__(self, name, value): """ EXAMPLES:: sage: from sage.doctest.util import RecordingDict sage: D = RecordingDict(d = 42) sage: D['a'] = 4 # indirect doctest sage: D.set {'a'} """ self.set.add(name) dict.__setitem__(self, name, value) def __delitem__(self, name): """ EXAMPLES:: sage: from sage.doctest.util import RecordingDict sage: D = RecordingDict(d = 42) sage: del D['d'] # indirect doctest sage: D.set {'d'} """ self.set.add(name) dict.__delitem__(self, name) def get(self, name, default=None): """ EXAMPLES:: sage: from sage.doctest.util import RecordingDict sage: D = RecordingDict(d = 42) sage: D.get('d') 42 sage: D.got {'d'} sage: D.get('not_here') sage: sorted(list(D.got)) ['d', 'not_here'] """ if name not in self.set: self.got.add(name) return dict.get(self, name, default) def copy(self): """ Note that set and got are not copied. EXAMPLES:: sage: from sage.doctest.util import RecordingDict sage: D = RecordingDict(d = 42) sage: D['a'] = 4 sage: D.set {'a'} sage: E = D.copy() sage: E.set set() sage: sorted(E.keys()) ['a', 'd'] """ return RecordingDict(dict.copy(self)) def __reduce__(self): """ Pickling. EXAMPLES:: sage: from sage.doctest.util import RecordingDict sage: D = RecordingDict(d = 42) sage: D['a'] = 4 sage: D.get('not_here') sage: E = loads(dumps(D)) sage: E.got {'not_here'} """ return make_recording_dict, (dict(self), self.set, self.got) def make_recording_dict(D, st, gt): """ Auxiliary function for pickling. EXAMPLES:: sage: from sage.doctest.util import make_recording_dict sage: D = make_recording_dict({'a':4,'d':42},set([]),set(['not_here'])) sage: sorted(D.items()) [('a', 4), ('d', 42)] sage: D.got {'not_here'} """ ans = RecordingDict(D) ans.set = st ans.got = gt return ans class NestedName: """ Class used to construct fully qualified names based on indentation level. EXAMPLES:: sage: from sage.doctest.util import NestedName sage: qname = NestedName('sage.categories.algebras') sage: qname[0] = 'Algebras'; qname sage.categories.algebras.Algebras sage: qname[4] = '__contains__'; qname sage.categories.algebras.Algebras.__contains__ sage: qname[4] = 'ParentMethods' sage: qname[8] = 'from_base_ring'; qname sage.categories.algebras.Algebras.ParentMethods.from_base_ring TESTS:: sage: TestSuite(qname).run() """ def __init__(self, base): """ INPUT: - base -- a string: the name of the module. EXAMPLES:: sage: from sage.doctest.util import NestedName sage: qname = NestedName('sage.categories.algebras') sage: qname sage.categories.algebras """ self.all = [base] def __setitem__(self, index, value): """ Sets the value at a given indentation level. INPUT: - index -- a positive integer, the indentation level (often a multiple of 4, but not necessarily) - value -- a string, the name of the class or function at that indentation level. EXAMPLES:: sage: from sage.doctest.util import NestedName sage: qname = NestedName('sage.categories.algebras') sage: qname[1] = 'Algebras' # indirect doctest sage: qname sage.categories.algebras.Algebras sage: qname.all ['sage.categories.algebras', None, 'Algebras'] """ if index < 0: raise ValueError while len(self.all) <= index: self.all.append(None) self.all[index+1:] = [value] def __str__(self): """ Return a .-separated string giving the full name. EXAMPLES:: sage: from sage.doctest.util import NestedName sage: qname = NestedName('sage.categories.algebras') sage: qname[1] = 'Algebras' sage: qname[44] = 'at_the_end_of_the_universe' sage: str(qname) # indirect doctest 'sage.categories.algebras.Algebras.at_the_end_of_the_universe' """ return repr(self) def __repr__(self): """ Return a .-separated string giving the full name. EXAMPLES:: sage: from sage.doctest.util import NestedName sage: qname = NestedName('sage.categories.algebras') sage: qname[1] = 'Algebras' sage: qname[44] = 'at_the_end_of_the_universe' sage: print(qname) # indirect doctest sage.categories.algebras.Algebras.at_the_end_of_the_universe """ return '.'.join(a for a in self.all if a is not None) def __eq__(self, other): """ Comparison is just comparison of the underlying lists. EXAMPLES:: sage: from sage.doctest.util import NestedName sage: qname = NestedName('sage.categories.algebras') sage: qname2 = NestedName('sage.categories.algebras') sage: qname == qname2 True sage: qname[0] = 'Algebras' sage: qname2[2] = 'Algebras' sage: repr(qname) == repr(qname2) True sage: qname == qname2 False """ if not isinstance(other, NestedName): return False return self.all == other.all def __ne__(self, other): """ Test for non-equality. EXAMPLES:: sage: from sage.doctest.util import NestedName sage: qname = NestedName('sage.categories.algebras') sage: qname2 = NestedName('sage.categories.algebras') sage: qname != qname2 False sage: qname[0] = 'Algebras' sage: qname2[2] = 'Algebras' sage: repr(qname) == repr(qname2) True sage: qname != qname2 True """ return not (self == other)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/doctest/util.py
0.816809
0.296833
util.py
pypi
import os import sys import re import random import doctest from sage.cpython.string import bytes_to_str from sage.repl.load import load from sage.misc.lazy_attribute import lazy_attribute from sage.misc.package_dir import is_package_or_sage_namespace_package_dir from .parsing import SageDocTestParser from .util import NestedName from sage.structure.dynamic_class import dynamic_class from sage.env import SAGE_SRC, SAGE_LIB # Python file parsing triple_quotes = re.compile(r"\s*[rRuU]*((''')|(\"\"\"))") name_regex = re.compile(r".*\s(\w+)([(].*)?:") # LaTeX file parsing begin_verb = re.compile(r"\s*\\begin{verbatim}") end_verb = re.compile(r"\s*\\end{verbatim}\s*(%link)?") begin_lstli = re.compile(r"\s*\\begin{lstlisting}") end_lstli = re.compile(r"\s*\\end{lstlisting}\s*(%link)?") skip = re.compile(r".*%skip.*") # ReST file parsing link_all = re.compile(r"^\s*\.\.\s+linkall\s*$") double_colon = re.compile(r"^(\s*).*::\s*$") code_block = re.compile(r"^(\s*)[.][.]\s*code-block\s*::.*$") whitespace = re.compile(r"\s*") bitness_marker = re.compile('#.*(32|64)-bit') bitness_value = '64' if sys.maxsize > (1 << 32) else '32' # For neutralizing doctests find_prompt = re.compile(r"^(\s*)(>>>|sage:)(.*)") # For testing that enough doctests are created sagestart = re.compile(r"^\s*(>>> |sage: )\s*[^#\s]") untested = re.compile("(not implemented|not tested)") # For parsing a PEP 0263 encoding declaration pep_0263 = re.compile(br'^[ \t\v]*#.*?coding[:=]\s*([-\w.]+)') # Source line number in warning output doctest_line_number = re.compile(r"^\s*doctest:[0-9]") def get_basename(path): """ This function returns the basename of the given path, e.g. sage.doctest.sources or doc.ru.tutorial.tour_advanced EXAMPLES:: sage: from sage.doctest.sources import get_basename sage: from sage.env import SAGE_SRC sage: import os sage: get_basename(os.path.join(SAGE_SRC,'sage','doctest','sources.py')) 'sage.doctest.sources' """ if path is None: return None if not os.path.exists(path): return path path = os.path.abspath(path) root = os.path.dirname(path) # If the file is in the sage library, we can use our knowledge of # the directory structure dev = SAGE_SRC sp = SAGE_LIB if path.startswith(dev): # there will be a branch name i = path.find(os.path.sep, len(dev)) if i == -1: # this source is the whole library.... return path root = path[:i] elif path.startswith(sp): root = path[:len(sp)] else: # If this file is in some python package we can see how deep # it goes. while is_package_or_sage_namespace_package_dir(root): root = os.path.dirname(root) fully_qualified_path = os.path.splitext(path[len(root) + 1:])[0] if os.path.split(path)[1] == '__init__.py': fully_qualified_path = fully_qualified_path[:-9] return fully_qualified_path.replace(os.path.sep, '.') class DocTestSource(): """ This class provides a common base class for different sources of doctests. INPUT: - ``options`` -- a :class:`sage.doctest.control.DocTestDefaults` instance or equivalent. """ def __init__(self, options): """ Initialization. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py') sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: TestSuite(FDS).run() """ self.options = options def __eq__(self, other): """ Comparison is just by comparison of attributes. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py') sage: DD = DocTestDefaults() sage: FDS = FileDocTestSource(filename,DD) sage: FDS2 = FileDocTestSource(filename,DD) sage: FDS == FDS2 True """ if type(self) != type(other): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Test for non-equality. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py') sage: DD = DocTestDefaults() sage: FDS = FileDocTestSource(filename,DD) sage: FDS2 = FileDocTestSource(filename,DD) sage: FDS != FDS2 False """ return not (self == other) def _process_doc(self, doctests, doc, namespace, start): """ Appends doctests defined in ``doc`` to the list ``doctests``. This function is called when a docstring block is completed (either by ending a triple quoted string in a Python file, unindenting from a comment block in a ReST file, or ending a verbatim or lstlisting environment in a LaTeX file). INPUT: - ``doctests`` -- a running list of doctests to which the new test(s) will be appended. - ``doc`` -- a list of lines of a docstring, each including the trailing newline. - ``namespace`` -- a dictionary or :class:`sage.doctest.util.RecordingDict`, used in the creation of new :class:`doctest.DocTest` s. - ``start`` -- an integer, giving the line number of the start of this docstring in the larger file. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.doctest.parsing import SageDocTestParser sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','util.py') sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: doctests, _ = FDS.create_doctests({}) sage: manual_doctests = [] sage: for dt in doctests: ....: FDS.qualified_name = dt.name ....: FDS._process_doc(manual_doctests, dt.docstring, {}, dt.lineno-1) sage: doctests == manual_doctests True """ docstring = "".join(doc) new_doctests = self.parse_docstring(docstring, namespace, start) sig_on_count_doc_doctest = "sig_on_count() # check sig_on/off pairings (virtual doctest)\n" for dt in new_doctests: if len(dt.examples) > 0 and not (hasattr(dt.examples[-1],'sage_source') and dt.examples[-1].sage_source == sig_on_count_doc_doctest): # Line number refers to the end of the docstring sigon = doctest.Example(sig_on_count_doc_doctest, "0\n", lineno=docstring.count("\n")) sigon.sage_source = sig_on_count_doc_doctest dt.examples.append(sigon) doctests.append(dt) def _create_doctests(self, namespace, tab_okay=None): """ Creates a list of doctests defined in this source. This function collects functionality common to file and string sources, and is called by :meth:`FileDocTestSource.create_doctests`. INPUT: - ``namespace`` -- a dictionary or :class:`sage.doctest.util.RecordingDict`, used in the creation of new :class:`doctest.DocTest` s. - ``tab_okay`` -- whether tabs are allowed in this source. OUTPUT: - ``doctests`` -- a list of doctests defined by this source - ``extras`` -- a dictionary with ``extras['tab']`` either False or a list of linenumbers on which tabs appear. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.doctest.util import NestedName sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py') sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS.qualified_name = NestedName('sage.doctest.sources') sage: doctests, extras = FDS._create_doctests({}) sage: len(doctests) 41 sage: extras['tab'] False sage: extras['line_number'] False """ if tab_okay is None: tab_okay = isinstance(self,TexSource) self._init() self.line_shift = 0 self.parser = SageDocTestParser(self.options.optional, self.options.long) self.linking = False doctests = [] in_docstring = False unparsed_doc = False doc = [] start = None tab_locations = [] contains_line_number = False for lineno, line in self: if doctest_line_number.search(line) is not None: contains_line_number = True if "\t" in line: tab_locations.append(str(lineno+1)) if "SAGE_DOCTEST_ALLOW_TABS" in line: tab_okay = True just_finished = False if in_docstring: if self.ending_docstring(line): in_docstring = False just_finished = True self._process_doc(doctests, doc, namespace, start) unparsed_doc = False else: bitness = bitness_marker.search(line) if bitness: if bitness.groups()[0] != bitness_value: self.line_shift += 1 continue else: line = line[:bitness.start()] + "\n" if self.line_shift and sagestart.match(line): # We insert blank lines to make up for the removed lines doc.extend(["\n"]*self.line_shift) self.line_shift = 0 doc.append(line) unparsed_doc = True if not in_docstring and (not just_finished or self.start_finish_can_overlap): # to get line numbers in linked docstrings correct we # append a blank line to the doc list. doc.append("\n") if not line.strip(): continue if self.starting_docstring(line): in_docstring = True if self.linking: # If there's already a doctest, we overwrite it. if len(doctests) > 0: doctests.pop() if start is None: start = lineno doc = [] else: self.line_shift = 0 start = lineno doc = [] # In ReST files we can end the file without decreasing the indentation level. if unparsed_doc: self._process_doc(doctests, doc, namespace, start) extras = dict(tab=not tab_okay and tab_locations, line_number=contains_line_number, optionals=self.parser.optionals) if self.options.randorder is not None and self.options.randorder is not False: # we want to randomize even when self.randorder = 0 random.seed(self.options.randorder) randomized = [] while doctests: i = random.randint(0, len(doctests) - 1) randomized.append(doctests.pop(i)) return randomized, extras else: return doctests, extras class StringDocTestSource(DocTestSource): r""" This class creates doctests from a string. INPUT: - ``basename`` -- string such as 'sage.doctests.sources', going into the names of created doctests and examples. - ``source`` -- a string, giving the source code to be parsed for doctests. - ``options`` -- a :class:`sage.doctest.control.DocTestDefaults` or equivalent. - ``printpath`` -- a string, to be used in place of a filename when doctest failures are displayed. - ``lineno_shift`` -- an integer (default: 0) by which to shift the line numbers of all doctests defined in this string. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import StringDocTestSource, PythonSource sage: from sage.structure.dynamic_class import dynamic_class sage: s = "'''\n sage: 2 + 2\n 4\n'''" sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource)) sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime') sage: dt, extras = PSS.create_doctests({}) sage: len(dt) 1 sage: extras['tab'] [] sage: extras['line_number'] False sage: s = "'''\n\tsage: 2 + 2\n\t4\n'''" sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime') sage: dt, extras = PSS.create_doctests({}) sage: extras['tab'] ['2', '3'] sage: s = "'''\n sage: import warnings; warnings.warn('foo')\n doctest:1: UserWarning: foo \n'''" sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime') sage: dt, extras = PSS.create_doctests({}) sage: extras['line_number'] True """ def __init__(self, basename, source, options, printpath, lineno_shift=0): r""" Initialization TESTS:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import StringDocTestSource, PythonSource sage: from sage.structure.dynamic_class import dynamic_class sage: s = "'''\n sage: 2 + 2\n 4\n'''" sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource)) sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime') sage: TestSuite(PSS).run() """ self.qualified_name = NestedName(basename) self.printpath = printpath self.source = source self.lineno_shift = lineno_shift DocTestSource.__init__(self, options) def __iter__(self): r""" Iterating over this source yields pairs ``(lineno, line)``. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import StringDocTestSource, PythonSource sage: from sage.structure.dynamic_class import dynamic_class sage: s = "'''\n sage: 2 + 2\n 4\n'''" sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource)) sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime') sage: for n, line in PSS: ....: print("{} {}".format(n, line)) 0 ''' 1 sage: 2 + 2 2 4 3 ''' """ for lineno, line in enumerate(self.source.split('\n')): yield lineno + self.lineno_shift, line + '\n' def create_doctests(self, namespace): r""" Creates doctests from this string. INPUT: - ``namespace`` -- a dictionary or :class:`sage.doctest.util.RecordingDict`. OUTPUT: - ``doctests`` -- a list of doctests defined by this string - ``tab_locations`` -- either False or a list of linenumbers on which tabs appear. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import StringDocTestSource, PythonSource sage: from sage.structure.dynamic_class import dynamic_class sage: s = "'''\n sage: 2 + 2\n 4\n'''" sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource)) sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime') sage: dt, tabs = PSS.create_doctests({}) sage: for t in dt: ....: print("{} {}".format(t.name, t.examples[0].sage_source)) <runtime> 2 + 2 """ return self._create_doctests(namespace) class FileDocTestSource(DocTestSource): """ This class creates doctests from a file. INPUT: - ``path`` -- string, the filename - ``options`` -- a :class:`sage.doctest.control.DocTestDefaults` instance or equivalent. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py') sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS.basename 'sage.doctest.sources' TESTS:: sage: TestSuite(FDS).run() :: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: filename = tmp_filename(ext=".txtt") sage: FDS = FileDocTestSource(filename,DocTestDefaults()) Traceback (most recent call last): ... ValueError: unknown extension for the file to test (=...txtt), valid extensions are: .py, .pyx, .pxd, .pxi, .sage, .spyx, .tex, .rst, .rst.txt """ def __init__(self, path, options): """ Initialization. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py') sage: FDS = FileDocTestSource(filename,DocTestDefaults(randorder=0)) sage: FDS.options.randorder 0 """ self.path = path DocTestSource.__init__(self, options) if path.endswith('.rst.txt'): ext = '.rst.txt' else: base, ext = os.path.splitext(path) valid_code_ext = ('.py', '.pyx', '.pxd', '.pxi', '.sage', '.spyx') if ext in valid_code_ext: self.__class__ = dynamic_class('PythonFileSource',(FileDocTestSource,PythonSource)) self.encoding = "utf-8" elif ext == '.tex': self.__class__ = dynamic_class('TexFileSource',(FileDocTestSource,TexSource)) self.encoding = "utf-8" elif ext == '.rst' or ext == '.rst.txt': self.__class__ = dynamic_class('RestFileSource',(FileDocTestSource,RestSource)) self.encoding = "utf-8" else: valid_ext = ", ".join(valid_code_ext + ('.tex', '.rst', '.rst.txt')) raise ValueError("unknown extension for the file to test (={})," " valid extensions are: {}".format(path, valid_ext)) def __iter__(self): r""" Iterating over this source yields pairs ``(lineno, line)``. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: filename = tmp_filename(ext=".py") sage: s = "'''\n sage: 2 + 2\n 4\n'''" sage: with open(filename, 'w') as f: ....: _ = f.write(s) sage: FDS = FileDocTestSource(filename, DocTestDefaults()) sage: for n, line in FDS: ....: print("{} {}".format(n, line)) 0 ''' 1 sage: 2 + 2 2 4 3 ''' The encoding is "utf-8" by default:: sage: FDS.encoding 'utf-8' We create a file with a Latin-1 encoding without declaring it:: sage: s = b"'''\nRegardons le polyn\xF4me...\n'''\n" sage: with open(filename, 'wb') as f: ....: _ = f.write(s) sage: FDS = FileDocTestSource(filename, DocTestDefaults()) sage: L = list(FDS) Traceback (most recent call last): ... UnicodeDecodeError: 'utf...8' codec can...t decode byte 0xf4 in position 18: invalid continuation byte This works if we add a PEP 0263 encoding declaration:: sage: s = b"#!/usr/bin/env python\n# -*- coding: latin-1 -*-\n" + s sage: with open(filename, 'wb') as f: ....: _ = f.write(s) sage: FDS = FileDocTestSource(filename, DocTestDefaults()) sage: L = list(FDS) sage: FDS.encoding 'latin-1' """ with open(self.path, 'rb') as source: for lineno, line in enumerate(source): if lineno < 2: match = pep_0263.search(line) if match: self.encoding = bytes_to_str(match.group(1), 'ascii') yield lineno, line.decode(self.encoding) @lazy_attribute def printpath(self): """ Whether the path is printed absolutely or relatively depends on an option. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: import os sage: root = os.path.realpath(os.path.join(SAGE_SRC,'sage')) sage: filename = os.path.join(root,'doctest','sources.py') sage: cwd = os.getcwd() sage: os.chdir(root) sage: FDS = FileDocTestSource(filename,DocTestDefaults(randorder=0,abspath=False)) sage: FDS.printpath 'doctest/sources.py' sage: FDS = FileDocTestSource(filename,DocTestDefaults(randorder=0,abspath=True)) sage: FDS.printpath '.../sage/doctest/sources.py' sage: os.chdir(cwd) """ if self.options.abspath: return os.path.abspath(self.path) else: relpath = os.path.relpath(self.path) if relpath.startswith(".." + os.path.sep): return self.path else: return relpath @lazy_attribute def basename(self): """ The basename of this file source, e.g. sage.doctest.sources EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','rings','integer.pyx') sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS.basename 'sage.rings.integer' """ return get_basename(self.path) @lazy_attribute def in_lib(self): """ Whether this file is to be treated as a module in a Python package. Such files aren't loaded before running tests. This uses :func:`~sage.misc.package_dir.is_package_or_sage_namespace_package_dir` but can be overridden via :class:`~sage.doctest.control.DocTestDefaults`. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC, 'sage', 'rings', 'integer.pyx') sage: FDS = FileDocTestSource(filename, DocTestDefaults()) sage: FDS.in_lib True sage: filename = os.path.join(SAGE_SRC, 'sage', 'doctest', 'tests', 'abort.rst') sage: FDS = FileDocTestSource(filename, DocTestDefaults()) sage: FDS.in_lib False You can override the default:: sage: FDS = FileDocTestSource("hello_world.py",DocTestDefaults()) sage: FDS.in_lib False sage: FDS = FileDocTestSource("hello_world.py",DocTestDefaults(force_lib=True)) sage: FDS.in_lib True """ return (self.options.force_lib or is_package_or_sage_namespace_package_dir(os.path.dirname(self.path))) def create_doctests(self, namespace): r""" Return a list of doctests for this file. INPUT: - ``namespace`` -- a dictionary or :class:`sage.doctest.util.RecordingDict`. OUTPUT: - ``doctests`` -- a list of doctests defined in this file. - ``extras`` -- a dictionary EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py') sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: doctests, extras = FDS.create_doctests(globals()) sage: len(doctests) 41 sage: extras['tab'] False We give a self referential example:: sage: doctests[18].name 'sage.doctest.sources.FileDocTestSource.create_doctests' sage: doctests[18].examples[10].source 'doctests[Integer(18)].examples[Integer(10)].source\n' TESTS: We check that we correctly process results that depend on 32 vs 64 bit architecture:: sage: import sys sage: bitness = '64' if sys.maxsize > (1 << 32) else '32' sage: gp.get_precision() == 38 False # 32-bit True # 64-bit sage: ex = doctests[18].examples[13] sage: (bitness == '64' and ex.want == 'True \n') or (bitness == '32' and ex.want == 'False \n') True We check that lines starting with a # aren't doctested:: #sage: raise RuntimeError """ if not os.path.exists(self.path): import errno raise IOError(errno.ENOENT, "File does not exist", self.path) base, filename = os.path.split(self.path) _, ext = os.path.splitext(filename) if not self.in_lib and ext in ('.py', '.pyx', '.sage', '.spyx'): cwd = os.getcwd() if base: os.chdir(base) try: load(filename, namespace) # errors raised here will be caught in DocTestTask finally: os.chdir(cwd) self.qualified_name = NestedName(self.basename) return self._create_doctests(namespace) def _test_enough_doctests(self, check_extras=True, verbose=True): r""" This function checks to see that the doctests are not getting unexpectedly skipped. It uses a different (and simpler) code path than the doctest creation functions, so there are a few files in Sage that it counts incorrectly. INPUT: - ``check_extras`` -- bool (default ``True``), whether to check if doctests are created that do not correspond to either a ``sage:`` or a ``>>>`` prompt - ``verbose`` -- bool (default ``True``), whether to print offending line numbers when there are missing or extra tests TESTS:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: cwd = os.getcwd() sage: os.chdir(SAGE_SRC) sage: import itertools sage: for path, dirs, files in itertools.chain(os.walk('sage'), os.walk('doc')): # long time ....: path = os.path.relpath(path) ....: dirs.sort(); files.sort() ....: for F in files: ....: _, ext = os.path.splitext(F) ....: if ext in ('.py', '.pyx', '.pxd', '.pxi', '.sage', '.spyx', '.rst'): ....: filename = os.path.join(path, F) ....: FDS = FileDocTestSource(filename, DocTestDefaults(long=True, optional=True, force_lib=True)) ....: FDS._test_enough_doctests(verbose=False) There are 3 unexpected tests being run in sage/doctest/parsing.py There are 1 unexpected tests being run in sage/doctest/reporting.py sage: os.chdir(cwd) """ expected = [] rest = isinstance(self, RestSource) if rest: skipping = False in_block = False last_line = '' for lineno, line in self: if not line.strip(): continue if rest: if line.strip().startswith(".. nodoctest"): return # We need to track blocks in order to figure out whether we're skipping. if in_block: indent = whitespace.match(line).end() if indent <= starting_indent: in_block = False skipping = False if not in_block: m1 = double_colon.match(line) m2 = code_block.match(line.lower()) starting = (m1 and not line.strip().startswith(".. ")) or m2 if starting: if ".. skip" in last_line: skipping = True in_block = True starting_indent = whitespace.match(line).end() last_line = line if (not rest or in_block) and sagestart.match(line) and not ((rest and skipping) or untested.search(line.lower())): expected.append(lineno+1) actual = [] tests, _ = self.create_doctests({}) for dt in tests: if dt.examples: for ex in dt.examples[:-1]: # the last entry is a sig_on_count() actual.append(dt.lineno + ex.lineno + 1) shortfall = sorted(set(expected).difference(set(actual))) extras = sorted(set(actual).difference(set(expected))) if len(actual) == len(expected): if not shortfall: return dif = extras[0] - shortfall[0] for e, s in zip(extras[1:],shortfall[1:]): if dif != e - s: break else: print("There are %s tests in %s that are shifted by %s" % (len(shortfall), self.path, dif)) if verbose: print(" The correct line numbers are %s" % (", ".join(str(n) for n in shortfall))) return elif len(actual) < len(expected): print("There are %s tests in %s that are not being run" % (len(expected) - len(actual), self.path)) elif check_extras: print("There are %s unexpected tests being run in %s" % (len(actual) - len(expected), self.path)) if verbose: if shortfall: print(" Tests on lines %s are not run" % (", ".join(str(n) for n in shortfall))) if check_extras and extras: print(" Tests on lines %s seem extraneous" % (", ".join(str(n) for n in extras))) class SourceLanguage: """ An abstract class for functions that depend on the programming language of a doctest source. Currently supported languages include Python, ReST and LaTeX. """ def parse_docstring(self, docstring, namespace, start): """ Return a list of doctest defined in this docstring. This function is called by :meth:`DocTestSource._process_doc`. The default implementation, defined here, is to use the :class:`sage.doctest.parsing.SageDocTestParser` attached to this source to get doctests from the docstring. INPUT: - ``docstring`` -- a string containing documentation and tests. - ``namespace`` -- a dictionary or :class:`sage.doctest.util.RecordingDict`. - ``start`` -- an integer, one less than the starting line number EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.doctest.parsing import SageDocTestParser sage: from sage.doctest.util import NestedName sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','util.py') sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: doctests, _ = FDS.create_doctests({}) sage: for dt in doctests: ....: FDS.qualified_name = dt.name ....: dt.examples = dt.examples[:-1] # strip off the sig_on() test ....: assert(FDS.parse_docstring(dt.docstring,{},dt.lineno-1)[0] == dt) """ return [self.parser.get_doctest(docstring, namespace, str(self.qualified_name), self.printpath, start + 1)] class PythonSource(SourceLanguage): """ This class defines the functions needed for the extraction of doctests from python sources. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py') sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: type(FDS) <class 'sage.doctest.sources.PythonFileSource'> """ # The same line can't both start and end a docstring start_finish_can_overlap = False def _init(self): """ This function is called before creating doctests from a Python source. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py') sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS._init() sage: FDS.last_indent -1 """ self.last_indent = -1 self.last_line = None self.quotetype = None self.paren_count = 0 self.bracket_count = 0 self.curly_count = 0 self.code_wrapping = False def _update_quotetype(self, line): r""" Updates the track of what kind of quoted string we're in. We need to track whether we're inside a triple quoted string, since a triple quoted string that starts a line could be the end of a string and thus not the beginning of a doctest (see sage.misc.sageinspect for an example). To do this tracking we need to track whether we're inside a string at all, since ''' inside a string doesn't start a triple quote (see the top of this file for an example). We also need to track parentheses and brackets, since we only want to update our record of last line and indentation level when the line is actually over. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py') sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS._init() sage: FDS._update_quotetype('\"\"\"'); print(" ".join(list(FDS.quotetype))) " " " sage: FDS._update_quotetype("'''"); print(" ".join(list(FDS.quotetype))) " " " sage: FDS._update_quotetype('\"\"\"'); print(FDS.quotetype) None sage: FDS._update_quotetype("triple_quotes = re.compile(\"\\s*[rRuU]*((''')|(\\\"\\\"\\\"))\")") sage: print(FDS.quotetype) None sage: FDS._update_quotetype("''' Single line triple quoted string \\''''") sage: print(FDS.quotetype) None sage: FDS._update_quotetype("' Lots of \\\\\\\\'") sage: print(FDS.quotetype) None """ def _update_parens(start,end=None): self.paren_count += line.count("(",start,end) - line.count(")",start,end) self.bracket_count += line.count("[",start,end) - line.count("]",start,end) self.curly_count += line.count("{",start,end) - line.count("}",start,end) pos = 0 while pos < len(line): if self.quotetype is None: next_single = line.find("'",pos) next_double = line.find('"',pos) if next_single == -1 and next_double == -1: next_comment = line.find("#",pos) if next_comment == -1: _update_parens(pos) else: _update_parens(pos,next_comment) break elif next_single == -1: m = next_double elif next_double == -1: m = next_single else: m = min(next_single, next_double) next_comment = line.find('#',pos,m) if next_comment != -1: _update_parens(pos,next_comment) break _update_parens(pos,m) if m+2 < len(line) and line[m] == line[m+1] == line[m+2]: self.quotetype = line[m:m+3] pos = m+3 else: self.quotetype = line[m] pos = m+1 else: next = line.find(self.quotetype,pos) if next == -1: break elif next == 0 or line[next-1] != '\\': pos = next + len(self.quotetype) self.quotetype = None else: # We need to worry about the possibility that # there are an even number of backslashes before # the quote, in which case it is not escaped count = 1 slashpos = next - 2 while slashpos >= pos and line[slashpos] == '\\': count += 1 slashpos -= 1 if count % 2 == 0: pos = next + len(self.quotetype) self.quotetype = None else: # The possible ending quote was escaped. pos = next + 1 def starting_docstring(self, line): """ Determines whether the input line starts a docstring. If the input line does start a docstring (a triple quote), then this function updates ``self.qualified_name``. INPUT: - ``line`` -- a string, one line of an input file OUTPUT: - either None or a Match object. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.doctest.util import NestedName sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py') sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS._init() sage: FDS.starting_docstring("r'''") <...Match object...> sage: FDS.ending_docstring("'''") <...Match object...> sage: FDS.qualified_name = NestedName(FDS.basename) sage: FDS.starting_docstring("class MyClass():") sage: FDS.starting_docstring(" def hello_world(self):") sage: FDS.starting_docstring(" '''") <...Match object...> sage: FDS.qualified_name sage.doctest.sources.MyClass.hello_world sage: FDS.ending_docstring(" '''") <...Match object...> sage: FDS.starting_docstring("class NewClass():") sage: FDS.starting_docstring(" '''") <...Match object...> sage: FDS.ending_docstring(" '''") <...Match object...> sage: FDS.qualified_name sage.doctest.sources.NewClass sage: FDS.starting_docstring("print(") sage: FDS.starting_docstring(" '''Not a docstring") sage: FDS.starting_docstring(" ''')") sage: FDS.starting_docstring("def foo():") sage: FDS.starting_docstring(" '''This is a docstring'''") <...Match object...> """ indent = whitespace.match(line).end() quotematch = None if self.quotetype is None and not self.code_wrapping: # We're not inside a triple quote and not inside code like # print( # """Not a docstring # """) if line[indent] != '#' and (indent == 0 or indent > self.last_indent): quotematch = triple_quotes.match(line) # It would be nice to only run the name_regex when # quotematch wasn't None, but then we mishandle classes # that don't have a docstring. if not self.code_wrapping and self.last_indent >= 0 and indent > self.last_indent: name = name_regex.match(self.last_line) if name: name = name.groups()[0] self.qualified_name[indent] = name elif quotematch: self.qualified_name[indent] = '?' self._update_quotetype(line) if line[indent] != '#' and not self.code_wrapping: self.last_line, self.last_indent = line, indent self.code_wrapping = not (self.paren_count == self.bracket_count == self.curly_count == 0) return quotematch def ending_docstring(self, line): r""" Determines whether the input line ends a docstring. INPUT: - ``line`` -- a string, one line of an input file. OUTPUT: - an object that, when evaluated in a boolean context, gives True or False depending on whether the input line marks the end of a docstring. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.doctest.util import NestedName sage: from sage.env import SAGE_SRC sage: import os sage: filename = os.path.join(SAGE_SRC,'sage','doctest','sources.py') sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS._init() sage: FDS.quotetype = "'''" sage: FDS.ending_docstring("'''") <...Match object...> sage: FDS.ending_docstring('\"\"\"') """ quotematch = triple_quotes.match(line) if quotematch is not None and quotematch.groups()[0] != self.quotetype: quotematch = None self._update_quotetype(line) return quotematch def _neutralize_doctests(self, reindent): r""" Return a string containing the source of ``self``, but with doctests modified so they are not tested. This function is used in creating doctests for ReST files, since docstrings of Python functions defined inside verbatim blocks screw up Python's doctest parsing. INPUT: - ``reindent`` -- an integer, the number of spaces to indent the result. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import StringDocTestSource, PythonSource sage: from sage.structure.dynamic_class import dynamic_class sage: s = "'''\n sage: 2 + 2\n 4\n'''" sage: PythonStringSource = dynamic_class('PythonStringSource',(StringDocTestSource, PythonSource)) sage: PSS = PythonStringSource('<runtime>', s, DocTestDefaults(), 'runtime') sage: print(PSS._neutralize_doctests(0)) ''' safe: 2 + 2 4 ''' """ neutralized = [] in_docstring = False self._init() for lineno, line in self: if not line.strip(): neutralized.append(line) elif in_docstring: if self.ending_docstring(line): in_docstring = False neutralized.append(" "*reindent + find_prompt.sub(r"\1safe:\3",line)) else: if self.starting_docstring(line): in_docstring = True neutralized.append(" "*reindent + line) return "".join(neutralized) class TexSource(SourceLanguage): """ This class defines the functions needed for the extraction of doctests from a LaTeX source. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: filename = "sage_paper.tex" sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: type(FDS) <class 'sage.doctest.sources.TexFileSource'> """ # The same line can't both start and end a docstring start_finish_can_overlap = False def _init(self): """ This function is called before creating doctests from a Tex file. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: filename = "sage_paper.tex" sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS._init() sage: FDS.skipping False """ self.skipping = False def starting_docstring(self, line): r""" Determines whether the input line starts a docstring. Docstring blocks in tex files are defined by verbatim or lstlisting environments, and can be linked together by adding %link immediately after the \end{verbatim} or \end{lstlisting}. Within a verbatim (or lstlisting) block, you can tell Sage not to process the rest of the block by including a %skip line. INPUT: - ``line`` -- a string, one line of an input file OUTPUT: - a boolean giving whether the input line marks the start of a docstring (verbatim block). EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: filename = "sage_paper.tex" sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS._init() We start docstrings with \begin{verbatim} or \begin{lstlisting}:: sage: FDS.starting_docstring(r"\begin{verbatim}") True sage: FDS.starting_docstring(r"\begin{lstlisting}") True sage: FDS.skipping False sage: FDS.ending_docstring("sage: 2+2") False sage: FDS.ending_docstring("4") False To start ignoring the rest of the verbatim block, use %skip:: sage: FDS.ending_docstring("%skip") True sage: FDS.skipping True sage: FDS.starting_docstring("sage: raise RuntimeError") False You can even pretend to start another verbatim block while skipping:: sage: FDS.starting_docstring(r"\begin{verbatim}") False sage: FDS.skipping True To stop skipping end the verbatim block:: sage: FDS.starting_docstring(r"\end{verbatim} %link") False sage: FDS.skipping False Linking works even when the block was ended while skipping:: sage: FDS.linking True sage: FDS.starting_docstring(r"\begin{verbatim}") True """ if self.skipping: if self.ending_docstring(line, check_skip=False): self.skipping = False return False return bool(begin_verb.match(line) or begin_lstli.match(line)) def ending_docstring(self, line, check_skip=True): r""" Determines whether the input line ends a docstring. Docstring blocks in tex files are defined by verbatim or lstlisting environments, and can be linked together by adding %link immediately after the \end{verbatim} or \end{lstlisting}. Within a verbatim (or lstlisting) block, you can tell Sage not to process the rest of the block by including a %skip line. INPUT: - ``line`` -- a string, one line of an input file - ``check_skip`` -- boolean (default True), used internally in starting_docstring. OUTPUT: - a boolean giving whether the input line marks the end of a docstring (verbatim block). EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: filename = "sage_paper.tex" sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS._init() sage: FDS.ending_docstring(r"\end{verbatim}") True sage: FDS.ending_docstring(r"\end{lstlisting}") True sage: FDS.linking False Use %link to link with the next verbatim block:: sage: FDS.ending_docstring(r"\end{verbatim}%link") True sage: FDS.linking True %skip also ends a docstring block:: sage: FDS.ending_docstring("%skip") True """ m = end_verb.match(line) if m: if m.groups()[0]: self.linking = True else: self.linking = False return True m = end_lstli.match(line) if m: if m.groups()[0]: self.linking = True else: self.linking = False return True if check_skip and skip.match(line): self.skipping = True return True return False class RestSource(SourceLanguage): """ This class defines the functions needed for the extraction of doctests from ReST sources. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: filename = "sage_doc.rst" sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: type(FDS) <class 'sage.doctest.sources.RestFileSource'> """ # The same line can both start and end a docstring start_finish_can_overlap = True def _init(self): """ This function is called before creating doctests from a ReST file. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: filename = "sage_doc.rst" sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS._init() sage: FDS.link_all False """ self.link_all = False self.last_line = "" self.last_indent = -1 self.first_line = False self.skipping = False def starting_docstring(self, line): """ A line ending with a double colon starts a verbatim block in a ReST file, as does a line containing ``.. CODE-BLOCK:: language``. This function also determines whether the docstring block should be joined with the previous one, or should be skipped. INPUT: - ``line`` -- a string, one line of an input file OUTPUT: - either None or a Match object. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: filename = "sage_doc.rst" sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS._init() sage: FDS.starting_docstring("Hello world::") True sage: FDS.ending_docstring(" sage: 2 + 2") False sage: FDS.ending_docstring(" 4") False sage: FDS.ending_docstring("We are now done") True sage: FDS.starting_docstring(".. link") sage: FDS.starting_docstring("::") True sage: FDS.linking True """ if link_all.match(line): self.link_all = True if self.skipping: end_block = self.ending_docstring(line) if end_block: self.skipping = False else: return False m1 = double_colon.match(line) m2 = code_block.match(line.lower()) starting = (m1 and not line.strip().startswith(".. ")) or m2 if starting: self.linking = self.link_all or '.. link' in self.last_line self.first_line = True m = m1 or m2 indent = len(m.groups()[0]) if '.. skip' in self.last_line: self.skipping = True starting = False else: indent = self.last_indent self.last_line, self.last_indent = line, indent return starting def ending_docstring(self, line): """ When the indentation level drops below the initial level the block ends. INPUT: - ``line`` -- a string, one line of an input file OUTPUT: - a boolean, whether the verbatim block is ending. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: filename = "sage_doc.rst" sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS._init() sage: FDS.starting_docstring("Hello world::") True sage: FDS.ending_docstring(" sage: 2 + 2") False sage: FDS.ending_docstring(" 4") False sage: FDS.ending_docstring("We are now done") True """ if not line.strip(): return False indent = whitespace.match(line).end() if self.first_line: self.first_line = False if indent <= self.last_indent: # We didn't indent at all return True self.last_indent = indent return indent < self.last_indent def parse_docstring(self, docstring, namespace, start): r""" Return a list of doctest defined in this docstring. Code blocks in a REST file can contain python functions with their own docstrings in addition to in-line doctests. We want to include the tests from these inner docstrings, but Python's doctesting module has a problem if we just pass on the whole block, since it expects to get just a docstring, not the Python code as well. Our solution is to create a new doctest source from this code block and append the doctests created from that source. We then replace the occurrences of "sage:" and ">>>" occurring inside a triple quote with "safe:" so that the doctest module doesn't treat them as tests. EXAMPLES:: sage: from sage.doctest.control import DocTestDefaults sage: from sage.doctest.sources import FileDocTestSource sage: from sage.doctest.parsing import SageDocTestParser sage: from sage.doctest.util import NestedName sage: filename = "sage_doc.rst" sage: FDS = FileDocTestSource(filename,DocTestDefaults()) sage: FDS.parser = SageDocTestParser(set(['sage'])) sage: FDS.qualified_name = NestedName('sage_doc') sage: s = "Some text::\n\n def example_python_function(a, \ ....: b):\n '''\n Brief description \ ....: of function.\n\n EXAMPLES::\n\n \ ....: sage: test1()\n sage: test2()\n \ ....: '''\n return a + b\n\n sage: test3()\n\nMore \ ....: ReST documentation." sage: tests = FDS.parse_docstring(s, {}, 100) sage: len(tests) 2 sage: for ex in tests[0].examples: ....: print(ex.sage_source) test3() sage: for ex in tests[1].examples: ....: print(ex.sage_source) test1() test2() sig_on_count() # check sig_on/off pairings (virtual doctest) """ PythonStringSource = dynamic_class("sage.doctest.sources.PythonStringSource", (StringDocTestSource, PythonSource)) min_indent = self.parser._min_indent(docstring) pysource = '\n'.join(l[min_indent:] for l in docstring.split('\n')) inner_source = PythonStringSource(self.basename, pysource, self.options, self.printpath, lineno_shift=start + 1) inner_doctests, _ = inner_source._create_doctests(namespace, True) safe_docstring = inner_source._neutralize_doctests(min_indent) outer_doctest = self.parser.get_doctest(safe_docstring, namespace, str(self.qualified_name), self.printpath, start + 1) return [outer_doctest] + inner_doctests class DictAsObject(dict): """ A simple subclass of dict that inserts the items from the initializing dictionary into attributes. EXAMPLES:: sage: from sage.doctest.sources import DictAsObject sage: D = DictAsObject({'a':2}) sage: D.a 2 """ def __init__(self, attrs): """ Initialization. INPUT: - ``attrs`` -- a dictionary. EXAMPLES:: sage: from sage.doctest.sources import DictAsObject sage: D = DictAsObject({'a':2}) sage: D.a == D['a'] True sage: D.a 2 """ super().__init__(attrs) self.__dict__.update(attrs) def __setitem__(self, ky, val): """ We preserve the ability to access entries through either the dictionary or attribute interfaces. EXAMPLES:: sage: from sage.doctest.sources import DictAsObject sage: D = DictAsObject({}) sage: D['a'] = 2 sage: D.a 2 """ super().__setitem__(ky, val) try: super().__setattr__(ky, val) except TypeError: pass def __setattr__(self, ky, val): """ We preserve the ability to access entries through either the dictionary or attribute interfaces. EXAMPLES:: sage: from sage.doctest.sources import DictAsObject sage: D = DictAsObject({}) sage: D.a = 2 sage: D['a'] 2 """ super().__setitem__(ky, val) super().__setattr__(ky, val)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/doctest/sources.py
0.438785
0.192027
sources.py
pypi
import io import os import zipfile from sage.cpython.string import bytes_to_str from sage.structure.sage_object import SageObject from sage.misc.cachefunc import cached_method INNER_HTML_TEMPLATE = """ <html> <head> <style> * {{ margin: 0; padding: 0; overflow: hidden; }} body, html {{ height: 100%; width: 100%; }} </style> <script type="text/javascript" src="{path_to_jsmol}/JSmol.min.js"></script> </head> <body> <script type="text/javascript"> delete Jmol._tracker; // Prevent JSmol from phoning home. var script = {script}; var Info = {{ width: '{width}', height: '{height}', debug: false, disableInitialConsole: true, // very slow when used with inline mesh color: '#3131ff', addSelectionOptions: false, use: 'HTML5', j2sPath: '{path_to_jsmol}/j2s', script: script, }}; var jmolApplet0 = Jmol.getApplet('jmolApplet0', Info); </script> </body> </html> """ IFRAME_TEMPLATE = """ <iframe srcdoc="{escaped_inner_html}" width="{width}" height="{height}" style="border: 0;"> </iframe> """ OUTER_HTML_TEMPLATE = """ <html> <head> <title>JSmol 3D Scene</title> </head> </body> {iframe} </body> </html> """.format(iframe=IFRAME_TEMPLATE) class JSMolHtml(SageObject): def __init__(self, jmol, path_to_jsmol=None, width='100%', height='100%'): """ INPUT: - ``jmol`` -- 3-d graphics or :class:`sage.repl.rich_output.output_graphics3d.OutputSceneJmol` instance. The 3-d scene to show. - ``path_to_jsmol`` -- string (optional, default is ``'/nbextensions/jupyter-jsmol/jsmol'``). The path (relative or absolute) where ``JSmol.min.js`` is served on the web server. - ``width`` -- integer or string (optional, default: ``'100%'``). The width of the JSmol applet using CSS dimensions. - ``height`` -- integer or string (optional, default: ``'100%'``). The height of the JSmol applet using CSS dimensions. EXAMPLES:: sage: from sage.repl.display.jsmol_iframe import JSMolHtml sage: JSMolHtml(sphere(), width=500, height=300) JSmol Window 500x300 """ from sage.repl.rich_output.output_graphics3d import OutputSceneJmol if not isinstance(jmol, OutputSceneJmol): jmol = jmol._rich_repr_jmol() self._jmol = jmol self._zip = zipfile.ZipFile(io.BytesIO(self._jmol.scene_zip.get())) if path_to_jsmol is None: self._path = os.path.join('/', 'nbextensions', 'jupyter-jsmol', 'jsmol') else: self._path = path_to_jsmol self._width = width self._height = height @cached_method def script(self): r""" Return the JMol script file. This method extracts the Jmol script from the Jmol spt file (a zip archive) and inlines meshes. OUTPUT: String. EXAMPLES:: sage: from sage.repl.display.jsmol_iframe import JSMolHtml sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol sage: jsmol = JSMolHtml(OutputSceneJmol.example(), width=500, height=300) sage: jsmol.script() 'data "model list"\n10\nempt...aliasdisplay on;\n' """ script = [] with self._zip.open('SCRIPT') as SCRIPT: for line in SCRIPT: if line.startswith(b'pmesh'): command, obj, meshfile = line.split(b' ', 3) assert command == b'pmesh' if meshfile not in [b'dots\n', b'mesh\n']: assert (meshfile.startswith(b'"') and meshfile.endswith(b'"\n')) meshfile = bytes_to_str(meshfile[1:-2]) # strip quotes script += [ 'pmesh {0} inline "'.format(bytes_to_str(obj)), bytes_to_str(self._zip.open(meshfile).read()), '"\n' ] continue script += [bytes_to_str(line)] return ''.join(script) def js_script(self): r""" The :meth:`script` as Javascript string. Since the many shortcomings of Javascript include multi-line strings, this actually returns Javascript code to reassemble the script from a list of strings. OUTPUT: String. Javascript code that evaluates to :meth:`script` as Javascript string. EXAMPLES:: sage: from sage.repl.display.jsmol_iframe import JSMolHtml sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol sage: jsmol = JSMolHtml(OutputSceneJmol.example(), width=500, height=300) sage: print(jsmol.js_script()) [ 'data "model list"', ... 'isosurface fullylit; pmesh o* fullylit; set antialiasdisplay on;', ].join('\n'); """ script = [r"["] for line in self.script().splitlines(): script += [r" '{0}',".format(line)] script += [r"].join('\n');"] return '\n'.join(script) def _repr_(self): """ Return as string representation OUTPUT: String. EXAMPLES:: sage: from sage.repl.display.jsmol_iframe import JSMolHtml sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol sage: JSMolHtml(OutputSceneJmol.example(), width=500, height=300)._repr_() 'JSmol Window 500x300' """ return 'JSmol Window {0}x{1}'.format(self._width, self._height) def inner_html(self): """ Return a HTML document containing a JSmol applet EXAMPLES:: sage: from sage.repl.display.jsmol_iframe import JSMolHtml sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol sage: jmol = JSMolHtml(OutputSceneJmol.example(), width=500, height=300) sage: print(jmol.inner_html()) <html> <head> <style> * { margin: 0; padding: 0; ... </html> """ return INNER_HTML_TEMPLATE.format( script=self.js_script(), width=self._width, height=self._height, path_to_jsmol=self._path, ) def iframe(self): """ Return HTML iframe OUTPUT: String. EXAMPLES:: sage: from sage.repl.display.jsmol_iframe import JSMolHtml sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol sage: jmol = JSMolHtml(OutputSceneJmol.example()) sage: print(jmol.iframe()) <iframe srcdoc=" ... </iframe> """ escaped_inner_html = self.inner_html().replace('"', '&quot;') return IFRAME_TEMPLATE.format(width=self._width, height=self._height, escaped_inner_html=escaped_inner_html) def outer_html(self): """ Return a HTML document containing an iframe with a JSmol applet OUTPUT: String EXAMPLES:: sage: from sage.repl.display.jsmol_iframe import JSMolHtml sage: from sage.repl.rich_output.output_graphics3d import OutputSceneJmol sage: jmol = JSMolHtml(OutputSceneJmol.example(), width=500, height=300) sage: print(jmol.outer_html()) <html> <head> <title>JSmol 3D Scene</title> </head> </body> <BLANKLINE> <iframe srcdoc=" ... </html> """ escaped_inner_html = self.inner_html().replace('"', '&quot;') outer = OUTER_HTML_TEMPLATE.format( script=self.js_script(), width=self._width, height=self._height, escaped_inner_html=escaped_inner_html, ) return outer
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/repl/display/jsmol_iframe.py
0.664867
0.198219
jsmol_iframe.py
pypi
import os import errno import warnings from sage.env import ( SAGE_DOC, SAGE_VENV, SAGE_EXTCODE, SAGE_VERSION, THREEJS_DIR, ) class SageKernelSpec(): def __init__(self, prefix=None): """ Utility to manage SageMath kernels and extensions INPUT: - ``prefix`` -- (optional, default: ``sys.prefix``) directory for the installation prefix EXAMPLES:: sage: from sage.repl.ipython_kernel.install import SageKernelSpec sage: prefix = tmp_dir() sage: spec = SageKernelSpec(prefix=prefix) sage: spec._display_name # random output 'SageMath 6.9' sage: spec.kernel_dir == SageKernelSpec(prefix=prefix).kernel_dir True """ self._display_name = 'SageMath {0}'.format(SAGE_VERSION) if prefix is None: from sys import prefix jupyter_dir = os.path.join(prefix, "share", "jupyter") self.nbextensions_dir = os.path.join(jupyter_dir, "nbextensions") self.kernel_dir = os.path.join(jupyter_dir, "kernels", self.identifier()) self._mkdirs() def _mkdirs(self): """ Create necessary parent directories EXAMPLES:: sage: from sage.repl.ipython_kernel.install import SageKernelSpec sage: spec = SageKernelSpec(prefix=tmp_dir()) sage: spec._mkdirs() sage: os.path.isdir(spec.nbextensions_dir) True """ def mkdir_p(path): try: os.makedirs(path) except OSError: if not os.path.isdir(path): raise mkdir_p(self.nbextensions_dir) mkdir_p(self.kernel_dir) @classmethod def identifier(cls): """ Internal identifier for the SageMath kernel OUTPUT: the string ``"sagemath"``. EXAMPLES:: sage: from sage.repl.ipython_kernel.install import SageKernelSpec sage: SageKernelSpec.identifier() 'sagemath' """ return 'sagemath' def symlink(self, src, dst): """ Symlink ``src`` to ``dst`` This is not an atomic operation. Already-existing symlinks will be deleted, already existing non-empty directories will be kept. EXAMPLES:: sage: from sage.repl.ipython_kernel.install import SageKernelSpec sage: spec = SageKernelSpec(prefix=tmp_dir()) sage: path = tmp_dir() sage: spec.symlink(os.path.join(path, 'a'), os.path.join(path, 'b')) sage: os.listdir(path) ['b'] """ try: os.remove(dst) except OSError as err: if err.errno == errno.EEXIST: return os.symlink(src, dst) def use_local_threejs(self): """ Symlink threejs to the Jupyter notebook. EXAMPLES:: sage: from sage.repl.ipython_kernel.install import SageKernelSpec sage: spec = SageKernelSpec(prefix=tmp_dir()) sage: spec.use_local_threejs() sage: threejs = os.path.join(spec.nbextensions_dir, 'threejs-sage') sage: os.path.isdir(threejs) True """ src = THREEJS_DIR dst = os.path.join(self.nbextensions_dir, 'threejs-sage') self.symlink(src, dst) def _kernel_cmd(self): """ Helper to construct the SageMath kernel command. OUTPUT: List of strings. The command to start a new SageMath kernel. EXAMPLES:: sage: from sage.repl.ipython_kernel.install import SageKernelSpec sage: spec = SageKernelSpec(prefix=tmp_dir()) sage: spec._kernel_cmd() ['/.../sage', '--python', '-m', 'sage.repl.ipython_kernel', '-f', '{connection_file}'] """ return [ os.path.join(SAGE_VENV, 'bin', 'sage'), '--python', '-m', 'sage.repl.ipython_kernel', '-f', '{connection_file}', ] def kernel_spec(self): """ Return the kernel spec as Python dictionary OUTPUT: A dictionary. See the Jupyter documentation for details. EXAMPLES:: sage: from sage.repl.ipython_kernel.install import SageKernelSpec sage: spec = SageKernelSpec(prefix=tmp_dir()) sage: spec.kernel_spec() {'argv': ..., 'display_name': 'SageMath ...', 'language': 'sage'} """ return dict( argv=self._kernel_cmd(), display_name=self._display_name, language='sage', ) def _install_spec(self): """ Install the SageMath Jupyter kernel EXAMPLES:: sage: from sage.repl.ipython_kernel.install import SageKernelSpec sage: spec = SageKernelSpec(prefix=tmp_dir()) sage: spec._install_spec() """ jsonfile = os.path.join(self.kernel_dir, "kernel.json") import json with open(jsonfile, 'w') as f: json.dump(self.kernel_spec(), f) def _symlink_resources(self): """ Symlink miscellaneous resources This method symlinks additional resources (like the SageMath documentation) into the SageMath kernel directory. This is necessary to make the help links in the notebook work. EXAMPLES:: sage: from sage.repl.ipython_kernel.install import SageKernelSpec sage: spec = SageKernelSpec(prefix=tmp_dir()) sage: spec._install_spec() sage: spec._symlink_resources() """ path = os.path.join(SAGE_EXTCODE, 'notebook-ipython') for filename in os.listdir(path): self.symlink( os.path.join(path, filename), os.path.join(self.kernel_dir, filename) ) self.symlink( SAGE_DOC, os.path.join(self.kernel_dir, 'doc') ) @classmethod def update(cls, *args, **kwds): """ Configure the Jupyter notebook for the SageMath kernel This method does everything necessary to use the SageMath kernel, you should never need to call any of the other methods directly. EXAMPLES:: sage: from sage.repl.ipython_kernel.install import SageKernelSpec sage: SageKernelSpec.update(prefix=tmp_dir()) """ instance = cls(*args, **kwds) instance.use_local_threejs() instance._install_spec() instance._symlink_resources() @classmethod def check(cls): """ Check that the SageMath kernel can be discovered by its name (sagemath). This method issues a warning if it cannot -- either because it is not installed, or it is shadowed by a different kernel of this name, or Jupyter is misconfigured in a different way. EXAMPLES:: sage: from sage.repl.ipython_kernel.install import SageKernelSpec sage: SageKernelSpec.check() # random """ from jupyter_client.kernelspec import get_kernel_spec, NoSuchKernel ident = cls.identifier() try: spec = get_kernel_spec(ident) except NoSuchKernel: warnings.warn(f'no kernel named {ident} is accessible; ' 'check your Jupyter configuration ' '(see https://docs.jupyter.org/en/latest/use/jupyter-directories.html)') else: from pathlib import Path if Path(spec.argv[0]).resolve() != Path(os.path.join(SAGE_VENV, 'bin', 'sage')).resolve(): warnings.warn(f'the kernel named {ident} does not seem to correspond to this ' 'installation of SageMath; check your Jupyter configuration ' '(see https://docs.jupyter.org/en/latest/use/jupyter-directories.html)') def have_prerequisites(debug=True): """ Check that we have all prerequisites to run the Jupyter notebook. In particular, the Jupyter notebook requires OpenSSL whether or not you are using https. See :trac:`17318`. INPUT: ``debug`` -- boolean (default: ``True``). Whether to print debug information in case that prerequisites are missing. OUTPUT: Boolean. EXAMPLES:: sage: from sage.repl.ipython_kernel.install import have_prerequisites sage: have_prerequisites(debug=False) in [True, False] True """ try: from notebook.notebookapp import NotebookApp return True except ImportError: if debug: import traceback traceback.print_exc() return False
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/repl/ipython_kernel/install.py
0.451327
0.153835
install.py
pypi
import os from xml.dom.minidom import parse from sage.rings.rational_field import QQ from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing class SymbolicData: """ Database of ideals as distributed by The SymbolicData Project (http://symbolicdata.org). This class needs the optional ``database_symbolic_data`` package to be installed. """ def __init__(self): """ EXAMPLES:: sage: sd = SymbolicData(); sd # optional - database_symbolic_data SymbolicData with 372 ideals """ from sage.env import SAGE_SHARE path = os.path.join(SAGE_SHARE, 'symbolic_data') self.__intpath = path + "/Data/XMLResources/INTPS/" self.__genpath = path + "/Data/XMLResources/GenPS/" def get_ideal(self, name, base_ring=QQ, term_order="degrevlex"): """ Return the ideal given by 'name' over the base ring given by 'base_ring' in a polynomial ring with the term order given by 'term_order'. INPUT: - ``name`` - name as on the symbolic data website - ``base_ring`` - base ring for the polynomial ring (default: ``QQ``) - ``term_order`` - term order for the polynomial ring (default: ``degrevlex``) OUTPUT: ideal as given by ``name`` in ``PolynomialRing(base_ring,vars,term_order)`` EXAMPLES:: sage: sd = SymbolicData() # optional - database_symbolic_data sage: sd.get_ideal('Katsura_3',GF(127),'degrevlex') # optional - database_symbolic_data Ideal (u0 + 2*u1 + 2*u2 + 2*u3 - 1, u1^2 + 2*u0*u2 + 2*u1*u3 - u2, 2*u0*u1 + 2*u1*u2 + 2*u2*u3 - u1, u0^2 + 2*u1^2 + 2*u2^2 + 2*u3^2 - u0) of Multivariate Polynomial Ring in u0, u1, u2, u3 over Finite Field of size 127 """ def _getTextFromNode(node): t = "" for n in node.childNodes: if n.nodeType == n.TEXT_NODE: t += str(n.nodeValue) else: raise TypeError('not a text node') return t def _dom2ideal(node): """ """ l = [] if str(node.nodeName) in ['vars', 'poly']: l.append(_getTextFromNode(node)) for c in node.childNodes: l += _dom2ideal(c) return l orig_name = name name = name.replace('__', '.') try: name = self.__intpath + name + ".xml" open(name) except IOError: try: name = self.__genpath + name + ".xml" open(name) except IOError: raise AttributeError("No ideal matching '%s' found in database." % orig_name) dom = parse(name) res = _dom2ideal(dom) variables, polys = res[0].replace("_", ""), [p.replace("_", "") for p in res[1:]] P = PolynomialRing(base_ring, len(variables.split(",")), variables) I = P.ideal([P(f) for f in polys]) return I def __repr__(self): """ EXAMPLES:: sage: sd = SymbolicData(); sd # optional - database_symbolic_data SymbolicData with 372 ideals """ try: l = len(self.__dir__()) except AttributeError: l = 0 return "SymbolicData with %d ideals" % l def __getattr__(self, name): """ EXAMPLES:: sage: sd = SymbolicData() # optional - database_symbolic_data sage: sd.Cyclic5 # optional - database_symbolic_data Traceback (most recent call last): ... AttributeError: No ideal matching 'Cyclic5' found in database. sage: sd.Cyclic_5 # optional - database_symbolic_data Ideal (v + w + x + y + z, v*w + w*x + x*y + v*z + y*z, v*w*x + w*x*y + v*w*z + v*y*z + x*y*z, v*w*x*y + v*w*x*z + v*w*y*z + v*x*y*z + w*x*y*z, v*w*x*y*z - 1) of Multivariate Polynomial Ring in v, w, x, y, z over Rational Field """ return self.get_ideal(name) def __dir__(self): """ EXAMPLES:: sage: sd = SymbolicData() # optional - database_symbolic_data sage: sorted(sd.__dir__())[:10] # optional - database_symbolic_data ['Bjoerk_8', 'Bronstein-86', 'Buchberger-87', 'Butcher', 'Caprasse', 'Cassou', 'Cohn_2', 'Curves__curve10_20', 'Curves__curve10_20', 'Curves__curve10_30'] """ if hasattr(self, "__ideals"): return self.__ideals try: __ideals = [s.replace('.xml', '') for s in os.listdir(self.__intpath)] __ideals += [s.replace('.xml', '') for s in os.listdir(self.__genpath)] self.__ideals = [s.replace('.', '__') for s in __ideals] return self.__ideals except OSError: raise AttributeError("Could not find symbolic data, you should perhaps install the optional package")
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/databases/symbolic_data.py
0.742982
0.421373
symbolic_data.py
pypi
import bz2 import os from sage.cpython.string import bytes_to_str def _dbz_to_string(name): r""" TESTS:: sage: from sage.databases.db_modular_polynomials import _dbz_to_string sage: _dbz_to_string('PolMod/Atk/pol.002.dbz') # optional - database_kohel '3 0 1 \n2 1 -1 \n2 0 744 \n1 1 -1 \n1 0 184512 \n0 2 1 \n0 1 7256 \n0 0 15252992 \n' sage: _dbz_to_string('PolMod/Cls/pol.001.dbz') # optional - database_kohel '1 0 1 \n' sage: _dbz_to_string('PolMod/Eta/pol.002.dbz') # optional - database_kohel '3 0 1 \n2 0 48 \n1 1 -1 \n1 0 768 \n0 0 4096 \n' sage: _dbz_to_string('PolMod/EtaCrr/crr.02.002.dbz') # optional - database_kohel '2 1 1 \n2 0 -48 \n1 1 2304 \n0 2 -4096 \n0 1 196608 \n' sage: _dbz_to_string('PolHeeg/Cls/0000001-0005000/pol.0000003.dbz') # optional - database_kohel '0\n1\n' """ from sage.env import SAGE_SHARE dblocation = os.path.join(SAGE_SHARE, 'kohel') filename = os.path.join(dblocation, name) try: with open(filename, 'rb') as f: data = bz2.decompress(f.read()) except IOError: raise ValueError('file not found in the Kohel database') return bytes_to_str(data) def _dbz_to_integer_list(name): r""" TESTS:: sage: from sage.databases.db_modular_polynomials import _dbz_to_integer_list sage: _dbz_to_integer_list('PolMod/Atk/pol.002.dbz') # optional - database_kohel [[3, 0, 1], [2, 1, -1], [2, 0, 744], [1, 1, -1], [1, 0, 184512], [0, 2, 1], [0, 1, 7256], [0, 0, 15252992]] sage: _dbz_to_integer_list('PolMod/Cls/pol.001.dbz') # optional - database_kohel [[1, 0, 1]] sage: _dbz_to_integer_list('PolMod/Eta/pol.002.dbz') # optional - database_kohel [[3, 0, 1], [2, 0, 48], [1, 1, -1], [1, 0, 768], [0, 0, 4096]] """ from sage.rings.integer import Integer data = _dbz_to_string(name) return [[Integer(v) for v in row.strip().split(" ")] for row in data.split("\n")[:-1]] def _dbz_to_integers(name): r""" TESTS:: sage: from sage.databases.db_modular_polynomials import _dbz_to_integers sage: _dbz_to_integers('PolHeeg/Cls/0000001-0005000/pol.0000003.dbz') # optional - database_kohel [0, 1] """ from sage.rings.integer import Integer return [Integer(i) for i in _dbz_to_string(name).split()] class ModularPolynomialDatabase: def _dbpath(self, level): r""" TESTS:: sage: C = ClassicalModularPolynomialDatabase() sage: C._dbpath(3) 'PolMod/Cls/pol.003.dbz' sage: C._dbpath(8) 'PolMod/Cls/pol.008.dbz' """ return "PolMod/%s/pol.%03d.dbz" % (self.model, level) def __repr__(self): r""" EXAMPLES:: sage: ClassicalModularPolynomialDatabase() Classical modular polynomial database sage: DedekindEtaModularPolynomialDatabase() Dedekind eta modular polynomial database sage: DedekindEtaModularPolynomialDatabase() Dedekind eta modular polynomial database sage: AtkinModularPolynomialDatabase() Atkin modular polynomial database """ if self.model.startswith("Cls"): head = "Classical" elif self.model.startswith("Atk"): head = "Atkin" elif self.model.startswith("Eta"): head = "Dedekind eta" if self.model.endswith("Crr"): poly = "correspondence" else: poly = "polynomial" return "%s modular %s database" % (head, poly) def __getitem__(self, level): """ Return the modular polynomial of given level, or an error if there is no such polynomial in the database. EXAMPLES:: sage: DBMP = ClassicalModularPolynomialDatabase() sage: f = DBMP[29] # optional - database_kohel sage: f.degree() # optional - database_kohel 58 sage: f.coefficient([28,28]) # optional - database_kohel 400152899204646997840260839128 sage: DBMP[50] # optional - database_kohel Traceback (most recent call last): ... ValueError: file not found in the Kohel database """ from sage.rings.integer import Integer from sage.rings.integer_ring import IntegerRing from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing if self.model in ("Atk", "Eta"): level = Integer(level) if not level.is_prime(): raise TypeError("Argument level (= %s) must be prime." % level) elif self.model in ("AtkCrr", "EtaCrr"): N = Integer(level[0]) if N not in (2, 3, 5, 7, 13): raise TypeError("Argument level (= %s) must be prime." % N) modpol = self._dbpath(level) coeff_list = _dbz_to_integer_list(modpol) if self.model == "Cls": P = PolynomialRing(IntegerRing(), 2, "j") else: P = PolynomialRing(IntegerRing(), 2, "x,j") poly = {} if self.model == "Cls": if level == 1: return P({(1, 0): 1, (0, 1): -1}) for cff in coeff_list: i = cff[0] j = cff[1] poly[(i, j)] = Integer(cff[2]) if i != j: poly[(j, i)] = Integer(cff[2]) else: for cff in coeff_list: poly[(cff[0], cff[1])] = Integer(cff[2]) return P(poly) class ModularCorrespondenceDatabase(ModularPolynomialDatabase): def _dbpath(self, level): r""" TESTS:: sage: DB = DedekindEtaModularCorrespondenceDatabase() sage: DB._dbpath((2,4)) 'PolMod/EtaCrr/crr.02.004.dbz' """ (Nlevel, crrlevel) = level return "PolMod/%s/crr.%02d.%03d.dbz" % (self.model, Nlevel, crrlevel) class ClassicalModularPolynomialDatabase(ModularPolynomialDatabase): """ The database of classical modular polynomials, i.e. the polynomials Phi_N(X,Y) relating the j-functions j(q) and j(q^N). """ model = "Cls" class DedekindEtaModularPolynomialDatabase(ModularPolynomialDatabase): """ The database of modular polynomials Phi_N(X,Y) relating a quotient of Dedekind eta functions, well-defined on X_0(N), relating x(q) and the j-function j(q). """ model = "Eta" class DedekindEtaModularCorrespondenceDatabase(ModularCorrespondenceDatabase): r""" The database of modular correspondences in `X_0(p) \times X_0(p)`, where the model of the curves `X_0(p) = \Bold{P}^1` are specified by quotients of Dedekind's eta function. """ model = "EtaCrr" class AtkinModularPolynomialDatabase(ModularPolynomialDatabase): """ The database of modular polynomials Phi(x,j) for `X_0(p)`, where x is a function on invariant under the Atkin-Lehner invariant, with pole of minimal order at infinity. """ model = "Atk" class AtkinModularCorrespondenceDatabase(ModularCorrespondenceDatabase): model = "AtkCrr"
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/databases/db_modular_polynomials.py
0.644001
0.254845
db_modular_polynomials.py
pypi
import bz2 import os import re from urllib.request import urlretrieve import ssl from sage.misc.verbose import verbose from sage.env import SAGE_SHARE from sage.rings.integer_ring import ZZ class SloaneEncyclopediaClass: """ A local copy of the Sloane Online Encyclopedia of Integer Sequences that contains only the sequence numbers and the sequences themselves. """ def __init__(self): """ Initialize the database but do not load any of the data. """ self.__path__ = os.path.join(SAGE_SHARE, 'sloane') self.__file__ = os.path.join(self.__path__, 'sloane-oeis.bz2') self.__file_names__ = os.path.join(self.__path__, 'sloane-names.bz2') self.__loaded__ = False self.__loaded_names__ = False def __repr__(self): """ String representation of this database. OUTPUT: str """ return "Local copy of Sloane Online Encyclopedia of Integer Sequences" def __iter__(self): """ Return an iterator through the encyclopedia. Elements are of the form [number, sequence]. """ for i in self.__data__: yield [i, self[i]] def __getitem__(self, N): """ Return sequence N in the encyclopedia. If sequence N does not exist, return []. INPUT: - ``N`` -- int OUTPUT: list """ self.load() if N not in self.__data__: # sequence N does not exist return [] if self.__data__[N][1] is None: # list N has not been created yet list = self.__data__[N][2].strip(',').split(',') self.__data__[N][1] = [ZZ(n) for n in list] return self.__data__[N][1] def __len__(self): """ Return the number of sequences in the encyclopedia. """ self.load() return len(self.__data__) def find(self, seq, maxresults=30): """ Return a list of all sequences which have seq as a subsequence, up to maxresults results. Sequences are returned in the form (number, list). INPUT: - ``seq`` -- list - ``maxresults`` -- int OUTPUT: list of 2-tuples (i, v), where v is a sequence with seq as a subsequence. """ self.load() answer, nanswer = [], 0 pattern = re.sub(r'[\[\]]', ',', str(seq).replace(' ', '')) for i in self.__data__: if self.__data__[i][2].find(pattern) != -1: answer.append((i, self[i])) nanswer = nanswer + 1 if nanswer == maxresults: return answer return answer def install(self, oeis_url="https://oeis.org/stripped.gz", names_url="https://oeis.org/names.gz", overwrite=False): """ Download and install the online encyclopedia, raising an IOError if either step fails. INPUT: - ``oeis_url`` - string (default: "https://oeis.org...") The URL of the stripped.gz encyclopedia file. - ``names_url`` - string (default: "https://oeis.org...") The URL of the names.gz encyclopedia file. If you do not want to download this file, set names_url=None. - ``overwrite`` - boolean (default: False) If the encyclopedia is already installed and overwrite=True, download and install the latest version over the installed one. """ # See if the encyclopedia already exists if not overwrite and os.path.exists(self.__file__): raise IOError("Sloane encyclopedia is already installed") tm = verbose("Downloading stripped version of Sloane encyclopedia") ssl._create_default_https_context = ssl.create_default_context try: fname, _ = urlretrieve(oeis_url) except IOError as msg: raise IOError("%s\nError fetching the following website:\n %s\nTry checking your internet connection." % (msg, oeis_url)) if names_url is not None: try: nname, _ = urlretrieve(names_url) except IOError as msg: raise IOError("%s\nError fetching the following website:\n %s\nTry checking your internet connection." % (msg, names_url)) else: nname = None verbose("Finished downloading", tm) self.install_from_gz(fname, nname, overwrite) # Delete the temporary downloaded files os.remove(fname) if nname is not None: os.remove(nname) def install_from_gz(self, stripped_file, names_file, overwrite=False): """ Install the online encyclopedia from a local stripped.gz file. INPUT: - ``stripped_file`` - string. The name of the stripped.gz OEIS file. - ``names_file`` - string. The name of the names.gz OEIS file, or None if the user does not want it installed. - ``overwrite`` - boolean (default: False) If the encyclopedia is already installed and overwrite=True, install 'filename' over the old encyclopedia. """ if not overwrite and os.path.exists(self.__file__): raise IOError("Sloane encyclopedia is already installed") copy_gz_file(stripped_file, self.__file__) if names_file is not None: copy_gz_file(names_file, self.__file_names__) else: # Delete old copies of names.gz since their sequence numbers # probably will not match the newly installed stripped.gz if os.path.exists(self.__file_names__): os.remove(self.__file_names__) # Remove the old database from memory so the new one will be # automatically loaded next time the user tries to access it self.unload() def load(self): """ Load the entire encyclopedia into memory from a file. This is done automatically if the user tries to perform a lookup or a search. """ if self.__loaded__: return try: file_seq = bz2.BZ2File(self.__file__, 'r') except IOError: raise IOError("The Sloane Encyclopedia database must be installed. Use e.g. 'SloaneEncyclopedia.install()' to download and install it.") self.__data__ = {} tm = verbose("Loading Sloane encyclopedia from disk") entry = re.compile(r'A(?P<num>\d{6}) ,(?P<body>.*),$') for L in file_seq: if len(L) == 0: continue m = entry.search(L) if m: seqnum = int(m.group('num')) msg = m.group('body').strip() self.__data__[seqnum] = [seqnum, None, ',' + msg + ',', None] file_seq.close() try: file_names = bz2.BZ2File(self.__file_names__, 'r') entry = re.compile(r'A(?P<num>\d{6}) (?P<body>.*)$') for L in file_names: if not L: continue m = entry.search(L) if m: seqnum = int(m.group('num')) self.__data__[seqnum][3] = m.group('body').strip() file_names.close() self.__loaded_names__ = True except KeyError: # Some sequence in the names file is not in the database raise KeyError("Sloane OEIS sequence and name files do not match. Try reinstalling, e.g. SloaneEncyclopedia.install(overwrite=True).") except IOError: # The names database is not installed self.__loaded_names__ = False verbose("Finished loading", tm) self.__loaded__ = True def sequence_name(self, N): """ Return the name of sequence ``N`` in the encyclopedia. If sequence ``N`` does not exist, return ``''``. If the names database is not installed, raise an ``IOError``. INPUT: - ``N`` -- int OUTPUT: string EXAMPLES:: sage: SloaneEncyclopedia.sequence_name(1) # optional - sloane_database 'Number of groups of order n.' """ self.load() if not self.__loaded_names__: raise IOError("The Sloane OEIS names file is not installed. Try reinstalling, e.g. SloaneEncyclopedia.install(overwrite=True).") if N not in self.__data__: # sequence N does not exist return '' return self.__data__[N][3] def unload(self): """ Remove the database from memory. """ if not self.__loaded__: return del self.__data__ self.__loaded__ = False self.__loaded_names__ = False SloaneEncyclopedia = SloaneEncyclopediaClass() def copy_gz_file(gz_source, bz_destination): """ Decompress a gzipped file and install the bzipped version. This is used by SloaneEncyclopedia.install_from_gz to install several gzipped OEIS database files. INPUT: - ``gz_source`` -- string. The name of the gzipped file. - ``bz_destination`` -- string. The name of the newly compressed file. """ import gzip # Read the gzipped input try: gz_input = gzip.open(gz_source, 'r') db_text = gz_input.read() gz_input.close() except IOError as msg: raise IOError("Error reading gzipped input file:\n%s" % msg) # Write the bzipped output try: os.makedirs(os.path.dirname(bz_destination), exist_ok=True) bz2_output = bz2.BZ2File(bz_destination, 'w') bz2_output.write(db_text) bz2_output.close() except IOError as msg: raise IOError("Error writing bzipped output file:\n%s" % msg)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/databases/sloane.py
0.565059
0.190837
sloane.py
pypi
"Operators" import operator from sage.symbolic.ring import is_SymbolicVariable, SR def add_vararg(first, *rest): r""" Return the sum of all the arguments. INPUT: - ``first``, ``*rest`` -- arguments to add OUTPUT: sum of the arguments EXAMPLES:: sage: from sage.symbolic.operators import add_vararg sage: add_vararg(1, 2, 3, 4, 5, 6, 7) 28 sage: x = SR.var('x') sage: s = 1 + x + x^2 # symbolic sum sage: bool(s.operator()(*s.operands()) == s) True """ for r in rest: first = first + r return first def mul_vararg(first, *rest): r""" Return the product of all the arguments. INPUT: - ``first``, ``*rest`` -- arguments to multiply OUTPUT: product of the arguments EXAMPLES:: sage: from sage.symbolic.operators import mul_vararg sage: mul_vararg(9, 8, 7, 6, 5, 4) 60480 sage: x = SR.var('x') sage: p = x * cos(x) * sin(x) # symbolic product sage: bool(p.operator()(*p.operands()) == p) True """ for r in rest: first = first * r return first arithmetic_operators = {add_vararg: '+', mul_vararg: '*', operator.add: '+', operator.sub: '-', operator.mul: '*', operator.truediv: '/', operator.floordiv: '//', operator.pow: '^'} relation_operators = {operator.eq:'==', operator.lt:'<', operator.gt:'>', operator.ne:'!=', operator.le:'<=', operator.ge:'>='} class FDerivativeOperator(): r""" Function derivative operators. A function derivative operator represents a partial derivative of a function with respect to some variables. The underlying data are the function, and the parameter set, a list recording the indices of the variables with respect to which the partial derivative is taken. """ def __init__(self, function, parameter_set): r""" Initialize this function derivative operator. EXAMPLES:: sage: from sage.symbolic.operators import FDerivativeOperator sage: f = function('foo') sage: op = FDerivativeOperator(f, [0, 1]) sage: loads(dumps(op)) D[0, 1](foo) """ self._f = function self._parameter_set = [int(_) for _ in parameter_set] def __call__(self, *args): r""" Call this function derivative operator on these arguments. EXAMPLES:: sage: from sage.symbolic.operators import FDerivativeOperator sage: x, y = SR.var('x, y') sage: f = function('foo') sage: op = FDerivativeOperator(f, [0, 1]) sage: op(x, y) diff(foo(x, y), x, y) sage: op(x, x^2) D[0, 1](foo)(x, x^2) TESTS: We should be able to operate on functions evaluated at a point, not just a symbolic variable, :trac:`12796`:: sage: from sage.symbolic.operators import FDerivativeOperator sage: f = function('f') sage: op = FDerivativeOperator(f, [0]) sage: op(1) D[0](f)(1) """ if (not all(is_SymbolicVariable(x) for x in args) or len(args) != len(set(args))): # An evaluated derivative of the form f'(1) is not a # symbolic variable, yet we would like to treat it # like one. So, we replace the argument `1` with a # temporary variable e.g. `t0` and then evaluate the # derivative f'(t0) symbolically at t0=1. See trac # #12796. temp_args = SR.temp_var(n=len(args)) vars = [temp_args[i] for i in self._parameter_set] return self._f(*temp_args).diff(*vars).function(*temp_args)(*args) vars = [args[i] for i in self._parameter_set] return self._f(*args).diff(*vars) def __repr__(self): r""" Return the string representation of this function derivative operator. EXAMPLES:: sage: from sage.symbolic.operators import FDerivativeOperator sage: f = function('foo') sage: op = FDerivativeOperator(f, [0, 1]); op D[0, 1](foo) """ return "D[%s](%s)" % (", ".join(map(repr, self._parameter_set)), self._f) def function(self): r""" Return the function associated to this function derivative operator. EXAMPLES:: sage: from sage.symbolic.operators import FDerivativeOperator sage: f = function('foo') sage: op = FDerivativeOperator(f, [0, 1]) sage: op.function() foo """ return self._f def change_function(self, new): r""" Return a new function derivative operator with the same parameter set but for a new function. sage: from sage.symbolic.operators import FDerivativeOperator sage: f = function('foo') sage: b = function('bar') sage: op = FDerivativeOperator(f, [0, 1]) sage: op.change_function(bar) D[0, 1](bar) """ return FDerivativeOperator(new, self._parameter_set) def parameter_set(self): r""" Return the parameter set of this function derivative operator. This is the list of indices of variables with respect to which the derivative is taken. EXAMPLES:: sage: from sage.symbolic.operators import FDerivativeOperator sage: f = function('foo') sage: op = FDerivativeOperator(f, [0, 1]) sage: op.parameter_set() [0, 1] """ return self._parameter_set
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/symbolic/operators.py
0.814385
0.653846
operators.py
pypi
r""" Benchmarks Tests that will take a long time if something is wrong, but be very quick otherwise. See https://wiki.sagemath.org/symbench. The parameters chosen below are such that with pynac most of these take well less than a second, but would not even be feasible using Sage's Maxima-based symbolics. Problem R1 Important note. Below we do s.expand().real() because s.real() takes forever (TODO?). :: sage: f(z) = sqrt(1/3)*z^2 + i/3 sage: s = f(f(f(f(f(f(f(f(f(f(i/2)))))))))) sage: s.expand().real() -15323490199844318074242473679071410934833494247466385771803570370858961112774390851798166656796902695599442662754502211584226105508648298600018090510170430216881977761279503642801008178271982531042720727178135881702924595044672634313417239327304576652633321095875724771887486594852083526001648217317718794685379391946143663292907934545842931411982264788766619812559999515408813796287448784343854980686798782575952258163992236113752353237705088451481168691158059505161807961082162315225057299394348203539002582692884735745377391416638540520323363224931163680324690025802009761307137504963304640835891588925883135078996398616361571065941964628043214890356454145039464055430143/160959987592246947739944859375773744043416001841910423046466880402863187009126824419781711398533250016237703449459397319370100476216445123130147322940019839927628599479294678599689928643570237983736966305423831947366332466878486992676823215303312139985015592974537721140932243906832125049776934072927576666849331956351862828567668505777388133331284248870175178634054430823171923639987569211668426477739974572402853248951261366399284257908177157179099041115431335587887276292978004143353025122721401971549897673882099546646236790739903146970578001092018346524464799146331225822142880459202800229013082033028722077703362360159827236163041299500992177627657014103138377287073792*sqrt(1/3) Problem R2:: sage: def hermite(n,y): ....: if n == 1: return 2*y ....: if n == 0: return 1 ....: return expand(2*y*hermite(n-1,y) - 2*(n-1)*hermite(n-2,y)) sage: hermite(15,var('y')) 32768*y^15 - 1720320*y^13 + 33546240*y^11 - 307507200*y^9 + 1383782400*y^7 - 2905943040*y^5 + 2421619200*y^3 - 518918400*y Problem R3:: sage: f = sum(var('x,y,z')); a = [bool(f==f) for _ in range(100000)] Problem R4:: sage: u = [e,pi,sqrt(2)]; Tuples(u,3).cardinality() 27 Problem R5:: sage: def blowup(L,n): ....: for i in [0..n]: ....: L.append( (L[i] + L[i+1]) * L[i+2] ) sage: L = list(var('x,y,z')) sage: blowup(L,15) sage: len(set(L)) 19 Problem R6:: sage: sum(((x+sin(i))/x+(x-sin(i))/x) for i in range(100)).expand() 200 Problem R7:: sage: f = x^24+34*x^12+45*x^3+9*x^18 +34*x^10+ 32*x^21 sage: a = [f(x=random()) for _ in range(10^4)] Problem R10:: sage: v = [float(z) for z in [-pi,-pi+1/100..,pi]] Problem R11:: sage: a = [random() + random()*I for w in [0..100]] sage: a.sort() Problem W3:: sage: acos(cos(x)) arccos(cos(x)) PROBLEM S1:: sage: _ = var('x,y,z') sage: f = (x+y+z+1)^10 sage: g = expand(f*(f+1)) PROBLEM S2:: sage: _ = var('x,y') sage: a = expand((x^sin(x) + y^cos(y) - z^(x+y))^100) PROBLEM S3:: sage: _ = var('x,y,z') sage: f = expand((x^y + y^z + z^x)^50) sage: g = f.diff(x) PROBLEM S4:: sage: w = (sin(x)*cos(x)).series(x,400) """
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/symbolic/benchmark.py
0.517571
0.484868
benchmark.py
pypi
from sage.symbolic.expression import Expression from sage.symbolic.ring import SR def maxima_integrator(expression, v, a=None, b=None): """ Integration using Maxima EXAMPLES:: sage: from sage.symbolic.integration.external import maxima_integrator sage: maxima_integrator(sin(x), x) -cos(x) sage: maxima_integrator(cos(x), x) sin(x) sage: f(x) = function('f')(x) sage: maxima_integrator(f(x), x) integrate(f(x), x) TESTS: Check that :trac:`25817` is fixed:: sage: maxima_integrator(log(e^x*log(x)*sin(x))/x^2, x) 1/2*(x*(Ei(-log(x)) + conjugate(Ei(-log(x)))) - 2*x*integrate(sin(x)/(x*cos(x)^2 + x*sin(x)^2 + 2*x*cos(x) + x), x) + 2*x*integrate(sin(x)/(x*cos(x)^2 + x*sin(x)^2 - 2*x*cos(x) + x), x) + 2*x*log(x) + 2*log(2) - log(cos(x)^2 + sin(x)^2 + 2*cos(x) + 1) - log(cos(x)^2 + sin(x)^2 - 2*cos(x) + 1) - 2*log(log(x)))/x """ from sage.calculus.calculus import maxima if not isinstance(expression, Expression): expression = SR(expression) if a is None: result = maxima.sr_integral(expression, v) else: result = maxima.sr_integral(expression, v, a, b) return result._sage_() def sympy_integrator(expression, v, a=None, b=None): """ Integration using SymPy EXAMPLES:: sage: from sage.symbolic.integration.external import sympy_integrator sage: sympy_integrator(sin(x), x) -cos(x) sage: sympy_integrator(cos(x), x) sin(x) """ import sympy ex = expression._sympy_() v = v._sympy_() if a is None: result = sympy.integrate(ex, v) else: result = sympy.integrate(ex, (v, a._sympy_(), b._sympy_())) return result._sage_() def mma_free_integrator(expression, v, a=None, b=None): """ Integration using Mathematica's online integrator EXAMPLES:: sage: from sage.symbolic.integration.external import mma_free_integrator sage: mma_free_integrator(sin(x), x) # optional - internet -cos(x) A definite integral:: sage: mma_free_integrator(e^(-x), x, a=0, b=oo) # optional - internet 1 TESTS: Check that :trac:`18212` is resolved:: sage: var('y') # optional - internet y sage: result = integral(sin(y)^2, y, algorithm='mathematica_free') # optional - internet sage: result.simplify_trig() # optional - internet -1/2*cos(y)*sin(y) + 1/2*y Check that :trac:`14764` is resolved:: sage: integrate(x^2, x, 0, 1, algorithm="mathematica_free") # optional - internet 1/3 sage: integrate(sin(x), [x, 0, pi], algorithm="mathematica_free") # optional - internet 2 sage: integrate(sqrt(x), (x, 0, 1), algorithm="mathematica_free") # optional - internet 2/3 :: sage: mma_free_integrator(exp(-x^2)*log(x), x) # optional - internet 1/2*sqrt(pi)*erf(x)*log(x) - x*hypergeometric((1/2, 1/2), (3/2, 3/2), -x^2) """ from sage.interfaces.mathematica import request_wolfram_alpha, parse_moutput_from_json, symbolic_expression_from_mathematica_string math_expr = expression._mathematica_init_() variable = v._mathematica_init_() if a is None and b is None: input = "Integrate[{},{}]".format(math_expr, variable) elif a is not None and b is not None: input = "Integrate[{},{{{},{},{}}}]".format(math_expr, variable, a._mathematica_init_(), b._mathematica_init_()) else: raise ValueError('a(={}) and b(={}) should be both None' ' or both defined'.format(a, b)) json_page_data = request_wolfram_alpha(input) all_outputs = parse_moutput_from_json(json_page_data) if not all_outputs: raise ValueError("no outputs found in the answer from Wolfram Alpha") first_output = all_outputs[0] return symbolic_expression_from_mathematica_string(first_output) def fricas_integrator(expression, v, a=None, b=None, noPole=True): """ Integration using FriCAS EXAMPLES:: sage: from sage.symbolic.integration.external import fricas_integrator # optional - fricas sage: fricas_integrator(sin(x), x) # optional - fricas -cos(x) sage: fricas_integrator(cos(x), x) # optional - fricas sin(x) sage: fricas_integrator(1/(x^2-2), x, 0, 1) # optional - fricas -1/8*sqrt(2)*(log(2) - log(-24*sqrt(2) + 34)) sage: fricas_integrator(1/(x^2+6), x, -oo, oo) # optional - fricas 1/6*sqrt(6)*pi TESTS: Check that :trac:`25220` is fixed:: sage: integral(sqrt(1-cos(x)), x, 0, 2*pi, algorithm="fricas") # optional - fricas 4*sqrt(2) Check that in case of failure one gets unevaluated integral:: sage: integral(cos(ln(cos(x))), x, 0, pi/8, algorithm='fricas') # optional - fricas integrate(cos(log(cos(x))), x, 0, 1/8*pi) sage: integral(cos(ln(cos(x))), x, algorithm='fricas') # optional - fricas integral(cos(log(cos(x))), x) Check that :trac:`28641` is fixed:: sage: integrate(sqrt(2)*x^2 + 2*x, x, algorithm="fricas") # optional - fricas 1/3*sqrt(2)*x^3 + x^2 sage: integrate(sqrt(2), x, algorithm="fricas") # optional - fricas sqrt(2)*x sage: integrate(1, x, algorithm="fricas") # optional - fricas x Check that :trac:`28630` is fixed:: sage: f = polylog(3, x) sage: f.integral(x, algorithm='fricas') # optional - fricas -x*dilog(x) - (x - 1)*log(-x + 1) + x*polylog(3, x) + x Check that :trac:`29043` is fixed:: sage: var("a c d"); f = (I*a*tan(d*x + c) + a)*sec(d*x + c)^10 (a, c, d) sage: ii = integrate(f, x, algorithm="fricas") # optional - fricas sage: 1/315*(64512*I*a*e^(10*I*d*x + 10*I*c) + 53760*I*a*e^(8*I*d*x + 8*I*c) + 30720*I*a*e^(6*I*d*x + 6*I*c) + 11520*I*a*e^(4*I*d*x + 4*I*c) + 2560*I*a*e^(2*I*d*x + 2*I*c) + 256*I*a)/(d*e^(20*I*d*x + 20*I*c) + 10*d*e^(18*I*d*x + 18*I*c) + 45*d*e^(16*I*d*x + 16*I*c) + 120*d*e^(14*I*d*x + 14*I*c) + 210*d*e^(12*I*d*x + 12*I*c) + 252*d*e^(10*I*d*x + 10*I*c) + 210*d*e^(8*I*d*x + 8*I*c) + 120*d*e^(6*I*d*x + 6*I*c) + 45*d*e^(4*I*d*x + 4*I*c) + 10*d*e^(2*I*d*x + 2*I*c) + d) - ii # optional - fricas 0 """ if not isinstance(expression, Expression): expression = SR(expression) from sage.interfaces.fricas import fricas e_fricas = fricas(expression) v_fricas = fricas(v) if a is None: result = e_fricas.integrate(v_fricas) else: seg = fricas.equation(v_fricas, fricas.segment(a, b)) if noPole: result = e_fricas.integrate(seg, '"noPole"') else: result = e_fricas.integrate(seg) result = result.sage() if result == "failed": result = expression.integrate(v, a, b, hold=True) elif result == "potentialPole": raise ValueError("The integrand has a potential pole" " in the integration interval") return result def giac_integrator(expression, v, a=None, b=None): r""" Integration using Giac EXAMPLES:: sage: from sage.symbolic.integration.external import giac_integrator sage: giac_integrator(sin(x), x) -cos(x) sage: giac_integrator(1/(x^2+6), x, -oo, oo) 1/6*sqrt(6)*pi TESTS:: sage: giac_integrator(e^(-x^2)*log(x), x) integrate(e^(-x^2)*log(x), x) Check that :trac:`30133` is fixed:: sage: ee = SR.var('e') sage: giac_integrator(ee^x, x) e^x/log(e) sage: y = SR.var('π') sage: giac_integrator(cos(y), y) sin(π) Check that :trac:`29966` is fixed:: sage: giac_integrator(sqrt(x + sqrt(x)), x) 1/12*(2*sqrt(x)*(4*sqrt(x) + 1) - 3)*sqrt(x + sqrt(x))... """ ex = expression._giac_() if a is None: result = ex.integrate(v._giac_()) else: result = ex.integrate(v._giac_(), a._giac_(), b._giac_()) if 'integrate' in format(result) or 'integration' in format(result): return expression.integrate(v, a, b, hold=True) else: return result._sage_() def libgiac_integrator(expression, v, a=None, b=None): r""" Integration using libgiac EXAMPLES:: sage: import sage.libs.giac ... sage: from sage.symbolic.integration.external import libgiac_integrator sage: libgiac_integrator(sin(x), x) -cos(x) sage: libgiac_integrator(1/(x^2+6), x, -oo, oo) No checks were made for singular points of antiderivative... 1/6*sqrt(6)*pi TESTS:: sage: libgiac_integrator(e^(-x^2)*log(x), x) integrate(e^(-x^2)*log(x), x) The following integral fails with the Giac Pexpect interface, but works with libgiac (:trac:`31873`):: sage: a, x = var('a,x') sage: f = sec(2*a*x) sage: F = libgiac_integrator(f, x) ... sage: (F.derivative(x) - f).simplify_trig() 0 """ from sage.libs.giac import libgiac from sage.libs.giac.giac import Pygen # We call Pygen on first argument because otherwise some expressions # involving derivatives result in doctest failures in interfaces/sympy.py # -- related to the fixme note in sage.libs.giac.giac.GiacFunction.__call__ # regarding conversion of lists. if a is None: result = libgiac.integrate(Pygen(expression), v) else: result = libgiac.integrate(Pygen(expression), v, a, b) if 'integrate' in format(result) or 'integration' in format(result): return expression.integrate(v, a, b, hold=True) else: return result.sage()
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/symbolic/integration/external.py
0.814533
0.792544
external.py
pypi
from sage.structure.unique_representation import UniqueRepresentation from sage.structure.richcmp import richcmp_method, rich_to_bool class UnknownError(TypeError): """ Raised whenever :class:`Unknown` is used in a boolean operation. EXAMPLES:: sage: not Unknown Traceback (most recent call last): ... UnknownError: Unknown does not evaluate in boolean context """ pass @richcmp_method class UnknownClass(UniqueRepresentation): """ The Unknown truth value The ``Unknown`` object is used in Sage in several places as return value in addition to ``True`` and ``False``, in order to signal uncertainty about or inability to compute the result. ``Unknown`` can be identified using ``is``, or by catching :class:`UnknownError` from a boolean operation. .. WARNING:: Calling ``bool()`` with ``Unknown`` as argument will throw an ``UnknownError``. This also means that applying ``and``, ``not``, and ``or`` to ``Unknown`` might fail. TESTS:: sage: TestSuite(Unknown).run() """ def __repr__(self): """ TESTS:: sage: Unknown Unknown """ return "Unknown" def __bool__(self): """ When evaluated in a boolean context ``Unknown`` raises a ``UnknownError``. EXAMPLES:: sage: bool(Unknown) Traceback (most recent call last): ... UnknownError: Unknown does not evaluate in boolean context sage: not Unknown Traceback (most recent call last): ... UnknownError: Unknown does not evaluate in boolean context """ raise UnknownError('Unknown does not evaluate in boolean context') def __and__(self, other): """ The ``&`` logical operation. EXAMPLES:: sage: Unknown & False False sage: Unknown & Unknown Unknown sage: Unknown & True Unknown sage: Unknown.__or__(3) NotImplemented """ if other is False: return False elif other is True or other is Unknown: return self else: return NotImplemented def __or__(self, other): """ The ``|`` logical connector. EXAMPLES:: sage: Unknown | False Unknown sage: Unknown | Unknown Unknown sage: Unknown | True True sage: Unknown.__or__(3) NotImplemented """ if other is True: return True elif other is False or other is Unknown: return self else: return NotImplemented def __richcmp__(self, other, op): """ Comparison of truth value. EXAMPLES:: sage: l = [False, Unknown, True] sage: for a in l: print([a < b for b in l]) [False, True, True] [False, False, True] [False, False, False] sage: for a in l: print([a <= b for b in l]) [True, True, True] [False, True, True] [False, False, True] """ if other is self: return rich_to_bool(op, 0) if not isinstance(other, bool): return NotImplemented if other: return rich_to_bool(op, -1) else: return rich_to_bool(op, +1) Unknown = UnknownClass()
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/unknown.py
0.890847
0.523177
unknown.py
pypi
from functools import (partial, update_wrapper, WRAPPER_ASSIGNMENTS, WRAPPER_UPDATES) from copy import copy from sage.misc.sageinspect import (sage_getsource, sage_getsourcelines, sage_getargspec) from inspect import FullArgSpec def sage_wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES): r""" Decorator factory which should be used in decorators for making sure that meta-information on the decorated callables are retained through the decorator, such that the introspection functions of ``sage.misc.sageinspect`` retrieves them correctly. This includes documentation string, source, and argument specification. This is an extension of the Python standard library decorator functools.wraps. That the argument specification is retained from the decorated functions implies, that if one uses ``sage_wraps`` in a decorator which intentionally changes the argument specification, one should add this information to the special attribute ``_sage_argspec_`` of the wrapping function (for an example, see e.g. ``@options`` decorator in this module). EXAMPLES: Demonstrate that documentation string and source are retained from the decorated function:: sage: def square(f): ....: @sage_wraps(f) ....: def new_f(x): ....: return f(x)*f(x) ....: return new_f sage: @square ....: def g(x): ....: "My little function" ....: return x sage: g(2) 4 sage: g(x) x^2 sage: g.__doc__ 'My little function' sage: from sage.misc.sageinspect import sage_getsource, sage_getsourcelines, sage_getfile sage: sage_getsource(g) '@square...def g(x)...' Demonstrate that the argument description are retained from the decorated function through the special method (when left unchanged) (see :trac:`9976`):: sage: def diff_arg_dec(f): ....: @sage_wraps(f) ....: def new_f(y, some_def_arg=2): ....: return f(y+some_def_arg) ....: return new_f sage: @diff_arg_dec ....: def g(x): ....: return x sage: g(1) 3 sage: g(1, some_def_arg=4) 5 sage: from sage.misc.sageinspect import sage_getargspec sage: sage_getargspec(g) FullArgSpec(args=['x'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={}) Demonstrate that it correctly gets the source lines and the source file, which is essential for interactive code edition; note that we do not test the line numbers, as they may easily change:: sage: P.<x,y> = QQ[] sage: I = P*[x,y] sage: sage_getfile(I.interreduced_basis) # known bug '.../sage/rings/polynomial/multi_polynomial_ideal.py' sage: sage_getsourcelines(I.interreduced_basis) ([' @handle_AA_and_QQbar\n', ' @singular_gb_standard_options\n', ' @libsingular_gb_standard_options\n', ' def interreduced_basis(self):\n', ... ' return self.basis.reduced()\n'], ...) The ``f`` attribute of the decorated function refers to the original function:: sage: foo = object() sage: @sage_wraps(foo) ....: def func(): ....: pass sage: wrapped = sage_wraps(foo)(func) sage: wrapped.f is foo True Demonstrate that sage_wraps works for non-function callables (:trac:`9919`):: sage: def square_for_met(f): ....: @sage_wraps(f) ....: def new_f(self, x): ....: return f(self,x)*f(self,x) ....: return new_f sage: class T: ....: @square_for_met ....: def g(self, x): ....: "My little method" ....: return x sage: t = T() sage: t.g(2) 4 sage: t.g.__doc__ 'My little method' The bug described in :trac:`11734` is fixed:: sage: def square(f): ....: @sage_wraps(f) ....: def new_f(x): ....: return f(x)*f(x) ....: return new_f sage: f = lambda x:x^2 sage: g = square(f) sage: g(3) # this line used to fail for some people if these command were manually entered on the sage prompt 81 """ #TRAC 9919: Workaround for bug in @update_wrapper when used with #non-function callables. assigned = set(assigned).intersection(set(dir(wrapped))) #end workaround def f(wrapper, assigned=assigned, updated=updated): update_wrapper(wrapper, wrapped, assigned=assigned, updated=updated) # For backwards-compatibility with old versions of sage_wraps wrapper.f = wrapped # For forwards-compatibility with functools.wraps on Python 3 wrapper.__wrapped__ = wrapped wrapper._sage_src_ = lambda: sage_getsource(wrapped) wrapper._sage_src_lines_ = lambda: sage_getsourcelines(wrapped) #Getting the signature right in documentation by Sphinx (Trac 9976) #The attribute _sage_argspec_() is read by Sphinx if present and used #as the argspec of the function instead of using reflection. wrapper._sage_argspec_ = lambda: sage_getargspec(wrapped) return wrapper return f # Infix operator decorator class infix_operator(): """ A decorator for functions which allows for a hack that makes the function behave like an infix operator. This decorator exists as a convenience for interactive use. EXAMPLES: An infix dot product operator:: sage: @infix_operator('multiply') ....: def dot(a, b): ....: '''Dot product.''' ....: return a.dot_product(b) sage: u = vector([1, 2, 3]) sage: v = vector([5, 4, 3]) sage: u *dot* v 22 An infix element-wise addition operator:: sage: @infix_operator('add') ....: def eadd(a, b): ....: return a.parent([i + j for i, j in zip(a, b)]) sage: u = vector([1, 2, 3]) sage: v = vector([5, 4, 3]) sage: u +eadd+ v (6, 6, 6) sage: 2*u +eadd+ v (7, 8, 9) A hack to simulate a postfix operator:: sage: @infix_operator('or') ....: def thendo(a, b): ....: return b(a) sage: x |thendo| cos |thendo| (lambda x: x^2) cos(x)^2 """ operators = { 'add': {'left': '__add__', 'right': '__radd__'}, 'multiply': {'left': '__mul__', 'right': '__rmul__'}, 'or': {'left': '__or__', 'right': '__ror__'}, } def __init__(self, precedence): """ INPUT: - ``precedence`` -- one of ``'add'``, ``'multiply'``, or ``'or'`` indicating the new operator's precedence in the order of operations. """ self.precedence = precedence def __call__(self, func): """Returns a function which acts as an inline operator.""" left_meth = self.operators[self.precedence]['left'] right_meth = self.operators[self.precedence]['right'] wrapper_name = func.__name__ wrapper_members = { 'function': staticmethod(func), left_meth: _infix_wrapper._left, right_meth: _infix_wrapper._right, '_sage_src_': lambda: sage_getsource(func) } for attr in WRAPPER_ASSIGNMENTS: try: wrapper_members[attr] = getattr(func, attr) except AttributeError: pass wrapper = type(wrapper_name, (_infix_wrapper,), wrapper_members) wrapper_inst = wrapper() wrapper_inst.__dict__.update(getattr(func, '__dict__', {})) return wrapper_inst class _infix_wrapper(): function = None def __init__(self, left=None, right=None): """ Initialize the actual infix object, with possibly a specified left and/or right operand. """ self.left = left self.right = right def __call__(self, *args, **kwds): """Call the passed function.""" return self.function(*args, **kwds) def _left(self, right): """The function for the operation on the left (e.g., __add__).""" if self.left is None: if self.right is None: new = copy(self) new.right = right return new else: raise SyntaxError("Infix operator already has its " "right argument") else: return self.function(self.left, right) def _right(self, left): """The function for the operation on the right (e.g., __radd__).""" if self.right is None: if self.left is None: new = copy(self) new.left = left return new else: raise SyntaxError("Infix operator already has its " "left argument") else: return self.function(left, self.right) def decorator_defaults(func): """ This function allows a decorator to have default arguments. Normally, a decorator can be called with or without arguments. However, the two cases call for different types of return values. If a decorator is called with no parentheses, it should be run directly on the function. However, if a decorator is called with parentheses (i.e., arguments), then it should return a function that is then in turn called with the defined function as an argument. This decorator allows us to have these default arguments without worrying about the return type. EXAMPLES:: sage: from sage.misc.decorators import decorator_defaults sage: @decorator_defaults ....: def my_decorator(f,*args,**kwds): ....: print(kwds) ....: print(args) ....: print(f.__name__) sage: @my_decorator ....: def my_fun(a,b): ....: return a,b {} () my_fun sage: @my_decorator(3,4,c=1,d=2) ....: def my_fun(a,b): ....: return a,b {'c': 1, 'd': 2} (3, 4) my_fun """ @sage_wraps(func) def my_wrap(*args, **kwds): if len(kwds) == 0 and len(args) == 1: # call without parentheses return func(*args) else: return lambda f: func(f, *args, **kwds) return my_wrap class suboptions(): def __init__(self, name, **options): """ A decorator for functions which collects all keywords starting with ``name+'_'`` and collects them into a dictionary which will be passed on to the wrapped function as a dictionary called ``name_options``. The keyword arguments passed into the constructor are taken to be default for the ``name_options`` dictionary. EXAMPLES:: sage: from sage.misc.decorators import suboptions sage: s = suboptions('arrow', size=2) sage: s.name 'arrow_' sage: s.options {'size': 2} """ self.name = name + "_" self.options = options def __call__(self, func): """ Returns a wrapper around func EXAMPLES:: sage: from sage.misc.decorators import suboptions sage: def f(*args, **kwds): print(sorted(kwds.items())) sage: f = suboptions('arrow', size=2)(f) sage: f(size=2) [('arrow_options', {'size': 2}), ('size', 2)] sage: f(arrow_size=3) [('arrow_options', {'size': 3})] sage: f(arrow_options={'size':4}) [('arrow_options', {'size': 4})] sage: f(arrow_options={'size':4}, arrow_size=5) [('arrow_options', {'size': 5})] Demonstrate that the introspected argument specification of the wrapped function is updated (see :trac:`9976`). sage: from sage.misc.sageinspect import sage_getargspec sage: sage_getargspec(f) FullArgSpec(args=['arrow_size'], varargs='args', varkw='kwds', defaults=(2,), kwonlyargs=[], kwonlydefaults=None, annotations={}) """ @sage_wraps(func) def wrapper(*args, **kwds): suboptions = copy(self.options) suboptions.update(kwds.pop(self.name+"options", {})) # Collect all the relevant keywords in kwds # and put them in suboptions for key, value in list(kwds.items()): if key.startswith(self.name): suboptions[key[len(self.name):]] = value del kwds[key] kwds[self.name + "options"] = suboptions return func(*args, **kwds) # Add the options specified by @options to the signature of the wrapped # function in the Sphinx-generated documentation (Trac 9976), using the # special attribute _sage_argspec_ (see e.g. sage.misc.sageinspect) def argspec(): argspec = sage_getargspec(func) def listForNone(l): return l if l is not None else [] newArgs = [self.name + opt for opt in self.options.keys()] args = (argspec.args if argspec.args is not None else []) + newArgs defaults = (argspec.defaults if argspec.defaults is not None else ()) \ + tuple(self.options.values()) # Note: argspec.defaults is not always a tuple for some reason return FullArgSpec(args, argspec.varargs, argspec.varkw, defaults, kwonlyargs=[], kwonlydefaults=None, annotations={}) wrapper._sage_argspec_ = argspec return wrapper class options(): def __init__(self, **options): """ A decorator for functions which allows for default options to be set and reset by the end user. Additionally, if one needs to, one can get at the original keyword arguments passed into the decorator. TESTS:: sage: from sage.misc.decorators import options sage: o = options(rgbcolor=(0,0,1)) sage: o.options {'rgbcolor': (0, 0, 1)} sage: o = options(rgbcolor=(0,0,1), __original_opts=True) sage: o.original_opts True sage: loads(dumps(o)).options {'rgbcolor': (0, 0, 1)} Demonstrate that the introspected argument specification of the wrapped function is updated (see :trac:`9976`):: sage: from sage.misc.decorators import options sage: o = options(rgbcolor=(0,0,1)) sage: def f(*args, **kwds): ....: print("{} {}".format(args, sorted(kwds.items()))) sage: f1 = o(f) sage: from sage.misc.sageinspect import sage_getargspec sage: sage_getargspec(f1) FullArgSpec(args=['rgbcolor'], varargs='args', varkw='kwds', defaults=((0, 0, 1),), kwonlyargs=[], kwonlydefaults=None, annotations={}) """ self.options = options self.original_opts = options.pop('__original_opts', False) def __call__(self, func): """ EXAMPLES:: sage: from sage.misc.decorators import options sage: o = options(rgbcolor=(0,0,1)) sage: def f(*args, **kwds): ....: print("{} {}".format(args, sorted(kwds.items()))) sage: f1 = o(f) sage: f1() () [('rgbcolor', (0, 0, 1))] sage: f1(rgbcolor=1) () [('rgbcolor', 1)] sage: o = options(rgbcolor=(0,0,1), __original_opts=True) sage: f2 = o(f) sage: f2(alpha=1) () [('__original_opts', {'alpha': 1}), ('alpha', 1), ('rgbcolor', (0, 0, 1))] """ @sage_wraps(func) def wrapper(*args, **kwds): options = copy(wrapper.options) if self.original_opts: options['__original_opts'] = kwds options.update(kwds) return func(*args, **options) #Add the options specified by @options to the signature of the wrapped #function in the Sphinx-generated documentation (Trac 9976), using the #special attribute _sage_argspec_ (see e.g. sage.misc.sageinspect) def argspec(): argspec = sage_getargspec(func) args = ((argspec.args if argspec.args is not None else []) + list(self.options)) defaults = (argspec.defaults or ()) + tuple(self.options.values()) # Note: argspec.defaults is not always a tuple for some reason return FullArgSpec(args, argspec.varargs, argspec.varkw, defaults, kwonlyargs=[], kwonlydefaults=None, annotations={}) wrapper._sage_argspec_ = argspec def defaults(): """ Return the default options. EXAMPLES:: sage: from sage.misc.decorators import options sage: o = options(rgbcolor=(0,0,1)) sage: def f(*args, **kwds): ....: print("{} {}".format(args, sorted(kwds.items()))) sage: f = o(f) sage: f.options['rgbcolor']=(1,1,1) sage: f.defaults() {'rgbcolor': (0, 0, 1)} """ return copy(self.options) def reset(): """ Reset the options to the defaults. EXAMPLES:: sage: from sage.misc.decorators import options sage: o = options(rgbcolor=(0,0,1)) sage: def f(*args, **kwds): ....: print("{} {}".format(args, sorted(kwds.items()))) sage: f = o(f) sage: f.options {'rgbcolor': (0, 0, 1)} sage: f.options['rgbcolor']=(1,1,1) sage: f.options {'rgbcolor': (1, 1, 1)} sage: f() () [('rgbcolor', (1, 1, 1))] sage: f.reset() sage: f.options {'rgbcolor': (0, 0, 1)} sage: f() () [('rgbcolor', (0, 0, 1))] """ wrapper.options = copy(self.options) wrapper.options = copy(self.options) wrapper.reset = reset wrapper.reset.__doc__ = """ Reset the options to the defaults. Defaults: %s """ % self.options wrapper.defaults = defaults wrapper.defaults.__doc__ = """ Return the default options. Defaults: %s """ % self.options return wrapper class rename_keyword(): def __init__(self, deprecated=None, deprecation=None, **renames): """ A decorator which renames keyword arguments and optionally deprecates the new keyword. INPUT: - ``deprecation`` -- integer. The trac ticket number where the deprecation was introduced. - the rest of the arguments is a list of keyword arguments in the form ``renamed_option='existing_option'``. This will have the effect of renaming ``renamed_option`` so that the function only sees ``existing_option``. If both ``renamed_option`` and ``existing_option`` are passed to the function, ``existing_option`` will override the ``renamed_option`` value. EXAMPLES:: sage: from sage.misc.decorators import rename_keyword sage: r = rename_keyword(color='rgbcolor') sage: r.renames {'color': 'rgbcolor'} sage: loads(dumps(r)).renames {'color': 'rgbcolor'} To deprecate an old keyword:: sage: r = rename_keyword(deprecation=13109, color='rgbcolor') """ assert deprecated is None, 'Use @rename_keyword(deprecation=<trac_number>, ...)' self.renames = renames self.deprecation = deprecation def __call__(self, func): """ Rename keywords. EXAMPLES:: sage: from sage.misc.decorators import rename_keyword sage: r = rename_keyword(color='rgbcolor') sage: def f(*args, **kwds): ....: print("{} {}".format(args, kwds)) sage: f = r(f) sage: f() () {} sage: f(alpha=1) () {'alpha': 1} sage: f(rgbcolor=1) () {'rgbcolor': 1} sage: f(color=1) () {'rgbcolor': 1} We can also deprecate the renamed keyword:: sage: r = rename_keyword(deprecation=13109, deprecated_option='new_option') sage: def f(*args, **kwds): ....: print("{} {}".format(args, kwds)) sage: f = r(f) sage: f() () {} sage: f(alpha=1) () {'alpha': 1} sage: f(new_option=1) () {'new_option': 1} sage: f(deprecated_option=1) doctest:...: DeprecationWarning: use the option 'new_option' instead of 'deprecated_option' See http://trac.sagemath.org/13109 for details. () {'new_option': 1} """ @sage_wraps(func) def wrapper(*args, **kwds): for old_name, new_name in self.renames.items(): if old_name in kwds and new_name not in kwds: if self.deprecation is not None: from sage.misc.superseded import deprecation deprecation(self.deprecation, "use the option " "%r instead of %r" % (new_name, old_name)) kwds[new_name] = kwds[old_name] del kwds[old_name] return func(*args, **kwds) return wrapper class specialize: r""" A decorator generator that returns a decorator that in turn returns a specialized function for function ``f``. In other words, it returns a function that acts like ``f`` with arguments ``*args`` and ``**kwargs`` supplied. INPUT: - ``*args``, ``**kwargs`` -- arguments to specialize the function for. OUTPUT: - a decorator that accepts a function ``f`` and specializes it with ``*args`` and ``**kwargs`` EXAMPLES:: sage: f = specialize(5)(lambda x, y: x+y) sage: f(10) 15 sage: f(5) 10 sage: @specialize("Bon Voyage") ....: def greet(greeting, name): ....: print("{0}, {1}!".format(greeting, name)) sage: greet("Monsieur Jean Valjean") Bon Voyage, Monsieur Jean Valjean! sage: greet(name = 'Javert') Bon Voyage, Javert! """ def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, f): return sage_wraps(f)(partial(f, *self.args, **self.kwargs)) def decorator_keywords(func): r""" A decorator for decorators with optional keyword arguments. EXAMPLES:: sage: from sage.misc.decorators import decorator_keywords sage: @decorator_keywords ....: def preprocess(f=None, processor=None): ....: def wrapper(*args, **kwargs): ....: if processor is not None: ....: args, kwargs = processor(*args, **kwargs) ....: return f(*args, **kwargs) ....: return wrapper This decorator can be called with and without arguments:: sage: @preprocess ....: def foo(x): return x sage: foo(None) sage: foo(1) 1 sage: def normalize(x): return ((0,),{}) if x is None else ((x,),{}) sage: @preprocess(processor=normalize) ....: def foo(x): return x sage: foo(None) 0 sage: foo(1) 1 """ @sage_wraps(func) def wrapped(f=None, **kwargs): if f is None: return sage_wraps(func)(lambda f:func(f, **kwargs)) else: return func(f, **kwargs) return wrapped
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/decorators.py
0.773473
0.348617
decorators.py
pypi
# default variable name var_name = 'x' def variable_names(n, name=None): r""" Convert a root string into a tuple of variable names by adding numbers in sequence. INPUT: - ``n`` a non-negative Integer; the number of variable names to output - ``names`` a string (default: ``None``); the root of the variable name. EXAMPLES:: sage: from sage.misc.defaults import variable_names sage: variable_names(0) () sage: variable_names(1) ('x',) sage: variable_names(1,'alpha') ('alpha',) sage: variable_names(2,'alpha') ('alpha0', 'alpha1') """ if name is None: name = var_name n = int(n) if n == 1: return (name,) return tuple(['%s%s' % (name, i) for i in range(n)]) def latex_variable_names(n, name=None): r""" Convert a root string into a tuple of variable names by adding numbers in sequence. INPUT: - ``n`` a non-negative Integer; the number of variable names to output - ``names`` a string (default: ``None``); the root of the variable name. EXAMPLES:: sage: from sage.misc.defaults import latex_variable_names sage: latex_variable_names(0) () sage: latex_variable_names(1,'a') ('a',) sage: latex_variable_names(3,beta) ('beta_{0}', 'beta_{1}', 'beta_{2}') sage: latex_variable_names(3,r'\beta') ('\\beta_{0}', '\\beta_{1}', '\\beta_{2}') """ if name is None: name = var_name n = int(n) if n == 1: return (name,) return tuple(['%s_{%s}' % (name, i) for i in range(n)]) def set_default_variable_name(name, separator=''): r""" Change the default variable name and separator. """ global var_name, var_sep var_name = str(name) var_sep = str(separator) # default series precision series_prec = 20 def series_precision(): """ Return the Sage-wide precision for series (symbolic, power series, Laurent series). EXAMPLES:: sage: series_precision() 20 """ return series_prec def set_series_precision(prec): """ Change the Sage-wide precision for series (symbolic, power series, Laurent series). EXAMPLES:: sage: set_series_precision(5) sage: series_precision() 5 sage: set_series_precision(20) """ global series_prec series_prec = prec
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/defaults.py
0.785144
0.513425
defaults.py
pypi
from sage.structure.sage_object import SageObject class MethodDecorator(SageObject): def __init__(self, f): """ EXAMPLES:: sage: from sage.misc.method_decorator import MethodDecorator sage: class Foo: ....: @MethodDecorator ....: def bar(self, x): ....: return x**2 sage: J = Foo() sage: J.bar <sage.misc.method_decorator.MethodDecorator object at ...> """ self.f = f if hasattr(f, "__doc__"): self.__doc__ = f.__doc__ else: self.__doc__ = f.__doc__ if hasattr(f, "__name__"): self.__name__ = f.__name__ self.__module__ = f.__module__ def _sage_src_(self): """ Return the source code for the wrapped function. EXAMPLES: This class is rather abstract so we showcase its features using one of its subclasses:: sage: P.<x,y,z> = PolynomialRing(ZZ) sage: I = ideal( x^2 - 3*y, y^3 - x*y, z^3 - x, x^4 - y*z + 1 ) sage: "primary" in I.primary_decomposition._sage_src_() # indirect doctest True """ from sage.misc.sageinspect import sage_getsource return sage_getsource(self.f) def __call__(self, *args, **kwds): """ EXAMPLES: This class is rather abstract so we showcase its features using one of its subclasses:: sage: P.<x,y,z> = PolynomialRing(Zmod(126)) sage: I = ideal( x^2 - 3*y, y^3 - x*y, z^3 - x, x^4 - y*z + 1 ) sage: I.primary_decomposition() # indirect doctest Traceback (most recent call last): ... ValueError: Coefficient ring must be a field for function 'primary_decomposition'. """ return self.f(self._instance, *args, **kwds) def __get__(self, inst, cls=None): """ EXAMPLES: This class is rather abstract so we showcase its features using one of its subclasses:: sage: P.<x,y,z> = PolynomialRing(Zmod(126)) sage: I = ideal( x^2 - 3*y, y^3 - x*y, z^3 - x, x^4 - y*z + 1 ) sage: I.primary_decomposition() # indirect doctest Traceback (most recent call last): ... ValueError: Coefficient ring must be a field for function 'primary_decomposition'. """ self._instance = inst return self
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/method_decorator.py
0.86267
0.332879
method_decorator.py
pypi
"Benchmarks" from .misc import cputime from sage.all import * def benchmark(n=-1): """ Run a well-chosen range of Sage commands and record the time it takes for each to run. INPUT: n -- int (default: -1) the benchmark number; the default of -1 runs all the benchmarks. OUTPUT: list -- summary of timings for each benchmark. int -- if n == -1, also return the total time EXAMPLES:: sage: from sage.misc.benchmark import * sage: _ = benchmark() Running benchmark 0 Benchmark 0: Factor the following polynomial over the rational numbers: (x^97+19*x+1)*(x^103-19*x^97+14)*(x^100-1) Time: ... seconds Running benchmark 1 Find the Mordell-Weil group of the elliptic curve 5077A using mwrank Time: ... seconds Running benchmark 2 Some basic arithmetic with very large Integer numbers: '3^1000001 * 19^100001 Time: ... seconds Running benchmark 3 Some basic arithmetic with very large Rational numbers: '(2/3)^100001 * (17/19)^100001 Time: ... seconds Running benchmark 4 Rational polynomial arithmetic using Sage. Compute (x^29+17*x-5)^200. Time: ... seconds Running benchmark 5 Rational polynomial arithmetic using Sage. Compute (x^19 - 18*x + 1)^50 one hundred times. Time: ... seconds Running benchmark 6 Compute the p-division polynomials of y^2 = x^3 + 37*x - 997 for primes p < 40. Time: ... seconds Running benchmark 7 Compute the Mordell-Weil group of y^2 = x^3 + 37*x - 997. Time: ... seconds Running benchmark 8 """ if isinstance(n, list): t = cputime() v = [benchmark(m) for m in n] return v, cputime(t) if n != -1: print("Running benchmark {}".format(n)) try: desc, t = eval("bench{}()".format(n)) except NameError: raise RuntimeError("no benchmark {}".format(n)) print(desc) print("Time: {} seconds".format(t)) return (n, t, desc) t = cputime() m = 0 v = [] while True: try: v.append(benchmark(m)) m += 1 except RuntimeError: break return v, cputime(t) def bench0(): """ Run a benchmark. BENCHMARK:: sage: from sage.misc.benchmark import * sage: print(bench0()[0]) Benchmark 0: Factor the following polynomial over the rational numbers: (x^97+19*x+1)*(x^103-19*x^97+14)*(x^100-1) """ desc = """Benchmark 0: Factor the following polynomial over the rational numbers: (x^97+19*x+1)*(x^103-19*x^97+14)*(x^100-1)""" x = polygen(QQ,"x") f = (x**97+19*x+1)*(x**103-19*x**97+14)*(x**100-1) t = cputime() F = f.factor() return (desc, cputime(t)) def bench1(): """ Run a benchmark. BENCHMARK:: sage: from sage.misc.benchmark import * sage: print(bench1()[0]) Find the Mordell-Weil group of the elliptic curve 5077A using mwrank """ desc = """Find the Mordell-Weil group of the elliptic curve 5077A using mwrank""" E = mwrank_EllipticCurve([0, 0, 1, -7, 6]) t = cputime() g = E.gens() return (desc, cputime(t)) def bench2(): """ Run a benchmark. BENCHMARK:: sage: from sage.misc.benchmark import * sage: print(bench2()[0]) Some basic arithmetic with very large Integer numbers: '3^1000001 * 19^100001 """ desc = """Some basic arithmetic with very large Integer numbers: '3^1000001 * 19^100001""" t = cputime() a = ZZ(3)**1000001 * ZZ(19)**100001 return (desc, cputime(t)) def bench3(): """ Run a benchmark. BENCHMARK:: sage: from sage.misc.benchmark import * sage: print(bench3()[0]) Some basic arithmetic with very large Rational numbers: '(2/3)^100001 * (17/19)^100001 """ desc = """Some basic arithmetic with very large Rational numbers: '(2/3)^100001 * (17/19)^100001""" t = cputime() a = QQ((2, 3))**100001 * QQ((17, 19))**100001 return (desc, cputime(t)) def bench4(): """ Run a benchmark. BENCHMARK:: sage: from sage.misc.benchmark import * sage: print(bench4()[0]) Rational polynomial arithmetic using Sage. Compute (x^29+17*x-5)^200. """ desc = """Rational polynomial arithmetic using Sage. Compute (x^29+17*x-5)^200.""" x = PolynomialRing(QQ, 'x').gen() t = cputime() f = x**29 + 17*x-5 a = f**200 return (desc, cputime(t)) def bench5(): """ Run a benchmark. BENCHMARK:: sage: from sage.misc.benchmark import * sage: print(bench5()[0]) Rational polynomial arithmetic using Sage. Compute (x^19 - 18*x + 1)^50 one hundred times. """ desc = """Rational polynomial arithmetic using Sage. Compute (x^19 - 18*x + 1)^50 one hundred times.""" x = PolynomialRing(QQ, 'x').gen() t = cputime() f = x**19 - 18*x + 1 w = [f**50 for _ in range(100)] return (desc, cputime(t)) def bench6(): """ Run a benchmark. BENCHMARK:: sage: from sage.misc.benchmark import * sage: print(bench6()[0]) Compute the p-division polynomials of y^2 = x^3 + 37*x - 997 for primes p < 40. """ desc = """Compute the p-division polynomials of y^2 = x^3 + 37*x - 997 for primes p < 40.""" E = EllipticCurve([0,0,0,37,-997]) t = cputime() for p in [2,3,5,7,11,13,17,19,23,29,31,37]: f = E.division_polynomial(p) return (desc, cputime(t)) def bench7(): """ Run a benchmark. BENCHMARK:: sage: from sage.misc.benchmark import * sage: print(bench7()[0]) Compute the Mordell-Weil group of y^2 = x^3 + 37*x - 997. """ desc = """Compute the Mordell-Weil group of y^2 = x^3 + 37*x - 997.""" E = EllipticCurve([0,0,0,37,-997]) t = cputime() G = E.gens() return (desc, cputime(t))
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/benchmark.py
0.790369
0.645874
benchmark.py
pypi
import os from sage.misc.superseded import deprecation def install_scripts(directory=None, ignore_existing=False): r""" This function has been deprecated. Running ``install_scripts(directory)`` creates scripts in the given directory that run various software components included with Sage. Each of these scripts essentially just runs ``sage --CMD`` where ``CMD`` is also the name of the script: - 'gap' runs GAP - 'gp' runs the PARI/GP interpreter - 'ipython' runs IPython - 'maxima' runs Maxima - 'mwrank' runs mwrank - 'R' runs R - 'singular' runs Singular - 'sqlite3' runs SQLite version 3 This command: - verbosely tells you which scripts it adds, and - will *not* overwrite any scripts you already have in the given directory. INPUT: - ``directory`` - string; the directory into which to put the scripts. This directory must exist and the user must have write and execute permissions. - ``ignore_existing`` - bool (optional, default False): if True, install script even if another version of the program is in your path. OUTPUT: Verbosely prints what it is doing and creates files in ``directory`` that are world executable and readable. .. note:: You may need to run ``sage`` as ``root`` in order to run ``install_scripts`` successfully, since the user running ``sage`` needs write permissions on ``directory``. Note that one good candidate for ``directory`` is ``'/usr/local/bin'``, so from the shell prompt, you could run :: sudo sage -c "install_scripts('/usr/local/bin')" .. note:: Running ``install_scripts(directory)`` will be most helpful if ``directory`` is in your path. AUTHORS: - William Stein: code / design - Arthur Gaer: design - John Palmieri: revision, 2011-07 (:trac:`11602`) EXAMPLES:: sage: import tempfile sage: with tempfile.TemporaryDirectory() as d: ....: install_scripts(d, ignore_existing=True) doctest:warning... the function install_scripts has been deprecated and will be removed in a future version of Sage See https://trac.sagemath.org/30207 for details. Checking that Sage has the command 'gap' installed ... """ deprecation(30207, 'the function install_scripts has been deprecated and ' 'will be removed in a future version of Sage') if directory is None: # We do this since the intended user of install_scripts # will likely be pretty clueless about how to use Sage or # its help system. from . import sagedoc print(sagedoc.format(install_scripts.__doc__)) print("USAGE: install_scripts('directory')") return if not os.path.exists(directory): print(f"Error: '{directory}' does not exist.") return if not os.path.isdir(directory): print(f"Error: '{directory}' is not a directory.") return if not (os.access(directory, os.W_OK) and os.access(directory, os.X_OK)): print(f"Error: you do not have write permission for '{directory}'.") return from sage.misc.sage_ostools import have_program from sage.env import SAGE_LOCAL if not SAGE_LOCAL: print(f"Error: This installation of Sage does not use SAGE_LOCAL, so install_scripts makes no sense.") return script_created = False SAGE_BIN = os.path.join(SAGE_LOCAL, 'bin') # See if 'directory' is already in PATH, and then remove # SAGE_LOCAL/bin from PATH so that we can later check whether # cmd is available outside of Sage. PATH = os.environ['PATH'].split(os.pathsep) PATH = [d for d in PATH if os.path.exists(d)] dir_in_path = any(os.path.samefile(directory, d) for d in PATH) PATH = os.pathsep.join(d for d in PATH if not os.path.samefile(d, SAGE_BIN)) for cmd in ['gap', 'gp', 'ipython', 'maxima', 'mwrank', 'R', 'singular', 'sqlite3']: print(f"Checking that Sage has the command '{cmd}' installed") # Check to see if Sage includes cmd. cmd_inside_sage = have_program(cmd, path=SAGE_BIN) if not cmd_inside_sage: print(f"The command '{cmd}' is not available as part of Sage; " + "not creating script.") print() continue cmd_outside_sage = have_program(cmd, path=PATH) if cmd_outside_sage: print(f"The command '{cmd}' is installed outside of Sage;", end=' ') if not ignore_existing: print("not creating script.") print() continue print("trying to create script anyway...") else: print(f"Creating script for '{cmd}'...") # Install shortcut. target = os.path.join(directory, cmd) if os.path.exists(target): print(f"The file '{target}' already exists; not adding script.") else: with open(target, 'w') as o: o.write('#!/bin/sh\n') o.write('exec sage --%s "$@"\n' % cmd) print(f"Created script '{target}'") os.system(f'chmod a+rx {target}') script_created = True print() if script_created: print("Finished creating scripts.") print() print("You need not do this again even if you upgrade or move Sage.") print("The only requirement is that your PATH contains both") print("'{}' and the directory containing the command 'sage'.".format(directory)) if not dir_in_path: print() print("Warning: '{}' is not currently in your PATH.".format(directory)) print() else: print("No scripts created.")
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/dist.py
0.533884
0.199444
dist.py
pypi
r""" ReST index of functions This module contains a function that generates a ReST index table of functions for use in doc-strings. {INDEX_OF_FUNCTIONS} """ import inspect from sage.misc.sageinspect import _extract_embedded_position from sage.misc.sageinspect import is_function_or_cython_function as _isfunction def gen_rest_table_index(obj, names=None, sort=True, only_local_functions=True): r""" Return a ReST table describing a list of functions. The list of functions can either be given explicitly, or implicitly as the functions/methods of a module or class. In the case of a class, only non-inherited methods are listed. INPUT: - ``obj`` -- a list of functions, a module or a class. If given a list of functions, the generated table will consist of these. If given a module or a class, all functions/methods it defines will be listed, except deprecated or those starting with an underscore. In the case of a class, note that inherited methods are not displayed. - ``names`` -- a dictionary associating a name to a function. Takes precedence over the automatically computed name for the functions. Only used when ``list_of_entries`` is a list. - ``sort`` (boolean; ``True``) -- whether to sort the list of methods lexicographically. - ``only_local_functions`` (boolean; ``True``) -- if ``list_of_entries`` is a module, ``only_local_functions = True`` means that imported functions will be filtered out. This can be useful to disable for making indexes of e.g. catalog modules such as :mod:`sage.coding.codes_catalog`. .. WARNING:: The ReST tables returned by this function use '@' as a delimiter for cells. This can cause trouble if the first sentence in the documentation of a function contains the '@' character. EXAMPLES:: sage: from sage.misc.rest_index_of_methods import gen_rest_table_index sage: print(gen_rest_table_index([graphs.PetersenGraph])) .. csv-table:: :class: contentstable :widths: 30, 70 :delim: @ <BLANKLINE> :func:`~sage.graphs.generators.smallgraphs.PetersenGraph` @ Return the Petersen Graph. The table of a module:: sage: print(gen_rest_table_index(sage.misc.rest_index_of_methods)) .. csv-table:: :class: contentstable :widths: 30, 70 :delim: @ <BLANKLINE> :func:`~sage.misc.rest_index_of_methods.doc_index` @ Attribute an index name to a function. :func:`~sage.misc.rest_index_of_methods.gen_rest_table_index` @ Return a ReST table describing a list of functions. :func:`~sage.misc.rest_index_of_methods.gen_thematic_rest_table_index` @ Return a ReST string of thematically sorted function (or methods) of a module (or class). :func:`~sage.misc.rest_index_of_methods.list_of_subfunctions` @ Returns the functions (resp. methods) of a given module (resp. class) with their names. <BLANKLINE> <BLANKLINE> The table of a class:: sage: print(gen_rest_table_index(Graph)) .. csv-table:: :class: contentstable :widths: 30, 70 :delim: @ ... :meth:`~sage.graphs.graph.Graph.sparse6_string` @ Return the sparse6 representation of the graph as an ASCII string. ... TESTS: When the first sentence of the docstring spans over several lines:: sage: def a(): ....: r''' ....: Here is a very very very long sentence ....: that spans on several lines. ....: ....: EXAMP... ....: ''' ....: print("hey") sage: 'Here is a very very very long sentence that spans on several lines' in gen_rest_table_index([a]) True The inherited methods do not show up:: sage: gen_rest_table_index(sage.combinat.posets.lattices.FiniteLatticePoset).count('\n') < 75 True sage: from sage.graphs.generic_graph import GenericGraph sage: A = gen_rest_table_index(Graph).count('\n') sage: B = gen_rest_table_index(GenericGraph).count('\n') sage: A < B True When ``only_local_functions`` is ``False``, we do not include ``gen_rest_table_index`` itself:: sage: print(gen_rest_table_index(sage.misc.rest_index_of_methods, only_local_functions=True)) .. csv-table:: :class: contentstable :widths: 30, 70 :delim: @ <BLANKLINE> :func:`~sage.misc.rest_index_of_methods.doc_index` @ Attribute an index name to a function. :func:`~sage.misc.rest_index_of_methods.gen_rest_table_index` @ Return a ReST table describing a list of functions. :func:`~sage.misc.rest_index_of_methods.gen_thematic_rest_table_index` @ Return a ReST string of thematically sorted function (or methods) of a module (or class). :func:`~sage.misc.rest_index_of_methods.list_of_subfunctions` @ Returns the functions (resp. methods) of a given module (resp. class) with their names. <BLANKLINE> <BLANKLINE> sage: print(gen_rest_table_index(sage.misc.rest_index_of_methods, only_local_functions=False)) .. csv-table:: :class: contentstable :widths: 30, 70 :delim: @ <BLANKLINE> :func:`~sage.misc.rest_index_of_methods.doc_index` @ Attribute an index name to a function. :func:`~sage.misc.rest_index_of_methods.gen_thematic_rest_table_index` @ Return a ReST string of thematically sorted function (or methods) of a module (or class). :func:`~sage.misc.rest_index_of_methods.list_of_subfunctions` @ Returns the functions (resp. methods) of a given module (resp. class) with their names. <BLANKLINE> <BLANKLINE> A function that is imported into a class under a different name is listed under its 'new' name:: sage: 'cliques_maximum' in gen_rest_table_index(Graph) True sage: 'all_max_cliques`' in gen_rest_table_index(Graph) False """ if names is None: names = {} # If input is a class/module, we list all its non-private and methods/functions if inspect.isclass(obj) or inspect.ismodule(obj): list_of_entries, names = list_of_subfunctions( obj, only_local_functions=only_local_functions) else: list_of_entries = obj fname = lambda x: names.get(x, getattr(x, "__name__", "")) assert isinstance(list_of_entries, list) s = [".. csv-table::", " :class: contentstable", " :widths: 30, 70", " :delim: @\n"] if sort: list_of_entries.sort(key=fname) for e in list_of_entries: if inspect.ismethod(e): link = ":meth:`~{module}.{cls}.{func}`".format( module=e.im_class.__module__, cls=e.im_class.__name__, func=fname(e)) elif _isfunction(e) and inspect.isclass(obj): link = ":meth:`~{module}.{cls}.{func}`".format( module=obj.__module__, cls=obj.__name__, func=fname(e)) elif _isfunction(e): link = ":func:`~{module}.{func}`".format( module=e.__module__, func=fname(e)) else: continue # Extract lines injected by cython doc = e.__doc__ doc_tmp = _extract_embedded_position(doc) if doc_tmp: doc = doc_tmp[0] # Descriptions of the method/function if doc: desc = doc.split('\n\n')[0] # first paragraph desc = " ".join(x.strip() for x in desc.splitlines()) # concatenate lines desc = desc.strip() # remove leading spaces else: desc = "NO DOCSTRING" s.append(" {} @ {}".format(link, desc.lstrip())) return '\n'.join(s) + '\n' def list_of_subfunctions(root, only_local_functions=True): r""" Returns the functions (resp. methods) of a given module (resp. class) with their names. INPUT: - ``root`` -- the module, or class, whose elements are to be listed. - ``only_local_functions`` (boolean; ``True``) -- if ``root`` is a module, ``only_local_functions = True`` means that imported functions will be filtered out. This can be useful to disable for making indexes of e.g. catalog modules such as :mod:`sage.coding.codes_catalog`. OUTPUT: A pair ``(list,dict)`` where ``list`` is a list of function/methods and ``dict`` associates to every function/method the name under which it appears in ``root``. EXAMPLES:: sage: from sage.misc.rest_index_of_methods import list_of_subfunctions sage: l = list_of_subfunctions(Graph)[0] sage: Graph.bipartite_color in l True TESTS: A ``staticmethod`` is not callable. We must handle them correctly, however:: sage: class A: ....: x = staticmethod(Graph.order) sage: list_of_subfunctions(A) ([<function GenericGraph.order at 0x...>], {<function GenericGraph.order at 0x...>: 'x'}) """ if inspect.ismodule(root): ismodule = True elif inspect.isclass(root): ismodule = False superclasses = inspect.getmro(root)[1:] else: raise ValueError("'root' must be a module or a class.") def local_filter(f,name): if only_local_functions: if ismodule: return inspect.getmodule(root) == inspect.getmodule(f) else: return not any(hasattr(s,name) for s in superclasses) else: return inspect.isclass(root) or not (f is gen_rest_table_index) functions = {getattr(root,name):name for name,f in root.__dict__.items() if (not name.startswith('_') and # private functions not hasattr(f,'trac_number') and # deprecated functions not inspect.isclass(f) and # classes callable(getattr(f,'__func__',f)) and # e.g. GenericGraph.graphics_array_defaults local_filter(f,name)) # possibly filter imported functions } return list(functions.keys()), functions def gen_thematic_rest_table_index(root,additional_categories=None,only_local_functions=True): r""" Return a ReST string of thematically sorted function (or methods) of a module (or class). INPUT: - ``root`` -- the module, or class, whose elements are to be listed. - ``additional_categories`` -- a dictionary associating a category (given as a string) to a function's name. Can be used when the decorator :func:`doc_index` does not work on a function. - ``only_local_functions`` (boolean; ``True``) -- if ``root`` is a module, ``only_local_functions = True`` means that imported functions will be filtered out. This can be useful to disable for making indexes of e.g. catalog modules such as :mod:`sage.coding.codes_catalog`. EXAMPLES:: sage: from sage.misc.rest_index_of_methods import gen_thematic_rest_table_index, list_of_subfunctions sage: l = list_of_subfunctions(Graph)[0] sage: Graph.bipartite_color in l True """ from collections import defaultdict if additional_categories is None: additional_categories = {} functions, names = list_of_subfunctions(root, only_local_functions=only_local_functions) theme_to_function = defaultdict(list) for f in functions: if hasattr(f, 'doc_index'): doc_ind = f.doc_index else: try: doc_ind = additional_categories.get(f.__name__, "Unsorted") except AttributeError: doc_ind = "Unsorted" theme_to_function[doc_ind].append(f) s = ["**"+theme+"**\n\n"+gen_rest_table_index(list_of_functions,names=names) for theme, list_of_functions in sorted(theme_to_function.items())] return "\n\n".join(s) def doc_index(name): r""" Attribute an index name to a function. This decorator can be applied to a function/method in order to specify in which index it must appear, in the index generated by :func:`gen_thematic_rest_table_index`. INPUT: - ``name`` -- a string, which will become the title of the index in which this function/method will appear. EXAMPLES:: sage: from sage.misc.rest_index_of_methods import doc_index sage: @doc_index("Wouhouuuuu") ....: def a(): ....: print("Hey") sage: a.doc_index 'Wouhouuuuu' """ def hey(f): setattr(f,"doc_index",name) return f return hey __doc__ = __doc__.format(INDEX_OF_FUNCTIONS=gen_rest_table_index([gen_rest_table_index]))
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/rest_index_of_methods.py
0.872605
0.76947
rest_index_of_methods.py
pypi
r""" Elements with labels. This module implements a simple wrapper class for pairs consisting of an "element" and a "label". For representation purposes (``repr``, ``str``, ``latex``), this pair behaves like its label, while the element is "silent". However, these pairs compare like usual pairs (i.e., both element and label have to be equal for two such pairs to be equal). This is used for visual representations of graphs and posets with vertex labels. """ from sage.misc.latex import latex class ElementWithLabel(): """ Auxiliary class for showing/viewing :class:`Poset`s with non-injective labelings. For hashing and equality testing the resulting object behaves like a tuple ``(element, label)``. For any presentation purposes it appears just as ``label`` would. EXAMPLES:: sage: P = Poset({1: [2,3]}) sage: labs = {i: P.rank(i) for i in range(1, 4)} sage: print(labs) {1: 0, 2: 1, 3: 1} sage: print(P.plot(element_labels=labs)) Graphics object consisting of 6 graphics primitives sage: from sage.misc.element_with_label import ElementWithLabel sage: W = WeylGroup("A1") sage: P = W.bruhat_poset(facade=True) sage: D = W.domain() sage: v = D.rho() - D.fundamental_weight(1) sage: nP = P.relabel(lambda w: ElementWithLabel(w, w.action(v))) sage: list(nP) [(0, 0), (0, 0)] """ def __init__(self, element, label): """ Construct an object that wraps ``element`` but presents itself as ``label``. TESTS:: sage: from sage.misc.element_with_label import ElementWithLabel sage: e = ElementWithLabel(1, 'a') sage: e 'a' sage: e.element 1 """ self.element = element self.label = label def _latex_(self): """ Return the latex representation of ``self``, which is just the latex representation of the label. TESTS:: sage: var('a_1') a_1 sage: from sage.misc.element_with_label import ElementWithLabel sage: e = ElementWithLabel(1, a_1) sage: latex(e) a_{1} """ return latex(self.label) def __str__(self): """ Return the string representation of ``self``, which is just the string representation of the label. TESTS:: sage: var('a_1') a_1 sage: from sage.misc.element_with_label import ElementWithLabel sage: e = ElementWithLabel(1, a_1) sage: str(e) 'a_1' """ return str(self.label) def __repr__(self): """ Return the representation of ``self``, which is just the representation of the label. TESTS:: sage: var('a_1') a_1 sage: from sage.misc.element_with_label import ElementWithLabel sage: e = ElementWithLabel(1, a_1) sage: repr(e) 'a_1' """ return repr(self.label) def __hash__(self): """ Return the hash of the labeled element ``self``, which is just the hash of ``self.element``. TESTS:: sage: from sage.misc.element_with_label import ElementWithLabel sage: a = ElementWithLabel(1, 'a') sage: b = ElementWithLabel(1, 'b') sage: d = {} sage: d[a] = 'element 1' sage: d[b] = 'element 2' sage: print(d) {'a': 'element 1', 'b': 'element 2'} sage: a = ElementWithLabel("a", [2,3]) sage: hash(a) == hash(a.element) True """ return hash(self.element) def __eq__(self, other): """ Two labeled elements are equal if and only if both of their constituents are equal. TESTS:: sage: from sage.misc.element_with_label import ElementWithLabel sage: a = ElementWithLabel(1, 'a') sage: b = ElementWithLabel(1, 'b') sage: x = ElementWithLabel(1, 'a') sage: a == b False sage: a == x True sage: 1 == a False sage: b == 1 False """ if not (isinstance(self, ElementWithLabel) and isinstance(other, ElementWithLabel)): return False return self.element == other.element and self.label == other.label def __ne__(self, other): """ Two labeled elements are not equal if and only if first or second constituents are not equal. TESTS:: sage: from sage.misc.element_with_label import ElementWithLabel sage: a = ElementWithLabel(1, 'a') sage: b = ElementWithLabel(1, 'b') sage: x = ElementWithLabel(1, 'a') sage: a != b True sage: a != x False """ return not(self == other)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/element_with_label.py
0.929208
0.792865
element_with_label.py
pypi
class SageTimeitResult(): r""" Represent the statistics of a timeit() command. Prints as a string so that it can be easily returned to a user. INPUT: - ``stats`` -- tuple of length 5 containing the following information: - integer, number of loops - integer, repeat number - Python integer, number of digits to print - number, best timing result - str, time unit EXAMPLES:: sage: from sage.misc.sage_timeit import SageTimeitResult sage: SageTimeitResult( (3, 5, int(8), pi, 'ms') ) 3 loops, best of 5: 3.1415927 ms per loop :: sage: units = [u"s", u"ms", u"μs", u"ns"] sage: scaling = [1, 1e3, 1e6, 1e9] sage: number = 7 sage: repeat = 13 sage: precision = int(5) sage: best = pi / 10 ^ 9 sage: order = 3 sage: stats = (number, repeat, precision, best * scaling[order], units[order]) sage: SageTimeitResult(stats) 7 loops, best of 13: 3.1416 ns per loop If the third argument is not a Python integer, a ``TypeError`` is raised:: sage: SageTimeitResult( (1, 2, 3, 4, 's') ) <repr(<sage.misc.sage_timeit.SageTimeitResult at 0x...>) failed: TypeError: * wants int> """ def __init__(self, stats, series=None): r""" Construction of a timing result. See documentation of ``SageTimeitResult`` for more details and examples. EXAMPLES:: sage: from sage.misc.sage_timeit import SageTimeitResult sage: SageTimeitResult( (3, 5, int(8), pi, 'ms') ) 3 loops, best of 5: 3.1415927 ms per loop sage: s = SageTimeitResult( (3, 5, int(8), pi, 'ms'), [1.0,1.1,0.5]) sage: s.series [1.00000000000000, 1.10000000000000, 0.500000000000000] """ self.stats = stats self.series = series if not None else [] def __repr__(self): r""" String representation. EXAMPLES:: sage: from sage.misc.sage_timeit import SageTimeitResult sage: stats = (1, 2, int(3), pi, 'ns') sage: SageTimeitResult(stats) #indirect doctest 1 loop, best of 2: 3.14 ns per loop """ if self.stats[0] > 1: s = u"%d loops, best of %d: %.*g %s per loop" % self.stats else: s = u"%d loop, best of %d: %.*g %s per loop" % self.stats if isinstance(s, str): return s return s.encode("utf-8") def sage_timeit(stmt, globals_dict=None, preparse=None, number=0, repeat=3, precision=3, seconds=False): """nodetex Accurately measure the wall time required to execute ``stmt``. INPUT: - ``stmt`` -- a text string. - ``globals_dict`` -- a dictionary or ``None`` (default). Evaluate ``stmt`` in the context of the globals dictionary. If not set, the current ``globals()`` dictionary is used. - ``preparse`` -- (default: use globals preparser default) if ``True`` preparse ``stmt`` using the Sage preparser. - ``number`` -- integer, (optional, default: 0), number of loops. - ``repeat`` -- integer, (optional, default: 3), number of repetition. - ``precision`` -- integer, (optional, default: 3), precision of output time. - ``seconds`` -- boolean (default: ``False``). Whether to just return time in seconds. OUTPUT: An instance of ``SageTimeitResult`` unless the optional parameter ``seconds=True`` is passed. In that case, the elapsed time in seconds is returned as a floating-point number. EXAMPLES:: sage: from sage.misc.sage_timeit import sage_timeit sage: sage_timeit('3^100000', globals(), preparse=True, number=50) # random output '50 loops, best of 3: 1.97 ms per loop' sage: sage_timeit('3^100000', globals(), preparse=False, number=50) # random output '50 loops, best of 3: 67.1 ns per loop' sage: a = 10 sage: sage_timeit('a^2', globals(), number=50) # random output '50 loops, best of 3: 4.26 us per loop' If you only want to see the timing and not have access to additional information, just use the ``timeit`` object:: sage: timeit('10^2', number=50) 50 loops, best of 3: ... per loop Using sage_timeit gives you more information though:: sage: s = sage_timeit('10^2', globals(), repeat=1000) sage: len(s.series) 1000 sage: mean(s.series) # random output 3.1298141479492283e-07 sage: min(s.series) # random output 2.9258728027343752e-07 sage: t = stats.TimeSeries(s.series) sage: t.scale(10^6).plot_histogram(bins=20,figsize=[12,6], ymax=2) Graphics object consisting of 20 graphics primitives The input expression can contain newlines (but doctests cannot, so we use ``os.linesep`` here):: sage: from sage.misc.sage_timeit import sage_timeit sage: from os import linesep as CR sage: # sage_timeit(r'a = 2\\nb=131\\nfactor(a^b-1)') sage: sage_timeit('a = 2' + CR + 'b=131' + CR + 'factor(a^b-1)', ....: globals(), number=10) 10 loops, best of 3: ... per loop Test to make sure that ``timeit`` behaves well with output:: sage: timeit("print('Hi')", number=50) 50 loops, best of 3: ... per loop If you want a machine-readable output, use the ``seconds=True`` option:: sage: timeit("print('Hi')", seconds=True) # random output 1.42555236816e-06 sage: t = timeit("print('Hi')", seconds=True) sage: t #r random output 3.6010742187499999e-07 TESTS: Make sure that garbage collection is re-enabled after an exception occurs in timeit:: sage: def f(): raise ValueError sage: import gc sage: gc.isenabled() True sage: timeit("f()") Traceback (most recent call last): ... ValueError sage: gc.isenabled() True """ import math import timeit as timeit_ import sage.repl.interpreter as interpreter import sage.repl.preparse as preparser number = int(number) repeat = int(repeat) precision = int(precision) if preparse is None: preparse = interpreter._do_preparse if preparse: stmt = preparser.preparse(stmt) if stmt == "": return '' units = [u"s", u"ms", u"μs", u"ns"] scaling = [1, 1e3, 1e6, 1e9] timer = timeit_.Timer() # this code has tight coupling to the inner workings of timeit.Timer, # but is there a better way to achieve that the code stmt has access # to the shell namespace? src = timeit_.template.format(stmt=timeit_.reindent(stmt, 8), setup="pass", init='') code = compile(src, "<magic-timeit>", "exec") ns = {} if not globals_dict: globals_dict = globals() exec(code, globals_dict, ns) timer.inner = ns["inner"] try: import sys f = sys.stdout sys.stdout = open('/dev/null', 'w') if number == 0: # determine number so that 0.2 <= total time < 2.0 number = 1 for i in range(1, 5): number *= 5 if timer.timeit(number) >= 0.2: break series = [s / number for s in timer.repeat(repeat, number)] best = min(series) finally: sys.stdout.close() sys.stdout = f import gc gc.enable() if seconds: return best if best > 0.0: order = min(-int(math.floor(math.log10(best)) // 3), 3) else: order = 3 stats = (number, repeat, precision, best * scaling[order], units[order]) return SageTimeitResult(stats, series=series)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/sage_timeit.py
0.857991
0.581481
sage_timeit.py
pypi
import types def abstract_method(f=None, optional=False): r""" Abstract methods INPUT: - ``f`` -- a function - ``optional`` -- a boolean; defaults to ``False`` The decorator :obj:`abstract_method` can be used to declare methods that should be implemented by all concrete derived classes. This declaration should typically include documentation for the specification for this method. The purpose is to enforce a consistent and visual syntax for such declarations. It is used by the Sage categories for automated tests (see ``Sets.Parent.test_not_implemented``). EXAMPLES: We create a class with an abstract method:: sage: class A(): ....: ....: @abstract_method ....: def my_method(self): ....: ''' ....: The method :meth:`my_method` computes my_method ....: ....: EXAMPLES:: ....: ....: ''' ....: pass sage: A.my_method <abstract method my_method at ...> The current policy is that a ``NotImplementedError`` is raised when accessing the method through an instance, even before the method is called:: sage: x = A() sage: x.my_method Traceback (most recent call last): ... NotImplementedError: <abstract method my_method at ...> It is also possible to mark abstract methods as optional:: sage: class A(): ....: ....: @abstract_method(optional = True) ....: def my_method(self): ....: ''' ....: The method :meth:`my_method` computes my_method ....: ....: EXAMPLES:: ....: ....: ''' ....: pass sage: A.my_method <optional abstract method my_method at ...> sage: x = A() sage: x.my_method NotImplemented The official mantra for testing whether an optional abstract method is implemented is:: sage: if x.my_method is not NotImplemented: ....: x.my_method() ....: else: ....: print("x.my_method is not available.") x.my_method is not available. .. rubric:: Discussion The policy details are not yet fixed. The purpose of this first implementation is to let developers experiment with it and give feedback on what's most practical. The advantage of the current policy is that attempts at using a non implemented methods are caught as early as possible. On the other hand, one cannot use introspection directly to fetch the documentation:: sage: x.my_method? # todo: not implemented Instead one needs to do:: sage: A._my_method? # todo: not implemented This could probably be fixed in :mod:`sage.misc.sageinspect`. .. TODO:: what should be the recommended mantra for existence testing from the class? .. TODO:: should extra information appear in the output? The name of the class? That of the super class where the abstract method is defined? .. TODO:: look for similar decorators on the web, and merge .. rubric:: Implementation details Technically, an abstract_method is a non-data descriptor (see Invoking Descriptors in the Python reference manual). The syntax ``@abstract_method`` w.r.t. @abstract_method(optional = True) is achieved by a little trick which we test here:: sage: abstract_method(optional = True) <function abstract_method.<locals>.<lambda> at ...> sage: abstract_method(optional = True)(banner) <optional abstract method banner at ...> sage: abstract_method(banner, optional = True) <optional abstract method banner at ...> """ if f is None: return lambda f: AbstractMethod(f, optional=optional) else: return AbstractMethod(f, optional) class AbstractMethod(): def __init__(self, f, optional=False): """ Constructor for abstract methods EXAMPLES:: sage: def f(x): ....: "doc of f" ....: return 1 sage: x = abstract_method(f); x <abstract method f at ...> sage: x.__doc__ 'doc of f' sage: x.__name__ 'f' sage: x.__module__ '__main__' """ assert (isinstance(f, types.FunctionType) or getattr(type(f), '__name__', None) == 'cython_function_or_method') assert isinstance(optional, bool) self._f = f self._optional = optional self.__doc__ = f.__doc__ self.__name__ = f.__name__ try: self.__module__ = f.__module__ except AttributeError: pass def __repr__(self): """ EXAMPLES:: sage: abstract_method(banner) <abstract method banner at ...> sage: abstract_method(banner, optional = True) <optional abstract method banner at ...> """ return "<" + ("optional " if self._optional else "") + "abstract method %s at %s>" % (self.__name__, hex(id(self._f))) def _sage_src_lines_(self): r""" Returns the source code location for the wrapped function. EXAMPLES:: sage: from sage.misc.sageinspect import sage_getsourcelines sage: g = abstract_method(banner) sage: (src, lines) = sage_getsourcelines(g) sage: src[0] 'def banner():\n' sage: lines 89 """ from sage.misc.sageinspect import sage_getsourcelines return sage_getsourcelines(self._f) def __get__(self, instance, cls): """ Implements the attribute access protocol. EXAMPLES:: sage: class A: pass sage: def f(x): return 1 sage: f = abstract_method(f) sage: f.__get__(A(), A) Traceback (most recent call last): ... NotImplementedError: <abstract method f at ...> """ if instance is None: return self elif self._optional: return NotImplemented else: raise NotImplementedError(repr(self)) def is_optional(self): """ Returns whether an abstract method is optional or not. EXAMPLES:: sage: class AbstractClass: ....: @abstract_method ....: def required(): pass ....: ....: @abstract_method(optional = True) ....: def optional(): pass sage: AbstractClass.required.is_optional() False sage: AbstractClass.optional.is_optional() True """ return self._optional def abstract_methods_of_class(cls): """ Returns the required and optional abstract methods of the class EXAMPLES:: sage: class AbstractClass: ....: @abstract_method ....: def required1(): pass ....: ....: @abstract_method(optional = True) ....: def optional2(): pass ....: ....: @abstract_method(optional = True) ....: def optional1(): pass ....: ....: @abstract_method ....: def required2(): pass sage: sage.misc.abstract_method.abstract_methods_of_class(AbstractClass) {'optional': ['optional1', 'optional2'], 'required': ['required1', 'required2']} """ result = {"required": [], "optional": []} for name in dir(cls): entry = getattr(cls, name) if not isinstance(entry, AbstractMethod): continue if entry.is_optional(): result["optional"].append(name) else: result["required"].append(name) return result
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/abstract_method.py
0.715424
0.492798
abstract_method.py
pypi
class LazyFormat(str): """ Lazy format strings .. NOTE:: We recommend to use :func:`sage.misc.lazy_string.lazy_string` instead, which is both faster and more flexible. An instance of :class:`LazyFormat` behaves like a usual format string, except that the evaluation of the ``__repr__`` method of the formatted arguments it postponed until actual printing. EXAMPLES: Under normal circumstances, :class:`Lazyformat` strings behave as usual:: sage: from sage.misc.lazy_format import LazyFormat sage: LazyFormat("Got `%s`; expected a list")%3 Got `3`; expected a list sage: LazyFormat("Got `%s`; expected %s")%(3, 2/3) Got `3`; expected 2/3 To demonstrate the lazyness, let us build an object with a broken ``__repr__`` method:: sage: class IDontLikeBeingPrinted(): ....: def __repr__(self): ....: raise ValueError("do not ever try to print me") There is no error when binding a lazy format with the broken object:: sage: lf = LazyFormat("<%s>")%IDontLikeBeingPrinted() The error only occurs upon printing:: sage: lf <repr(<sage.misc.lazy_format.LazyFormat at 0x...>) failed: ValueError: do not ever try to print me> .. rubric:: Common use case: Most of the time, ``__repr__`` methods are only called during user interaction, and therefore need not be fast; and indeed there are objects ``x`` in Sage such ``x.__repr__()`` is time consuming. There are however some uses cases where many format strings are constructed but not actually printed. This includes error handling messages in :mod:`unittest` or :class:`TestSuite` executions:: sage: QQ._tester().assertIn(0, QQ, ....: "%s doesn't contain 0"%QQ) In the above ``QQ.__repr__()`` has been called, and the result immediately discarded. To demonstrate this we replace ``QQ`` in the format string argument with our broken object:: sage: QQ._tester().assertTrue(True, ....: "%s doesn't contain 0"%IDontLikeBeingPrinted()) Traceback (most recent call last): ... ValueError: do not ever try to print me This behavior can induce major performance penalties when testing. Note that this issue does not impact the usual assert:: sage: assert True, "%s is wrong"%IDontLikeBeingPrinted() We now check that :class:`LazyFormat` indeed solves the assertion problem:: sage: QQ._tester().assertTrue(True, ....: LazyFormat("%s is wrong")%IDontLikeBeingPrinted()) sage: QQ._tester().assertTrue(False, ....: LazyFormat("%s is wrong")%IDontLikeBeingPrinted()) Traceback (most recent call last): ... AssertionError: ... """ def __mod__(self, args): """ Binds the lazy format string with its parameters EXAMPLES:: sage: from sage.misc.lazy_format import LazyFormat sage: form = LazyFormat("<%s>") sage: form unbound LazyFormat("<%s>") sage: form%"params" <params> """ if hasattr(self, "_args"): # self is already bound... self = LazyFormat(""+self) self._args = args return self def __repr__(self): """ TESTS:: sage: from sage.misc.lazy_format import LazyFormat sage: form = LazyFormat("<%s>") sage: form unbound LazyFormat("<%s>") sage: print(form) unbound LazyFormat("<%s>") sage: form%"toto" <toto> sage: print(form % "toto") <toto> sage: print(str(form % "toto")) <toto> sage: print((form % "toto").__repr__()) <toto> """ try: args = self._args except AttributeError: return "unbound LazyFormat(\""+self+"\")" else: return str.__mod__(self, args) __str__ = __repr__
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/lazy_format.py
0.745491
0.682243
lazy_format.py
pypi
r""" Tables Display a rectangular array as a table, either in plain text, LaTeX, or html. See the documentation for :class:`table` for details and examples. AUTHORS: - John H. Palmieri (2012-11) """ from io import StringIO from sage.structure.sage_object import SageObject from sage.misc.cachefunc import cached_method class table(SageObject): r""" Display a rectangular array as a table, either in plain text, LaTeX, or html. INPUT: - ``rows`` (default ``None``) - a list of lists (or list of tuples, etc.), containing the data to be displayed. - ``columns`` (default ``None``) - a list of lists (etc.), containing the data to be displayed, but stored as columns. Set either ``rows`` or ``columns``, but not both. - ``header_row`` (default ``False``) - if ``True``, first row is highlighted. - ``header_column`` (default ``False``) - if ``True``, first column is highlighted. - ``frame`` (default ``False``) - if ``True``, put a box around each cell. - ``align`` (default 'left') - the alignment of each entry: either 'left', 'center', or 'right' EXAMPLES:: sage: rows = [['a', 'b', 'c'], [100,2,3], [4,5,60]] sage: table(rows) a b c 100 2 3 4 5 60 sage: latex(table(rows)) \begin{tabular}{lll} a & b & c \\ $100$ & $2$ & $3$ \\ $4$ & $5$ & $60$ \\ \end{tabular} If ``header_row`` is ``True``, then the first row is highlighted. If ``header_column`` is ``True``, then the first column is highlighted. If ``frame`` is ``True``, then print a box around every "cell". :: sage: table(rows, header_row=True) a b c +-----+---+----+ 100 2 3 4 5 60 sage: latex(table(rows, header_row=True)) \begin{tabular}{lll} a & b & c \\ \hline $100$ & $2$ & $3$ \\ $4$ & $5$ & $60$ \\ \end{tabular} sage: table(rows=rows, frame=True) +-----+---+----+ | a | b | c | +-----+---+----+ | 100 | 2 | 3 | +-----+---+----+ | 4 | 5 | 60 | +-----+---+----+ sage: latex(table(rows=rows, frame=True)) \begin{tabular}{|l|l|l|} \hline a & b & c \\ \hline $100$ & $2$ & $3$ \\ \hline $4$ & $5$ & $60$ \\ \hline \end{tabular} sage: table(rows, header_column=True, frame=True) +-----++---+----+ | a || b | c | +-----++---+----+ | 100 || 2 | 3 | +-----++---+----+ | 4 || 5 | 60 | +-----++---+----+ sage: latex(table(rows, header_row=True, frame=True)) \begin{tabular}{|l|l|l|} \hline a & b & c \\ \hline \hline $100$ & $2$ & $3$ \\ \hline $4$ & $5$ & $60$ \\ \hline \end{tabular} sage: table(rows, header_column=True) a | b c 100 | 2 3 4 | 5 60 The argument ``header_row`` can, instead of being ``True`` or ``False``, be the contents of the header row, so that ``rows`` consists of the data, while ``header_row`` is the header information. The same goes for ``header_column``. Passing lists for both arguments simultaneously is not supported. :: sage: table([(x,n(sin(x), digits=2)) for x in [0..3]], header_row=["$x$", r"$\sin(x)$"], frame=True) +-----+-----------+ | $x$ | $\sin(x)$ | +=====+===========+ | 0 | 0.00 | +-----+-----------+ | 1 | 0.84 | +-----+-----------+ | 2 | 0.91 | +-----+-----------+ | 3 | 0.14 | +-----+-----------+ You can create the transpose of this table in several ways, for example, "by hand," that is, changing the data defining the table:: sage: table(rows=[[x for x in [0..3]], [n(sin(x), digits=2) for x in [0..3]]], header_column=['$x$', r'$\sin(x)$'], frame=True) +-----------++------+------+------+------+ | $x$ || 0 | 1 | 2 | 3 | +-----------++------+------+------+------+ | $\sin(x)$ || 0.00 | 0.84 | 0.91 | 0.14 | +-----------++------+------+------+------+ or by passing the original data as the ``columns`` of the table and using ``header_column`` instead of ``header_row``:: sage: table(columns=[(x,n(sin(x), digits=2)) for x in [0..3]], header_column=['$x$', r'$\sin(x)$'], frame=True) +-----------++------+------+------+------+ | $x$ || 0 | 1 | 2 | 3 | +-----------++------+------+------+------+ | $\sin(x)$ || 0.00 | 0.84 | 0.91 | 0.14 | +-----------++------+------+------+------+ or by taking the :meth:`transpose` of the original table:: sage: table(rows=[(x,n(sin(x), digits=2)) for x in [0..3]], header_row=['$x$', r'$\sin(x)$'], frame=True).transpose() +-----------++------+------+------+------+ | $x$ || 0 | 1 | 2 | 3 | +-----------++------+------+------+------+ | $\sin(x)$ || 0.00 | 0.84 | 0.91 | 0.14 | +-----------++------+------+------+------+ In either plain text or LaTeX, entries in tables can be aligned to the left (default), center, or right:: sage: table(rows, align='left') a b c 100 2 3 4 5 60 sage: table(rows, align='center') a b c 100 2 3 4 5 60 sage: table(rows, align='right', frame=True) +-----+---+----+ | a | b | c | +-----+---+----+ | 100 | 2 | 3 | +-----+---+----+ | 4 | 5 | 60 | +-----+---+----+ To generate HTML you should use ``html(table(...))``:: sage: data = [["$x$", r"$\sin(x)$"]] + [(x,n(sin(x), digits=2)) for x in [0..3]] sage: output = html(table(data, header_row=True, frame=True)) sage: type(output) <class 'sage.misc.html.HtmlFragment'> sage: print(output) <div class="notruncate"> <table border="1" class="table_form"> <tbody> <tr> <th style="text-align:left">\(x\)</th> <th style="text-align:left">\(\sin(x)\)</th> </tr> <tr class ="row-a"> <td style="text-align:left">\(0\)</td> <td style="text-align:left">\(0.00\)</td> </tr> <tr class ="row-b"> <td style="text-align:left">\(1\)</td> <td style="text-align:left">\(0.84\)</td> </tr> <tr class ="row-a"> <td style="text-align:left">\(2\)</td> <td style="text-align:left">\(0.91\)</td> </tr> <tr class ="row-b"> <td style="text-align:left">\(3\)</td> <td style="text-align:left">\(0.14\)</td> </tr> </tbody> </table> </div> It is an error to specify both ``rows`` and ``columns``:: sage: table(rows=[[1,2,3], [4,5,6]], columns=[[0,0,0], [0,0,1024]]) Traceback (most recent call last): ... ValueError: do not set both 'rows' and 'columns' when defining a table sage: table(columns=[[0,0,0], [0,0,1024]]) 0 0 0 0 0 1024 Note that if ``rows`` is just a list or tuple, not nested, then it is treated as a single row:: sage: table([1,2,3]) 1 2 3 Also, if you pass a non-rectangular array, the longer rows or columns get truncated:: sage: table([[1,2,3,7,12], [4,5]]) 1 2 4 5 sage: table(columns=[[1,2,3], [4,5,6,7]]) 1 4 2 5 3 6 TESTS:: sage: TestSuite(table([["$x$", r"$\sin(x)$"]] + ....: [(x,n(sin(x), digits=2)) for x in [0..3]], ....: header_row=True, frame=True)).run() .. automethod:: _rich_repr_ """ def __init__(self, rows=None, columns=None, header_row=False, header_column=False, frame=False, align='left'): r""" EXAMPLES:: sage: table([1,2,3], frame=True) +---+---+---+ | 1 | 2 | 3 | +---+---+---+ """ # If both rows and columns are set, raise an error. if rows and columns: raise ValueError("do not set both 'rows' and 'columns' when defining a table") # If columns is set, use its transpose for rows. if columns: rows = list(zip(*columns)) # Set the rest of the options. self._options = {} if header_row is True: self._options['header_row'] = True elif header_row: self._options['header_row'] = True rows = [header_row] + rows else: self._options['header_row'] = False if header_column is True: self._options['header_column'] = True elif header_column: self._options['header_column'] = True rows = [(a,) + tuple(x) for (a, x) in zip(header_column, rows)] else: self._options['header_column'] = False self._options['frame'] = frame self._options['align'] = align # Store rows as a tuple. if not isinstance(rows[0], (list, tuple)): rows = (rows,) self._rows = tuple(rows) def __eq__(self, other): r""" Two tables are equal if and only if their data rowss and their options are the same. EXAMPLES:: sage: rows = [['a', 'b', 'c'], [1,plot(sin(x)),3], [4,5,identity_matrix(2)]] sage: T = table(rows, header_row=True) sage: T2 = table(rows, header_row=True) sage: T is T2 False sage: T == T2 True sage: T2.options(frame=True) sage: T == T2 False """ return (self._rows == other._rows and self.options() == other.options()) def options(self, **kwds): r""" With no arguments, return the dictionary of options for this table. With arguments, modify options. INPUT: - ``header_row`` - if True, first row is highlighted. - ``header_column`` - if True, first column is highlighted. - ``frame`` - if True, put a box around each cell. - ``align`` - the alignment of each entry: either 'left', 'center', or 'right' EXAMPLES:: sage: T = table([['a', 'b', 'c'], [1,2,3]]) sage: T.options()['align'], T.options()['frame'] ('left', False) sage: T.options(align='right', frame=True) sage: T.options()['align'], T.options()['frame'] ('right', True) Note that when first initializing a table, ``header_row`` or ``header_column`` can be a list. In this case, during the initialization process, the header is merged with the rest of the data, so changing the header option later using ``table.options(...)`` doesn't affect the contents of the table, just whether the row or column is highlighted. When using this :meth:`options` method, no merging of data occurs, so here ``header_row`` and ``header_column`` should just be ``True`` or ``False``, not a list. :: sage: T = table([[1,2,3], [4,5,6]], header_row=['a', 'b', 'c'], frame=True) sage: T +---+---+---+ | a | b | c | +===+===+===+ | 1 | 2 | 3 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ sage: T.options(header_row=False) sage: T +---+---+---+ | a | b | c | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ If you do specify a list for ``header_row``, an error is raised:: sage: T.options(header_row=['x', 'y', 'z']) Traceback (most recent call last): ... TypeError: header_row should be either True or False. """ if kwds: for option in ['align', 'frame']: if option in kwds: self._options[option] = kwds[option] for option in ['header_row', 'header_column']: if option in kwds: if not kwds[option]: self._options[option] = kwds[option] elif kwds[option] is True: self._options[option] = kwds[option] else: raise TypeError("%s should be either True or False." % option) else: return self._options def transpose(self): r""" Return a table which is the transpose of this one: rows and columns have been interchanged. Several of the properties of the original table are preserved: whether a frame is present and any alignment setting. On the other hand, header rows are converted to header columns, and vice versa. EXAMPLES:: sage: T = table([[1,2,3], [4,5,6]]) sage: T.transpose() 1 4 2 5 3 6 sage: T = table([[1,2,3], [4,5,6]], header_row=['x', 'y', 'z'], frame=True) sage: T.transpose() +---++---+---+ | x || 1 | 4 | +---++---+---+ | y || 2 | 5 | +---++---+---+ | z || 3 | 6 | +---++---+---+ """ return table(list(zip(*self._rows)), header_row=self._options['header_column'], header_column=self._options['header_row'], frame=self._options['frame'], align=self._options['align']) @cached_method def _widths(self): r""" The maximum widths for (the string representation of) each column. Used by the :meth:`_repr_` method. EXAMPLES:: sage: table([['a', 'bb', 'ccccc'], [10, -12, 0], [1, 2, 3]])._widths() (2, 3, 5) """ nc = len(self._rows[0]) widths = [0] * nc for row in self._rows: w = [] for (idx, x) in zip(range(nc), row): w.append(max(widths[idx], len(str(x)))) widths = w return tuple(widths) def _repr_(self): r""" String representation of a table. The class docstring has many examples; here is one more. EXAMPLES:: sage: table([['a', 'bb', 'ccccc'], [10, -12, 0], [1, 2, 3]], align='right') # indirect doctest a bb ccccc 10 -12 0 1 2 3 """ rows = self._rows nc = len(rows[0]) if len(rows) == 0 or nc == 0: return "" frame_line = "+" + "+".join("-" * (x + 2) for x in self._widths()) + "+\n" if self._options['header_column'] and self._options['frame']: frame_line = "+" + frame_line[1:].replace('+', '++', 1) if self._options['frame']: s = frame_line else: s = "" if self._options['header_row']: s += self._str_table_row(rows[0], header_row=True) rows = rows[1:] for row in rows: s += self._str_table_row(row, header_row=False) return s.strip("\n") def _rich_repr_(self, display_manager, **kwds): """ Rich Output Magic Method See :mod:`sage.repl.rich_output` for details. EXAMPLES:: sage: from sage.repl.rich_output import get_display_manager sage: dm = get_display_manager() sage: t = table([1, 2, 3]) sage: t._rich_repr_(dm) # the doctest backend does not support html """ OutputHtml = display_manager.types.OutputHtml if OutputHtml in display_manager.supported_output(): return OutputHtml(self._html_()) def _str_table_row(self, row, header_row=False): r""" String representation of a row of a table. Used by the :meth:`_repr_` method. EXAMPLES:: sage: T = table([['a', 'bb', 'ccccc'], [10, -12, 0], [1, 2, 3]], align='right') sage: T._str_table_row([1,2,3]) ' 1 2 3\n' sage: T._str_table_row([1,2,3], True) ' 1 2 3\n+----+-----+-------+\n' sage: T.options(header_column=True) sage: T._str_table_row([1,2,3], True) ' 1 | 2 3\n+----+-----+-------+\n' sage: T.options(frame=True) sage: T._str_table_row([1,2,3], False) '| 1 || 2 | 3 |\n+----++-----+-------+\n' Check that :trac:`14601` has been fixed:: sage: table([['111111', '222222', '333333']])._str_table_row([False,True,None], False) ' False True None\n' """ frame = self._options['frame'] widths = self._widths() frame_line = "+" + "+".join("-" * (x + 2) for x in widths) + "+\n" align = self._options['align'] if align == 'right': align_char = '>' elif align == 'center': align_char = '^' else: align_char = '<' s = "" if frame: s += "| " else: s += " " if self._options['header_column']: if frame: frame_line = "+" + frame_line[1:].replace('+', '++', 1) s += ("{!s:" + align_char + str(widths[0]) + "}").format(row[0]) if frame: s += " || " else: s += " | " row = row[1:] widths = widths[1:] for (entry, width) in zip(row, widths): s += ("{!s:" + align_char + str(width) + "}").format(entry) if frame: s += " | " else: s += " " s = s.rstrip(' ') s += "\n" if frame and header_row: s += frame_line.replace('-', '=') elif frame or header_row: s += frame_line return s def _latex_(self): r""" LaTeX representation of a table. If an entry is a Sage object, it is replaced by its LaTeX representation, delimited by dollar signs (i.e., ``x`` is replaced by ``$latex(x)$``). If an entry is a string, the dollar signs are not automatically added, so tables can include both plain text and mathematics. OUTPUT: String. EXAMPLES:: sage: from sage.misc.table import table sage: a = [[r'$\sin(x)$', '$x$', 'text'], [1,34342,3], [identity_matrix(2),5,6]] sage: latex(table(a)) # indirect doctest \begin{tabular}{lll} $\sin(x)$ & $x$ & text \\ $1$ & $34342$ & $3$ \\ $\left(\begin{array}{rr} 1 & 0 \\ 0 & 1 \end{array}\right)$ & $5$ & $6$ \\ \end{tabular} sage: latex(table(a, frame=True, align='center')) \begin{tabular}{|c|c|c|} \hline $\sin(x)$ & $x$ & text \\ \hline $1$ & $34342$ & $3$ \\ \hline $\left(\begin{array}{rr} 1 & 0 \\ 0 & 1 \end{array}\right)$ & $5$ & $6$ \\ \hline \end{tabular} """ from .latex import latex, LatexExpr rows = self._rows nc = len(rows[0]) if len(rows) == 0 or nc == 0: return "" align_char = self._options['align'][0] # 'l', 'c', 'r' if self._options['frame']: frame_char = '|' frame_str = ' \\hline' else: frame_char = '' frame_str = '' if self._options['header_column']: head_col_char = '|' else: head_col_char = '' if self._options['header_row']: head_row_str = ' \\hline' else: head_row_str = '' # table header s = "\\begin{tabular}{" s += frame_char + align_char + frame_char + head_col_char s += frame_char.join([align_char] * (nc - 1)) s += frame_char + "}" + frame_str + "\n" # first row s += " & ".join(LatexExpr(x) if isinstance(x, (str, LatexExpr)) else '$' + latex(x).strip() + '$' for x in rows[0]) s += " \\\\" + frame_str + head_row_str + "\n" # other rows for row in rows[1:]: s += " & ".join(LatexExpr(x) if isinstance(x, (str, LatexExpr)) else '$' + latex(x).strip() + '$' for x in row) s += " \\\\" + frame_str + "\n" s += "\\end{tabular}" return s def _html_(self): r""" HTML representation of a table. Strings of html will be parsed for math inside dollar and double-dollar signs. 2D graphics will be displayed in the cells. Expressions will be latexed. The ``align`` option for tables is ignored in HTML output. Specifying ``header_column=True`` may not have any visible effect in the Sage notebook, depending on the version of the notebook. OUTPUT: A :class:`~sage.misc.html.HtmlFragment` instance. EXAMPLES:: sage: T = table([[r'$\sin(x)$', '$x$', 'text'], [1,34342,3], [identity_matrix(2),5,6]]) sage: T._html_() '<div.../div>' sage: print(T._html_()) <div class="notruncate"> <table class="table_form"> <tbody> <tr class ="row-a"> <td style="text-align:left">\(\sin(x)\)</td> <td style="text-align:left">\(x\)</td> <td style="text-align:left">text</td> </tr> <tr class ="row-b"> <td style="text-align:left">\(1\)</td> <td style="text-align:left">\(34342\)</td> <td style="text-align:left">\(3\)</td> </tr> <tr class ="row-a"> <td style="text-align:left">\(\left(\begin{array}{rr} 1 & 0 \\ 0 & 1 \end{array}\right)\)</td> <td style="text-align:left">\(5\)</td> <td style="text-align:left">\(6\)</td> </tr> </tbody> </table> </div> Note that calling ``html(table(...))`` has the same effect as calling ``table(...)._html_()``:: sage: T = table([["$x$", r"$\sin(x)$"]] + [(x,n(sin(x), digits=2)) for x in [0..3]], header_row=True, frame=True) sage: T +-----+-----------+ | $x$ | $\sin(x)$ | +=====+===========+ | 0 | 0.00 | +-----+-----------+ | 1 | 0.84 | +-----+-----------+ | 2 | 0.91 | +-----+-----------+ | 3 | 0.14 | +-----+-----------+ sage: print(html(T)) <div class="notruncate"> <table border="1" class="table_form"> <tbody> <tr> <th style="text-align:left">\(x\)</th> <th style="text-align:left">\(\sin(x)\)</th> </tr> <tr class ="row-a"> <td style="text-align:left">\(0\)</td> <td style="text-align:left">\(0.00\)</td> </tr> <tr class ="row-b"> <td style="text-align:left">\(1\)</td> <td style="text-align:left">\(0.84\)</td> </tr> <tr class ="row-a"> <td style="text-align:left">\(2\)</td> <td style="text-align:left">\(0.91\)</td> </tr> <tr class ="row-b"> <td style="text-align:left">\(3\)</td> <td style="text-align:left">\(0.14\)</td> </tr> </tbody> </table> </div> """ from itertools import cycle rows = self._rows header_row = self._options['header_row'] if self._options['frame']: frame = 'border="1"' else: frame = '' s = StringIO() if rows: s.writelines([ # If the table has < 100 rows, don't truncate the output in the notebook '<div class="notruncate">\n' if len(rows) <= 100 else '<div class="truncate">', '<table {} class="table_form">\n'.format(frame), '<tbody>\n', ]) # First row: if header_row: s.write('<tr>\n') self._html_table_row(s, rows[0], header=header_row) s.write('</tr>\n') rows = rows[1:] # Other rows: for row_class, row in zip(cycle(["row-a", "row-b"]), rows): s.write('<tr class ="{}">\n'.format(row_class)) self._html_table_row(s, row, header=False) s.write('</tr>\n') s.write('</tbody>\n</table>\n</div>') return s.getvalue() def _html_table_row(self, file, row, header=False): r""" Write table row Helper method used by the :meth:`_html_` method. INPUT: - ``file`` -- file-like object. The table row data will be written to it. - ``row`` -- a list with the same number of entries as each row of the table. - ``header`` -- bool (default False). If True, treat this as a header row, using ``<th>`` instead of ``<td>``. OUTPUT: This method returns nothing. All output is written to ``file``. Strings are written verbatim unless they seem to be LaTeX code, in which case they are enclosed in a ``script`` tag appropriate for MathJax. Sage objects are printed using their LaTeX representations. EXAMPLES:: sage: T = table([['a', 'bb', 'ccccc'], [10, -12, 0], [1, 2, 3]]) sage: from io import StringIO sage: s = StringIO() sage: T._html_table_row(s, ['a', 2, '$x$']) sage: print(s.getvalue()) <td style="text-align:left">a</td> <td style="text-align:left">\(2\)</td> <td style="text-align:left">\(x\)</td> """ from sage.plot.all import Graphics from .latex import latex from .html import math_parse import types if isinstance(row, types.GeneratorType): row = list(row) elif not isinstance(row, (list, tuple)): row = [row] align_char = self._options['align'][0] # 'l', 'c', 'r' if align_char == 'l': style = 'text-align:left' elif align_char == 'c': style = 'text-align:center' elif align_char == 'r': style = 'text-align:right' else: style = '' style_attr = f' style="{style}"' if style else '' column_tag = f'<th{style_attr}>%s</th>\n' if header else f'<td{style_attr}>%s</td>\n' if self._options['header_column']: first_column_tag = '<th class="ch"{style_attr}>%s</th>\n' if header else '<td class="ch"{style_attr}>%s</td>\n' else: first_column_tag = column_tag # first entry of row entry = row[0] if isinstance(entry, Graphics): file.write(first_column_tag % entry.show(linkmode=True)) elif isinstance(entry, str): file.write(first_column_tag % math_parse(entry)) else: file.write(first_column_tag % (r'\(%s\)' % latex(entry))) # other entries for column in range(1, len(row)): if isinstance(row[column], Graphics): file.write(column_tag % row[column].show(linkmode=True)) elif isinstance(row[column], str): file.write(column_tag % math_parse(row[column])) else: file.write(column_tag % (r'\(%s\)' % latex(row[column])))
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/table.py
0.920767
0.877004
table.py
pypi
class MultiplexFunction(): """ A simple wrapper object for functions that are called on a list of objects. """ def __init__(self, multiplexer, name): """ EXAMPLES:: sage: from sage.misc.object_multiplexer import Multiplex, MultiplexFunction sage: m = Multiplex(1,1/2) sage: f = MultiplexFunction(m,'str') sage: f <sage.misc.object_multiplexer.MultiplexFunction object at 0x...> """ self.multiplexer = multiplexer self.name = name def __call__(self, *args, **kwds): """ EXAMPLES:: sage: from sage.misc.object_multiplexer import Multiplex, MultiplexFunction sage: m = Multiplex(1,1/2) sage: f = MultiplexFunction(m,'str') sage: f() ('1', '1/2') """ l = [] for child in self.multiplexer.children: l.append(getattr(child, self.name)(*args, **kwds)) if all(e is None for e in l): return None return tuple(l) class Multiplex(): """ Object for a list of children such that function calls on this new object implies that the same function is called on all children. """ def __init__(self, *args): """ EXAMPLES:: sage: from sage.misc.object_multiplexer import Multiplex sage: m = Multiplex(1,1/2) sage: m.str() ('1', '1/2') """ self.children = [arg for arg in args if arg is not None] def __getattr__(self, name): """ EXAMPLES:: sage: from sage.misc.object_multiplexer import Multiplex sage: m = Multiplex(1,1/2) sage: m.str <sage.misc.object_multiplexer.MultiplexFunction object at 0x...> sage: m.__bork__ Traceback (most recent call last): ... AttributeError: 'Multiplex' has no attribute '__bork__' """ if name.startswith("__"): raise AttributeError("'Multiplex' has no attribute '%s'" % name) return MultiplexFunction(self, name)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/object_multiplexer.py
0.738009
0.299675
object_multiplexer.py
pypi
r""" Random Numbers with Python API AUTHORS: -- Carl Witty (2008-03): new file This module has the same functions as the Python standard module \module{random}, but uses the current \sage random number state from \module{sage.misc.randstate} (so that it can be controlled by the same global random number seeds). The functions here are less efficient than the functions in \module{random}, because they look up the current random number state on each call. If you are going to be creating many random numbers in a row, it is better to use the functions in \module{sage.misc.randstate} directly. Here is an example: (The imports on the next two lines are not necessary, since \function{randrange} and \function{current_randstate} are both available by default at the \code{sage:} prompt; but you would need them to run these examples inside a module.) :: sage: from sage.misc.prandom import randrange sage: from sage.misc.randstate import current_randstate sage: def test1(): ....: return sum([randrange(100) for i in range(100)]) sage: def test2(): ....: randrange = current_randstate().python_random().randrange ....: return sum([randrange(100) for i in range(100)]) Test2 will be slightly faster than test1, but they give the same answer:: sage: with seed(0): test1() 5169 sage: with seed(0): test2() 5169 sage: with seed(1): test1() 5097 sage: with seed(1): test2() 5097 sage: timeit('test1()') # random 625 loops, best of 3: 590 us per loop sage: timeit('test2()') # random 625 loops, best of 3: 460 us per loop The docstrings for the functions in this file are mostly copied from Python's \file{random.py}, so those docstrings are "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; All Rights Reserved" and are available under the terms of the Python Software Foundation License Version 2. """ # We deliberately omit "seed" and several other seed-related functions... # setting seeds should only be done through sage.misc.randstate . from sage.misc.randstate import current_randstate def _pyrand(): r""" A tiny private helper function to return an instance of random.Random from the current \sage random number state. Only for use in prandom.py; other modules should use current_randstate().python_random(). EXAMPLES:: sage: set_random_seed(0) sage: from sage.misc.prandom import _pyrand sage: _pyrand() <...random.Random object at 0x...> sage: _pyrand().getrandbits(10) 114 """ return current_randstate().python_random() def getrandbits(k): r""" getrandbits(k) -> x. Generates a long int with k random bits. EXAMPLES:: sage: getrandbits(10) in range(2^10) True sage: getrandbits(200) in range(2^200) True sage: getrandbits(4) in range(2^4) True """ return _pyrand().getrandbits(k) def randrange(start, stop=None, step=1): r""" Choose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want. EXAMPLES:: sage: s = randrange(0, 100, 11) sage: 0 <= s < 100 True sage: s % 11 0 sage: 5000 <= randrange(5000, 5100) < 5100 True sage: s = [randrange(0, 2) for i in range(15)] sage: all(t in [0, 1] for t in s) True sage: s = randrange(0, 1000000, 1000) sage: 0 <= s < 1000000 True sage: s % 1000 0 sage: -100 <= randrange(-100, 10) < 10 True """ return _pyrand().randrange(start, stop, step) def randint(a, b): r""" Return random integer in range [a, b], including both end points. EXAMPLES:: sage: s = [randint(0, 2) for i in range(15)]; s # random [0, 1, 0, 0, 1, 0, 2, 0, 2, 1, 2, 2, 0, 2, 2] sage: all(t in [0, 1, 2] for t in s) True sage: -100 <= randint(-100, 10) <= 10 True """ return _pyrand().randint(a, b) def choice(seq): r""" Choose a random element from a non-empty sequence. EXAMPLES:: sage: s = [choice(list(primes(10, 100))) for i in range(5)]; s # random [17, 47, 11, 31, 47] sage: all(t in primes(10, 100) for t in s) True """ return _pyrand().choice(seq) def shuffle(x): r""" x, random=random.random -> shuffle list x in place; return None. Optional arg random is a 0-argument function returning a random float in [0.0, 1.0); by default, the sage.misc.random.random. EXAMPLES:: sage: shuffle([1 .. 10]) """ return _pyrand().shuffle(x) def sample(population, k): r""" Choose k unique random elements from a population sequence. Return a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample in a range of integers, use xrange as an argument (in Python 2) or range (in Python 3). This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60) EXAMPLES:: sage: from sage.misc.misc import is_sublist sage: l = ["Here", "I", "come", "to", "save", "the", "day"] sage: s = sample(l, 3); s # random ['Here', 'to', 'day'] sage: is_sublist(sorted(s), sorted(l)) True sage: len(s) 3 sage: s = sample(range(2^30), 7); s # random [357009070, 558990255, 196187132, 752551188, 85926697, 954621491, 624802848] sage: len(s) 7 sage: all(t in range(2^30) for t in s) True """ return _pyrand().sample(population, k) def random(): r""" Get the next random number in the range [0.0, 1.0). EXAMPLES:: sage: sample = [random() for i in [1 .. 4]]; sample # random [0.111439293741037, 0.5143475134191677, 0.04468968524815642, 0.332490606442413] sage: all(0.0 <= s <= 1.0 for s in sample) True """ return _pyrand().random() def uniform(a, b): r""" Get a random number in the range [a, b). Equivalent to \code{a + (b-a) * random()}. EXAMPLES:: sage: s = uniform(0, 1); s # random 0.111439293741037 sage: 0.0 <= s <= 1.0 True sage: s = uniform(e, pi); s # random 0.5143475134191677*pi + 0.48565248658083227*e sage: bool(e <= s <= pi) True """ return _pyrand().uniform(a, b) def betavariate(alpha, beta): r""" Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. EXAMPLES:: sage: s = betavariate(0.1, 0.9); s # random 9.75087916621299e-9 sage: 0.0 <= s <= 1.0 True sage: s = betavariate(0.9, 0.1); s # random 0.941890400939253 sage: 0.0 <= s <= 1.0 True """ return _pyrand().betavariate(alpha, beta) def expovariate(lambd): r""" Exponential distribution. lambd is 1.0 divided by the desired mean. (The parameter would be called "lambda", but that is a reserved word in Python.) Returned values range from 0 to positive infinity. EXAMPLES:: sage: sample = [expovariate(0.001) for i in range(3)]; sample # random [118.152309288166, 722.261959038118, 45.7190543690470] sage: all(s >= 0.0 for s in sample) True sage: sample = [expovariate(1.0) for i in range(3)]; sample # random [0.404201816061304, 0.735220464997051, 0.201765578600627] sage: all(s >= 0.0 for s in sample) True sage: sample = [expovariate(1000) for i in range(3)]; sample # random [0.0012068700332283973, 8.340929747302108e-05, 0.00219877067980605] sage: all(s >= 0.0 for s in sample) True """ return _pyrand().expovariate(lambd) def gammavariate(alpha, beta): r""" Gamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. EXAMPLES:: sage: sample = gammavariate(1.0, 3.0); sample # random 6.58282586130638 sage: sample > 0 True sage: sample = gammavariate(3.0, 1.0); sample # random 3.07801512341612 sage: sample > 0 True """ return _pyrand().gammavariate(alpha, beta) def gauss(mu, sigma): r""" Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function, but is not thread-safe. EXAMPLES:: sage: [gauss(0, 1) for i in range(3)] # random [0.9191011757657915, 0.7744526756246484, 0.8638996866800877] sage: [gauss(0, 100) for i in range(3)] # random [24.916051749154448, -62.99272061579273, -8.1993122536718...] sage: [gauss(1000, 10) for i in range(3)] # random [998.7590700045661, 996.1087338511692, 1010.1256817458031] """ return _pyrand().gauss(mu, sigma) def lognormvariate(mu, sigma): r""" Log normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero. EXAMPLES:: sage: [lognormvariate(100, 10) for i in range(3)] # random [2.9410355688290246e+37, 2.2257548162070125e+38, 4.142299451717446e+43] """ return _pyrand().lognormvariate(mu, sigma) def normalvariate(mu, sigma): r""" Normal distribution. mu is the mean, and sigma is the standard deviation. EXAMPLES:: sage: [normalvariate(0, 1) for i in range(3)] # random [-1.372558980559407, -1.1701670364898928, 0.04324100555110143] sage: [normalvariate(0, 100) for i in range(3)] # random [37.45695875041769, 159.6347743233298, 124.1029321124009] sage: [normalvariate(1000, 10) for i in range(3)] # random [1008.5303090383741, 989.8624892644895, 985.7728921150242] """ return _pyrand().normalvariate(mu, sigma) def vonmisesvariate(mu, kappa): r""" Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi. EXAMPLES:: sage: sample = [vonmisesvariate(1.0r, 3.0r) for i in range(1, 5)]; sample # random [0.898328639355427, 0.6718030007041281, 2.0308777524813393, 1.714325253725145] sage: all(s >= 0.0 for s in sample) True """ return _pyrand().vonmisesvariate(mu, kappa) def paretovariate(alpha): r""" Pareto distribution. alpha is the shape parameter. EXAMPLES:: sage: sample = [paretovariate(3) for i in range(1, 5)]; sample # random [1.0401699394233033, 1.2722080162636495, 1.0153564009379579, 1.1442323078983077] sage: all(s >= 1.0 for s in sample) True """ return _pyrand().paretovariate(alpha) def weibullvariate(alpha, beta): r""" Weibull distribution. alpha is the scale parameter and beta is the shape parameter. EXAMPLES:: sage: sample = [weibullvariate(1, 3) for i in range(1, 5)]; sample # random [0.49069775546342537, 0.8972185564611213, 0.357573846531942, 0.739377255516847] sage: all(s >= 0.0 for s in sample) True """ return _pyrand().weibullvariate(alpha, beta)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/prandom.py
0.812198
0.794982
prandom.py
pypi
"Flatten nested lists" import sys def flatten(in_list, ltypes=(list, tuple), max_level=sys.maxsize): """ Flatten a nested list. INPUT: - ``in_list`` -- a list or tuple - ``ltypes`` -- optional list of particular types to flatten - ``max_level`` -- the maximum level to flatten OUTPUT: a flat list of the entries of ``in_list`` EXAMPLES:: sage: flatten([[1,1],[1],2]) [1, 1, 1, 2] sage: flatten([[1,2,3], (4,5), [[[1],[2]]]]) [1, 2, 3, 4, 5, 1, 2] sage: flatten([[1,2,3], (4,5), [[[1],[2]]]],max_level=1) [1, 2, 3, 4, 5, [[1], [2]]] sage: flatten([[[3],[]]],max_level=0) [[[3], []]] sage: flatten([[[3],[]]],max_level=1) [[3], []] sage: flatten([[[3],[]]],max_level=2) [3] In the following example, the vector is not flattened because it is not given in the ``ltypes`` input. :: sage: flatten((['Hi',2,vector(QQ,[1,2,3])],(4,5,6))) ['Hi', 2, (1, 2, 3), 4, 5, 6] We give the vector type and then even the vector gets flattened:: sage: tV = sage.modules.vector_rational_dense.Vector_rational_dense sage: flatten((['Hi',2,vector(QQ,[1,2,3])], (4,5,6)), ....: ltypes=(list, tuple, tV)) ['Hi', 2, 1, 2, 3, 4, 5, 6] We flatten a finite field. :: sage: flatten(GF(5)) [0, 1, 2, 3, 4] sage: flatten([GF(5)]) [Finite Field of size 5] sage: tGF = type(GF(5)) sage: flatten([GF(5)], ltypes = (list, tuple, tGF)) [0, 1, 2, 3, 4] Degenerate cases:: sage: flatten([[],[]]) [] sage: flatten([[[]]]) [] """ index = 0 current_level = 0 new_list = [x for x in in_list] level_list = [0] * len(in_list) while index < len(new_list): len_v = True while isinstance(new_list[index], ltypes) and current_level < max_level: v = list(new_list[index]) len_v = len(v) new_list[index : index + 1] = v old_level = level_list[index] level_list[index : index + 1] = [0] * len_v if len_v: current_level += 1 level_list[index + len_v - 1] = old_level + 1 else: current_level -= old_level index -= 1 break # If len_v == 0, then index points to a previous element, so we # do not need to do anything. if len_v: current_level -= level_list[index] index += 1 return new_list
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/misc/flatten.py
0.563138
0.576959
flatten.py
pypi
from sage.misc.cachefunc import cached_method from sage.structure.unique_representation import UniqueRepresentation from sage.structure.parent import Parent from sage.structure.element import ModuleElement, parent from sage.structure.richcmp import richcmp from sage.categories.chain_complexes import ChainComplexes from sage.categories.tensor import tensor from sage.combinat.free_module import CombinatorialFreeModule from sage.homology.chain_complex import ChainComplex, Chain_class class HochschildComplex(UniqueRepresentation, Parent): r""" The Hochschild complex. Let `A` be an algebra over a commutative ring `R` such that `A` a projective `R`-module, and `M` an `A`-bimodule. The *Hochschild complex* is the chain complex given by .. MATH:: C_n(A, M) := M \otimes A^{\otimes n} with the boundary operators given as follows. For fixed `n`, define the face maps .. MATH:: f_{n,i}(m \otimes a_1 \otimes \cdots \otimes a_n) = \begin{cases} m a_1 \otimes \cdots \otimes a_n & \text{if } i = 0, \\ a_n m \otimes a_1 \otimes \cdots \otimes a_{n-1} & \text{if } i = n, \\ m \otimes a_1 \otimes \cdots \otimes a_i a_{i+1} \otimes \cdots \otimes a_n & \text{otherwise.} \end{cases} We define the boundary operators as .. MATH:: d_n = \sum_{i=0}^n (-1)^i f_{n,i}. The *Hochschild homology* of `A` is the homology of this complex. Alternatively, the Hochschild homology can be described by `HH_n(A, M) = \operatorname{Tor}_n^{A^e}(A, M)`, where `A^e = A \otimes A^o` (`A^o` is the opposite algebra of `A`) is the enveloping algebra of `A`. *Hochschild cohomology* is the homology of the dual complex and can be described by `HH^n(A, M) = \operatorname{Ext}^n_{A^e}(A, M)`. Another perspective on Hochschild homology is that `f_{n,i}` make the family `C_n(A, M)` a simplicial object in the category of `R`-modules, and the degeneracy maps are .. MATH:: s_i(a_0 \otimes \cdots \otimes a_n) = a_0 \otimes \cdots \otimes a_i \otimes 1 \otimes a_{i+1} \otimes \cdots \otimes a_n The Hochschild homology can also be constructed as the homology of this simplicial module. REFERENCES: - :wikipedia:`Hochschild_homology` - https://ncatlab.org/nlab/show/Hochschild+cohomology - [Red2001]_ """ def __init__(self, A, M): """ Initialize ``self``. EXAMPLES:: sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: T = SGA.trivial_representation() sage: H = SGA.hochschild_complex(T) sage: H.category() Category of chain complexes over Rational Field sage: H in ChainComplexes(QQ) True sage: TestSuite(H).run() """ self._A = A self._M = M Parent.__init__(self, base=A.base_ring(), category=ChainComplexes(A.base_ring())) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: T = SGA.trivial_representation() sage: T.rename("Trivial representation of SGA") sage: SGA.hochschild_complex(T) Hochschild complex of Symmetric group algebra of order 3 over Rational Field with coefficients in Trivial representation of SGA sage: T.rename() # reset the name """ return "Hochschild complex of {} with coefficients in {}".format(self._A, self._M) def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: T = SGA.trivial_representation() sage: H = SGA.hochschild_complex(T) sage: latex(H) C_{\bullet}\left(..., ...\right) """ from sage.misc.latex import latex return "C_{{\\bullet}}\\left({}, {}\\right)".format(latex(self._A), latex(self._M)) def algebra(self): """ Return the defining algebra of ``self``. EXAMPLES:: sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: T = SGA.trivial_representation() sage: H = SGA.hochschild_complex(T) sage: H.algebra() Symmetric group algebra of order 3 over Rational Field """ return self._A def coefficients(self): """ Return the coefficients of ``self``. EXAMPLES:: sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: T = SGA.trivial_representation() sage: H = SGA.hochschild_complex(T) sage: H.coefficients() Trivial representation of Standard permutations of 3 over Rational Field """ return self._M def module(self, d): """ Return the module in degree ``d``. EXAMPLES:: sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: T = SGA.trivial_representation() sage: H = SGA.hochschild_complex(T) sage: H.module(0) Trivial representation of Standard permutations of 3 over Rational Field sage: H.module(1) Trivial representation of Standard permutations of 3 over Rational Field # Symmetric group algebra of order 3 over Rational Field sage: H.module(2) Trivial representation of Standard permutations of 3 over Rational Field # Symmetric group algebra of order 3 over Rational Field # Symmetric group algebra of order 3 over Rational Field """ if d < 0: raise ValueError("only defined for non-negative degree") return tensor([self._M] + [self._A] * d) @cached_method def trivial_module(self): """ Return the trivial module of ``self``. EXAMPLES:: sage: E.<x,y> = ExteriorAlgebra(QQ) sage: H = E.hochschild_complex(E) sage: H.trivial_module() Free module generated by {} over Rational Field """ return CombinatorialFreeModule(self._A.base_ring(), []) def boundary(self, d): """ Return the boundary operator in degree ``d``. EXAMPLES:: sage: E.<x,y> = ExteriorAlgebra(QQ) sage: H = E.hochschild_complex(E) sage: d1 = H.boundary(1) sage: z = d1.domain().an_element(); z 2*1 # 1 + 2*1 # x + 3*1 # y sage: d1(z) 0 sage: d1.matrix() [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 2 0 0 -2 0 0 0 0 0 0] sage: s = SymmetricFunctions(QQ).s() sage: H = s.hochschild_complex(s) sage: d1 = H.boundary(1) sage: x = d1.domain().an_element(); x 2*s[] # s[] + 2*s[] # s[1] + 3*s[] # s[2] sage: d1(x) 0 sage: y = tensor([s.an_element(), s.an_element()]) sage: d1(y) 0 sage: z = tensor([s[2,1] + s[3], s.an_element()]) sage: d1(z) 0 TESTS:: sage: def test_complex(H, n): ....: phi = H.boundary(n) ....: psi = H.boundary(n+1) ....: comp = phi * psi ....: zero = H.module(n-1).zero() ....: return all(comp(b) == zero for b in H.module(n+1).basis()) sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: H = SGA.hochschild_complex(SGA) sage: test_complex(H, 1) True sage: test_complex(H, 2) True sage: test_complex(H, 3) # long time True sage: E.<x,y> = ExteriorAlgebra(QQ) sage: H = E.hochschild_complex(E) sage: test_complex(H, 1) True sage: test_complex(H, 2) True sage: test_complex(H, 3) True """ R = self._A.base_ring() one = R.one() if d == 0: t = self.trivial_module() zero = t.zero() return self.module(0).module_morphism(lambda x: zero, codomain=t) Fd = self.module(d-1) Fd1 = self.module(d) mone = -one def on_basis(k): p = self._M.monomial(k[0]) * self._A.monomial(k[1]) ret = Fd._from_dict({(m,) + k[2:]: c for m,c in p}, remove_zeros=False) for i in range(1, d): p = self._A.monomial(k[i]) * self._A.monomial(k[i+1]) ret += mone**i * Fd._from_dict({k[:i] + (m,) + k[i+2:]: c for m,c in p}, remove_zeros=False) p = self._A.monomial(k[-1]) * self._M.monomial(k[0]) ret += mone**d * Fd._from_dict({(m,) + k[1:-1]: c for m,c in p}, remove_zeros=False) return ret return Fd1.module_morphism(on_basis, codomain=Fd) differential = boundary def coboundary(self, d): """ Return the coboundary morphism of degree ``d``. EXAMPLES:: sage: E.<x,y> = ExteriorAlgebra(QQ) sage: H = E.hochschild_complex(E) sage: del1 = H.coboundary(1) sage: z = del1.domain().an_element(); z 2 + 2*x + 3*y sage: del1(z) 0 sage: del1.matrix() [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 2] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 -2] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] TESTS:: sage: def test_complex(H, n): ....: phi = H.coboundary(n) ....: psi = H.coboundary(n+1) ....: comp = psi * phi ....: zero = H.module(n+1).zero() ....: return all(comp(b) == zero for b in H.module(n-1).basis()) sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: H = SGA.hochschild_complex(SGA) sage: test_complex(H, 1) True sage: test_complex(H, 2) True sage: E.<x,y> = ExteriorAlgebra(QQ) sage: H = E.hochschild_complex(E) sage: test_complex(H, 1) True sage: test_complex(H, 2) True sage: test_complex(H, 3) True """ if self._A.category() is not self._A.category().FiniteDimensional(): raise NotImplementedError("the algebra must be finite dimensional") bdry = self.boundary(d) dom = bdry.domain() cod = bdry.codomain() return cod.module_morphism(matrix=bdry.matrix().transpose(), codomain=dom) def homology(self, d): r""" Return the ``d``-th homology group. EXAMPLES:: sage: E.<x,y> = ExteriorAlgebra(QQ) sage: H = E.hochschild_complex(E) sage: H.homology(0) Vector space of dimension 3 over Rational Field sage: H.homology(1) Vector space of dimension 4 over Rational Field sage: H.homology(2) Vector space of dimension 6 over Rational Field sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: T = SGA.trivial_representation() sage: H = SGA.hochschild_complex(T) sage: H.homology(0) Vector space of dimension 1 over Rational Field sage: H.homology(1) Vector space of dimension 0 over Rational Field sage: H.homology(2) Vector space of dimension 0 over Rational Field When working over general rings (except `\ZZ`) and we can construct a unitriangular basis for the image quotient, we fallback to a slower implementation using (combinatorial) free modules:: sage: R.<x,y> = QQ[] sage: SGA = SymmetricGroupAlgebra(R, 2) sage: T = SGA.trivial_representation() sage: H = SGA.hochschild_complex(T) sage: H.homology(1) Free module generated by {} over Multivariate Polynomial Ring in x, y over Rational Field """ if self._A.category() is not self._A.category().FiniteDimensional(): raise NotImplementedError("the algebra must be finite dimensional") maps = {d: self.boundary(d).matrix(), d+1: self.boundary(d+1).matrix()} C = ChainComplex(maps, degree_of_differential=-1) try: return C.homology(d) except NotImplementedError: pass # Fallback if we are not working over a field or \ZZ bdry = self.boundary(d) bdry1 = self.boundary(d+1) ker = bdry.kernel() im_retract = ker.submodule([ker.retract(b) for b in bdry1.image_basis()], unitriangular=True) return ker.quotient_module(im_retract) def cohomology(self, d): r""" Return the ``d``-th cohomology group. EXAMPLES:: sage: E.<x,y> = ExteriorAlgebra(QQ) sage: H = E.hochschild_complex(E) sage: H.cohomology(0) Vector space of dimension 3 over Rational Field sage: H.cohomology(1) Vector space of dimension 4 over Rational Field sage: H.cohomology(2) Vector space of dimension 6 over Rational Field sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: T = SGA.trivial_representation() sage: H = SGA.hochschild_complex(T) sage: H.cohomology(0) Vector space of dimension 1 over Rational Field sage: H.cohomology(1) Vector space of dimension 0 over Rational Field sage: H.cohomology(2) Vector space of dimension 0 over Rational Field When working over general rings (except `\ZZ`) and we can construct a unitriangular basis for the image quotient, we fallback to a slower implementation using (combinatorial) free modules:: sage: R.<x,y> = QQ[] sage: SGA = SymmetricGroupAlgebra(R, 2) sage: T = SGA.trivial_representation() sage: H = SGA.hochschild_complex(T) sage: H.cohomology(1) Free module generated by {} over Multivariate Polynomial Ring in x, y over Rational Field """ if self._A.category() is not self._A.category().FiniteDimensional(): raise NotImplementedError("the algebra must be finite dimensional") maps = {d+1: self.coboundary(d+1).matrix(), d: self.coboundary(d).matrix()} C = ChainComplex(maps, degree_of_differential=1) try: return C.homology(d+1) except NotImplementedError: pass # Fallback if we are not working over a field or \ZZ cb = self.coboundary(d) cb1 = self.coboundary(d+1) ker = cb1.kernel() im_retract = ker.submodule([ker.retract(b) for b in cb.image_basis()], unitriangular=True) return ker.quotient_module(im_retract) def _element_constructor_(self, vectors): """ Construct an element of ``self`` from ``vectors``. TESTS:: sage: E.<x,y> = ExteriorAlgebra(QQ) sage: H = E.hochschild_complex(E) sage: H(0) Trivial chain sage: H(2) Chain(0: 2) sage: H(x+2*y) Chain(0: x + 2*y) sage: H({0: H.module(0).an_element()}) Chain(0: 2 + 2*x + 3*y) sage: H({2: H.module(2).an_element()}) Chain(2: 2*1 # 1 # 1 + 2*1 # 1 # x + 3*1 # 1 # y) sage: H({0:x-y, 2: H.module(2).an_element()}) Chain with 2 nonzero terms over Rational Field sage: H([2]) Traceback (most recent call last): ... ValueError: cannot construct an element from [2] """ if not vectors: # special case: the zero chain return self.element_class(self, {}) # special case: an element of the defining module if self._M.has_coerce_map_from(parent(vectors)): vectors = self._M(vectors) if parent(vectors) is self._M: mc = vectors.monomial_coefficients(copy=False) vec = self.module(0)._from_dict({(k,): mc[k] for k in mc}) return self.element_class(self, {0: vec}) if isinstance(vectors, (Chain_class, self.element_class)): vectors = vectors._vec data = dict() if not isinstance(vectors, dict): raise ValueError("cannot construct an element from {}".format(vectors)) # Special handling for the 0 free module # FIXME: Allow coercions between the 0 free module and the defining module if 0 in vectors: vec = vectors.pop(0) if parent(vec) is self._M: mc = vec.monomial_coefficients(copy=False) data[0] = self.module(0)._from_dict({(k,): mc[k] for k in mc}) else: data[0] = self.module(0)(vec) for degree in vectors: vec = self.module(degree)(vectors[degree]) if not vec: continue data[degree] = vec return self.element_class(self, data) def _an_element_(self): """ Return an element of ``self``. EXAMPLES:: sage: F.<x,y> = FreeAlgebra(ZZ) sage: H = F.hochschild_complex(F) sage: v = H.an_element() sage: [v.vector(i) for i in range(6)] [2*F[1] + 2*F[x] + 3*F[y], 2*F[1] # F[1] + 2*F[1] # F[x] + 3*F[1] # F[y], 2*F[1] # F[1] # F[1] + 2*F[1] # F[1] # F[x] + 3*F[1] # F[1] # F[y], 2*F[1] # F[1] # F[1] # F[1] + 2*F[1] # F[1] # F[1] # F[x] + 3*F[1] # F[1] # F[1] # F[y], 0, 0] """ return self.element_class(self, {d: self.module(d).an_element() for d in range(4)}) class Element(ModuleElement): """ A chain of the Hochschild complex. INPUT: Can be one of the following: - A dictionary whose keys are the degree and whose `d`-th value is an element in the degree `d` module. - An element in the coefficient module `M`. EXAMPLES:: sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: T = SGA.trivial_representation() sage: H = SGA.hochschild_complex(T) sage: H(T.an_element()) Chain(0: 2*B['v']) sage: H({0: T.an_element()}) Chain(0: 2*B['v']) sage: H({1: H.module(1).an_element()}) Chain(1: 2*B['v'] # [1, 2, 3] + 2*B['v'] # [1, 3, 2] + 3*B['v'] # [2, 1, 3]) sage: H({0: H.module(0).an_element(), 3: H.module(3).an_element()}) Chain with 2 nonzero terms over Rational Field sage: F.<x,y> = FreeAlgebra(ZZ) sage: H = F.hochschild_complex(F) sage: H(x + 2*y^2) Chain(0: F[x] + 2*F[y^2]) sage: H({0: x*y - x}) Chain(0: -F[x] + F[x*y]) sage: H(2) Chain(0: 2*F[1]) sage: H({0: x-y, 2: H.module(2).basis().an_element()}) Chain with 2 nonzero terms over Integer Ring """ def __init__(self, parent, vectors): """ Initialize ``self``. EXAMPLES:: sage: F.<x,y> = FreeAlgebra(ZZ) sage: H = F.hochschild_complex(F) sage: a = H({0: x-y, 2: H.module(2).basis().an_element()}) sage: TestSuite(a).run() """ self._vec = vectors ModuleElement.__init__(self, parent) def vector(self, degree): """ Return the free module element in ``degree``. EXAMPLES:: sage: F.<x,y> = FreeAlgebra(ZZ) sage: H = F.hochschild_complex(F) sage: a = H({0: x-y, 2: H.module(2).basis().an_element()}) sage: [a.vector(i) for i in range(3)] [F[x] - F[y], 0, F[1] # F[1] # F[1]] """ try: return self._vec[degree] except KeyError: return self.parent().module(degree).zero() def _repr_(self): """ Print representation. EXAMPLES:: sage: E.<x,y> = ExteriorAlgebra(QQ) sage: H = E.hochschild_complex(E) sage: H(0) Trivial chain sage: H(x+2*y) Chain(0: x + 2*y) sage: H({2: H.module(2).an_element()}) Chain(2: 2*1 # 1 # 1 + 2*1 # 1 # x + 3*1 # 1 # y) sage: H({0:x-y, 2: H.module(2).an_element()}) Chain with 2 nonzero terms over Rational Field """ n = len(self._vec) if n == 0: return 'Trivial chain' if n == 1: (deg, vec), = self._vec.items() return 'Chain({0}: {1})'.format(deg, vec) return 'Chain with {0} nonzero terms over {1}'.format(n, self.parent().base_ring()) def _ascii_art_(self): """ Return an ascii art representation. Note that arrows go to the left so that composition of differentials is the usual matrix multiplication. EXAMPLES:: sage: F.<x,y> = FreeAlgebra(ZZ) sage: H = F.hochschild_complex(F) sage: a = H({0: x - y, ....: 1: H.module(1).basis().an_element(), ....: 2: H.module(2).basis().an_element()}) sage: ascii_art(a) d_0 d_1 d_2 d_3 0 <---- F - F <---- 1 # 1 <---- 1 # 1 # 1 <---- 0 x y """ from sage.typeset.ascii_art import AsciiArt, ascii_art if not self._vec: # 0 chain return AsciiArt(['0']) def arrow_art(d): d_str = [' d_{0} '.format(d)] arrow = ' <' + '-'*(len(d_str[0])-3) + ' ' d_str.append(arrow) return AsciiArt(d_str, baseline=0) result = AsciiArt(['0']) max_deg = max(self._vec) for deg in range(min(self._vec), max_deg+1): A = ascii_art(self.vector(deg)) A._baseline = A.height() // 2 result += arrow_art(deg) + A return result + arrow_art(max_deg+1) + AsciiArt(['0']) def _add_(self, other): """ Module addition EXAMPLES:: sage: F.<x,y> = FreeAlgebra(ZZ) sage: H = F.hochschild_complex(F) sage: a = H({0: x - y, ....: 1: H.module(1).basis().an_element(), ....: 2: H.module(2).basis().an_element()}) sage: [a.vector(i) for i in range(3)] [F[x] - F[y], F[1] # F[1], F[1] # F[1] # F[1]] sage: [H.an_element().vector(i) for i in range(3)] [2*F[1] + 2*F[x] + 3*F[y], 2*F[1] # F[1] + 2*F[1] # F[x] + 3*F[1] # F[y], 2*F[1] # F[1] # F[1] + 2*F[1] # F[1] # F[x] + 3*F[1] # F[1] # F[y]] sage: v = a + H.an_element() sage: [v.vector(i) for i in range(3)] [2*F[1] + 3*F[x] + 2*F[y], 3*F[1] # F[1] + 2*F[1] # F[x] + 3*F[1] # F[y], 3*F[1] # F[1] # F[1] + 2*F[1] # F[1] # F[x] + 3*F[1] # F[1] # F[y]] """ vectors = dict(self._vec) # Make a (shallow) copy for d in other._vec: if d in vectors: vectors[d] += other._vec[d] if not vectors[d]: del vectors[d] else: vectors[d] = other._vec parent = self.parent() return parent.element_class(parent, vectors) def _lmul_(self, scalar): """ Scalar multiplication EXAMPLES:: sage: F.<x,y> = FreeAlgebra(ZZ) sage: H = F.hochschild_complex(F) sage: a = H({0: x - y, ....: 1: H.module(1).basis().an_element(), ....: 2: H.module(2).basis().an_element()}) sage: v = 3*a sage: [v.vector(i) for i in range(3)] [3*F[x] - 3*F[y], 3*F[1] # F[1], 3*F[1] # F[1] # F[1]] """ if scalar == 0: return self.zero() vectors = dict() for d in self._vec: vec = scalar * self._vec[d] if vec: vectors[d] = vec return self.__class__(self.parent(), vectors) def _richcmp_(self, other, op): """ Rich comparison of ``self`` to ``other``. EXAMPLES:: sage: F.<x,y> = FreeAlgebra(ZZ) sage: H = F.hochschild_complex(F) sage: a = H({0: x - y, ....: 1: H.module(1).basis().an_element(), ....: 2: H.module(2).basis().an_element()}) sage: a == 3*a False sage: a + a == 2*a True sage: a == H.zero() False sage: a != 3*a True sage: a + a != 2*a False sage: a != H.zero() True """ return richcmp(self._vec, other._vec, op)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/homology/hochschild_complex.py
0.925129
0.685035
hochschild_complex.py
pypi
from sage.structure.unique_representation import UniqueRepresentation from sage.structure.parent import Parent from sage.combinat.combination import rank from sage.arith.all import binomial from sage.rings.integer_ring import ZZ from sage.matrix.constructor import matrix from sage.homology.chain_complex import ChainComplex_class import itertools class KoszulComplex(ChainComplex_class, UniqueRepresentation): r""" A Koszul complex. Let `R` be a ring and consider `x_1, x_2, \ldots, x_n \in R`. The *Koszul complex* `K_*(x_1, \ldots, x_n)` is given by defining a chain complex structure on the exterior algebra `\bigwedge^n R` with the basis `e_{i_1} \wedge \cdots \wedge e_{i_a}`. The differential is given by .. MATH:: \partial(e_{i_1} \wedge \cdots \wedge e_{i_a}) = \sum_{r=1}^a (-1)^{r-1} x_{i_r} e_{i_1} \wedge \cdots \wedge \hat{e}_{i_r} \wedge \cdots \wedge e_{i_a}, where `\hat{e}_{i_r}` denotes the omitted factor. Alternatively we can describe the Koszul complex by considering the basic complex `K_{x_i}` .. MATH:: 0 \rightarrow R \xrightarrow{x_i} R \rightarrow 0. Then the Koszul complex is given by `K_*(x_1, \ldots, x_n) = \bigotimes_i K_{x_i}`. INPUT: - ``R`` -- the base ring - ``elements`` -- a tuple of elements of ``R`` EXAMPLES:: sage: R.<x,y,z> = QQ[] sage: K = KoszulComplex(R, [x,y]) sage: ascii_art(K) [-y] [x y] [ x] 0 <-- C_0 <------ C_1 <----- C_2 <-- 0 sage: K = KoszulComplex(R, [x,y,z]) sage: ascii_art(K) [-y -z 0] [ z] [ x 0 -z] [-y] [x y z] [ 0 x y] [ x] 0 <-- C_0 <-------- C_1 <----------- C_2 <----- C_3 <-- 0 sage: K = KoszulComplex(R, [x+y*z,x+y-z]) sage: ascii_art(K) [-x - y + z] [ y*z + x x + y - z] [ y*z + x] 0 <-- C_0 <---------------------- C_1 <------------- C_2 <-- 0 REFERENCES: - :wikipedia:`Koszul_complex` """ @staticmethod def __classcall_private__(cls, R=None, elements=None): """ Normalize input to ensure a unique representation. TESTS:: sage: R.<x,y,z> = QQ[] sage: K1 = KoszulComplex(R, [x,y,z]) sage: K2 = KoszulComplex(R, (x,y,z)) sage: K3 = KoszulComplex((x,y,z)) sage: K1 is K2 and K2 is K3 True Check some corner cases:: sage: K1 = KoszulComplex(ZZ) sage: K2 = KoszulComplex(()) sage: K3 = KoszulComplex(ZZ, []) sage: K1 is K2 and K2 is K3 True sage: K1 is KoszulComplex() True """ if elements is None: if R is None: R = () elements = R if not elements: R = ZZ # default to ZZ as the base ring if no elements are given elif isinstance(R, Parent): elements = () else: R = elements[0].parent() elif R is None: # elements is not None R = elements[0].parent() return super(KoszulComplex, cls).__classcall__(cls, R, tuple(elements)) def __init__(self, R, elements): """ Initialize ``self``. EXAMPLES:: sage: R.<x,y,z> = QQ[] sage: K = KoszulComplex(R, [x,y]) sage: TestSuite(K).run() """ # Generate the differentials self._elements = elements n = len(elements) I = list(range(n)) diff = {} zero = R.zero() for i in I: M = matrix(R, binomial(n,i), binomial(n,i+1), zero) j = 0 for comb in itertools.combinations(I, i+1): for k,val in enumerate(comb): r = rank(comb[:k] + comb[k+1:], n, False) M[r,j] = (-1)**k * elements[val] j += 1 M.set_immutable() diff[i+1] = M diff[0] = matrix(R, 0, 1, zero) diff[0].set_immutable() diff[n+1] = matrix(R, 1, 0, zero) diff[n+1].set_immutable() ChainComplex_class.__init__(self, ZZ, ZZ(-1), R, diff) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: R.<x,y,z> = QQ[] sage: KoszulComplex(R, [x,y,z]) Koszul complex defined by (x, y, z) over Multivariate Polynomial Ring in x, y, z over Rational Field sage: KoszulComplex(ZZ, []) Trivial Koszul complex over Integer Ring """ if not self._elements: return "Trivial Koszul complex over {}".format(self.base_ring()) return "Koszul complex defined by {} over {}".format(self._elements, self.base_ring())
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/homology/koszul_complex.py
0.914811
0.739211
koszul_complex.py
pypi
from sage.modules.free_module import VectorSpace from sage.groups.additive_abelian.additive_abelian_group import AdditiveAbelianGroup_fixed_gens from sage.rings.integer_ring import ZZ class HomologyGroup_class(AdditiveAbelianGroup_fixed_gens): """ Discrete Abelian group on `n` generators. This class inherits from :class:`~sage.groups.additive_abelian.additive_abelian_group.AdditiveAbelianGroup_fixed_gens`; see :mod:`sage.groups.additive_abelian.additive_abelian_group` for more documentation. The main difference between the classes is in the print representation. EXAMPLES:: sage: from sage.homology.homology_group import HomologyGroup sage: G = AbelianGroup(5, [5,5,7,8,9]); G Multiplicative Abelian group isomorphic to C5 x C5 x C7 x C8 x C9 sage: H = HomologyGroup(5, ZZ, [5,5,7,8,9]); H C5 x C5 x C7 x C8 x C9 sage: G == loads(dumps(G)) True sage: AbelianGroup(4) Multiplicative Abelian group isomorphic to Z x Z x Z x Z sage: HomologyGroup(4, ZZ) Z x Z x Z x Z sage: HomologyGroup(100, ZZ) Z^100 """ def __init__(self, n, invfac): """ See :func:`HomologyGroup` for full documentation. EXAMPLES:: sage: from sage.homology.homology_group import HomologyGroup sage: H = HomologyGroup(5, ZZ, [5,5,7,8,9]); H C5 x C5 x C7 x C8 x C9 """ n = len(invfac) A = ZZ ** n B = A.span([A.gen(i) * invfac[i] for i in range(n)]) AdditiveAbelianGroup_fixed_gens.__init__(self, A, B, A.gens()) self._original_invts = invfac def _repr_(self): """ Print representation of ``self``. EXAMPLES:: sage: from sage.homology.homology_group import HomologyGroup sage: H = HomologyGroup(7, ZZ, [4,4,4,4,4,7,7]) sage: H._repr_() 'C4^5 x C7 x C7' sage: HomologyGroup(6, ZZ) Z^6 """ eldv = self._original_invts if len(eldv) == 0: return "0" rank = len([x for x in eldv if x == 0]) torsion = sorted(x for x in eldv if x) if rank > 4: g = ["Z^%s" % rank] else: g = ["Z"] * rank if len(torsion) != 0: printed = [] for t in torsion: numfac = torsion.count(t) too_many = (numfac > 4) if too_many: if t not in printed: g.append("C{}^{}".format(t, numfac)) printed.append(t) else: g.append("C%s" % t) times = " x " return times.join(g) def _latex_(self): r""" LaTeX representation of ``self``. EXAMPLES:: sage: from sage.homology.homology_group import HomologyGroup sage: H = HomologyGroup(7, ZZ, [4,4,4,4,4,7,7]) sage: H._latex_() 'C_{4}^{5} \\times C_{7} \\times C_{7}' sage: latex(HomologyGroup(6, ZZ)) \ZZ^{6} """ eldv = self._original_invts if len(eldv) == 0: return "0" rank = len([x for x in eldv if x == 0]) torsion = sorted(x for x in eldv if x) if rank > 4: g = ["\\ZZ^{{{}}}".format(rank)] else: g = ["\\ZZ"] * rank if len(torsion) != 0: printed = [] for t in torsion: numfac = torsion.count(t) too_many = (numfac > 4) if too_many: if t not in printed: g.append("C_{{{}}}^{{{}}}".format(t, numfac)) printed.append(t) else: g.append("C_{{{}}}".format(t)) times = " \\times " return times.join(g) def HomologyGroup(n, base_ring, invfac=None): """ Abelian group on `n` generators which represents a homology group in a fixed degree. INPUT: - ``n`` -- integer; the number of generators - ``base_ring`` -- ring; the base ring over which the homology is computed - ``inv_fac`` -- list of integers; the invariant factors -- ignored if the base ring is a field OUTPUT: A class that can represent the homology group in a fixed homological degree. EXAMPLES:: sage: from sage.homology.homology_group import HomologyGroup sage: G = AbelianGroup(5, [5,5,7,8,9]); G Multiplicative Abelian group isomorphic to C5 x C5 x C7 x C8 x C9 sage: H = HomologyGroup(5, ZZ, [5,5,7,8,9]); H C5 x C5 x C7 x C8 x C9 sage: AbelianGroup(4) Multiplicative Abelian group isomorphic to Z x Z x Z x Z sage: HomologyGroup(4, ZZ) Z x Z x Z x Z sage: HomologyGroup(100, ZZ) Z^100 """ if base_ring.is_field(): return VectorSpace(base_ring, n) # copied from AbelianGroup: if invfac is None: if isinstance(n, (list, tuple)): invfac = n n = len(n) else: invfac = [] if len(invfac) < n: invfac = [0] * (n - len(invfac)) + invfac elif len(invfac) > n: raise ValueError("invfac (={}) must have length n (={})".format(invfac, n)) return HomologyGroup_class(n, invfac)
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/homology/homology_group.py
0.873417
0.455441
homology_group.py
pypi
from .calculus import SR from sage.symbolic.expression import Expression def simplify(f): r""" Simplify the expression `f`. EXAMPLES: We simplify the expression `i + x - x`. :: sage: f = I + x - x; simplify(f) I In fact, printing `f` yields the same thing - i.e., the simplified form. """ try: return f.simplify() except AttributeError: return f def derivative(f, *args, **kwds): r""" The derivative of `f`. Repeated differentiation is supported by the syntax given in the examples below. ALIAS: diff EXAMPLES: We differentiate a callable symbolic function:: sage: f(x,y) = x*y + sin(x^2) + e^(-x) sage: f (x, y) |--> x*y + e^(-x) + sin(x^2) sage: derivative(f, x) (x, y) |--> 2*x*cos(x^2) + y - e^(-x) sage: derivative(f, y) (x, y) |--> x We differentiate a polynomial:: sage: t = polygen(QQ, 't') sage: f = (1-t)^5; f -t^5 + 5*t^4 - 10*t^3 + 10*t^2 - 5*t + 1 sage: derivative(f) -5*t^4 + 20*t^3 - 30*t^2 + 20*t - 5 sage: derivative(f, t) -5*t^4 + 20*t^3 - 30*t^2 + 20*t - 5 sage: derivative(f, t, t) -20*t^3 + 60*t^2 - 60*t + 20 sage: derivative(f, t, 2) -20*t^3 + 60*t^2 - 60*t + 20 sage: derivative(f, 2) -20*t^3 + 60*t^2 - 60*t + 20 We differentiate a symbolic expression:: sage: var('a x') (a, x) sage: f = exp(sin(a - x^2))/x sage: derivative(f, x) -2*cos(-x^2 + a)*e^(sin(-x^2 + a)) - e^(sin(-x^2 + a))/x^2 sage: derivative(f, a) cos(-x^2 + a)*e^(sin(-x^2 + a))/x Syntax for repeated differentiation:: sage: R.<u, v> = PolynomialRing(QQ) sage: f = u^4*v^5 sage: derivative(f, u) 4*u^3*v^5 sage: f.derivative(u) # can always use method notation too 4*u^3*v^5 :: sage: derivative(f, u, u) 12*u^2*v^5 sage: derivative(f, u, u, u) 24*u*v^5 sage: derivative(f, u, 3) 24*u*v^5 :: sage: derivative(f, u, v) 20*u^3*v^4 sage: derivative(f, u, 2, v) 60*u^2*v^4 sage: derivative(f, u, v, 2) 80*u^3*v^3 sage: derivative(f, [u, v, v]) 80*u^3*v^3 We differentiate a scalar field on a manifold:: sage: M = Manifold(2, 'M') sage: X.<x,y> = M.chart() sage: f = M.scalar_field(x^2*y, name='f') sage: derivative(f) 1-form df on the 2-dimensional differentiable manifold M sage: derivative(f).display() df = 2*x*y dx + x^2 dy We differentiate a differentiable form, getting its exterior derivative:: sage: a = M.one_form(-y, x, name='a'); a.display() a = -y dx + x dy sage: derivative(a) 2-form da on the 2-dimensional differentiable manifold M sage: derivative(a).display() da = 2 dx∧dy """ try: return f.derivative(*args, **kwds) except AttributeError: pass if not isinstance(f, Expression): f = SR(f) return f.derivative(*args, **kwds) diff = derivative def integral(f, *args, **kwds): r""" The integral of `f`. EXAMPLES:: sage: integral(sin(x), x) -cos(x) sage: integral(sin(x)^2, x, pi, 123*pi/2) 121/4*pi sage: integral( sin(x), x, 0, pi) 2 We integrate a symbolic function:: sage: f(x,y,z) = x*y/z + sin(z) sage: integral(f, z) (x, y, z) |--> x*y*log(z) - cos(z) :: sage: var('a,b') (a, b) sage: assume(b-a>0) sage: integral( sin(x), x, a, b) cos(a) - cos(b) sage: forget() :: sage: integral(x/(x^3-1), x) 1/3*sqrt(3)*arctan(1/3*sqrt(3)*(2*x + 1)) - 1/6*log(x^2 + x + 1) + 1/3*log(x - 1) :: sage: integral( exp(-x^2), x ) 1/2*sqrt(pi)*erf(x) We define the Gaussian, plot and integrate it numerically and symbolically:: sage: f(x) = 1/(sqrt(2*pi)) * e^(-x^2/2) sage: P = plot(f, -4, 4, hue=0.8, thickness=2) sage: P.show(ymin=0, ymax=0.4) sage: numerical_integral(f, -4, 4) # random output (0.99993665751633376, 1.1101527003413533e-14) sage: integrate(f, x) x |--> 1/2*erf(1/2*sqrt(2)*x) You can have Sage calculate multiple integrals. For example, consider the function `exp(y^2)` on the region between the lines `x=y`, `x=1`, and `y=0`. We find the value of the integral on this region using the command:: sage: area = integral(integral(exp(y^2),x,0,y),y,0,1); area 1/2*e - 1/2 sage: float(area) 0.859140914229522... We compute the line integral of `\sin(x)` along the arc of the curve `x=y^4` from `(1,-1)` to `(1,1)`:: sage: t = var('t') sage: (x,y) = (t^4,t) sage: (dx,dy) = (diff(x,t), diff(y,t)) sage: integral(sin(x)*dx, t,-1, 1) 0 sage: restore('x,y') # restore the symbolic variables x and y Sage is now (:trac:`27958`) able to compute the following integral:: sage: result = integral(exp(-x^2)*log(x), x) ... sage: result 1/2*sqrt(pi)*erf(x)*log(x) - x*hypergeometric((1/2, 1/2), (3/2, 3/2), -x^2) and its value:: sage: integral( exp(-x^2)*ln(x), x, 0, oo) -1/4*sqrt(pi)*(euler_gamma + 2*log(2)) This definite integral is easy:: sage: integral( ln(x)/x, x, 1, 2) 1/2*log(2)^2 Sage cannot do this elliptic integral (yet):: sage: integral(1/sqrt(2*t^4 - 3*t^2 - 2), t, 2, 3) integrate(1/(sqrt(2*t^2 + 1)*sqrt(t^2 - 2)), t, 2, 3) A double integral:: sage: y = var('y') sage: integral(integral(x*y^2, x, 0, y), y, -2, 2) 32/5 This illustrates using assumptions:: sage: integral(abs(x), x, 0, 5) 25/2 sage: a = var("a") sage: integral(abs(x), x, 0, a) 1/2*a*abs(a) sage: integral(abs(x)*x, x, 0, a) Traceback (most recent call last): ... ValueError: Computation failed since Maxima requested additional constraints; using the 'assume' command before evaluation *may* help (example of legal syntax is 'assume(a>0)', see `assume?` for more details) Is a positive, negative or zero? sage: assume(a>0) sage: integral(abs(x)*x, x, 0, a) 1/3*a^3 sage: forget() # forget the assumptions. We integrate and differentiate a huge mess:: sage: f = (x^2-1+3*(1+x^2)^(1/3))/(1+x^2)^(2/3)*x/(x^2+2)^2 sage: g = integral(f, x) sage: h = f - diff(g, x) :: sage: [float(h(x=i)) for i in range(5)] #random [0.0, -1.1102230246251565e-16, -5.5511151231257827e-17, -5.5511151231257827e-17, -6.9388939039072284e-17] sage: h.factor() 0 sage: bool(h == 0) True """ try: return f.integral(*args, **kwds) except AttributeError: pass if not isinstance(f, Expression): f = SR(f) return f.integral(*args, **kwds) integrate = integral def limit(f, dir=None, taylor=False, **argv): r""" Return the limit as the variable `v` approaches `a` from the given direction. :: limit(expr, x = a) limit(expr, x = a, dir='above') INPUT: - ``dir`` - (default: None); dir may have the value 'plus' (or 'above') for a limit from above, 'minus' (or 'below') for a limit from below, or may be omitted (implying a two-sided limit is to be computed). - ``taylor`` - (default: False); if True, use Taylor series, which allows more limits to be computed (but may also crash in some obscure cases due to bugs in Maxima). - ``\*\*argv`` - 1 named parameter ALIAS: You can also use lim instead of limit. EXAMPLES:: sage: limit(sin(x)/x, x=0) 1 sage: limit(exp(x), x=oo) +Infinity sage: lim(exp(x), x=-oo) 0 sage: lim(1/x, x=0) Infinity sage: limit(sqrt(x^2+x+1)+x, taylor=True, x=-oo) -1/2 sage: limit((tan(sin(x)) - sin(tan(x)))/x^7, taylor=True, x=0) 1/30 Sage does not know how to do this limit (which is 0), so it returns it unevaluated:: sage: lim(exp(x^2)*(1-erf(x)), x=infinity) -limit((erf(x) - 1)*e^(x^2), x, +Infinity) """ if not isinstance(f, Expression): f = SR(f) return f.limit(dir=dir, taylor=taylor, **argv) lim = limit def taylor(f, *args): """ Expands self in a truncated Taylor or Laurent series in the variable `v` around the point `a`, containing terms through `(x - a)^n`. Functions in more variables are also supported. INPUT: - ``*args`` - the following notation is supported - ``x, a, n`` - variable, point, degree - ``(x, a), (y, b), ..., n`` - variables with points, degree of polynomial EXAMPLES:: sage: var('x,k,n') (x, k, n) sage: taylor (sqrt (1 - k^2*sin(x)^2), x, 0, 6) -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 :: sage: taylor ((x + 1)^n, x, 0, 4) 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 :: sage: taylor ((x + 1)^n, x, 0, 4) 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 Taylor polynomial in two variables:: sage: x,y=var('x y'); taylor(x*y^3,(x,1),(y,-1),4) (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 """ if not isinstance(f, Expression): f = SR(f) return f.taylor(*args) def expand(x, *args, **kwds): """ EXAMPLES:: sage: a = (x-1)*(x^2 - 1); a (x^2 - 1)*(x - 1) sage: expand(a) x^3 - x^2 - x + 1 You can also use expand on polynomial, integer, and other factorizations:: sage: x = polygen(ZZ) sage: F = factor(x^12 - 1); F (x - 1) * (x + 1) * (x^2 - x + 1) * (x^2 + 1) * (x^2 + x + 1) * (x^4 - x^2 + 1) sage: expand(F) x^12 - 1 sage: F.expand() x^12 - 1 sage: F = factor(2007); F 3^2 * 223 sage: expand(F) 2007 Note: If you want to compute the expanded form of a polynomial arithmetic operation quickly and the coefficients of the polynomial all lie in some ring, e.g., the integers, it is vastly faster to create a polynomial ring and do the arithmetic there. :: sage: x = polygen(ZZ) # polynomial over a given base ring. sage: f = sum(x^n for n in range(5)) sage: f*f # much faster, even if the degree is huge x^8 + 2*x^7 + 3*x^6 + 4*x^5 + 5*x^4 + 4*x^3 + 3*x^2 + 2*x + 1 TESTS:: sage: t1 = (sqrt(3)-3)*(sqrt(3)+1)/6 sage: tt1 = -1/sqrt(3) sage: t2 = sqrt(3)/6 sage: float(t1) -0.577350269189625... sage: float(tt1) -0.577350269189625... sage: float(t2) 0.28867513459481287 sage: float(expand(t1 + t2)) -0.288675134594812... sage: float(expand(tt1 + t2)) -0.288675134594812... """ try: return x.expand(*args, **kwds) except AttributeError: return x
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/calculus/functional.py
0.924688
0.818338
functional.py
pypi
from .calculus import maxima as maxima_calculus from .calculus import (laplace, inverse_laplace, limit, lim) from .integration import numerical_integral, monte_carlo_integral integral_numerical = numerical_integral from .interpolation import spline, Spline from .functional import (diff, derivative, expand, taylor, simplify) from .functions import (wronskian,jacobian) from .ode import ode_solver, ode_system from .desolvers import (desolve, desolve_laplace, desolve_system, eulers_method, eulers_method_2x2, eulers_method_2x2_plot, desolve_rk4, desolve_system_rk4, desolve_odeint, desolve_mintides, desolve_tides_mpfr) from .var import (var, function, clear_vars) from .transforms.all import * # We lazy_import the following modules since they import numpy which slows down sage startup from sage.misc.lazy_import import lazy_import lazy_import("sage.calculus.riemann",["Riemann_Map"]) lazy_import("sage.calculus.interpolators",["polygon_spline","complex_cubic_spline"]) from sage.modules.free_module_element import vector from sage.matrix.constructor import matrix def symbolic_expression(x): """ Create a symbolic expression or vector of symbolic expressions from x. INPUT: - ``x`` - an object OUTPUT: - a symbolic expression. EXAMPLES:: sage: a = symbolic_expression(3/2); a 3/2 sage: type(a) <class 'sage.symbolic.expression.Expression'> sage: R.<x> = QQ[]; type(x) <class 'sage.rings.polynomial.polynomial_rational_flint.Polynomial_rational_flint'> sage: a = symbolic_expression(2*x^2 + 3); a 2*x^2 + 3 sage: type(a) <class 'sage.symbolic.expression.Expression'> sage: from sage.structure.element import Expression sage: isinstance(a, Expression) True sage: a in SR True sage: a.parent() Symbolic Ring Note that equations exist in the symbolic ring:: sage: E = EllipticCurve('15a'); E Elliptic Curve defined by y^2 + x*y + y = x^3 + x^2 - 10*x - 10 over Rational Field sage: symbolic_expression(E) x*y + y^2 + y == x^3 + x^2 - 10*x - 10 sage: symbolic_expression(E) in SR True If ``x`` is a list or tuple, create a vector of symbolic expressions:: sage: v=symbolic_expression([x,1]); v (x, 1) sage: v.base_ring() Symbolic Ring sage: v=symbolic_expression((x,1)); v (x, 1) sage: v.base_ring() Symbolic Ring sage: v=symbolic_expression((3,1)); v (3, 1) sage: v.base_ring() Symbolic Ring sage: E = EllipticCurve('15a'); E Elliptic Curve defined by y^2 + x*y + y = x^3 + x^2 - 10*x - 10 over Rational Field sage: v=symbolic_expression([E,E]); v (x*y + y^2 + y == x^3 + x^2 - 10*x - 10, x*y + y^2 + y == x^3 + x^2 - 10*x - 10) sage: v.base_ring() Symbolic Ring Likewise, if ``x`` is a vector, create a vector of symbolic expressions:: sage: u = vector([1, 2, 3]) sage: v = symbolic_expression(u); v (1, 2, 3) sage: v.parent() Vector space of dimension 3 over Symbolic Ring If ``x`` is a list or tuple of lists/tuples/vectors, create a matrix of symbolic expressions:: sage: M = symbolic_expression([[1, x, x^2], (x, x^2, x^3), vector([x^2, x^3, x^4])]); M [ 1 x x^2] [ x x^2 x^3] [x^2 x^3 x^4] sage: M.parent() Full MatrixSpace of 3 by 3 dense matrices over Symbolic Ring If ``x`` is a matrix, create a matrix of symbolic expressions:: sage: A = matrix([[1, 2, 3], [4, 5, 6]]) sage: B = symbolic_expression(A); B [1 2 3] [4 5 6] sage: B.parent() Full MatrixSpace of 2 by 3 dense matrices over Symbolic Ring If ``x`` is a function, for example defined by a ``lambda`` expression, create a symbolic function:: sage: f = symbolic_expression(lambda z: z^2 + 1); f z |--> z^2 + 1 sage: f.parent() Callable function ring with argument z sage: f(7) 50 If ``x`` is a list or tuple of functions, or if ``x`` is a function that returns a list or tuple, create a callable symbolic vector:: sage: symbolic_expression([lambda mu, nu: mu^2 + nu^2, lambda mu, nu: mu^2 - nu^2]) (mu, nu) |--> (mu^2 + nu^2, mu^2 - nu^2) sage: f = symbolic_expression(lambda uwu: [1, uwu, uwu^2]); f uwu |--> (1, uwu, uwu^2) sage: f.parent() Vector space of dimension 3 over Callable function ring with argument uwu sage: f(5) (1, 5, 25) sage: f(5).parent() Vector space of dimension 3 over Symbolic Ring TESTS: Lists, tuples, and vectors of length 0 become vectors over a symbolic ring:: sage: symbolic_expression([]).parent() Vector space of dimension 0 over Symbolic Ring sage: symbolic_expression(()).parent() Vector space of dimension 0 over Symbolic Ring sage: symbolic_expression(vector(QQ, 0)).parent() Vector space of dimension 0 over Symbolic Ring If a matrix has dimension 0, the result is still a matrix over a symbolic ring:: sage: symbolic_expression(matrix(QQ, 2, 0)).parent() Full MatrixSpace of 2 by 0 dense matrices over Symbolic Ring sage: symbolic_expression(matrix(QQ, 0, 3)).parent() Full MatrixSpace of 0 by 3 dense matrices over Symbolic Ring Also functions defined using ``def`` can be used, but we do not advertise it as a use case:: sage: def sos(x, y): ....: return x^2 + y^2 sage: symbolic_expression(sos) (x, y) |--> x^2 + y^2 Functions that take a varying number of arguments or keyword-only arguments are not accepted:: sage: def variadic(x, *y): ....: return x sage: symbolic_expression(variadic) Traceback (most recent call last): ... TypeError: unable to convert <function variadic at 0x...> to a symbolic expression sage: def function_with_keyword_only_arg(x, *, sign=1): ....: return sign * x sage: symbolic_expression(function_with_keyword_only_arg) Traceback (most recent call last): ... TypeError: unable to convert <function function_with_keyword_only_arg at 0x...> to a symbolic expression """ from sage.symbolic.expression import Expression from sage.symbolic.ring import SR from sage.modules.free_module_element import is_FreeModuleElement from sage.structure.element import is_Matrix if isinstance(x, Expression): return x elif hasattr(x, '_symbolic_'): return x._symbolic_(SR) elif isinstance(x, (tuple, list)) or is_FreeModuleElement(x): expressions = [symbolic_expression(item) for item in x] if not expressions: # Make sure it is symbolic also when length is 0 return vector(SR, 0) if is_FreeModuleElement(expressions[0]): return matrix(expressions) return vector(expressions) elif is_Matrix(x): if not x.nrows() or not x.ncols(): # Make sure it is symbolic and of correct dimensions # also when a matrix dimension is 0 return matrix(SR, x.nrows(), x.ncols()) rows = [symbolic_expression(row) for row in x.rows()] return matrix(rows) elif callable(x): from inspect import signature, Parameter try: s = signature(x) except ValueError: pass else: if all(param.kind in (Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD) for param in s.parameters.values()): vars = [SR.var(name) for name in s.parameters.keys()] result = x(*vars) if isinstance(result, (tuple, list)): return vector(SR, result).function(*vars) else: return SR(result).function(*vars) return SR(x) from . import desolvers
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/calculus/all.py
0.864697
0.683578
all.py
pypi
r""" Further examples from Wester's paper These are all the problems at http://yacas.sourceforge.net/essaysmanual.html They come from the 1994 paper "Review of CAS mathematical capabilities", by Michael Wester, who put forward 123 problems that a reasonable computer algebra system should be able to solve and tested the then current versions of various commercial CAS on this list. Sage can do most of the problems natively now, i.e., with no explicit calls to Maxima or other systems. :: sage: # (YES) factorial of 50, and factor it sage: factorial(50) 30414093201713378043612608166064768844377641568960512000000000000 sage: factor(factorial(50)) 2^47 * 3^22 * 5^12 * 7^8 * 11^4 * 13^3 * 17^2 * 19^2 * 23^2 * 29 * 31 * 37 * 41 * 43 * 47 :: sage: # (YES) 1/2+...+1/10 = 4861/2520 sage: sum(1/n for n in range(2,10+1)) == 4861/2520 True :: sage: # (YES) Evaluate e^(Pi*Sqrt(163)) to 50 decimal digits sage: a = e^(pi*sqrt(163)); a e^(sqrt(163)*pi) sage: RealField(150)(a) 2.6253741264076874399999999999925007259719820e17 :: sage: # (YES) Evaluate the Bessel function J[2] numerically at z=1+I. sage: bessel_J(2, 1+I).n() 0.0415798869439621 + 0.247397641513306*I :: sage: # (YES) Obtain period of decimal fraction 1/7=0.(142857). sage: a = 1/7 sage: a 1/7 sage: a.period() 6 :: sage: # (YES) Continued fraction of 3.1415926535 sage: a = 3.1415926535 sage: continued_fraction(a) [3; 7, 15, 1, 292, 1, 1, 6, 2, 13, 4] :: sage: # (YES) Sqrt(2*Sqrt(3)+4)=1+Sqrt(3). sage: # The Maxima backend equality checker does this; sage: # note the equality only holds for one choice of sign, sage: # but Maxima always chooses the "positive" one sage: a = sqrt(2*sqrt(3) + 4); b = 1 + sqrt(3) sage: float(a-b) 0.0 sage: bool(a == b) True sage: # We can, of course, do this in a quadratic field sage: k.<sqrt3> = QuadraticField(3) sage: asqr = 2*sqrt3 + 4 sage: b = 1+sqrt3 sage: asqr == b^2 True :: sage: # (YES) Sqrt(14+3*Sqrt(3+2*Sqrt(5-12*Sqrt(3-2*Sqrt(2)))))=3+Sqrt(2). sage: a = sqrt(14+3*sqrt(3+2*sqrt(5-12*sqrt(3-2*sqrt(2))))) sage: b = 3+sqrt(2) sage: a, b (sqrt(3*sqrt(2*sqrt(-12*sqrt(-2*sqrt(2) + 3) + 5) + 3) + 14), sqrt(2) + 3) sage: bool(a==b) True sage: abs(float(a-b)) < 1e-10 True sage: # 2*Infinity-3=Infinity. sage: 2*infinity-3 == infinity True :: sage: # (YES) Standard deviation of the sample (1, 2, 3, 4, 5). sage: v = vector(RDF, 5, [1,2,3,4,5]) sage: v.standard_deviation() 1.5811388300841898 :: sage: # (NO) Hypothesis testing with t-distribution. sage: # (NO) Hypothesis testing with chi^2 distribution sage: # (But both are included in Scipy and R) :: sage: # (YES) (x^2-4)/(x^2+4*x+4)=(x-2)/(x+2). sage: R.<x> = QQ[] sage: (x^2-4)/(x^2+4*x+4) == (x-2)/(x+2) True sage: restore('x') :: sage: # (YES -- Maxima doesn't immediately consider them sage: # equal, but simplification shows that they are) sage: # (Exp(x)-1)/(Exp(x/2)+1)=Exp(x/2)-1. sage: f = (exp(x)-1)/(exp(x/2)+1) sage: g = exp(x/2)-1 sage: f (e^x - 1)/(e^(1/2*x) + 1) sage: g e^(1/2*x) - 1 sage: f.canonicalize_radical() e^(1/2*x) - 1 sage: g e^(1/2*x) - 1 sage: f(x=10.0).n(53), g(x=10.0).n(53) (147.413159102577, 147.413159102577) sage: bool(f == g) True :: sage: # (YES) Expand (1+x)^20, take derivative and factorize. sage: # first do it using algebraic polys sage: R.<x> = QQ[] sage: f = (1+x)^20; f x^20 + 20*x^19 + 190*x^18 + 1140*x^17 + 4845*x^16 + 15504*x^15 + 38760*x^14 + 77520*x^13 + 125970*x^12 + 167960*x^11 + 184756*x^10 + 167960*x^9 + 125970*x^8 + 77520*x^7 + 38760*x^6 + 15504*x^5 + 4845*x^4 + 1140*x^3 + 190*x^2 + 20*x + 1 sage: deriv = f.derivative() sage: deriv 20*x^19 + 380*x^18 + 3420*x^17 + 19380*x^16 + 77520*x^15 + 232560*x^14 + 542640*x^13 + 1007760*x^12 + 1511640*x^11 + 1847560*x^10 + 1847560*x^9 + 1511640*x^8 + 1007760*x^7 + 542640*x^6 + 232560*x^5 + 77520*x^4 + 19380*x^3 + 3420*x^2 + 380*x + 20 sage: deriv.factor() (20) * (x + 1)^19 sage: restore('x') sage: # next do it symbolically sage: var('y') y sage: f = (1+y)^20; f (y + 1)^20 sage: g = f.expand(); g y^20 + 20*y^19 + 190*y^18 + 1140*y^17 + 4845*y^16 + 15504*y^15 + 38760*y^14 + 77520*y^13 + 125970*y^12 + 167960*y^11 + 184756*y^10 + 167960*y^9 + 125970*y^8 + 77520*y^7 + 38760*y^6 + 15504*y^5 + 4845*y^4 + 1140*y^3 + 190*y^2 + 20*y + 1 sage: deriv = g.derivative(); deriv 20*y^19 + 380*y^18 + 3420*y^17 + 19380*y^16 + 77520*y^15 + 232560*y^14 + 542640*y^13 + 1007760*y^12 + 1511640*y^11 + 1847560*y^10 + 1847560*y^9 + 1511640*y^8 + 1007760*y^7 + 542640*y^6 + 232560*y^5 + 77520*y^4 + 19380*y^3 + 3420*y^2 + 380*y + 20 sage: deriv.factor() 20*(y + 1)^19 :: sage: # (YES) Factorize x^100-1. sage: factor(x^100-1) (x^40 - x^30 + x^20 - x^10 + 1)*(x^20 + x^15 + x^10 + x^5 + 1)*(x^20 - x^15 + x^10 - x^5 + 1)*(x^8 - x^6 + x^4 - x^2 + 1)*(x^4 + x^3 + x^2 + x + 1)*(x^4 - x^3 + x^2 - x + 1)*(x^2 + 1)*(x + 1)*(x - 1) sage: # Also, algebraically sage: x = polygen(QQ) sage: factor(x^100 - 1) (x - 1) * (x + 1) * (x^2 + 1) * (x^4 - x^3 + x^2 - x + 1) * (x^4 + x^3 + x^2 + x + 1) * (x^8 - x^6 + x^4 - x^2 + 1) * (x^20 - x^15 + x^10 - x^5 + 1) * (x^20 + x^15 + x^10 + x^5 + 1) * (x^40 - x^30 + x^20 - x^10 + 1) sage: restore('x') :: sage: # (YES) Factorize x^4-3*x^2+1 in the field of rational numbers extended by roots of x^2-x-1. sage: k.< a> = NumberField(x^2 - x -1) sage: R.< y> = k[] sage: f = y^4 - 3*y^2 + 1 sage: f y^4 - 3*y^2 + 1 sage: factor(f) (y - a) * (y - a + 1) * (y + a - 1) * (y + a) :: sage: # (YES) Factorize x^4-3*x^2+1 mod 5. sage: k.< x > = GF(5) [ ] sage: f = x^4 - 3*x^2 + 1 sage: f.factor() (x + 2)^2 * (x + 3)^2 sage: # Alternatively, from symbol x as follows: sage: reset('x') sage: f = x^4 - 3*x^2 + 1 sage: f.polynomial(GF(5)).factor() (x + 2)^2 * (x + 3)^2 :: sage: # (YES) Partial fraction decomposition of (x^2+2*x+3)/(x^3+4*x^2+5*x+2) sage: f = (x^2+2*x+3)/(x^3+4*x^2+5*x+2); f (x^2 + 2*x + 3)/(x^3 + 4*x^2 + 5*x + 2) sage: f.partial_fraction() 3/(x + 2) - 2/(x + 1) + 2/(x + 1)^2 :: sage: # (YES) Assuming x>=y, y>=z, z>=x, deduce x=z. sage: forget() sage: var('x,y,z') (x, y, z) sage: assume(x>=y, y>=z,z>=x) sage: bool(x==z) True :: sage: # (YES) Assuming x>y, y>0, deduce 2*x^2>2*y^2. sage: forget() sage: assume(x>y, y>0) sage: sorted(assumptions()) [x > y, y > 0] sage: bool(2*x^2 > 2*y^2) True sage: forget() sage: assumptions() [] :: sage: # (NO) Solve the inequality Abs(x-1)>2. sage: # Maxima doesn't solve inequalities sage: # (but some Maxima packages do): sage: eqn = abs(x-1) > 2 sage: eqn abs(x - 1) > 2 :: sage: # (NO) Solve the inequality (x-1)*...*(x-5)<0. sage: eqn = prod(x-i for i in range(1,5 +1)) < 0 sage: # but don't know how to solve sage: eqn (x - 1)*(x - 2)*(x - 3)*(x - 4)*(x - 5) < 0 :: sage: # (YES) Cos(3*x)/Cos(x)=Cos(x)^2-3*Sin(x)^2 or similar equivalent combination. sage: f = cos(3*x)/cos(x) sage: g = cos(x)^2 - 3*sin(x)^2 sage: h = f-g sage: h.trig_simplify() 0 :: sage: # (YES) Cos(3*x)/Cos(x)=2*Cos(2*x)-1. sage: f = cos(3*x)/cos(x) sage: g = 2*cos(2*x) - 1 sage: h = f-g sage: h.trig_simplify() 0 :: sage: # (GOOD ENOUGH) Define rewrite rules to match Cos(3*x)/Cos(x)=Cos(x)^2-3*Sin(x)^2. sage: # Sage has no notion of "rewrite rules", but sage: # it can simplify both to the same thing. sage: (cos(3*x)/cos(x)).simplify_full() 4*cos(x)^2 - 3 sage: (cos(x)^2-3*sin(x)^2).simplify_full() 4*cos(x)^2 - 3 :: sage: # (YES) Sqrt(997)-(997^3)^(1/6)=0 sage: a = sqrt(997) - (997^3)^(1/6) sage: a.simplify() 0 sage: bool(a == 0) True :: sage: # (YES) Sqrt(99983)-99983^3^(1/6)=0 sage: a = sqrt(99983) - (99983^3)^(1/6) sage: bool(a==0) True sage: float(a) 1.1368683772...e-13 sage: 13*7691 99983 :: sage: # (YES) (2^(1/3) + 4^(1/3))^3 - 6*(2^(1/3) + 4^(1/3))-6 = 0 sage: a = (2^(1/3) + 4^(1/3))^3 - 6*(2^(1/3) + 4^(1/3)) - 6; a (4^(1/3) + 2^(1/3))^3 - 6*4^(1/3) - 6*2^(1/3) - 6 sage: bool(a==0) True sage: abs(float(a)) < 1e-10 True Or we can do it using number fields. :: sage: reset('x') sage: k.<b> = NumberField(x^3-2) sage: a = (b + b^2)^3 - 6*(b + b^2) - 6 sage: a 0 :: sage: # (NO, except numerically) Ln(Tan(x/2+Pi/4))-ArcSinh(Tan(x))=0 # Sage uses the Maxima convention when comparing symbolic expressions and # returns True only when it can prove equality. Thus, in this case, we get # False even though the equality holds. sage: f = log(tan(x/2 + pi/4)) - arcsinh(tan(x)) sage: bool(f == 0) False sage: [abs(float(f(x=i/10))) < 1e-15 for i in range(1,5)] [True, True, True, True] sage: # Numerically, the expression Ln(Tan(x/2+Pi/4))-ArcSinh(Tan(x))=0 and its derivative at x=0 are zero. sage: g = f.derivative() sage: abs(float(f(x=0))) < 1e-10 True sage: abs(float(g(x=0))) < 1e-10 True sage: g -sqrt(tan(x)^2 + 1) + 1/2*(tan(1/4*pi + 1/2*x)^2 + 1)/tan(1/4*pi + 1/2*x) :: sage: # (NO) Ln((2*Sqrt(r) + 1)/Sqrt(4*r 4*Sqrt(r) 1))=0. sage: var('r') r sage: f = log( (2*sqrt(r) + 1) / sqrt(4*r + 4*sqrt(r) + 1)); f log((2*sqrt(r) + 1)/sqrt(4*r + 4*sqrt(r) + 1)) sage: bool(f == 0) False sage: [abs(float(f(r=i))) < 1e-10 for i in [0.1,0.3,0.5]] [True, True, True] :: sage: # (NO) sage: # (4*r+4*Sqrt(r)+1)^(Sqrt(r)/(2*Sqrt(r)+1))*(2*Sqrt(r)+1)^(2*Sqrt(r)+1)^(-1)-2*Sqrt(r)-1=0, assuming r>0. sage: assume(r>0) sage: f = (4*r+4*sqrt(r)+1)^(sqrt(r)/(2*sqrt(r)+1))*(2*sqrt(r)+1)^(2*sqrt(r)+1)^(-1)-2*sqrt(r)-1 sage: f (4*r + 4*sqrt(r) + 1)^(sqrt(r)/(2*sqrt(r) + 1))*(2*sqrt(r) + 1)^(1/(2*sqrt(r) + 1)) - 2*sqrt(r) - 1 sage: bool(f == 0) False sage: [abs(float(f(r=i))) < 1e-10 for i in [0.1,0.3,0.5]] [True, True, True] :: sage: # (YES) Obtain real and imaginary parts of Ln(3+4*I). sage: a = log(3+4*I); a log(4*I + 3) sage: a.real() log(5) sage: a.imag() arctan(4/3) :: sage: # (YES) Obtain real and imaginary parts of Tan(x+I*y) sage: z = var('z') sage: a = tan(z); a tan(z) sage: a.real() sin(2*real_part(z))/(cos(2*real_part(z)) + cosh(2*imag_part(z))) sage: a.imag() sinh(2*imag_part(z))/(cos(2*real_part(z)) + cosh(2*imag_part(z))) :: sage: # (YES) Simplify Ln(Exp(z)) to z for -Pi<Im(z)<=Pi. sage: # Unfortunately (?), Maxima does this even without sage: # any assumptions. sage: # We *would* use assume(-pi < imag(z)) sage: # and assume(imag(z) <= pi) sage: f = log(exp(z)); f log(e^z) sage: f.simplify() z sage: forget() :: sage: # (YES) Assuming Re(x)>0, Re(y)>0, deduce x^(1/n)*y^(1/n)-(x*y)^(1/n)=0. sage: # Maxima 5.26 has different behaviours depending on the current sage: # domain. sage: # To stick with the behaviour of previous versions, the domain is set sage: # to 'real' in the following. sage: # See Trac #10682 for further details. sage: n = var('n') sage: f = x^(1/n)*y^(1/n)-(x*y)^(1/n) sage: assume(real(x) > 0, real(y) > 0) sage: f.simplify() x^(1/n)*y^(1/n) - (x*y)^(1/n) sage: maxima = sage.calculus.calculus.maxima sage: maxima.set('domain', 'real') # set domain to real sage: f.simplify() 0 sage: maxima.set('domain', 'complex') # set domain back to its default value sage: forget() :: sage: # (YES) Transform equations, (x==2)/2+(1==1)=>x/2+1==2. sage: eq1 = x == 2 sage: eq2 = SR(1) == SR(1) sage: eq1/2 + eq2 1/2*x + 1 == 2 :: sage: # (SOMEWHAT) Solve Exp(x)=1 and get all solutions. sage: # to_poly_solve in Maxima can do this. sage: solve(exp(x) == 1, x) [x == 0] :: sage: # (SOMEWHAT) Solve Tan(x)=1 and get all solutions. sage: # to_poly_solve in Maxima can do this. sage: solve(tan(x) == 1, x) [x == 1/4*pi] :: sage: # (YES) Solve a degenerate 3x3 linear system. sage: # x+y+z==6,2*x+y+2*z==10,x+3*y+z==10 sage: # First symbolically: sage: solve([x+y+z==6, 2*x+y+2*z==10, x+3*y+z==10], x,y,z) [[x == -r1 + 4, y == 2, z == r1]] :: sage: # (YES) Invert a 2x2 symbolic matrix. sage: # [[a,b],[1,a*b]] sage: # Using multivariate poly ring -- much nicer sage: R.<a,b> = QQ[] sage: m = matrix(2,2,[a,b, 1, a*b]) sage: zz = m^(-1) sage: zz [ a/(a^2 - 1) (-1)/(a^2 - 1)] [(-1)/(a^2*b - b) a/(a^2*b - b)] :: sage: # (YES) Compute and factor the determinant of the 4x4 Vandermonde matrix in a, b, c, d. sage: var('a,b,c,d') (a, b, c, d) sage: m = matrix(SR, 4, 4, [[z^i for i in range(4)] for z in [a,b,c,d]]) sage: m [ 1 a a^2 a^3] [ 1 b b^2 b^3] [ 1 c c^2 c^3] [ 1 d d^2 d^3] sage: d = m.determinant() sage: d.factor() (a - b)*(a - c)*(a - d)*(b - c)*(b - d)*(c - d) :: sage: # (YES) Compute and factor the determinant of the 4x4 Vandermonde matrix in a, b, c, d. sage: # Do it instead in a multivariate ring sage: R.<a,b,c,d> = QQ[] sage: m = matrix(R, 4, 4, [[z^i for i in range(4)] for z in [a,b,c,d]]) sage: m [ 1 a a^2 a^3] [ 1 b b^2 b^3] [ 1 c c^2 c^3] [ 1 d d^2 d^3] sage: d = m.determinant() sage: d a^3*b^2*c - a^2*b^3*c - a^3*b*c^2 + a*b^3*c^2 + a^2*b*c^3 - a*b^2*c^3 - a^3*b^2*d + a^2*b^3*d + a^3*c^2*d - b^3*c^2*d - a^2*c^3*d + b^2*c^3*d + a^3*b*d^2 - a*b^3*d^2 - a^3*c*d^2 + b^3*c*d^2 + a*c^3*d^2 - b*c^3*d^2 - a^2*b*d^3 + a*b^2*d^3 + a^2*c*d^3 - b^2*c*d^3 - a*c^2*d^3 + b*c^2*d^3 sage: d.factor() (-1) * (c - d) * (-b + c) * (b - d) * (-a + c) * (-a + b) * (a - d) :: sage: # (YES) Find the eigenvalues of a 3x3 integer matrix. sage: m = matrix(QQ, 3, [5,-3,-7, -2,1,2, 2,-3,-4]) sage: m.eigenspaces_left() [ (3, Vector space of degree 3 and dimension 1 over Rational Field User basis matrix: [ 1 0 -1]), (1, Vector space of degree 3 and dimension 1 over Rational Field User basis matrix: [ 1 1 -1]), (-2, Vector space of degree 3 and dimension 1 over Rational Field User basis matrix: [0 1 1]) ] :: sage: # (YES) Verify some standard limits found by L'Hopital's rule: sage: # Verify(Limit(x,Infinity) (1+1/x)^x, Exp(1)); sage: # Verify(Limit(x,0) (1-Cos(x))/x^2, 1/2); sage: limit( (1+1/x)^x, x = oo) e sage: limit( (1-cos(x))/(x^2), x = 1/2) -4*cos(1/2) + 4 :: sage: # (OK-ish) D(x)Abs(x) sage: # Verify(D(x) Abs(x), Sign(x)); sage: diff(abs(x)) 1/2*(x + conjugate(x))/abs(x) sage: _.simplify_full() x/abs(x) sage: _ = var('x', domain='real') sage: diff(abs(x)) x/abs(x) sage: forget() :: sage: # (YES) (Integrate(x)Abs(x))=Abs(x)*x/2 sage: integral(abs(x), x) 1/2*x*abs(x) :: sage: # (YES) Compute derivative of Abs(x), piecewise defined. sage: # Verify(D(x)if(x<0) (-x) else x, sage: # Simplify(if(x<0) -1 else 1)) Piecewise defined function with 2 parts, [[(-10, 0), -1], [(0, 10), 1]] sage: # (NOT really) Integrate Abs(x), piecewise defined. sage: # Verify(Simplify(Integrate(x) sage: # if(x<0) (-x) else x), sage: # Simplify(if(x<0) (-x^2/2) else x^2/2)); sage: f = piecewise([ ((-10,0), -x), ((0,10), x)]) sage: f.integral(definite=True) 100 :: sage: # (YES) Taylor series of 1/Sqrt(1-v^2/c^2) at v=0. sage: var('v,c') (v, c) sage: taylor(1/sqrt(1-v^2/c^2), v, 0, 7) 1/2*v^2/c^2 + 3/8*v^4/c^4 + 5/16*v^6/c^6 + 1 :: sage: # (OK-ish) (Taylor expansion of Sin(x))/(Taylor expansion of Cos(x)) = (Taylor expansion of Tan(x)). sage: # TestYacas(Taylor(x,0,5)(Taylor(x,0,5)Sin(x))/ sage: # (Taylor(x,0,5)Cos(x)), Taylor(x,0,5)Tan(x)); sage: f = taylor(sin(x), x, 0, 8) sage: g = taylor(cos(x), x, 0, 8) sage: h = taylor(tan(x), x, 0, 8) sage: f = f.power_series(QQ) sage: g = g.power_series(QQ) sage: h = h.power_series(QQ) sage: f - g*h O(x^8) :: sage: # (YES) Taylor expansion of Ln(x)^a*Exp(-b*x) at x=1. sage: a,b = var('a,b') sage: taylor(log(x)^a*exp(-b*x), x, 1, 3) -1/48*(a^3*(x - 1)^a + a^2*(6*b + 5)*(x - 1)^a + 8*b^3*(x - 1)^a + 2*(6*b^2 + 5*b + 3)*a*(x - 1)^a)*(x - 1)^3*e^(-b) + 1/24*(3*a^2*(x - 1)^a + a*(12*b + 5)*(x - 1)^a + 12*b^2*(x - 1)^a)*(x - 1)^2*e^(-b) - 1/2*(a*(x - 1)^a + 2*b*(x - 1)^a)*(x - 1)*e^(-b) + (x - 1)^a*e^(-b) :: sage: # (YES) Taylor expansion of Ln(Sin(x)/x) at x=0. sage: taylor(log(sin(x)/x), x, 0, 10) -1/467775*x^10 - 1/37800*x^8 - 1/2835*x^6 - 1/180*x^4 - 1/6*x^2 :: sage: # (NO) Compute n-th term of the Taylor series of Ln(Sin(x)/x) at x=0. sage: # need formal functions :: sage: # (NO) Compute n-th term of the Taylor series of Exp(-x)*Sin(x) at x=0. sage: # (Sort of, with some work) sage: # Solve x=Sin(y)+Cos(y) for y as Taylor series in x at x=1. sage: # TestYacas(InverseTaylor(y,0,4) Sin(y)+Cos(y), sage: # (y-1)+(y-1)^2/2+2*(y-1)^3/3+(y-1)^4); sage: # Note that InverseTaylor does not give the series in terms of x but in terms of y which is semantically sage: # wrong. But other CAS do the same. sage: f = sin(y) + cos(y) sage: g = f.taylor(y, 0, 10) sage: h = g.power_series(QQ) sage: k = (h - 1).reverse() sage: k y + 1/2*y^2 + 2/3*y^3 + y^4 + 17/10*y^5 + 37/12*y^6 + 41/7*y^7 + 23/2*y^8 + 1667/72*y^9 + 3803/80*y^10 + O(y^11) :: sage: # (OK) Compute Legendre polynomials directly from Rodrigues's formula, P[n]=1/(2^n*n!) *(Deriv(x,n)(x^2-1)^n). sage: # P(n,x) := Simplify( 1/(2*n)!! * sage: # Deriv(x,n) (x^2-1)^n ); sage: # TestYacas(P(4,x), (35*x^4)/8+(-15*x^2)/4+3/8); sage: P = lambda n, x: simplify(diff((x^2-1)^n,x,n) / (2^n * factorial(n))) sage: P(4,x).expand() 35/8*x^4 - 15/4*x^2 + 3/8 :: sage: # (YES) Define the polynomial p=Sum(i,1,5,a[i]*x^i). sage: # symbolically sage: ps = sum(var('a%s'%i)*x^i for i in range(1,6)); ps a5*x^5 + a4*x^4 + a3*x^3 + a2*x^2 + a1*x sage: ps.parent() Symbolic Ring sage: # algebraically sage: R = PolynomialRing(QQ,5,names='a') sage: S.<x> = PolynomialRing(R) sage: p = S(list(R.gens()))*x; p a4*x^5 + a3*x^4 + a2*x^3 + a1*x^2 + a0*x sage: p.parent() Univariate Polynomial Ring in x over Multivariate Polynomial Ring in a0, a1, a2, a3, a4 over Rational Field :: sage: # (YES) Convert the above to Horner's form. sage: # Verify(Horner(p, x), ((((a[5]*x+a[4])*x sage: # +a[3])*x+a[2])*x+a[1])*x); sage: restore('x') sage: SR(p).horner(x) ((((a4*x + a3)*x + a2)*x + a1)*x + a0)*x :: sage: # (NO) Convert the result of problem 127 to Fortran syntax. sage: # CForm(Horner(p, x)); :: sage: # (YES) Verify that True And False=False. sage: (True and False) is False True :: sage: # (YES) Prove x Or Not x. sage: for x in [True, False]: ....: print(x or (not x)) True True :: sage: # (YES) Prove x Or y Or x And y=>x Or y. sage: for x in [True, False]: ....: for y in [True, False]: ....: if x or y or x and y: ....: if not (x or y): ....: print("failed!") """
/sagemath-standard-10.0b0.tar.gz/sagemath-standard-10.0b0/sage/calculus/wester.py
0.765637
0.656562
wester.py
pypi
import dataclasses from dataclasses import dataclass from typing import Any, List, Optional @dataclass class Device: """Device connected to a router.""" uid: Optional[int] = None alias: Optional[str] = None phys_address: Optional[str] = None ip_address: Optional[str] = None address_source: Optional[str] = None dhcp_client: Optional[str] = None lease_time_remaining: Optional[int] = None associated_device: Optional[Any] = None layer1_interface: Optional[Any] = None layer3_interface: Optional[Any] = None vendor_class_id: Optional[Any] = None client_id: Optional[Any] = None user_class_id: Optional[Any] = None host_name: Optional[Any] = None active: Optional[bool] = None lease_start: Optional[int] = None lease_duration: Optional[int] = None interface_type: Optional[str] = None # enum! detected_device_type: Optional[str] = None active_last_change: Optional[Any] = None user_friendly_name: Optional[str] = None user_host_name: Optional[str] = None user_device_type: Optional[Any] = None # enum! icon: Optional[Any] = None room: Optional[Any] = None blacklist_enable: Optional[bool] = None blacklisted: Optional[bool] = None unblock_hours_count: Optional[int] = None blacklist_status: Optional[bool] = None blacklisted_according_to_schedule: Optional[bool] = None blacklisted_schedule: Optional[List] = None hidden: Optional[bool] = None options: Optional[List] = None vendor_class_idv6: Optional[Any] = None ipv4_addresses: Optional[List] = None ipv6_addresses: Optional[List] = None device_type_association: Optional[Any] = None # TODO Remove extra kwargs before init def __init__(self, **kwargs): """Override to accept more args than specified.""" names = {f.name for f in dataclasses.fields(self)} for k, v in kwargs.items(): if k in names: setattr(self, k, v) @property def id(self): """Return unique ID for device.""" return self.phys_address.upper() @property def name(self): """Return name of the device.""" return self.user_host_name or self.host_name @dataclass class DeviceInfo: """Sagemcom Router representation.""" mac_address: str serial_number: Optional[str] = None manufacturer: Optional[Any] = None model_name: Optional[Any] = None model_number: Optional[Any] = None software_version: Optional[str] = None hardware_version: Optional[str] = None up_time: Optional[Any] = None reboot_count: Optional[Any] = None router_name: Optional[Any] = None bootloader_version: Optional[Any] = None device_category: Optional[Any] = None manufacturer_oui: Optional[Any] = None product_class: Optional[str] = None description: Optional[str] = None additional_hardware_version: Optional[str] = None additional_software_version: Optional[str] = None external_firmware_version: Optional[str] = None internal_firmware_version: Optional[str] = None gui_firmware_version: Optional[str] = None guiapi_version: Optional[float] = None provisioning_code: Optional[str] = None up_time: Optional[int] = None first_use_date: Optional[str] = None mac_address: Optional[str] = None mode: Optional[str] = None country: Optional[str] = None reboot_count: Optional[int] = None nodes_to_restore: Optional[str] = None router_name: Optional[str] = None reboot_status: Optional[float] = None reset_status: Optional[float] = None update_status: Optional[float] = None SNMP: Optional[bool] = None first_connection: Optional[bool] = None build_date: Optional[str] = None spec_version: Optional[str] = None CLID: Optional[str] = None flush_device_log: Optional[bool] = None locations: Optional[str] = None api_version: Optional[str] = None # TODO Remove extra kwargs before init def __init__(self, **kwargs): """Override to accept more args than specified.""" names = {f.name for f in dataclasses.fields(self)} for k, v in kwargs.items(): if k in names: setattr(self, k, v) @property def id(self): """Return unique ID for gateway.""" return self.mac_address @dataclass class PortMapping: """Port Mapping representation.""" uid: int enable: bool status: Optional[str] = None # Enum alias: Optional[str] = None external_interface: Optional[str] = None all_external_interfaces: Optional[bool] = None lease_duration: Optional[int] = None external_port: Optional[int] = None external_port_end_range: Optional[int] = None internal_interface: Optional[str] = None internal_port: Optional[int] = None protocol: Optional[str] = None service: Optional[str] = None internal_client: Optional[str] = None public_ip: Optional[str] = None description: Optional[str] = None creator: Optional[str] = None target: Optional[str] = None lease_start: Optional[str] = None # Date? # TODO Remove extra kwargs before init def __init__(self, **kwargs): """Override to accept more args than specified.""" names = {f.name for f in dataclasses.fields(self)} for k, v in kwargs.items(): if k in names: setattr(self, k, v) @property def id(self): """Return unique ID for port mapping.""" return self.uid
/sagemcom_api-1.0.8-py3-none-any.whl/sagemcom_api/models.py
0.851027
0.275842
models.py
pypi
import json import boto3 import jmespath from pymongo import MongoClient from pymysql.connections import Connection class Environment(): def __init__(self, stack, region='us-west-2'): self.stack = stack self.session = boto3.session.Session(region_name=region) def notebooks_running(self): """List notebook servers currently running in a stack Returns: list(ec2 id): Stack notebook servers that are running """ filters = [ { "Name": "tag:sagesaver:stack-origin", "Values": [self.stack] }, { "Name": "tag:sagesaver:server-type", "Values": ["Notebook"] }, { "Name": "instance-state-name", "Values": ["running", "pending"] } ] client = self.session.client('ec2') response = client.describe_instances(Filters = filters) notebook_instances = jmespath.search("Reservations[].Instances[].InstanceId", response) return notebook_instances def db_secret(self): '''Retrieves SageSaver database credentials from Secrets Manager Returns: json: Database credentials ''' client = self.session.client('secretsmanager') secret_name = f'{self.stack}-Database-Secret' get_secret_value_response = client.get_secret_value(SecretId=secret_name) secret = get_secret_value_response['SecretString'] return json.loads(secret) def mongo_client(self): '''Generates a client to a SageSaver MongoDB database Returns: pymongo client: Client connected to the mongo database ''' secret = self.db_secret() return MongoClient( username=secret['username'], password=secret['password'], port=secret['port'], host=secret['host'] ) def mysql_client(self): '''Generates a client to a SageSaver MySQL database Returns: pymysql client: Client connected to the mysql database ''' secret = self.db_secret() return Connection( user=secret['username'], password=secret['password'], port=secret['port'], host=secret['host'] )
/sagesaver_tools-0.1.2-py3-none-any.whl/sstools/environment.py
0.596433
0.215454
environment.py
pypi
import sys import os import textwrap from pyparsing import * def skipToMatching(opener, closer): nest = nestedExpr(opener, closer) return originalTextFor(nest) curlybrackets = skipToMatching('{', '}') squarebrackets = skipToMatching('[', ']') sagemacroparser = r'\sage' + curlybrackets('code') sagestrmacroparser = r'\sagestr' + curlybrackets('code') sageplotparser = (r'\sageplot' + Optional(squarebrackets)('opts') + Optional(squarebrackets)('format') + curlybrackets('code')) sagetexpause = Literal(r'\sagetexpause') sagetexunpause = Literal(r'\sagetexunpause') class SoutParser(): def __init__(self, fn): self.label = [] parselabel = (r'\newlabel{@sageinline' + Word(nums)('num') + '}{' + curlybrackets('result') + '{}{}{}{}}') parselabel.ignore('%' + restOfLine) parselabel.setParseAction(self.newlabel) try: OneOrMore(parselabel).parseFile(fn) except IOError: print('Error accessing {}; exiting. Does your .sout file exist?'.format(fn)) sys.exit(1) def newlabel(self, s, l, t): self.label.append(t.result[1:-1]) class DeSageTex(): def __init__(self, texfn, soutfn): self.sagen = 0 self.plotn = 0 self.fn = os.path.basename(texfn) self.sout = SoutParser(soutfn) strmacro = sagestrmacroparser smacro = sagemacroparser smacro.setParseAction(self.sage) strmacro.setParseAction(self.sage) usepackage = (r'\usepackage' + Optional(squarebrackets) + '{sagetex}') usepackage.setParseAction(replaceWith(r"""% "\usepackage{sagetex}" line was here: \RequirePackage{verbatim} \RequirePackage{graphicx} \newcommand{\sagetexpause}{\relax} \newcommand{\sagetexunpause}{\relax}""")) splot = sageplotparser splot.setParseAction(self.plot) beginorend = oneOf('begin end') blockorverb = 'sage' + oneOf('block verbatim') blockorverb.setParseAction(replaceWith('verbatim')) senv = '\\' + beginorend + '{' + blockorverb + '}' silent = Literal('sagesilent') silent.setParseAction(replaceWith('comment')) ssilent = '\\' + beginorend + '{' + silent + '}' stexindent = Suppress(r'\setlength{\sagetexindent}' + curlybrackets) doit = smacro | senv | ssilent | usepackage | splot | stexindent |strmacro doit.ignore('%' + restOfLine) doit.ignore(r'\begin{verbatim}' + SkipTo(r'\end{verbatim}')) doit.ignore(r'\begin{comment}' + SkipTo(r'\end{comment}')) doit.ignore(r'\sagetexpause' + SkipTo(r'\sagetexunpause')) str = ''.join(open(texfn, 'r').readlines()) self.result = doit.transformString(str) def sage(self, s, l, t): self.sagen += 1 return self.sout.label[self.sagen - 1] def plot(self, s, l, t): self.plotn += 1 if len(t.opts) == 0: opts = r'[width=.75\textwidth]' else: opts = t.opts[0] return (r'\includegraphics%s{sage-plots-for-%s.tex/plot-%s}' % (opts, self.fn, self.plotn - 1)) class SageCodeExtractor(): def __init__(self, texfn, inline=True): smacro = sagemacroparser smacro.setParseAction(self.macroout) splot = sageplotparser splot.setParseAction(self.plotout) env_names = oneOf('sageblock sageverbatim sagesilent') senv = r'\begin{' + env_names('env') + '}' + SkipTo( r'\end{' + matchPreviousExpr(env_names) + '}')('code') senv.leaveWhitespace() senv.setParseAction(self.envout) spause = sagetexpause spause.setParseAction(self.pause) sunpause = sagetexunpause sunpause.setParseAction(self.unpause) if inline: doit = smacro | splot | senv | spause | sunpause else: doit = senv | spause | sunpause doit.ignore('%' + restOfLine) str = ''.join(open(texfn, 'r').readlines()) self.result = '' doit.transformString(str) def macroout(self, s, l, t): self.result += '#> \\sage{} from line %s\n' % lineno(l, s) self.result += textwrap.dedent(t.code[1:-1]) + '\n\n' def plotout(self, s, l, t): self.result += '#> \\sageplot{} from line %s:\n' % lineno(l, s) if t.format != '': self.result += '#> format: %s' % t.format[0][1:-1] + '\n' self.result += textwrap.dedent(t.code[1:-1]) + '\n\n' def envout(self, s, l, t): self.result += '#> %s environment from line %s:' % (t.env, lineno(l, s)) self.result += textwrap.dedent(''.join(t.code)) + '\n' def pause(self, s, l, t): self.result += ('#> SageTeX (probably) paused on input line %s.\n\n' % (lineno(l, s))) def unpause(self, s, l, t): self.result += ('#> SageTeX (probably) unpaused on input line %s.\n\n' % (lineno(l, s)))
/sagetex-3.6.1.tar.gz/sagetex-3.6.1/sagetexparse.py
0.402862
0.186262
sagetexparse.py
pypi
<img align="left" src="docs/images/scp.png" width="180"> # SageWorks<sup><i>TM</i></sup> <p align="center"> <img height="360" align="left" src="https://user-images.githubusercontent.com/4806709/236641571-fc38899a-8b92-4b7c-80a0-cc9d39b92e4a.png"> <img height="360" aligh="right" src="https://user-images.githubusercontent.com/4806709/236641581-51777977-bca4-4af3-8bec-fb1758c964b8.png"> </p> #### SageWorks: The scientist's workbench powered by AWS® for scalability, flexibility, and security. SageWorks is a medium granularity framework that manages and aggregates AWS® Services into classes and concepts. When you use SageWorks you think about **DataSources**, **FeatureSets**, **Models**, and **Endpoints**. Underneath the hood those classes handle all the details around updating and managing a **complex set of AWS Services**. All the power and none of the pain so that your team can **Do Science Faster!** <p align="center"> <img width="800" src="docs/images/sageworks_concepts.png"> </p> ### Full SageWorks OverView [SageWorks Architected FrameWork](https://docs.google.com/presentation/d/1ZiSy4ulEx5gfNQS76yRv8vgkehJ9gXRJ1PulutLKzis/edit?usp=sharing) ## Why SageWorks? <img align="right" src="docs/images/graph_representation.png" width="300"> - The AWS SageMaker® ecosystem is **awesome** but has a large number of services with significant complexity - SageWorks provides **rapid prototyping** through easy to use **classes** and **transforms** - SageWorks provides **visibility** and **transparency** into AWS SageMaker® Pipelines - What S3 data sources are getting pulled? - What Features Store/Group is the Model Using? - What's the ***Provenance*** of a Model in Model Registry? - What SageMaker Endpoints are associated with this model? ### Single Pane of Glass Visibility into the AWS Services that underpin the SageWorks Classes. We can see that SageWorks automatically tags and tracks the inputs of all artifacts providing 'data provenance' for all steps in the AWS modeling pipeline. <p align="center"> <img width="800" alt="Top Dashboard" src="https://github.com/SuperCowPowers/sageworks/assets/4806709/c4a7f054-e640-407c-9e5c-f9d3ea1bd717.png"> </p> <i><b> Clearly illustrated:</b> SageWorks provides intuitive and transparent visibility into the full pipeline of your AWS Sagemaker Deployments.</i> ## Getting Started - [SageWorks Overview](https://docs.google.com/presentation/d/1ZiSy4ulEx5gfNQS76yRv8vgkehJ9gXRJ1PulutLKzis/edit?usp=sharing) Slides that cover and illustrate the SageWorks Modeling Pipeline. - [SageWorks Docs/Wiki](https://github.com/SuperCowPowers/sageworks/wiki) Our general documentation for getting started with SageWorks. - [SageWorks AWS Onboarding](https://github.com/SuperCowPowers/sageworks/wiki/Onboarding-SageWorks-to-AWS) Deploy the SageWorks Stack to your AWS Account. - [Notebook: Start to Finish AWS ML Pipeline](https://nbviewer.org/github/SuperCowPowers/sageworks/blob/main/notebooks/ML_Pipeline_with_SageWorks.ipynb) Building an AWS® ML Pipeline from start to finish. - [Video: Coding with SageWorks](https://drive.google.com/file/d/1iO7IuQtTYdx4BtQjxv9lI1aVJ2ZcAo43/view?usp=sharing) Informal coding + chatting while building a full ML pipeline. - Join our [Discord](https://discord.gg/WHAJuz8sw8) for questions and advice on using SageWorks within your organization. ### SageWorks Zen - The AWS SageMaker® set of services is vast and **complex**. - SageWorks Classes encapsulate, organize, and manage sets of AWS® Services. - **Heavy** transforms typically use **[AWS Athena](https://aws.amazon.com/athena/)** or **[Apache Spark](https://spark.apache.org/)** (AWS Glue/EMR Serverless). - **Light** transforms will typically use **[Pandas](https://pandas.pydata.org/)**. - Heavy and Light transforms both update **AWS Artifacts** (collections of AWS Services). - **Quick prototypes** are typically built with the **light path** and then flipped to the **heavy path** as the system matures and usage grows. ### Classes and Concepts The SageWorks Classes are organized to work in concert with AWS Services. For more details on the current classes and class hierarchies see [SageWorks Classes and Concepts](docs/sageworks_classes_concepts.md). ### Contributions If you'd like to contribute to the SageWorks project, you're more than welcome. All contributions will fall under the existing project [license](https://github.com/SuperCowPowers/sageworks/blob/main/LICENSE). If you are interested in contributing or have questions please feel free to contact us at [sageworks@supercowpowers.com](mailto:sageworks@supercowpowers.com). ### SageWorks Alpha Testers Wanted Our experienced team can provide development and consulting services to help you effectively use Amazon’s Machine Learning services within your organization. The popularity of cloud based Machine Learning services is booming. The problem many companies face is how that capability gets effectively used and harnessed to drive real business decisions and provide concrete value for their organization. Using SageWorks will minimize the time and manpower needed to incorporate AWS ML into your organization. If your company would like to be a SageWorks Alpha Tester, contact us at [sageworks@supercowpowers.com](mailto:sageworks@supercowpowers.com). ® Amazon Web Services, AWS, the Powered by AWS logo, are trademarks of Amazon.com, Inc. or its affiliates.
/sageworks-0.1.5.3.tar.gz/sageworks-0.1.5.3/Readme.md
0.843638
0.848847
Readme.md
pypi
from dash import Dash import dash_bootstrap_components as dbc # SageWorks Imports from sageworks.views.artifacts_web_view import ArtifactsWebView from sageworks.web_components import table # Local Imports import layout # Note: The 'app' and 'server' objects need to be at the top level since NGINX/uWSGI needs to # import this file and use the server object as an ^entry-point^ into the Dash Application Code # Create our Dash Application app = Dash(title="SageWorks Artifacts", external_stylesheets=[dbc.themes.BOOTSTRAP]) # app = Dash(title='Hello World Application', external_stylesheets=[dbc.themes.DARKLY]) server = app.server def setup_artifact_viewer(): # Set Default Template for figures # load_figure_template('darkly') # Grab a view that gives us a summary of all the artifacts currently in SageWorks sageworks_artifacts = ArtifactsWebView() web_artifacts_summary = sageworks_artifacts.view_data() # Just a bunch of tables for now :) tables = {} for service_category, artifact_info_df in web_artifacts_summary.items(): # Grab the Artifact Information DataFrame for each AWS Service tables[service_category] = table.create(service_category, artifact_info_df) # Create our components components = { "incoming_data": tables["INCOMING_DATA_S3"], "data_sources": tables["DATA_SOURCES"], "feature_sets": tables["FEATURE_SETS"], "models": tables["MODELS"], "endpoints": tables["ENDPOINTS"], } # Setup up our application layout app.layout = layout.artifact_layout(app, components) # Setup our callbacks/connections """ callbacks.table_row_select(app, 'model_table') callbacks.update_figures(app, df) callbacks.update_model_details(app, df) callbacks.update_feature_details(app, df) """ # Now actually set up the scoreboard setup_artifact_viewer() if __name__ == "__main__": # Run our web application in TEST mode # Note: This 'main' is purely for running/testing locally app.run_server(host="0.0.0.0", port=8080, debug=True)
/sageworks-0.1.5.3.tar.gz/sageworks-0.1.5.3/applications/hello_world/hello_world.py
0.632389
0.168549
hello_world.py
pypi
import dash from dash import Dash from dash.dependencies import Input, Output # SageWorks Imports from sageworks.web_components.mock_model_data import ModelData from sageworks.web_components import ( feature_importance, confusion_matrix, model_details, feature_details, ) # Highlights the selected row in the table def table_row_select(app: Dash, table_name: str): @app.callback( Output(table_name, "style_data_conditional"), Input(table_name, "derived_viewport_selected_row_ids"), ) def style_selected_rows(selected_rows): if selected_rows is None: return dash.no_update foo = [ { "if": {"filter_query": "{{id}} ={}".format(i)}, "backgroundColor": "rgb(200, 220, 200)", } for i in selected_rows ] return foo # Updates the feature importance and confusion matrix figures when a model is selected def update_figures(app: Dash, model_data: ModelData): @app.callback( [Output("feature_importance", "figure"), Output("confusion_matrix", "figure")], Input("model_table", "derived_viewport_selected_row_ids"), ) def generate_new_figures(selected_rows): print(f"Selected Rows: {selected_rows}") # If there's no selection we're going to return figures for the first row (0) if not selected_rows: selected_rows = [0] # Grab the data for this row model_row_index = selected_rows[0] # Generate a figure for the feature importance component feature_info = model_data.get_model_feature_importance(model_row_index) feature_figure = feature_importance.create_figure(feature_info) # Generate a figure for the confusion matrix component c_matrix = model_data.get_model_confusion_matrix(model_row_index) matrix_figure = confusion_matrix.create_figure(c_matrix) # Now return both of the new figures return [feature_figure, matrix_figure] # Updates the model details when a model row is selected def update_model_details(app: Dash, model_data: ModelData): @app.callback( Output("model_details", "children"), Input("model_table", "derived_viewport_selected_row_ids"), ) def generate_new_markdown(selected_rows): print(f"Selected Rows: {selected_rows}") # If there's no selection we're going to return the model details for the first row (0) if not selected_rows: selected_rows = [0] # Grab the data for this row model_row_index = selected_rows[0] # Generate new Details (Markdown) for the selected model model_info = model_data.get_model_details(model_row_index) model_markdown = model_details.create_markdown(model_info) # Return the details/markdown for this model return model_markdown # Updates the feature details when a model row is selected def update_feature_details(app: Dash, model_data: ModelData): @app.callback( Output("feature_details", "children"), Input("model_table", "derived_viewport_selected_row_ids"), ) def generate_new_markdown(selected_rows): print(f"Selected Rows: {selected_rows}") # If there's no selection we're going to return the feature details for the first row (0) if not selected_rows: selected_rows = [0] # Grab the data for this row model_row_index = selected_rows[0] # Generate new Details (Markdown) for the features for this model feature_info = model_data.get_model_feature_importance(model_row_index) feature_markdown = feature_details.create_markdown(feature_info) # Return the details/markdown for these features return feature_markdown
/sageworks-0.1.5.3.tar.gz/sageworks-0.1.5.3/applications/hello_world/callbacks.py
0.649467
0.391929
callbacks.py
pypi
from dash import Dash from dash_bootstrap_templates import load_figure_template import dash_bootstrap_components as dbc # SageWorks Imports from sageworks.web_components import ( table, data_and_feature_details, distribution_plots, scatter_plot, ) from sageworks.views.data_source_web_view import DataSourceWebView # Local Imports from layout import data_sources_layout import callbacks # Create our Dash app app = Dash( title="SageWorks: Outlier Inspector", external_stylesheets=[dbc.themes.DARKLY], ) # Okay feels a bit weird but Dash pages just have a bunch of top level code (no classes/methods) # Put the components into 'dark' mode load_figure_template("darkly") # Grab a view that gives us a summary of the FeatureSets in SageWorks data_source_broker = DataSourceWebView() data_source_rows = data_source_broker.data_sources_summary() # Create a table to display the data sources data_sources_table = table.create( "data_sources_table", data_source_rows, header_color="rgb(100, 60, 60)", row_select="single", markdown_columns=["Name"], ) # Data Source Details details = data_source_broker.data_source_details(0) data_details = data_and_feature_details.create("data_source_details", details) # Grab outlier rows from the first data source outlier_rows = data_source_broker.data_source_outliers(0) column_types = details["column_details"] if details is not None else None data_source_outlier_rows = table.create( "data_source_outlier_rows", outlier_rows, column_types=column_types, header_color="rgb(80, 80, 80)", row_select="single", max_height="400px", color_column="cluster", ) # Create a box plot of all the numeric columns in the sample rows smart_sample_rows = data_source_broker.data_source_smart_sample(0) violin = distribution_plots.create( "data_source_violin_plot", smart_sample_rows, plot_type="violin", figure_args={ "box_visible": True, "meanline_visible": True, "showlegend": False, "points": "all", }, max_plots=48, ) # Create the outlier cluster plot cluster_plot = scatter_plot.create("outlier_scatter_plot", outlier_rows, "Outlier Groups") # Create our components components = { "data_sources_table": data_sources_table, "data_source_outlier_rows": data_source_outlier_rows, "outlier_scatter_plot": cluster_plot, "data_source_details": data_details, "violin_plot": violin, } # Set up our application layout app.layout = data_sources_layout(**components) # Refresh our data timer callbacks.refresh_data_timer(app) # Periodic update to the data sources summary table callbacks.update_data_sources_table(app, data_source_broker) # Callbacks for when a data source is selected callbacks.table_row_select(app, "data_sources_table") callbacks.update_data_source_details(app, data_source_broker) callbacks.update_data_source_outlier_rows(app, data_source_broker) callbacks.update_cluster_plot(app, data_source_broker) callbacks.update_violin_plots(app, data_source_broker) if __name__ == "__main__": """Run our web application in TEST mode""" # Note: This 'main' is purely for running/testing locally # app.run_server(host="0.0.0.0", port=8081, debug=True) app.run_server(host="0.0.0.0", port=8081)
/sageworks-0.1.5.3.tar.gz/sageworks-0.1.5.3/applications/outlier_inspector/app.py
0.5794
0.337313
app.py
pypi
from datetime import datetime import dash from dash import Dash from dash.dependencies import Input, Output # SageWorks Imports from sageworks.views.data_source_web_view import DataSourceWebView from sageworks.web_components import ( table, data_and_feature_details, distribution_plots, scatter_plot, ) def refresh_data_timer(app: Dash): @app.callback( Output("last-updated-data-sources", "children"), Input("data-sources-updater", "n_intervals"), ) def time_updated(_n): return datetime.now().strftime("Last Updated: %Y-%m-%d %H:%M:%S") def update_data_sources_table(app: Dash, data_source_broker: DataSourceWebView): @app.callback( Output("data_sources_table", "data"), Input("data-sources-updater", "n_intervals"), ) def data_sources_update(_n): """Return the table data as a dictionary""" data_source_broker.refresh() data_source_rows = data_source_broker.data_sources_summary() data_source_rows["id"] = data_source_rows.index return data_source_rows.to_dict("records") # Highlights the selected row in the table def table_row_select(app: Dash, table_name: str): @app.callback( Output(table_name, "style_data_conditional"), Input(table_name, "derived_viewport_selected_row_ids"), ) def style_selected_rows(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update row_style = [ { "if": {"filter_query": "{{id}} ={}".format(i)}, "backgroundColor": "rgb(80, 80, 80)", } for i in selected_rows ] return row_style # Updates the data source details when a row is selected in the summary def update_data_source_details(app: Dash, data_source_web_view: DataSourceWebView): @app.callback( [ Output("data_source_details_header", "children"), Output("data_source_details", "children"), ], Input("data_sources_table", "derived_viewport_selected_row_ids"), ) def generate_new_markdown(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update print("Calling DataSource Details...") data_source_details = data_source_web_view.data_source_details(selected_rows[0]) data_source_details_markdown = data_and_feature_details.create_markdown(data_source_details) # Name of the data source for the Header data_source_name = data_source_web_view.data_source_name(selected_rows[0]) header = f"Details: {data_source_name}" # Return the details/markdown for these data details return [header, data_source_details_markdown] def update_data_source_outlier_rows(app: Dash, data_source_web_view: DataSourceWebView): @app.callback( [ Output("data_source_outlier_rows_header", "children"), Output("data_source_outlier_rows", "columns"), Output("data_source_outlier_rows", "data"), ], Input("data_sources_table", "derived_viewport_selected_row_ids"), prevent_initial_call=True, ) def sample_rows_update(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update print("Calling DataSource Sample Rows...") sample_rows = data_source_web_view.data_source_outliers(selected_rows[0]) # Name of the data source data_source_name = data_source_web_view.data_source_name(selected_rows[0]) header = f"Outlier Rows: {data_source_name}" # The columns need to be in a special format for the DataTable column_setup_list = table.column_setup(sample_rows) # Return the columns and the data return [header, column_setup_list, sample_rows.to_dict("records")] def update_cluster_plot(app: Dash, data_source_web_view: DataSourceWebView): """Updates the Cluster Plot when a new feature set is selected""" @app.callback( Output("outlier_scatter_plot", "figure"), Input("data_sources_table", "derived_viewport_selected_row_ids"), prevent_initial_call=True, ) def generate_new_cluster_plot(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update outlier_rows = data_source_web_view.data_source_outliers(selected_rows[0]) return scatter_plot.create_figure(outlier_rows) def update_violin_plots(app: Dash, data_source_web_view: DataSourceWebView): """Updates the Violin Plots when a new feature set is selected""" @app.callback( Output("data_source_violin_plot", "figure"), Input("data_sources_table", "derived_viewport_selected_row_ids"), prevent_initial_call=True, ) def generate_new_violin_plot(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update smart_sample_rows = data_source_web_view.data_source_smart_sample(selected_rows[0]) return distribution_plots.create_figure( smart_sample_rows, plot_type="violin", figure_args={ "box_visible": True, "meanline_visible": True, "showlegend": False, "points": "all", }, max_plots=48, )
/sageworks-0.1.5.3.tar.gz/sageworks-0.1.5.3/applications/outlier_inspector/callbacks.py
0.768299
0.284828
callbacks.py
pypi
from pathlib import Path from dash import Dash import dash_bootstrap_components as dbc # SageWorks Imports from sageworks.web_components import confusion_matrix, table, scatter_plot from sageworks.web_components import ( feature_importance, model_data, model_details, feature_details, ) # Local Imports import layout import callbacks # Note: The 'app' and 'server' objects need to be at the top level since NGINX/uWSGI needs to # import this file and use the server object as an ^entry-point^ into the Dash Application Code # Create our Dash Application app = Dash(title="Model Details Viewer", external_stylesheets=[dbc.themes.BOOTSTRAP]) # app = Dash(title='Hello World Application', external_stylesheets=[dbc.themes.DARKLY]) server = app.server def setup_model_details_view(): # Set Default Template for figures # load_figure_template('darkly') # Read in our model data data_path = str(Path(__file__).resolve().parent.parent / "data/toy_data.csv") model_info = model_data.ModelData(data_path) # Create our components model_df = model_info.get_model_df() model_table = table.create( "model_table", model_df, show_columns=["model_name", "date_created", "f_scores"], row_select="single", ) details = model_details.create(model_info.get_model_details(0)) c_matrix = confusion_matrix.create(model_info.get_model_confusion_matrix(0)) scatter = scatter_plot.create("model_scatter", model_df) my_feature_importance = feature_importance.create(model_info.get_model_feature_importance(0)) my_feature_details = feature_details.create(model_info.get_model_feature_importance(0)) components = { "model_table": model_table, "model_details": details, "confusion_matrix": c_matrix, "scatter_plot": scatter, "feature_importance": my_feature_importance, "feature_details": my_feature_details, } # Setup up our application layout app.layout = layout.scoreboard_layout(app, components) # Setup our callbacks/connections callbacks.table_row_select(app, "model_table") callbacks.update_figures(app, model_info) callbacks.update_model_details(app, model_info) callbacks.update_feature_details(app, model_info) # Now actually set up the model details view setup_model_details_view() if __name__ == "__main__": # Run our web application in TEST mode # Note: This 'main' is purely for running/testing locally app.run_server(host="0.0.0.0", port=8080, debug=True)
/sageworks-0.1.5.3.tar.gz/sageworks-0.1.5.3/applications/model_viewer/model_viewer.py
0.637482
0.177169
model_viewer.py
pypi
import dash from dash import Dash from dash.dependencies import Input, Output # SageWorks Imports from sageworks.web_components.mock_model_data import ModelData from sageworks.web_components import ( feature_importance, confusion_matrix, model_details, feature_details, ) # Highlights the selected row in the table def table_row_select(app: Dash, table_name: str): @app.callback( Output(table_name, "style_data_conditional"), Input(table_name, "derived_viewport_selected_row_ids"), ) def style_selected_rows(selected_rows): if selected_rows is None: return dash.no_update foo = [ { "if": {"filter_query": "{{id}} ={}".format(i)}, "backgroundColor": "rgb(200, 220, 200)", } for i in selected_rows ] return foo # Updates the feature importance and confusion matrix figures when a model is selected def update_figures(app: Dash, model_data: ModelData): @app.callback( [Output("feature_importance", "figure"), Output("confusion_matrix", "figure")], Input("model_table", "derived_viewport_selected_row_ids"), ) def generate_new_figures(selected_rows): print(f"Selected Rows: {selected_rows}") # If there's no selection we're going to return figures for the first row (0) if not selected_rows: selected_rows = [0] # Grab the data for this row model_row_index = selected_rows[0] # Generate a figure for the feature importance component feature_info = model_data.get_model_feature_importance(model_row_index) feature_figure = feature_importance.create_figure(feature_info) # Generate a figure for the confusion matrix component c_matrix = model_data.get_model_confusion_matrix(model_row_index) matrix_figure = confusion_matrix.create_figure(c_matrix) # Now return both of the new figures return [feature_figure, matrix_figure] # Updates the model details when a model row is selected def update_model_details(app: Dash, model_data: ModelData): @app.callback( Output("model_details", "children"), Input("model_table", "derived_viewport_selected_row_ids"), ) def generate_new_markdown(selected_rows): print(f"Selected Rows: {selected_rows}") # If there's no selection we're going to return the model details for the first row (0) if not selected_rows: selected_rows = [0] # Grab the data for this row model_row_index = selected_rows[0] # Generate new Details (Markdown) for the selected model model_info = model_data.get_model_details(model_row_index) model_markdown = model_details.create_markdown(model_info) # Return the details/markdown for this model return model_markdown # Updates the feature details when a model row is selected def update_feature_details(app: Dash, model_data: ModelData): @app.callback( Output("feature_details", "children"), Input("model_table", "derived_viewport_selected_row_ids"), ) def generate_new_markdown(selected_rows): print(f"Selected Rows: {selected_rows}") # If there's no selection we're going to return the feature details for the first row (0) if not selected_rows: selected_rows = [0] # Grab the data for this row model_row_index = selected_rows[0] # Generate new Details (Markdown) for the features for this model feature_info = model_data.get_model_feature_importance(model_row_index) feature_markdown = feature_details.create_markdown(feature_info) # Return the details/markdown for these features return feature_markdown
/sageworks-0.1.5.3.tar.gz/sageworks-0.1.5.3/applications/model_viewer/callbacks.py
0.649467
0.391929
callbacks.py
pypi
from dash import Dash from dash_bootstrap_templates import load_figure_template import dash_bootstrap_components as dbc # SageWorks Imports from sageworks.web_components import ( table, data_and_feature_details, distribution_plots, scatter_plot, ) from sageworks.views.feature_set_web_view import FeatureSetWebView # Local Imports from layout import feature_sets_layout import callbacks app = Dash( title="SageWorks: Anomaly Inspector", external_stylesheets=[dbc.themes.DARKLY], ) # Okay feels a bit weird but Dash pages just have a bunch of top level code (no classes/methods) # Put the components into 'dark' mode load_figure_template("darkly") # Grab a view that gives us a summary of the FeatureSets in SageWorks feature_set_broker = FeatureSetWebView() feature_set_rows = feature_set_broker.feature_sets_summary() # Create a table to display the data sources feature_sets_table = table.create( "feature_sets_table", feature_set_rows, header_color="rgb(100, 100, 60)", row_select="single", markdown_columns=["Feature Group"], ) # Grab sample rows from the first data source anomalous_rows = feature_set_broker.feature_set_anomalies(0) feature_set_anomalies_rows = table.create( "feature_set_anomalies_rows", anomalous_rows, header_color="rgb(60, 60, 100)", max_height="400px", ) # Data Source Details details = feature_set_broker.feature_set_details(0) data_details = data_and_feature_details.create("feature_set_details", details) # Create a box plot of all the numeric columns in the sample rows smart_sample_rows = feature_set_broker.feature_set_smart_sample(0) violin = distribution_plots.create( "feature_set_violin_plot", smart_sample_rows, plot_type="violin", figure_args={ "box_visible": True, "meanline_visible": True, "showlegend": False, "points": "all", }, max_plots=48, ) # Create the anomaly cluster plot cluster_plot = scatter_plot.create("anomaly_scatter_plot", anomalous_rows) # Create our components components = { "feature_sets_table": feature_sets_table, "feature_set_anomalies_rows": feature_set_anomalies_rows, "anomaly_scatter_plot": cluster_plot, "feature_set_details": data_details, "violin_plot": violin, } # Set up our layout (Dash looks for a var called layout) app.layout = feature_sets_layout(**components) # Refresh our data timer callbacks.refresh_data_timer(app) # Periodic update to the data sources summary table callbacks.update_feature_sets_table(app, feature_set_broker) # Callbacks for when a data source is selected callbacks.table_row_select(app, "feature_sets_table") callbacks.update_feature_set_details(app, feature_set_broker) callbacks.update_feature_set_anomalies_rows(app, feature_set_broker) callbacks.update_cluster_plot(app, feature_set_broker) callbacks.update_violin_plots(app, feature_set_broker) if __name__ == "__main__": """Run our web application in TEST mode""" # Note: This 'main' is purely for running/testing locally # app.run_server(host="0.0.0.0", port=8080, debug=True) app.run_server(host="0.0.0.0", port=8080, debug=True)
/sageworks-0.1.5.3.tar.gz/sageworks-0.1.5.3/applications/anomaly_inspector/app.py
0.581184
0.311139
app.py
pypi
from datetime import datetime import dash from dash import Dash from dash.dependencies import Input, Output # SageWorks Imports from sageworks.views.feature_set_web_view import FeatureSetWebView from sageworks.web_components import ( data_and_feature_details, distribution_plots, scatter_plot, ) def refresh_data_timer(app: Dash): @app.callback( Output("last-updated-feature-sets", "children"), Input("feature-sets-updater", "n_intervals"), ) def time_updated(_n): return datetime.now().strftime("Last Updated: %Y-%m-%d %H:%M:%S") def update_feature_sets_table(app: Dash, feature_set_broker: FeatureSetWebView): @app.callback( Output("feature_sets_table", "data"), Input("feature-sets-updater", "n_intervals"), ) def feature_sets_update(_n): """Return the table data as a dictionary""" feature_set_broker.refresh() feature_set_rows = feature_set_broker.feature_sets_summary() feature_set_rows["id"] = feature_set_rows.index return feature_set_rows.to_dict("records") # Highlights the selected row in the table def table_row_select(app: Dash, table_name: str): @app.callback( Output(table_name, "style_data_conditional"), Input(table_name, "derived_viewport_selected_row_ids"), ) def style_selected_rows(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update row_style = [ { "if": {"filter_query": "{{id}} ={}".format(i)}, "backgroundColor": "rgb(80, 80, 80)", } for i in selected_rows ] return row_style # Updates the data source details when a row is selected in the summary def update_feature_set_details(app: Dash, feature_set_web_view: FeatureSetWebView): @app.callback( [ Output("feature_details_header", "children"), Output("feature_set_details", "children"), ], Input("feature_sets_table", "derived_viewport_selected_row_ids"), ) def generate_new_markdown(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update print("Calling FeatureSet Details...") feature_details = feature_set_web_view.feature_set_details(selected_rows[0]) feature_details_markdown = data_and_feature_details.create_markdown(feature_details) # Name of the data source for the Header feature_set_name = feature_set_web_view.feature_set_name(selected_rows[0]) header = f"Details: {feature_set_name}" # Return the details/markdown for these data details return [header, feature_details_markdown] def update_feature_set_anomalies_rows(app: Dash, feature_set_web_view: FeatureSetWebView): @app.callback( [ Output("feature_sample_rows_header", "children"), Output("feature_set_anomalies_rows", "columns"), Output("feature_set_anomalies_rows", "data"), ], Input("feature_sets_table", "derived_viewport_selected_row_ids"), prevent_initial_call=True, ) def sample_rows_update(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update print("Calling FeatureSet Sample Rows...") sample_rows = feature_set_web_view.feature_set_anomalies(selected_rows[0]) # Name of the data source feature_set_name = feature_set_web_view.feature_set_name(selected_rows[0]) header = f"Anomalous Rows: {feature_set_name}" # The columns need to be in a special format for the DataTable column_setup = [{"name": c, "id": c, "presentation": "input"} for c in sample_rows.columns] # Return the columns and the data return [header, column_setup, sample_rows.to_dict("records")] def update_cluster_plot(app: Dash, feature_set_web_view: FeatureSetWebView): """Updates the Cluster Plot when a new feature set is selected""" @app.callback( Output("anomaly_scatter_plot", "figure"), Input("feature_sets_table", "derived_viewport_selected_row_ids"), prevent_initial_call=True, ) def generate_new_cluster_plot(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update print("Calling FeatureSet Sample Rows Refresh...") anomalous_rows = feature_set_web_view.feature_set_anomalies(selected_rows[0]) return scatter_plot.create_figure(anomalous_rows) def update_violin_plots(app: Dash, feature_set_web_view: FeatureSetWebView): """Updates the Violin Plots when a new feature set is selected""" @app.callback( Output("feature_set_violin_plot", "figure"), Input("feature_sets_table", "derived_viewport_selected_row_ids"), prevent_initial_call=True, ) def generate_new_violin_plot(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update print("Calling FeatureSet Sample Rows Refresh...") smart_sample_rows = feature_set_web_view.feature_set_smart_sample(selected_rows[0]) return distribution_plots.create_figure( smart_sample_rows, plot_type="violin", figure_args={ "box_visible": True, "meanline_visible": True, "showlegend": False, "points": "all", }, max_plots=48, )
/sageworks-0.1.5.3.tar.gz/sageworks-0.1.5.3/applications/anomaly_inspector/callbacks.py
0.773302
0.268252
callbacks.py
pypi
from dash import register_page import dash from dash_bootstrap_templates import load_figure_template # SageWorks Imports from sageworks.web_components import table, data_and_feature_details, distribution_plots from sageworks.views.data_source_web_view import DataSourceWebView # Local Imports from .layout import data_sources_layout from . import callbacks register_page( __name__, path="/data_sources", name="SageWorks - Data Sources", ) # Okay feels a bit weird but Dash pages just have a bunch of top level code (no classes/methods) # Put the components into 'dark' mode load_figure_template("darkly") # Grab a view that gives us a summary of the DataSources in SageWorks data_source_broker = DataSourceWebView() data_source_rows = data_source_broker.data_sources_summary() # Create a table to display the data sources data_sources_table = table.create( "data_sources_table", data_source_rows, header_color="rgb(100, 60, 60)", row_select="single", markdown_columns=["Name"], ) # Data Source Details details = data_source_broker.data_source_details(0) data_details = data_and_feature_details.create("data_source_details", details) # Grab sample rows from the first data source sample_rows = data_source_broker.data_source_sample(0) column_types = details["column_details"] if details is not None else None data_source_sample_rows = table.create( "data_source_sample_rows", sample_rows, column_types=column_types, header_color="rgb(60, 60, 100)", max_height="200px", ) # Create a box plot of all the numeric columns in the sample rows smart_sample_rows = data_source_broker.data_source_smart_sample(0) violin = distribution_plots.create( "data_source_violin_plot", smart_sample_rows, plot_type="violin", figure_args={ "box_visible": True, "meanline_visible": True, "showlegend": False, "points": "all", }, max_plots=48, ) # Create our components components = { "data_sources_table": data_sources_table, "data_source_details": data_details, "data_source_sample_rows": data_source_sample_rows, "violin_plot": violin, } # Set up our layout (Dash looks for a var called layout) layout = data_sources_layout(**components) # Setup our callbacks/connections app = dash.get_app() # Refresh our data timer callbacks.refresh_data_timer(app) # Periodic update to the data sources summary table callbacks.update_data_sources_table(app, data_source_broker) # Callbacks for when a data source is selected callbacks.table_row_select(app, "data_sources_table") callbacks.update_data_source_details(app, data_source_broker) callbacks.update_data_source_sample_rows(app, data_source_broker) callbacks.update_violin_plots(app, data_source_broker)
/sageworks-0.1.5.3.tar.gz/sageworks-0.1.5.3/applications/aws_dashboard/pages/data_sources/page.py
0.525125
0.27163
page.py
pypi
from datetime import datetime import dash from dash import Dash from dash.dependencies import Input, Output # SageWorks Imports from sageworks.views.data_source_web_view import DataSourceWebView from sageworks.web_components import data_and_feature_details, distribution_plots def refresh_data_timer(app: Dash): @app.callback( Output("last-updated-data-sources", "children"), Input("data-sources-updater", "n_intervals"), ) def time_updated(_n): return datetime.now().strftime("Last Updated: %Y-%m-%d %H:%M:%S") def update_data_sources_table(app: Dash, data_source_broker: DataSourceWebView): @app.callback( Output("data_sources_table", "data"), Input("data-sources-updater", "n_intervals"), ) def data_sources_update(_n): """Return the table data as a dictionary""" data_source_broker.refresh() data_source_rows = data_source_broker.data_sources_summary() data_source_rows["id"] = data_source_rows.index return data_source_rows.to_dict("records") # Highlights the selected row in the table def table_row_select(app: Dash, table_name: str): @app.callback( Output(table_name, "style_data_conditional"), Input(table_name, "derived_viewport_selected_row_ids"), ) def style_selected_rows(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update row_style = [ { "if": {"filter_query": "{{id}} ={}".format(i)}, "backgroundColor": "rgb(80, 80, 80)", } for i in selected_rows ] return row_style # Updates the data source details when a row is selected in the summary def update_data_source_details(app: Dash, data_source_web_view: DataSourceWebView): @app.callback( [ Output("data_details_header", "children"), Output("data_source_details", "children"), ], Input("data_sources_table", "derived_viewport_selected_row_ids"), ) def generate_new_markdown(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update print("Calling DataSource Details...") data_details = data_source_web_view.data_source_details(selected_rows[0]) data_details_markdown = data_and_feature_details.create_markdown(data_details) # Name of the data source for the Header data_source_name = data_source_web_view.data_source_name(selected_rows[0]) header = f"Details: {data_source_name}" # Return the details/markdown for these data details return [header, data_details_markdown] def update_data_source_sample_rows(app: Dash, data_source_web_view: DataSourceWebView): @app.callback( [ Output("sample_rows_header", "children"), Output("data_source_sample_rows", "columns"), Output("data_source_sample_rows", "data"), ], Input("data_sources_table", "derived_viewport_selected_row_ids"), prevent_initial_call=True, ) def sample_rows_update(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update print("Calling DataSource Sample Rows...") sample_rows = data_source_web_view.data_source_sample(selected_rows[0]) # Name of the data source data_source_name = data_source_web_view.data_source_name(selected_rows[0]) header = f"Sampled Rows: {data_source_name}" # The columns need to be in a special format for the DataTable column_setup = [{"name": c, "id": c, "presentation": "input"} for c in sample_rows.columns] # Return the columns and the data return [header, column_setup, sample_rows.to_dict("records")] def update_violin_plots(app: Dash, data_source_web_view: DataSourceWebView): """Updates the Violin Plots when a new data source is selected""" @app.callback( Output("data_source_violin_plot", "figure"), Input("data_sources_table", "derived_viewport_selected_row_ids"), prevent_initial_call=True, ) def generate_new_violin_plot(selected_rows): print(f"Selected Rows: {selected_rows}") if not selected_rows or selected_rows[0] is None: return dash.no_update print("Calling DataSource Sample Rows Refresh...") smart_sample_rows = data_source_web_view.data_source_smart_sample(selected_rows[0]) return distribution_plots.create_figure( smart_sample_rows, plot_type="violin", figure_args={ "box_visible": True, "meanline_visible": True, "showlegend": False, "points": "all", }, max_plots=48, )
/sageworks-0.1.5.3.tar.gz/sageworks-0.1.5.3/applications/aws_dashboard/pages/data_sources/callbacks.py
0.753013
0.28123
callbacks.py
pypi
from dash import html, dcc, dash_table import dash_bootstrap_components as dbc def main_layout( incoming_data: dash_table.DataTable, glue_jobs: dash_table.DataTable, data_sources: dash_table.DataTable, feature_sets: dash_table.DataTable, models: dash_table.DataTable, endpoints: dash_table.DataTable, ) -> html.Div: # Just put all the tables in as Rows for Now (do something fancy later) layout = html.Div( children=[ dcc.Store(data="", id="remove-artifact-store", storage_type="session"), dcc.Store(data="", id="modal-trigger-state-store", storage_type="session"), dbc.Modal( [ dbc.ModalHeader(dbc.ModalTitle("Attention")), dbc.ModalBody(id="modal-body"), dbc.ModalFooter( [ dbc.Button("No", id="no-button", n_clicks=0), dbc.Button("Yes", id="yes-button", n_clicks=0), ] ), ], id="modal", is_open=False, ), dbc.Row( [ html.H2("SageWorks Dashboard"), html.Div( "Last Updated: ", id="last-updated", style={ "color": "rgb(140, 200, 140)", "fontSize": 15, "padding": "0px 0px 0px 120px", }, ), ] ), dbc.Row(html.H3("Incoming Data"), style={"padding": "10px 0px 0px 0px"}), dbc.Row(incoming_data), dbc.Row(html.H3("Glue Jobs"), style={"padding": "10px 0px 0px 0px"}), dbc.Row(glue_jobs), dbc.Row(html.H3("Data Sources"), style={"padding": "10px 0px 0px 0px"}), dbc.Row(data_sources), dbc.Row(html.H3("Feature Sets"), style={"padding": "10px 0px 0px 0px"}), dbc.Row(feature_sets), dbc.Row(html.H3("Models"), style={"padding": "10px 0px 0px 0px"}), dbc.Row(models), dbc.Row(html.H3("Endpoints"), style={"padding": "10px 0px 0px 0px"}), dbc.Row(endpoints), dcc.Interval(id="main-updater", interval=5000, n_intervals=0), ], style={"margin": "30px"}, ) return layout
/sageworks-0.1.5.3.tar.gz/sageworks-0.1.5.3/applications/aws_dashboard/pages/main/layout.py
0.457137
0.211295
layout.py
pypi