Can Julia land on the Moon?

In recent years, we’ve been working on developing a simulation framework tailored to our needs at the European Space Agency, in the context of the Argonaut lunar lander programme.

The result is ATLAS (Argonaut Tools for Landing Analysis and Simulation), a closed-loop, high-fidelity guidance, navigation, and control simulation framework developed entirely in Julia.

Last month, we had the opportunity to present some of our experience transitioning from MATLAB/Simulink to Julia for closed-loop simulations at the ESA GNC & ICATT Conference.

We’re now sharing this work in a paper that we hope will be of interest to the Julia community, particularly those working in control systems, GNC, and aerospace applications.

For those interested, you can find the paper here:

My understanding is that this is not technically correct, although the “issue” described is real:

In Julia, most objects — especially arrays and other mutable structures — are passed by reference by default. This means that functions typically operate on the original data unless explicit steps are taken to create a copy

The Julia approach is sometimes referred to as “call by sharing”:

C++:

#include <iostream>
#include <vector>

// The ampersand (&) passes the vector by reference.
// Reassigning or modifying 'vec' will directly affect the original vector in main().
void modifyValue(std::vector<int> &vec) {
    vec = {42}; // Replaces the vector's contents with {42}
}

int main() {
    std::vector<int> original = {10};
    std::cout << "Before function call: " << original[0] << std::endl;
    modifyValue(original);
    std::cout << "After function call: " << original[0] << std::endl;
    return 0;
}

Julia:

# Call by sharing
function modifyValue(vec)
    vec = [42] # the local variable vec is binded to another object, "original" is unchanged
end

original = [10]
println("Before function call: $(original[1])")
modifyValue(original);
println("After function call: $(original[1])")

# ----
function modifyValue2(vec)
    vec[1] = 42 # the local variable that point to the same object is modified, "original" is hence also changed
end
modifyValue2(original);
println("After modifyValue2 function call: $(original[1])")
$ g++ test.cpp -o test
$ ./test
Before function call: 10
After function call: 42
$ julia test.jl
Before function call: 10
After function call: 10
After modifyValue2 function call: 42

Impressive work, thanks for the share!

The section 3.3 on the Kalman Filter implementation grabbed my attention. We reached similar conclusions by working on the same problem in parallel. I first implemented the same naive out-of-place version (MATLAB habits :laughing:) before transitioning to a similar optimized and in-place version, using rdiv! and cholesky!. Although my version is a bit longer, to support additional goodies like the extended version. But really, it’s reassuring that we converged towards a similar implementation in the end.

I was only starting to learn Julia when I optimized this part of the codebase, and I found this step was one of the steepest in the learning curve. So this part of your paper resonates a lot with my own experience:

In this sense, Julia does not eliminate the tension between ease of use and performance, but rather relocates it within the language itself. The user must still navigate a spectrum between readability and efficiency; however, this trade-off is managed through coding style rather than through a transition between different programming languages.

Yes, transitioning to fast in-place computations reduces readability a lot. I did not expected that, since Julia is considered a high-level language. This is obvious for the standard Kalman filter. It’s even worse for more complex estimators like the in-place version of the Unscented Kalman filter. It is still a huge win to keep everything in the same language nonetheless (better debugging experience, quick iterative development, easier code inspection, transparent codebase, etc.).

Thanks! It is a steep learning curve indeed.

We’re still discovering new ways to make our code more efficient by removing unnecessary allocations and ensuring type stability. The key for me is to understand at what point we are bending our GNC algorithm design “too much” just to exploit the capabilities of the language. This is a very important boundary that, for now, I’m not willing to cross :wink:

Very interesting, thanks for sharing!

Regarding Section 3.5, we run into similar issues with TTFX for these types of simulators. Did you end up just living with it, or did you find good workarounds for this?

Unfortunately TTFX is still the major issue we face every day when using Julia, and we have not found a good workaroud yet (we haven’t tried really hard honestly). I have to acknowledge that things are getting better with the latest Julia releases.

The good news is that TTFX has been steadily improving for a while.

One “trick” I would recommend is to organise your generic code into a Julia package proper - then that package and all its dependencies can be precompiled and cached. Even if your code needs to be recompiled, any heavy dependencies (DifferentialEquations.jl, plotting tools, etc) will load pretty much instantly.

You can then use Revise.jl to edit your package code live. In my own workflow, I have a neovim instance with a scratch file and a Julia REPL, then tab through files in the package to edit them. Revise reloads/recompiles these functions when they change without you having to touch anything. I keep Revise in my startup.jl file :slight_smile: .

I noticed there are also some tricks you can pull in your listed code. Julia has some very powerful metaprogramming and reflection tools. You can use these to e.g. query field names and look them up.

So e.g. this code:

@inline function logDke(t, x, dke::DKE)
    return (
        torque_B=copy(dke.torque_B),
        force_B=copy(dke.force_B),
        <...>
    )
end

can be turned into a generic one-liner (including the copy):

log_struct(p) = (; (v=>getfield(p, v) |> copy for v in fieldnames(typeof(p)))...)

So this code

@inline simLog(x, t, integrator) = (
    gncLog=logGnc(integrator.p.gnc),
    dkeLog=logDke(t, x, integrator.p.dke),
    senLog=logSen(integrator.p.sen),
    actLog=logAct(t, integrator.p.act),
)

could become

@inline simLog(x, t, integrator) = (
    x = x, t = t,
    gncLog = log_struct(integrator.p.gnc),
    dkeLog = log_struct(integrator.p.dke),
    senLog = log_struct(integrator.p.sen),
    actLog = log_struct(integrator.p.act),
)

(assuming you factor out any dependence on t and x in the original log calls).

This also means that if you change the fields of any structures, you don’t need to chase through your code to update all the logging functions :slight_smile: .

This discussion also discusses the use of generated functions (which lets you generate methods of functions specialised for particular types), which takes the cost of the call from microseconds to nanoseconds, if you’re into that kind of yak-shaving :slight_smile: .

Also, greetings from a fellow ECSS enjoyer! I’ve been meaning to put together a library to do PUS encoding/decoding for a while… hopefully will get to it next year!

Also regarding Section 3.3, does anyone have an intuition for why the Julia implementation of kalmanNaive is much slower (6-7x) than a “comparable” Matlab implementation (which the paper does not show but that I imagine being almost identical to the Julia one, except for the obvious syntactic translations). I understand that the naive Julia version is leaving a lot of potential optimizations on the table, but I imagine that a comparable Matlab version would as well.

function kalmanNaive(x, P, y, yEst, R, H)
    K = (P * H’) / (R + H * P * H’)
    x = x + K * (y - yEst)
    P = (I - K * H) * P
    return x, P
end

It looks like a very simple function that essentially does only a few linear algebra operations, so I would expect this difference between the two languages to be applicable in many scenarios.

Did you consider StaticArrays.jl? I didn’t see mention of it in the paper. It’s a small, fairly mature package at this point that can provide significant performance gains and without the readability compromises you encountered with your in-place implementations. It’s one limitation is it should only be used with relatively small arrays (approx. <100 elements), but for many astrodynamics problems that’s often not an issue. And when able, it is often trivial to apply…just have to be careful that downstream operations don’t inadvertently convert a static array back to a regular one.

Hi, nice to see people in ESA experimenting with newer tools. I’ve been developing similar software entirely in Julia for the past few years, and I’ve got some experience working with the mainstream simulators often used in ESA-related missions. I think section 3.7 in the paper pretty much sums it up. Almost everything you do is non-linear and sensitive to inevitable perturbations in the initial state. Running a simulation for hours to produce timeseries plots where you could be running multiple MC analyses is essential IMO. Plus, you can take it a step further and do sensitivity analysis, etc. I recall Dario Izzo and the ACT doing stuff like a differentiable SGP4 propagator proof of concepts back in the day. These things are trivial to do in Julia. Having one extra software engineer to join your team and help you squeeze out performance or simplify the codebase is absolutely free compared to having to deal with Simulink, or worse yet, things like SIMULUS. Even installing the toolchain can be complicated, let alone working with it to do anything useful. AFAIK there’s a lot of people in aerospace companies and NASA working with Julia (see (For what) is NASA using Julia? as an example).

As an aside, I think your simulation code is fast enough. Yes, you might be able to make it slightly faster by using generated functions here and there or using static arrays for pretty much everything (don’t forget the quaternions), if you aren’t already, but it will roughly be on the same order of magnitude. In my experience, what can help significantly more is building different “tiers” of the simulation: replacing computationally intensive models with simpler ones, without sacrificing much on the fidelity side. Then, you can build workflows where you use the cheap simulation for exploring the parameter/state space, iterating on the design, etc., and you use the high-fidelity version as a sanity check. If possible for your use-case, that’s probably a good way to unlock more performance.

I don’t know what the comparable Matlab implementation does either, but just passing static arrays to this implementation turns it allocation free. For small state you get a nice improvement. The second version in the paper with the preallocated state is quite slower. You can make it faster, but just using StaticArrays is still better unless the state is at about n = 35 on my machine. There’s other things in the second version that could be improved though

My guess is because MATLAB doesn’t support explicit in-place computation, they put a lot of money and energy into optimizing simple linear algebra computations like this. Maybe they try to be smart and skip some temporary allocations by fusing the operations when it’s possible and obvious. Hard to say with proprietary software. I know that MathWork put a LOT of effort into beating everyone else on linear algebra benchmarks, and impressively, they succeeded with a syntax that enforce pure functions only!

There is a similar issue when we compare the performance of dynamic dispatch between Python and Julia. Since Python doesn’t support compiled static dispatch like in Julia, dynamic dispatch is generally faster in Python as there are no other option available in the language.

where do you see this?

Also, this has been discussed many times here, but matlab uses bundles MKL with threads whereas julia not : julia code is serial (by default or use to be).

I often see allocation free serial julia code beating threaded matlab code.

And then, there is BLIS, LoopVectorization, etc…

Yeah I was referring to pure out-of-place linear algebra computations. For example, the naive Kalman filter here: Can Julia land on the Moon? - #8 by dmaioli

For the source, I will keep looking, but I’m not able to find a good reference that compare pure out-of-place operations e.g. using +, -, *, \ and /, without appending a . to the operators or using bang methods. Well there is the paper just above…

Gotta admit that it’s a claim I heard a lot from The MathWork themself, and they are certainly not a neutral and objective player in this game XD. The blog posts that I found do not provide the data to support their claim.

Now on why out-of-place if in-place is possible for any operations in Julia? For the readability of the syntax.

edit: found this paper that compares common linear algebra computations among MATLAB, Julia, Python and others. Julia seems to beats the others on most benchmarks but see e.g. Table 3 and B.1 in which MATLAB is a strong contender. The difference is not huge however, so @dmaioli raised a good point, a 6-7x difference for the naive Kalman filter is quite surprising.

Because:

  • out of place (OOP) can be faster than inplace (INP) sometimes (MVector vs SVector)
  • not all linear algebra is inplace, so then we need to combine these two worlds
  • I remember there were a macro for translating OOP to INP

I would say one of the best inpiration for how to write inplace/outplace code is SciML

  • in table 3 and B1: all high level language are roughly similar, like Numpy.

Id be curious about GPU, MPI, Multi-GPU, preconditioners, etc.

Thank you all for the many suggestions. We did try StaticArrays.jl, but we did not notice any significant speedup. Additionally, many of the “local” variables that would benefit from StaticArrays are often needed elsewhere as well, so the easiest solution for us was to store them as Vectors in our structures.

I think our next step is to try transitioning to GPUs, but I agree that what we have today is already fast enough for “classic” GNC purposes.

Perhaps you can open-source some of the more fundamental computational parts so others can have a look and provide feedback?