<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Dimitri Lozeve's Blog</title>
    <link href="https://www.lozeve.com/atom.xml" rel="self" />
    <link href="https://www.lozeve.com" />
    <id>https://www.lozeve.com/atom.xml</id>
    <author>
        <name>Dimitri Lozeve</name>
        <email>dimitri+web@lozeve.com</email>
    </author>
    <updated>2020-08-02T00:00:00Z</updated>
    <entry>
    <title>Dyalog APL Problem Solving Competition 2020 — Phase II</title>
    <link href="https://www.lozeve.com/posts/dyalog-apl-competition-2020-phase-2.html" />
    <id>https://www.lozeve.com/posts/dyalog-apl-competition-2020-phase-2.html</id>
    <published>2020-08-02T00:00:00Z</published>
    <updated>2020-08-02T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
    <section class="header">
        
    </section>
    <section>
        <div id="toc"><h2>Table of Contents</h2><ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#problem-1-take-a-dive">Problem 1 – Take a Dive</a></li>
<li><a href="#problem-2-another-step-in-the-proper-direction">Problem 2 – Another Step in the Proper Direction</a></li>
<li><a href="#problem-3-past-tasks-blast">Problem 3 – Past Tasks Blast</a></li>
<li><a href="#problem-4-bioinformatics">Problem 4 – Bioinformatics</a></li>
<li><a href="#problem-5-future-and-present-value">Problem 5 – Future and Present Value</a></li>
<li><a href="#problem-6-merge">Problem 6 – Merge</a></li>
<li><a href="#problem-7-upc">Problem 7 – UPC</a></li>
<li><a href="#problem-8-balancing-the-scales">Problem 8 – Balancing the Scales</a></li>
<li><a href="#problem-9-upwardly-mobile">Problem 9 – Upwardly Mobile</a></li>
</ul></div>
<h2 id="introduction">Introduction</h2>
<p>After <a href="./dyalog-apl-competition-2020-phase-1.html">Phase I</a>, here are my solutions to Phase II problems. The full code is included in the post, but everything is also available <a href="https://github.com/dlozeve/apl-competition-2020">on GitHub</a>.</p>
<p>A PDF of the problems descriptions is available on <a href="https://www.dyalogaplcompetition.com/">the competition website</a>, or directly from <a href="https://github.com/dlozeve/apl-competition-2020/blob/master/Contest2020/2020%20APL%20Problem%20Solving%20Competition%20Phase%20II%20Problems.pdf">my GitHub repo</a>.</p>
<p>The submission guidelines gave a template where everything is defined in a <code>Contest2020.Problems</code> Namespace. I kept the default values for <code>⎕IO</code> and <code>⎕ML</code> because the problems were not particularly easier with <code>⎕IO←0</code>.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true"></a>:Namespace Contest2020</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true"></a></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true"></a> :Namespace Problems</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true"></a>  (⎕IO ⎕ML ⎕WX)←1 1 3</span></code></pre></div>
<h2 id="problem-1-take-a-dive">Problem 1 – Take a Dive</h2>
<div class="sourceCode" id="cb2"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true"></a>∇ score←dd DiveScore scores</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true"></a>  :If 7=≢scores</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true"></a>   scores←scores[¯2↓2↓⍋scores]</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true"></a>  :ElseIf 5=≢scores</span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true"></a>   scores←scores[¯1↓1↓⍋scores]</span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true"></a>  :Else</span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true"></a>   scores←scores</span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true"></a>  :EndIf</span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true"></a>  score←2(⍎⍕)dd×+/scores</span>
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true"></a>∇</span></code></pre></div>
<p>This is a very straightforward implementation of the algorithm describe in the problem description. I decided to switch explicitly on the size of the input vector because I feel it is more natural. For the cases with 5 or 7 judges, we use Drop (<code>↓</code>) to remove the lowest and highest scores.</p>
<p>At the end, we sum up the scores with <code>+/</code> and multiply them by <code>dd</code>. The last operation, <code>2(⍎⍕)</code>, is a train using <a href="https://help.dyalog.com/18.0/index.htm#Language/Primitive%20Functions/Format%20Dyadic.htm">Format (Dyadic)</a> to round to 2 decimal places, and <a href="https://help.dyalog.com/18.0/index.htm#Language/Primitive%20Functions/Execute.htm">Execute</a> to get actual numbers and not strings.</p>
<h2 id="problem-2-another-step-in-the-proper-direction">Problem 2 – Another Step in the Proper Direction</h2>
<div class="sourceCode" id="cb3"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true"></a>∇ steps←{p}Steps fromTo;segments;width</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true"></a>  width←|-/fromTo</span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true"></a>  :If 0=⎕NC'p' ⍝ No left argument: same as Problem 5 of Phase I</span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true"></a>   segments←0,⍳width</span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true"></a>  :ElseIf p&lt;0 ⍝ -⌊p is the number of equally-sized steps to take</span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true"></a>   segments←(-⌊p){0,⍵×⍺÷⍨⍳⍺}width</span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true"></a>  :ElseIf p&gt;0 ⍝ p is the step size</span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true"></a>   segments←p{⍵⌊⍺×0,⍳⌈⍵÷⍺}width</span>
<span id="cb3-9"><a href="#cb3-9" aria-hidden="true"></a>  :ElseIf p=0 ⍝ As if we took zero step</span>
<span id="cb3-10"><a href="#cb3-10" aria-hidden="true"></a>   segments←0</span>
<span id="cb3-11"><a href="#cb3-11" aria-hidden="true"></a>  :EndIf</span>
<span id="cb3-12"><a href="#cb3-12" aria-hidden="true"></a>  ⍝ Take into account the start point and the direction.</span>
<span id="cb3-13"><a href="#cb3-13" aria-hidden="true"></a>  steps←fromTo{(⊃⍺)+(-×-/⍺)×⍵}segments</span>
<span id="cb3-14"><a href="#cb3-14" aria-hidden="true"></a>∇</span></code></pre></div>
<p>This is an extension to <a href="./dyalog-apl-competition-2020-phase-1.html#stepping-in-the-proper-direction">Problem 5 of Phase I</a>. In each case, we compute the “segments”, i.e., the steps starting from 0. In a last step, common to all cases, we add the correct starting point and correct the direction if need be.</p>
<p>To compute equally-sized steps, we first divide the segment <span class="math inline">\([0, 1]\)</span> in <code>p</code> equal segments with <code>(⍳p)÷p</code>. This subdivision can then be multiplied by the width to obtain the required segments.</p>
<p>When <code>p</code> is the step size, we just divide the width by the step size (rounded to the next largest integer) to get the required number of segments. If the last segment is too large, we “crop” it to the width with Minimum (<code>⌊</code>).</p>
<h2 id="problem-3-past-tasks-blast">Problem 3 – Past Tasks Blast</h2>
<div class="sourceCode" id="cb4"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true"></a>∇ urls←PastTasks url;r;paths</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true"></a>  r←HttpCommand.Get url</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true"></a>  paths←('[a-zA-Z0-9_/]+\.pdf'⎕S'&amp;')r.Data</span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true"></a>  urls←('https://www.dyalog.com/'∘,)¨paths</span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true"></a>∇</span></code></pre></div>
<p>I decided to use <code>HttpCommand</code> for this task, since it is simply one <code>]load HttpCommand</code> away and should be platform-independent.</p>
<p>Parsing XML is not something I consider “fun” in the best of cases, and I feel like APL is not the best language to do this kind of thing. Given how simple the task is, I just decided to find the relevant bits with a regular expression using <a href="https://help.dyalog.com/18.0/index.htm#Language/System%20Functions/r.htm">Replace and Search</a> (<code>⎕S</code>).</p>
<p>After finding all the strings vaguely resembling a PDF file name (only alphanumeric characters and underscores, with a <code>.pdf</code> extension), I just concatenate them to the base URL of the Dyalog domain.</p>
<h2 id="problem-4-bioinformatics">Problem 4 – Bioinformatics</h2>
<p>The first task can be solved by decomposing it into several functions.</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true"></a>⍝ Test if a DNA string is a reverse palindrome.</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true"></a>isrevp←{⍵≡⌽'TAGC'['ATCG'⍳⍵]}</span></code></pre></div>
<p>First, we compute the complement of a DNA string (using simple indexing) and test if its Reverse (<code>⌽</code>) is equal to the original string.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true"></a>⍝ Generate all subarrays (position, length) pairs, for 4 ≤ length ≤ 12.</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true"></a>subarrays←{⊃,/(⍳⍵),¨¨3↓¨⍳¨12⌊1+⍵-⍳⍵}</span></code></pre></div>
<p>We first compute all the possible lengths for each starting point. For instance, the last element cannot have any (position, length) pair associated to it, because there is no three element following it. So we crop the possible lengths to <span class="math inline">\([3, 12]\)</span>. For instance for an array of size 10:</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true"></a>        {3↓¨⍳¨12⌊1+⍵-⍳⍵}10</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true"></a>┌──────────────┬───────────┬─────────┬───────┬─────┬───┬─┬┬┬┐</span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true"></a>│4 5 6 7 8 9 10│4 5 6 7 8 9│4 5 6 7 8│4 5 6 7│4 5 6│4 5│4││││</span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true"></a>└──────────────┴───────────┴─────────┴───────┴─────┴───┴─┴┴┴┘</span></code></pre></div>
<p>Then, we just add the corresponding starting position to each length (1 for the first block, 2 for the second, and so on). Finally, we flatten everything.</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true"></a>∇ r←revp dna;positions</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true"></a>  positions←subarrays⍴dna</span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true"></a>  ⍝ Filter subarrays which are reverse palindromes.</span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true"></a>  r←↑({isrevp dna[¯1+⍵[1]+⍳⍵[2]]}¨positions)/positions</span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true"></a>∇</span></code></pre></div>
<p>For each possible (position, length) pair, we get the corresponding DNA substring with <code>dna[¯1+⍵[1]+⍳⍵[2]]</code> (adding <code>¯1</code> is necessary because <code>⎕IO←1</code>). We test if this substring is a reverse palindrome using <code>isrevp</code> above. <a href="https://help.dyalog.com/18.0/index.htm#Language/Primitive%20Functions/Replicate.htm">Replicate</a> (<code>/</code>) then selects only the (position, length) pairs for which the substring is a reverse palindrome.</p>
<p>The second task is just about counting the number of subsets modulo 1,000,000. So we just need to compute <span class="math inline">\(2^n \mod 1000000\)</span> for any positive integer <span class="math inline">\(n\leq1000\)</span>.</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true"></a>sset←{((1E6|2∘×)⍣⍵)1}</span></code></pre></div>
<p>Since we cannot just compute <span class="math inline">\(2^n\)</span> directly and take the remainder, we use modular arithmetic to stay mod 1,000,000 during the whole computation. The dfn <code>(1E6|2∘×)</code> doubles its argument mod 1,000,000. So we just apply this function <span class="math inline">\(n\)</span> times using the <a href="https://help.dyalog.com/18.0/index.htm#Language/Primitive%20Operators/Power%20Operator.htm">Power</a> operator (<code>⍣</code>), with an initial value of 1.</p>
<h2 id="problem-5-future-and-present-value">Problem 5 – Future and Present Value</h2>
<p>First solution: <code>((1+⊢)⊥⊣)</code> computes the total return for a vector of amounts <code>⍺</code> and a vector of rates <code>⍵</code>. It is applied to every prefix subarray of amounts and rates to get all intermediate values. However, this has quadratic complexity.</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true"></a>rr←(,\⊣)((1+⊢)⊥⊣)¨(,\⊢)</span></code></pre></div>
<p>Second solution: We want to be able to use the recurrence relation (<code>recur</code>) and scan through the vectors of amounts and rates, accumulating the total value at every time step. However, APL evaluation is right-associative, so a simple <a href="https://help.dyalog.com/18.0/index.htm#Language/Primitive%20Operators/Scan.htm">Scan</a> (<code>recur\amounts,¨values</code>) would not give the correct result, since <code>recur</code> is not associative and we need to evaluate it left-to-right. (In any case, in this case, Scan would have quadratic complexity, so would not bring any benefit over the previous solution.) What we need is something akin to Haskell’s <code>scanl</code> function, which would evaluate left to right in <span class="math inline">\(O(n)\)</span> time<span><label for="sn-0" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-0" class="margin-toggle" /><span class="sidenote">There is an interesting <a href="https://stackoverflow.com/a/25100675/8864368">StackOverflow answer</a> explaining the behaviour of Scan, and compares it to Haskell’s <code>scanl</code> function.<br />
<br />
</span></span>. This is what we do here, accumulating values from left to right. (This is inspired from <a href="https://dfns.dyalog.com/c_ascan.htm"><code>dfns.ascan</code></a>, although heavily simplified.)</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true"></a>rr←{recur←{⍵[1]+⍺×1+⍵[2]} ⋄ 1↓⌽⊃{(⊂(⊃⍵)recur⍺),⍵}/⌽⍺,¨⍵}</span></code></pre></div>
<p>For the second task, there is an explicit formula for cashflow calculations, so we can just apply it.</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true"></a>pv←{+/⍺÷×\1+⍵}</span></code></pre></div>
<h2 id="problem-6-merge">Problem 6 – Merge</h2>
<div class="sourceCode" id="cb13"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true"></a>∇ text←templateFile Merge jsonFile;template;ns</span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true"></a>  template←⊃⎕NGET templateFile 1</span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true"></a>  ns←⎕JSON⊃⎕NGET jsonFile</span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true"></a>  ⍝ We use a simple regex search and replace on the</span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true"></a>  ⍝ template.</span>
<span id="cb13-6"><a href="#cb13-6" aria-hidden="true"></a>  text←↑('@[a-zA-Z]*@'⎕R{ns getval ¯1↓1↓⍵.Match})template</span>
<span id="cb13-7"><a href="#cb13-7" aria-hidden="true"></a>∇</span></code></pre></div>
<p>We first read the template and the JSON values from their files. The <a href="https://help.dyalog.com/18.0/index.htm#Language/System%20Functions/nget.htm"><code>⎕NGET</code></a> function read simple text files, and <a href="https://help.dyalog.com/18.0/index.htm#Language/System%20Functions/json.htm"><code>⎕JSON</code></a> extracts the key-value pairs as a namespace.</p>
<p>Assuming all variable names contain only letters, we match the regex <code>@[a-zA-Z]*@</code> to match variable names enclosed between <code>@</code> symbols. The function <code>getval</code> then returns the appropriate value, and we can replace the variable name in the template.</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true"></a>∇ val←ns getval var</span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true"></a>  :If ''≡var ⍝ literal '@'</span>
<span id="cb14-3"><a href="#cb14-3" aria-hidden="true"></a>   val←'@'</span>
<span id="cb14-4"><a href="#cb14-4" aria-hidden="true"></a>  :ElseIf (⊂var)∊ns.⎕NL ¯2</span>
<span id="cb14-5"><a href="#cb14-5" aria-hidden="true"></a>   val←⍕ns⍎var</span>
<span id="cb14-6"><a href="#cb14-6" aria-hidden="true"></a>  :Else</span>
<span id="cb14-7"><a href="#cb14-7" aria-hidden="true"></a>   val←'???'</span>
<span id="cb14-8"><a href="#cb14-8" aria-hidden="true"></a>  :EndIf</span>
<span id="cb14-9"><a href="#cb14-9" aria-hidden="true"></a>∇</span></code></pre></div>
<p>This function takes the namespace matching the variable names to their respective values, and the name of the variable.</p>
<ul>
<li>If the variable name is empty, we matched the string <code>@@</code>, which corresponds to a literal <code>@</code>.</li>
<li>If the variable name is present in the namespace, we query the namespace to get the required value.</li>
<li>Otherwise, we have an unknown variable, so we replace it with <code>???</code>.</li>
</ul>
<h2 id="problem-7-upc">Problem 7 – UPC</h2>
<div class="sourceCode" id="cb15"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true"></a>CheckDigit←{10|-⍵+.×11⍴3 1}</span></code></pre></div>
<p>The check digit satisfies the equation <span class="math display">\[ 3 x_{1}+x_{2}+3 x_{3}+x_{4}+3 x_{5}+x_{6}+3 x_{7}+x_{8}+3 x_{9}+x_{10}+3 x_{11}+x_{12} \equiv 0 \bmod 10, \]</span> therefore, <span class="math display">\[ x_{12} \equiv -(3 x_{1}+x_{2}+3 x_{3}+x_{4}+3 x_{5}+x_{6}+3 x_{7}+x_{8}+3 x_{9}+x_{10}+3 x_{11}) \bmod 10. \]</span></p>
<p>Translated to APL, we just take the dot product between the first 11 digits of the barcode with <code>11⍴3 1</code>, negate it, and take the remainder by 10.</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true"></a>⍝ Left and right representations of digits. Decoding</span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true"></a>⍝ the binary representation from decimal is more</span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true"></a>⍝ compact than writing everything explicitly.</span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true"></a>lrepr←⍉(7⍴2)⊤13 25 19 61 35 49 47 59 55 11</span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true"></a>rrepr←~¨lrepr</span></code></pre></div>
<p>For the second task, the first thing we need to do is save the representation of digits. To save space, I did not encode the binary representation explicitly, instead using a decimal representation that I then decode in base 2. The right representation is just the bitwise negation.</p>
<div class="sourceCode" id="cb17"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true"></a>∇ bits←WriteUPC digits;left;right</span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true"></a>  :If (11=≢digits)∧∧/digits∊0,⍳9</span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true"></a>   left←,lrepr[1+6↑digits;]</span>
<span id="cb17-4"><a href="#cb17-4" aria-hidden="true"></a>   right←,rrepr[1+6↓digits,CheckDigit digits;]</span>
<span id="cb17-5"><a href="#cb17-5" aria-hidden="true"></a>   bits←1 0 1,left,0 1 0 1 0,right,1 0 1</span>
<span id="cb17-6"><a href="#cb17-6" aria-hidden="true"></a>  :Else</span>
<span id="cb17-7"><a href="#cb17-7" aria-hidden="true"></a>   bits←¯1</span>
<span id="cb17-8"><a href="#cb17-8" aria-hidden="true"></a>  :EndIf</span>
<span id="cb17-9"><a href="#cb17-9" aria-hidden="true"></a>∇</span></code></pre></div>
<p>First of all, if the vector <code>digits</code> does not have exactly 11 elements, all between 0 and 9, it is an error and we return <code>¯1</code>.</p>
<p>Then, we take the first 6 digits and encode them with <code>lrepr</code>, and the last 5 digits plus the check digit encoded with <code>rrepr</code>. In each case, adding 1 is necessary because <code>⎕IO←1</code>. We return the final bit array with the required beginning, middle, and end guard patterns.</p>
<div class="sourceCode" id="cb18"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true"></a>∇ digits←ReadUPC bits</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true"></a>  :If 95≠⍴bits ⍝ incorrect number of bits</span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true"></a>   digits←¯1</span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true"></a>  :Else</span>
<span id="cb18-5"><a href="#cb18-5" aria-hidden="true"></a>   ⍝ Test if the barcode was scanned right-to-left.</span>
<span id="cb18-6"><a href="#cb18-6" aria-hidden="true"></a>   :If 0=2|+/bits[3+⍳7]</span>
<span id="cb18-7"><a href="#cb18-7" aria-hidden="true"></a>    bits←⌽bits</span>
<span id="cb18-8"><a href="#cb18-8" aria-hidden="true"></a>   :EndIf</span>
<span id="cb18-9"><a href="#cb18-9" aria-hidden="true"></a>   digits←({¯1+lrepr⍳⍵}¨(7/⍳6)⊆42↑3↓bits),{¯1+rrepr⍳⍵}¨(7/⍳6)⊆¯42↑¯3↓bits</span>
<span id="cb18-10"><a href="#cb18-10" aria-hidden="true"></a>   :If ~∧/digits∊0,⍳9 ⍝ incorrect parity</span>
<span id="cb18-11"><a href="#cb18-11" aria-hidden="true"></a>    digits←¯1</span>
<span id="cb18-12"><a href="#cb18-12" aria-hidden="true"></a>   :ElseIf (⊃⌽digits)≠CheckDigit ¯1↓digits ⍝ incorrect check digit</span>
<span id="cb18-13"><a href="#cb18-13" aria-hidden="true"></a>    digits←¯1</span>
<span id="cb18-14"><a href="#cb18-14" aria-hidden="true"></a>   :EndIf</span>
<span id="cb18-15"><a href="#cb18-15" aria-hidden="true"></a>  :EndIf</span>
<span id="cb18-16"><a href="#cb18-16" aria-hidden="true"></a>∇</span></code></pre></div>
<ul>
<li>If we don’t have the correct number of bits, we return <code>¯1</code>.</li>
<li>We test the first digit for its parity, to determine if its actually a left representation. If it’s not, we reverse the bit array.</li>
<li>Then, we take the bit array representing the right digits (<code>¯42↑¯3↓bits</code>), separate the different digits using <a href="https://help.dyalog.com/18.0/index.htm#Language/Primitive%20Functions/Partition.htm">Partition</a> (<code>⊆</code>), and look up each of them in the <code>rrepr</code> vector using <a href="https://help.dyalog.com/18.0/index.htm#Language/Primitive%20Functions/Index%20Of.htm">Index Of</a> (<code>⍳</code>). We do the same for the left digits.</li>
<li>Final checks for the range of the digits (i.e., if the representations could not be found in the <code>lrepr</code> and <code>rrepr</code> vectors), and for the check digit.</li>
</ul>
<h2 id="problem-8-balancing-the-scales">Problem 8 – Balancing the Scales</h2>
<div class="sourceCode" id="cb19"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true"></a>∇ parts←Balance nums;subsets;partitions</span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true"></a>  ⍝ This is a brute force solution, running in</span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true"></a>  ⍝ exponential time. We generate all the possible</span>
<span id="cb19-4"><a href="#cb19-4" aria-hidden="true"></a>  ⍝ partitions, filter out those which are not</span>
<span id="cb19-5"><a href="#cb19-5" aria-hidden="true"></a>  ⍝ balanced, and return the first matching one. There</span>
<span id="cb19-6"><a href="#cb19-6" aria-hidden="true"></a>  ⍝ are more advanced approach running in</span>
<span id="cb19-7"><a href="#cb19-7" aria-hidden="true"></a>  ⍝ pseudo-polynomial time (based on dynamic</span>
<span id="cb19-8"><a href="#cb19-8" aria-hidden="true"></a>  ⍝ programming, see the &quot;Partition problem&quot; Wikipedia</span>
<span id="cb19-9"><a href="#cb19-9" aria-hidden="true"></a>  ⍝ page), but they are not warranted here, as the</span>
<span id="cb19-10"><a href="#cb19-10" aria-hidden="true"></a>  ⍝ input size remains fairly small.</span>
<span id="cb19-11"><a href="#cb19-11" aria-hidden="true"></a></span>
<span id="cb19-12"><a href="#cb19-12" aria-hidden="true"></a>  ⍝ Generate all partitions of a vector of a given</span>
<span id="cb19-13"><a href="#cb19-13" aria-hidden="true"></a>  ⍝ size, as binary mask vectors.</span>
<span id="cb19-14"><a href="#cb19-14" aria-hidden="true"></a>  subsets←{1↓2⊥⍣¯1⍳2*⍵}</span>
<span id="cb19-15"><a href="#cb19-15" aria-hidden="true"></a>  ⍝ Keep only the subsets whose sum is exactly</span>
<span id="cb19-16"><a href="#cb19-16" aria-hidden="true"></a>  ⍝ (+/nums)÷2.</span>
<span id="cb19-17"><a href="#cb19-17" aria-hidden="true"></a>  partitions←nums{((2÷⍨+/⍺)=⍺+.×⍵)/⍵}subsets⍴nums</span>
<span id="cb19-18"><a href="#cb19-18" aria-hidden="true"></a>  :If 0=≢,partitions</span>
<span id="cb19-19"><a href="#cb19-19" aria-hidden="true"></a>   ⍝ If no partition satisfy the above</span>
<span id="cb19-20"><a href="#cb19-20" aria-hidden="true"></a>   ⍝ criterion, we return ⍬.</span>
<span id="cb19-21"><a href="#cb19-21" aria-hidden="true"></a>   parts←⍬</span>
<span id="cb19-22"><a href="#cb19-22" aria-hidden="true"></a>  :Else</span>
<span id="cb19-23"><a href="#cb19-23" aria-hidden="true"></a>   ⍝ Otherwise, we return the first possible</span>
<span id="cb19-24"><a href="#cb19-24" aria-hidden="true"></a>   ⍝ partition.</span>
<span id="cb19-25"><a href="#cb19-25" aria-hidden="true"></a>   parts←nums{((⊂,(⊂~))⊃↓⍉⍵)/¨2⍴⊂⍺}partitions</span>
<span id="cb19-26"><a href="#cb19-26" aria-hidden="true"></a>  :EndIf</span>
<span id="cb19-27"><a href="#cb19-27" aria-hidden="true"></a>∇</span></code></pre></div>
<h2 id="problem-9-upwardly-mobile">Problem 9 – Upwardly Mobile</h2>
<p>This is the only problem that I didn’t complete. It required parsing the files containing the graphical representations of the trees, which was needlessly complex and, quite frankly, hard and boring with a language like APL.</p>
<p>However, the next part is interesting: once we have a matrix of coefficients representing the relationships between the weights, we can solve the system of equations. <a href="https://help.dyalog.com/18.0/index.htm#Language/Primitive%20Functions/Matrix%20Divide.htm">Matrix Divide</a> (<code>⌹</code>) will find one solution to the system. Since the system is overdetermined, we fix <code>A=1</code> to find one possible solution. Since we want integer weights, the solution we find is smaller than the one we want, and may contain fractional weights. So we multiply everything by the <a href="https://help.dyalog.com/18.0/index.htm#Language/Primitive%20Functions/And%20Lowest%20Common%20Multiple.htm">Lowest Common Multiple</a> (<code>∧</code>) to get the smallest integer weights.</p>
<div class="sourceCode" id="cb20"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true"></a>∇ weights←Weights filename;mobile;branches;mat</span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true"></a>  ⍝ Put your code and comments below here</span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true"></a></span>
<span id="cb20-4"><a href="#cb20-4" aria-hidden="true"></a>  ⍝ Parse the mobile input file.</span>
<span id="cb20-5"><a href="#cb20-5" aria-hidden="true"></a>  mobile←↑⊃⎕NGET filename 1</span>
<span id="cb20-6"><a href="#cb20-6" aria-hidden="true"></a>  branches←⍸mobile∊'┌┴┐'</span>
<span id="cb20-7"><a href="#cb20-7" aria-hidden="true"></a>  ⍝ TODO: Build the matrix of coefficients mat.</span>
<span id="cb20-8"><a href="#cb20-8" aria-hidden="true"></a></span>
<span id="cb20-9"><a href="#cb20-9" aria-hidden="true"></a>  ⍝ Solve the system of equations (arbitrarily setting</span>
<span id="cb20-10"><a href="#cb20-10" aria-hidden="true"></a>  ⍝ the first variable at 1 because the system is</span>
<span id="cb20-11"><a href="#cb20-11" aria-hidden="true"></a>  ⍝ overdetermined), then multiply the coefficients by</span>
<span id="cb20-12"><a href="#cb20-12" aria-hidden="true"></a>  ⍝ their least common multiple to get the smallest</span>
<span id="cb20-13"><a href="#cb20-13" aria-hidden="true"></a>  ⍝ integer weights.</span>
<span id="cb20-14"><a href="#cb20-14" aria-hidden="true"></a>  weights←((1∘,)×(∧/÷))mat[;1]⌹1↓[2]mat</span>
<span id="cb20-15"><a href="#cb20-15" aria-hidden="true"></a>∇</span></code></pre></div>
<div class="sourceCode" id="cb21"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true"></a> :EndNamespace</span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true"></a>:EndNamespace</span></code></pre></div>
    </section>
</article>
]]></summary>
</entry>
<entry>
    <title>Dyalog APL Problem Solving Competition 2020 — Phase I</title>
    <link href="https://www.lozeve.com/posts/dyalog-apl-competition-2020-phase-1.html" />
    <id>https://www.lozeve.com/posts/dyalog-apl-competition-2020-phase-1.html</id>
    <published>2020-08-02T00:00:00Z</published>
    <updated>2020-08-02T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
    <section class="header">
        
    </section>
    <section>
        <div id="toc"><h2>Table of Contents</h2><ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#lets-split">1. Let’s Split!</a></li>
<li><a href="#character-building">2. Character Building</a></li>
<li><a href="#excel-lent-columns">3. Excel-lent Columns</a></li>
<li><a href="#take-a-leap">4. Take a Leap</a></li>
<li><a href="#stepping-in-the-proper-direction">5. Stepping in the Proper Direction</a></li>
<li><a href="#please-move-to-the-front">6. Please Move to the Front</a></li>
<li><a href="#see-you-in-a-bit">7. See You in a Bit</a></li>
<li><a href="#zigzag-numbers">8. Zigzag Numbers</a></li>
<li><a href="#rise-and-fall">9. Rise and Fall</a></li>
<li><a href="#stacking-it-up">10. Stacking It Up</a></li>
</ul></div>
<h2 id="introduction">Introduction</h2>
<p>I’ve always been quite fond of <a href="https://en.wikipedia.org/wiki/APL_(programming_language)">APL</a> and its “array-oriented” approach of programming<span><label for="sn-0" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-0" class="margin-toggle" /><span class="sidenote">See my <a href="./ising-apl.html">previous post</a> on simulating the Ising model with APL. It also contains more background on APL.<br />
<br />
</span></span>. Every year, <a href="https://www.dyalog.com/">Dyalog</a> (the company behind probably the most popular APL implementation) organises a competition with various challenges in APL.</p>
<p>The <a href="https://www.dyalogaplcompetition.com/">Dyalog APL Problem Solving Competition</a> consists of two phases:</p>
<ul>
<li>Phase I consists of 10 short puzzles (similar to what one can find on <a href="https://projecteuler.net/">Project Euler</a> or similar), that can be solved by a one-line APL function.</li>
<li>Phase II is a collection of larger problems, that may require longer solutions and a larger context (e.g. reading and writing to files), often in a more applied setting. Problems are often inspired by existing domains, such as AI, bioinformatics, and so on.</li>
</ul>
<p>In 2018, I participated in the competition, entering only Phase I<span><label for="sn-1" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-1" class="margin-toggle" /><span class="sidenote">Since I was a student at the time, I was eligible for a prize, and <a href="https://www.dyalog.com/nnews/128/456/Winners-Announced-for-the-2018-APL-Programming-Contest.htm">I won $100</a> for a 10-line submission, which is quite good!<br />
<br />
</span></span> (my solutions are on <a href="https://github.com/dlozeve/apl-competition-2018">GitHub</a>). This year, I entered in both phases. I explain my solutions to Phase I in this post. <a href="./dyalog-apl-competition-2020-phase-2.html">Another post</a> will contain annotated solutions for Phase II problems.</p>
<p>The full code for my submission is on GitHub at <a href="https://github.com/dlozeve/apl-competition-2020">dlozeve/apl-competition-2020</a>, but everything is reproduced in this post.</p>
<h2 id="lets-split">1. Let’s Split!</h2>
<blockquote>
<p>Write a function that, given a right argument <code>Y</code> which is a scalar or a non-empty vector and a left argument <code>X</code> which is a single non-zero integer so that its absolute value is less or equal to <code>≢Y</code>, splits <code>Y</code> into a vector of two vectors according to <code>X</code>, as follows:</p>
<p>If <code>X&gt;0</code>, the first vector contains the first <code>X</code> elements of <code>Y</code> and the second vector contains the remaining elements.</p>
<p>If <code>X&lt;0</code>, the second vector contains the last <code>|X</code> elements of <code>Y</code> and the first vector contains the remaining elements.</p>
</blockquote>
<p><strong>Solution:</strong> <code>(0&gt;⊣)⌽((⊂↑),(⊂↓))</code></p>
<p>There are three nested trains here<span><label for="sn-2" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-2" class="margin-toggle" /><span class="sidenote">Trains are nice to read (even if they are easy to abuse), and generally make for shorter dfns, which is better for Phase I.<br />
<br />
</span></span>. The first one, <code>((⊂↑),(⊂↓))</code>, uses the two functions <a href="https://help.dyalog.com/18.0/index.htm#Language/Primitive%20Functions/Take.htm">Take</a> (<code>↑</code>) and <a href="https://help.dyalog.com/18.0/index.htm#Language/Primitive%20Functions/Drop.htm">Drop</a> (<code>↓</code>) to build a nested array consisting of the two outputs we need. (Take and Drop already have the behaviour needed regarding negative arguments.) However, if the left argument is positive, the two arrays will not be in the correct order. So we need a way to reverse them if <code>X&lt;0</code>.</p>
<p>The second train <code>(0&gt;⊣)</code> will return 1 if its left argument is positive. From this, we can use <a href="https://help.dyalog.com/18.0/index.htm#Language/Primitive%20Functions/Rotate.htm">Rotate</a> (<code>⌽</code>) to correctly order the nested array, in the last train.</p>
<h2 id="character-building">2. Character Building</h2>
<blockquote>
<p>UTF-8 encodes Unicode characters using 1-4 integers for each character. Dyalog APL includes a system function, <code>⎕UCS</code>, that can convert characters into integers and integers into characters. The expression <code>'UTF-8'∘⎕UCS</code> converts between characters and UTF-8.</p>
<p>Consider the following:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true"></a>      'UTF-8'∘⎕UCS 'D¥⍺⌊○9'</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true"></a>68 194 165 226 141 186 226 140 138 226 151 139 57</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true"></a>      'UTF-8'∘⎕UCS 68 194 165 226 141 186 226 140 138 226 151 139 57</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true"></a>D¥⍺⌊○9</span></code></pre></div>
<p>How many integers does each character use?</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true"></a>      'UTF-8'∘⎕UCS¨ 'D¥⍺⌊○9' ⍝ using ]Boxing on</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true"></a>┌──┬───────┬───────────┬───────────┬───────────┬──┐</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true"></a>│68│194 165│226 141 186│226 140 138│226 151 139│57│</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true"></a>└──┴───────┴───────────┴───────────┴───────────┴──┘      </span></code></pre></div>
<p>The rule is that an integer in the range 128 to 191 (inclusive) continues the character of the previous integer (which may itself be a continuation). With that in mind, write a function that, given a right argument which is a simple integer vector representing valid UTF-8 text, encloses each sequence of integers that represent a single character, like the result of <code>'UTF-8'∘⎕UCS¨'UTF-8'∘⎕UCS</code> but does not use any system functions (names beginning with <code>⎕</code>)</p>
</blockquote>
<p><strong>Solution:</strong> <code>{(~⍵∊127+⍳64)⊂⍵}</code></p>
<p>First, we build a binary array from the string, encoding each continuation character as 0, and all the others as 1. Next, we can use this binary array with <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Partitioned%20Enclose.htm">Partitioned Enclose</a> (<code>⊂</code>) to return the correct output.</p>
<h2 id="excel-lent-columns">3. Excel-lent Columns</h2>
<blockquote>
<p>A Microsoft Excel spreadsheet numbers its rows counting up from 1. However, Excel’s columns are labelled alphabetically — beginning with A–Z, then AA–AZ, BA–BZ, up to ZA–ZZ, then AAA–AAZ and so on.</p>
<p>Write a function that, given a right argument which is a character scalar or non-empty vector representing a valid character Excel column identifier between A and XFD, returns the corresponding column number</p>
</blockquote>
<p><strong>Solution:</strong> <code>26⊥⎕A∘⍳</code></p>
<p>We use the alphabet <code>⎕A</code> and <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Index%20Of.htm">Index Of</a> (<code>⍳</code>) to compute the index in the alphabet of every character. As a train, this can be done by <code>(⎕A∘⍳)</code>. We then obtain an array of numbers, each representing a letter from 1 to 26. The <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Decode.htm">Decode</a> (<code>⊥</code>) function can then turn this base-26 number into the expected result.</p>
<h2 id="take-a-leap">4. Take a Leap</h2>
<blockquote>
<p>Write a function that, given a right argument which is an integer array of year numbers greater than or equal to 1752 and less than 4000, returns a result of the same shape as the right argument where 1 indicates that the corresponding year is a leap year (0 otherwise).</p>
<p>A leap year algorithm can be found <a href="https://en.wikipedia.org/wiki/Leap_year#Algorithm">here</a>.</p>
</blockquote>
<p><strong>Solution:</strong> <code>1 3∊⍨(0+.=400 100 4∘.|⊢)</code></p>
<p>According to the algorithm, a year is a leap year in two situations:</p>
<ul>
<li>if it is divisible by 4, but not 100 (and therefore not 400),</li>
<li>if it is divisible by 400 (and therefore 4 and 100 as well).</li>
</ul>
<p>The train <code>(400 100 4∘.|⊢)</code> will test if each year in the right argument is divisible by 400, 100, and 4, using an <a href="https://help.dyalog.com/latest/#Language/Primitive%20Operators/Outer%20Product.htm">Outer Product</a>. We then use an <a href="https://help.dyalog.com/latest/#Language/Primitive%20Operators/Inner%20Product.htm">Inner Product</a> to count how many times each year is divisible by one of these numbers. If the count is 1 or 3, it is a leap year. Note that we use <a href="https://help.dyalog.com/latest/#Language/Primitive%20Operators/Commute.htm">Commute</a> (<code>⍨</code>) to keep the dfn as a train, and to preserve the natural right-to-left reading of the algorithm.</p>
<h2 id="stepping-in-the-proper-direction">5. Stepping in the Proper Direction</h2>
<blockquote>
<p>Write a function that, given a right argument of 2 integers, returns a vector of the integers from the first element of the right argument to the second, inclusively.</p>
</blockquote>
<p><strong>Solution:</strong> <code>{(⊃⍵)+(-×-/⍵)×0,⍳|-/⍵}</code></p>
<p>First, we have to compute the range of the output, which is the absolute value of the difference between the two integers <code>|-/⍵</code>. From this, we compute the actual sequence, including zero<span><label for="sn-3" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-3" class="margin-toggle" /><span class="sidenote">If we had <code>⎕IO←0</code>, we could have written <code>⍳|1+-/⍵</code>, but this is the same number of characters.<br />
<br />
</span></span>: <code>0,⍳|-/⍵</code>.</p>
<p>This sequence will always be nondecreasing, but we have to make it decreasing if needed, so we multiply it by the opposite of the sign of <code>-/⍵</code>. Finally, we just have to start the sequence at the first element of <code>⍵</code>.</p>
<h2 id="please-move-to-the-front">6. Please Move to the Front</h2>
<blockquote>
<p>Write a function that, given a right argument which is an integer vector and a left argument which is an integer scalar, reorders the right argument so any elements equal to the left argument come first while all other elements keep their order.</p>
</blockquote>
<p><strong>Solution:</strong> <code>{⍵[⍋⍺≠⍵]}</code></p>
<p><code>⍺≠⍵</code> will return a binary vector marking as 0 all elements equal to the left argument. Using this index to sort in the usual way with <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Grade%20Up%20Monadic.htm">Grade Up</a> will return the expected result.</p>
<h2 id="see-you-in-a-bit">7. See You in a Bit</h2>
<blockquote>
<p>A common technique for encoding a set of on/off states is to use a value of <span class="math inline">\(2^n\)</span> for the state in position <span class="math inline">\(n\)</span> (origin 0), 1 if the state is “on” or 0 for “off” and then add the values. Dyalog APL’s <a href="https://help.dyalog.com/17.1/#Language/APL%20Component%20Files/Component%20Files.htm#File_Access_Control">component file permission codes</a> are an example of this. For example, if you wanted to grant permissions for read (access code 1), append (access code 8) and rename (access code 128) then the resulting code would be 137 because that’s 1 + 8 + 128.</p>
<p>Write a function that, given a non-negative right argument which is an integer scalar representing the encoded state and a left argument which is an integer scalar representing the encoded state settings that you want to query, returns 1 if all of the codes in the left argument are found in the right argument (0 otherwise).</p>
</blockquote>
<p><strong>Solution:</strong> <code>{f←⍸∘⌽(2∘⊥⍣¯1)⋄∧/(f⍺)∊f⍵}</code></p>
<p>The difficult part is to find the set of states for an integer. We need a function that will return <code>1 8 128</code> (or an equivalent representation) for an input of <code>137</code>. To do this, we need the base-2 representations of <span class="math inline">\(137 = 1 + 8 + 128 = 2^0 + 2^3 + 2^7 =
10010001_2\)</span>. The function <code>(2∘⊥⍣¯1)</code> will return the base-2 representation of its argument, and by <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Reverse.htm">reversing</a> and finding <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Where.htm">where</a> the non-zero elements are, we find the correct exponents (<code>1 3 7</code> in this case). That is what the function <code>f</code> does.</p>
<p>Next, we just need to check that all elements of <code>f⍺</code> are also in <code>f⍵</code>.</p>
<h2 id="zigzag-numbers">8. Zigzag Numbers</h2>
<blockquote>
<p>A zigzag number is an integer in which the difference in magnitude of each pair of consecutive digits alternates from positive to negative or negative to positive.</p>
<p>Write a function that takes a single integer greater than or equal to 100 and less than 10<sup>15</sup> as its right argument and returns a 1 if the integer is a zigzag number, 0 otherwise.</p>
</blockquote>
<p><strong>Solution:</strong> <code>∧/2=∘|2-/∘×2-/(10∘⊥⍣¯1)</code></p>
<p>First, we decompose a number into an array of digits, using <code>(10∘⊥⍣¯1)</code> (<a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Decode.htm">Decode</a> (<code>⊥</code>) in base 10). Then, we <a href="https://help.dyalog.com/latest/#Language/Primitive%20Operators/Reduce%20N%20Wise.htm">Reduce N Wise</a> to compute the difference between each pair of digits, take the sign, and ensure that the signs are indeed alternating.</p>
<h2 id="rise-and-fall">9. Rise and Fall</h2>
<blockquote>
<p>Write a function that, given a right argument which is an integer scalar or vector, returns a 1 if the values of the right argument conform to the following pattern (0 otherwise):</p>
<ul>
<li>The elements increase or stay the same until the “apex” (the highest value) is reached</li>
<li>After the apex, any remaining values decrease or remain the same</li>
</ul>
</blockquote>
<p><strong>Solution:</strong> <code>{∧/(⍳∘≢≡⍋)¨(⊂((⊢⍳⌈/)↑⊢),⍵),⊂⌽((⊢⍳⌈/)↓⊢),⍵}</code></p>
<p>How do we approach this? First we have to split the vector at the “apex”. The train <code>(⊢⍳⌈/)</code> will return the <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Index%20Of.htm">index of</a> (<code>⍳</code>) the maximum element.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true"></a>      (⊢⍳⌈/)1 3 3 4 5 2 1</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true"></a>5</span></code></pre></div>
<p>Combined with <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Take.htm">Take</a> (<code>↑</code>) and <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Drop.htm">Drop</a> (<code>↓</code>), we build a two-element vector containing both parts, in ascending order (we <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Reverse.htm">Reverse</a> (<code>⌽</code>) one of them). Note that we have to <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Ravel.htm">Ravel</a> (<code>,</code>) the argument to avoid rank errors in Index Of.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true"></a>      {(⊂((⊢⍳⌈/)↑⊢),⍵),⊂⌽((⊢⍳⌈/)↓⊢),⍵}1 3 3 4 5 2 1</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true"></a>┌─────────┬───┐</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true"></a>│1 3 3 4 5│1 2│</span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true"></a>└─────────┴───┘</span></code></pre></div>
<p>Next, <code>(⍳∘≢≡⍋)</code> on each of the two vectors will test if they are non-decreasing (i.e. if the ranks of all the elements correspond to a simple range from 1 to the size of the vector).</p>
<h2 id="stacking-it-up">10. Stacking It Up</h2>
<blockquote>
<p>Write a function that takes as its right argument a vector of simple arrays of rank 2 or less (scalar, vector, or matrix). Each simple array will consist of either non-negative integers or printable ASCII characters. The function must return a simple character array that displays identically to what <code>{⎕←⍵}¨</code> displays when applied to the right argument.</p>
</blockquote>
<p><strong>Solution:</strong> <code>{↑⊃,/↓¨⍕¨⍵}</code></p>
<p>The first step is to <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Format%20Monadic.htm">Format</a> (<code>⍕</code>) everything to get strings.<span><label for="sn-4" class="margin-toggle">⊕</label><input type="checkbox" id="sn-4" class="margin-toggle" /><span class="marginnote"> A lot of trial-and-error is always necessary when dealing with nested arrays, and this being about formatting exacerbates the problem.<br />
<br />
</span></span> The next step would be to “stack everything vertically”, so we will need <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Mix.htm">Mix</a> (<code>↑</code>) at some point. However, if we do it immediately we don’t get the correct result:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true"></a>      {↑⍕¨⍵}(3 3⍴⍳9)(↑'Adam' 'Michael')</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true"></a>1 2 3  </span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true"></a>4 5 6  </span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true"></a>7 8 9  </span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true"></a></span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true"></a>Adam   </span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true"></a>Michael</span></code></pre></div>
<p>Mix is padding with spaces both horizontally (necessary as we want the output to be a simple array of characters) and vertically (not what we want). We will have to decompose everything line by line, and then mix all the lines together. This is exactly what <a href="https://help.dyalog.com/latest/#Language/Primitive%20Functions/Split.htm">Split</a><span><label for="sn-5" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-5" class="margin-toggle" /><span class="sidenote">Split is the dual of Mix.<br />
<br />
</span></span> (<code>↓</code>) does:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode default"><code class="sourceCode default"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true"></a>      {↓¨⍕¨⍵}(3 3⍴⍳9)(↑'Adam' 'Michael')(⍳10) '*'(5 5⍴⍳25)</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true"></a>┌───────────────────┬─────────────────┬──────────────────────┬─┬───────────────</span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true"></a>│┌─────┬─────┬─────┐│┌───────┬───────┐│┌────────────────────┐│*│┌──────────────</span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true"></a>││1 2 3│4 5 6│7 8 9│││Adam   │Michael│││1 2 3 4 5 6 7 8 9 10││ ││ 1  2  3  4  5</span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true"></a>│└─────┴─────┴─────┘│└───────┴───────┘│└────────────────────┘│ │└──────────────</span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true"></a>└───────────────────┴─────────────────┴──────────────────────┴─┴───────────────</span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true"></a></span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true"></a>      ─────────────────────────────────────────────────────────────┐</span>
<span id="cb6-9"><a href="#cb6-9" aria-hidden="true"></a>      ┬──────────────┬──────────────┬──────────────┬──────────────┐│</span>
<span id="cb6-10"><a href="#cb6-10" aria-hidden="true"></a>      │ 6  7  8  9 10│11 12 13 14 15│16 17 18 19 20│21 22 23 24 25││</span>
<span id="cb6-11"><a href="#cb6-11" aria-hidden="true"></a>      ┴──────────────┴──────────────┴──────────────┴──────────────┘│</span>
<span id="cb6-12"><a href="#cb6-12" aria-hidden="true"></a>      ─────────────────────────────────────────────────────────────┘</span></code></pre></div>
<p>Next, we clean this up with Ravel (<code>,</code>) and we can Mix to obtain the final result.</p>
    </section>
</article>
]]></summary>
</entry>
<entry>
    <title>Operations Research and Optimization: where to start?</title>
    <link href="https://www.lozeve.com/posts/operations-research-references.html" />
    <id>https://www.lozeve.com/posts/operations-research-references.html</id>
    <published>2020-05-27T00:00:00Z</published>
    <updated>2020-05-27T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
    <section class="header">
        
    </section>
    <section>
        <div id="toc"><h2>Table of Contents</h2><ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#why-is-it-hard-to-approach">Why is it hard to approach?</a></li>
<li><a href="#where-to-start">Where to start</a>
<ul>
<li><a href="#introduction-and-modelling">Introduction and modelling</a></li>
<li><a href="#theory-and-algorithms">Theory and algorithms</a></li>
<li><a href="#online-courses">Online courses</a></li>
</ul></li>
<li><a href="#solvers-and-computational-resources">Solvers and computational resources <span id="solvers"></span></a></li>
<li><a href="#conclusion">Conclusion</a></li>
<li><a href="#references">References</a></li>
</ul></div>
<h2 id="introduction">Introduction</h2>
<p><a href="https://en.wikipedia.org/wiki/Operations_research">Operations research</a> (OR) is a vast area comprising a lot of theory, different branches of mathematics, and too many applications to count. In this post, I will try to explain why it can be a little disconcerting to explore at first, and how to start investigating the topic with a few references to get started.</p>
<p>Keep in mind that although I studied it during my graduate studies, this is not my primary area of expertise (I’m a data scientist by trade), and I definitely don’t pretend to know everything in OR. This is a field too vast for any single person to understand in its entirety, and I talk mostly from an “amateur mathematician and computer scientist” standpoint.</p>
<h2 id="why-is-it-hard-to-approach">Why is it hard to approach?</h2>
<p>Operations research can be difficult to approach, since there are many references and subfields. Compared to machine learning for instance, OR has a slightly longer history (going back to the 17th century, for example with <a href="https://en.wikipedia.org/wiki/Gaspard_Monge">Monge</a> and the <a href="https://en.wikipedia.org/wiki/Transportation_theory_(mathematics)">optimal transport problem</a>)<span><label for="sn-0" class="margin-toggle">⊕</label><input type="checkbox" id="sn-0" class="margin-toggle" /><span class="marginnote"> For a very nice introduction (in French) to optimal transport, see these blog posts by <a href="https://twitter.com/gabrielpeyre">Gabriel Peyré</a>, on the CNRS maths blog: <a href="https://images.math.cnrs.fr/Le-transport-optimal-numerique-et-ses-applications-Partie-1.html">Part 1</a> and <a href="https://images.math.cnrs.fr/Le-transport-optimal-numerique-et-ses-applications-Partie-2.html">Part 2</a>. See also the resources on <a href="https://optimaltransport.github.io/">optimaltransport.github.io</a> (in English).<br />
<br />
</span></span>. This means that good textbooks and such have existed for a long time, but also that there will be plenty of material to choose from.</p>
<p>Moreover, OR is very close to applications. Sometimes methods may vary a lot in their presentation depending on whether they’re applied to train tracks, sudoku, or travelling salesmen. In practice, the terminology and notations are not the same everywhere. This is disconcerting if you are used to “pure” mathematics, where notations evolved over a long time and is pretty much standardised for many areas. In contrast, if you’re used to the statistics literature with its <a href="https://lingpipe-blog.com/2009/10/13/whats-wrong-with-probability-notation/">strange notations</a>, you will find that OR is actually very well formalized.</p>
<p>There are many subfields of operations research, including all kinds of optimization (constrained and unconstrained), game theory, dynamic programming, stochastic processes, etc.</p>
<h2 id="where-to-start">Where to start</h2>
<h3 id="introduction-and-modelling">Introduction and modelling</h3>
<p>For an overall introduction, I recommend <span class="citation" data-cites="wentzel1988_operat">Wentzel (<a href="#ref-wentzel1988_operat" role="doc-biblioref">1988</a>)</span>. It is an old book, published by Mir Publications, a Soviet publisher which published many excellent scientific textbooks<span><label for="sn-1" class="margin-toggle">⊕</label><input type="checkbox" id="sn-1" class="margin-toggle" /><span class="marginnote"> Mir also published <a href="https://mirtitles.org/2011/06/03/physics-for-everyone/"><em>Physics for Everyone</em></a> by Lev Landau and Alexander Kitaigorodsky, a three-volume introduction to physics that is really accessible. Together with Feynman’s famous <a href="https://www.feynmanlectures.caltech.edu/">lectures</a>, I read them (in French) when I was a kid, and it was the best introduction I could possibly have to the subject.<br />
<br />
</span></span>. It is out of print, but it is available <a href="https://archive.org/details/WentzelOperationsResearchMir1983">on Archive.org</a><span><label for="sn-2" class="margin-toggle">⊕</label><input type="checkbox" id="sn-2" class="margin-toggle" /><span class="marginnote"><br />
<br />
<img src="/images/or_references/wentzel.jpg" width="200" /><br />
<br />
</span></span>. The book is quite old, but everything presented is still extremely relevant today. It requires absolutely no background, and covers everything: a general introduction to the field, linear programming, dynamic programming, Markov processes and queues, Monte Carlo methods, and game theory. Even if you already know some of these topics, the presentations is so clear that it is a pleasure to read! (In particular, it is one of the best presentations of dynamic programming that I have ever read. The explanation of the simplex algorithm is also excellent.)</p>
<p>If you are interested in optimization, the first thing you have to learn is modelling, i.e. transforming your problem (described in natural language, often from a particular industrial application) into a mathematical programme. The mathematical programme is the structure on which you will be able to apply an algorithm to find an optimal solution. Even if (like me) you are initially more interested in the algorithmic side of things, learning to create models will shed a lot of light on the overall process, and will give you more insight in general on the reasoning behind algorithms.</p>
<p>The best book I have read on the subject is <span class="citation" data-cites="williams2013_model">Williams (<a href="#ref-williams2013_model" role="doc-biblioref">2013</a>)</span><span><label for="sn-3" class="margin-toggle">⊕</label><input type="checkbox" id="sn-3" class="margin-toggle" /><span class="marginnote"><br />
<br />
<img src="/images/or_references/williams.jpg" width="200" /><br />
<br />
</span></span>. It contains a lot of concrete, step-by-step examples on concrete applications, in a multitude of domains, and remains very easy to read and to follow. It covers nearly every type of problem, so it is very useful as a reference. When you encounter a concrete problem in real life afterwards, you will know how to construct an appropriate model, and in the process you will often identify a common type of problem. The book then gives plenty of advice on how to approach each type of problem. Finally, it is also a great resource to build a “mental map” of the field, avoiding getting lost in the jungle of linear, stochastic, mixed integer, quadratic, and other network problems.</p>
<p>Another interesting resource is the freely available <a href="https://docs.mosek.com/modeling-cookbook/index.html">MOSEK Modeling Cookbook</a>, covering many types of problems, with more mathematical details than in <span class="citation" data-cites="williams2013_model">Williams (<a href="#ref-williams2013_model" role="doc-biblioref">2013</a>)</span>. It is built for people wanting to use the commercial <a href="https://www.mosek.com/">MOSEK</a> solver, so it could be useful if you plan to use a solver package like this one (more details on solvers <a href="#solvers">below</a>).</p>
<h3 id="theory-and-algorithms">Theory and algorithms</h3>
<p>The basic algorithm for optimization is the <a href="https://en.wikipedia.org/wiki/Simplex_algorithm">simplex algorithm</a>, developed by Dantzig in the 1940s to solve <a href="https://en.wikipedia.org/wiki/Linear_programming">linear programming</a> problems. It is the one of the main building blocks for mathematical optimization, and is used and referenced extensively in all kinds of approaches. As such, it is really important to understand it in detail. There are many books on the subject, but I especially liked <span class="citation" data-cites="chvatal1983_linear">Chvátal (<a href="#ref-chvatal1983_linear" role="doc-biblioref">1983</a>)</span> (out of print, but you can find cheap used versions on Amazon). It covers everything there is to know on the simplex algorithms (step-by-step explanations with simple examples, correctness and complexity analysis, computational and implementation considerations) and to many applications. I think it is overall the best introduction. <span class="citation" data-cites="vanderbei2014_linear">Vanderbei (<a href="#ref-vanderbei2014_linear" role="doc-biblioref">2014</a>)</span> follows a very similar outline, but contains more recent computational considerations<span><label for="sn-4" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-4" class="margin-toggle" /><span class="sidenote">For all the details about practical implementations of the simplex algorithm, <span class="citation" data-cites="maros2003_comput">Maros (<a href="#ref-maros2003_comput" role="doc-biblioref">2003</a>)</span> is dedicated to the computational aspects and contains everything you will need.<br />
<br />
</span></span>. (The author also has <a href="http://vanderbei.princeton.edu/307/lectures.html">lecture slides</a>.)</p>
<p>For more books on linear programming, the two books <span class="citation" data-cites="dantzig1997_linear">Dantzig (<a href="#ref-dantzig1997_linear" role="doc-biblioref">1997</a>)</span>, <span class="citation" data-cites="dantzig2003_linear">Dantzig (<a href="#ref-dantzig2003_linear" role="doc-biblioref">2003</a>)</span> are very complete, if somewhat more mathematically advanced. <span class="citation" data-cites="bertsimas1997_introd">Bertsimas and Tsitsiklis (<a href="#ref-bertsimas1997_introd" role="doc-biblioref">1997</a>)</span> is also a great reference, if you can find it.</p>
<p>For all the other subfields, <a href="https://or.stackexchange.com/a/870">this great StackExchange answer</a> contains a lot of useful references, including most of the above. Of particular note are <span class="citation" data-cites="peyreComputationalOptimalTransport2019">Peyré and Cuturi (<a href="#ref-peyreComputationalOptimalTransport2019" role="doc-biblioref">2019</a>)</span> for optimal transport, <span class="citation" data-cites="boyd2004_convex">Boyd (<a href="#ref-boyd2004_convex" role="doc-biblioref">2004</a>)</span> for convex optimization (<a href="https://web.stanford.edu/~boyd/cvxbook/">freely available online</a>), and <span class="citation" data-cites="nocedal2006_numer">Nocedal (<a href="#ref-nocedal2006_numer" role="doc-biblioref">2006</a>)</span> for numerical optimization. <span class="citation" data-cites="kochenderfer2019_algor">Kochenderfer (<a href="#ref-kochenderfer2019_algor" role="doc-biblioref">2019</a>)</span><span><label for="sn-5" class="margin-toggle">⊕</label><input type="checkbox" id="sn-5" class="margin-toggle" /><span class="marginnote"><br />
<br />
<img src="/images/or_references/kochenderfer.jpg" width="200" /><br />
<br />
</span></span> is not in the list (because it is very recent) but is also excellent, with examples in Julia covering nearly every kind of optimization algorithms.</p>
<h3 id="online-courses">Online courses</h3>
<p>If you would like to watch video lectures, there are a few good opportunities freely available online, in particular on <a href="https://ocw.mit.edu/index.htm">MIT OpenCourseWare</a>. The list of courses at MIT is available <a href="https://orc.mit.edu/academics/course-offerings">on their webpage</a>. I haven’t actually looked in details at the courses content<span><label for="sn-6" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-6" class="margin-toggle" /><span class="sidenote">I am more comfortable reading books than watching lecture videos online. Although I liked attending classes during my studies, I do not have the same feeling in front of a video. When I read, I can re-read three times the same sentence, pause to look up something, or skim a few paragraphs. I find that the inability to do that with a video diminishes greatly my ability to concentrate.<br />
<br />
</span></span>, so I cannot vouch for them directly, but MIT courses are generally of excellent quality. Most courses are also taught by Bertsimas and Bertsekas, who are very famous and wrote many excellent books.</p>
<p>Of particular notes are:</p>
<ul>
<li><a href="https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-251j-introduction-to-mathematical-programming-fall-2009/">Introduction to Mathematical Programming</a>,</li>
<li><a href="https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/">Nonlinear Optimization</a>,</li>
<li><a href="https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-253-convex-analysis-and-optimization-spring-2012/">Convex Analysis and Optimization</a>,</li>
<li><a href="https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-972-algebraic-techniques-and-semidefinite-optimization-spring-2006/">Algebraic Techniques and Semidefinite Optimization</a>,</li>
<li><a href="https://ocw.mit.edu/courses/sloan-school-of-management/15-083j-integer-programming-and-combinatorial-optimization-fall-2009/">Integer Programming and Combinatorial Optimization</a>.</li>
</ul>
<p>Another interesting course I found online is <a href="https://www.ams.jhu.edu/~wcook12/dl/index.html">Deep Learning in Discrete Optimization</a>, at Johns Hopkins<span><label for="sn-7" class="margin-toggle">⊕</label><input type="checkbox" id="sn-7" class="margin-toggle" /><span class="marginnote"> It is taught by William Cook, who is the author of <a href="https://press.princeton.edu/books/paperback/9780691163529/in-pursuit-of-the-traveling-salesman"><em>In Pursuit of the Traveling Salesman</em></a>, a nice introduction to the TSP problem in a readable form.<br />
<br />
</span></span>. It contains an interesting overview of deep learning and integer programming, with a focus on connections, and applications to recent research areas in ML (reinforcement learning, attention, etc.).</p>
<h2 id="solvers-and-computational-resources">Solvers and computational resources <span id="solvers"></span></h2>
<p>When you start reading about modelling and algorithms, I recommend you try solving a few problems yourself, either by hand for small instances, or using an existing solver. It will allow you to follow the examples in books, while also practising your modelling skills. You will also get an intuition of what is difficult to model and to solve.</p>
<p>There are many solvers available, both free and commercial, with various capabilities. I recommend you use the fantastic <a href="https://github.com/JuliaOpt/JuMP.jl">JuMP</a><span><label for="sn-8" class="margin-toggle">⊕</label><input type="checkbox" id="sn-8" class="margin-toggle" /><span class="marginnote"><br />
<br />
<img src="/images/or_references/jump.svg" width="250" /><br />
<br />
</span></span> library for Julia, which exposes a domain-specific language for modelling, along with interfaces to nearly all major solver packages. (Even if you don’t know Julia, this is a great and easy way to start!) If you’d rather use Python, you can use Google’s <a href="https://developers.google.com/optimization/introduction/python">OR-Tools</a> or <a href="https://github.com/coin-or/pulp">PuLP</a> for linear programming.</p>
<p>Regarding solvers, there is a <a href="http://www.juliaopt.org/JuMP.jl/stable/installation/#Getting-Solvers-1">list of solvers</a> on JuMP’s documentation, with their capabilities and their license. Free solvers include <a href="https://www.gnu.org/software/glpk/">GLPK</a> (linear programming), <a href="https://github.com/coin-or/Ipopt">Ipopt</a> (non-linear programming), and <a href="https://scip.zib.de/">SCIP</a> (mixed-integer linear programming).</p>
<p>Commercial solvers often have better performance, and some of them propose a free academic license: <a href="https://www.mosek.com/">MOSEK</a>, <a href="https://www.gurobi.com/">Gurobi</a>, and <a href="https://www.ibm.com/analytics/cplex-optimizer">IBM CPLEX</a> in particular all offer free academic licenses and work very well with JuMP.</p>
<p>Another awesome resource is the <a href="https://neos-server.org/neos/">NEOS Server</a>. It offers free computing resources for numerical optimization, including all major free and commercial solvers! You can submit jobs on it in a standard format, or interface your favourite programming language with it. The fact that such an amazing resource exists for free, for everyone is extraordinary. They also have an accompanying book, the <a href="https://neos-guide.org/">NEOS Guide</a>, containing many case studies and description of problem types. The <a href="https://neos-guide.org/content/optimization-taxonomy">taxonomy</a> may be particularly useful.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Operations research is a fascinating topic, and it has an abundant literature that makes it very easy to dive into the subject. If you are interested in algorithms, modelling for practical applications, or just wish to understand more, I hope to have given you the first steps to follow, start reading and experimenting.</p>
<h2 class="unnumbered" id="references">References</h2>
<div id="refs" class="references hanging-indent" role="doc-bibliography">
<div id="ref-bertsimas1997_introd">
<p>Bertsimas, Dimitris, and John N. Tsitsiklis. 1997. <em>Introduction to Linear Optimization</em>. Belmont, Massachusetts: Athena Scientific. <a href="http://www.athenasc.com/linoptbook.html">http://www.athenasc.com/linoptbook.html</a>.</p>
</div>
<div id="ref-boyd2004_convex">
<p>Boyd, Stephen. 2004. <em>Convex Optimization</em>. Cambridge, UK New York: Cambridge University Press.</p>
</div>
<div id="ref-chvatal1983_linear">
<p>Chvátal, Vašek. 1983. <em>Linear Programming</em>. New York: W.H. Freeman.</p>
</div>
<div id="ref-dantzig1997_linear">
<p>Dantzig, George. 1997. <em>Linear Programming 1: Introduction</em>. New York: Springer. <a href="https://www.springer.com/gp/book/9780387948331">https://www.springer.com/gp/book/9780387948331</a>.</p>
</div>
<div id="ref-dantzig2003_linear">
<p>———. 2003. <em>Linear Programming 2: Theory and Extensions</em>. New York: Springer. <a href="https://www.springer.com/gp/book/9780387986135">https://www.springer.com/gp/book/9780387986135</a>.</p>
</div>
<div id="ref-kochenderfer2019_algor">
<p>Kochenderfer, Mykel. 2019. <em>Algorithms for Optimization</em>. Cambridge, Massachusetts: The MIT Press.</p>
</div>
<div id="ref-maros2003_comput">
<p>Maros, István. 2003. <em>Computational Techniques of the Simplex Method</em>. Boston: Kluwer Academic Publishers.</p>
</div>
<div id="ref-nocedal2006_numer">
<p>Nocedal, Jorge. 2006. <em>Numerical Optimization</em>. New York: Springer. <a href="https://www.springer.com/gp/book/9780387303031">https://www.springer.com/gp/book/9780387303031</a>.</p>
</div>
<div id="ref-peyreComputationalOptimalTransport2019">
<p>Peyré, Gabriel, and Marco Cuturi. 2019. “Computational Optimal Transport.” <em>Foundations and Trends in Machine Learning</em> 11 (5-6): 355–206. <a href="https://doi.org/10.1561/2200000073">https://doi.org/10.1561/2200000073</a>.</p>
</div>
<div id="ref-vanderbei2014_linear">
<p>Vanderbei, Robert. 2014. <em>Linear Programming : Foundations and Extensions</em>. New York: Springer.</p>
</div>
<div id="ref-wentzel1988_operat">
<p>Wentzel, Elena S. 1988. <em>Operations Research: A Methodological Approach</em>. Moscow: Mir publishers.</p>
</div>
<div id="ref-williams2013_model">
<p>Williams, H. Paul. 2013. <em>Model Building in Mathematical Programming</em>. Chichester, West Sussex: Wiley. <a href="https://www.wiley.com/en-fr/Model+Building+in+Mathematical+Programming,+5th+Edition-p-9781118443330">https://www.wiley.com/en-fr/Model+Building+in+Mathematical+Programming,+5th+Edition-p-9781118443330</a>.</p>
</div>
</div>
    </section>
</article>
]]></summary>
</entry>
<entry>
    <title>ICLR 2020 Notes: Speakers and Workshops</title>
    <link href="https://www.lozeve.com/posts/iclr-2020-notes.html" />
    <id>https://www.lozeve.com/posts/iclr-2020-notes.html</id>
    <published>2020-05-05T00:00:00Z</published>
    <updated>2020-05-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
    <section class="header">
        
    </section>
    <section>
        <div id="toc"><h2>Table of Contents</h2><ul>
<li><a href="#the-format-of-the-virtual-conference">The Format of the Virtual Conference</a></li>
<li><a href="#speakers">Speakers</a>
<ul>
<li><a href="#prof.-leslie-kaelbling-doing-for-our-robots-what-nature-did-for-us">Prof. Leslie Kaelbling, <span>Doing for Our Robots What Nature Did For Us</span></a></li>
<li><a href="#dr.-laurent-dinh-invertible-models-and-normalizing-flows">Dr. Laurent Dinh, <span>Invertible Models and Normalizing Flows</span></a></li>
<li><a href="#profs.-yann-lecun-and-yoshua-bengio-reflections-from-the-turing-award-winners">Profs. Yann LeCun and Yoshua Bengio, <span>Reflections from the Turing Award Winners</span></a></li>
</ul></li>
<li><a href="#workshops">Workshops</a>
<ul>
<li><a href="#beyond-tabula-rasa-in-reinforcement-learning-agents-that-remember-adapt-and-generalize"><span>Beyond ‘tabula rasa’ in reinforcement learning: agents that remember, adapt, and generalize</span></a></li>
<li><a href="#causal-learning-for-decision-making"><span>Causal Learning For Decision Making</span></a></li>
<li><a href="#bridging-ai-and-cognitive-science"><span>Bridging AI and Cognitive Science</span></a></li>
<li><a href="#integration-of-deep-neural-models-and-differential-equations"><span>Integration of Deep Neural Models and Differential Equations</span></a></li>
</ul></li>
</ul></div>
<p>ICLR is one of the most important conferences in machine learning, and as such, I was very excited to have the opportunity to volunteer and attend the first fully-virtual edition of the event. The whole content of the conference has been made <a href="https://iclr.cc/virtual_2020/index.html">publicly available</a>, only a few days after the end of the event!</p>
<p>I would like to thank the <a href="https://iclr.cc/Conferences/2020/Committees">organizing committee</a> for this incredible event, and the possibility to volunteer to help other participants<span><label for="sn-0" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-0" class="margin-toggle" /><span class="sidenote">To better organize the event, and help people navigate the various online tools, they brought in 500(!) volunteers, waved our registration fees, and asked us to do simple load-testing and tech support. This was a very generous offer, and felt very rewarding for us, as we could attend the conference, and give back to the organization a little bit.<br />
<br />
</span></span>.</p>
<p>The many volunteers, the online-only nature of the event, and the low registration fees also allowed for what felt like a very diverse, inclusive event. Many graduate students and researchers from industry (like me), who do not generally have the time or the resources to travel to conferences like this, were able to attend, and make the exchanges richer.</p>
<p>In this post, I will try to give my impressions on the event, the speakers, and the workshops that I could attend. I will do a quick recap of the most interesting papers I saw in a future post.</p>
<h2 id="the-format-of-the-virtual-conference">The Format of the Virtual Conference</h2>
<p>As a result of global travel restrictions, the conference was made fully-virtual. It was supposed to take place in Addis Ababa, Ethiopia, which is great for people who are often the target of restrictive visa policies in Northern American countries.</p>
<p>The thing I appreciated most about the conference format was its emphasis on <em>asynchronous</em> communication. Given how little time they had to plan the conference, they could have made all poster presentations via video-conference and call it a day. Instead, each poster had to record a 5-minute video<span><label for="sn-1" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-1" class="margin-toggle" /><span class="sidenote">The videos are streamed using <a href="https://library.slideslive.com/">SlidesLive</a>, which is a great solution for synchronising videos and slides. It is very comfortable to navigate through the slides and synchronising the video to the slides and vice-versa. As a result, SlidesLive also has a very nice library of talks, including major conferences. This is much better than browsing YouTube randomly.<br />
<br />
</span></span> summarising their research. Alongside each presentation, there was a dedicated Rocket.Chat channel<span><label for="sn-2" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-2" class="margin-toggle" /><span class="sidenote"><a href="https://rocket.chat/">Rocket.Chat</a> seems to be an <a href="https://github.com/RocketChat/Rocket.Chat">open-source</a> alternative to Slack. Overall, the experience was great, and I appreciate the efforts of the organizers to use open source software instead of proprietary applications. I hope other conferences will do the same, and perhaps even avoid Zoom, because of recent privacy concerns (maybe try <a href="https://jitsi.org/">Jitsi</a>?).<br />
<br />
</span></span> where anyone could ask a question to the authors, or just show their appreciation for the work. This was a fantastic idea as it allowed any participant to interact with papers and authors at any time they please, which is especially important in a setting where people were spread all over the globe.</p>
<p>There were also Zoom session where authors were available for direct, face-to-face discussions, allowing for more traditional conversations. But asking questions on the channel had also the advantage of keeping a track of all questions that were asked by other people. As such, I quickly acquired the habit of watching the video, looking at the chat to see the previous discussions (even if they happened in the middle of the night in my timezone!), and then skimming the paper or asking questions myself.</p>
<p>All of these excellent ideas were implemented by an <a href="https://iclr.cc/virtual_2020/papers.html?filter=keywords">amazing website</a>, collecting all papers in a searchable, easy-to-use interface, and even including a nice <a href="https://iclr.cc/virtual_2020/paper_vis.html">visualisation</a> of papers as a point cloud!</p>
<h2 id="speakers">Speakers</h2>
<p>Overall, there were 8 speakers (two for each day of the main conference). They made a 40-minute presentation, and then there was a Q&amp;A both via the chat and via Zoom. I only saw a few of them, but I expect I will be watching the others in the near future.</p>
<h3 id="prof.-leslie-kaelbling-doing-for-our-robots-what-nature-did-for-us">Prof. Leslie Kaelbling, <a href="https://iclr.cc/virtual_2020/speaker_2.html">Doing for Our Robots What Nature Did For Us</a></h3>
<p>This talk was fascinating. It is about robotics, and especially how to design the “software” of our robots. We want to program a robot in a way that it could work the best it can over all possible domains it can encounter. I loved the discussion on how to describe the space of distributions over domains, from the point of view of the robot factory:</p>
<ul>
<li>The domain could be very narrow (e.g. playing a specific Atari game) or very broad and complex (performing a complex task in an open world).</li>
<li>The factory could know in advance in which domain the robot will evolve, or have a lot of uncertainty around it.</li>
</ul>
<p>There are many ways to describe a policy (i.e. the software running in the robot’s head), and many ways to obtain them. If you are familiar with recent advances in reinforcement learning, this talk is a great occasion to take a step back, and review the relevant background ideas from engineering and control theory.</p>
<p>Finally, the most important take-away from this talk is the importance of <em>abstractions</em>. Whatever the methods we use to program our robots, we still need a lot of human insights to give them good structural biases. There are many more insights, on the cost of experience, (hierarchical) planning, learning constraints, etc, so I strongly encourage you to watch the talk!</p>
<h3 id="dr.-laurent-dinh-invertible-models-and-normalizing-flows">Dr. Laurent Dinh, <a href="https://iclr.cc/virtual_2020/speaker_4.html">Invertible Models and Normalizing Flows</a></h3>
<p>This is a very clear presentation of an area of ML research I do not know very well. I really like the approach of teaching a set of methods from a “historical”, personal point of view. Laurent Dinh shows us how he arrived at this topic, what he finds interesting, in a very personal and relatable manner. This has the double advantage of introducing us to a topic that he is passionate about, while also giving us a glimpse of a researcher’s process, without hiding the momentary disillusions and disappointments, but emphasising the great achievements. Normalizing flows are also very interesting because it is grounded in strong theoretical results, that brings together a lot of different methods.</p>
<h3 id="profs.-yann-lecun-and-yoshua-bengio-reflections-from-the-turing-award-winners">Profs. Yann LeCun and Yoshua Bengio, <a href="https://iclr.cc/virtual_2020/speaker_7.html">Reflections from the Turing Award Winners</a></h3>
<p>This talk was very interesting, and yet felt very familiar, as if I already saw a very similar one elsewhere. Especially for Yann LeCun, who clearly reuses the same slides for many presentations at various events. They both came back to their favourite subjects: self-supervised learning for Yann LeCun, and system 1/system 2 for Yoshua Bengio. All in all, they are very good speakers, and their presentations are always insightful. Yann LeCun gives a lot of references on recent technical advances, which is great if you want to go deeper in the approaches he recommends. Yoshua Bengio is also very good at broadening the debate around deep learning, and introducing very important concepts from cognitive science.</p>
<h2 id="workshops">Workshops</h2>
<p>On Sunday, there were <a href="https://iclr.cc/virtual_2020/workshops.html">15 different workshops</a>. All of them were recorded, and are available on the website. As always, unfortunately, there are too many interesting things to watch everything, but I saw bits and pieces of different workshops.</p>
<h3 id="beyond-tabula-rasa-in-reinforcement-learning-agents-that-remember-adapt-and-generalize"><a href="https://iclr.cc/virtual_2020/workshops_12.html">Beyond ‘tabula rasa’ in reinforcement learning: agents that remember, adapt, and generalize</a></h3>
<p>A lot of pretty advanced talks about RL. The general theme was meta-learning, aka “learning to learn”. This is a very active area of research, which goes way beyond classical RL theory, and offer many interesting avenues to adjacent fields (both inside ML and outside, especially cognitive science). The <a href="http://www.betr-rl.ml/2020/abs/101/">first talk</a>, by Martha White, about inductive biases, was a very interesting and approachable introduction to the problems and challenges of the field. There was also a panel with Jürgen Schmidhuber. We hear a lot about him from the various controversies, but it’s nice to see him talking about research and future developments in RL.</p>
<h3 id="causal-learning-for-decision-making"><a href="https://iclr.cc/virtual_2020/workshops_14.html">Causal Learning For Decision Making</a></h3>
<p>Ever since I read Judea Pearl’s <a href="https://www.goodreads.com/book/show/36204378-the-book-of-why"><em>The Book of Why</em></a> on causality, I have been interested in how we can incorporate causality reasoning in machine learning. This is a complex topic, and I’m not sure yet that it is a complete revolution as Judea Pearl likes to portray it, but it nevertheless introduces a lot of new fascinating ideas. Yoshua Bengio gave an interesting talk<span><label for="sn-3" class="margin-toggle sidenote-number"></label><input type="checkbox" id="sn-3" class="margin-toggle" /><span class="sidenote">You can find it at 4:45:20 in the <a href="https://slideslive.com/38926830/workshop-on-causal-learning-for-decision-making">livestream</a> of the workshop.<br />
<br />
</span></span> (even though very similar to his keynote talk) on causal priors for deep learning.</p>
<h3 id="bridging-ai-and-cognitive-science"><a href="https://iclr.cc/virtual_2020/workshops_4.html">Bridging AI and Cognitive Science</a></h3>
<p>Cognitive science is fascinating, and I believe that collaboration between ML practitioners and cognitive scientists will greatly help advance both fields. I only watched <a href="https://baicsworkshop.github.io/program/baics_45.html">Leslie Kaelbling’s presentation</a>, which echoes a lot of things from her talk at the main conference. It complements it nicely, with more focus on intelligence, especially <em>embodied</em> intelligence. I think she has the right approach to relationships between AI and natural science, explicitly listing the things from her work that would be helpful to natural scientists, and things she wish she knew about natural intelligences. It raises many fascinating questions on ourselves, what we build, and what we understand. I felt it was very motivational!</p>
<h3 id="integration-of-deep-neural-models-and-differential-equations"><a href="https://iclr.cc/virtual_2020/workshops_5.html">Integration of Deep Neural Models and Differential Equations</a></h3>
<p>I didn’t attend this workshop, but I think I will watch the presentations if I can find the time. I have found the intersection of differential equations and ML very interesting, ever since the famous <a href="https://papers.nips.cc/paper/7892-neural-ordinary-differential-equations">NeurIPS best paper</a> on Neural ODEs. I think that such improvements to ML theory from other fields in mathematics would be extremely beneficial to a better understanding of the systems we build.</p>
    </section>
</article>
]]></summary>
</entry>
<entry>
    <title>Reading notes: Hierarchical Optimal Transport for Document Representation</title>
    <link href="https://www.lozeve.com/posts/hierarchical-optimal-transport-for-document-classification.html" />
    <id>https://www.lozeve.com/posts/hierarchical-optimal-transport-for-document-classification.html</id>
    <published>2020-04-05T00:00:00Z</published>
    <updated>2020-04-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
    <section class="header">
        
    </section>
    <section>
        <div id="toc"><h2>Table of Contents</h2><ul>
<li><a href="#introduction-and-motivation">Introduction and motivation</a></li>
<li><a href="#background-optimal-transport">Background: optimal transport</a></li>
<li><a href="#hierarchical-optimal-transport">Hierarchical optimal transport</a></li>
<li><a href="#experiments">Experiments</a></li>
<li><a href="#conclusion">Conclusion</a></li>
<li><a href="#references">References</a></li>
</ul></div>
<p>Two weeks ago, I did a presentation for my colleagues of the paper from <span class="citation" data-cites="yurochkin2019_hierar_optim_trans_docum_repres">Yurochkin et al. (<a href="#ref-yurochkin2019_hierar_optim_trans_docum_repres" role="doc-biblioref">2019</a>)</span>, from <a href="https://papers.nips.cc/book/advances-in-neural-information-processing-systems-32-2019">NeurIPS 2019</a>. It contains an interesting approach to document classification leading to strong performance, and, most importantly, excellent interpretability.</p>
<p>This paper seems interesting to me because of it uses two methods with strong theoretical guarantees: optimal transport and topic modelling. Optimal transport looks very promising to me in NLP, and has seen a lot of interest in recent years due to advances in approximation algorithms, such as entropy regularisation. It is also quite refreshing to see approaches using solid results in optimisation, compared to purely experimental deep learning methods.</p>
<h2 id="introduction-and-motivation">Introduction and motivation</h2>
<p>The problem of the paper is to measure similarity (i.e. a distance) between pairs of documents, by incorporating <em>semantic</em> similarities (and not only syntactic artefacts), without encountering scalability issues.</p>
<p>They propose a “meta-distance” between documents, called the hierarchical optimal topic transport (HOTT), providing a scalable metric incorporating topic information between documents. As such, they try to combine two different levels of analysis:</p>
<ul>
<li>word embeddings data, to embed language knowledge (via pre-trained embeddings for instance),</li>
<li>topic modelling methods (e.g. <a href="https://scikit-learn.org/stable/modules/decomposition.html#latentdirichletallocation">Latent Dirichlet Allocation</a>), to represent semantically-meaningful groups of words.</li>
</ul>
<h2 id="background-optimal-transport">Background: optimal transport</h2>
<p>The essential backbone of the method is the Wasserstein distance, derived from optimal transport theory. Optimal transport is a fascinating and deep subject, so I won’t enter into the details here. For an introduction to the theory and its applications, check out the excellent book from <span class="citation" data-cites="peyreComputationalOptimalTransport2019">Peyré and Cuturi (<a href="#ref-peyreComputationalOptimalTransport2019" role="doc-biblioref">2019</a>)</span>, (<a href="https://arxiv.org/abs/1803.00567">available on ArXiv</a> as well). There are also <a href="https://images.math.cnrs.fr/Le-transport-optimal-numerique-et-ses-applications-Partie-1.html?lang=fr">very nice posts</a> (in French) by Gabriel Peyré on the <a href="https://images.math.cnrs.fr/">CNRS maths blog</a>. Many more resources (including slides for presentations) are available at <a href="https://optimaltransport.github.io">https://optimaltransport.github.io</a>. For a more complete theoretical treatment of the subject, check out <span class="citation" data-cites="santambrogioOptimalTransportApplied2015">Santambrogio (<a href="#ref-santambrogioOptimalTransportApplied2015" role="doc-biblioref">2015</a>)</span>, or, if you’re feeling particularly adventurous, <span class="citation" data-cites="villaniOptimalTransportOld2009">Villani (<a href="#ref-villaniOptimalTransportOld2009" role="doc-biblioref">2009</a>)</span>.</p>
<p>For this paper, only a superficial understanding of how the <a href="https://en.wikipedia.org/wiki/Wasserstein_metric">Wasserstein distance</a> works is necessary. Optimal transport is an optimisation technique to lift a distance between points in a given metric space, to a distance between probability <em>distributions</em> over this metric space. The historical example is to move piles of dirt around: you know the distance between any two points, and you have piles of dirt lying around<span><label for="sn-0" class="margin-toggle">⊕</label><input type="checkbox" id="sn-0" class="margin-toggle" /><span class="marginnote"> Optimal transport originated with Monge, and then Kantorovich, both of whom had very clear military applications in mind (either in Revolutionary France, or during WWII). A lot of historical examples move cannon balls, or other military equipment, along a front line.<br />
<br />
</span></span>. Now, if you want to move these piles to another configuration (fewer piles, say, or a different repartition of dirt a few metres away), you need to find the most efficient way to move them. The total cost you obtain will define a distance between the two configurations of dirt, and is usually called the <a href="https://en.wikipedia.org/wiki/Earth_mover%27s_distance">earth mover’s distance</a>, which is just an instance of the general Wasserstein metric.</p>
<p>More formally, we start with two sets of points <span class="math inline">\(x = (x_1, x_2, \ldots,
      x_n)\)</span>, and <span class="math inline">\(y = (y_1, y_2, \ldots, y_n)\)</span>, along with probability distributions <span class="math inline">\(p \in \Delta^n\)</span>, <span class="math inline">\(q \in \Delta^m\)</span> over <span class="math inline">\(x\)</span> and <span class="math inline">\(y\)</span> (<span class="math inline">\(\Delta^n\)</span> is the probability simplex of dimension <span class="math inline">\(n\)</span>, i.e. the set of vectors of size <span class="math inline">\(n\)</span> summing to 1). We can then define the Wasserstein distance as <span class="math display">\[
W_1(p, q) = \min_{P \in \mathbb{R}_+^{n\times m}} \sum_{i,j} C_{i,j} P_{i,j}
\]</span> <span class="math display">\[
\text{\small subject to } \sum_j P_{i,j} = p_i \text{ \small and } \sum_i P_{i,j} = q_j,
\]</span> where <span class="math inline">\(C_{i,j} = d(x_i, x_j)\)</span> are the costs computed from the original distance between points, and <span class="math inline">\(P_{i,j}\)</span> represent the amount we are moving from pile <span class="math inline">\(i\)</span> to pile <span class="math inline">\(j\)</span>.</p>
<p>Now, how can this be applied to a natural language setting? Once we have word embeddings, we can consider that the vocabulary forms a metric space (we can compute a distance, for instance the euclidean or the <a href="https://en.wikipedia.org/wiki/Cosine_similarity">cosine distance</a>, between two word embeddings). The key is to define documents as <em>distributions</em> over words.</p>
<p>Given a vocabulary <span class="math inline">\(V \subset \mathbb{R}^n\)</span> and a corpus <span class="math inline">\(D = (d^1, d^2, \ldots, d^{\lvert D \rvert})\)</span>, we represent a document as <span class="math inline">\(d^i \in \Delta^{l_i}\)</span> where <span class="math inline">\(l_i\)</span> is the number of unique words in <span class="math inline">\(d^i\)</span>, and <span class="math inline">\(d^i_j\)</span> is the proportion of word <span class="math inline">\(v_j\)</span> in the document <span class="math inline">\(d^i\)</span>. The word mover’s distance (WMD) is then defined simply as <span class="math display">\[ \operatorname{WMD}(d^1, d^2) = W_1(d^1, d^2). \]</span></p>
<p>If you didn’t follow all of this, don’t worry! The gist is: if you have a distance between points, you can solve an optimisation problem to obtain a distance between <em>distributions</em> over these points! This is especially useful when you consider that each word embedding is a point, and a document is just a set of words, along with the number of times they appear.</p>
<h2 id="hierarchical-optimal-transport">Hierarchical optimal transport</h2>
<p>Using optimal transport, we can use the word mover’s distance to define a metric between documents. However, this suffers from two drawbacks:</p>
<ul>
<li>Documents represented as distributions over words are not easily interpretable. For long documents, the vocabulary is huge and word frequencies are not easily understandable for humans.</li>
<li>Large vocabularies mean that the space on which we have to find an optimal matching is huge. The <a href="https://en.wikipedia.org/wiki/Hungarian_algorithm">Hungarian algorithm</a> used to compute the optimal transport distance runs in <span class="math inline">\(O(l^3 \log l)\)</span>, where <span class="math inline">\(l\)</span> is the maximum number of unique words in each documents. This quickly becomes intractable as the size of documents become larger, or if you have to compute all pairwise distances between a large number of documents (e.g. for clustering purposes).</li>
</ul>
<p>To escape these issues, we will add an intermediary step using <a href="https://en.wikipedia.org/wiki/Topic_model">topic modelling</a>. Once we have topics <span class="math inline">\(T = (t_1, t_2, \ldots, t_{\lvert T
\rvert}) \subset \Delta^{\lvert V \rvert}\)</span>, we get two kinds of representations:</p>
<ul>
<li>representations of topics as distributions over words,</li>
<li>representations of documents as distributions over topics <span class="math inline">\(\bar{d^i} \in \Delta^{\lvert T \rvert}\)</span>.</li>
</ul>
<p>Since they are distributions over words, the word mover’s distance defines a metric over topics. As such, the topics with the WMD become a metric space.</p>
<p>We can now define the hierarchical optimal topic transport (HOTT), as the optimal transport distance between documents, represented as distributions over topics. For two documents <span class="math inline">\(d^1\)</span>, <span class="math inline">\(d^2\)</span>, <span class="math display">\[
\operatorname{HOTT}(d^1, d^2) = W_1\left( \sum_{k=1}^{\lvert T \rvert} \bar{d^1_k} \delta_{t_k}, \sum_{k=1}^{\lvert T \rvert} \bar{d^2_k} \delta_{t_k} \right).
\]</span> where <span class="math inline">\(\delta_{t_k}\)</span> is a distribution supported on topic <span class="math inline">\(t_k\)</span>.</p>
<p>Note that in this case, we used optimal transport <em>twice</em>:</p>
<ul>
<li>once to find distances between topics (WMD),</li>
<li>once to find distances between documents, where the distance between topics became the costs in the new optimal transport problem.</li>
</ul>
<p>The first one can be precomputed once for all subsequent distances, so it is invariable in the number of documents we have to process. The second one only operates on <span class="math inline">\(\lvert T \rvert\)</span> topics instead of the full vocabulary: the resulting optimisation problem is much smaller! This is great for performance, as it should be easy now to compute all pairwise distances in a large set of documents.</p>
<p>Another interesting insight is that topics are represented as collections of words (we can keep the top 20 as a visual representations), and documents as collections of topics with weights. Both of these representations are highly interpretable for a human being who wants to understand what’s going on. I think this is one of the strongest aspects of these approaches: both the various representations and the algorithms are fully interpretable. Compared to a deep learning approach, we can make sense of every intermediate step, from the representations of topics to the weights in the optimisation algorithm to compute higher-level distances.</p>
<p><img src="/images/hott_fig1.jpg" /><span><label for="sn-1" class="margin-toggle">⊕</label><input type="checkbox" id="sn-1" class="margin-toggle" /><span class="marginnote"> Representation of two documents in topic space, along with how the distance was computed between them. Everything is interpretable: from the documents as collections of topics, to the matchings between topics determining the overall distance between the books <span class="citation" data-cites="yurochkin2019_hierar_optim_trans_docum_repres">(Yurochkin et al. <a href="#ref-yurochkin2019_hierar_optim_trans_docum_repres" role="doc-biblioref">2019</a>)</span>.<br />
<br />
</span></span></p>
<h2 id="experiments">Experiments</h2>
<p>The paper is very complete regarding experiments, providing a full evaluation of the method on one particular application: document clustering. They use <a href="https://scikit-learn.org/stable/modules/decomposition.html#latentdirichletallocation">Latent Dirichlet Allocation</a> to compute topics and GloVe for pretrained word embeddings <span class="citation" data-cites="pennington2014_glove">(Pennington, Socher, and Manning <a href="#ref-pennington2014_glove" role="doc-biblioref">2014</a>)</span>, and <a href="https://www.gurobi.com/">Gurobi</a> to solve the optimisation problems. Their code is available <a href="https://github.com/IBM/HOTT">on GitHub</a>.</p>
<p>If you want the details, I encourage you to read the full paper, they tested the methods on a wide variety of datasets, with datasets containing very short documents (like Twitter), and long documents with a large vocabulary (books). With a simple <span class="math inline">\(k\)</span>-NN classification, they establish that HOTT performs best on average, especially on large vocabularies (books, the “gutenberg” dataset). It also has a much better computational performance than alternative methods based on regularisation of the optimal transport problem directly on words. So the hierarchical nature of the approach allows to gain considerably in performance, along with improvements in interpretability.</p>
<p>What’s really interesting in the paper is the sensitivity analysis: they ran experiments with different word embeddings methods (word2vec, <span class="citation" data-cites="mikolovDistributedRepresentationsWords2013">(Mikolov et al. <a href="#ref-mikolovDistributedRepresentationsWords2013" role="doc-biblioref">2013</a>)</span>), and with different parameters for the topic modelling (topic truncation, number of topics, etc). All of these reveal that changes in hyperparameters do not impact the performance of HOTT significantly. This is extremely important in a field like NLP where most of the times small variations in approach lead to drastically different results.</p>
<h2 id="conclusion">Conclusion</h2>
<p>All in all, this paper present a very interesting approach to compute distance between natural-language documents. It is no secret that I like methods with strong theoretical background (in this case optimisation and optimal transport), guaranteeing a stability and benefiting from decades of research in a well-established domain.</p>
<p>Most importantly, this paper allows for future exploration in document representation with <em>interpretability</em> in mind. This is often added as an afterthought in academic research but is one of the most important topics for the industry, as a system must be understood by end users, often not trained in ML, before being deployed. The notion of topic, and distances as weights, can be understood easily by anyone without significant background in ML or in maths.</p>
<p>Finally, I feel like they did not stop at a simple theoretical argument, but carefully checked on real-world datasets, measuring sensitivity to all the arbitrary choices they had to take. Again, from an industry perspective, this allows to implement the new approach quickly and easily, being confident that it won’t break unexpectedly without extensive testing.</p>
<h2 class="unnumbered" id="references">References</h2>
<div id="refs" class="references hanging-indent" role="doc-bibliography">
<div id="ref-mikolovDistributedRepresentationsWords2013">
<p>Mikolov, Tomas, Ilya Sutskever, Kai Chen, Greg S Corrado, and Jeff Dean. 2013. “Distributed Representations of Words and Phrases and Their Compositionality.” In <em>Advances in Neural Information Processing Systems 26</em>, 3111–9. <a href="http://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf">http://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf</a>.</p>
</div>
<div id="ref-pennington2014_glove">
<p>Pennington, Jeffrey, Richard Socher, and Christopher Manning. 2014. “Glove: Global Vectors for Word Representation.” In <em>Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing (EMNLP)</em>, 1532–43. Doha, Qatar: Association for Computational Linguistics. <a href="https://doi.org/10.3115/v1/D14-1162">https://doi.org/10.3115/v1/D14-1162</a>.</p>
</div>
<div id="ref-peyreComputationalOptimalTransport2019">
<p>Peyré, Gabriel, and Marco Cuturi. 2019. “Computational Optimal Transport.” <em>Foundations and Trends in Machine Learning</em> 11 (5-6): 355–206. <a href="https://doi.org/10.1561/2200000073">https://doi.org/10.1561/2200000073</a>.</p>
</div>
<div id="ref-santambrogioOptimalTransportApplied2015">
<p>Santambrogio, Filippo. 2015. <em>Optimal Transport for Applied Mathematicians</em>. Vol. 87. Progress in Nonlinear Differential Equations and Their Applications. Cham: Springer International Publishing. <a href="https://doi.org/10.1007/978-3-319-20828-2">https://doi.org/10.1007/978-3-319-20828-2</a>.</p>
</div>
<div id="ref-villaniOptimalTransportOld2009">
<p>Villani, Cédric. 2009. <em>Optimal Transport: Old and New</em>. Grundlehren Der Mathematischen Wissenschaften 338. Berlin: Springer.</p>
</div>
<div id="ref-yurochkin2019_hierar_optim_trans_docum_repres">
<p>Yurochkin, Mikhail, Sebastian Claici, Edward Chien, Farzaneh Mirzazadeh, and Justin M Solomon. 2019. “Hierarchical Optimal Transport for Document Representation.” In <em>Advances in Neural Information Processing Systems 32</em>, 1599–1609. <a href="http://papers.nips.cc/paper/8438-hierarchical-optimal-transport-for-document-representation.pdf">http://papers.nips.cc/paper/8438-hierarchical-optimal-transport-for-document-representation.pdf</a>.</p>
</div>
</div>
    </section>
</article>
]]></summary>
</entry>
<entry>
    <title>Mindsay: Towards Self-Learning Chatbots</title>
    <link href="https://www.lozeve.com/posts/self-learning-chatbots-destygo.html" />
    <id>https://www.lozeve.com/posts/self-learning-chatbots-destygo.html</id>
    <published>2019-04-06T00:00:00Z</published>
    <updated>2019-04-06T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
    <section class="header">
        
    </section>
    <section>
        <p>Last week I made a presentation at the <a href="https://www.meetup.com/Paris-NLP/">Paris NLP Meetup</a>, on how we implemented self-learning chatbots in production at Mindsay.</p>
<p>It was fascinating to other people interested in NLP about the technologies and models we deploy at work! It’s always nice to have some feedback about our work, and preparing this talk forced me to take a step back about what we do and rethink it in new interesting ways.</p>
<p>Also check out the <a href="https://nlpparis.wordpress.com/2019/03/29/paris-nlp-season-3-meetup-4-at-meilleursagents/">other presentations</a>, one about diachronic (i.e. time-dependent) word embeddings and the other about the different models and the use of Knowledge Bases for Information Retrieval. (This might even give us new ideas to explore…)</p>
<p>If you’re interested about exciting applications at the confluence of Reinforcement Learning and NLP, the slides are available <a href="https://drive.google.com/file/d/1aS1NpPxRzsQCsAqoQIVZrdf8R1Y2VKrT/view">here</a>. It includes basic RL theory, how we transposed it to the specific case of conversational agents, the technical and mathematical challenges in implementing self-learning chatbots, and of course plenty of references for further reading if we piqued your interest!</p>
<p><strong><strong>Update:</strong></strong> The videos are now available on the <a href="https://nlpparis.wordpress.com/2019/03/29/paris-nlp-season-3-meetup-4-at-meilleursagents/">NLP Meetup website</a>.</p>
<p><strong><strong>Update 2:</strong></strong> Destygo changed its name to <a href="https://www.mindsay.com/">Mindsay</a>!</p>
    </section>
</article>
]]></summary>
</entry>
<entry>
    <title>Random matrices from the Ginibre ensemble</title>
    <link href="https://www.lozeve.com/posts/ginibre-ensemble.html" />
    <id>https://www.lozeve.com/posts/ginibre-ensemble.html</id>
    <published>2019-03-20T00:00:00Z</published>
    <updated>2019-03-20T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
    <section class="header">
        
    </section>
    <section>
        <h3 id="ginibre-ensemble-and-its-properties">Ginibre ensemble and its properties</h3>
<p>The <em>Ginibre ensemble</em> is a set of random matrices with the entries chosen independently. Each entry of a <span class="math inline">\(n \times n\)</span> matrix is a complex number, with both the real and imaginary part sampled from a normal distribution of mean zero and variance <span class="math inline">\(1/2n\)</span>.</p>
<p>Random matrices distributions are very complex and are a very active subject of research. I stumbled on this example while reading an article in <em>Notices of the AMS</em> by Brian C. Hall <a href="#ref-1">(1)</a>.</p>
<p>Now what is interesting about these random matrices is the distribution of their <span class="math inline">\(n\)</span> eigenvalues in the complex plane.</p>
<p>The <a href="https://en.wikipedia.org/wiki/Circular_law">circular law</a> (first established by Jean Ginibre in 1965 <a href="#ref-2">(2)</a>) states that when <span class="math inline">\(n\)</span> is large, with high probability, almost all the eigenvalues lie in the unit disk. Moreover, they tend to be nearly uniformly distributed there.</p>
<p>I find this mildly fascinating that such a straightforward definition of a random matrix can exhibit such non-random properties in their spectrum.</p>
<h3 id="simulation">Simulation</h3>
<p>I ran a quick simulation, thanks to <a href="https://julialang.org/">Julia</a>’s great ecosystem for linear algebra and statistical distributions:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode julia"><code class="sourceCode julia"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true"></a><span class="kw">using</span> LinearAlgebra</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true"></a><span class="kw">using</span> UnicodePlots</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true"></a></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true"></a><span class="kw">function</span> ginibre(n)</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true"></a>    <span class="kw">return</span> randn((n<span class="op">,</span> n)) <span class="op">*</span> sqrt(<span class="fl">1</span><span class="op">/</span><span class="fl">2</span>n) <span class="op">+</span> <span class="cn">im</span> <span class="op">*</span> randn((n<span class="op">,</span> n)) <span class="op">*</span> sqrt(<span class="fl">1</span><span class="op">/</span><span class="fl">2</span>n)</span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true"></a><span class="kw">end</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true"></a></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true"></a>v <span class="op">=</span> eigvals(ginibre(<span class="fl">2000</span>))</span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true"></a></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true"></a>scatterplot(real(v)<span class="op">,</span> imag(v)<span class="op">,</span> xlim<span class="op">=</span>[<span class="op">-</span><span class="fl">1.5</span><span class="op">,</span><span class="fl">1.5</span>]<span class="op">,</span> ylim<span class="op">=</span>[<span class="op">-</span><span class="fl">1.5</span><span class="op">,</span><span class="fl">1.5</span>])</span></code></pre></div>
<p>I like using <code>UnicodePlots</code> for this kind of quick-and-dirty plots, directly in the terminal. Here is the output:</p>
<p><img src="../images/ginibre.png" /></p>
<h3 id="references">References</h3>
<ol>
<li><span id="ref-1"></span>Hall, Brian C. 2019. “Eigenvalues of Random Matrices in the General Linear Group in the Large-<span class="math inline">\(N\)</span> Limit.” <em>Notices of the American Mathematical Society</em> 66, no. 4 (Spring): 568-569. <a href="https://www.ams.org/journals/notices/201904/201904FullIssue.pdf">https://www.ams.org/journals/notices/201904/201904FullIssue.pdf</a></li>
<li><span id="ref-2"></span>Ginibre, Jean. “Statistical ensembles of complex, quaternion, and real matrices.” Journal of Mathematical Physics 6.3 (1965): 440-449. <a href="https://doi.org/10.1063/1.1704292">https://doi.org/10.1063/1.1704292</a></li>
</ol>
    </section>
</article>
]]></summary>
</entry>
<entry>
    <title>Peano Axioms</title>
    <link href="https://www.lozeve.com/posts/peano.html" />
    <id>https://www.lozeve.com/posts/peano.html</id>
    <published>2019-03-18T00:00:00Z</published>
    <updated>2019-03-18T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
    <section class="header">
        
    </section>
    <section>
        <div id="toc"><h2>Table of Contents</h2><ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#the-axioms">The Axioms</a></li>
<li><a href="#addition">Addition</a>
<ul>
<li><a href="#commutativity">Commutativity</a></li>
<li><a href="#associativity">Associativity</a></li>
<li><a href="#identity-element">Identity element</a></li>
</ul></li>
<li><a href="#going-further">Going further</a></li>
<li><a href="#references">References</a></li>
</ul></div>
<h2 id="introduction">Introduction</h2>
<p>I have recently bought the book <em>Category Theory</em> from Steve Awodey <span class="citation" data-cites="awodeyCategoryTheory2010">(Awodey <a href="#ref-awodeyCategoryTheory2010" role="doc-biblioref">2010</a>)</span> is awesome, but probably the topic for another post), and a particular passage excited my curiosity:</p>
<blockquote>
<p>Let us begin by distinguishing between the following things: i. categorical foundations for mathematics, ii. mathematical foundations for category theory.</p>
<p>As for the first point, one sometimes hears it said that category theory can be used to provide “foundations for mathematics,” as an alternative to set theory. That is in fact the case, but it is not what we are doing here. In set theory, one often begins with existential axioms such as “there is an infinite set” and derives further sets by axioms like “every set has a powerset,” thus building up a universe of mathematical objects (namely sets), which in principle suffice for “all of mathematics.”</p>
</blockquote>
<p>This statement is interesting because one often considers category theory as pretty “fundamental”, in the sense that it has no issue with considering what I call “dangerous” notions, such as the category <span class="math inline">\(\mathbf{Set}\)</span> of all sets, and even the category <span class="math inline">\(\mathbf{Cat}\)</span> of all categories. Surely a theory this general, that can afford to study such objects, should provide suitable foundations for mathematics? Awodey addresses these issues very explicitly in the section following the quote above, and finds a good way of avoiding circular definitions.</p>
<p>Now, I remember some basics from my undergrad studies about foundations of mathematics. I was told that if you could define arithmetic, you basically had everything else “for free” (as Kronecker famously said, “natural numbers were created by God, everything else is the work of men”). I was also told that two sets of axioms existed, the <a href="https://en.wikipedia.org/wiki/Peano_axioms">Peano axioms</a> and the <a href="https://en.wikipedia.org/wiki/Zermelo%E2%80%93Fraenkel_set_theory">Zermelo-Fraenkel</a> axioms. Also, I should steer clear of the axiom of choice if I could, because one can do <a href="https://en.wikipedia.org/wiki/Banach%E2%80%93Tarski_paradox">strange things</a> with it, and it is equivalent to many <a href="https://en.wikipedia.org/wiki/Zorn%27s_lemma">different statements</a>. Finally (and this I knew mainly from <em>Logicomix</em>, I must admit), it is <a href="https://en.wikipedia.org/wiki/G%C3%B6del%27s_incompleteness_theorems">impossible</a> for a set of axioms to be both complete and consistent.</p>
<p>Given all this, I realised that my knowledge of foundational mathematics was pretty deficient. I do not believe that it is a very important topic that everyone should know about, even though Gödel’s incompleteness theorem is very interesting from a logical and philosophical standpoint. However, I wanted to go deeper on this subject.</p>
<p>In this post, I will try to share my path through Peano’s axioms <span class="citation" data-cites="gowersPrincetonCompanionMathematics2010">(Gowers, Barrow-Green, and Leader <a href="#ref-gowersPrincetonCompanionMathematics2010" role="doc-biblioref">2010</a>)</span>, because they are very simple, and it is easy to uncover basic algebraic structure from them.</p>
<h2 id="the-axioms">The Axioms</h2>
<p>The purpose of the axioms is to define a collection of objects that we will call the <em>natural numbers</em>. Here, we place ourselves in the context of <a href="https://en.wikipedia.org/wiki/First-order_logic">first-order logic</a>. Logic is not the main topic here, so I will just assume that I have access to some quantifiers, to some predicates, to some variables, and, most importantly, to a relation <span class="math inline">\(=\)</span> which is reflexive, symmetric, transitive, and closed over the natural numbers.</p>
<p>Without further digressions, let us define two symbols <span class="math inline">\(0\)</span> and <span class="math inline">\(s\)</span> (called <em>successor</em>) such that:</p>
<ol>
<li><span class="math inline">\(0\)</span> is a natural number.</li>
<li>For every natural number <span class="math inline">\(n\)</span>, <span class="math inline">\(s(n)\)</span> is a natural number. (“The successor of a natural number is a natural number.”)</li>
<li>For all natural number <span class="math inline">\(m\)</span> and <span class="math inline">\(n\)</span>, if <span class="math inline">\(s(m) = s(n)\)</span>, then <span class="math inline">\(m=n\)</span>. (“If two numbers have the same successor, they are equal.”)</li>
<li>For every natural number <span class="math inline">\(n\)</span>, <span class="math inline">\(s(n) = 0\)</span> is false. (“<span class="math inline">\(0\)</span> is nobody’s successor.”)</li>
<li>If <span class="math inline">\(A\)</span> is a set such that:
<ul>
<li><span class="math inline">\(0\)</span> is in <span class="math inline">\(A\)</span></li>
<li>for every natural number <span class="math inline">\(n\)</span>, if <span class="math inline">\(n\)</span> is in <span class="math inline">\(A\)</span> then <span class="math inline">\(s(n)\)</span> is in <span class="math inline">\(A\)</span></li>
</ul>
then <span class="math inline">\(A\)</span> contains every natural number.</li>
</ol>
<p>Let’s break this down. Axioms 1–4 define a collection of objects, written <span class="math inline">\(0\)</span>, <span class="math inline">\(s(0)\)</span>, <span class="math inline">\(s(s(0))\)</span>, and so on, and ensure their basic properties. All of these are natural numbers by the first four axioms, but how can we be sure that <em>all</em> natural numbers are of the form <span class="math inline">\(s( \cdots s(0))\)</span>? This is where the <em>induction axiom</em> (Axiom 5) intervenes. It ensures that every natural number is “well-formed” according to the previous axioms.</p>
<p>But Axiom 5 is slightly disturbing, because it mentions a “set” and a relation “is in”. This seems pretty straightforward at first sight, but these notions were never defined anywhere before that! Isn’t our goal to <em>define</em> all these notions in order to derive a foundation of mathematics? (I still don’t know the answer to that question.) I prefer the following alternative version of the induction axiom:</p>
<ul>
<li>If <span class="math inline">\(\varphi\)</span> is a <a href="https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)">unary predicate</a> such that:
<ul>
<li><span class="math inline">\(\varphi(0)\)</span> is true</li>
<li>for every natural number <span class="math inline">\(n\)</span>, if <span class="math inline">\(\varphi(n)\)</span> is true, then <span class="math inline">\(\varphi(s(n))\)</span> is also true</li>
</ul>
then <span class="math inline">\(\varphi(n)\)</span> is true for every natural number <span class="math inline">\(n\)</span>.</li>
</ul>
<p>The alternative formulation is much better in my opinion, as it obviously implies the first one (juste choose <span class="math inline">\(\varphi(n)\)</span> as “<span class="math inline">\(n\)</span> is a natural number”), and it only references predicates. It will also be much more useful afterwards, as we will see.</p>
<h2 id="addition">Addition</h2>
<p>What is needed afterwards? The most basic notion after the natural numbers themselves is the addition operator. We define an operator <span class="math inline">\(+\)</span> by the following (recursive) rules:</p>
<ol>
<li><span class="math inline">\(\forall a,\quad a+0 = a\)</span>.</li>
<li><span class="math inline">\(\forall a, \forall b,\quad a + s(b) = s(a+b)\)</span>.</li>
</ol>
<p>Let us use these rules to prove the basic properties of <span class="math inline">\(+\)</span>.</p>
<h3 id="commutativity">Commutativity</h3>
<div class="proposition">
<p><span class="math inline">\(\forall a, \forall b,\quad a+b = b+a\)</span>.</p>
</div>
<div class="proof">
<p>First, we prove that every natural number commutes with <span class="math inline">\(0\)</span>.</p>
<ul>
<li><p><span class="math inline">\(0+0 = 0+0\)</span>.</p></li>
<li><p>For every natural number <span class="math inline">\(a\)</span> such that <span class="math inline">\(0+a = a+0\)</span>, we have:</p>
<span class="math display">\[\begin{align}
 0 + s(a) &amp;= s(0+a)\\
 &amp;= s(a+0)\\
 &amp;= s(a)\\
 &amp;= s(a) + 0.
\end{align}
\]</span></li>
</ul>
<p>By Axiom 5, every natural number commutes with <span class="math inline">\(0\)</span>.</p>
<p>We can now prove the main proposition:</p>
<ul>
<li><p><span class="math inline">\(\forall a,\quad a+0=0+a\)</span>.</p></li>
<li><p>For all <span class="math inline">\(a\)</span> and <span class="math inline">\(b\)</span> such that <span class="math inline">\(a+b=b+a\)</span>,</p>
<span class="math display">\[\begin{align}
 a + s(b) &amp;= s(a+b)\\
 &amp;= s(b+a)\\
 &amp;= s(b) + a.     
\end{align}
\]</span></li>
</ul>
<p>We used the opposite of the second rule for <span class="math inline">\(+\)</span>, namely <span class="math inline">\(\forall a,
\forall b,\quad s(a) + b = s(a+b)\)</span>. This can easily be proved by another induction.</p>
</div>
<h3 id="associativity">Associativity</h3>
<div class="proposition">
<p><span class="math inline">\(\forall a, \forall b, \forall c,\quad a+(b+c) = (a+b)+c\)</span>.</p>
</div>
<div class="proof">
<p>Todo, left as an exercise to the reader 😉</p>
</div>
<h3 id="identity-element">Identity element</h3>
<div class="proposition">
<p><span class="math inline">\(\forall a,\quad a+0 = 0+a = a\)</span>.</p>
</div>
<div class="proof">
<p>This follows directly from the definition of <span class="math inline">\(+\)</span> and commutativity.</p>
</div>
<p>From all these properties, it follows that the set of natural numbers with <span class="math inline">\(+\)</span> is a commutative <a href="https://en.wikipedia.org/wiki/Monoid">monoid</a>.</p>
<h2 id="going-further">Going further</h2>
<p>We have imbued our newly created set of natural numbers with a significant algebraic structure. From there, similar arguments will create more structure, notably by introducing another operation <span class="math inline">\(\times\)</span>, and an order <span class="math inline">\(\leq\)</span>.</p>
<p>It is now a matter of conventional mathematics to construct the integers <span class="math inline">\(\mathbb{Z}\)</span> and the rationals <span class="math inline">\(\mathbb{Q}\)</span> (using equivalence classes), and eventually the real numbers <span class="math inline">\(\mathbb{R}\)</span>.</p>
<p>It is remarkable how very few (and very simple, as far as you would consider the induction axiom “simple”) axioms are enough to build an entire theory of mathematics. This sort of things makes me agree with Eugene Wigner <span class="citation" data-cites="wignerUnreasonableEffectivenessMathematics1990">(Wigner <a href="#ref-wignerUnreasonableEffectivenessMathematics1990" role="doc-biblioref">1990</a>)</span> when he says that “mathematics is the science of skillful operations with concepts and rules invented just for this purpose”. We drew some arbitrary rules out of thin air, and derived countless properties and theorems from them, basically for our own enjoyment. (As Wigner would say, it is <em>incredible</em> that any of these fanciful inventions coming out of nowhere turned out to be even remotely useful.) Mathematics is done mainly for the mathematician’s own pleasure!</p>
<blockquote>
<p>Mathematics cannot be defined without acknowledging its most obvious feature: namely, that it is interesting — M. Polanyi <span class="citation" data-cites="wignerUnreasonableEffectivenessMathematics1990">(Wigner <a href="#ref-wignerUnreasonableEffectivenessMathematics1990" role="doc-biblioref">1990</a>)</span></p>
</blockquote>
<h2 class="unnumbered" id="references">References</h2>
<div id="refs" class="references hanging-indent" role="doc-bibliography">
<div id="ref-awodeyCategoryTheory2010">
<p>Awodey, Steve. 2010. <em>Category Theory</em>. 2nd ed. Oxford Logic Guides 52. Oxford ; New York: Oxford University Press.</p>
</div>
<div id="ref-gowersPrincetonCompanionMathematics2010">
<p>Gowers, Timothy, June Barrow-Green, and Imre Leader. 2010. <em>The Princeton Companion to Mathematics</em>. Princeton University Press.</p>
</div>
<div id="ref-wignerUnreasonableEffectivenessMathematics1990">
<p>Wigner, Eugene P. 1990. “The Unreasonable Effectiveness of Mathematics in the Natural Sciences.” In <em>Mathematics and Science</em>, by Ronald E Mickens, 291–306. WORLD SCIENTIFIC. <a href="https://doi.org/10.1142/9789814503488_0018">https://doi.org/10.1142/9789814503488_0018</a>.</p>
</div>
</div>
    </section>
</article>
]]></summary>
</entry>
<entry>
    <title>Quick Notes on Reinforcement Learning</title>
    <link href="https://www.lozeve.com/posts/reinforcement-learning-1.html" />
    <id>https://www.lozeve.com/posts/reinforcement-learning-1.html</id>
    <published>2018-11-21T00:00:00Z</published>
    <updated>2018-11-21T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
    <section class="header">
        
    </section>
    <section>
        <h2 id="introduction">Introduction</h2>
<p>In this series of blog posts, I intend to write my notes as I go through Richard S. Sutton’s excellent <em>Reinforcement Learning: An Introduction</em> <a href="#ref-1">(1)</a>.</p>
<p>I will try to formalise the maths behind it a little bit, mainly because I would like to use it as a useful personal reference to the main concepts in RL. I will probably add a few remarks about a possible implementation as I go on.</p>
<h2 id="relationship-between-agent-and-environment">Relationship between agent and environment</h2>
<h3 id="context-and-assumptions">Context and assumptions</h3>
<p>The goal of reinforcement learning is to select the best actions availables to an agent as it goes through a series of states in an environment. In this post, we will only consider <em>discrete</em> time steps.</p>
<p>The most important hypothesis we make is the <em>Markov property:</em></p>
<blockquote>
<p>At each time step, the next state of the agent depends only on the current state and the current action taken. It cannot depend on the history of the states visited by the agent.</p>
</blockquote>
<p>This property is essential to make our problems tractable, and often holds true in practice (to a reasonable approximation).</p>
<p>With this assumption, we can define the relationship between agent and environment as a <em>Markov Decision Process</em> (MDP).</p>
<div class="definition">
<p>A <em>Markov Decision Process</em> is a tuple <span class="math inline">\((\mathcal{S}, \mathcal{A},
\mathcal{R}, p)\)</span> where:</p>
<ul>
<li><p><span class="math inline">\(\mathcal{S}\)</span> is a set of <em>states</em>,</p></li>
<li><p><span class="math inline">\(\mathcal{A}\)</span> is an application mapping each state <span class="math inline">\(s \in
 \mathcal{S}\)</span> to a set <span class="math inline">\(\mathcal{A}(s)\)</span> of possible <em>actions</em> for this state. In this post, we will often simplify by using <span class="math inline">\(\mathcal{A}\)</span> as a set, assuming that all actions are possible for each state,</p></li>
<li><p><span class="math inline">\(\mathcal{R} \subset \mathbb{R}\)</span> is a set of <em>rewards</em>,</p></li>
<li><p>and <span class="math inline">\(p\)</span> is a function representing the <em>dynamics</em> of the MDP:</p>
<span class="math display">\[\begin{align}
 p &amp;: \mathcal{S} \times \mathcal{R} \times \mathcal{S} \times \mathcal{A} \mapsto [0,1] \\
 p(s', r \;|\; s, a) &amp;:= \mathbb{P}(S_t=s', R_t=r \;|\; S_{t-1}=s, A_{t-1}=a),
\end{align}
\]</span>
<p>such that <span class="math display">\[ \forall s \in \mathcal{S}, \forall a \in \mathcal{A},\quad \sum_{s', r} p(s', r \;|\; s, a) = 1. \]</span></p></li>
</ul>
</div>
<p>The function <span class="math inline">\(p\)</span> represents the probability of transitioning to the state <span class="math inline">\(s'\)</span> and getting a reward <span class="math inline">\(r\)</span> when the agent is at state <span class="math inline">\(s\)</span> and chooses action <span class="math inline">\(a\)</span>.</p>
<p>We will also use occasionally the <em>state-transition probabilities</em>:</p>
<span class="math display">\[\begin{align}
 p &amp;: \mathcal{S} \times \mathcal{S} \times \mathcal{A} \mapsto [0,1] \\
p(s' \;|\; s, a) &amp;:= \mathbb{P}(S_t=s' \;|\; S_{t-1}=s, A_{t-1}=a) \\
&amp;= \sum_r p(s', r \;|\; s, a).
\end{align}
\]</span>
<h3 id="rewarding-the-agent">Rewarding the agent</h3>
<div class="definition">
<p>The <em>expected reward</em> of a state-action pair is the function</p>
<span class="math display">\[\begin{align}
r &amp;: \mathcal{S} \times \mathcal{A} \mapsto \mathbb{R} \\
r(s,a) &amp;:= \mathbb{E}[R_t \;|\; S_{t-1}=s, A_{t-1}=a] \\
&amp;= \sum_r r \sum_{s'} p(s', r \;|\; s, a).
\end{align}
\]</span>
</div>
<div class="definition">
<p>The <em>discounted return</em> is the sum of all future rewards, with a multiplicative factor to give more weights to more immediate rewards: <span class="math display">\[ G_t := \sum_{k=t+1}^T \gamma^{k-t-1} R_k, \]</span> where <span class="math inline">\(T\)</span> can be infinite or <span class="math inline">\(\gamma\)</span> can be 1, but not both.</p>
</div>
<h2 id="deciding-what-to-do-policies">Deciding what to do: policies</h2>
<h3 id="defining-our-policy-and-its-value">Defining our policy and its value</h3>
<p>A <em>policy</em> is a way for the agent to choose the next action to perform.</p>
<div class="definition">
<p>A <em>policy</em> is a function <span class="math inline">\(\pi\)</span> defined as</p>
<span class="math display">\[\begin{align}
\pi &amp;: \mathcal{A} \times \mathcal{S} \mapsto [0,1] \\
\pi(a \;|\; s) &amp;:= \mathbb{P}(A_t=a \;|\; S_t=s).
\end{align}
\]</span>
</div>
<p>In order to compare policies, we need to associate values to them.</p>
<div class="definition">
<p>The <em>state-value function</em> of a policy <span class="math inline">\(\pi\)</span> is</p>
<span class="math display">\[\begin{align}
v_{\pi} &amp;: \mathcal{S} \mapsto \mathbb{R} \\
v_{\pi}(s) &amp;:= \text{expected return when starting in $s$ and following $\pi$} \\
v_{\pi}(s) &amp;:= \mathbb{E}_{\pi}\left[ G_t \;|\; S_t=s\right] \\
v_{\pi}(s) &amp;= \mathbb{E}_{\pi}\left[ \sum_{k=0}^{\infty} \gamma^k R_{t+k+1} \;|\; S_t=s\right]
\end{align}
\]</span>
</div>
<p>We can also compute the value starting from a state <span class="math inline">\(s\)</span> by also taking into account the action taken <span class="math inline">\(a\)</span>.</p>
<div class="definition">
<p>The <em>action-value function</em> of a policy <span class="math inline">\(\pi\)</span> is</p>
<span class="math display">\[\begin{align}
q_{\pi} &amp;: \mathcal{S} \times \mathcal{A} \mapsto \mathbb{R} \\
q_{\pi}(s,a) &amp;:= \text{expected return when starting from $s$, taking action $a$, and following $\pi$} \\
q_{\pi}(s,a) &amp;:= \mathbb{E}_{\pi}\left[ G_t \;|\; S_t=s, A_t=a \right] \\
q_{\pi}(s,a) &amp;= \mathbb{E}_{\pi}\left[ \sum_{k=0}^{\infty} \gamma^k R_{t+k+1} \;|\; S_t=s, A_t=a\right]
\end{align}
\]</span>
</div>
<h3 id="the-quest-for-the-optimal-policy">The quest for the optimal policy</h3>
<h2 id="references">References</h2>
<ol>
<li><span id="ref-1"></span>R. S. Sutton and A. G. Barto, Reinforcement learning: an introduction, Second edition. Cambridge, MA: The MIT Press, 2018.</li>
</ol>
    </section>
</article>
]]></summary>
</entry>
<entry>
    <title>Ising model simulation in APL</title>
    <link href="https://www.lozeve.com/posts/ising-apl.html" />
    <id>https://www.lozeve.com/posts/ising-apl.html</id>
    <published>2018-03-05T00:00:00Z</published>
    <updated>2018-03-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
    <section class="header">
        
    </section>
    <section>
        <div id="toc"><h2>Table of Contents</h2><ul>
<li><a href="#the-apl-family-of-languages">The APL family of languages</a>
<ul>
<li><a href="#why-apl">Why APL?</a></li>
<li><a href="#implementations">Implementations</a></li>
</ul></li>
<li><a href="#the-ising-model-in-apl">The Ising model in APL</a></li>
<li><a href="#conclusion">Conclusion</a></li>
</ul></div>
<h2 id="the-apl-family-of-languages">The APL family of languages</h2>
<h3 id="why-apl">Why APL?</h3>
<p>I recently got interested in <a href="https://en.wikipedia.org/wiki/APL_(programming_language)">APL</a>, an <em>array-based</em> programming language. In APL (and derivatives), we try to reason about programs as series of transformations of multi-dimensional arrays. This is exactly the kind of style I like in Haskell and other functional languages, where I also try to use higher-order functions (map, fold, etc) on lists or arrays. A developer only needs to understand these abstractions once, instead of deconstructing each loop or each recursive function encountered in a program.</p>
<p>APL also tries to be a really simple and <em>terse</em> language. This combined with strange Unicode characters for primitive functions and operators, gives it a reputation of unreadability. However, there is only a small number of functions to learn, and you get used really quickly to read them and understand what they do. Some combinations also occur so frequently that you can recognize them instantly (APL programmers call them <em>idioms</em>).</p>
<h3 id="implementations">Implementations</h3>
<p>APL is actually a family of languages. The classic APL, as created by Ken Iverson, with strange symbols, has many implementations. I initially tried <a href="https://www.gnu.org/software/apl/">GNU APL</a>, but due to the lack of documentation and proper tooling, I went to <a href="https://www.dyalog.com/">Dyalog APL</a> (which is proprietary, but free for personal use). There are also APL derivatives, that often use ASCII symbols: <a href="http://www.jsoftware.com/">J</a> (free) and <a href="https://code.kx.com/q/">Q/kdb+</a> (proprietary, but free for personal use).</p>
<p>The advantage of Dyalog is that it comes with good tooling (which is necessary for inserting all the symbols!), a large ecosystem, and pretty good <a href="http://docs.dyalog.com/">documentation</a>. If you want to start, look at <a href="http://www.dyalog.com/mastering-dyalog-apl.htm"><em>Mastering Dyalog APL</em></a> by Bernard Legrand, freely available online.</p>
<h2 id="the-ising-model-in-apl">The Ising model in APL</h2>
<p>I needed a small project to try APL while I was learning. Something array-based, obviously. Since I already implemented a Metropolis-Hastings simulation of the <a href="./ising-model.html">Ising model</a>, which is based on a regular lattice, I decided to reimplement it in Dyalog APL.</p>
<p>It is only a few lines long, but I will try to explain what it does step by step.</p>
<p>The first function simply generates a random lattice filled by elements of <span class="math inline">\(\{-1,+1\}\)</span>.</p>
<pre class="apl"><code>L←{(2×?⍵ ⍵⍴2)-3}
</code></pre>
<p>Let’s deconstruct what is done here:</p>
<ul>
<li>⍵ is the argument of our function.</li>
<li>We generate a ⍵×⍵ matrix filled with 2, using the <code>⍴</code> function: <code>⍵ ⍵⍴2</code></li>
<li><code>?</code> draws a random number between 1 and its argument. We give it our matrix to generate a random matrix of 1 and 2.</li>
<li>We multiply everything by 2 and subtract 3, so that the result is in <span class="math inline">\(\{-1,+1\}\)</span>.</li>
<li>Finally, we assign the result to the name <code>L</code>.</li>
</ul>
<p>Sample output:</p>
<pre class="apl"><code>      ising.L 5
 1 ¯1  1 ¯1  1
 1  1  1 ¯1 ¯1
 1 ¯1 ¯1 ¯1 ¯1
 1  1  1 ¯1 ¯1
¯1 ¯1  1  1  1
</code></pre>
<p>Next, we compute the energy variation (for details on the Ising model, see <a href="./ising-model.html">my previous post</a>).</p>
<pre class="apl"><code>∆E←{
    ⎕IO←0
    (x y)←⍺
    N←⊃⍴⍵
    xn←N|((x-1)y)((x+1)y)
    yn←N|(x(y-1))(x(y+1))
    ⍵[x;y]×+/⍵[xn,yn]
}
</code></pre>
<ul>
<li>⍺ is the left argument (coordinates of the site), ⍵ is the right argument (lattice).</li>
<li>We extract the x and y coordinates of the site.</li>
<li><code>N</code> is the size of the lattice.</li>
<li><code>xn</code> and <code>yn</code> are respectively the vertical and lateral neighbours of the site. <code>N|</code> takes the coordinates modulo <code>N</code> (so the lattice is actually a torus). (Note: we used <code>⎕IO←0</code> to use 0-based array indexing.)</li>
<li><code>+/</code> sums over all neighbours of the site, and then we multiply by the value of the site itself to get <span class="math inline">\(\Delta E\)</span>.</li>
</ul>
<p>Sample output, for site <span class="math inline">\((3, 3)\)</span> in a random <span class="math inline">\(5\times 5\)</span> lattice:</p>
<pre class="apl"><code>      3 3ising.∆E ising.L 5
¯4
</code></pre>
<p>Then comes the actual Metropolis-Hastings part:</p>
<pre class="apl"><code>U←{
    ⎕IO←0
    N←⊃⍴⍵
    (x y)←?N N
    new←⍵
    new[x;y]×←(2×(?0)&gt;*-⍺×x y ∆E ⍵)-1
    new
}
</code></pre>
<ul>
<li>⍺ is the <span class="math inline">\(\beta\)</span> parameter of the Ising model, ⍵ is the lattice.</li>
<li>We draw a random site <span class="math inline">\((x,y)\)</span> with the <code>?</code> function.</li>
<li><code>new</code> is the lattice but with the <span class="math inline">\((x,y)\)</span> site flipped.</li>
<li>We compute the probability <span class="math inline">\(\alpha = \exp(-\beta\Delta E)\)</span> using the <code>*</code> function (exponential) and our previous <code>∆E</code> function.</li>
<li><code>?0</code> returns a uniform random number in <span class="math inline">\([0,1)\)</span>. Based on this value, we decide whether to update the lattice, and we return it.</li>
</ul>
<p>We can now bring everything together for display:</p>
<pre class="apl"><code>Ising←{' ⌹'[1+1=({10 U ⍵}⍣⍵)L ⍺]}
</code></pre>
<ul>
<li>We draw a random lattice of size ⍺ with <code>L ⍺</code>.</li>
<li>We apply to it our update function, with $β$=10, ⍵ times (using the <code>⍣</code> function, which applies a function <span class="math inline">\(n\)</span> times.</li>
<li>Finally, we display -1 as a space and 1 as a domino ⌹.</li>
</ul>
<p>Final output, with a <span class="math inline">\(80\times 80\)</span> random lattice, after 50000 update steps:</p>
<pre class="apl"><code>      80ising.Ising 50000
   ⌹⌹⌹⌹ ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹      ⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹          
   ⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹ ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹           
⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹       ⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹
⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹       ⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹             ⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹     ⌹⌹⌹⌹⌹⌹             ⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹ ⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹       ⌹⌹⌹⌹⌹      ⌹       
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹        ⌹⌹⌹⌹      ⌹⌹⌹      
 ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹       ⌹⌹⌹      
 ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹    ⌹⌹⌹⌹⌹⌹      
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹          ⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹
⌹⌹⌹⌹ ⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹           ⌹⌹⌹⌹                ⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹
  ⌹ ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹ ⌹⌹⌹⌹           ⌹⌹⌹⌹                ⌹⌹⌹      ⌹⌹⌹⌹⌹         
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹                ⌹⌹        ⌹           
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹                                     
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹⌹                                    
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹           ⌹                         
 ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹          ⌹                          
⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹          ⌹⌹⌹⌹⌹⌹                          ⌹⌹     ⌹⌹⌹
⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹                  ⌹⌹⌹⌹⌹⌹         ⌹               ⌹⌹⌹     ⌹⌹⌹
⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹                   ⌹⌹⌹⌹⌹⌹                     ⌹⌹⌹⌹⌹⌹     ⌹⌹⌹
⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹             ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹                ⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹                 ⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹ ⌹⌹⌹⌹⌹⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹                            ⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹                               ⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹                                ⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹                   ⌹⌹⌹⌹             ⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹                   ⌹⌹⌹⌹                           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹                  ⌹⌹⌹⌹⌹⌹⌹                ⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹ 
  ⌹⌹⌹⌹                  ⌹⌹⌹⌹⌹⌹⌹              ⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  
  ⌹⌹⌹⌹                 ⌹⌹⌹⌹⌹⌹⌹⌹⌹             ⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  
  ⌹⌹⌹⌹   ⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  
 ⌹⌹⌹⌹⌹   ⌹ ⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  
 ⌹⌹⌹⌹⌹   ⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  
 ⌹⌹⌹⌹⌹             ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  
⌹⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹
⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹
⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹ ⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹             ⌹          ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹                       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹            ⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹              ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
                    ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹
                       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹⌹⌹⌹  
            ⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹  
           ⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹⌹  
   ⌹⌹⌹ ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹          ⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹           ⌹⌹⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹             ⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹  ⌹⌹⌹⌹   ⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹        ⌹⌹⌹                       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹         ⌹⌹⌹                          ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       ⌹⌹⌹         ⌹⌹⌹    ⌹⌹                      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹     ⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹⌹                      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹          ⌹⌹⌹⌹⌹⌹⌹⌹                      ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹       
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹                         ⌹⌹⌹⌹⌹⌹⌹⌹       
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹⌹⌹⌹                          ⌹⌹⌹⌹⌹⌹⌹       
  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹                          ⌹⌹⌹          
 ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹                        ⌹⌹⌹          
 ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹                        ⌹⌹⌹          
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹                      ⌹⌹⌹⌹          
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹            ⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹       ⌹             ⌹⌹⌹⌹⌹       ⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹ ⌹             ⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹            ⌹⌹⌹⌹⌹⌹     ⌹⌹⌹⌹⌹
⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹             ⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹           ⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹
   ⌹⌹⌹⌹⌹⌹⌹⌹             ⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹ 
   ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         ⌹⌹⌹⌹⌹⌹⌹⌹           
   ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹   ⌹⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         
   ⌹⌹⌹  ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹      ⌹⌹⌹⌹⌹        ⌹⌹⌹⌹⌹⌹⌹    ⌹⌹⌹⌹       ⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹⌹         
</code></pre>
<p>Complete code, with the namespace:</p>
<pre class="apl"><code>:Namespace ising

        L←{(2×?⍵ ⍵⍴2)-3}

        ∆E←{
                ⎕IO←0
                (x y)←⍺
                N←⊃⍴⍵
                xn←N|((x-1)y)((x+1)y)
                yn←N|(x(y-1))(x(y+1))
                ⍵[x;y]×+/⍵[xn,yn]
        }

        U←{
                ⎕IO←0
                N←⊃⍴⍵
                (x y)←?N N
                new←⍵
                new[x;y]×←(2×(?0)&gt;*-⍺×x y ∆E ⍵)-1
                new
        }

        Ising←{' ⌹'[1+1=({10 U ⍵}⍣⍵)L ⍺]}

:EndNamespace
</code></pre>
<h2 id="conclusion">Conclusion</h2>
<p>The algorithm is very fast (I think it can be optimized by the interpreter because there is no branching), and is easy to reason about. The whole program fits in a few lines, and you clearly see what each function and each line does. It could probably be optimized further (I don’t know every APL function yet…), and also could probably be golfed to a few lines (at the cost of readability?).</p>
<p>It took me some time to write this, but Dyalog’s tools make it really easy to insert symbols and to look up what they do. Next time, I will look into some ASCII-based APL descendants. J seems to have a <a href="http://code.jsoftware.com/wiki/NuVoc">good documentation</a> and a tradition of <em>tacit definitions</em>, similar to the point-free style in Haskell. Overall, J seems well-suited to modern functional programming, while APL is still under the influence of its early days when it was more procedural. Another interesting area is K, Q, and their database engine kdb+, which seems to be extremely performant and actually used in production.</p>
<p>Still, Unicode symbols make the code much more readable, mainly because there is a one-to-one link between symbols and functions, which cannot be maintained with only a few ASCII characters.</p>
    </section>
</article>
]]></summary>
</entry>

</feed>
