I am a beginner Julia user and am having a hard time developing a model because it takes a very long time to initialize certain arrays. I tried using
BenchmarkTools.jl to get an accurate time but it generated an iterate error that I cannot replicate. Anyway, I think the time with a smaller sample size (
NumTotalSpecies) used for testing takes too long. Could I have some suggestions for my code?
time_FoodWeb = @time create_FoodWeb(BM, Ropt,γ) 82.159197 seconds (155.09 M allocations: 76.550 GiB, 12.35% gc time) 161.635944 seconds (383.93 M allocations: 195.124 GiB, 12.91% gc time) 51.302236 seconds (125.56 M allocations: 63.508 GiB, 14.34% gc time)
using Distributions, Random const D = 0.25 const Ropt = 100 const γ= 2 const q = rand(Normal(0.5,0.2)) #Hill exponent, μ = 0.5, σ = 0.2 #const = #was a constant but removed to allow testing NumPlantSpecies = 8 #const NumAnimalSpecies = 12 #const NumTotalSpecies = NumPlantSpecies + NumAnimalSpecies #const BM_P = sort(rand(Uniform(10^0, 10^6), NumPlantSpecies)) #body mass of Plant species #const BM_A = sort(rand(Uniform(10^2, 10^12), NumAnimalSpecies)) #body mass of Animal species #const BM = vcat(BM_P,BM_A) #placing BM_P and BM_A together under BM as mass of all species #const function create_FoodWeb(BM,Ropt,γ) function create_L(BM,Ropt,γ) L = @. ((BM/(BM'*Ropt))' * exp(1-(BM/(BM'*Ropt))'))^γ # Weak links (Lij <p) are removed L[:,1:NumPlantSpecies] .= 0.0 L[L .<= 0.01] .= 0.0 return(L) end condition = true while condition BM_P = sort(rand(Uniform(10^0, 10^6), NumPlantSpecies)) BM_A = sort(rand(Uniform(10^2, 10^12), NumAnimalSpecies)) BM = vcat(BM_P,BM_A) global L = create_L(BM,Ropt,γ) #take the link probabilities of the previous matrix and determine if L[i,j] > p global FoodWeb = zero(L) FoodWeb[:,1:NumPlantSpecies] .= 0.0 # keeps plants as basal species FoodWeb[L .> rand.(Uniform(0, 1))] .= 1.0 # Sets F[i,j] = 0 wherever L[i,j] < F[i,j] condition = any(sum(x->x>0, FoodWeb, dims=1) + sum(x->x>0, FoodWeb, dims=2)' .== 0.0) #dims=(1) for column, dims=(2) for row end return(BM, L, FoodWeb) end
Here I wanted to use
permutedims instead of
BM is an array but this leads to an error.
L = @. ((BM/(BM'*Ropt))' * exp(1-(BM/(BM'*Ropt))'))^γ
ERROR: MethodError: no method matching permutedims(::Float64)