amc.ast module

Abstract Syntax Tree classes.

The ast module provides classes necessary to build abstract syntax trees for reduced and unreduced equations.

class amc.ast.AST(type)

Bases: object

An Abstract Syntax Tree node.

The AST node is the basic building block of the abstract syntax tree that represents unreduced and reduced equations. Access to a node’s children is provided by subscripting:

>>> node = AST('node')
>>> node[:] = [AST('child')]
>>> node[0].type
'child'
>>> len(node), len(node[0])
(1, 0)
Parameters
typestr

The type of the node. Used for traversing the AST.

Attributes
typestr

The type of the node. Used for traversing the AST.

type
class amc.ast.ASTTraverser

Bases: object

Base class for implementing AST traversers.

This class provides the basic facilities for traversing an AST in pre- or post-order. It supports two modes of operation:

The first mode is activated by invoking the static method traverse on the root of the tree and providing two functions preaction and postaction. The preaction function is called for each node before its children, postaction is called after its children have been traversed.

The second mode can be used by subclassing ASTTraverser: for each type of AST node (according to the AST.type attribute), the methods n_<type> and n_<type>_exit can be implemented. These methods will be called before and after visiting the children of a node of the given type. Additionally, methods named default and default_exit can be provided, which will be called when the node does not have a type attribute or no type-specific method has been provided.

In both modes, preactions may call the static prune method to signal that the node children should not be traversed. The postaction for this node will still be called.

Methods

prune([params])

Stop processing the current node’s children.

start(self, root)

Start the AST traversal.

traverse(root[, preaction, postaction])

Traverse the AST represented by the given root node.

static prune(params=None)

Stop processing the current node’s children.

Warning

Must be called from a preaction and does not return.

Parameters
paramsdict

Dictionary of kwargs to pass to the postaction.

start(self, root)

Start the AST traversal.

Starts the AST traversal beginning with the root. This method is intended for use with subclasses of ASTTraverser. For each node visited, it looks for the method n_<type> and n_<type>_exit, respectively to use as pre- and postactions. If no appropriate methods are found or the node does not have a type attribute, default or default_exit is called, both of which default to doing nothing.

Parameters
rootAST

The root node of the AST to traverse.

Returns
result

The return value of the root’s postaction.

static traverse(root, preaction=(lambda n, **k: None), postaction=(lambda n, r, **k: None))

Traverse the AST represented by the given root node.

Parameters
rootAST

The root node of the AST to traverse.

preactioncallable

Function to be called before visiting the given node’s children.

Parameters

  • node :

    Current node.

  • **kwargs :

    Additional keyword arguments passed from the parent.

Optionally, kwargs to the node’s postaction and the children’s preactions can be provided by returning a dict-like object. The root preaction is called without parameters.

postactioncallable

Function to be called after visiting the given node’s children.

Parameters

  • node:

    Current node.

  • results:

    List of return values of of all children’s postactions, in order.

  • **kwargs:

    Additional keyword arguments passed from the preaction.

The return value of this function is appended to a list that is passed to the parent’s postaction.

Returns
result

The return value of the root node’s postaction.

See also

prune

To skip traversing a node’s children.

class amc.ast.Add(terms)

Bases: amc.ast.AST

Add node.

Represents an addition of terms.

Note

Add nodes have type add.

Parameters
termsiterable

Terms to add.

Notes

The constructor simplifies the terms, removing zeros and splicing contents of Add objects. It may, therefore, not return an Add object at all, e.g., if there is only one term.

Attributes
contains_permbool

Flag to signal that at least one term contains a permutation operator.

depends_onset of Index

Set of all indices the terms depend on.

Methods

apply_permutation(self, i, j)

Permute two indices in all terms.

distribute(self, terms[, side, keep_diagonal])

Apply the distributive law to turn a Mul of Add into an Add of Mul.

expand(self[, keep_diagonal])

Expand the terms of the Add.

expand_permutations(self)

Expand permutation operators in terms.

is_diagonal(self)

Check if all variables contained in terms are diagonal.

apply_permutation(self, i, j)

Permute two indices in all terms.

Parameters
i, jIndex

Indices to permute.

Returns
new_addAdd

New Add with indices i and j exchanged, or self if the object is independent of both.

distribute(self, terms, side='right', keep_diagonal=True)

Apply the distributive law to turn a Mul of Add into an Add of Mul.

Parameters
termslist of AST

Factors of the product to distribute.

side{‘left’, ‘right’}

Indicates whether the terms are on the left or right side of this Add.

keep_diagonalbool

If True, keeps diagonal terms undistributed.

Returns
An Add or Mul instance containing the distributed terms.
expand(self, keep_diagonal=True)

Expand the terms of the Add.

Expands each term into a sum of products.

Parameters
keep_diagonalbool

If set, keeps diagonal subterms, like sums of diagonal tensors, unexpanded.

Returns
new_addAdd

New, expanded Add or self if expansion did not change the terms.

expand_permutations(self)

Expand permutation operators in terms.

Expands permutation operators, turning them into sums over products of permuted expressions.

Returns
new_addAdd

New, expanded Add or self if expansion did not change the object.

is_diagonal(self)

Check if all variables contained in terms are diagonal.

Returns
True if all terms are diagonal.
type
class amc.ast.DeltaJ(a, b)

Bases: amc.ast.AST

DeltaJ node.

Represents a delta constraint on angular momenta.

Note

DeltaJ nodes have type deltaj.

Parameters
a, bIndex

Indices to be constrained.

Attributes
a, bIndex

Constrained indices.

depends_onset of Index

Set of the two constrained indices.

type
class amc.ast.Equation(lhs, rhs)

Bases: amc.ast.AST

Equation node.

Represents a reduced or unreduced equation.

Note

Equation nodes have type equation.

Parameters
lhsVariable or ReducedVariable

Left-hand side of the equation. Must be a variable.

rhsAST

Right-hand side of the equation. Can be any expression. The left-hand side introduces a set of indices, which must be the only free indices on the right-hand side.

Attributes
lhsVariable or ReducedVariable

Left-hand side of the equation.

rhsAST

Right-hand side of the equation. Can be any expression.

Methods

expand(self[, keep_diagonal])

Expand the equation.

expand_permutations(self)

Expand permutation operators in expressions.

expand(self, keep_diagonal=True)

Expand the equation.

Expands the right-hand side of the equation into a sum of products.

Parameters
keep_diagonalbool

If set, keeps diagonal subterms, like sums of diagonal tensors, unexpanded.

Returns
new_eqnAST

New, expanded equation or self if expansion did not change the right-hand side.

expand_permutations(self)

Expand permutation operators in expressions.

Expands permutation operators, turning them into sums over products of permuted expressions.

Returns
new_eqnAST

New, expanded equation or self if expansion did not change the right-hand side.

type
class amc.ast.HatPhaseFactor(index, hatpower=0, jphase=0, mphase=0, sign=1)

Bases: amc.ast.AST

Combined node for hat and phase factors.

Represents the terms \((-1)^{xj+ym} (\sqrt{2j+1})^z\).

Note

HatPhaseFactor nodes have type hatphasefactor.

Parameters
indexIndex

Index associated with the hat-phase factor.

hatpowerinteger

Power of the hat factor \(\sqrt{2j+1}\).

jphaseinteger

Multiplier of j in the phase factor.

mphaseinteger

Multiplier of m in the phase factor.

sign{+1, -1}

Overall sign.

Notes

The constructor might return an int or a Mul.

Attributes
indexIndex

Index associated with the hat-phase factor.

hatpowerinteger

Power of the hat factor \(\sqrt{2j+1}\).

jphaseinteger

Multiplier of j in the phase factor.

mphaseinteger

Multiplier of m in the phase factor.

type
class amc.ast.Index(name, type, class_)

Bases: object

Index object.

Represents a tensor index.

Parameters
namestr

Name of the index.

type{‘int’, ‘hint’}

Type of the index. Must be ‘int’ for integer indices, or ‘hint’ for half-integers.

class_{‘am’, ‘part’}

Index class. Must be ‘am’ for simple angular-momentum indices, or ‘part’ for particle indices. ‘part’ indicates that the index ranges over the full single-particle basis instead of just an angular momentum.

Attributes
namestr

Name of the index.

type{‘int’, ‘hint’}

Type of the index. Must be ‘int’ for integer indices, or ‘hint’ for half-integers.

class_{‘am’, ‘part’}

Index class. Must be ‘am’ for simple angular-momentum indices, or ‘part’ for particle indices. ‘part’ indicates that the index ranges over the full single-particle basis instead of just an angular momentum.

constrained_toIndex or None

Index object that this index is constrained to via a delta constraint.

Methods

coupled_type(i1, i2)

Get the coupled type for an index pair.

static coupled_type(i1, i2)

Get the coupled type for an index pair.

Parameters
i1, i2Index

The indices to couple.

Returns
cptypestr

The index type resulting from coupling i1 and i2 together.

class amc.ast.Mul(terms)

Bases: amc.ast.AST

Multiplication node.

Represents a multiplication of factors.

Note

Mul nodes have type mul.

Parameters
termsiterable

Factors to multiply.

Notes

The constructor cleans up the list of terms, removing factors of one, splicing Mul factors, and collecting numerical factors. Depending on the nature and number of factors, the resulting object may not be a Mul.

Attributes
contains_permbool

Flag to signal that at least one factor contains a permutation operator.

depends_onset of Index

Set of all indices the factors depend on.

Methods

apply_permutation(self, i, j)

Permute two indices in all factors.

expand(self[, keep_diagonal])

Expand the factors of the Mul.

expand_permutations(self)

Expand permutation operators in factors.

apply_permutation(self, i, j)

Permute two indices in all factors.

Parameters
i, jIndex

Indices to permute.

Returns
new_mulMul

New Mul with indices i and j exchanged, or self if the object is independent of both.

expand(self, keep_diagonal=True)

Expand the factors of the Mul.

Expands all factors, then distributes over each Add factor.

Parameters
keep_diagonalbool

If set, keeps diagonal subterms, like sums of diagonal tensors, unexpanded.

Returns
new_expr

New, expanded expression. May be self if the expansion did not change anything. In most cases the returned expression is a Mul without Add factors or an Add of Mul terms.

expand_permutations(self)

Expand permutation operators in factors.

Expands permutation operators, turning them into sums of permuted expressions.

Returns
new_mulMul

New, expanded Mul or self if expansion did not change the object.

type
class amc.ast.NineJ(indices)

Bases: amc.ast.AST

9j node.

Represents a Wigner 9j symbol.

Note

NineJ nodes have type ninej.

Parameters
indices9-tuple of Index

Indices of the 9j symbol.

Attributes
depends_onset of Index

Set of the indices.

indices9-tuple of Index

Indices of the 9j symbol.

type
class amc.ast.Permute(sets)

Bases: amc.ast.AST

Permute node.

Represents a permutation or transposition operator.

Note

Permute nodes have type permute.

The permute operator supports two modes of operation: With a single set, it acts as a transposition operator. With multiple sets, it generates all distinct permutations between indices of different sets, along with the appropriate sign of the permutation, e.g.

\[\begin{split}P(a/b) &= 1 - P(ab) \\ P(ab/c) &= 1 - P(ac) - P(bc).\end{split}\]
Parameters
setsiterable of iterable of Index

Sets of indices to be permuted.

Attributes
contains_permbool

Always True.

depends_onset of Index

Set of all indices appearing in the permute object.

Methods

apply_operator(self, terms)

Apply the Permute operator to the provided factors.

apply_permutation(self, i, j)

Permute two indices in the permutation sets.

apply_operator(self, terms)

Apply the Permute operator to the provided factors.

Parameters
termsiterable

Factors the Permute acts on. It is assumed that the factors belong to a Mul.

Returns
mul_or_add

Depending on operation mode, a Mul with indices transposed, or an Add with all generated terms.

apply_permutation(self, i, j)

Permute two indices in the permutation sets.

Parameters
i, jIndex

Indices to permute.

Returns
new_permPermute

New Permute with indices i and j exchanged, or self if the object is independent of both, or the permutation had no effect.

type
class amc.ast.ReducedVariable(tensor, subscripts, labels)

Bases: amc.ast.AST

Reduced tensor variable node.

Note

ReducedVariable nodes have type reducedvariable.

Parameters
tensorTensorDeclaration

The tensor that this variable belongs to.

subscriptstuple of Index

List of subscripts. Length must be compatible with tensor.mode.

labelstuple of Index

List of additional angular-momentum labels. Must be compatible with tensor.scheme.

Attributes
tensorTensorDeclaration

The tensor that this variable belongs to.

subscriptstuple of Index

List of subscripts.

labelstuple of Index

List of additional angular-momentum labels.

depends_onset of Index

Set of the subscript and label indices.

Methods

apply_permutation(self, i, j)

Permute two indices.

apply_permutation(self, i, j)

Permute two indices.

Parameters
i, jIndex

Indices to permute.

Returns
new_var

New variable with indices i and j exchanged, or self if the ReducedVariable is independent of both.

type
class amc.ast.SixJ(indices)

Bases: amc.ast.AST

6j node.

Represents a Wigner 6j symbol.

Note

SixJ nodes have type sixj.

Parameters
indices6-tuple of Index

Indices of the 6j symbol.

Attributes
depends_onset of Index

Set of the indices.

indices6-tuple of Index

Indices of the 6j symbol.

type
class amc.ast.Sum(subscripts, expression)

Bases: amc.ast.AST

Summation node.

Represents a sum over indices.

Note

Sum nodes have type sum.

Parameters
subscriptsiterable of Index

Indices that are summed over.

expressionAST

Body of the sum.

Notes

The constructor cleans up the expression, factoring out factors that do not depend on the summed indices, and coalescing sub-sums. Therefore, the returned object might be a Mul or an int.

Attributes
contains_permbool

Flag to signal that at least one factor contains a permutation operator.

depends_onset of Index

Indices the expression depends on but are not summed over.

subscriptsset of Index

Indices that are summed over.

Methods

apply_permutation(self, i, j)

Permute two indices in the sum body.

distribute(self, terms[, side, keep_diagonal])

Distribute the sum over the given terms.

expand(self[, keep_diagonal])

Expand the sum body.

expand_permutations(self)

Expand permutations in the sum body.

apply_permutation(self, i, j)

Permute two indices in the sum body.

Parameters
i, jIndex

Indices to permute.

Returns
new_sumSum

New Sum with indices i and j exchanged, or self if the object is independent of both.

distribute(self, terms, side='right', keep_diagonal=False)

Distribute the sum over the given terms.

Pulls the given terms into the sum.

Parameters
termslist of AST

Factors of the product to distribute.

side{‘left’, ‘right’}

Indicates whether the terms are on the left or right side of this Sum.

keep_diagonalbool

If True, keeps diagonal terms undistributed.

Returns
new_sumSum

A Sum containing a Mul of the terms with the original body.

expand(self, keep_diagonal=True)

Expand the sum body.

If the body expands to an Add, distribute the sum over each term.

Parameters
keep_diagonalbool

If set, keeps diagonal subterms, like sums of diagonal tensors, unexpanded.

Returns
new_expr

New, expanded expression. May be self if the expansion did not change anything.

expand_permutations(self)

Expand permutations in the sum body.

Returns
A new Sum with permutations expanded, or self if there are no
permutations in the body.
type
class amc.ast.TensorDeclaration(name, mode, scalar=True, reduce=False, diagonal=False, scheme=None, **kwargs)

Bases: amc.ast.AST

Tensor declaration node.

A node that declares a tensor, enabling its use in variables.

Note

TensorDeclaration nodes have type declare.

Parameters
namestr

Name of the tensor.

modeint or 2-tuple of int

Mode of the tensor, specifies the number and type of indices. If mode is an integer, it has to be even, and it is assumed that the tensor has mode // 2 creator and mode // 2 annihilator indices.

If mode is a 2-tuple, the first and second members give the number of creator and annihilator indices, respectively.

scalarbool

True if tensor has rank zero, False otherwise.

reducebool

If True, use reduced matrix elements even if the tensor is scalar. Has no effect on nonscalar tensors because these are always reduced.

diagonalbool

Flag signaling that the tensor is diagonal. A diagonal tensor only has half as many indices as its mode suggests, and no coupling scheme.

scheme2-tuple, optional

Coupling scheme of the tensor. If omitted, a default scheme is generated by coupling indices left-to-right. If given, must be a tree of 2-tuples with integers as leaves.

The coupling scheme is specified as follows: each index on the tensor is assigned a number, starting at 1. A tuple of integers indicates that the angular momenta of the respective indices should be coupled to some collective angular momentum. An integer may be negated to indicate coupling of the time-reversed state. A tuple containing a tuple indicates coupling of the collective angular momenta to a new angular momentum. The top-level angular momenta are coupled to the tensor rank.

Example

((1,2),3) couples 1 and 2 to J0, and J0 and 3 to J1. ((1,-4),(3,-2)) couples 1 and time-reversed 4 to J0, 3 and time-reversed 2 to J1, and J0 and J1 to J2 (the rank of the tensor).

**kwargs

Additional arguments, stored as a dict in the attrs attribute.

Attributes
namestr
mode2-tuple of int
scalarbool
reducebool
diagonalbool
scheme2-tuple
attrsdict

All parameters are available as attributes under the same name. mode is converted to a tuple, and a scheme is generated if none was provided.

effective_mode2-tuple

The effective number of left and right indices, accounting for cross coupling.

type
class amc.ast.ThreeJ(indices)

Bases: amc.ast.AST

3j node.

Represents a triangular inequality between three indices.

Note

ThreeJ nodes have type threej.

Parameters
indices3-tuple of Index

Indices constrained by the 3j symbol.

Attributes
depends_onset of Index

Set of the three indices.

indices3-tuple of Index

Indices constrained by the 3j symbol.

type
class amc.ast.Variable(tensor, subscripts)

Bases: amc.ast.AST

Unreduced tensor variable node.

Note

Variable nodes have type variable.

Parameters
tensorTensorDeclaration

The tensor that this variable belongs to.

subscriptstuple of Index

List of subscripts. Length must be compatible with tensor.mode.

Attributes
tensorTensorDeclaration

The tensor that this variable belongs to.

subscriptstuple of Index

List of subscripts.

depends_onset of Index

Set of the subscript indices.

Methods

apply_permutation(self, i, j)

Permute two indices.

apply_permutation(self, i, j)

Permute two indices.

Parameters
i, jIndex

Indices to permute.

Returns
new_var

New variable with indices i and j exchanged, or self if the Variable is independent of both.

type