Category Archives: Julia

Explore the Capabilities of Broadcasting in Julia Programming

By: Steven Whitaker

Re-posted from: https://glcs.hashnode.dev/broadcasting

Julia is a relatively new,free, and open-source programming language.It has a syntaxsimilar to that of other popular programming languagessuch as MATLAB and Python,but it boasts being able to achieve C-like speeds.

Unlike other languagesthat focus on technical computing,Julia does not require usersto vectorize their code(i.e., to have one version of a functionthat operates on scalar valuesand another versionthat operates on arrays).Instead,Julia provides a built-in mechanismfor vectorizing functions:broadcasting.

Broadcasting is useful in Juliafor several reasons,including:

  • It allows functionsthat operate on scalar values(e.g., cos())to operate elementwiseon an array of values,eliminating the needfor specialized, vectorized versionsof those functions.
  • It allows for more efficient memory allocationin certain situations.For example,suppose we have a function, func,and we want to computefunc(1, 2) and func(1, 3).Instead of broadcastingon [1, 1] and [2, 3],we can broadcaston 1 and [2, 3],avoiding the memory allocationfor [1, 1].

On top of that,Julia provides a very convenient syntaxfor broadcasting,making it so anyonecan easily use broadcasting in their code.

In this post,we will learn what broadcasting is,and we will see several examplesof how to effectively use broadcasting.

This post assumes you already have Julia installed.If you haven’t yet,check out our earlierpost on how to install Julia.

What Is Broadcasting?

Broadcasting essentially is a methodfor calling functions elementwisewhile virtually copying inputsso that all inputs have the same size.(For example,if two inputs to a broadcasted function fare 1 and [1, 2, 3],the first input is treatedas if it is [1, 1, 1]but without actually allocating memoryfor an array.Then the function is appliedto each pair of inputs:f(1, 1), f(1, 2), and f(1, 3).)

If that definition doesn’t make sense right now,don’t worry,the examples below will help illustrate.

The Dot Syntax

The first thing to know about broadcastingis that it is very convenient to use.

All you need to do is add dots.

For example,if you want to take the square rootof a collection of values,just add a dot (.):

julia> sqrt.([1, 4, 9]) # Notice the dot after `sqrt`3-element Vector{Float64}: 1.0 2.0 3.0

Vectorizing Operators and Functions

As stated earlier,Julia doesn’t requirevectorized versions of functions.In fact,many functions don’t even have methodsthat take array inputs.Take sqrt for example:

julia> sqrt([1, 4, 9]) # No dot after `sqrt`ERROR: MethodError: no method matching sqrt(::Vector{Int64})

So, even though sqrtdoesn’t have a vectorized versionexplicitly defined,the dot syntax still allowssqrt to be applied elementwise.The same applies to other functions and operators:

julia> [1, 2, 3] ^ 3 # No dotERROR: MethodError: no method matching ^(::Vector{Int64}, ::Int64)julia> [1, 2, 3] .^ 3 # With dot3-element Vector{Int64}:  1  8 27julia> uppercase(["hello", "world"]) # No dotERROR: MethodError: no method matching uppercase(::Vector{String})julia> uppercase.(["hello", "world"]) # With dot2-element Vector{String}: "HELLO" "WORLD"

Vectorization

Vectorization even workswith user-defined functions:

julia> myfunc(x) = x * 2myfunc (generic function with 1 method)julia> myfunc.([1, 2])2-element Vector{Int64}: 2 4

Note that some functionsdo have methodsthat operate on arrays,so be careful when decidingwhether a function should apply elementwise.Take cos as an example:

julia> A = [0 ; /2 /6];julia> cos(A) # Matrix cosine, *not* elementwise cosine2x2 Matrix{Float64}: -0.572989  -0.285823 -0.142912  -0.620626julia> cos.(A) # Add a dot for computing the cosine elementwise2x2 Matrix{Float64}: 1.0          -1.0 6.12323e-17   0.866025

Broadcasting with Multiple Inputs

Broadcasting gets more interestingwhen multiple inputs are involved.Let’s use addition (+) as an example.

We can add a scalar to each element of an array:

julia> [1, 2, 3] .+ 103-element Vector{Int64}: 11 12 13julia> 10 .+ [1, 2, 3]3-element Vector{Int64}: 11 12 13

Scalar-vector broadcasting

We can also sum two arrays elementwise:

julia> [1, 2, 3] .+ [10, 20, 30]3-element Vector{Int64}: 11 22 33

Broadcasting even works with arraysof different sizes.The only requirement is that non-singleton dimensionsmust match across inputs.

julia> [1 2 3; 4 5 6] .+ [10, 20] # Sizes: (2, 3) and (2,)2x3 Matrix{Int64}: 11  12  13 24  25  26julia> [1 2 3; 4 5 6] .+ [10 20] # Sizes: (2, 3) and (1, 2)ERROR: DimensionMismatch: arrays could not be broadcast to a common size; got a dimension with lengths 3 and 2julia> [1 2 3; 4 5 6] .+ [10 20 30] # Sizes: (2, 3) and (1, 3)2x3 Matrix{Int64}: 11  22  33 14  25  36

In the first example([1 2 3; 4 5 6] .+ [10, 20]),the column vector [10, 20]was added to each columnof the matrix,while in the second working example([1 2 3; 4 5 6] .+ [10 20 30]),the row vector [10 20 30]was added to each rowof the matrix.

Matrix-vector broadcasting

Matrix-row-vector broadcasting

Treating Inputs as Scalars

Sometimes,it is usefulto broadcast overonly a subset of the inputs.For example,suppose we have a functionthat scales an input matrix:

julia> myfunc2(X, a) = X * amyfunc2 (generic function with 1 method)

Suppose we want to scale a given matrixby several different scale factors.The result should be an array of matrices,one matrix for each scale factor applied.We might try to use broadcasting:

julia> X = [1 2; 3 4]; a = [10, 20];julia> myfunc2.(X, a)2x2 Matrix{Int64}: 10  20 60  80

But the result is just one matrix!We have one matrix becausewe broadcasted over a and X,not just a.In this case,we need to wrap Xin a single-element Tuple:

julia> myfunc2.((X,), a)2-element Vector{Matrix{Int64}}: [10 20; 30 40] [20 40; 60 80]

Now we have the result we want:an array where the first entryis X scaled by a[1]and the second entryis X scaled by a[2].

So,whenever you need to treat an inputas a scalarfor broadcasting purposes,just wrap it in a Tuple.

Broadcasting with Dictionaries and Strings

Dictionaries and stringsmay act differently than expectedin broadcasting,so let’s clarify some things here.

First,attempting to broadcast over a dictionarywill throw an error:

julia> d = Dict("key1" => "hello", "key2" => "world")Dict{String, String} with 2 entries:  "key2" => "world"  "key1" => "hello"julia> println.(d)ERROR: ArgumentError: broadcasting over dictionaries and `NamedTuple`s is reserved

There are different solutionsdepending on the context.For example:

  • Treat the dictionary as a scalar:
    julia> println.((d,)); # Note that `d` is wrapped in a `Tuple`Dict("key2" => "world", "key1" => "hello")
  • Broadcast over the values explicitly:
    julia> println.(values(d));worldhello

Regarding strings,strings are treated as scalars,not as collections of characters.For example:

julia> string.("string", [1, 2])2-element Vector{String}: "string1" "string2"

(The above would have erroredif strings were not treated as scalars,because length("string") is 6,whereas length([1, 2]) is 2.)

To broadcast over the charactersin a string,use collect:

julia> string.(collect("string"), 1:6)6-element Vector{String}: "s1" "t2" "r3" "i4" "n5" "g6"

Summary

In this post,we learned what broadcasting is,and we saw several examplesof how to effectively use broadcastingto apply functions elementwise.

Have any further questions about broadcasting?Feel free to ask themin the comments below!

Does broadcasting make sense now?Move on to thenext post to learn about Julia’s type system!Or,feel free to take a lookat our other Julia tutorial posts!

Additional Links

Resources for Learning the Julia Programming Language

By: Jacob Zelko

Re-posted from: https://jacobzelko.com/10082023195125-julia-learning-resources/index.html

Resources for Learning the Julia Programming Language

Date: October 8 2023

Summary: A non-exhaustive list of recommendations for how I suggest learning Julia to language newcomers

Keywords: #julia #programming #beginners #recommendations #learning #archive #blog

Bibliography

Not Available

Table of Contents

    1. Motivation
    2. Before Programming with Julia, Let's Set It Up
    3. Julia Programming for New Programmers
    4. Quickly Picking Up Julia Programming
    5. What Is a Julian?
    6. Building Up Expertise in Julia Programming
    7. Domain Specific Workflows in Julia
      1. Working with Data
      2. Plotting
    8. Conclusion
  1. How To Cite
  2. References:
  3. Discussion:

Motivation

I saw an interesting post on BlueSky recently that got me thinking about Julia learning resources. I tend to give out a lot of advice about how to go about learning Julia but I realized I have never really centralized one place where I keep that information. This blog post talks about my personal opinions both within the Julia ecosystem and recommendations for how to learn Julia.

Before Programming with Julia, Let's Set It Up

The fantastic initiative, Modern Julia Workflows, spearheaded by Guillaume Dalle and co has a number of sections that can help with getting set-up fast (I'll be referring to their work quite a bit throughout this post). In particular, here are the sections I'd recommend to get set-up fastest:

  1. How to install Julia on your computer

  2. What you need to write Julia. A special note on this from me is that you really do not need much – you could use something like NotePad on Windows, textedit on OSX, or KWrite on *nix systems. I like the stance Dalle takes in recommending VSCode however as this gives you the best mileage whether you are a beginner or expert programmer.

Suggestion 2 here will most likely take you the longest if you have never worked with a text editor before (a piece of software to create and edit most different types of files). So, no worries and enjoy the learning here!

Julia Programming for New Programmers

If you are completely new to programming in general, I'd recommend the course, Julia Programming for Nervous Beginners, by Dr. Henri Laurie. It really eases you through how to start with programming and uses Julia as that learning tool. Otherwise, skip to the next section.

Quickly Picking Up Julia Programming

To pick up Julia programming, I recommend Introduction to Julia (for programmers) by Dr. Jane Herriman. This will get you going with Julia the fastest – especially if you already know some programming.

What Is a Julian?

Before continuing your Julia adventure, it is worth a pause to discuss a couple aspects of Julia that one may not immediately recognize but are crucial in a productive Julia workflow. Otherwise, one may end up despairing over the supposed virtues of Julia. Here are some specific pieces:

  1. Julia is a REPL-centric workflow. If you are unfamiliar with what a REPL is, please see this reference for details but in short, the Julia REPL is a continuous loop that accepts all valid inputs. From loading a file, experimenting with code, or calling functions, the REPL serves as a scratchpad to iteratively build your overall Julia software instantly.

  2. Julia is compiled – packages and functions will take a moment to load for use. This builds on the previous point, but yes, as Julia is compiled, any package or function you want to use may execute slightly longer initially but then will be compiled for the duration of your work session. This is why you want your Julia workflow to be REPL-centric as you can get around this issue.

  3. Julians organize Julia software into "projects" or packages. Whether you are writing a collection of small scripts to analyze some data or developing a completely new software package, to effectively maneuver through your Julia code, make liberal use of Pkg.jl. Dalle has an excellent reference that talks about this concept of project environments as well as how to build your own local package.

  4. Working within Julia can be extremely efficient – if you know how. This is a circular statement as it naturally raises the question of, "how do I actually build a concrete Julia workflow?" Thankfully, much has been written about this

  5. Julians want to help you. What is wonderful about the Julia community is that, in contrast to perhaps alternative internet communities, the bulk of Julians greatly enjoy helping not only other Julians but other programmers in general (there has been numerous occasions where I have seen Julians help other language users become even more proficient in their workflows). This is an invaluable assortment of where to find your fellow Julians.

I hope this section does not come off as overtly prescriptive, but I have seen the notion of "you are holding the tool wrong" or "what is Julian" (i.e. how do proficient Julia users do X) pop up too many times for new Julians or those experimenting with the language. I hope with this nudging guidance here, a new Julian can more clearly understand the "why" of what other more proficient Julians recommend.

Building Up Expertise in Julia Programming

At this stage, we can now move from the beginner to intermediate Julian stage. Here, I think the world of Julia quite truly opens up to the new user. To delve deeper into Julia, here are some resources I would personally recommend:

  • Believe it or not, the Julia documentation is actually really nice to read and accessible. Now, I don't just say this as I have helped write some of it, but I do truly think it worth looking through to get a better feel for aspects of Julia one may not consider. I would suggest starting with the Manual section of the documentation.

  • Check out the MIT Computational Thinking Course to have a more hands-on introduction to scientific computing. I have never personally gone through it, but I hear it highly praised.

  • Try solving problems on Exercism.io to practice and improve your skills. I am a mentor here although don't have as much time anymore to help review. I still find this to be a really great place to further your learning and to get better at programming Julia – you'll often get feedback from expert Julia users which, in itself, is extremely valuable.

Domain Specific Workflows in Julia

I will probably spin out the following sub-sections into their own blogs, but here are some selected domain specific workflows I have used or become familiar with that I use regularly within Julia.

Working with Data

This admittedly broad workflow encompasses much, but the most important packages in this space are:

  • DataFrames.jl: This package provides a powerful data manipulation and analysis tool for Julia, similar to the pandas library in Python.

    • Additionally, the author of the package, Bogumił Kamiński, is an extremely prolific blogger who shares many different ways of using DataFrames.jl.

I highly suggest his blog.

  • CSV.jl: Utility library for working with CSV and other delimited files in the Julia programming language

  • TerminalPager.jl: a REPL-based Julia variable and documentation explorer

Plotting

When I first started within Julia, this was the only area I felt that was sorely lacking within the ecosystem. However, I am happy to say that this is no longer the case! In my mind, the best Julia plotting package is Makie.jl. It is an interactive data visualization and plotting ecosystem that has support for multiple backends ranging from publication quality static images, 3D images, to fully interactive plots and visualizations. I use it whenever I can.

Conclusion

NOTE: This blog post is a continuous work in progress.

As this blog post is a continuous work in progress, please feel free to comment below on questions about how I could improve it or explain more. That said, my goal with this blog post was not to cover every aspect of the Julia ecosystem but how to quickly go from knowing nothing about programming to becoming a self-sufficient Julian. May this concise guide help you in your way to achieving all that you want within Julia.

How To Cite

Zelko, Jacob. Resources for Learning the Julia Programming Language. https://jacobzelko.com/10082023195125-julia-learning-resources. October 8 2023.

References:

Discussion:


Summer school ‘Research Software Engineering with Julia: Basics, Visualization, and Statistics’ in Stuttgart

By: Hendrik Ranocha -- Julia blog

Re-posted from: https://ranocha.de/blog/RSE_summer_school/

I was invited to give lectures at the summer school
Research Software Engineering with Julia: Basics, Visualization, and Statistics
in Stuttgart in the week 2023-10-09 to 2023-10-13.

See http://www.simtech-summerschool.de and
https://www.simtech.uni-stuttgart.de/events/simtech-summer-school/SuSch_2
for more information.