Commit 97359ba0 authored by G. Jay Kerns's avatar G. Jay Kerns

I think we're just about there

parent 7681ac4b
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Introduction to <code>julia</code></title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<meta name="title" content="Introduction to <code>julia</code>"/>
<meta name="generator" content="Org-mode"/>
<meta name="author" content="G. Jay Kerns"/>
<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
html { font-family: Times, serif; font-size: 12pt; }
.title { text-align: center; }
.todo { color: red; }
.done { color: green; }
.tag { background-color: #add8e6; font-weight:normal }
.target { }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.right {margin-left:auto; margin-right:0px; text-align:right;}
.left {margin-left:0px; margin-right:auto; text-align:left;}
.center {margin-left:auto; margin-right:auto; text-align:center;}
p.verse { margin-left: 3% }
pre {
border: 1pt solid #AEBDCC;
background-color: #F3F5F7;
padding: 5pt;
font-family: courier, monospace;
font-size: 90%;
overflow:auto;
}
table { border-collapse: collapse; }
td, th { vertical-align: top; }
th.right { text-align:center; }
th.left { text-align:center; }
th.center { text-align:center; }
td.right { text-align:right; }
td.left { text-align:left; }
td.center { text-align:center; }
dt { font-weight: bold; }
div.figure { padding: 0.5em; }
div.figure p { text-align: center; }
div.inlinetask {
padding:10px;
border:2px solid gray;
margin:10px;
background: #ffffcc;
}
textarea { overflow-x: auto; }
.linenr { font-size:smaller }
.code-highlighted {background-color:#ffff00;}
.org-info-js_info-navigation { border-style:none; }
#org-info-js_console-label { font-size:10px; font-weight:bold;
white-space:nowrap; }
.org-info-js_search-highlight {background-color:#ffff00; color:#000000;
font-weight:bold; }
/*]]>*/-->
</style>
<script type="text/javascript">
/*
@licstart The following is the entire license notice for the
JavaScript code in this tag.
Copyright (C) 2012 Free Software Foundation, Inc.
The JavaScript code in this tag is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License (GNU GPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later version. The code is distributed WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
As additional permission under GNU GPL version 3 section 7, you
may distribute non-source (e.g., minimized or compacted) forms of
that code without the copy of the GNU GPL normally required by
section 4, provided you include this license notice and a URL
through which recipients can access the Corresponding Source.
@licend The above is the entire license notice
for the JavaScript code in this tag.
*/
<!--/*--><![CDATA[/*><!--*/
function CodeHighlightOn(elem, id)
{
var target = document.getElementById(id);
if(null != target) {
elem.cacheClassElem = elem.className;
elem.cacheClassTarget = target.className;
target.className = "code-highlighted";
elem.className = "code-highlighted";
}
}
function CodeHighlightOff(elem, id)
{
var target = document.getElementById(id);
if(elem.cacheClassElem)
elem.className = elem.cacheClassElem;
if(elem.cacheClassTarget)
target.className = elem.cacheClassTarget;
}
/*]]>*///-->
</script>
<script type="text/javascript" src="http://orgmode.org/mathjax/MathJax.js">
<!--/*--><![CDATA[/*><!--*/
MathJax.Hub.Config({
// Only one of the two following lines, depending on user settings
// First allows browser-native MathML display, second forces HTML/CSS
// config: ["MMLorHTML.js"], jax: ["input/TeX"],
jax: ["input/TeX", "output/HTML-CSS"],
extensions: ["tex2jax.js","TeX/AMSmath.js","TeX/AMSsymbols.js",
"TeX/noUndefined.js"],
tex2jax: {
inlineMath: [ ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"], ["\\begin{displaymath}","\\end{displaymath}"] ],
skipTags: ["script","noscript","style","textarea","pre","code"],
ignoreClass: "tex2jax_ignore",
processEscapes: false,
processEnvironments: true,
preview: "TeX"
},
showProcessingMessages: true,
displayAlign: "center",
displayIndent: "2em",
"HTML-CSS": {
scale: 100,
availableFonts: ["STIX","TeX"],
preferredFont: "TeX",
webFont: "TeX",
imageFont: "TeX",
showMathMenu: true,
},
MMLorHTML: {
prefer: {
MSIE: "MML",
Firefox: "MML",
Opera: "HTML",
other: "HTML"
}
}
});
/*]]>*///-->
</script>
</head>
<body>
<div id="content">
<h1 class="title">Introduction to <code>julia</code></h1>
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#sec-1">1. What you need to get started</a></li>
<li><a href="#sec-2">2. Getting started with julia</a>
<ul>
<li><a href="#sec-2-1">2.1. Communicating with julia</a></li>
<li><a href="#sec-2-2">2.2. <code>julia</code> is one fancy calculator</a></li>
<li><a href="#sec-2-3">2.3. Getting Help</a></li>
</ul>
</li>
<li><a href="#sec-3">3. Other tips</a>
<ul>
<li><a href="#sec-3-1">3.1. Other resources</a></li>
</ul>
</li>
<li><a href="#sec-4">4. Plotting with Winston</a></li>
<li><a href="#sec-5">5. Fitting (generalized) linear models</a></li>
</ul>
</div>
</div>
<p>
\vspace{0.25in}
</p>
<p>
This document is a <i>brief</i> introduction to <code>julia</code>. It is a reworked
<i>Brief Introduction to R</i> (which is an abbreviated Chapter 2 of <a href="http:ipsur.org" >IPSUR</a>)
which I usually distribute to students using R for the first time.
One of the reasons for this document is that I wanted to get better
acquainted with <code>julia</code> and thought it might make it easier for others
to get better acquainted with it, too. In what follows, we assume you
have at least a passing familiarity with Org-mode and Emacs
keybindings.
</p>
<p>
Please bear in mind that the discussion below is written as if a
person has launched <code>julia</code> with <code>M-x julia</code> and is sitting in front
of an ESS <code>julia</code> interactive session right now. But that isn't
required. In fact, one of the best things about Org-mode is that such
a thing in fact <b>is not</b> required, and a person can happily breeze
through an org file tapping <code>C-c C-c</code> as (s)he goes. For the purpose
of this introductory document it doesn't matter which approach you
use; be warned, however, that some of the lower code blocks depend on
values from the upper code blocks and if you try to execute them out
of order then you will get an error.
</p>
<div id="outline-container-1" class="outline-2">
<h2 id="sec-1"><span class="section-number-2">1</span> What you need to get started</h2>
<div class="outline-text-2" id="text-1">
<p>
You will need to install <a href="http://julialang.org" ><code>julia</code></a>, a recent version of <a href="http://ess.r-project.org" >ESS</a>, and an
updated version of <a href="http://orgmode.org" >Org-mode</a>. Instructions for how to accomplish all
three tasks are detailed in <a href="ob-julia-doc.html" >Org-mode and <code>julia</code>: an introduction</a>.
Please read that document first to get up to speed before continuing.
</p>
<p>
<b>Note:</b> several code blocks below have the header argument <code>:eval
no-export</code> which means that the code block can be evaluated
interactively in this session by <code>C-c C-c</code> with point in the code
block but will <i>not</i> be evaluated during export. The reason is that
those blocks have settings which conflict with my current setup yet
are meant to be useful for others people.
</p>
</div>
</div>
<div id="outline-container-2" class="outline-2">
<h2 id="sec-2"><span class="section-number-2">2</span> Getting started with julia</h2>
<div id="outline-container-2-1" class="outline-3">
<h3 id="sec-2-1"><span class="section-number-3">2.1</span> Communicating with julia</h3>
<div class="outline-text-3" id="text-2-1">
<p>
There are three basic methods (provided by ESS) for communicating with
<code>julia</code>.
</p>
<ul class="org-ul">
<li><b>An Interactive session (julia&gt;).</b> This is the most basic way to
complete simple, one-line commands. Do <code>M-x julia RET</code> during an
Emacs session and the Emacs/ESS <code>julia</code> mode will open in a buffer.
Type whatever command you like; <code>julia</code> will evaluate what is typed
there and output the results in the buffer. This method is akin to
launching <code>julia</code> in a terminal.
</li>
<li><b>Source files.</b> For longer programs (called <i>scripts</i>) there is too
much code to write all at once in an interactive session. Further,
sometimes we only wish to modify a small piece of the script and
before running it again in <code>julia</code>.
<p>
The way to do this is to open a dedicated <code>julia</code> script buffer with
the sequence <code>C-x C-f whatever.jl</code>, where <code>whatever.jl</code> is a <code>julia</code>
script which you've named whatever. Write the code in the buffer,
then when satisfied the user evaluates lines or regions according to
the following table. Then <code>julia</code> will evaluate the respective code
and give output in the interactive buffer.
</p>
<table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
<colgroup>
<col class="left"/>
<col class="left"/>
</colgroup>
<tbody>
<tr>
<td class="left"><code>C-RET</code></td>
<td class="left">Send region or current line and step to next line of code.</td>
</tr>
<tr>
<td class="left"><code>M-C-x</code></td>
<td class="left">Send region or function or paragraph.</td>
</tr>
<tr>
<td class="left"><code>C-c C-c</code></td>
<td class="left">Send region or function or paragraph and step to next line.</td>
</tr>
</tbody>
</table>
</li>
<li><b>Script mode.</b> It is also possible to write a <code>julia</code> script (say, <code>myscript.jl</code> and evaluate the script from a terminal like this:
<pre class="example">
~$ julia myscript.jl
</pre>
<p>
Depending on what's in the script, <code>julia</code> can be instructed to do
all sorts of things. See <code>julia --help</code> for additional
options. (Note: you will need to add <code>julia</code> to your <code>PATH</code> or
otherwise execute <code>julia</code> from its location before proceeding with
this method.)
</p>
</li>
</ul>
</div>
</div>
<div id="outline-container-2-2" class="outline-3">
<h3 id="sec-2-2"><span class="section-number-3">2.2</span> <code>julia</code> is one fancy calculator</h3>
<div class="outline-text-3" id="text-2-2">
<p>
<code>julia</code> can do any arithmetic you can imagine. For example, in an
interactive session type <code>2 + 3</code> and observe
</p>
<div class="org-src-container">
<pre class="src src-julia">2 + 3
</pre>
</div>
<pre class="example">
5
</pre>
<p>
The <code>julia></code> means that <code>julia</code> is waiting on your next command. Entry
numbers will be generated for each row, such as
</p>
<div class="org-src-container">
<pre class="src src-julia">[3:50]
</pre>
</div>
<pre class="example">
48-element Int32 Array:
3
4
5
6
7
8
9
10
11
12
41
42
43
44
45
46
47
48
49
50
</pre>
<p>
Notice that <code>julia</code> doesn't show the whole list of numbers, it elides
them with vertical ellipses \(\vdots\). Note also the <code>[3:50]</code>
notation, which generates all integers in sequence from 3 to 50. One
can also do things like
</p>
<div class="org-src-container">
<pre class="src src-julia">2 * 3 * 4 * 5 <span style="color: #b22222;"># </span><span style="color: #b22222;">multiply</span>
<span style="color: #0000ff;">sqrt</span>(10) <span style="color: #b22222;"># </span><span style="color: #b22222;">square root</span>
pi <span style="color: #b22222;"># </span><span style="color: #b22222;">pi</span>
<span style="color: #0000ff;">sqrt</span>(-2)
</pre>
</div>
<pre class="example">
120
3.1622776601683795
3.141592653589793
ERROR: DomainError()
in sqrt at math.jl:111
</pre>
<p>
Notice that a <code>DomainError()</code> was produced; we are not allowed to take
square roots of negative numbers. Also notice the number sign <code>#</code>,
which is used for comments. Everything typed on the same line after
the <code>#</code> will be ignored by julia. There is no <code>julia</code> continuation
prompt. If you press <code>RET</code> before a statement is complete then empty
lines keep piling up until you finish the command.
</p>
<p>
Some other fuctions that will be of use are <code>abs()</code> for absolute
value, <code>log()</code> for the natural logarithm, <code>exp()</code> for the exponential
function, and <code>factorial()</code> for&hellip; uh&hellip; factorials.
</p>
<p>
Assignment is useful for storing values to be used later. Notice the
semicolon at the end of the first statement. Without the semicolon,
<code>julia</code> would print the result of the assigment (namely, <code>5</code>).
</p>
<div class="org-src-container">
<pre class="src src-julia">y = 5; <span style="color: #b22222;"># </span><span style="color: #b22222;">stores the value 5 in y</span>
3 + y
</pre>
</div>
<pre class="example">
8
</pre>
<p>
There aren't other assignment operators (like <code><-</code> in R). For
variable names you can use letters (perhaps followed by) numbers,
and/or underscore "_" characters. You cannot use mathematical
operators, you cannot use dots, and numbers can't go in front of
numbers (those are interpreted by <code>julia</code> as coefficients). Here are
some valid variable names: <code>x</code>, <code>x1</code>, <code>y32</code>, <code>z_var</code>.
</p>
<p>
If you would like to enter the data 74,31,95,61,76,34,23,54,96 into
<code>julia</code>, you may create a data array with double brackets (the analogue
of the <code>c()</code> function in R).
</p>
<div class="org-src-container">
<pre class="src src-julia">fred = [74, 31, 95, 61, 76, 34, 23, 54, 96]
</pre>
</div>
<pre class="example">
9-element Int32 Array:
74
31
95
61
76
34
23
54
96
</pre>
<p>
The array <code>fred</code> has 9 entries. We can access individual components
with bracket <code>[ ]</code> notation:
</p>
<div class="org-src-container">
<pre class="src src-julia">fred[3]
fred[2:4]
fred[[1, 3, 5, 8]]
</pre>
</div>
<pre class="example">
95
3-element Int32 Array:
31
95
61
4-element Int32 Array:
74
95
76
54
</pre>
<p>
Notice we needed double brackets for the third example. If you would
like to empty the array <code>fred</code>, you can do it by typing <code>fred = []</code>.
</p>
<p>
Data arrays in <code>julia</code> have type. There are all sorts of integer types
(<code>Int8</code>, <code>uInt8</code>, <code>Int32</code>, &hellip;), strings (<code>ASCIIString</code>), logical
(<code>Bool</code>), unicode characters (<code>Char</code>), then there are floating-point
types (<code>Float16</code>, <code>Float32</code>), even complex numbers like <code>1 + 2im</code> and
even rational numbers like <code>3//4</code>, not to mention <code>Inf</code>, <code>-Inf</code>, and
<code>NaN</code> (which stands for <i>not a number</i>). If you ever want to know what
it is you're dealing with you can find out with the <code>typeof</code> function.
</p>
<div class="org-src-container">
<pre class="src src-julia">simpsons = [<span style="color: #8b2252;">"Homer"</span>, <span style="color: #8b2252;">"Marge"</span>, <span style="color: #8b2252;">"Bart"</span>, <span style="color: #8b2252;">"Lisa"</span>, <span style="color: #8b2252;">"Maggie"</span>];
<span style="color: #0000ff;">typeof</span>(simpsons)
</pre>
</div>
<pre class="example">
Array{ASCIIString,1}
</pre>
<p>
Here is an example of a logical vector:
</p>
<div class="org-src-container">
<pre class="src src-julia">x = 5;
x &gt;= 6
</pre>
</div>
<pre class="example">
false
</pre>
<p>
Notice the <code>>=</code> symbol which stands for "greater than or equal to".
Many functions in <code>julia</code> are vectorized. Once we have stored a data
vector then we can evaluate functions on it.
</p>
<div class="org-src-container">
<pre class="src src-julia"><span style="color: #0000ff;">sum</span>(fred)
<span style="color: #0000ff;">length</span>(fred)
<span style="color: #0000ff;">sum</span>(fred)/<span style="color: #0000ff;">length</span>(fred)
<span style="color: #0000ff;">mean</span>(fred) <span style="color: #b22222;"># </span><span style="color: #b22222;">sample mean, should be same answer</span>
</pre>
</div>
<pre class="example">
544
9
60.44444444444444
60.44444444444444
</pre>
<p>
Other popular functions for vectors are <code>min()</code>, <code>max()</code>, <code>sort()</code>,
and <code>cumsum()</code>.
</p>
<p>
Arithmetic in <code>julia</code> is usually done element-wise, and the operands
(usually) must be of conformable dimensions.
</p>
<div class="org-src-container">
<pre class="src src-julia">mary = [4, 5, 3, 6, 4, 6, 7, 3, 1];
fred + mary
fred - <span style="color: #0000ff;">mean</span>(mary)
</pre>
</div>
<pre class="example">
9-element Int32 Array:
78
36
98
67
80
40
30
57
97
9-element Float64 Array:
69.6667
26.6667
90.6667
56.6667
71.6667
29.6667
18.6667
49.6667
91.6667
</pre>
<p>
The operations <code>+</code> and <code>-</code> are performed element-wise. Notice in the
last vector that <code>mean(fred)</code> was subtracted from each entry in
turn. This is also known as data recycling. Other popular vectorizing
functions are <code>sin()</code>, <code>cos()</code>, <code>exp()</code>, <code>log()</code>, and <code>sqrt()</code>.
</p>
<p>
An operation which is <i>not</i> performed elementwise is array multiplication, <code>*</code>. If were were to try <code>fred*mary</code> then we would get an error:
</p>
<pre class="example">
ERROR: no method *(Array{Int32,1},Array{Int32,1})
</pre>
<p>
The reason for the error is that <code>julia</code> is trying to do matrix multiplication on two <code>9x1</code> arrays which, we know from Linear Algebra, is not allowed. Instead, we can accomplish element-wise multiplication with the following:
</p>
<div class="org-src-container">
<pre class="src src-julia">fred.*mary
</pre>
</div>
<pre class="example">
9-element Int32 Array:
296
155
285
366
304
204
161
162
96
</pre>
<p>
Notice the dot before the multiplication. A similar trick works for
elementwise division. By the way, with two <code>9x1</code> arrays it is legal
to compute the dot product like this:
</p>
<div class="org-src-container">
<pre class="src src-julia">fred<span style="color: #8b2252;">'*mary</span>
</pre>
</div>
<pre class="example">
1-element Int32 Array:
2029
</pre>
<p>
where notice we have transposed <code>fred</code> and done ordinary matrix
multiplication with <code>fred'*mary</code>.
</p>
</div>
</div>
<div id="outline-container-2-3" class="outline-3">
<h3 id="sec-2-3"><span class="section-number-3">2.3</span> Getting Help</h3>
<div class="outline-text-3" id="text-2-3">
<p>
When you get in the thick of <code>julia</code> you will soon find yourself
looking for help. The help resources for <code>julia</code> are not (yet) as
extensive as those for some other languages that have been around for
a while (such as R). <code>julia</code> is new and many of the help topics
haven't been written yet. Nevertheless, sometimes a person is lucky
and you can get help on a function when it's available with the
<code>help()</code> function.
</p>
<div class="org-src-container">
<pre class="src src-julia"><span style="color: #0000ff;">help</span>(<span style="color: #8b2252;">"factorial"</span>)
</pre>
</div>
<pre class="example">
Loading help data...
Base.factorial(n)
Factorial of n
Base.factorial(n, k)
Compute "factorial(n)/factorial(k)"
</pre>
<p>
In addition to this, you can type <code>help()</code> which gives an extended
list of help topics. For instance, I find myself doing
<code>help("Statistics")</code> a lot.
</p>
</div>
</div>
</div>
<div id="outline-container-3" class="outline-2">
<h2 id="sec-3"><span class="section-number-2">3</span> Other tips</h2>
<div class="outline-text-2" id="text-3">
<p>
It is unnecessary to retype commands repeatedly, since Emacs/ESS
remembers what you have entered at the <code>julia></code> prompt. To navigate
through previous commands put point at the lowest command line and
do either <code>M-p</code> or <code>M-n</code>.
</p>
</div>
<div id="outline-container-3-1" class="outline-3">
<h3 id="sec-3-1"><span class="section-number-3">3.1</span> Other resources</h3>
<div class="outline-text-3" id="text-3-1">
<ul class="org-ul">
<li>Check out the official <code>julia</code> manual <a href="http://docs.julialang.org/en/latest/manual/" >here</a>.
</li>
<li>The <i>Standard Library</i> (a different type of manual) is <a href="http://docs.julialang.org/en/latest/stdlib/" >here</a>.
</li>
<li>There is a vibrant and growing <code>julia</code> community whose gateway is <a href="http://julialang.org/community/" >here</a>.
</li>
<li>There is a large and growing list of contributed packages <a href="http://docs.julialang.org/en/latest/packages/packagelist/" >here</a>.
</li>
</ul>
</div>
</div>
</div>
<div id="outline-container-4" class="outline-2">
<h2 id="sec-4"><span class="section-number-2">4</span> Plotting with Winston</h2>
<div class="outline-text-2" id="text-4">
<p>
There's a pretty well fleshed out plotting example in the Graphics
section of <a href="ob-julia-doc.html" >Org-mode and <code>julia</code>: an introduction</a>. Check it out.
</p>
</div>
</div>
<div id="outline-container-5" class="outline-2">
<h2 id="sec-5"><span class="section-number-2">5</span> Fitting (generalized) linear models</h2>
<div class="outline-text-2" id="text-5">
<p>
Douglas Bates (of <a href="http://www.springer.com/statistics/statistical+theory+and+methods/book/978-1-4419-0317-4" >Mixed Effects Models in S and S-PLUS</a> fame) has been
putting together a <code>julia</code> package called GLM which already supports
fitting generalized linear models to datasets. This, together with
the RDatasets package means there is already a bunch of stuff to keep
a person busy. Below is a modified example from the Multiple
Regression chapter of IPSUR, translated to <code>julia</code> speak.
</p>
<p>
First, we start <code>using</code> the packages we'll need.
</p>
<div class="org-src-container">
<pre class="src src-julia">using RDatasets, DataFrames, Distributions, GLM
</pre>
</div>
<p>
Next we load the <code>trees</code> data frame from the RDatasets package (via
the DataFrames package) and fit a linear model to the data.
</p>
<div class="org-src-container">
<pre class="src src-julia">trees = <span style="color: #0000ff;">data</span>(<span style="color: #8b2252;">"datasets"</span>, <span style="color: #8b2252;">"trees"</span>)
treeslm = <span style="color: #0000ff;">lm</span>(:(Girth ~ Height + Volume), trees)
</pre>
</div>
<p>
There is a <i>ton</i> of output from both the above commands which we omit
here for the sake of brevity. Most of it, though, is similar to to
output we might see in an R session. We can extract the model
coefficients with the <code>coef</code> function:
</p>
<div class="org-src-container">
<pre class="src src-julia"><span style="color: #0000ff;">coef</span>(treeslm)
</pre>
</div>
<pre class="example">
3-element Float64 Array:
10.8164
-0.0454835
0.19518
</pre>
<p>
and we can finish by looking at a summary table similar to something
like <code>summary(treeslm)</code> in R.
</p>
<div class="org-src-container">
<pre class="src src-julia"><span style="color: #0000ff;">coeftable</span>(treeslm)
</pre>
</div>
<pre class="example">
3x4 DataFrame:
Estimate Std.Error t value Pr(&gt;|t|)
[1,] 10.8164 1.9732 5.48165 7.44691e-6
[2,] -0.0454835 0.0282621 -1.60935 0.118759
[3,] 0.19518 0.0109553 17.8161 8.2233e-17
</pre>
</div>
</div>
</div><div id="postamble">
<p class="date">Date: </p>
<p class="author">Author : G. Jay Kerns</p>
<p class="creator">Generated by <a href="http://orgmode.org">Org</a> mode 7.9.3f in <a href="http://www.gnu.org/software/emacs/">Emacs</a> 24.3.50.1.</p>
<a href="http://validator.w3.org/check?uri=referer">Validate XHTML 1.0</a>
</div>
</body>
</html>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Org-mode and julia: an introduction</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<meta name="title" content="Org-mode and julia: an introduction"/>
<meta name="generator" content="Org-mode"/>
<meta name="author" content="G. Jay Kerns"/>
<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
html { font-family: Times, serif; font-size: 12pt; }
.title { text-align: center; }
.todo { color: red; }
.done { color: green; }
.tag { background-color: #add8e6; font-weight:normal }
.target { }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.right {margin-left:auto; margin-right:0px; text-align:right;}
.left {margin-left:0px; margin-right:auto; text-align:left;}
.center {margin-left:auto; margin-right:auto; text-align:center;}
p.verse { margin-left: 3% }
pre {
border: 1pt solid #AEBDCC;
background-color: #F3F5F7;
padding: 5pt;
font-family: courier, monospace;
font-size: 90%;
overflow:auto;
}
table { border-collapse: collapse; }
td, th { vertical-align: top; }
th.right { text-align:center; }
th.left { text-align:center; }
th.center { text-align:center; }
td.right { text-align:right; }
td.left { text-align:left; }
td.center { text-align:center; }
dt { font-weight: bold; }
div.figure { padding: 0.5em; }
div.figure p { text-align: center; }
div.inlinetask {
padding:10px;
border:2px solid gray;
margin:10px;
background: #ffffcc;
}
textarea { overflow-x: auto; }
.linenr { font-size:smaller }
.code-highlighted {background-color:#ffff00;}
.org-info-js_info-navigation { border-style:none; }
#org-info-js_console-label { font-size:10px; font-weight:bold;
white-space:nowrap; }
.org-info-js_search-highlight {background-color:#ffff00; color:#000000;
font-weight:bold; }
/*]]>*/-->
</style>
<script type="text/javascript">
/*
@licstart The following is the entire license notice for the
JavaScript code in this tag.
Copyright (C) 2012 Free Software Foundation, Inc.
The JavaScript code in this tag is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License (GNU GPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later version. The code is distributed WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
As additional permission under GNU GPL version 3 section 7, you
may distribute non-source (e.g., minimized or compacted) forms of
that code without the copy of the GNU GPL normally required by
section 4, provided you include this license notice and a URL
through which recipients can access the Corresponding Source.
@licend The above is the entire license notice
for the JavaScript code in this tag.
*/
<!--/*--><![CDATA[/*><!--*/
function CodeHighlightOn(elem, id)
{
var target = document.getElementById(id);
if(null != target) {
elem.cacheClassElem = elem.className;
elem.cacheClassTarget = target.className;
target.className = "code-highlighted";
elem.className = "code-highlighted";
}
}
function CodeHighlightOff(elem, id)
{
var target = document.getElementById(id);
if(elem.cacheClassElem)
elem.className = elem.cacheClassElem;
if(elem.cacheClassTarget)
target.className = elem.cacheClassTarget;
}
/*]]>*///-->
</script>
<script type="text/javascript" src="http://orgmode.org/mathjax/MathJax.js">
<!--/*--><![CDATA[/*><!--*/
MathJax.Hub.Config({
// Only one of the two following lines, depending on user settings
// First allows browser-native MathML display, second forces HTML/CSS
// config: ["MMLorHTML.js"], jax: ["input/TeX"],
jax: ["input/TeX", "output/HTML-CSS"],
extensions: ["tex2jax.js","TeX/AMSmath.js","TeX/AMSsymbols.js",
"TeX/noUndefined.js"],
tex2jax: {
inlineMath: [ ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"], ["\\begin{displaymath}","\\end{displaymath}"] ],
skipTags: ["script","noscript","style","textarea","pre","code"],
ignoreClass: "tex2jax_ignore",
processEscapes: false,
processEnvironments: true,
preview: "TeX"
},
showProcessingMessages: true,
displayAlign: "center",
displayIndent: "2em",
"HTML-CSS": {
scale: 100,
availableFonts: ["STIX","TeX"],
preferredFont: "TeX",
webFont: "TeX",
imageFont: "TeX",
showMathMenu: true,
},
MMLorHTML: {
prefer: {
MSIE: "MML",
Firefox: "MML",
Opera: "HTML",
other: "HTML"
}
}
});
/*]]>*///-->
</script>
</head>
<body>
<div id="content">
<h1 class="title">Org-mode and julia: an introduction</h1>
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#sec-1">1. What you need to get started</a>
<ul>
<li><a href="#sec-1-1">1.1. Julia</a></li>
<li><a href="#sec-1-2">1.2. ESS - Emacs Speaks Statistics</a></li>
<li><a href="#sec-1-3">1.3. Add-on packages</a></li>
<li><a href="#sec-1-4">1.4. Org-mode</a></li>
<li><a href="#sec-1-5">1.5. <code>ob-julia.el</code></a></li>
</ul>
</li>
<li><a href="#sec-2">2. Evaluation inside the Org buffer</a>
<ul>
<li><a href="#sec-2-1">2.1. :results value</a></li>
<li><a href="#sec-2-2">2.2. :results output</a></li>
</ul>
</li>
<li><a href="#sec-3">3. Graphics</a>
<ul>
<li><a href="#sec-3-1">3.1. Plotting with Winston</a></li>
</ul>
</li>
<li><a href="#sec-4">4. Export to other formats</a>
<ul>
<li><a href="#sec-4-1">4.1. HTML</a></li>
<li><a href="#sec-4-2">4.2. LaTeX</a></li>
<li><a href="#sec-4-3">4.3. Beamer</a></li>
</ul>
</li>
<li><a href="#sec-5">5. Other things to mention</a></li>
</ul>
</div>
</div>
<p>
\newpage
</p>
<p>
This document is an introduction to Org-mode + <code>julia</code>. The only
prerequisites are a passing familiarity with Org-mode and Emacs
keybindings.
</p>
<div id="outline-container-1" class="outline-2">
<h2 id="sec-1"><span class="section-number-2">1</span> What you need to get started</h2>
<div class="outline-text-2" id="text-1">
<p>
<b>Note:</b> several code blocks below have the header argument <code>:eval
no-export</code>. This means that the code block can be evaluated
interactively by <code>C-c C-c</code> with point in the block but will <i>not</i> be
evaluated during export. That header argument is present because
those blocks have settings which conflict with my current setup (or
are otherwise redundant) yet are meant to be useful for other
people.
</p>
</div>
<div id="outline-container-1-1" class="outline-3">
<h3 id="sec-1-1"><span class="section-number-3">1.1</span> Julia</h3>
<div class="outline-text-3" id="text-1-1">
<p>
You are going to need a working installation of <code>julia</code>. The homepage
on <a href="https://github.com/JuliaLang/julia" >GitHub</a> has the pertinent links collected all in one place:
</p>
<ul class="org-ul">
<li><b>Homepage:</b> <a href="http://julialang.org" >http://julialang.org</a>
</li>
<li><b>Binaries:</b> <a href="http://code.google.com/p/julialang/downloads/list" >http://code.google.com/p/julialang/downloads/list</a>
</li>
<li><b>Packages:</b> <a href="http://docs.julialang.org/en/latest/packages/packagelist/" >http://docs.julialang.org/en/latest/packages/packagelist/</a>
</li>
<li><b>Mailing lists:</b> <a href="http://julialang.org/community/" >http://julialang.org/community/</a>
</li>
<li><b>IRC:</b> <a href="http://webchat.freenode.net/?channels=julia" >http://webchat.freenode.net/?channels=julia</a>
</li>
<li><b>Source code:</b> <a href="https://github.com/JuliaLang/julia" >https://github.com/JuliaLang/julia</a>
</li>
<li><b>Git clone URL:</b> <code>git://github.com/JuliaLang/julia.git</code>
</li>
<li><b>Documentation:</b> <a href="http://julialang.org/manual/" >http://julialang.org/manual/</a>
</li>
</ul>
<p>
<span style="text-decoration:underline;">Fair warning:</span> the initial install takes a <i>long time</i>, largely
because julia has a lot of dependencies. Never fear, though;
subsequent updates are brief.
</p>
</div>
</div>
<div id="outline-container-1-2" class="outline-3">
<h3 id="sec-1-2"><span class="section-number-3">1.2</span> ESS - Emacs Speaks Statistics</h3>
<div class="outline-text-3" id="text-1-2">
<p>
You are going to need a relavely bleeding-edge version of ESS since it
is only due to recent ESS changes that this document is even possible.
The place to look for the latest version of ESS is <a href="http://stat.ethz.ch/ESS/index.php?Section=download" >here</a>. At some
point after installation you will likely put something like the
following in your <code>.emacs</code>:
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(<span style="color: #a020f0;">require</span> '<span style="color: #008b8b;">ess-site</span>)
</pre>
</div>
<p>
Once ESS is up and running you will need to tell it where the <code>julia</code>
executable is. Edit the following and place it in your <code>.emacs</code>:
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(setq inferior-julia-program-name <span style="color: #8b2252;">"/path/to/julia-release-basic"</span>)
</pre>
</div>
<p>
After the above steps are complete then you should be able to start
Emacs and launch an interactive <code>julia</code> session via <code>M-x julia</code>. If
you manage to get that settled then at this point you should be able
to do everything in the <a href="intro-julia.html" >Introduction to Julia</a>.
</p>
</div>
</div>
<div id="outline-container-1-3" class="outline-3">
<h3 id="sec-1-3"><span class="section-number-3">1.3</span> Add-on packages</h3>
<div class="outline-text-3" id="text-1-3">
<p>
There is a growing list of <a href="http://docs.julialang.org/en/release-0.1/packages/packagelist/" >contibuted packages</a> which add to the base
functionality of <code>julia</code>. For example, several statistics packages
were mentioned a few moths ago in a blog post by <a href="https://github.com/johnmyleswhite" >John Myles White</a>
entitled <a href="http://www.johnmyleswhite.com/notebook/2012/12/02/the-state-of-statistics-in-julia/" >The State of Statistics in Julia</a>. The instructions in the
blog post are (already) a bit out-of-date; the currently recommended
way to install the packages is to launch an interactive <code>julia</code>
session and execute the following command:
</p>
<div class="org-src-container">
<pre class="src src-julia">Pkg.<span style="color: #0000ff;">add</span>(<span style="color: #8b2252;">"DataFrames"</span>, <span style="color: #8b2252;">"Distributions"</span>, <span style="color: #8b2252;">"GLM"</span>, <span style="color: #8b2252;">"MCMC"</span>, <span style="color: #8b2252;">"Optim"</span>,
<span style="color: #8b2252;">"NHST"</span>, <span style="color: #8b2252;">"Clustering"</span>)
</pre>
</div>
<p>
I recommend you <b>not</b> execute the <code>Pkg.add</code> command here (if you do it
in this buffer then you can't watch the download and install as it is
happening). As John notes, the <code>RDatasets</code> package takes a lot longer
to download than the others. Perhaps it would be wise to install it
separately.
</p>
<div class="org-src-container">
<pre class="src src-julia">Pkg.<span style="color: #0000ff;">add</span>(<span style="color: #8b2252;">"RDatasets"</span>)
</pre>
</div>
<p>
You will notice both <code>Pkg.add</code> code blocks have the <code>:eval never</code>
header argument.
</p>
</div>
</div>
<div id="outline-container-1-4" class="outline-3">
<h3 id="sec-1-4"><span class="section-number-3">1.4</span> Org-mode</h3>
<div class="outline-text-3" id="text-1-4">
<p>
Since you have at least a passing familiarity with org-mode then you
probably already have something like the following in your <code>.emacs</code>:
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(<span style="color: #a020f0;">require</span> '<span style="color: #008b8b;">org</span>)
</pre>
</div>
<p>
Another handy setting to have is
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(setq org-confirm-babel-evaluate nil)
</pre>
</div>
<p>
The following lines (either here or in your <code>.emacs</code>) permit inline
image display in the Emacs buffer.
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(add-hook 'org-babel-after-execute-hook 'org-display-inline-images)
(add-hook 'org-mode-hook 'org-display-inline-images)
</pre>
</div>
</div>
</div>
<div id="outline-container-1-5" class="outline-3">
<h3 id="sec-1-5"><span class="section-number-3">1.5</span> <code>ob-julia.el</code></h3>
<div class="outline-text-3" id="text-1-5">
<p>
You are going to want a copy of <code>ob-julia.el</code> to fully integrate
<code>julia</code> with Org-mode. You can find it and some other documents to
get you started <a href="https://github.com/gjkerns/ob-julia" >here</a>. Download <code>ob-julia.el</code> into a convenient place.
Edit the code block below and evaluate it by <code>C-c C-c</code> with point in
the code block.
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(load <span style="color: #8b2252;">"/path/to/ob-julia.el"</span>)
</pre>
</div>
<p>
An alternative method is to put the following in your <code>.emacs</code> (these
should go below the <code>(require 'org)</code> line):
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(add-to-list 'load-path <span style="color: #8b2252;">"/path/to/ob-julia.el"</span>)
(org-babel-do-load-languages
'org-babel-load-languages
'((emacs-lisp . t) (julia . t)))
</pre>
</div>
<p>
You are all set.
</p>
</div>
</div>
</div>
<div id="outline-container-2" class="outline-2">
<h2 id="sec-2"><span class="section-number-2">2</span> Evaluation inside the Org buffer</h2>
<div class="outline-text-2" id="text-2">
<p>
If you've gotten this far then everything is installed in the right
place and initialized properly. Now the fun begins.
</p>
</div>
<div id="outline-container-2-1" class="outline-3">
<h3 id="sec-2-1"><span class="section-number-3">2.1</span> :results value</h3>
</div>
<div id="outline-container-2-2" class="outline-3">
<h3 id="sec-2-2"><span class="section-number-3">2.2</span> :results output</h3>
</div>
</div>
<div id="outline-container-3" class="outline-2">
<h2 id="sec-3"><span class="section-number-2">3</span> Graphics</h2>
<div class="outline-text-2" id="text-3">
<p>
The most stable and fully featured of the <code>julia</code> graphics packages at
the time of this writing appears to be the <a href="https://github.com/nolta/Winston.jl" >Winston package</a>, although
the <a href="https://github.com/dcjones/Gadfly.jl" >Gadfly package</a> is also available and appears promising. To
install the Winston package execute the following in an interactive
session. As above I recommend you <b>not</b> execute this here (hence the
<code>:eval never</code> header argument).
</p>
<div class="org-src-container">
<pre class="src src-julia">Pkg.<span style="color: #0000ff;">add</span>(<span style="color: #8b2252;">"Winston"</span>)
</pre>
</div>
<p>
The Winston package has lots of dependencies and many of them must be
built from source (on Ubuntu).
</p>
</div>
<div id="outline-container-3-1" class="outline-3">
<h3 id="sec-3-1"><span class="section-number-3">3.1</span> Plotting with Winston</h3>
<div class="outline-text-3" id="text-3-1">
<p>
To get up and running with plots in <code>julia</code> check out the many example
graphs (with code) on the <a href="https://github.com/nolta/Winston.jl/blob/master/doc/examples.md" >Winston examples page</a>. As far as Org-mode is
concerned, you can do plotting
</p>
<ol class="org-ol">
<li>Interactively with a plot window,
</li>
<li>In-buffer with a <code>png</code>,
</li>
<li>Via export into LaTeX, HTML, Beamer&hellip;
</li>
</ol>
<p>
All three methods require setting up the plot object as a first step,
after, of course, loading the Winston package. Let's set up a simple
plot object (do <code>C-c C-c</code> with point in the block):
</p>
<div class="org-src-container">
<pre class="src src-julia">using Winston
x = <span style="color: #0000ff;">linspace</span>(0, 3pi, 100)
c = <span style="color: #0000ff;">cos</span>(x)
s = <span style="color: #0000ff;">sin</span>(x)
p = <span style="color: #0000ff;">FramedPlot</span>();
<span style="color: #0000ff;">setattr</span>(p, <span style="color: #8b2252;">"title"</span>, <span style="color: #8b2252;">"title!"</span>)
<span style="color: #0000ff;">setattr</span>(p, <span style="color: #8b2252;">"xlabel"</span>, L<span style="color: #8b2252;">"\Sigma x^2_i"</span>)
<span style="color: #0000ff;">setattr</span>(p, <span style="color: #8b2252;">"ylabel"</span>, L<span style="color: #8b2252;">"\Theta_i"</span>)
<span style="color: #0000ff;">add</span>(p, <span style="color: #0000ff;">FillBetween</span>(x, c, x, s) )
<span style="color: #0000ff;">add</span>(p, <span style="color: #0000ff;">Curve</span>(x, c, <span style="color: #8b2252;">"color"</span>, <span style="color: #8b2252;">"red"</span>) )
<span style="color: #0000ff;">add</span>(p, <span style="color: #0000ff;">Curve</span>(x, s, <span style="color: #8b2252;">"color"</span>, <span style="color: #8b2252;">"blue"</span>) )
</pre>
</div>
<p>
We did <code>:results silent</code> to omit the lengthy output from being
inserted in the org buffer. So the hard part is finished &ndash; we've
created a plot object <code>p</code> which is now available to manipulate.
</p>
<p>
To launch a plot window and look at the graph right now evaluate the
following code block.
</p>
<div class="org-src-container">
<pre class="src src-julia">Winston.<span style="color: #0000ff;">tk</span>(p)
</pre>
</div>
<p>
A plot should open in an X11 window with a pretty graph. Suppose
instead we'd like to insert the graph in the org buffer right now. We
need the inline-image display options described in section <i>Org
mode</i>. Assuming you've done that, evaluate the following code block.
</p>
<div class="org-src-container">
<pre class="src src-julia"><span style="color: #0000ff;">file</span>(p, <span style="color: #8b2252;">"example1.png"</span>)
</pre>
</div>
<p>
The code block evaluates the command <code>file(p, "example1.png")</code>, which
tells <code>julia</code> to write the graph to a <code>.png</code> file (also available are
<code>.pdf</code>, <code>.svg</code>, and <code>.eps</code>, though none of those can be inserted in
the org buffer). The header argument <code>:results graphics</code> tells
org-mode that the results are going to be graphics (as opposed to
elisp tables or STDOUT output) and the header argument <code>:file
example1.png</code> tells org to insert an link to the file <code>example1.png</code>
(just created by <code>julia</code>) right after the the code block. This link
is evaluated by <code>org-display-inline-images</code> which results in a <code>.png</code>
in the org buffer.
</p>
<p>
Notice that we had to specify the file name <i>twice</i>, once inside the
code block and once as a header argument. Some languages (such as R)
only require one specification: the header argument. The reason for
this is simple: <code>ob-R.el</code> includes code which dynamically constructs a
graphics device call behind the scenes, the call depending on the file
extension in the <code>:file</code> header argument. Such a thing is more
difficult with <code>julia</code> because different graphics packages have
markedly different device calls (for instance, <code>Gadfly</code> uses
<code>SVG("filename", p)</code>). Maybe someday the calls will stabilize and it
will make sense to write wrapper code to do that automatically. In
the meantime, use whatever package you like and write the filename
twice.
</p>
<p>
We'll defer the export method discussion to the next section.
</p>
</div>
</div>
</div>
<div id="outline-container-4" class="outline-2">
<h2 id="sec-4"><span class="section-number-2">4</span> Export to other formats</h2>
<div class="outline-text-2" id="text-4">
<p>
Sooner or later you will want to share your work with others, people
who have not (yet) fully come to the realization that Emacs+Org is
really quite better than sliced bread and also is destined to conquer
the entire observable Universe. Perhaps you'd like to make a
presentation about how awesome <code>julia</code> is at a(n) (inter)national
conference. Org-mode supports export to multiple formats. Here we'll
describe a few. There has been work recently on a brand new exporter
which hasn't yet made it to the official maintenance branch as of the
time of this writing. The following instructions apply to the new
exporter, which is one of the reasons why it was important in the
first section to update your Org-mode.
</p>
</div>
<div id="outline-container-4-1" class="outline-3">
<h3 id="sec-4-1"><span class="section-number-3">4.1</span> HTML</h3>
<div class="outline-text-3" id="text-4-1">
<p>
This is the easiest. Insert the following in your <code>.emacs</code>:
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(<span style="color: #a020f0;">require</span> '<span style="color: #008b8b;">ox-html</span>)
</pre>
</div>
<p>
Then open this file and execute <code>C-c C-e</code> to open the export
dispatcher. From there you have three options:
</p>
<ol class="org-ol">
<li><code>h H</code> exports as an HTML buffer (can be saved later),
</li>
<li><code>h h</code> exports as an HTML file (saved in the working directory),
</li>
<li><code>h o</code> exports as an HTML file and opens in a browser.
</li>
</ol>
<p>
That's it. There are a lot of other cool things you can do; see the
Org manual. If you export to HTML then you are going to want your
images (if any) to be <code>.png</code> or <code>.svg</code> files.
</p>
</div>
</div>
<div id="outline-container-4-2" class="outline-3">
<h3 id="sec-4-2"><span class="section-number-3">4.2</span> LaTeX</h3>
<div class="outline-text-3" id="text-4-2">
<p>
This one is just as easy. Insert the following in your <code>.emacs</code>:
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(<span style="color: #a020f0;">require</span> '<span style="color: #008b8b;">ox-latex</span>)
</pre>
</div>
<p>
Then open this file and do
</p>
<ol class="org-ol">
<li><code>C-c C-e l L</code> to export as a LaTeX buffer,
</li>
<li><code>C-c C-e l l</code> to export as a LaTeX file,
</li>
<li><code>C-c C-e l p</code> to export as LaTeX and generate a PDF,
</li>
<li><code>C-c C-e l o</code> to export as LaTeX, generate PDF, and open.
</li>
</ol>
<p>
There are a <i>ton</i> of other LaTeX things to do. See the Org manual.
If you export to PDF then it's fine to use image formats <code>.png</code>,
<code>.eps</code>, or <code>.pdf</code>, but the <code>.png</code> exports as a blurry raster image -
use <code>.pdf</code> instead (or <code>.eps</code> for external plain LaTeX export).
</p>
</div>
</div>
<div id="outline-container-4-3" class="outline-3">
<h3 id="sec-4-3"><span class="section-number-3">4.3</span> Beamer</h3>
<div class="outline-text-3" id="text-4-3">
<p>
Beamer is a special case unto itself. The short story is that you need
the following in your <code>.emacs</code>:
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(<span style="color: #a020f0;">require</span> '<span style="color: #008b8b;">ox-beamer</span>)
</pre>
</div>
<p>
Then also add an entry for the beamer class in your <code>.emacs</code>. Here is
a boilerplate version which you can customize to taste:
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(add-to-list 'org-latex-classes
'(<span style="color: #8b2252;">"beamer"</span>
<span style="color: #8b2252;">"\\documentclass[presentation]{beamer}</span>
<span style="color: #8b2252;"> \[DEFAULT-PACKAGES]</span>
<span style="color: #8b2252;"> \[PACKAGES]</span>
<span style="color: #8b2252;"> \[EXTRA]"</span>
(<span style="color: #8b2252;">"\\section{%s}"</span> . <span style="color: #8b2252;">"\\section*{%s}"</span>)
(<span style="color: #8b2252;">"\\subsection{%s}"</span> . <span style="color: #8b2252;">"\\subsection*{%s}"</span>)
(<span style="color: #8b2252;">"\\subsubsection{%s}"</span> . <span style="color: #8b2252;">"\\subsubsection*{%s}"</span>)))
</pre>
</div>
<p>
Since beamer is such a special case I have tweaked a minimal <code>julia</code>
beamer presentation in <a href="ob-julia-beamer.html" >Sample <code>julia</code> Presentation</a>. See there, see the
Org manual, and see Worg too for more information.
</p>
</div>
</div>
</div>
<div id="outline-container-5" class="outline-2">
<h2 id="sec-5"><span class="section-number-2">5</span> Other things to mention</h2>
<div class="outline-text-2" id="text-5">
<ul class="org-ul">
<li>You can extract all of the <code>julia</code> source code (also known as
<i>tangling</i> the Org document) with the keystrokes <code>C-c C-v t</code>. This
will generate a <code>julia</code> script (with extension <code>.jl</code>) in the working
directory. Note that this capability is turned off by default. You
can activate it by adding the header argument <code>:tangle yes</code> to those
code blocks you'd like to tangle or doing a buffer-wide header
setting with the line <code>#+PROPERTY: tangle yes</code> near the top of the
org file. See the Org manual for details.
</li>
<li>At the time of this writing <code>ob-julia.el</code> only supports <code>:session</code>
evaluation and does not support external process evaluation. This
means that every <code>SRC julia</code> block should have a <code>:session
SOMETHING</code> header argument. Alternatively, you can put a
buffer-wide header argument at the top of the org file, something
like this:
<pre class="example">
#+PROPERTY: session *julia*
</pre>
</li>
<li>You may have noticed that those <code>julia</code> code lines with no output
(for instance, lines with semicolons <code>;</code> at the end) generate an
empty line in the <code>#+RESULTS</code> below the code block. Consequently,
the first time you evaluate a <code>julia</code> code block without having
previously initiated a <code>julia</code> session with <code>M-x julia</code> the
<code>#+RESULTS</code> will have an extra mystery empty line. It is no
mystery. The first statement executed by ESS when loading <code>julia</code>
is an <code>include</code> command. That command has no output. If that empty
line bothers you then execute the code block again; the mystery
empty line will disappear.
</li>
<li>Be careful when executing code blocks with <code>:results value</code>. Code
block evaluation in that case works by writing the <code>julia</code> commands
to an external file in the <code>/tmp</code> directory, evaluating the commands
with <code>julia</code>, writing the results to a comma-separated (<code>.csv</code>)
file, then reading the <code>.csv</code> file and converting the result to
<code>elisp</code> for insertion to the org buffer. Not all object types are
supported by <code>julia</code> for writing to <code>.csv</code> files, in particular,
<code>1x1</code> matrices and arrays of ASCII characters are not supported
(yet). If you try to evaluate code blocks in those cases (or any
other case where output to <code>.csv</code> is not supported) then you will
get an error.
</li>
<li>After playing around with <code>julia</code> for a while you will notice that
instead of printing long arrays it will elide them with vertical
dots in the middle of the output which look similar to this \(
\vdots \) in the buffer. It turns out that LaTeX does not like
those three dots because they correspond to a special character, and
the upshot is that your org file will not export to LaTeX
successfully. One way around this is to explicitly declare that
special symbol in the LaTeX header. That is the reason for the
following line at the top of this org file.
<pre class="example">
#+LaTeX_HEADER: \DeclareUnicodeCharacter{22EE}{\vdots}
</pre>
</li>
<li><code>ob-julia.el</code> does not support <code>rownames</code> and <code>colnames</code> like
<code>ob-R.el</code> does.
</li>
</ul>
</div>
</div>
</div><div id="postamble">
<p class="date">Date: </p>
<p class="author">Author : G. Jay Kerns</p>
<p class="creator">Generated by <a href="http://orgmode.org">Org</a> mode 7.9.3f in <a href="http://www.gnu.org/software/emacs/">Emacs</a> 24.3.50.1.</p>
<a href="http://validator.w3.org/check?uri=referer">Validate XHTML 1.0</a>
</div>
</body>
</html>
#+TITLE: Introduction to julia
#+TITLE: Introduction to =julia=
#+AUTHOR: G. Jay Kerns
#+EMAIL: gkerns@ysu.edu
#+OPTIONS: H:2
......@@ -6,153 +6,62 @@
#+PROPERTY: results output
#+PROPERTY: session *julia*
#+PROPERTY: tangle yes
#+PROPERTY: eval no-export
#+LaTeX_HEADER: \DeclareUnicodeCharacter{22EE}{\vdots}
This document is a /brief/ introduction to =julia=. It is based on a
/Brief Introduction to R/ (an abbreviated Chapter 2 of [[http:ipsur.org][IPSUR]]) which I
usually distribute to students using R for the first time. One of the
reasons for this document is that I wanted to get better acquainted
with =julia= and make it easier for others to get better acquainted,
too.
\vspace{0.25in}
This document is a /brief/ introduction to =julia=. It is a reworked
/Brief Introduction to R/ (which is an abbreviated Chapter 2 of [[http:ipsur.org][IPSUR]])
which I usually distribute to students using R for the first time.
One of the reasons for this document is that I wanted to get better
acquainted with =julia= and thought it might make it easier for others
to get better acquainted with it, too. In what follows, we assume you
have at least a passing familiarity with Org-mode and Emacs
keybindings.
Please bear in mind that the discussion below is written as if a
person has launched =julia= with =M-x julia= and is sitting in front
of an ESS =julia= interactive session right now. But that isn't
required. In fact, one of the best things about Org-mode is that such
a thing in fact *is not* required, and a person can happily breeze
through an org file tapping =C-c C-c= as (s)he goes. For the purpose
of this introductory document it doesn't matter which approach you
use; be warned, however, that some of the lower code blocks depend on
values from the upper code blocks and if you try to execute them out
of order then you will get an error.
* What you need to get started
This document assumes you have at least a passing familiarity with
Org-mode and Emacs keybindings.
You will need to install [[http://julialang.org][=julia=]], a recent version of [[http://ess.r-project.org][ESS]], and an
updated version of [[http://orgmode.org][Org-mode]]. Instructions for how to accomplish all
three tasks are detailed in [[file:ob-julia-doc.org][Org-mode and =julia=: an introduction]].
Please read that document first to get up to speed before continuing.
#+BEGIN_SRC emacs-lisp :results silent :eval no-export
(load "/path/to/ob-julia.el")
(org-babel-julia-initiate-session "*julia*" nil)
#+END_SRC
- *Note:* a lot of the code blocks below have the header argument
=:eval no-export= which means that the code block can be evaluated
*Note:* several code blocks below have the header argument =:eval
no-export= which means that the code block can be evaluated
interactively in this session by =C-c C-c= with point in the code
block but will /not/ be evaluated during export. The reason is that
those blocks have settings which conflict with my current setup but
would be useful for others going through this document.
** Julia
- First install takes the longest, later updates not so bad.
- all the dependencies
** Add-on packages
Based on [[http://www.johnmyleswhite.com/notebook/2012/12/02/the-state-of-statistics-in-julia/][The State of Statistics in Julia]] by John Myles White.
#+BEGIN_SRC julia :eval never
Pkg.add("DataFrames", "Distributions", "GLM", "MCMC", "Optim",
"NHST", "Clustering")
#+END_SRC
#+BEGIN_SRC julia :eval never
Pkg.add("RDatasets")
#+END_SRC
*** Winston
The most stable and fully featured of the =julia= graphics packages at
the time of this writing appears to be the =Winston= package, though
the =Gadfly= package is available and looks promising.
#+BEGIN_SRC julia :eval never
Pkg.add("Winston")
#+END_SRC
The Winston package has lots of dependencies and many of them must be
built from source (on Ubuntu).
*** Gadfly
#+BEGIN_SRC julia :eval never
Pkg.add("Gadfly")
#+END_SRC
- packages take a lot longer to load than R
** Org-mode
This document assumes that you have at least a passing familiarity
with org-mode such that you likely have something like the following
already in your =.emacs=:
#+BEGIN_SRC emacs-lisp :eval never
(require 'org)
#+END_SRC
Another handy setting to have is
#+BEGIN_SRC emacs-lisp
(setq org-confirm-babel-evaluate nil)
#+END_SRC
In order to run this org file you will need to load =ob-julia.el= at
some point. One way is to edit the following code block and then =C-c
C-c= with point inside the block:
#+BEGIN_SRC emacs-lisp :results silent :eval no-export
(load "/path/to/ob-julia.el")
(org-babel-julia-initiate-session "*julia*" nil)
#+END_SRC
The first command loads the =ob-julia.el= file and the second
initiates a =julia= session in a buffer called =*julia*=. An
alternative method is to put the following in your =.emacs= (these
should go below the =(require 'org)= line):
#+BEGIN_SRC emacs-lisp :eval no-export
(add-to-list 'load-path "/path/to/ob-julia.el")
(org-babel-do-load-languages
'org-babel-load-languages
'((emacs-lisp . t)
(julia . t)))
#+END_SRC
The following lines (either here or in your =.emacs=) allow for inline
image display in the Emacs buffer.
#+BEGIN_SRC emacs-lisp :eval no-export
(add-hook 'org-babel-after-execute-hook 'org-display-inline-images)
(add-hook 'org-mode-hook 'org-display-inline-images)
#+END_SRC
If you'd like to do LaTeX export then put the following in your =.emacs=.
#+BEGIN_SRC emacs-lisp :eval never
(require 'ox-latex)
(require 'ox-beamer)
#+END_SRC
** ESS - Emacs Speaks Statistics
The place to get the latest version of ESS is [[http://stat.ethz.ch/ESS/index.php?Section=download][here]].
#+BEGIN_SRC emacs-lisp :eval never
(add-to-list 'load-path "/path/to/ESS/lisp")
(require 'ess-site)
#+END_SRC
#+BEGIN_SRC emacs-lisp :eval never
(setq inferior-julia-program-name "/path/to/julia-release-basic")
#+END_SRC
those blocks have settings which conflict with my current setup yet
are meant to be useful for others people.
* Getting started with julia
** Communicating with julia
There are three basic methods for communicating with julia.
There are three basic methods (provided by ESS) for communicating with
=julia=.
- *An Interactive session (julia>).* This is the most basic way to
complete simple, one-line commands. Do =M-x julia RET= during an
Emacs session and the Emacs/ESS =julia= mode will open in a buffer.
Type whatever command you like; =julia= will evaluate what is typed
there and output the results in the buffer.
there and output the results in the buffer. This method is akin to
launching =julia= in a terminal.
- *Source files.* For longer programs (called /scripts/) there is too
much code to write all at once in an interactive session. Also,
sometimes we only wish to modify a small piece of the script and run
it again in =julia=.
much code to write all at once in an interactive session. Further,
sometimes we only wish to modify a small piece of the script and
before running it again in =julia=.
The way to do this is to open a dedicated =julia= script buffer with
the sequence =C-x C-f whatever.jl=, where =whatever.jl= is a =julia=
......@@ -165,7 +74,15 @@ There are three basic methods for communicating with julia.
| =M-C-x= | Send region or function or paragraph. |
| =C-c C-c= | Send region or function or paragraph and step to next line. |
- *Script mode.* Hello there.
- *Script mode.* It is also possible to write a =julia= script (say, =myscript.jl= and evaluate the script from a terminal like this:
: ~$ julia myscript.jl
Depending on what's in the script, =julia= can be instructed to do
all sorts of things. See =julia --help= for additional
options. (Note: you will need to add =julia= to your =PATH= or
otherwise execute =julia= from its location before proceeding with
this method.)
** =julia= is one fancy calculator
......@@ -232,7 +149,7 @@ Notice that a =DomainError()= was produced; we are not allowed to take
square roots of negative numbers. Also notice the number sign =#=,
which is used for comments. Everything typed on the same line after
the =#= will be ignored by julia. There is no =julia= continuation
prompt. If you press =RET= before a statement is complete then empty
prompt. If you press =RET= before a statement is complete then empty
lines keep piling up until you finish the command.
Some other fuctions that will be of use are =abs()= for absolute
......@@ -248,15 +165,19 @@ y = 5; # stores the value 5 in y
3 + y
#+END_SRC
#+RESULTS:
:
: 8
There aren't other assignment operators (like =<-= in R). For
variable names you can use letters. (possibly followed by) numbers,
variable names you can use letters (perhaps followed by) numbers,
and/or underscore "_" characters. You cannot use mathematical
operators, you cannot use dots, and numbers can't go in front of
numbers (those are interpreted by =julia= as coefficients). Examples:
=x=, =x1=, =y32=, =z_var=.
numbers (those are interpreted by =julia= as coefficients). Here are
some valid variable names: =x=, =x1=, =y32=, =z_var=.
If you would like to enter the data 74,31,95,61,76,34,23,54,96 into
julia, you may create a data array with double brackets (the analogue
=julia=, you may create a data array with double brackets (the analogue
of the =c()= function in R).
#+BEGIN_SRC julia
......@@ -312,17 +233,12 @@ even rational numbers like =3//4=, not to mention =Inf=, =-Inf=, and
it is you're dealing with you can find out with the =typeof= function.
#+BEGIN_SRC julia
simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"]
simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"];
typeof(simpsons)
#+END_SRC
#+RESULTS:
: 5-element ASCIIString Array:
: "Homer"
: "Marge"
: "Bart"
: "Lisa"
: "Maggie"
:
: Array{ASCIIString,1}
Here is an example of a logical vector:
......@@ -344,7 +260,7 @@ vector then we can evaluate functions on it.
sum(fred)
length(fred)
sum(fred)/length(fred)
mean(fred) # sample mean, should be same answer
mean(fred) # sample mean, should be same answer
#+END_SRC
#+RESULTS:
......@@ -357,13 +273,12 @@ Other popular functions for vectors are =min()=, =max()=, =sort()=,
and =cumsum()=.
Arithmetic in =julia= is usually done element-wise, and the operands
must be of conformable dimensions.
(usually) must be of conformable dimensions.
#+BEGIN_SRC julia
fred2 = [4, 5, 3, 6, 4, 6, 7, 3, 1];
fred + fred2
fred - fred2
fred - mean(fred)
mary = [4, 5, 3, 6, 4, 6, 7, 3, 1];
fred + mary
fred - mean(mary)
#+END_SRC
#+RESULTS:
......@@ -379,26 +294,16 @@ fred - mean(fred)
30
57
97
9-element Int32 Array:
70
26
92
55
72
28
16
51
95
9-element Float64 Array:
13.5556
-29.4444
34.5556
0.555556
15.5556
-26.4444
-37.4444
-6.44444
35.5556
69.6667
26.6667
90.6667
56.6667
71.6667
29.6667
18.6667
49.6667
91.6667
#+end_example
The operations =+= and =-= are performed element-wise. Notice in the
......@@ -406,14 +311,50 @@ last vector that =mean(fred)= was subtracted from each entry in
turn. This is also known as data recycling. Other popular vectorizing
functions are =sin()=, =cos()=, =exp()=, =log()=, and =sqrt()=.
An operation which is /not/ performed elementwise is array multiplication, =*=. If were were to try =fred*mary= then we would get an error:
: ERROR: no method *(Array{Int32,1},Array{Int32,1})
The reason for the error is that =julia= is trying to do matrix multiplication on two =9x1= arrays which, we know from Linear Algebra, is not allowed. Instead, we can accomplish element-wise multiplication with the following:
#+BEGIN_SRC julia
fred.*mary
#+END_SRC
#+RESULTS:
#+begin_example
9-element Int32 Array:
296
155
285
366
304
204
161
162
96
#+end_example
Notice the dot before the multiplication. A similar trick works for
elementwise division. By the way, with two =9x1= arrays it is legal
to compute the dot product like this:
#+BEGIN_SRC julia
fred'*mary
#+END_SRC
where notice we have transposed =fred= and done ordinary matrix
multiplication with =fred'*mary=.
** Getting Help
When you are using =julia= it will not take long before you find
yourself needing help. The help resources for =julia= are not as
extensive as those for some other languages (such as R). =julia= is
new and many of the help topics haven't been written yet.
Nevertheless sometimes a person is lucky and you can get help on a
function when it's available with the =help()= function.
When you get in the thick of =julia= you will soon find yourself
looking for help. The help resources for =julia= are not (yet) as
extensive as those for some other languages that have been around for
a while (such as R). =julia= is new and many of the help topics
haven't been written yet. Nevertheless, sometimes a person is lucky
and you can get help on a function when it's available with the
=help()= function.
#+BEGIN_SRC julia
help("factorial")
......@@ -432,21 +373,12 @@ In addition to this, you can type =help()= which gives an extended
list of help topics. For instance, I find myself doing
=help("Statistics")= a lot.
Note also =example()=. This initiates the running of examples, if
available, of the use of the function specified by the argument.
* Other tips
It is unnecessary to retype commands repeatedly, since Emacs/ESS
remembers what you have entered at the =julia>= prompt. To navigate
through previous commands put point at the lowest command line and
push either =M-p= or =M-n=.
To find out what all variables are in the current work environment,
use the commands =ls()= or =objects()=. These list all available
objects in the workspace. If you wish to remove one or more variables,
use =remove(var1, var2)=, and to remove all of them use
=rm(list=ls())=.
do either =M-p= or =M-n=.
** Other resources
......@@ -457,23 +389,8 @@ use =remove(var1, var2)=, and to remove all of them use
* Plotting with Winston
#+BEGIN_SRC julia :results graphics :file example1.png :eval no-export
using Winston
x = linspace( 0, 3pi, 100 )
c = cos(x)
s = sin(x)
p = FramedPlot();
setattr(p, "title", "title!")
setattr(p, "xlabel", L"\Sigma x^2_i")
setattr(p, "ylabel", L"\Theta_i")
add(p, FillBetween(x, c, x, s) )
add(p, Curve(x, c, "color", "red") )
add(p, Curve(x, s, "color", "blue") )
file(p, "example1.png")
#+END_SRC
#+RESULTS:
[[file:example1.png]]
There's a pretty well fleshed out plotting example in the Graphics
section of [[file:ob-julia-doc.org][Org-mode and =julia=: an introduction]]. Check it out.
* Fitting (generalized) linear models
......@@ -484,31 +401,34 @@ the RDatasets package means there is already a bunch of stuff to keep
a person busy. Below is a modified example from the Multiple
Regression chapter of IPSUR, translated to =julia= speak.
First, we load the packages we'll need.
First, we start =using= the packages we'll need.
#+BEGIN_SRC julia :exports code
using RDatasets, DataFrames, Distributions, GLM
#+END_SRC
Next we load the =trees= data frame from the RDatasets package and fit
a linear model to the data.
#+RESULTS:
#+BEGIN_SRC julia :exports code
trees = data("datasets", "trees");
Next we load the =trees= data frame from the RDatasets package (via
the DataFrames package) and fit a linear model to the data.
#+BEGIN_SRC julia :exports code :results silent
trees = data("datasets", "trees")
treeslm = lm(:(Girth ~ Height + Volume), trees)
#+END_SRC
The extended output above should look similar to something we might
see in an R session. We can extract the model coefficients with the
=coef= function:
There is a /ton/ of output from both the above commands which we omit
here for the sake of brevity. Most of it, though, is similar to to
output we might see in an R session. We can extract the model
coefficients with the =coef= function:
#+BEGIN_SRC julia :exports code
#+BEGIN_SRC julia
coef(treeslm)
#+END_SRC
and we can finish by looking at a summary table similar to something
like =summary(treeslm)= in R.
#+BEGIN_SRC julia :exports code
#+BEGIN_SRC julia
coeftable(treeslm)
#+END_SRC
2 + 3
[3:50]
2 * 3 * 4 * 5 # multiply
sqrt(10) # square root
pi # pi
sqrt(-2)
y = 5; # stores the value 5 in y
3 + y
fred = [74, 31, 95, 61, 76, 34, 23, 54, 96]
fred[3]
fred[2:4]
fred[[1, 3, 5, 8]]
simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"];
typeof(simpsons)
x = 5;
x >= 6
sum(fred)
length(fred)
sum(fred)/length(fred)
mean(fred) # sample mean, should be same answer
mary = [4, 5, 3, 6, 4, 6, 7, 3, 1];
fred + mary
fred - mean(mary)
fred.*mary
fred'*mary
help("factorial")
using RDatasets, DataFrames, Distributions, GLM
trees = data("datasets", "trees")
treeslm = lm(:(Girth ~ Height + Volume), trees)
coef(treeslm)
coeftable(treeslm)
Pkg.add("DataFrames", "Distributions", "GLM", "MCMC", "Optim",
"NHST", "Clustering")
Pkg.add("RDatasets")
Pkg.add("Winston")
using Winston
x = linspace(0, 3pi, 100)
c = cos(x)
s = sin(x)
p = FramedPlot();
setattr(p, "title", "title!")
setattr(p, "xlabel", L"\Sigma x^2_i")
setattr(p, "ylabel", L"\Theta_i")
add(p, FillBetween(x, c, x, s) )
add(p, Curve(x, c, "color", "red") )
add(p, Curve(x, s, "color", "blue") )
Winston.tk(p)
file(p, "example1.png")
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Org-mode and julia: an introduction</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<meta name="title" content="Org-mode and julia: an introduction"/>
<meta name="generator" content="Org-mode"/>
<meta name="author" content="G. Jay Kerns"/>
<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
html { font-family: Times, serif; font-size: 12pt; }
.title { text-align: center; }
.todo { color: red; }
.done { color: green; }
.tag { background-color: #add8e6; font-weight:normal }
.target { }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.right {margin-left:auto; margin-right:0px; text-align:right;}
.left {margin-left:0px; margin-right:auto; text-align:left;}
.center {margin-left:auto; margin-right:auto; text-align:center;}
p.verse { margin-left: 3% }
pre {
border: 1pt solid #AEBDCC;
background-color: #F3F5F7;
padding: 5pt;
font-family: courier, monospace;
font-size: 90%;
overflow:auto;
}
table { border-collapse: collapse; }
td, th { vertical-align: top; }
th.right { text-align:center; }
th.left { text-align:center; }
th.center { text-align:center; }
td.right { text-align:right; }
td.left { text-align:left; }
td.center { text-align:center; }
dt { font-weight: bold; }
div.figure { padding: 0.5em; }
div.figure p { text-align: center; }
div.inlinetask {
padding:10px;
border:2px solid gray;
margin:10px;
background: #ffffcc;
}
textarea { overflow-x: auto; }
.linenr { font-size:smaller }
.code-highlighted {background-color:#ffff00;}
.org-info-js_info-navigation { border-style:none; }
#org-info-js_console-label { font-size:10px; font-weight:bold;
white-space:nowrap; }
.org-info-js_search-highlight {background-color:#ffff00; color:#000000;
font-weight:bold; }
/*]]>*/-->
</style><script type="text/javascript">
/*
@licstart The following is the entire license notice for the
JavaScript code in this tag.
Copyright (C) 2012 Free Software Foundation, Inc.
The JavaScript code in this tag is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License (GNU GPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later version. The code is distributed WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
As additional permission under GNU GPL version 3 section 7, you
may distribute non-source (e.g., minimized or compacted) forms of
that code without the copy of the GNU GPL normally required by
section 4, provided you include this license notice and a URL
through which recipients can access the Corresponding Source.
@licend The above is the entire license notice
for the JavaScript code in this tag.
*/
<!--/*--><![CDATA[/*><!--*/
function CodeHighlightOn(elem, id)
{
var target = document.getElementById(id);
if(null != target) {
elem.cacheClassElem = elem.className;
elem.cacheClassTarget = target.className;
target.className = "code-highlighted";
elem.className = "code-highlighted";
}
}
function CodeHighlightOff(elem, id)
{
var target = document.getElementById(id);
if(elem.cacheClassElem)
elem.className = elem.cacheClassElem;
if(elem.cacheClassTarget)
target.className = elem.cacheClassTarget;
}
/*]]>*///-->
</script>
</head>
<body>
<div id="content">
<h1 class="title">Org-mode and julia: an introduction</h1>
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#sec-1">1. What you need to get started</a>
<ul>
<li><a href="#sec-1-1">1.1. Julia</a></li>
<li><a href="#sec-1-2">1.2. Add on packages</a>
<ul>
<li><a href="#sec-1-2-1">1.2.1. Winston</a></li>
<li><a href="#sec-1-2-2">1.2.2. Gadfly</a></li>
</ul>
</li>
<li><a href="#sec-1-3">1.3. ESS</a></li>
<li><a href="#sec-1-4">1.4. Org-mode</a></li>
</ul>
</li>
<li><a href="#sec-2">2. Getting started</a></li>
<li><a href="#sec-3">3. Plotting with Winston</a></li>
<li><a href="#sec-4">4. Plotting with Gadfly</a></li>
<li><a href="#sec-5">5. Fitting linear models</a></li>
</ul>
</div>
</div>
<div id="outline-container-1" class="outline-2">
<h2 id="sec-1"><span class="section-number-2">1</span> What you need to get started</h2>
<div class="outline-text-2" id="text-1">
<div class="org-src-container">
<pre class="src src-emacs-lisp">(load <span style="color: #8b2252;">"~/gitm/projects/ob-julia.el"</span>)
(org-babel-julia-initiate-session <span style="color: #8b2252;">"*julia*"</span> nil)
</pre>
</div>
<div class="org-src-container">
<pre class="src src-julia"><span style="color: #0000ff;">rand</span>(9)
</pre>
</div>
<pre class="example">
9-element Float64 Array:
0.683697
0.115187
0.65871
0.126754
0.296551
0.117243
0.952961
0.74621
0.92133
</pre>
</div>
<div id="outline-container-1-1" class="outline-3">
<h3 id="sec-1-1"><span class="section-number-3">1.1</span> Julia</h3>
<div class="outline-text-3" id="text-1-1">
<ul class="org-ul">
<li>First install takes the longest, later updates not so bad.
</li>
<li>all the dependencies
</li>
</ul>
</div>
</div>
<div id="outline-container-1-2" class="outline-3">
<h3 id="sec-1-2"><span class="section-number-3">1.2</span> Add on packages</h3>
<div class="outline-text-3" id="text-1-2">
<p>
Based on <a href="http://www.johnmyleswhite.com/notebook/2012/12/02/the-state-of-statistics-in-julia/" >The State of Statistics in Julia</a> by John Myles White.
</p>
<div class="org-src-container">
<pre class="src src-julia">Pkg.<span style="color: #0000ff;">add</span>(<span style="color: #8b2252;">"DataFrames"</span>, <span style="color: #8b2252;">"Distributions"</span>, <span style="color: #8b2252;">"MCMC"</span>, <span style="color: #8b2252;">"Optim"</span>, <span style="color: #8b2252;">"NHST"</span>, <span style="color: #8b2252;">"Clustering"</span>)
</pre>
</div>
<div class="org-src-container">
<pre class="src src-julia">Pkg.<span style="color: #0000ff;">add</span>(<span style="color: #8b2252;">"RDatasets"</span>)
</pre>
</div>
<p>
This one is pretty big.
</p>
</div>
<div id="outline-container-1-2-1" class="outline-4">
<h4 id="sec-1-2-1"><span class="section-number-4">1.2.1</span> Winston</h4>
<div class="outline-text-4" id="text-1-2-1">
<div class="org-src-container">
<pre class="src src-julia">Pkg.<span style="color: #0000ff;">add</span>(<span style="color: #8b2252;">"Winston"</span>)
</pre>
</div>
<p>
This one has lots of dependencies.
</p>
</div>
</div>
<div id="outline-container-1-2-2" class="outline-4">
<h4 id="sec-1-2-2"><span class="section-number-4">1.2.2</span> Gadfly</h4>
<div class="outline-text-4" id="text-1-2-2">
<div class="org-src-container">
<pre class="src src-julia">Pkg.<span style="color: #0000ff;">add</span>(<span style="color: #8b2252;">"Gadfly"</span>)
</pre>
</div>
<ul class="org-ul">
<li>packages take a lot longer to load than R
</li>
</ul>
</div>
</div>
</div>
<div id="outline-container-1-3" class="outline-3">
<h3 id="sec-1-3"><span class="section-number-3">1.3</span> ESS</h3>
<div class="outline-text-3" id="text-1-3">
<p>
<a href="http://stat.ethz.ch/ESS/index.php?Section=download" >http://stat.ethz.ch/ESS/index.php?Section=download</a>
</p>
<div class="org-src-container">
<pre class="src src-julia"><span style="color: #0000ff;">rand</span>(9)
<span style="color: #0000ff;">print</span>(<span style="color: #8b2252;">"hello"</span>)
</pre>
</div>
<pre class="example">
9-element Float64 Array:
0.914156
0.489364
0.840862
0.389737
0.914611
0.398722
0.298391
0.592467
0.0428432
hello
</pre>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(add-to-list 'load-path <span style="color: #8b2252;">"~/path/to/ESS/lisp"</span>)
(<span style="color: #a020f0;">require</span> '<span style="color: #008b8b;">ess-site</span>)
</pre>
</div>
</div>
</div>
<div id="outline-container-1-4" class="outline-3">
<h3 id="sec-1-4"><span class="section-number-3">1.4</span> Org-mode</h3>
<div class="outline-text-3" id="text-1-4">
<div class="org-src-container">
<pre class="src src-emacs-lisp">(setq inferior-julia-program-name <span style="color: #8b2252;">"~/path/to/julia-release-basic"</span>)
</pre>
</div>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(org-babel-do-load-languages
'org-babel-load-languages
'((emacs-lisp . t)
(julia . t)))
</pre>
</div>
<p>
For inline image display
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(add-hook 'org-babel-after-execute-hook 'org-display-inline-images)
(add-hook 'org-mode-hook 'org-display-inline-images)
</pre>
</div>
</div>
</div>
</div>
<div id="outline-container-2" class="outline-2">
<h2 id="sec-2"><span class="section-number-2">2</span> Getting started</h2>
<div class="outline-text-2" id="text-2">
<div class="org-src-container">
<pre class="src src-julia">[3:50]
x = [3:6]
y = [5:11]
z = [4:7]
x + z
ans
<span style="color: #0000ff;">sum</span>(x)
<span style="color: #0000ff;">mean</span>(x)
<span style="color: #0000ff;">exp</span>(x)
<span style="color: #0000ff;">log</span>(x)
<span style="color: #0000ff;">sort</span>(x)
<span style="color: #0000ff;">sqrt</span>(x)
<span style="color: #0000ff;">diff</span>(x)
x[3]
y[2:4]
<span style="color: #0000ff;">typeof</span>(x)
1.0
1.
<span style="color: #008b8b;">Inf</span>
-<span style="color: #008b8b;">Inf</span>
<span style="color: #008b8b;">NaN</span>
<span style="color: #008b8b;">true</span>
<span style="color: #008b8b;">false</span>
1 + 2im
</pre>
</div>
</div>
</div>
<div id="outline-container-3" class="outline-2">
<h2 id="sec-3"><span class="section-number-2">3</span> Plotting with Winston</h2>
<div class="outline-text-2" id="text-3">
<div class="org-src-container">
<pre class="src src-julia">using Winston
x = <span style="color: #0000ff;">linspace</span>( 0, 3pi, 100 )
c = <span style="color: #0000ff;">cos</span>(x)
s = <span style="color: #0000ff;">sin</span>(x)
p = <span style="color: #0000ff;">FramedPlot</span>();
<span style="color: #0000ff;">setattr</span>(p, <span style="color: #8b2252;">"title"</span>, <span style="color: #8b2252;">"title!"</span>)
<span style="color: #0000ff;">setattr</span>(p, <span style="color: #8b2252;">"xlabel"</span>, L<span style="color: #8b2252;">"\Sigma x^2_i"</span>)
<span style="color: #0000ff;">setattr</span>(p, <span style="color: #8b2252;">"ylabel"</span>, L<span style="color: #8b2252;">"\Theta_i"</span>)
<span style="color: #0000ff;">add</span>(p, <span style="color: #0000ff;">FillBetween</span>(x, c, x, s) )
<span style="color: #0000ff;">add</span>(p, <span style="color: #0000ff;">Curve</span>(x, c, <span style="color: #8b2252;">"color"</span>, <span style="color: #8b2252;">"red"</span>) )
<span style="color: #0000ff;">add</span>(p, <span style="color: #0000ff;">Curve</span>(x, s, <span style="color: #8b2252;">"color"</span>, <span style="color: #8b2252;">"blue"</span>) )
<span style="color: #0000ff;">file</span>(p, <span style="color: #8b2252;">"blah2.png"</span>)
</pre>
</div>
<div class="figure">
<p><img src="blah2.png" alt="blah2.png"/></p>
<p></p>
</div>
</div>
</div>
<div id="outline-container-4" class="outline-2">
<h2 id="sec-4"><span class="section-number-2">4</span> Plotting with Gadfly</h2>
<div class="outline-text-2" id="text-4">
<div class="org-src-container">
<pre class="src src-julia">using RDatasets
using Gadfly
using Compose
iris = <span style="color: #0000ff;">data</span>(<span style="color: #8b2252;">"datasets"</span>, <span style="color: #8b2252;">"iris"</span>)
p = <span style="color: #0000ff;">plot</span>(iris, {:x =&gt; <span style="color: #8b2252;">"Sepal.Length"</span>, :y =&gt; <span style="color: #8b2252;">"Sepal.Width"</span>}, Geom.point);
<span style="color: #0000ff;">SVG</span>(<span style="color: #8b2252;">"iris_plot.svg"</span>, 6inch, 4inch)
</pre>
</div>
</div>
</div>
<div id="outline-container-5" class="outline-2">
<h2 id="sec-5"><span class="section-number-2">5</span> Fitting linear models</h2>
</div>
</div><div id="postamble">
<p class="date">Date: </p>
<p class="author">Author : G. Jay Kerns</p>
<p class="creator">Generated by <a href="http://orgmode.org">Org</a> mode 7.9.3f in <a href="http://www.gnu.org/software/emacs/">Emacs</a> 24.3.50.1.</p>
<a href="http://validator.w3.org/check?uri=referer">Validate XHTML 1.0</a>
</div>
</body>
</html>
......@@ -8,21 +8,21 @@
#+PROPERTY: tangle yes
#+LaTeX_HEADER: \DeclareUnicodeCharacter{22EE}{\vdots}
\newpage
This document is an introduction to Org-mode + =julia=. The only
prerequisites are a passing familiarity with Org-mode and Emacs
keybindings.
\newpage
* What you need to get started
- *Note:* several code blocks below have the header argument =:eval
*Note:* several code blocks below have the header argument =:eval
no-export=. This means that the code block can be evaluated
interactively by =C-c C-c= with point in the code block but will
/not/ be evaluated during export. That header argument is present
because those blocks have settings which conflict with my current
setup (or are otherwise redundant) yet are meant to be useful for
other people working through this document.
interactively by =C-c C-c= with point in the block but will /not/ be
evaluated during export. That header argument is present because
those blocks have settings which conflict with my current setup (or
are otherwise redundant) yet are meant to be useful for other
people.
** Julia
......@@ -76,18 +76,24 @@ blog post are (already) a bit out-of-date; the currently recommended
way to install the packages is to launch an interactive =julia=
session and execute the following command:
#+BEGIN_SRC julia :eval no-export
#+BEGIN_SRC julia :eval never
Pkg.add("DataFrames", "Distributions", "GLM", "MCMC", "Optim",
"NHST", "Clustering")
#+END_SRC
As John notes, the =RDatasets= package takes a lot longer to download
than the others. Perhaps it would be wise to install it separately.
I recommend you *not* execute the =Pkg.add= command here (if you do it
in this buffer then you can't watch the download and install as it is
happening). As John notes, the =RDatasets= package takes a lot longer
to download than the others. Perhaps it would be wise to install it
separately.
#+BEGIN_SRC julia :eval no-export
#+BEGIN_SRC julia :eval never
Pkg.add("RDatasets")
#+END_SRC
You will notice both =Pkg.add= code blocks have the =:eval never=
header argument.
** Org-mode
Since you have at least a passing familiarity with org-mode then you
......@@ -150,9 +156,8 @@ The most stable and fully featured of the =julia= graphics packages at
the time of this writing appears to be the [[https://github.com/nolta/Winston.jl][Winston package]], although
the [[https://github.com/dcjones/Gadfly.jl][Gadfly package]] is also available and appears promising. To
install the Winston package execute the following in an interactive
session. I recommend you *not* execute this here (if you do it in
this buffer then you can't watch the download and install as it is
happening).
session. As above I recommend you *not* execute this here (hence the
=:eval never= header argument).
#+BEGIN_SRC julia :eval never
Pkg.add("Winston")
......@@ -370,5 +375,6 @@ Org manual, and see Worg too for more information.
: #+LaTeX_HEADER: \DeclareUnicodeCharacter{22EE}{\vdots}
- =ob-julia.el= does not support =rownames= and =colnames= like =ob-R.el= does.
- =ob-julia.el= does not support =rownames= and =colnames= like
=ob-R.el= does.
;;; ob-julia.el --- org-babel functions for julia code evaluation
;; Copyright (C) 2013 G. Jay Kerns
;; Copyright (C) 2013
;; Author: G. Jay Kerns, based on ob-R.el by Eric Schulte and Dan Davison
;; Org-Babel support for evaluating julia code
......@@ -240,12 +240,6 @@ last statement in BODY, as elisp."
(org-babel-comint-eval-invisibly-and-wait-for-file
session tmp-file
(format org-babel-julia-write-object-command
;; don't need row or column names for julia
;; only need filename and object name
; (if row-names-p "TRUE" "FALSE")
; (if column-names-p
; (if row-names-p "NA" "TRUE")
; "FALSE")
(org-babel-process-file-name tmp-file 'noquote) "ans"))
(org-babel-julia-process-value-result
(org-babel-result-cond result-params
......
% Created 2013-03-02 Sat 21:14
\documentclass[11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{fixltx2e}
\usepackage{graphicx}
\usepackage{longtable}
\usepackage{float}
\usepackage{wrapfig}
\usepackage{soul}
\usepackage{textcomp}
\usepackage{marvosym}
\usepackage{wasysym}
\usepackage{latexsym}
\usepackage{amssymb}
\usepackage{hyperref}
\tolerance=1000
\DeclareUnicodeCharacter{22EE}{\vdots}
\author{G. Jay Kerns}
\date{\today}
\title{Introduction to \texttt{julia}}
\hypersetup{
pdfkeywords={},
pdfsubject={},
pdfcreator={Generated by Org mode 7.9.3f in Emacs 24.3.50.1.}}
\begin{document}
\maketitle
\tableofcontents
\vspace{0.25in}
This document is a \emph{brief} introduction to \texttt{julia}. It is a reworked
\emph{Brief Introduction to R} (which is an abbreviated Chapter 2 of \href{http:ipsur.org}{IPSUR})
which I usually distribute to students using R for the first time.
One of the reasons for this document is that I wanted to get better
acquainted with \texttt{julia} and thought it might make it easier for others
to get better acquainted with it, too. In what follows, we assume you
have at least a passing familiarity with Org-mode and Emacs
keybindings.
Please bear in mind that the discussion below is written as if a
person has launched \texttt{julia} with \texttt{M-x julia} and is sitting in front
of an ESS \texttt{julia} interactive session right now. But that isn't
required. In fact, one of the best things about Org-mode is that such
a thing in fact \textbf{is not} required, and a person can happily breeze
through an org file tapping \texttt{C-c C-c} as (s)he goes. For the purpose
of this introductory document it doesn't matter which approach you
use; be warned, however, that some of the lower code blocks depend on
values from the upper code blocks and if you try to execute them out
of order then you will get an error.
\section[What you need to get started]{What you need to get started}
\label{sec-1}
You will need to install \href{http://julialang.org}{\texttt{julia}}, a recent version of \href{http://ess.r-project.org}{ESS}, and an
updated version of \href{http://orgmode.org}{Org-mode}. Instructions for how to accomplish all
three tasks are detailed in \href{file://ob-julia-doc.org}{Org-mode and \texttt{julia}: an introduction}.
Please read that document first to get up to speed before continuing.
\textbf{Note:} several code blocks below have the header argument \texttt{:eval
no-export} which means that the code block can be evaluated
interactively in this session by \texttt{C-c C-c} with point in the code
block but will \emph{not} be evaluated during export. The reason is that
those blocks have settings which conflict with my current setup yet
are meant to be useful for others people.
\section[Getting started with julia]{Getting started with julia}
\label{sec-2}
\subsection[Communicating with julia]{Communicating with julia}
\label{sec-2-1}
There are three basic methods (provided by ESS) for communicating with
\texttt{julia}.
\begin{itemize}
\item \textbf{An Interactive session (julia>).} This is the most basic way to
complete simple, one-line commands. Do \texttt{M-x julia RET} during an
Emacs session and the Emacs/ESS \texttt{julia} mode will open in a buffer.
Type whatever command you like; \texttt{julia} will evaluate what is typed
there and output the results in the buffer. This method is akin to
launching \texttt{julia} in a terminal.
\item \textbf{Source files.} For longer programs (called \emph{scripts}) there is too
much code to write all at once in an interactive session. Further,
sometimes we only wish to modify a small piece of the script and
before running it again in \texttt{julia}.
The way to do this is to open a dedicated \texttt{julia} script buffer with
the sequence \texttt{C-x C-f whatever.jl}, where \texttt{whatever.jl} is a \texttt{julia}
script which you've named whatever. Write the code in the buffer,
then when satisfied the user evaluates lines or regions according to
the following table. Then \texttt{julia} will evaluate the respective code
and give output in the interactive buffer.
\begin{center}
\begin{tabular}{ll}
\texttt{C-RET} & Send region or current line and step to next line of code.\\
\texttt{M-C-x} & Send region or function or paragraph.\\
\texttt{C-c C-c} & Send region or function or paragraph and step to next line.\\
\end{tabular}
\end{center}
\item \textbf{Script mode.} It is also possible to write a \texttt{julia} script (say, \texttt{myscript.jl} and evaluate the script from a terminal like this:
\begin{verbatim}
~$ julia myscript.jl
\end{verbatim}
Depending on what's in the script, \texttt{julia} can be instructed to do
all sorts of things. See \texttt{julia -{}-help} for additional
options. (Note: you will need to add \texttt{julia} to your \texttt{PATH} or
otherwise execute \texttt{julia} from its location before proceeding with
this method.)
\end{itemize}
\subsection[\texttt{julia} is one fancy calculator]{\texttt{julia} is one fancy calculator}
\label{sec-2-2}
\texttt{julia} can do any arithmetic you can imagine. For example, in an
interactive session type \texttt{2 + 3} and observe
\begin{verbatim}
2 + 3
\end{verbatim}
\begin{verbatim}
5
\end{verbatim}
The \texttt{julia>} means that \texttt{julia} is waiting on your next command. Entry
numbers will be generated for each row, such as
\begin{verbatim}
[3:50]
\end{verbatim}
\begin{verbatim}
48-element Int32 Array:
3
4
5
6
7
8
9
10
11
12
41
42
43
44
45
46
47
48
49
50
\end{verbatim}
Notice that \texttt{julia} doesn't show the whole list of numbers, it elides
them with vertical ellipses \(\vdots\). Note also the \texttt{[3:50]}
notation, which generates all integers in sequence from 3 to 50. One
can also do things like
\begin{verbatim}
2 * 3 * 4 * 5 # multiply
sqrt(10) # square root
pi # pi
sqrt(-2)
\end{verbatim}
\begin{verbatim}
120
3.1622776601683795
3.141592653589793
ERROR: DomainError()
in sqrt at math.jl:111
\end{verbatim}
Notice that a \texttt{DomainError()} was produced; we are not allowed to take
square roots of negative numbers. Also notice the number sign \texttt{\#},
which is used for comments. Everything typed on the same line after
the \texttt{\#} will be ignored by julia. There is no \texttt{julia} continuation
prompt. If you press \texttt{RET} before a statement is complete then empty
lines keep piling up until you finish the command.
Some other fuctions that will be of use are \texttt{abs()} for absolute
value, \texttt{log()} for the natural logarithm, \texttt{exp()} for the exponential
function, and \texttt{factorial()} for\ldots{} uh\ldots{} factorials.
Assignment is useful for storing values to be used later. Notice the
semicolon at the end of the first statement. Without the semicolon,
\texttt{julia} would print the result of the assigment (namely, \texttt{5}).
\begin{verbatim}
y = 5; # stores the value 5 in y
3 + y
\end{verbatim}
\begin{verbatim}
8
\end{verbatim}
There aren't other assignment operators (like \texttt{<-} in R). For
variable names you can use letters (perhaps followed by) numbers,
and/or underscore "\_" characters. You cannot use mathematical
operators, you cannot use dots, and numbers can't go in front of
numbers (those are interpreted by \texttt{julia} as coefficients). Here are
some valid variable names: \texttt{x}, \texttt{x1}, \texttt{y32}, \texttt{z\_var}.
If you would like to enter the data 74,31,95,61,76,34,23,54,96 into
\texttt{julia}, you may create a data array with double brackets (the analogue
of the \texttt{c()} function in R).
\begin{verbatim}
fred = [74, 31, 95, 61, 76, 34, 23, 54, 96]
\end{verbatim}
\begin{verbatim}
9-element Int32 Array:
74
31
95
61
76
34
23
54
96
\end{verbatim}
The array \texttt{fred} has 9 entries. We can access individual components
with bracket \texttt{[ ]} notation:
\begin{verbatim}
fred[3]
fred[2:4]
fred[[1, 3, 5, 8]]
\end{verbatim}
\begin{verbatim}
95
3-element Int32 Array:
31
95
61
4-element Int32 Array:
74
95
76
54
\end{verbatim}
Notice we needed double brackets for the third example. If you would
like to empty the array \texttt{fred}, you can do it by typing \texttt{fred = []}.
Data arrays in \texttt{julia} have type. There are all sorts of integer types
(\texttt{Int8}, \texttt{uInt8}, \texttt{Int32}, \ldots{}), strings (\texttt{ASCIIString}), logical
(\texttt{Bool}), unicode characters (\texttt{Char}), then there are floating-point
types (\texttt{Float16}, \texttt{Float32}), even complex numbers like \texttt{1 + 2im} and
even rational numbers like \texttt{3//4}, not to mention \texttt{Inf}, \texttt{-Inf}, and
\texttt{NaN} (which stands for \emph{not a number}). If you ever want to know what
it is you're dealing with you can find out with the \texttt{typeof} function.
\begin{verbatim}
simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"];
typeof(simpsons)
\end{verbatim}
\begin{verbatim}
Array{ASCIIString,1}
\end{verbatim}
Here is an example of a logical vector:
\begin{verbatim}
x = 5;
x >= 6
\end{verbatim}
\begin{verbatim}
false
\end{verbatim}
Notice the \verb~>=~ symbol which stands for "greater than or equal to".
Many functions in \texttt{julia} are vectorized. Once we have stored a data
vector then we can evaluate functions on it.
\begin{verbatim}
sum(fred)
length(fred)
sum(fred)/length(fred)
mean(fred) # sample mean, should be same answer
\end{verbatim}
\begin{verbatim}
544
9
60.44444444444444
60.44444444444444
\end{verbatim}
Other popular functions for vectors are \texttt{min()}, \texttt{max()}, \texttt{sort()},
and \texttt{cumsum()}.
Arithmetic in \texttt{julia} is usually done element-wise, and the operands
(usually) must be of conformable dimensions.
\begin{verbatim}
mary = [4, 5, 3, 6, 4, 6, 7, 3, 1];
fred + mary
fred - mean(mary)
\end{verbatim}
\begin{verbatim}
9-element Int32 Array:
78
36
98
67
80
40
30
57
97
9-element Float64 Array:
69.6667
26.6667
90.6667
56.6667
71.6667
29.6667
18.6667
49.6667
91.6667
\end{verbatim}
The operations \texttt{+} and \texttt{-} are performed element-wise. Notice in the
last vector that \texttt{mean(fred)} was subtracted from each entry in
turn. This is also known as data recycling. Other popular vectorizing
functions are \texttt{sin()}, \texttt{cos()}, \texttt{exp()}, \texttt{log()}, and \texttt{sqrt()}.
An operation which is \emph{not} performed elementwise is array multiplication, \texttt{*}. If were were to try \texttt{fred*mary} then we would get an error:
\begin{verbatim}
ERROR: no method *(Array{Int32,1},Array{Int32,1})
\end{verbatim}
The reason for the error is that \texttt{julia} is trying to do matrix multiplication on two \texttt{9x1} arrays which, we know from Linear Algebra, is not allowed. Instead, we can accomplish element-wise multiplication with the following:
\begin{verbatim}
fred.*mary
\end{verbatim}
\begin{verbatim}
9-element Int32 Array:
296
155
285
366
304
204
161
162
96
\end{verbatim}
Notice the dot before the multiplication. A similar trick works for
elementwise division. By the way, with two \texttt{9x1} arrays it is legal
to compute the dot product like this:
\begin{verbatim}
fred'*mary
\end{verbatim}
\begin{verbatim}
1-element Int32 Array:
2029
\end{verbatim}
where notice we have transposed \texttt{fred} and done ordinary matrix
multiplication with \texttt{fred'*mary}.
\subsection[Getting Help]{Getting Help}
\label{sec-2-3}
When you get in the thick of \texttt{julia} you will soon find yourself
looking for help. The help resources for \texttt{julia} are not (yet) as
extensive as those for some other languages that have been around for
a while (such as R). \texttt{julia} is new and many of the help topics
haven't been written yet. Nevertheless, sometimes a person is lucky
and you can get help on a function when it's available with the
\texttt{help()} function.
\begin{verbatim}
help("factorial")
\end{verbatim}
\begin{verbatim}
Loading help data...
Base.factorial(n)
Factorial of n
Base.factorial(n, k)
Compute "factorial(n)/factorial(k)"
\end{verbatim}
In addition to this, you can type \texttt{help()} which gives an extended
list of help topics. For instance, I find myself doing
\texttt{help("Statistics")} a lot.
\section[Other tips]{Other tips}
\label{sec-3}
It is unnecessary to retype commands repeatedly, since Emacs/ESS
remembers what you have entered at the \texttt{julia>} prompt. To navigate
through previous commands put point at the lowest command line and
do either \texttt{M-p} or \texttt{M-n}.
\subsection[Other resources]{Other resources}
\label{sec-3-1}
\begin{itemize}
\item Check out the official \texttt{julia} manual \href{http://docs.julialang.org/en/latest/manual/}{here}.
\item The \emph{Standard Library} (a different type of manual) is \href{http://docs.julialang.org/en/latest/stdlib/}{here}.
\item There is a vibrant and growing \texttt{julia} community whose gateway is \href{http://julialang.org/community/}{here}.
\item There is a large and growing list of contributed packages \href{http://docs.julialang.org/en/latest/packages/packagelist/}{here}.
\end{itemize}
\section[Plotting with Winston]{Plotting with Winston}
\label{sec-4}
There's a pretty well fleshed out plotting example in the Graphics
section of \href{file://ob-julia-doc.org}{Org-mode and \texttt{julia}: an introduction}. Check it out.
\section[Fitting (generalized) linear models]{Fitting (generalized) linear models}
\label{sec-5}
Douglas Bates (of \href{http://www.springer.com/statistics/statistical+theory+and+methods/book/978-1-4419-0317-4}{Mixed Effects Models in S and S-PLUS} fame) has been
putting together a \texttt{julia} package called GLM which already supports
fitting generalized linear models to datasets. This, together with
the RDatasets package means there is already a bunch of stuff to keep
a person busy. Below is a modified example from the Multiple
Regression chapter of IPSUR, translated to \texttt{julia} speak.
First, we start \texttt{using} the packages we'll need.
\begin{verbatim}
using RDatasets, DataFrames, Distributions, GLM
\end{verbatim}
Next we load the \texttt{trees} data frame from the RDatasets package (via
the DataFrames package) and fit a linear model to the data.
\begin{verbatim}
trees = data("datasets", "trees")
treeslm = lm(:(Girth ~ Height + Volume), trees)
\end{verbatim}
There is a \emph{ton} of output from both the above commands which we omit
here for the sake of brevity. Most of it, though, is similar to to
output we might see in an R session. We can extract the model
coefficients with the \texttt{coef} function:
\begin{verbatim}
coef(treeslm)
\end{verbatim}
\begin{verbatim}
3-element Float64 Array:
10.8164
-0.0454835
0.19518
\end{verbatim}
and we can finish by looking at a summary table similar to something
like \texttt{summary(treeslm)} in R.
\begin{verbatim}
coeftable(treeslm)
\end{verbatim}
\begin{verbatim}
3x4 DataFrame:
Estimate Std.Error t value Pr(>|t|)
[1,] 10.8164 1.9732 5.48165 7.44691e-6
[2,] -0.0454835 0.0282621 -1.60935 0.118759
[3,] 0.19518 0.0109553 17.8161 8.2233e-17
\end{verbatim}
% Generated by Org mode 7.9.3f in Emacs 24.3.50.1.
\end{document}
\ No newline at end of file
% Created 2013-03-02 Sat 17:25
% Created 2013-03-02 Sat 21:09
\documentclass[presentation]{beamer}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
......@@ -79,6 +79,8 @@ sqrt(5)
\begin{block}{Here is the output}
\begin{verbatim}
5
hello, there!
2.23606797749979
......
% Created 2013-03-02 Sat 18:42
% Created 2013-03-02 Sat 21:15
\documentclass[11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
......@@ -28,25 +28,22 @@
\maketitle
\tableofcontents
\newpage
This document is an introduction to Org-mode + \texttt{julia}. The only
prerequisites are a passing familiarity with Org-mode and Emacs
keybindings.
\newpage
\section[What you need to get started]{What you need to get started}
\label{sec-1}
\begin{description}
\item[Note:] a lot of the code blocks below have the header argument
\texttt{:eval no-export}. This means that the code block can be
evaluated interactively by \texttt{C-c C-c} with point in the code
block but will \emph{not} be evaluated during export. That
header argument is present because those blocks have
settings which conflict with my current setup (or are
otherwise redundant) yet are meant to be useful for other
people working through this document.
\end{description}
\textbf{Note:} several code blocks below have the header argument \texttt{:eval
no-export}. This means that the code block can be evaluated
interactively by \texttt{C-c C-c} with point in the block but will \emph{not} be
evaluated during export. That header argument is present because
those blocks have settings which conflict with my current setup (or
are otherwise redundant) yet are meant to be useful for other
people.
\subsection[Julia]{Julia}
\label{sec-1-1}
......@@ -108,12 +105,18 @@ Pkg.add("DataFrames", "Distributions", "GLM", "MCMC", "Optim",
"NHST", "Clustering")
\end{verbatim}
As John notes, the \texttt{RDatasets} package takes a lot longer to download
than the others. Perhaps it would be wise to install it separately.
I recommend you \textbf{not} execute the \texttt{Pkg.add} command here (if you do it
in this buffer then you can't watch the download and install as it is
happening). As John notes, the \texttt{RDatasets} package takes a lot longer
to download than the others. Perhaps it would be wise to install it
separately.
\begin{verbatim}
Pkg.add("RDatasets")
\end{verbatim}
You will notice both \texttt{Pkg.add} code blocks have the \texttt{:eval never}
header argument.
\subsection[Org-mode]{Org-mode}
\label{sec-1-4}
......@@ -179,9 +182,8 @@ The most stable and fully featured of the \texttt{julia} graphics packages at
the time of this writing appears to be the \href{https://github.com/nolta/Winston.jl}{Winston package}, although
the \href{https://github.com/dcjones/Gadfly.jl}{Gadfly package} is also available and appears promising. To
install the Winston package execute the following in an interactive
session. I recommend you \textbf{not} execute this here (if you do it in
this buffer then you can't watch the download and install as it is
happening).
session. As above I recommend you \textbf{not} execute this here (hence the
\texttt{:eval never} header argument).
\begin{verbatim}
Pkg.add("Winston")
......@@ -222,7 +224,7 @@ add(p, Curve(x, s, "color", "blue") )
\end{verbatim}
We did \texttt{:results silent} to omit the lengthy output from being
inserted in the org buffer. So the hard part is finished -- we've
inserted in the org buffer. So the hard part is finished -- we've
created a plot object \texttt{p} which is now available to manipulate.
To launch a plot window and look at the graph right now evaluate the
......@@ -364,6 +366,17 @@ code blocks you'd like to tangle or doing a buffer-wide header
setting with the line \texttt{\#+PROPERTY: tangle yes} near the top of the
org file. See the Org manual for details.
\item At the time of this writing \texttt{ob-julia.el} only supports \texttt{:session}
evaluation and does not support external process evaluation. This
means that every \texttt{SRC julia} block should have a \texttt{:session
SOMETHING} header argument. Alternatively, you can put a
buffer-wide header argument at the top of the org file, something
like this:
\begin{verbatim}
#+PROPERTY: session *julia*
\end{verbatim}
\item You may have noticed that those \texttt{julia} code lines with no output
(for instance, lines with semicolons \texttt{;} at the end) generate an
empty line in the \texttt{\#+RESULTS} below the code block. Consequently,
......@@ -391,15 +404,18 @@ get an error.
instead of printing long arrays it will elide them with vertical
dots in the middle of the output which look similar to this \(
\vdots \) in the buffer. It turns out that \LaTeX{} does not like
those three dots because it corresponds to a special character, and
those three dots because they correspond to a special character, and
the upshot is that your org file will not export to \LaTeX{}
successfully. One way around this is to explicitly declare that
special symbol in the \LaTeX{} header. That is the reason for the
special symbol in the \LaTeX{} header. That is the reason for the
following line at the top of this org file.
\begin{verbatim}
#+LaTeX_HEADER: \DeclareUnicodeCharacter{22EE}{\vdots}
\end{verbatim}
\item \texttt{ob-julia.el} does not support \texttt{rownames} and \texttt{colnames} like
\texttt{ob-R.el} does.
\end{itemize}
% Generated by Org mode 7.9.3f in Emacs 24.3.50.1.
\end{document}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment