Learning new programming languages

Programming languages are possibly one of the simplest parts of software engineering. You can know your language from the inside-out and still have problems in a project — knowing the tool doesn’t imply knowing the craft. But learning a new language is really a lot of fun.

Inspired by Avdi Grimm’s roadmap for learning new languages, I decided to give it a try and put my current interests in writing.

  • Julia – http://julialang.org/
    I have experience writing code in MATLAB, Octave, Python (with Numpy, Scipy and Pandas) and a bit of R, and still I’m excited with Julia.There are at least 3 features of Julia that are powerful and make me wish to work with it: its Just-In-Time compiler, parallel for and the awesome metaprogramming inherited from LISP.

    The drawback is… is… well, I didn’t have time to really use it and get comfortable writing Julia programs. Yet.

  • Haskell – https://www.haskell.org/

    I already tried learning Haskell a couple of times. Maybe 3 or 4 or 5 times. I wrote programs based on mathematics and some simple scripts, most of the syntax isn’t strange anymore, even monads make sense now; however, I still feel a bit stiff when writing Haskell. I don’t know.

    Two books I recently bought might help with that – Real World Haskell and Parallel and Concurrent Programming in Haskell. I probably need to motivate myself to write something useful with it.

  • Rust – http://www.rust-lang.org/

    There is a quote in Rust’s website that sums my expectations of it:

    Rust is a systems programming language that runs blazingly fast, prevents nearly all segfaults, and guarantees thread safety.

    I know how to read C/C++ and even write a bit of it, but it’s messy and takes more time than I usually have for side projects. Writing code that is safe & fast shouldn’t be so hard. ;)

All-in-all, this is a very brief list. However, I don’t think I should focus on more languages right now. To be honest, I think that my next learning targets are in applied mathematics. I need a stronger foundation in Partial Differential Equations and Probability Theory. There are several topics in optimization that I should take the time to study. Calculus of variations also seems quite cool.

(good thing that I have friends in pure math to help me find references!)

SciRuby projects for Google Summer of Code 2015

Another year with SciRuby accepted as a mentoring organization in Google Summer of Code (GSoC)! The Community Bonding Period ended yesterday; the coding period officially begins today.

I’m really happy with the projects chosen this year; various different subjects and some would be really useful for me, i.e. Alexej’s LMM gem, Sameer’s Daru and Will’s changes to NMatrix.

That’s all. After the next GSoC meeting, I should write about how each of the projects are going.

The most socially useful communication technology

Text is the most socially useful communication technology. It works well in 1:1, 1:N, and M:N modes. It can be indexed and searched efficiently, even by hand. It can be translated. It can be produced and consumed at variable speeds. It is asynchronous. It can be compared, diffed, clustered, corrected, summarized and filtered algorithmically. It permits multiparty editing. It permits branching conversations, lurking, annotation, quoting, reviewing, summarizing, structured responses, exegesis, even fan fic.

I read the post “Always bet on text” today and, I must say, it is a beautiful way to look at the process of communicating by writing. :)

Excel trying to take over the world

Intuitively, it is not just the limited capability of ordinary software that makes it safe: it is also its lack of ambition. There is no subroutine in Excel that secretly wants to take over the world if only it were smart enough to find a way.
— Nick Bostrom, Superintelligence

I wouldn’t be so certain about it.

There are “scientists” (economists) who think it is OK to use Excel for making predictions that affect several people, as you can see from this article in The Guardian. Essentially, they didn’t add four years of data from New Zealand to a spreadsheet. Other methodological factors were in effect as well. And all of this contributed to lots of people losing their jobs in various countries when the recommended austerity measures were put in place. Imagine if Excel wanted to take over the world.

The paper that discusses in depth about Reinhart and Rogoff’s mistake is “Does High Public Debt Consistently Stifle Economic Growth? A Critique of Reinhart and Rogo ff“.

Completeness and incomputability

It is notable that completeness and incomputability are complementary properties: It is easy to prove that any complete prediction method must be incomputable. Moreover, any computable prediction method cannot be complete — there will always be a large space of regularities for which the predictions are catastrophically poor.

— Ray Solomonoff, “Algorithmic Probability — Its Discovery — Its Properties and Application to Strong AI”

This quote is a paragraph from the book Randomness Through Computation, an amazing work I was reading this morning.

The idea that any computable prediction method can’t be complete is profound for those of us that work with machine learning; it implies we always have to deal with trade-offs. Explicitly considering this makes for a better thought process when designing applications.

References

  1. Ray Solomonoff — Wikipedia.
  2. Solomonoff’s Lightsaber — Wikipedia, LessWrong

Books so far in 2014

I have a lot of books.

I’ve finally decided to organize my collection and keep track of what I read. In this post, I’ll list the books I read since January — or at least an approximation given by the email confirmations of the ebooks I bought, my memory and the ones in my bookshelf. I also divided them in sections. Papers are included as well.

Continue reading

Updates on NMatrix and SciRuby development

For the last couple of days, I’ve been thinking about what I wrote two weeks ago regarding SciRuby and the whole Ruby scientific computing scene. I still believe that the sciruby gem can be used as an integrated environment, but there are some problems that must be solved before:

  1. We need a reasonably feature complete and easy to install version of NMatrix.
  2. A good plotting tool. Right now, Naoki is working on this as part of GSoC 2014.
  3. Statistics. Lots of things are already implemented in Statsample, but both Statsample::DataFrame and Statsample::Vector should use NMatrix behind the hood. Supporting JRuby can be problematic here…
  4. Given 1 and 2, it’s possible to implement a lot of other interesting and useful things. For example: linear regression methods, k-means clustering, neural networks, use NMatrix as a matrix type for OpenCV images. There are lots of possibilities.
  5. Minimization, integration and others.

With that in mind, my objective for the following weeks is to improve NMatrix. First, there are BLAS routines (mainly from level II, but some stuff from level I and III as well) that aren’t implemented in NMatrix and/or that aren’t available for the rational and ruby objects dtypes. There’s also LAPACK.

Another benefit of having complete C/C++ implementations is that we’ll eventually have to generalize these interfaces to allow other implementations (e.g. Mac OSX vecLib’s LAPACK, Intel’s MKL), thus making it much easier to install NMatrix. As Collin (and, I think, Pjotr) said in the sciruby-dev mailing list, it should be as easy as gem install nmatrix.

BLAS and LAPACK general implementations

  • HAVE_CBLAS_H being derived from mkmf‘s have_header
  • Many more routines are implemented. Ideally, BLAS level 1 and 2 should be complete by the end of May.

An important next step is to be able to link against arbitrary BLAS and LAPACK implementations, given that they obey the standard. Issue #188 started some ideas; issue #22 is the original (and very old) one.

After that…

When NMatrix support both BLAS and LAPACK without a problem — i.e. have its own implementation and can also link against arbitrary ones (OSX’s vecLib, GSL, ATLAS, Intel’s MKL, AMD’s Core Math Library) — we’ll be able to build on top of it. There are some routines in NMatrix that are already working with every dtype, but most of them aren’t. When we know exactly which routines can’t work with which dtypes, we’ll reach a very good standpoint to talk about what we support.

Alright, we have determinants for rational matrices, but not “other operation”, etc. What else? STYPES! We also need to have good support for Yale matrices. (obs: maybe add “old Yale” format?)

There isn’t much to do: we have to support the whole BLAS/LAPACK standard, almost everything linear algebra-wise is in these. After that, it’s mostly improvements to the interface, better method naming, better documentation and examples, better IO, etc.

Another point that would be good to adress is to remove the dependency of g++ > 4.6. We should strive to remove everything that depends on C++11 features, thus allowing normal Mac OSX users to install NMatrix without having to first install another compiler.

Better documentation

We need to refactor our documentation. Oh, how we need to!

First, remove everything that shouldn’t be in the facing API — the classes and modules used in NMatrix::IO shouldn’t be available in the public API anyway, only the outside-facing stuff: how to save and load to/from each format. Probably more things as well.

Second, do a better job of being consistent with docs. There are some methods without a return type or stuff like that. Lots of methods in the C/C++ world aren’t documented as well. We can do better!

Finally, a really good documentation template. Fivefish is a good choice — it provides a very pretty, searchable and clean interface. (create NMatrix’s docs with it and host on my own server, see what happens).

Solving linear systems in NMatrix

I’m writing some guides for NMatrix, so in the following weeks there should be some posts similar to this one, but more complex.

Linear systems are one of the most useful methods from “common algebra”. Various problems can be represented by them: systems of linear ODEs, operations research optimizations, linear electrical circuits and a lot of the “wording problems” from basic algebra. We can represent these systems as

Ax = b

Where A is a matrix of coefficients and b a vector representing the other side of the equation.

Continue reading

Gems for scientific computing

UPDATE (20/04): User centrx from #ruby-lang at freenode warned me that I forgot about RSRuby/RinRuby, so I added them to projects.yml.

In Wicked Good Ruby 2013, Bryan Liles made a presentation about Machine Learning with Ruby. It’s a good introduction to the subject and he presents some useful tricks (I didn’t know about Grapher.app, for example). But the best advise I could get is that there’s a lot of room for improvement in the Ruby scientific computing scene.

Having contributed to some SciRuby projects in the last year, I’ve seen it first-hand. With NMatrix, it’s possible to do a lot of vector and matrix calculations easily, if you know how to install it — a task that’s much easier today. There are statsample for statistics, distribution for probability distributions, minimization, integration, the GSL bindings and others. But if you need plotting, it can be pretty hard to use (e.g. Rubyvis) or depend on external programs (Plotrb outputs SVG files). Do you want an integrated environment, like MATLAB or Pylab? There isn’t one.

Searching for more instances of people interested in the subject, I found a presentation about neural networks by Matthew Kirk from Ruby Conf 2013, an Eurucamp 2013 presentation by Juanjo Bazán and slides from a presentation by Shahrooz Afsharipour at a German university. If we needed any confirmation that there are folks looking for SciRuby, here’s the evidence.

What can be done

In order to address these problems, I’m trying to come up with concrete steps towards creating a scientific community around Ruby. It’s obvious we need “more scientific libraries”, but what do we already have? What is easy to install and what isn’t? Should we create something new or improve what we have?

Also, I’m mapping the Ruby scientific computing landscape. I’ve compiled a YAML file with a list of the projects that I’ve found so far. In the future, this could be transformed in a nice visualization on sciruby.org to help scientists find the libraries they need.

If you know how to use the R programming language, both RSRuby and RinRuby can be used. They’re libraries that run R code inside of Ruby, so you can technically do anything you’d do with R in Ruby. This is suboptimal and R isn’t known for its speed.

For an integrated environment, we can revive the sciruby gem. For example:

I’m updating the SciRuby repository in this branch. Before creating the above DSL, it’s necessary to remove a lot of cruft (e.g. should use bundler/gem_tasks instead of hoe) and add some niceties (e.g. Travis CI support). Most importantly, adding dependency to the main SciRuby projects — NMatrix, statsample, minimization, integration, etc — in order to have a real integrated environment without require’ing everything manually. I’ll probably submit a pull request by next week.

We also need to improve our current selection: NMatrix installation shouldn’t depend on ATLAS, plotrb (or other solution) needs to be more usable, show how IRuby can be used to write scripts with nice graphics and LaTeX-support and create a list of all the applications that use our libraries for reference.

The Ruby Science Foundation was selected for Google Summer of Code 2014, thus some very bright students will help us fix some of these problems during the summer. However, there’s a lot to be done in every SciRuby project, if you’ve got the time. :)

Conclusion

We still have a long way before having a full-fledged scientific community — but there’s hope! Some areas to look at:

  • Good numerical libraries: NMatrix, mdarray.
  • Algorithms for data mining, modeling and simulations: AI4R, ruby-fann, ruby-libsvm, statsample, distribution, etc.
  • Plotting: Rubyvis is a port of Protovis, which was deprecated in favor of
    D3js. Thus, we should create some plotting library around a C backend or
    around D3, like Plotrb.
  • Integrated environment: IRuby together with SciRuby.

Except for plotting, an area that really needs a lot of love and care, most of these are already working, but with usability problems (installation, mostly).

If you think that it’d be cool to have a scientific community centered around Ruby and you do have some time available, please please please:

  1. Take a look at the SciRuby repositories.
  2. If there’s a subject you’re interested in, see if you can refactor something, add more tests, well, anything.
  3. Open issues about new features or pull requests improving the current ones.
  4. If you don’t understand much about the subject, but see something that could be improved, do it: is there Travis CI support? Something wrong with the gemspec? Is it still using some gem to generate gemspecs?
  5. There’s the sciruby-dev mailing list and the #sciruby channel on Freenode if there’s something you want to ask or discuss.

You can find me as agarie on freenode or @carlos_agarie on twitter.

References

  1. SciRuby. SiteGitHub
  2. List of scientific computing projects in Ruby. projects.yml
  3. Wicked Good Ruby 2013. Site
  4. Bryan Liles: Machine Learning with Ruby. bryan
  5. Matthew Kirk: Test-driven neural networks with Ruby. neural
  6. Shahrooz Afsharipour: Ruby in the context of scientific computing. slides in PDF
  7. Juanjo Bazán: presentation in Eurucamp 2013. juanjo-slides

A PNG showing differently in Firefox and Chrome

I was chatting with some friends on IM when someone posted an URL to a Psyduck image. In it said “Now open this in Firefox” when opened in Google Chrome or Safari and “Now open this in IE (or Chrome/Safari)” when opened in Firefox.

Psyduck

What.

At first, I though it would be a simple use of pattern matching against HTTP’s User-Agent on the server to send two different PNG files depending on the browser. However, both files had the same size and I couldn’t reproduce it with curl. Worse: I downloaded the file and the same behavior was present, so it should be something with the image itself.

I never really studied or read about binary file formats before, so I googled a bit and installed the chunkypng gem. After playing a bit with its documentation, I could see which blocks it had.

Can you see the acTL block? It isn’t in the PNG specification. Why is it there? After some more searching, it was clear that this block is only available in APNG files, an extension to PNG enabling animated images similar to GIF.

The first byte @content of the acTL block is the number of frames (only 1) and the second one is how many times to loop the APNG
(source). From the spec, there’s always a “default image” (described by the IDAT blocks, exactly like a normal PNG file), thus this extra frame should be the second Psyduck image.

To confirm this hypothesis, I installed pngcrush with Homebrew and removed the acTL block:

I ended up with an image that will look the same independent of the host browser:

Altered Psyduck

Search a bit more lead me to the cause of the discrepancy: only Firefox and Opera have support for APNG files! From this post in Google’s Products forum and this ticket in Chromium’s issue tracker, WebKit/Chrome doesn’t support the format and probably won’t for some time. Also, from the spec:

APNG is backwards-compatible with PNG; any PNG decoder should be able to ignore the APNG-specific chunks and display a single image.

Take all that and the mystery is solved: when that image is opened in Firefox (or Opera), it’s treated as an APNG and the second frame is shown. In Chrome/Safari (WebKit), the extra blocks are ignored and the default image is shown.

That was fun.

References

  1. PNG specification
  2. APNG specification

Cross validation in Ruby

These days I had some data mining problems in which I wanted to use Ruby instead of Python. One of the problems I faced is that I wanted to use k-fold cross validation, but couldn’t find a sufficiently simple gem (or gist or whatever) for it. I ended up creating my own version.

A review of k-fold cross validation

A common way to study the performance of a model is to partition a dataset into training and validation sets. Cross validation is a method to assess if a model can generalize well independent of how this separation is decided.

The method of k-fold cross validation is to divide the dataset into k partitions, select one at a time for the validation set and use the other k – 1 partitions for training. So you end up with k different models, and respective performance measures against the validation sets.

The image below is an example of one fold: the k-th partition is left out for validation and partitions 1, …, k-1 are used for training.

k-fold cross validation

E.g., if k = 5, you end up with 80% of the dataset for training and 20% for validation.

The implementation

My solution is a function that receives the dataset, the number of partitions and a block, responsible for training and using the classifier in question. Most of it is straightforward, just keep in mind that the last partition (k-1-th) should encompass all the remaining elements when dataset.size isn’t divisible by k. Obviously, the training set is defined by the elements not in the validation set.

The last part is to yield both sets to the given block. Some information regarding the functionality of the yield keyword can be seen in another post and in Ruby core’s documentation.

Now suppose you have a CSV file called “dataset.csv” and you have a classifier you want to train. It’s as easy as:

And your classifier’s code is totally decoupled from the cross validation function. I like it.

Conclusion

I found a gem on GitHub the other day unsurprisingly called cross validation. Its API is similar to scikit-learn‘s, which I find particularly strange. Too object oriented for me.

This code isn’t a full-blown gem and I don’t think there should be one just for cross validation. It fits in a whole machine learning library, though–and I hope to build one based on NMatrix… eventually.

MATLAB in OS X Mountain Lion

I needed to write an optimization function for college and came across this problem today: if you use OS X Mountain Lion (I think the problem also happens in Lion and < 10.6), your MATLAB should stop working correctly after a Java update that occurred in June. Well, Java.

The problem lies with a bug packed in the Java Security Update released by Apple. For some reason, the corresponding fix isn’t automatically downloaded by the App Store, so we must do it manually1. This bug interferes with MATLAB’s graphical user interface, making it unusable.

It’s pretty easy: go to support.apple.com/kb/DL1572 and download the update. Then, just install and open MATLAB.

Another “solution” is to run MATLAB without its GUI by using:

Where $MATLAB is the installation directory, for example in /Applications/MATLAB_R2009b.app/.

Moral: don’t leave some computer-based homework for the last day when it depends on Java.

  1. http://www.mathworks.com/matlabcentral/answers/79489#answer_89629