Ferrite.jl icon indicating copy to clipboard operation
Ferrite.jl copied to clipboard

CellIterator not broadcast safe

Open sebastianpech opened this issue 6 years ago • 6 comments

I haven't looked into the details of that issue (Opened it as a reminder) and tbh I don't know much about the inner workings of broadcast and materialize. As the current id is mutated in the CellIterator the first example only picks up the last id. Any ideas if there's a possible fix for that?

Wrong

julia> cellid.(CellIterator(dh))
22754-element Array{Int64,1}:
 22754
 22754
 22754
 22754
 22754
 22754
     ⋮
 22754
 22754
 22754
 22754
 22754

Correct

julia> map(CellIterator(dh)) do cell
           cellid(cell)
       end
22754-element Array{Int64,1}:
     1
     2
     3
     4
     5
     6
     ⋮
 22750
 22751
 22752
 22753
 22754

sebastianpech avatar Dec 03 '19 15:12 sebastianpech

julia> struct Iter
           max::Int
           x::Base.RefValue{Int}
           Iter(x) = new(x, Ref(1))
       end
       Base.length(iter::Iter) = iter.max
       function Base.iterate(iter::Iter, state=1)
           iter.x[] = state
           if state > iter.max
               return nothing
           else
               return iter, state+1
           end
       end
       get_x(iter::Iter) = iter.x[];

julia> iter = Iter(5);

julia> get_x.(iter)
5-element Array{Int64,1}:
 6
 6
 6
 6
 6

so looks like broadcasting is not iterating somehow?

fredrikekre avatar Dec 09 '19 13:12 fredrikekre

Isn't the problem that there is ever only one Iter object in the array (they all refer to the same object) so iter.x will always be the same thing.

KristofferC avatar Dec 09 '19 13:12 KristofferC

But we extract the immutable Int at each iteration?

fredrikekre avatar Dec 09 '19 13:12 fredrikekre

E.g. this works:

julia> collect(get_x(y) for y in iter)
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

fredrikekre avatar Dec 09 '19 13:12 fredrikekre

I guess this happens because broadcasting is lazy and iterates through once before actually calling get_x.

fredrikekre avatar Dec 09 '19 13:12 fredrikekre

Oh, I misread the example completely.

KristofferC avatar Dec 09 '19 13:12 KristofferC