+2 votes
asked by (240 points)
edited by

Forgive me if I'm missing something obvious, but is there a simple way to iterate over all non-zero elements of an ITensor?

Something like:

ITensor T = ITensor(...);
for (std::vector< IndexVal > ivals : T) {
    ...
}

This would get me the set of IndexVal addressing all elements of the tensor in no particular order, just like that output we get when we use PrintData(T). This would be useful to study the structure and sparsity of the tensor, or do some manual element-wise operations.

I know of ITensor::visit(), but it doesn't seem to be possible to get the actual IndexVal out of that, just the value of the element.

1 Answer

+2 votes
answered by (70.1k points)
selected by
 
Best answer

Good suggestion, thanks. I think this is a feature we should definitely have, so I just added it! (You'll have to pull the latest version of ITensor to get it.)

What I added is a function called iterInds which you in a range-based for loop, which gives the behavior you asked about.

Here is a sample code using it:

auto i = Index("i",2);
auto j = Index("j",3);
auto k = Index("k",4);

auto is = IndexSet(i,j,k);

auto T = randomTensor(i,j,k);

for(auto it : iterInds(T))
    {
    Print(it[0]);
    Print(it[1]);
    Print(it[2]);
    Print(T.real(it));
    println();
    }

PrintData(T);
commented by (240 points)
Perfect! It's working like a charm. This will be super helpful.

Thank you so much for the speedy update! :)
Welcome to ITensor Support Q&A, where you can ask questions and receive answers from other members of the community.

Formatting Tips:
  • To format code, indent by four spaces
  • To format inline LaTeX, surround it by @@ on both sides
  • To format LaTeX on its own line, surround it by $$ above and below
  • For LaTeX, it may be necessary to backslash-escape underscore characters to obtain proper formatting. So for example writing \sum\_i to represent a sum over i.
If you cannot register due to firewall issues (e.g. you cannot see the capcha box) please email Miles Stoudenmire to ask for an account.

To report ITensor bugs, please use the issue tracker.

Categories

...