I'm new to Julia.
I'm really confused with using custom modules.
Note: I'm working via vim, not Juno.
For example, this is my directory tree (please ignore the tmp.txt).
.
├── algorithm
│ └── controller.jl
├── debug.jl
├── main.jl
├── model
│ └── aerospace_systems.jl
└── tmp.txt
2 directories, 5 files
I usually write main functions in main.jl and import (using) modules from other directories, e.g., algorithm and model.
In my case, there are a few annoying problems:
- If I want to use module
Controllerinalgorithm/controller.jl(suppose there exists) atmodel/aerospace_system.jl, then it seems that I have to addinclude("../algorithm/controller.jl")inmodel/aerospace_system.jleven I execute functions inmain.jl. - After import the module
Controllerasinclude("../algorithm/controller.jl"); using .Controllerinmodel/aerospace_system.jl, I cannot directly use a contained functions, e.g.,nocontrolinController. In this case, I run commands in Julia REPL as follows:
julia> includet("main.jl") # using Revise
julia> run_main()
ERROR: UndefVarError: nocontrol not defined
...
So my questions are... Q1) How to resolve the above issue? Q2) Is there any way to avoid such confusing relative paths? (can fix a path independent of codes' location?)
Here are brief codes related to the issue, hope it would be helpful:
main.jl
includet("model/aerospace_systems.jl")
using DynamicalSystems
using .AerospaceSystems
using Plots
ENV["GKSwstype"]="nul" # do not show figures automatically
function simulate_linear(x0; T=10., dt=0.01)
system = linearsystem(x0=x0)
traj = trajectory(system, T, dt=dt)
ts = 0:dt:T
return ts, traj
end
function draw_plot(ts, traj)
p = plot(ts, traj,
xlabel="t (s)", label=["x1" "x2" "x3"], linewidth=1.5)
save_path = "data/plot.pdf"
save_dir = dirname(save_path)
if !isdir(save_dir)
mkdir(save_dir)
end
savefig(p, save_path)
end
function run_main()
## main
x0 = 10*ones(3)
ts, traj = simulate_linear(x0)
## plot
draw_plot(ts, traj)
end
model/aerospace_systems.jl
module AerospaceSystems
export linearsystem
using Debugger
using StaticArrays
using DynamicalSystems
const CDS = ContinuousDynamicalSystem
include("../algorithm/controller.jl")
import .Controller
function linearsystem(;x0=zeros(3), controller=nocontrol)
lineardynamics_with_controller(x, p, t) = lineardynamics(x, p, t; controller=controller)
return CDS(lineardynamics_with_controller, x0, nothing)
end
algorithm/controller.jl
module Controller
export nocontrol, negativelinearfeedback
using LinearAlgebra
function nocontrol(x, t; dim=1)
return zeros(dim, 1)
end
function negativelinearfeedback(x, t; K=I)
return -K*x
end
end