Expression¶
This module defines the function parse(), which parses a tensor
expression.
-
nutils.expression.parse(expression, variables, functions, indices, arg_shapes={}, default_geometry_name='x')[source]¶ Parse
expressionand return AST.This function parses a tensor expression with Einstein Summation Convection stored in a
strand returns an Abstract Syntax Tree (AST). The syntax ofexpressionis as follows:Integers or decimal numbers are denoted in the usual way. Examples:
1,1.2,.2. A number may not start with a zero, except when followed by a dot:0.1is valid, but01is not.Variables are denoted with a string of alphanumeric characters. The first character may not be a numeral. Unlike Python variables, underscores are not allowed, as they have a special meaning. If the variable is an array with one or more axes, all those axes should be labeled with a latin character, the index, and appended to the variable with an underscore. For example an array
awith two axes can be denoted witha_ij. Optionally, a single numeral may be used to select an item at the concerning axis. Example: ina_i0the first axis ofais labelediand the first element of the second axis is selected. If the same index occurs twice, the trace is taken along the concerning axes. Example: the trace of the first and third axes ofbis denoted byb_iji. It is invalid to specify an index more than twice. The following names cannot be used as variables:n,δ,$. The variable namedx, or the value of argumentdefault_geometry_name, has a special meaning, detailed below.A term, the product of two or more arrays or scalars, is denoted by space-separated variables, constants or compound expressions. Example:
a b cdenotes the product of the scalarsa,bandc. A term may start with a number, but a number is not allowed in other parts of the term. Example:2 adenotes two timesa;2 2 aand2 a 2`are invalid. When two arrays in a term have the same index, this index is summed. Example:a_i b_idenotes the inner product ofaandbandA_ij b_j`a matrix vector product. It is not allowed to use an index more than twice in a term.The operator
/denotes a fraction. Example: ina b / c da bis the numerator andc dthe denominator. Both the numerator and the denominator may start with a number. Example:2 a / 3 b. The denominator must be a scalar. Example:2 / a_i b_iis valid, but2 a_i / b_iis not.Warning
This syntax is different from the Python syntax. In Python
a*b / c*dis mathematically equivalent toa*b*d/c.The operators
+and-denote add and subtract. Both operators should be surrounded by whitespace, e.g.a + b. Both operands should have the same shape. Example:a_ij + b_i c_jis a valid, provided that the lengths of the axes with the same indices match, buta_ij + b_iis invalid. At the beginning of an expression or a compound-may be used to negate the following term. Example: in-a b + cthe terma bis negated before addingc. It is not allowed to negate other terms:a + -bis invalid, so isa -b.An expression surrounded by parentheses is a compound expression and can be used as single entity in a term. Example:
(a_i + b_i) c_idenotes the inner product ofa_i + b_iwithc_i.Exponentiation is denoted by a
^, where the left and right operands should be a number, variable or compound expression and the right operand should be a scalar. Example:a^2denotes the square ofa,a^-2denotesato the power-2anda^(1 / 2)the square root ofa.An argument is denoted by a name — following the same rules as a variable name — prefixed with a question mark. An argument is a scalar or array with a yet unknown value. Example:
basis_i ?coeffs_idenotes the inner product of a basis with unknown coefficient vector?coeffs. If possible the shape of the argument is deduced from the expression. In the previous example the shape of?coeffsis equal to the shape ofbasis. If the shape cannot be deduced from the expression the shape should be defined manually (seeparse()). Arguments and variables live in separate namespaces:?xandxare different entities.An argument may be substituted by appending without whitespace
(arg = value)to a variable of compound expression, whereargis an argument andvaluethe substitution. The substitution applies to the variable of compound expression only. The value may be an expression. Example:2 ?x(x = 3 + y)is equivalent to2 (3 + y)and2 ?x(x=y) + 3is equivalent to2 (y) + 3. It is possible to apply multiple substitutions. Example:(?x + ?y)(x = 1, y = )2is equivalent to1 + 2.The gradient of a variable to the default geometry — the default geometry is variable
xunless overriden by the argumentdefault_geometry_name— is denoted by an underscore, a comma and an index. If the variable is an array with more than one axis, the underscore is omitted. Example:a_,idenotes the gradient of the scalarato the geometry andb_i,jthe gradient of vectorb. The gradient of a compound expression is denoted by an underscore, a comma and an index. Example:(a_i + b_j)_,kdenotes the gradient ofa_i + b_j. The usual summation rules apply and it is allowed to use a numeral as index. The surface gradient is denoted with a semicolon instead of a comma, but follows the same rules as the gradient otherwise. Example:a_i;jis the sufrace gradient ofa_ito the geometry. It is also possible to take the gradient to another geometry by appending the name of the geometry, which should exist as a variable, and an underscore directly after the comma of semicolon. Example:a_i,altgeom_jdenotes the gradient ofa_itoaltgeomand the gradient axis has indexj. Futhermore, it is possible to take the derivative to an argument by adding the argument with appropriate indices after the comma. Example:(?x^2)_,?xdenotes the derivative of?x^2to?x, which is equivalent to2 ?x, and(?y_i ?y_i),?y_jis the derivative of?y_i ?y_ito?y_j, which is equivalent to2 ?y_j.The normal of the default geometry is denoted by
n_i, where the indeximay be replaced with an index of choice. The normal with respect to different geometry is denoted by appending an underscore with the name of the geometry right aftern. Example:n_altgeom_jis the normal with respect to geometryaltgeom.A dirac is denoted by
δor$and takes two indices. The shape of the dirac is deduced from the expression. Example: letAbe a square matrix with three rows and columns, thenδ_ijin(A_ij - λ δ_ij) x_jhas three rows and columns as well.An expression surrounded by square brackets or curly braces denotes the jump or mean, respectively, of the enclosed expression. Example:
[ a_i ]denotes the jump ofa_iand{ a_i + b_i }denotes the mean ofa_i + b_i.A function call is denoted by a name — following the same rules as for a variable name — directly followed by the left parenthesis
(, without a space. The arguments to the function are separated by a comma and at least one space. The function is applied pointwise to the arguments and all arguments should have the same shape. Example:f(x_i, y_i).denotes the call to functionfwith argumentsx_iandy_i. Functions and variables share a namespace: defining a variable with the same name as a function renders the function inaccessible.A stack of two or more arrays along an axis is denoted by a
<followed by comma and space separated arrays followed by>and an index. If an argument does not have an axis with the specified stack index, the argument is expanded with an axis of length one. Beside the stack axis, all arguments should have the same shape. Example:<1, x_i>_i, withxa vector of length three, creates an array with components1,x_0,x_1,x_2.
Parameters: - expression (
str) – The expression to parse. Seeexpressionfor the expression syntax. - variables (
dictofstrandnutils.function.Arraypairs) – Adictof variable names and array pairs. All variables used in theexpressionshould exist invariables. - functions (
dictofstrandintpairs) – Adictof function names and number of arguments pairs. All functions used in theexpressionshould exist infunctions. - indices (
str) – The indices used for aligning the resulting array. For example, letexpressionbe'a_ij'. Ifindicesis'ij', then the returned array is simplyvariables['a'], but ifindicesis'ji'the transpose ofvariables['a']is returned. All indices of theexpressionshould be listed precisely once. - arg_shapes (
dictofstrandtupleorints pairs) – Adictof argument names and shapes. Ifexpressioncontains an argument not present inarg_shapesthe shape will be decuded from the expression and added to a copy ofarg_shapes. - default_geometry_name (
str) – The name of the default geometry variable. When computing a gradient or the normal, e.g.'f_,i'or'n_i', this variable is used as the geometry, unless the geometry is explicitly mentioned in the expression. Default:'x'.
Returns: ast (
tuple) – The parsedexpressionas an abstract syntax tree (AST). The AST is atupleof an opcode and arguments. The special opcodeNoneindicates that the single argument is used verbatim. All other opcodes have AST as arguments. The following opcodes exist:(None, const) ('group', group) ('arg', name, *shape) ('substitute', array, arg, value) ('call', func, arg) ('eye', length) ('normal', geom) ('getitem', array, dim, index) ('trace', array, n1, n2) ('sum', array, axis) ('concatenate', *args) ('grad', array, geom) ('surfgrad', array, geom) ('derivative', func, target) ('append_axis', array, length) ('transpose', array, trans) ('jump', array) ('mean', array) ('neg', array) ('add', left, right) ('sub', left, right) ('mul', left, right) ('truediv', left, right) ('pow', left, right)
arg_shapes (
dictofstrandtupleofints pairs) – A copy ofarg_shapesupdated with shapes of arguments present in thisexpression.