UndefVarError: Distributions not defined

Hi,
I am very new to Julia but need it for numerical simulations for my master thesis.
I am using the Distributions package, since I have to sample from a von Mises Distribution with parameter \kappa.
Generally sampling from a von Mises distribution works, however in my code I have to do that within a function, since the parameter \kappa depends on other variables defined in the function’s scope.
Unfortunately I cannot get that to work, and I always get an “UndefVarError: Distributions not defined” error.
I assume there is some issue with the scope of variables, however I have no idea how to get the code to work.

Here is the function, where I want to sample from a von Mises distribution (var.n_label[i,j] is a boolean variable, defined in another function above this one):

function set_neighbour_orientation(param,var)
     for i=1:param.N
         tmpx = tmpy = 0.0
         for j=1:param.N 
             tmpx += var.n_label[i,j] * cos(var.θ[j])
             tmpy += var.n_label[i,j] * sin(var.θ[j]) 
         end
         avg_tmpx = tmpx/param.N 
         avg_tmpy = tmpy/param.N #(define the flux)
         J_i =(avg_tmpx, avg_tmpy)
         square = avg_tmpx * avg_tmpx + avg_tmpy * avg_tmpy
         κ = sqrt(square)
         vm = Distributions.VonMises(κ)
         var.ψ[i] = rand(vm)
     end
 end

At the risk of suggesting something trivial, have you checked that you’ve definitely run using Distributions before calling the function?

3 Likes

Yeah I am pretty sure of that. If I put something like

vm=VonMises()
v= rand(vm)
println(v)

anywhere else in the code, outside of a function, it prints some von Mises sample and throws the error after that.

Is your function part of a module?
Or: How do you run/define your function? Copy/Paste into REPL? include? using yourModule?

Yes it is part of a module and I define the functions within that module like that:

import .mod_vicsek_model:  
set_initial_condition,
set_neighbour_list,
set_neighbour_orientation,
set_white_noise,
set_new_θ,
set_new_r,
set_periodic_bc,
set_new_rθ

It’s very much possible that my mistake is somewhere in how I call modules/ functions, since I am not very accustomed to the julia syntax.

You need
using Distributions
inside your module, before importing the function:
e.g.:

module mod_vicsek_model
using Distributions
...
function set_neighbour_orientation(param,var)
         ...
         vm = VonMises(κ)
         ...
     end
 end
...
end

Than you can just call

VonMises()

without Distributions. at front.
(edited to fit more your given information)

https://docs.julialang.org/en/v1/manual/modules/

3 Likes

Thank you, this solved my issue!

2 Likes