analyze_expr {lazy.symbolic}R Documentation

Decompose an Expression into Additive Terms and Multiplicative Factors

Description

Decompose an Expression into Additive Terms and Multiplicative Factors

Usage

analyze_expr(expr, sort = 0, print = 0, debug = 0)

Arguments

expr

An input expression

sort

= 1 to sort the result by variable name

print

= 0 not to print the result

debug

= 1 to print useful info

Details

The result of the analysis is stored in a character matrix named tab.
If the input expression is
"-inv(A)+(B+C)+D%*%E+F%*%(G-(H)-(I)+J)"
it will be decomposed into the terms and factoers in the matrix show below:

       topers   o1  factor_1    o2     factor_2
  -----------------------------------------------------
  term_1    -       inv(A)
  term_2    +       (B+C)
  term_3    +       D           %*%    E
  term_4    +       F           %*%    (G-(H)-(I)+J)


Each row of the tab matrix corresponds to a term in expr and each term is decomposed into factors and operators.

topers and o1 are the operators to be attached to factor1.
(o1 may be an empty string vector as shown in the example above.)
o2 is the operator to be attached to factor2, etc.

topers and o1 are additive operators, + or -, and op2, op3,..., are multiplicative operators, *, %*%, etc.

From this, the original expression can be recovered as:
paste( apply(tab,1, function(x){paste(x,collapse="")} ), collapse="")

Value

A list of tab and ok.

Examples

analyze_expr( "-inv(A)+(B+C)+D%*%E+F%*%(G-(H)-(I)+J)" )
analyze_expr( "-inv(A)+(B+C)+D%*%E+F%*%(G-(H)-(I)+J)", sort=1 )

# scalar expression
set.seed(1701)

nexpr=20
for( i in 1:nexpr ){

 # generate expression
 natom=10
 expr=gen_random_expr( natom=natom, nparen=4, oper=c("*","+","-") )
 if( runif(1) < 0.2 ) expr=sub( "a", "F(a)", expr )
 if( runif(1) < 0.3 ) expr=sub( "d", "F1(d)", expr )
 if( runif(1) < 0.2 ) expr=sub( letters[natom], "Ff2(x)", expr )

 # analyze expression
 res=analyze_expr( expr, print=1 )

}


# matrix expression
set.seed(1701)

nexpr=20
for( i in 1:nexpr ){

  # generate expression
  natom=10
  expr=gen_random_expr( natom=natom, nparen=4
                        , alpha=LETTERS[1:natom], oper=c("%*%","+","-") )
  if( runif(1) < 0.3 ) expr=sub( "A", "inv(A)", expr )
  if( runif(1) < 0.3 ) expr=sub( "C", "diag(C)", expr )
  if( runif(1) < 0.3 ) expr=sub( LETTERS[natom], "ginv(X)", expr )

  # analyze expression
  res=analyze_expr( expr, print=1 )

}


[Package lazy.symbolic version 0.1.4 ]