Julia relative path and importing custom modules

Viewed 200

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:

  1. If I want to use module Controller in algorithm/controller.jl (suppose there exists) at model/aerospace_system.jl, then it seems that I have to add include("../algorithm/controller.jl") in model/aerospace_system.jl even I execute functions in main.jl.
  2. After import the module Controller as include("../algorithm/controller.jl"); using .Controller in model/aerospace_system.jl, I cannot directly use a contained functions, e.g., nocontrol in Controller. 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:

  1. 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
  1. 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
  1. 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
0 Answers
Related