Julia相对路径和导入自定义模块

时间:2020-09-07 02:20:26

标签: julia

我是Julia的新手。 我真的对使用自定义模块感到困惑。 注意:我是通过vim而不是Juno工作的。

例如,这是我的目录树(请忽略tmp.txt)。

.
├── algorithm
│   └── controller.jl
├── debug.jl
├── main.jl
├── model
│   └── aerospace_systems.jl
└── tmp.txt

2 directories, 5 files

我通常在main.jl中编写主要功能,并从其他目录(例如algorithmmodel)导入(使用)模块。

就我而言,有一些烦人的问题:

  1. 如果我想在Controller的{​​{1}}中使用模块algorithm/controller.jl(假设存在),则似乎我必须在{{1}中添加model/aerospace_system.jl }甚至我都在include("../algorithm/controller.jl")中执行函数。
  2. 将模块model/aerospace_system.jl导入为 main.jl中的Controller, 我无法直接使用包含的函数,例如include("../algorithm/controller.jl"); using .Controller中的model/aerospace_system.jl。 在这种情况下,我在Julia REPL中运行命令,如下所示:
nocontrol

所以我的问题是... Q1)如何解决以上问题? Q2)有什么方法可以避免这种相对混乱的相对路径? (是否可以确定与代码位置无关的路径?)

以下是与此问题相关的简短代码,希望对您有所帮助:

  1. Controller
julia> includet("main.jl")  # using Revise
julia> run_main()
ERROR: UndefVarError: nocontrol not defined
...
  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

0 个答案:

没有答案