Hi,
I’m implementing a Monte Carlo algorithm in which the Markov chain state is defined by a site index (in two dimensions to be more concrete). The site index performs a random walk according to some given rules. The current and suggested states types are, as far as I understand, NTuple{2,Int64}.
The code is quite involved but I believe I have managed to isolate the “problematic” section, see below. Basically, “hop” generates the site index of the next state and “jump” rejects or accepts.
function hop(index::NTuple{2,Int64},input_leg::Int64,output_leg::Int64,L::Int64,M::Int64)
if input_leg==1
if output_leg==2
(index[1]==L ? 1 :index[1]+1,index[2])
elseif output_leg==3
(index[1],index[2]==2*M ? 1 : index[2]+1)
else # output_leg==4
(index[1]==L ? 1 :index[1]+1,index[2]==2*M ? 1 : index[2]+1)
end
elseif input_leg==2
if output_leg==1
(index[1]==1 ? L :index[1]-1,index[2])
elseif output_leg==3
(index[1]==1 ? L :index[1]-1,index[2]==2*M ? 1 : index[2]+1)
else # output_leg==4
(index[1],index[2]==2*M ? 1 : index[2]+1)
end
elseif input_leg==3
if output_leg==1
(index[1],index[2]==1 ? 2*M : index[2]-1)
elseif output_leg==2
(index[1]==L ? 1 :index[1]+1,index[2]==1 ? 2*M : index[2]-1)
else # output_leg==4
(index[1]==L ? 1 :index[1]+1,index[2])
end
else # input_leg==4
if output_leg==1
(index[1]==1 ? L :index[1]-1,index[2]==1 ? 2*M : index[2]-1)
elseif output_leg==2
(index[1],index[2]==1 ? 2*M : index[2]-1)
else # output_leg==3
(index[1]==1 ? L :index[1]-1,index[2])
end
end
end
function jump()
index=(5,6)
i=0
while i<100000
nn=hop(index,rand(1:4),rand(1:4),4,6)
if rand()<0.5
index=nn
end
i+=1
end
end
jump()
It seems like a lot of memory is being allocated (see below a julia run using --track-allocation=user)
- function jump()
- index=(5,6)
724746 i=0
0 while i<100000
0 nn=hop(index,rand(1:4),rand(1:4),4,6)
0 if rand()<0.5
0 index=nn
- end
0 i+=1
- end
- end
-
- jump()
I’m pretty sure that the allocation report doesn’t correctly indicate the line in which memory allocation occurs. My best bet is that “nn” is being allocated at each step. Is that expected? If so, how to avoid this?
Thanks!
Snir