I have a piece of code involving a large matrix. I have been trying to optimise it. I have exhausted all my options, I would like to know of suggestions that experts on this forum might have.
using Distributions
using StatsBase
using LightGraphs
using LinearAlgebra
mutable struct Par
g::SimpleDiGraph{Int64} ;
μ::Int64 ;
n::Int64 ;
P::Int64 ;
ctime::Int64 ;
cstub::Float64 ;
crate::Int64 ;
cvalue::Float64 ;
expcval::Float64 ;
temp::Bool ;
end
mutable struct Arr
θ::Array{Float64,1} ;
C::Array{Float64,1} ;
wts::Array{Float64,1} ;
upagents::Array{Int64,1} ;
edg::Array{Int64,1} ;
cedg::Array{Int64,1} ;
temp::Array{Float64,1} ;
end
mutable struct Mat
θₜ::Array{Float64,2} ;
end
function main(Cmin::Float64,Cmax::Float64,N::Int64,outdeg::Int64,Pᵣ::Float64,σ::Int64,Pᵢ::Float64)
p = Par(SimpleDiGraph(Int64),90,5000,Int64(N/2),0,0.0,0,0.0,0.0,false) ;
a = Arr(Float64[],Float64[],Float64[],Int64[],Int64[],Int64[],Float64[]) ;
m = Mat(Matrix{Float64}(undef,N,p.n)) ;
p.g = watts_strogatz(N,outdeg,Pᵣ,is_directed=true) ;
a.θ = rand(Normal(p.μ,σ),N)*pi/180 ;
a.C = rand(Uniform(Cmin,Cmax),N) ;
a.wts = 1.0 .- a.C ;
a.wts = a.wts/sum(a.wts) ;
for t = 1:1:p.n
m.θₜ[:,t] = a.θ ;
a.upagents = sample([1:1:N;],Weights(a.wts),p.P,replace=false) ;
for i ∈ a.upagents
a.edg = inneighbors(p.g,i) ;
a.cedg = setdiff([1:1:N;],a.edg) ;
a.cedg = setdiff(vcat(a.edg,a.cedg[rand(length(a.cedg)).<Pᵢ]),i) ;
a.temp = exp.(-abs.(m.θₜ[i,t] .-m.θₜ[a.cedg,t])/(1.0-a.C[i])) ;
a.temp = vcat(a.C[i],(a.temp*(1-a.C[i]))/sum(a.temp)) ;
a.cedg = vcat(i,a.cedg) ;
a.θ[i] = atan(sum(a.temp.*sin.(m.θₜ[a.cedg,t])),sum(a.temp.*cos.(m.θₜ[a.cedg,t]))) ;
end
a.temp = round.(a.θ,digits=2) ;
p.temp = all(y->y.==a.temp[1],a.temp) ;
if(p.temp==true)
p.ctime = t ;
p.crate = 1 ;
p.cvalue = a.θ[1] ;
p.expcval = round(sum(a.C.*m.θₜ[:,1])/sum(a.C),digits=2) ;
p.cstub = mean(a.C) ;
break
end
end
return p.ctime,p.crate,p.cvalue,p.expcval,p.cstub
end
For Cmin=0.5;Cmax=0.9;N=1000;outdeg=250;Pᵣ=0.0;σ=10;Pᵢ=0.5;
, I get
@time main(Cmin,Cmax,N,outdeg,Pᵣ,σ,Pᵢ)
32.085691 seconds (20.75 M allocations: 25.131 GiB, 15.87% gc time)
(316, 1, 1.5760757023650616, 1.57, 0.6931634326318095)