Tag Archives: Julia

Tabular Data I/O in Julia

By: randyzwitch - Articles

Re-posted from: http://randyzwitch.com/julia-import-data/

Importing tabular data into Julia can be done in (at least) three ways: reading a delimited file into an array, reading a delimited file into a DataFrame and accessing databases using ODBC.

Reading a file into an array using readdlm

The most basic way to read data into Julia is through the use of the readdlm function, which will create an array:

readdlm(source, delim::Char, T::Type; options...)

If you are reading in a fairly normal delimited file, you can get away with just using the first two arguments, source and delim:It’s important to note that by only specifying the first two arguments, you leave it up to Julia to determine the type of array to return. In the code example above, an array of type ‘Any’ is returned, as the .csv file I read in was not of homogenous type such as Int64 or ASCIIString. If you know for certain which type of array you want, you specify the data type using the type argument:

It’s probably the case that unless you are looking to do linear algebra or other specific mathy type work, you’ll likely find that reading your data into a DataFrame will be more comfortable to work with (especially if you are coming from an R, Python/pandas or even spreadsheet tradition).

To write an array out to a file, you can use the writedlm function (defaults to comma-separated):

writedlm(filename, array, delim::Char)

Reading a file into a DataFrame using readtable

As I covered in my prior blog post about Julia, you can also read in delimited files into Julia using the DataFrames package, which returns a DataFrame instead of an array. Besides just being able to read in delimited files, the DataFrames package also supports reading in gzippped files on the fly:From what I understand, in the future you will be able to read files directly from Amazon S3 into a DataFrame (this is already supported in the AWS package), but for now, the DataFrames package works only on local files. Writing a DataFrame to file can be done with the writetable function: writetable(filename::String, df::DataFrame) By default, the writetable function will use the delimiter specified by the filename extension and default to printing the column names as a header.

Accessing Databases using ODBC

The third major way of importing tabular data into Julia is through the use of ODBC access to various databases such as MySQL and PostgreSQL.

Using a DSN

The Julia ODBC package provides functionality to connect to a database using a Data Source Name (DSN). Assuming you store all the credentials in your DSN (server name, username, password, etc.), connecting to a database is as easy as:

Of course, if you don’t want to store your password in your DSN (especially in the case where there are multiple users for a computer), you can pass the “usr” and “pwd” arguments to the ODBC.connect function:

ODBC.connect(dsn; usr="", pwd="")

Using a connection string

Alternatively, you can build your own connection strings within a Julia session using the advancedconnect function:Regardless of which way you connect, you can query data using the query function. If you want your output as a DataFrame, you can assign the result of the function to an object. If you want to save the results to a file, you specify the “file” argument:

Summary

Overall, importing data into Julia is no easier/more difficult than any other language. The biggest thing I’ve noticed thus far is that Julia is a bit less efficient than Python/pandas or R in terms of the amount of RAM needed to store data. In my experience, this is really only an issue once you are working with 1GB+ files (of course, depending on the resources available to you on your machine).

A Beginner’s Look at Julia

By: randyzwitch - Articles

Re-posted from: http://randyzwitch.com/julia-language-beginners/

Over the past month or so, I’ve been playing with a new scientific programming language called ‘Julia‘, which aims to be a high-level language with performance approaching that of C. With that goal in mind, Julia could be a replacement for the ‘multi-language’ problem of needing to move between R, Python, MATLAB, C, Fortran, Scala, etc. within a single scientific programming project.  Here are some observations that might be helpful for others looking to get started with Julia.

 

Get used to ‘Git’ and ‘make’

While there are pre-built binaries for Julia, due to the rapid pace of development, it’s best to build Julia from source. To be able to keep up with the literally dozen code changes per day, you can clone the Julia GitHub repository to your local machine. If you use one of the GitHub GUI’s, this is as easy as hitting the ‘Sync Branch’ button to receive all of the newest code updates.

To install Julia, you need to compile the code. The instructions for each supported operating system are listed on the Julia GitHub page. For Mac users, use Terminal to navigate to the directory where you cloned Julia, then run the following command, where ‘n’ refers to the number of concurrent processes you want the compiler to use:

make -j n

I use 8 concurrent processes on a 2013 MacBook Pro and it works pretty well. Certainly much faster than a single process. Note that the first time you run the ‘make’ command, the build process will take much longer than successive builds, as Julia downloads all the required libraries needed. After the first build, you can just run the ‘make’ command with a single process, as the code updates don’t take very long to build.

Package management is also done via GitHub. To add Julia packages to your install, you use the Pkg.add() function, with the package name in double-quotes.

Julia code feels very familiar

Text file import

Although the Julia documentation makes numerous references to MATLAB in terms of code similarity, Julia feels very familiar to me as an R and Python user. Take reading a .csv file into a dataframe and finding the dimensions of the resulting object:
In each language, the basic syntax is to call a ‘read’ function, specify the .csv filename, then the defaults of the function read in a basic file. I also could’ve specified other keyword arguments, but for purposes of this example I kept it simple.

Looping

Looping in Julia is similar to other languages. Python requires proper spacing for each level of a loop, with a colon for each evaluated expression. And although you generally don’t use many loops in R, to do so requires using parenthesis and brackets.

If you’re coming from a Python background, you can see that there’s not a ton of difference between Python looping into a dictionary vs. Julia. The biggest differences are the use of the ‘end’ control-flow word and that Julia doesn’t currently have the convenience “Counter” object type. R doesn’t natively have a dictionary type, but you can add a similar concept using the hash package.

Vectorization

While not required to achieve high performance, Julia also provides the functional programming construct of vectorization and list comprehensions. In R, you use the ‘apply’ family of functions instead of loops in order to apply a function to multiple elements in a list. In Python, there are the ‘map’ and ‘reduce’ functions, but there is also the concept of list comprehensions. In Julia, both of the aforementioned functionalities are possible.

In each case, the syntax is just about the same to apply a function across a list/array of numbers.

A small, but intense community

One thing that’s important to note about Julia at this stage is that it’s very early. If you’re going to be messing around with Julia, there’s going to be a lot of alone-time experimenting and reading the Julia documentation. There are also several other resources including a Julia-Users Google group, Julia for R programmers, individual discussions on GitHub in the ‘Issues’ section of each Julia package, and a few tutorials floating around (here and here).

Beyond just the written examples though, I’ve found that the budding Julia community is very helpful and willing in terms of answering questions. I’ve been bugging the hell out of John Myles White and he hasn’t complained (yet!), and even when code issues are raised through the users group or on GitHub, ultimately everyone has been very respectful and eager to help. So don’t be intimidated by the fact that Julia has a very MIT and Ph.D-ness to it…jump right in and migrate some of your favorite code over from other languages.

While I haven’t moved to using Julia for my everyday workload, I am getting facility to the point where I’m starting to consider using Julia for selected projects. Once the language matures a bit more, JuliaStudio starts to approach RStudio in terms of functionality, and I get more familiar with the language in general, I can see Julia taking over for at least one if not all of my scientific programming languages.

Well, that was embarrassing.

I have long been confused by the strange behavior of integers as arguments to functions.
If I pass a variable into a function, I expect the function to be able to modify it.
This expectation applies to variables local to the calling context and to global variables;
it also applied to Strings and Floats and Integers and Chars.
When I’m trying to do something
(like modifying Int arguments inside a function and seeing the change outside it)
and it isn’t working, I fiddle with it until it does.

However, today, I decided that I should actually ask why it didn’t work the way I expect.
Today, I had the embarrassing experience of correcting my fundamentally flawed model of how variables work.
I’m going to skip over explaining the details of my previous model, since I don’t want to encourage its remaining grip on my mind.
Instead, I’m going to work through a very physical metaphor for my new understanding.

The Metaphor: A Table of Boxes and Forms and Colorful Stickers

There are two kinds of values: mutable and immutable.
Immutable values cannot be edited; they are like paper forms filled out in indelible ink.
Numbers (Ints,Floats,BigInts,BigFloats,etc), Chars, Strings, and user-defined immutable types are all immutable.
Mutable values can be edited; they are like boxes with boxes and paper forms inside.
I like to picture them as those organizer-boxes, with dividers it them.
Dictionaries, Arrays, and all other user-defined types are mutable.

There is a table (as in, a piece of furniture) of these boxes and forms; this is all the memory your program is using.
(this metaphor, as you may have noticed, is ignoring the stack/heap distinction and other implementation concerns.
I’m focused on getting correct expectations for what the value of my variables might be after I use them as arguments to a function.)
As your program executes, it fills out new forms, puts new boxes on the table, and throws out boxes and forms that it’s not using.
It also moves things into or out of the boxes.

There is one other component to this setup: stickers.
Any time that code is executing, it is executing within a context.
This context is made of bindings of names (variable names) to the values on the table.
We’ll model these bindings as stickers.
The name of the variable is printed on the sticker,
and the sticker is stuck to the value that the variable is currently bound to.
Each context has its own color of sticker, and ignores stickers that aren’t of its color.

Example 1: x = x + 1

Let’s say we have the variable name x bound to an Int value, 5.
This value is immutable, so it will be a paper form with 5 written on it in ink.
Because we’re calling this form by the name x, there is a sticker on the form with the name x printed on it.
Now that I’ve explained the context, let’s run the line of code x = x + 1.
First, we’ll take a look at the value on the form labeled x; it’s 5.
Then, we’ll write the result of 5 + 1 on a new form.
Finally, we’ll move the x sticker from the form with 5 written on it to the form with 6 written on it.

Example 2: a[2] = 6

Forget about x. a is a 1-dimensional Array.
Picture a as a long, thin box with three dividers in it.
Each space between the dividers is an element of a, so a is of length 4.
There is a sticker with a printed on it on the outside of the box.
Each of the spaces in the box has a paper form with a number written on it;
what numbers are written on them is not relevant to this example.

Now, let’s simulate running a[2] = 6.
(We’re simulating Julia code, so we’re indexing from 1.)
First, we’ll get a paper form and write 6 on it in pen.
Then, we’ll replace the paper in the second box from the left of a with the new form.
That’s all we need to do; notice that no stickers have been moved.

Example 3: foo(x)

Say we have our integer variable x again.
It’s a form with 6 written on it, with an x sticker stuck to it.
The sticker is blue.

Now, we have a function:

 :::.jl
 function foo(z::Int)
   z = z + 1
 end

I’m going to ignore irrelevant portions of calling this function,
including that it will return the value of z + 1.

When we run the line foo(x), we will move into the context of foo.
Our previous context is the calling context (the one calling foo).
Our current context is inside foo, so now there is a green z sticker on our form.
Now, inside foo, we’ll write 7 on a new form, and move our green z sticker to it.
Then we return from the function call, and remove all the green stickers.

What is the value of x now?

Well, the blue x sticker is still stuck to the form with 6 written on it.
This means that foo did not modify x.
In fact, passing an Int variable as an argument to a function will never modify that variable.
Inside the context of foo, we can’t see the blue x sticker at all — and we definitely can’t move it.[1]
The form is immutable, so you can’t erase and you can’t write anything new on it.
There’s nothing that foo could possibly do to change the value of x in the calling context.

Example 4: foo(a[2])

Picture the box for a again. It’s got 4 pieces of paper in it; the second one says 6.
There are no labels on any of the four forms; there is a blue a label on the outside of the box.

Now, we’ll execute foo(a[2]), where foo is the same function from the previous example.
As we move from the calling context into the foo context,
we’ll stick a green z sticker on the form in the second compartment of the box with the blue a sticker.
Now, we’ll get out a new form, write 7 on it, and move the green z sticker to this new form.
Finally, we’ll remove all the green stickers as we return to the calling context.

The value of a is unchanged.

Example 5: bar(a)

So far, we haven’t managed to mutate any arguments to a function.
This is about to change.

Picture the box for a. Let’s say that the four forms in have,
respectively, the following numbers written on them: 1,6,8,19.
None of the forms have any labels on them; the only label is the blue a on the box.

We’ll need a new function for this:

 :::.jl
 function bar(xs::Array)
   xs[2] = 42
 end

Now, let’s simulate: bar(a).
We’ll move from the blue calling context to the green callee context;
we’ll put a green xs sticker on the box.
Then we’ll take the piece of paper in the second compartment (with 6 written on it)
and replace it with a new form with 42 written on it.
Now, we’ll return to the calling context, removing the green xs sticker.
Notice that we did not move any stickers.

What is the value of a now?

It’s [1,42,8,19]. The assignment in bar did affect the value of a.
It did not affect the binding of a (the blue sticker),
but it affected which values were inside the mutable box that is the value of a.

Conclusion

I already had a sort of messy awareness of this whole thing.
I mean, I’ve brushed up against “by value” vs “by reference”;
I’m fine with writing C and using pointer;
I was good on the difference between variables shadowing and modifying a mutable box in OCaml.
But it wasn’t until today that this all clicked into place in my mental model
of how passing variables as arguments to functions works in “normal” languages, like Julia and Java and such.
Suddenly, the division between types that are passed “by reference” and ones that are inexplicably passed “by value” makes complete sense.

I am happy that I noted that I was confused and expressed my confusion despite feeling embarrassed.
After trying several functions in the Julia REPL and determining that the behavior did indeed break my mental model (I felt so confused),
I asked one of my mentors for the summer the relevant question.
Once I convinced him that I was in fact not joking and was honestly surprised and confused,
he was very patient about correcting my misunderstanding.
Being very confused about a fundamental aspect of programming,
misunderstanding such a seemingly basic thing,
was embarrassing to admit to myself;
it was much more embarrassing to reveal that mistake in front of someone as awesome as him.
I still feel embarrassed, but the world also makes a lot more sense, which is worth it.

Footnotes

  1. Except in certain circumstances in C++.