# How will I get the number of terms in an object in Cadabra 2?

e.g ,

Ex:={1}^R_{\mu \nu};

Here {1}^R_{\mu \nu} is perturbed Ricci Tensor

I have tried things like :

number_of_terms(Ex);

Cadabra 2 is showing syntax error.

+1 vote

First of all, you cannot use Ex (with a capital E) as a name for an expression, because Ex is the name of the Cadabra expression object. Secondly, you cannot add pre-fix superscripts like this; the best you can do there is to use the LaTeXForm property. So you can do

R1{#}::LaTeXForm("{}^{1}R").
ex:= R1_{\mu\nu};

Now what do you wan to do next? This expression clearly only contains one term. Did you want to compute it for a particular metric and then determine the number of non-zero components?

by (66.3k points)

I am not sure if there is any algorithm called "number_of_terms" in Cadabra2. Is it? It was in CADABRA1 where it was applied using @number_of_terms. Perhaps the question was about how to get the number of terms in an expression that is sum of many terms.

Counting number of child elements is done with Python's standard len, so

ex:=A+B+C+D+E;
len(ex);

gives 5.

But note that this may not do what you want when you have single terms with indices, as it always counts the number of children, and when there is only a single term there is no \sum node at the top. So you get

ex:= A_{m n p q};
len(ex);

giving 4. I should probably re-instate number_of_terms to make this easier to catch...