Tag Archives: Julia

Julia 1.11: Top Features and Important Updates

By: Steven Whitaker

Re-posted from: https://blog.glcs.io/julia-1-11

A new version of the Julia programming languagewas just released!Version 1.11 is now the latest stable version of Julia.

This release is a minor release,meaning it includes language enhancementsand bug fixesbut should also be fully compatiblewith code written in previous Julia versions(from version 1.0 and onward).

In this post,we will check out some of the features and improvementsintroduced in this newest Julia version.Read the full post,or click on the links belowto jump to the features that interest you.

If you are new to Julia(or just need a refresher),feel free to check out our Julia tutorial series,beginning with how to install Julia and VS Code.

Improved Clarity of Public API with public Keyword

An important aspect of semantic versioning(aka SemVer, which Julia and Julia packages follow)is the public API users have access to.In essence,SemVer states that minor package updatesshould not break compatibilitywith existing code that uses the public API.However,other parts of the code are free to changein a minor update.To illustrate:

  • If I have sum([1, 2, 3]) in my codethat I wrote in Julia 1.10,it will continue to return 6 in Julia 1.11because sum is part of Julia’s public API.But it could break in Julia 2.0.(Hopefully not, though!)
  • If I have SomePackage._internal_function(0) in my codethat I wrote with SomePackage v1.2.0,it might error when SomePackage upgrades to v1.2.1(because, for example, _internal_function got deleted).Such a change would be allowedbecause _internal_function is not part of the public API.

So, the question is,how does a user knowwhat the public API of a package is?Historically,there have been some conventions followed:

  • Names that are exported(e.g., export DataFrame)are part of the public API.
  • Unexported names that are prefixed with an underscore(e.g., SomePackage._internal_function)are not part of the public API.

But what about a function like ForwardDiff.gradient?That function is the reason why 99%of users load the ForwardDiff package,but it’s not exported!The good news is that it’s still part of the public APIbecause, well, ForwardDiff’s maintainers say so.Or maybe it’s because the documentation says so.Or maybe it’s because enough people use it?Sometimes it’s not entirely clear.

But now in Julia 1.11,your the code can indicatethe public API!This is thanks to a new public keyword.Now,all symbols that are documented with publicare part of the public API.(Note that this is in addition to exported symbols,i.e., func would be considered public APIwith either export func or public func.)

Usage of public is the same as export.For example:

module MyPackagepublic add1"""Docstring for a public function."""add1(x) = x + 1"""Docstring for a private function."""private_add1(x) = x + 1end

With using MyPackage,no symbols are made available (except MyPackage),e.g., add1 can only be called via MyPackage.add1,because nothing is exported with export.And both MyPackage.add1(1) and MyPackage.private_add1(1) work,even though add1 is public and private_add1 is private.So,the public keyword doesn’t change how MyPackage works or is used.

However,the public keyword does change some behaviors.The most notable difference iswhen displaying documentation in the REPL’s help mode:

help?> MyPackage.add1  Docstring for a public function.help?> MyPackage.private_add1   Warning      The following bindings may be internal; they may change or be removed in future versions:          MyPackage.private_add1  Docstring for a private function.

See the warning with private_add1?Such warnings,in addition to the more straightforward documentation of the public API,may help reduce usage of package internals(particularly accidental usage),which in turn may help improvethe stability of Julia packages.

To summarize,even though the public keyworddoesn’t change how a package works or is used,it does provide a mechanism for clearly stating the public APIand providing warnings when viewing the documentationfor internal functions.This, in turn,may improve the stability of Julia packagesas they adhere more closelyto public APIs.

Read more about public in the Julia manual.

Standardized Entry Point for Scripts

There is now a standardized entry pointwhen running scripts from the command line.

Julia 1.11 introduces the @main macro.This macro, when placed in a script,and when the script is run via the command line,tells Julia to run a function called mainafter running the code in the script.main will be passed a Vector of Stringscontaining the command line arguments passed to the script.

To use @main,just include it in your scripton its own lineafter defining your main function.(If @main occurs before defining main,for example at the top of the script,an error will be thrown,so the ordering matters.)

Of course,for this to workthere has to be a function mainwith a method that takes a Vector{String} as the only input.

Let’s look at an exampleto illustrate how this works.Say we have the following in test.jl:

print_val(x) = print(x)function main(args)    print_val(args)end@main

If we run this file in the REPLwith include("test.jl"),the functions print_val and mainwill be defined,but main will not get called.This is the same behavioras when @main is not present.

On the other hand,if we run this file via the command linewith julia test.jl,the functions print_val and mainwill be definedand then main will be calledwith the command line argumentsas the input.To illustrate:

  • julia test.jl will call main(String[])(because no command line arguments were passed).
  • julia test.jl 1 hello will call main(["1", "hello"]).

As a result of @main,a Julia file can have different behaviordepending on whether it is run as a script or not.

If you’re familiar with Python,@main might remind you ofif __name__ == "__main__".However,there is one significant difference:

  • In Python,if script1.py imports script2.pyand script2.py has the “if main” check,running script1.py as a scriptwill not run script2.py‘s “if main” code.
  • In Julia,if script1.jl includes script2.jland script2.jl uses @main,running script1.jl as a scriptwill run script2.jl‘s main function.(Technicality:Unless script1.jl defines an appropriate main method,in which case script1.jl‘s main would be called,even if script1.jl did not include @main.)

This isn’t to say Julia’s @main is bad or wrong;it’s just important to know that it works differentlythan Python.And it’s still cool to have a standardized entry pointfor Julia scripts now!

Read more about @main in the Julia manual.

Improved String Styling

Julia 1.11 introduces a new StyledStrings.jlstandard library package.This package provides a convenient wayto add styling to strings.StyledStrings makes printing styled stringsmuch easier than calling printstyled,particularly when different parts of the stringhave different styles.

The easiest way to create a styled stringis with styled"...".For example:

using StyledStringsstyled_string = styled"{italic:This} is a {bold,bright_cyan:styled string}!"

Then, when printing the styled string,it will display according to the provided annotations.

Also, because the style information is stored with the string,it can easily be preserved across string manipulationssuch as string concatenation or grabbing a substring.

Check out the documentationfor more informationabout the variety of different annotationsStyledStrings supports.

And here’s some more informationfrom the State of Julia talk at JuliaCon 2024:

Slide about StyledStrings

New Functions for Testing Existence of Documentation

Julia 1.11 makes it easyto determine programmatically whether a function has a docstring.This can be useful for, e.g., CI checksto ensure a package is well documented.

There are two functions for this purpose.The first is Docs.hasdoc,which is used to query a particular function.hasdoc takes two inputs:the module to look inand the name (as a Symbol) of the function.For example:

julia> Docs.hasdoc(Base, :sum)true

The other function providedis Docs.undocumented_names,which returns a list of a module’s public namesthat have no docstrings.(Note that public names include symbols exported via exportas well as symbols declared as public via public.)For example:

julia> module Example       export f1, f4       public f2, f5       "Exported, documented"       f1() = 1       "Public, documented"       f2() = 2       "Internal, documented"       f3() = 3       # Exported, undocumented       f4() = 4       # Public, undocumented       f5() = 5       # Internal, undocumented       f6() = 6       endMain.Example# Note that `f6` is not returned because it is neither exported nor public.julia> Docs.undocumented_names(Example)3-element Vector{Symbol}: :Example :f4 :f5

It will be interesting to see what tooling arisesto take advantage of these functions.

More Complete timed Macro

The @timed macroprovides more complete timing informationin Julia 1.11.

Previously,@timed gave run time and allocation/garbage collection information,but nothing about compilation time.Now, compilation time is included.

But why care about @timedwhen @time already gave all that info?Because @time is hard-coded to print to stdout,meaning there’s no way to capture the information,e.g., for logging purposes.

I actually had a project where I wanted to redirect the output of @timeto a log file.I couldn’t just use redirect_stdiobecause that would also redirect the outputof the code being timed.I ended up using @timed along with Base.time_printto create the log statements,but I was disappointed @timed didn’t give me compilation time information.Well, now it does!

New Convenience Function logrange

Pop quiz:Which of the followingis the correct wayto create a logarithmically spaced range of numbers?

  1. log.(range(exp(a), exp(b), N))
  2. exp.(range(log(a), log(b), N))

I have occasionally neededto use logarithmically spaced ranges of numbers,not so frequently that I memorized which expression to use,but frequently enough that I developed a real distastefor the mental gymnastics I had to go throughevery time just to rememberwhere to put the exps and logs.Maybe I should have just taken some timeto memorize the answer…

But now it doesn’t matter!The correct answer is neither 1 nor 2,but logrange(a, b, N)!Here’s an example usage:

julia> logrange(1, 10, 5)5-element Base.LogRange{Float64, Base.TwicePrecision{Float64}}: 1.0, 1.77828, 3.16228, 5.62341, 10.0

I know it’s a fairly minor change,but the addition of logrange in Julia 1.11is probably the change I’m most excited about.There was much rejoicing when I saw the news!

Summary

In this post,we learned aboutsome of the new featuresand improvementsintroduced in Julia 1.11.Curious readers cancheck out the release notesfor the full list of changes.

Note also that with the new release,Julia 1.10 will now become the LTS (long-term support) version,replacing Julia 1.6.As a result,Julia 1.10 will receive maintenance updatesinstead of Julia 1.6(which has now reached end of support)until the next LTS version is announced.If you want to learn more about what changes Julia 1.10 brought,check out our post!

What are you most excited aboutin Julia 1.11?Let us know in the comments below!

Additional Links

]]>

Maximizing Julia Development with VSCode Extension

By: Justyn Nissly

Re-posted from: https://blog.glcs.io/julia-vs-code-extension

In this article, we will review some of the features that the Julia extension offers! If you don’t have Julia, VS Code, or the Julia extension already installed, look at this article to help you get set up!

Running a Julia File

Now that we have the extension installed and configured, we can start using the extension.One of the first things we will examine is the most basic feature – running code!To run code, we do the following:

  1. Click the drop down in the top right of the code window
  2. Click “Julia: Execute Code in REPL”
  3. Enjoy the results!

When you hit Ctrl+Enter, the line your cursor is currently on will run, and the cursor will advance to the next line.This is one way to step through the code line by line.

You are also able to use Ctrl+F5 (Option+F5 for Macs) to run the entire file. You can learn more about running Julia code from the official documentation.

Code Navigation

The information in this section applies to any language and is not exclusive to the Julia extension. The features below are helpful to know and can increase your productivity as you code.

Within VS Code, if you use Ctrl+P, a prompt will open at the top of your editor. In that prompt, you can start typing the name of a file you want to jump to in your project. Once you click the option (or press enter), VS Code will jump directly to that file. You can also use Ctrl+G to jump to a specific line number in the file if you know which line you are looking for. Being able to jump back and forth between files without having to search the file tree will greatly enhance your workflow. Imagine all the time you will save by not searching through file trees!

Using Ctrl+Shift+O (be sure to use the letter O, not the number 0) will allow you to navigate through individual symbols within your program. After using the shortcut above, type : and all your symbols will be grouped by type. You are then able to navigate between them all.

Editing Code

Code navigation is a great skill to develop, especially when given some wonderful legacy code to unravel…we’ve all been there. Being proficient in navigating your code does you no good unless you are also proficient at editing the code.

One way to get going quickly is to use the “rename symbol” shortcut. You can either right click on a symbol and press “rename” or hit F2. When you rename the symbol, it will be renamed everywhere else in the file that it exists. Pretty neat, huh?

Change_Symbol

The Plot Viewer

Up until this point in the article we have laid the ground work for working with your code in VS Code. Next, we will look into some of the Julia specific features that the Julia extension offers, starting with the plot viewer.

The plot viewer is a really handy tool that lets you…well…view plots. We can look at an example to see how it works.

First, we will install the plots package if it hasn’t been installed already.

julia> using Pkgjulia> Pkg.add("Plots")# OR# We can type the "]" key and use the package interface(@v1.10) pkg>(@v1.10) pkg> add Plots

After we do that, we can create a plot to visualize.

using Plotsfunction make_plot()    # Create a plot    p = plot()     = range(0, 2, length=100)    x = cos.() * 5    y = sin.() * 5    plot!(p, x, y, linecolor=:black, linewidth=2, legend=:topright)    x_left = 1 .+ 0.5 * cos.()    y_left = 2 .+ 0.5 * sin.()    plot!(p, x_left, y_left, linecolor=:black, linewidth=2, fillalpha=0.2)    x_right = 3 .+ 0.5 * cos.()    y_right = 2 .+ 0.5 * sin.()    plot!(p, x_right, y_right, linecolor=:black, linewidth=2, fillalpha=0.2)    _arc = range(0, , length=10)    x_arc = 2 .+ cos.(_arc) * 2    y_arc = -1 .+ sin.(_arc) * 1    plot!(p, x_arc, y_arc, linecolor=:black, linewidth=2)    # Adjust plot limits and display the final plot    xlims!(-6, 6)    ylims!(-6, 6)    display(p)end# Execute the function to plotmake_plot()

Next we run this by using the keyboard shortcut we learned earlier (Ctrl+Enter), and we can see the result below!

Make_Plot

Pretty cool! Now we can see our charts generated in real time right inside our editor!

The Table Viewer

I don’t know about you, but I never liked having to try and dump the contents of an array, matrix,or other data structures to the console and try and parse through the data. Lucky for us we don’t have to do that.The Julia extension allows us to view any Tables.jl compatible table in the special table viewer.There are two ways to do this.

The first way is by clicking the “View in VS Code” button next to your table in the “Workspace” section.

Table_View_Button

The second way to do this is by running the vscodedisplay(name_of_table) directly in the REPL.

It’s pretty cool if you ask me.Having the ability to view the data is a nice feature, but to make it even better, you can sort the data in the UI by clicking the column headers. You can also copy data by using Ctrl + C just like you would in Excel!

A word of caution: All the table data you see is cached so any changes you make will not be reflected in the table viewer. To fix that just re-display the table in the editor and you will see your changes.

Debugging

The last topic we will cover is the debugging tools.

There are many things you can do in the VS Code debugger that are not language-specific. We aren’t going to cover all of those features here, so if you want a more in-depth look, check out the official documentation.

Since the only truly bug free code is no code, we will start by writing some code that we can test and try to catch bugs in.

function do_math(a, b)    c = a + b    d = a * b    c + dendfunction print_things()    println("First print")    println("Second print")    var = do_math(5,8)    println("Third print and math: ", var)    var2 = do_math("Bug",3)    println("Fourth print and bug: ", var2)endprint_things()

We have code to run, so we can run the debugger and see what we get. First, we must switch to the “Run and Debug” tab. We do this by either clicking on the tab (the one with the bug and play button) or by hitting Ctrl+Shift+D.

Once we are there, we will be greeted with a screen like this:

Debug_Screen

From here we can observe the compiled Julia code, our breakpoints, and several other things as the program runs. We will want to run our code through the debugger, and to do that, we can either click the big “Run and Debug” button or hit F5.

Debug_Error_Message

We step through the code a bit, and see some of what the debugger will show us.

Debugger_Annotated

1: The variables passed into the function

2: The variables local to the function

3: The indicator of which line we are currently on

4: A breakpoint indicator

We can set our breakpoints by double clicking next to the line numbers. After setting our breakpoints, we will be able to step through the code. As we step through the code line by line, the variables that get created are populated in the top section and their values are shown. Another neat feature the debugger gives that is not highlighted above but should be noted is the “CALL STACK” section. As the name suggests, this will show us the entire call stack as you step through the code. All of these are most likely things we have seen before in other debuggers, but they are useful nonetheless.

Keyboard Shortcuts

To wrap up, let’s look at a list of keyboard shortcuts for effective Julia extension usage.Note that a command like Alt+J Alt+C means press Alt+J followed by Alt+C.

Command Shortcut
Execute Code in REPL and Move Shift+Enter
Execute Code in REPL Ctrl+Enter
Execute Code Cell in REPL Alt+Enter
Execute Code Cell in REPL and Move Alt+Shift+Enter
Interrupt Execution Ctrl+C
Clear Current Inline Result Escape
Clear Inline Results In Editor Alt+J Alt+C
Select Current Module Alt+J Alt+M
New Julia File Alt+J Alt+N
Start REPL Alt+J Alt+O
Stop REPL Alt+J Alt+K
Restart REPL Alt+J Alt+R
Change Current Environment Alt+J Alt+E
Show Documentation Alt+J Alt+D
Show Plot Alt+J Alt+P
REPLVariables.focus Alt+J Alt+W
Interrupt Execution Ctrl+Shift+C
Browse Back Documentation Left
Browse Forward Documentation Right
Show Previous Plot Left
Show Next Plot Right
Show First Plot Home
Show Last Plot End
Delete plot Delete
Delete All Plots Shift+Delete

Summary

We reviewed some of the basics of the Julia VS Code extension. We looked at running a Julia file, the basics of code navigation and editing, the usefulness of the plot and table viewers, and some basic debugging features. This was only an overview, and there is much more that the extension has to offer! If you would like to do a deeper dive into the Julia VS Code extension, visit the official documentation or their GitHub.

If you would like to learn more about Julia so you can fully take advantage of the extension’s features, check out our Julia Basics series!

]]>

Installing Julia 1.10 and VSCode

By: Uwe

Re-posted from: https://ufechner7.github.io/2024/08/09/installing-julia-with-juliaup.html

Introduction

Installing Julia is easy, but perhaps you also want to install an integrated development environment (IDE) or a version control system (e.g. git), therefore I give some hints how to do that in this blog post.

Furthermore there are different ways to install multiple Julia versions in parallel and to keep your version up-to-date which are also explained in this blog post.

Highlights of version 1.10 of Julia are explained here .

Installation of Julia

Windows

Windows

Please download and install Julia using juliaup. Launch the Command Prompt app and type:

winget install julia -s msstore
juliaup add 1.10
juliaup update

If that doesn’t work, download https://install.julialang.org/Julia.appinstaller and double-click on the downloaded file to install it.

Optional

It is suggested to install Windows Terminal . Copy and paste works better, unicode works much better and you can use it with bash or Command Prompt, whatever you prefer. It is suggested to set one of these two as default using the Settings menu of Windows Terminal.

Uninstallation

Uninstallation is preferably performed by using the Windows uninstaller. The directory in %HOME%/.julia can then be deleted if you want to remove all traces of Julia (this includes user installed packages).

Linux

Linux

Copy and past the following line to install julia:

curl -fsSL https://install.julialang.org | sh

Restart your terminal, and then execute:

juliaup add 1.10
juliaup update

It is suggested to add the following line to your .bashrc file:

alias jl='./bin/run_julia'

This makes it possible to run Julia with the shortcut jl later, if you have a run_julia script in the bin folder of your projects. I suggest to use such a script, the most simple version of it would just contain the line julia --project .

Mac

Mac

Please download and install juliaup as explained at https://github.com/JuliaLang/juliaup .

Restart your terminal, and then execute:

juliaup add 1.10
juliaup update

Installation of the IDE VSCode

It is useful to install the integrated development environment VSCode, even though it is not required. You can also use any editor of your choice.

VSCode provides syntax highlighting, but also the feature “goto definition” which can help to understand and explore the code.

You can download and install VSCode for all operating systems here .

For Ubuntu Linux the following ppa can be used to install vscode and to keep it up-to-date: https://www.ubuntuupdates.org/ppa/vscode .

Installing the Julia extension

  • Start or open Visual Studio Code.
  • Select View and then click Extensions to open Extension View.
  • Enter the term julia in the marketplace search box. Click the green Install button to download the extension.

Julia VSCode extension

You successfully downloaded the Julia extension for VS Code.

NOTE: It is recommended that you restart VS Code after installation.

Julia development with VSCode is well documented here: Julia Visual Studio Code Documentation

I would NOT use all the advanced features of julia-vscode, I prefer to just use the vscode terminal and launch julia from the terminal. This makes it easy to launch Julia with any command line options and also to start and restart Julia quickly.

Other useful VSCode extensions

  • Project Manager
  • Better TOML
  • Code Spell Checker

VScode supports git out-of-the box.