<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Alex Bowe . com</title>
	
	<link>http://alexbowe.com</link>
	<description>Programming, Mathematics, Data, etc...</description>
	<lastBuildDate>Sun, 20 Jan 2013 19:44:45 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/alexbowe" /><feedburner:info uri="alexbowe" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><creativeCommons:license>http://creativecommons.org/licenses/by/2.0/</creativeCommons:license><item>
		<title>Failing at Google Interviews</title>
		<link>http://feedproxy.google.com/~r/alexbowe/~3/2q5kb0msVtE/</link>
		<comments>http://alexbowe.com/failing-at-google-interviews/#comments</comments>
		<pubDate>Sat, 24 Sep 2011 07:18:41 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[career]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[interviews]]></category>
		<category><![CDATA[reading]]></category>

		<guid isPermaLink="false">http://alexbowe.com/?p=57</guid>
		<description><![CDATA[<p>I&#8217;ve participated in about four sets of Google interviews (of about 3 interviews each) for various positions. I&#8217;m still not a Googler though, which I guess indicates that I&#8217;m not the best person to give this advice. However, I think it&#8217;s about time I put in my 0.002372757892 bitcoins. I recently did exactly this to [...]</p><p>The post <a href="http://alexbowe.com/failing-at-google-interviews/">Failing at Google Interviews</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve participated in about four <em>sets</em> of Google interviews (of about 3 interviews each) for various positions. I&#8217;m still not a Googler though, which I guess indicates that I&#8217;m not the best person to give this advice. However, I think it&#8217;s about time I put in my 0.002372757892 bitcoins. I recently did exactly this to help my brother prepare for his interviews and the guy kicked ass. If he gets the job I&#8217;m going to take as much credit for it as I can ;)</p>
<p>During my interviews I didn&#8217;t sign a NDA, but I do respect the effort that interviewers put into preparing their questions so I&#8217;m not going to discuss them. That doesn&#8217;t matter though, because you probably won&#8217;t get the same questions anyway, and the algorithm stuff is far from the whole story.</p>
<p>This post is mainly about the rituals I perform during preparation for the interviews, and the lessons I have learned from them. I am of the strong opinion that everyone should apply for a job at Google.</p>
<h2>Why Should I?!</h2>
<p>Not everyone wants to work for Google, but there are valuable side effects to a Google interview. Even if you don&#8217;t think you want a job there, or think that you are under-qualified, it is a great idea to just try for one. The absolute worst thing that could happen is that you have fun and learn something.</p>
<p>A couple of the things I learned are algorithms for (weighted) random sampling, queueing, vector calculus, and some cool applications of bloom filters.</p>
<p>The people you will talk to are smart, and it&#8217;s a fun experience to be able to solve problems with smart and passionate people. One of my interviews was just a discussion about the good and bad parts (in our opinions) of a bunch of programming languages (Scheme, Python, C, C++, Java, Erlang). We discussed <a href="http://mitpress.mit.edu/sicp/">SICP</a> and the current state of education, and he recommended some research papers for me to read. All the intriguing questions and back-and-forth made me feel like I was being taught by a modern <a href="http://en.wikipedia.org/wiki/Socratic_method">Socrates</a> (perhaps Google should consider offering a Computer Science degree taught entirely with interviews :P).</p>
<p>Sadly, a subsequent interview stumped me because I didn&#8217;t understand the requirements. Even the stumping interviews have given me a great chance to realise some gaps in my knowledge and refine my approach. I knew that it was important to get the requirements right, but this really drove it home.</p>
<p>I hope I&#8217;ve got you curious about what you could learn from a Google interview. If you are worried about the possible rejection, treat it as a win in a game of <a href="http://rejectiontherapy.com/rules/">Rejection Therapy</a>. You can re-apply as many times as you like, so you could also think of it as <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a> for your skills, and you like TDD, right?</p>
<h2>How To Prepare for the Interview : Technical</h2>
<p>When you are accepted for a phone interview, Google sends you an email giving you tips on how to prepare. Interestingly, this has been a different list each time. I&#8217;ll discuss the one I liked the most. They only give advice on the technical side. I will also discuss what I think are some other important aspects to be mindful of.</p>
<p>First of all, you are going to want to practice. Even if you have been coding every day for years, you might not be used to the short question style. <a href="http://projecteuler.net/">Project Euler</a> is <em>the bomb</em> for this. You will learn some maths too, which will come in handy, and it builds confidence. Do at least one of these every day until your interview.</p>
<p>You will also want some reading material. Google recommended <a href="http://steve-yegge.blogspot.com/2008/03/get-that-job-at-google.html">this post by Steve Yegge</a>, which does a good job of calming you. They also recommended <a href="http://sites.google.com/site/steveyegge2/five-essential-phone-screen-questions">another post by Steve Yegge</a> where he covers some styles of questions that are likely to be asked. Yegge recommends a particular book very highly &#8211; <a href="http://www.algorist.com/">The Algorithm Design Manual</a>:</p>
<p><img style="float: right; margin: 10px 50px 10px 50px;" src="http://img138.imageshack.us/img138/3826/thealgorithmdesignmanua.jpg" alt="" width="180px" /></p>
<blockquote><p>
  More than any other book it helped me understand just how astonishingly commonplace (and important) <strong>graph problems</strong> are – they should be part of every working programmer&#8217;s toolkit. The book also covers basic data structures and sorting algorithms, which is a nice bonus. But the gold mine is the second half of the book, which is a sort of encyclopedia of <strong>1-pagers</strong> on zillions of useful problems and various ways to solve them, without too much detail. Almost every 1-pager has a simple picture, making it easy to remember. This is a great way to learn how to <strong>identify hundreds of problem types</strong>.
</p></blockquote>
<p>I haven&#8217;t read the whole thing, but what I have read of it is eye and mind opening. This wasn&#8217;t recommended to me directly by Google recruiting staff, but one of my interviewers emailed me a bunch of links after, including a link to the page for this book. There was a recent review of this book featured on <a href="http://eriwen.com/books/best-algorithms-book/">Hacker News</a>. It is very good. The author, Steve Skiena, also offers his <a href="http://www.cs.sunysb.edu/~algorith/video-lectures/">lecture videos and slides</a> &#8211; kick back and watch them with a beer after work/uni.</p>
<p><img style="float: left; margin: 10px 50px 10px 50px;" src="http://cm.bell-labs.com/cm/cs/pearls/pp2e.jpg" alt="" width="180px" /></p>
<p>If the size of The Algorithm Design Manual is daunting and you want a short book to conquer quickly (for morale reasons), give <a href="http://cm.bell-labs.com/cm/cs/pearls/">Programming Pearls</a> a read. Answer as many questions in it as you can.</p>
<p>The phone interviews usually are accompanied by a Google doc for you to program into. I usually nominate Python as my preferred language, but usually they make me use C or C++ (they often say I can use Java too). I was rusty with my C++ syntax at the time, but they didn&#8217;t seem to mind. I just explained things like using templates, even though I can never remember the syntax for the cool metaprogramming tricks.</p>
<p>Speaking of tricks, you get style points for using features of the language that are less well known. I had an interviewer say he was impressed because I used Pythons pattern matching (simple example: <code>(a, b) = (b, a)</code>). List comprehensions, map/reduce, generators, lambdas, and decorators could all help make you look cool, too. Only use them if they are <em>useful</em> though!</p>
<h2>How To Prepare for the Interview : Non-Technical</h2>
<p>There will also be a few non-technical questions. When I did my first one, a friend recommended that I have answers ready for cookie-cutter questions like <em>&#8220;Where do you see yourself in ten years?&#8221;</em> and <em>&#8220;Why do you want to work for Google?&#8221;</em>. Don&#8217;t bother with that! Do you really think one of the biggest companies in the world will waste their time asking questions like that? Every candidate would say the same answer, something about leading a team and how Google would let you contribute to society, or whatever (great, but <em>everyone</em> wants that).</p>
<p>They <em>will</em> ask you about your previous work and education, though, and pretty much always ask about a technical challenge you overcame. I like to talk about a fun incremental A* search I did at my first job (and why we needed it to be iterative). You can probably think of something, don&#8217;t stress, but better to think of it before the interview.</p>
<p>And have a question ready for when they let you have your turn. Don&#8217;t search for <em>&#8220;good questions to ask in technical interviews&#8221;</em>, because if it isn&#8217;t <em>your</em> question, you might be uninterested if the interviewer talks about it for a long time. Think of something that you could have a discussion about, something you are opinionated about. Think of something you hated at a previous job (but don&#8217;t come across as bitter), how you would improve that, and then ask them if they do that. For me, I was interested in the code review process at Google, and what sort of project they would assign to a beginner.</p>
<p>I know someone who asked questions from <a href="http://www.joelonsoftware.com/articles/fog0000000043.html">The Joel Test</a>. The interviewer might recognise these questions and either congratulate you on reading blogs about your field, or quietly yawn to themselves. It&#8217;s up if you want to take that risk (well, it&#8217;s not a <em>big</em> risk). I definitely think it&#8217;s better to ask about something that has the potential to annoy you on a personal level if they don&#8217;t give you the answer you want ;) it&#8217;s subtle, but people can detect your healthy arrogance and passion.</p>
<p>If you have a tech blog, refer to it. I&#8217;ve had interviewers discuss my posts with me (which they found from my resume). Blogs aren&#8217;t hard to write, and even a few posts on an otherwise barren blog will make you look more thoughtful.</p>
<p>Finally, the absolute best way to prepare for a Google interview is to do more Google interviews, so if you fail, good for you! ;)</p>
<h2>Just Before the Interview</h2>
<p>Here are a few things that help me handle the pressure before an interview.</p>
<p>One time I was walking to an interview in the city (not a Google interview) and I was really nervous, even though I didn&#8217;t care either way if I got the job. I thought about how the nerves wouldn&#8217;t be an issue after the interview, because I&#8217;d have already done the scary thing by then. I couldn&#8217;t time travel, but I instead wondered if there is a way to use up the nerves on something else.</p>
<p>There was a girl walking next to me, so I turned to her and said she was dressed nicely. She said a timid &#8220;thank you&#8221; and picked up pace to get away from me. I laughed at my failure, but suddenly I didn&#8217;t feel so scared about the interview. I think this is a great example of why <a href="http://rejectiontherapy.com/rules/">Rejection Therapy</a> is worth experimenting with.</p>
<p>So yeah, talk to a stranger. If you are waiting at home for a phone call though, another thing I do is jack jumps, dancing, or jogging on the spot just to make myself forget the other reason my heart is pounding so fast.</p>
<h2>During the Interview</h2>
<p>If you are doing a phone interview, answer it standing up (you can sit down after) and pace around a little bit. Smile as you talk, as well. You should also take down their name on paper ready to use a few times casually. These are tricks from the infamous <a href="http://en.wikipedia.org/wiki/How_to_Win_Friends_and_Influence_People">How to Win Friends and Influence People</a>. Maybe <em>these alone</em> won&#8217;t make you likeable, but I think it causes you to think about the other person and stop being so self conscious, which helps you to relax. You&#8217;ll be <a href="http://www.youtube.com/watch?v=u8UE4P8kB-c">one charming motherfucking pig</a>.</p>
<p>Take some time to think before answering, and especially to seek clarification on the questions. Ask what the data representation is. I&#8217;ve found that they tend to say &#8220;whatever you want&#8221;. In a graph question, I said &#8220;Okay, then it&#8217;s an adjacency matrix&#8221;, which made the question over and done with in ten seconds. The interviewer seemed to like that, so don&#8217;t be afraid to be a (humble) smart ass.</p>
<p>You might recognise the adjacency matrix as potentially being a very poor choice, depending on the nature of the graph. I did discuss when this might not be a good option. In fact, for every question, I <strong>start off by describing a naive approach</strong>, and then refine it. This helps to verify the question requirements, and gives you an easy starting point. Maybe you could introspectively comment on agile methodology (Google practises Scrum).</p>
<p>One last thing! Google schedules the interview to be from 45 minutes to an hour. I have had awkward moments at the end of interviews where the interviewer mentions that our time is nearly up, and <em>then</em> asks another question, or asks if I have any questions. It made me feel like he was in a rush, so I didn&#8217;t feel like expanding on things much. Now, I recommend taking as much time as they will give you. Keep talking until they hang up on you if you have to :) although it might help to say &#8220;I don&#8217;t mind if we go over, as long as I&#8217;m not keeping you from something&#8221; when the interviewer mentions the time.</p>
<h2>Reflect</h2>
<p><a href="http://steve-yegge.blogspot.com/2008/03/get-that-job-at-google.html">Steve Yegge</a> says there are lots of smart Googlers who didn&#8217;t get in until their third attempt (I still haven&#8217;t gotten in after my fourth, and I don&#8217;t think I&#8217;m stupid). As I mentioned, I&#8217;m writing this post because I found the process of doing a Google interview at all to be very rewarding.</p>
<p>It is important to reflect afterwards in order to reap the full benefits of interviewing at Google. If you did well, why? But more importantly, if you feel you did poorly, why? Google won&#8217;t give feedback, which can be a bit depressing at times. After each interview write notes about what you felt went well and what didn&#8217;t &#8211; this way you can look back if you don&#8217;t get the job, and decide what you need to work on. This post is the culmination of my reflections and the notes &#8211; if you decide to write a blog post, I&#8217;d enjoy reading it and will link it here.</p>
<p>If you want more blog posts to read about how to get better at Computer Science, I recently found <a href="http://matt.might.net/articles/what-cs-majors-should-know/">this post by Matt Might</a> to be a good target to aim for. Check out <a href="http://profshonle.blogspot.com/2010/08/ten-things-every-computer-science-major.html">Ten Things Every Computer Science Major Should Learn by Macneil Shonle</a> as well, and my previous post <a href="http://www.alexbowe.com/advice-to-cs-undergrads">Advice to CS Undergrads</a> (the links at the end in particular).</p>
<p>Have you really read this far? Consider adding me to <a href="http://www.twitter.com/alexbowe">Twitter</a> and telling me what you thought :)</p>
<p>The post <a href="http://alexbowe.com/failing-at-google-interviews/">Failing at Google Interviews</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p><img src="http://feeds.feedburner.com/~r/alexbowe/~4/2q5kb0msVtE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://alexbowe.com/failing-at-google-interviews/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://alexbowe.com/failing-at-google-interviews/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=failing-at-google-interviews</feedburner:origLink></item>
		<item>
		<title>FM-Indexes and Backwards Search</title>
		<link>http://feedproxy.google.com/~r/alexbowe/~3/aEfUCMlNKvI/</link>
		<comments>http://alexbowe.com/fm-index/#comments</comments>
		<pubDate>Wed, 24 Aug 2011 00:02:53 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[burrows wheeler]]></category>
		<category><![CDATA[bwt]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[data structure]]></category>
		<category><![CDATA[fm-index]]></category>
		<category><![CDATA[search]]></category>
		<category><![CDATA[suffix array]]></category>

		<guid isPermaLink="false">http://alexbowe.com/?p=116</guid>
		<description><![CDATA[<p>Last time (way back in June! I have got to start blogging consistently again) I discussed a gorgeous data structure called the Wavelet Tree. When a Wavelet Tree is stored using RRR sequences, it can answer rank and select operations in $&#92;mathcal{O}(&#92;log{A})$ time, where A is the size of the alphabet. If the size of [...]</p><p>The post <a href="http://alexbowe.com/fm-index/">FM-Indexes and Backwards Search</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://alexbowe.s3.amazonaws.com/blog/overview-fm.png" width="519" height="200" class="aligncenter" /></p>
<p>Last time (way back in June! I have got to start blogging consistently again) I discussed a gorgeous data structure called the <a href="http://alexbowe.com/wavelet-trees/">Wavelet Tree</a>. When a Wavelet Tree is stored using RRR sequences, it can answer rank and select operations in $&#92;mathcal{O}(&#92;log{A})$ time, where A is the size of the alphabet. If the size of the alphabet is $2$, we could just use RRR by itself, which answers rank and select in $&#92;mathcal{O}(1)$ time for binary strings. RRR also compresses the binary strings, and hence compresses a Wavelet Tree which is stored using RRR.</p>
<p>So far so good, but I suspect rank and select queries seem to be of limited use right now (although once you are familiar with the available structures, applications show up often). One of the neatest uses of rank that I&#8217;ve seen is in substring search, which is certainly a wide reaching problem (for a very recent application to genome assembly, see Jared Simpson&#8217;s paper from 2010 called <em>Efficient construction of an assembly string graph using the FM-index</em>).</p>
<p><strong>Note</strong> that arrays and strings are one-based (not zero-based).</p>
<h1>Suffix Arrays</h1>
<p>There is a variety of Suffix Array construction algorithms, including some $&#92;mathcal{O}(N)$ ones (Puglisi et al. 2007). However, I will explain it from the most common (and intuitive) angle.</p>
<p>In its simplest form, a suffix array can be constructed for a string $S[1..N]$ like so:</p>
<ol>
<li>Construct an array of pointers to all suffixes $S[1..N], S[2..N], &#8230;, S[N..N]$.</li>
<li>Sort these pointers by the lexicographical (i.e. alphabetical) ordering of their associated suffixes.</li>
</ol>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/mississippi.png" width="264" height="38" class="aligncenter" /></p>
<p>For example, the sorting of the string <code>'mississippi'</code> with terminating character <code>$</code> would look like this:</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/mississippi-sa-sort.png" width="332" height="218" class="aligncenter" /></p>
<h1>Burrows-Wheeler Transform</h1>
<p>The <a href="http://en.wikipedia.org/wiki/Burrows-Wheeler_transform">Burrows-Wheeler Transform</a> (BWT) is a was developed by Burrows and Wheeler to reversibly permute a string in such a way that characters from repeated substrings would be clustered together. It was useful for compression schemes such as run-length encoding.</p>
<p>It is not the point of this blog to explain how it works, but it is closely linked to Suffix Arrays: $BWT[i] = S[SA[i] &#8211; 1, BWT[1] = &#92;$ $ (it wraps around) for the original string $S$, Suffix Array $SA$, and Burrows-Wheeler Transform string $BWT$. In other words, the $i^{th}$ symbol of the BWT is the symbol <em>just before</em> the $i^{th}$ <em>suffix</em>. See the image below:</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/mississippi-sa.png" width="259" height="219" class="aligncenter" /></p>
<p>In particular, $BWT[1] = S[SA[1] &#8211; 1] = S[12 - 1] = S[11] = i$ (or the $11^{th}$ symbol from the original string <code>'mississippi'</code>).</p>
<p>Ferragina and Manzini (Ferragina et al. 2000) recommended that a BWT be paired with a Suffix Array, creating the so-called FM-Index, which enables backward search. The BWT also lets us reconstruct the original string $S$ (not covered in this blog), allowing us to discard the original document &#8211; indexes with this property are known as <em>self indexes</em>.</p>
<h1>Backward Search</h1>
<p>This is where rank comes in. If it is hard to follow (it is certainly not easy to explain) then hang in there until the example, which should clear things up.</p>
<p>Since any pattern $P$ in $S$ (the original string) is a <em>prefix</em> of a <em>suffix</em> (our Suffix Array stores suffixes), and because the suffixes are lexicographically ordered, all occurrences of a search pattern $P$ lie in a contiguous portion of the Suffix Array. One way to hone in on our search term is to use successive binary searches. Storing the BWT lets us use a cooler way, though&#8230;</p>
<p>Backward search instead utilises the BWT in a series of paired <a href="http://www.alexbowe.com/wavelet-trees">rank queries</a> (which can be answered with a Wavelet Tree, for example), improving the query performance considerably.<br />
Backward search issues $p$ pairs of rank queries, where $p$ denotes the length of the pattern $P$. The paired rank queries are:</p>
<p>$$<br />
&#92;begin{align}<br />
s^&#92;prime &amp;= C[P[i]] + rank(s-1, P[i]) + 1 &#92;&#92;<br />
e^&#92;prime &amp;= C[P[i]] + rank(e, P[i])<br />
&#92;end{align}<br />
$$</p>
<p>Where $s$ denotes the start of the range and $e$ is the end of the range. Initially $s = 1$ and $e = N$. If at any stage $e &#92;lt s$, then $P$ doesn&#8217;t exist in $S$.</p>
<p>As for $C$&#8230; $C$ is a lookup table containing the count of all symbols in our alphabet which sort lexicographically before $P[i]$. What does this mean? Well, $C$ would look like this:</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/C-table.png" width="168" height="62" class="aligncenter" /></p>
<p>Which means that there aren&#8217;t any characters in $S$ that sort before $&#92;$$, one that sorts before $i$ (the $&#92;$$), five that sort before $m$ (the $&#92;$$ and the $i$s) and so on. In the example I store it in a less compact way as the column $F$ (which contains the first symbol for each suffix &#8211; essentially the same information, since each suffix is sorted), so it might be easier to follow (wishful thinking).</p>
<p>Why is this called backwards search? Well, our index variable $i$ actually starts at $|P|$ (the last character of our search pattern), and decreases to $1$. This maintains the invariant that $SA[s..e]$ contains all the suffixes of which $P[i..|P|]$ is a prefix, and hence all locations of $P[i..|P|]$ in $S$.</p>
<h1>Example</h1>
<p>Let&#8217;s practice this magic spell&#8230;<br />
Let our search pattern P be <code>'iss'</code>, and our string $S$ be <code>'mississippi'</code>. Starting with $i = 3$, $c = P[i] = $<code>'s'</code>. The working for each rank query is shown below each figure. I&#8217;m representing the current symbol as $c$ to avoid confusion between <code>'s'</code> and $s$ and $s^&#92;prime$.</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/bwt-1.png" width="252" height="203" class="aligncenter" /></p>
<p>Here (above) we are at the first stage of backwards search for <code>'iss'</code> on <code>'mississippi'</code> string &#8211; before any rank queries have been made.<br />
<strong>Note</strong>: we do not store the document anymore &#8211; the gray text &#8211; and we don&#8217;t store $F$, but instead store $C$ &#8211; see section on <strong>Backward Search</strong>.</p>
<p>Starting from $s=1$ and $e=12$ (as above) and $c = P[i] =$ <code>'s'</code> where $i = 3$, we make our first two rank queries:</p>
<p>$$<br />
&#92;begin{align}<br />
s^&#92;prime &amp;= C[c] + rank(0, c) + 1 = 8 + 0 + 1 = 9 &#92;&#92;<br />
e^&#92;prime &amp;= C[c] + rank(12, c) = 8 + 4 = 12<br />
&#92;end{align}<br />
$$</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/bwt-2.png" width="253" height="204" class="aligncenter" /></p>
<p>After the above, we are now at the <em>second</em> stage of backwards search for <code>'iss'</code> on <code>'mississippi'</code> string. All the occurrences of <code>'s'</code> lie in $SA[9..12]$.</p>
<p>From $s = 9$ and $e = 11$, and $c = P[i] =$ <code>'s'</code> where $i = 2$, our next two rank queries are:</p>
<p>$$<br />
&#92;begin{align}<br />
s^{&#92;prime&#92;prime} &amp;= C[c] + rank(8, c) + 1 = 8 + 2 + 1 = 11 &#92;&#92;<br />
e^{&#92;prime&#92;prime} &amp;= C[c] + rank(12, c) = 8 + 4 = 12<br />
&#92;end{align}<br />
$$</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/bwt-3.png" width="260" height="205" class="aligncenter" /></p>
<p>We are now at the <em>third</em> stage of backwards search for <code>'iss'</code> on <code>'mississippi'</code> string. All the occurrences of <code>'ss'</code> lie in $SA[11..12]$.</p>
<p>From $s = 11$ and $e = 12$, and $c = P[i] =$ <code>'i'</code> where $i = 1$, our final two rank queries are:</p>
<p>$$<br />
&#92;begin{align}<br />
s^{&#92;prime&#92;prime&#92;prime} &amp;= C[c] + rank(10, c) + 1 = 1 + 2 + 1 = 4 &#92;&#92;<br />
e^{&#92;prime&#92;prime&#92;prime} &amp;= C[c] + rank(12, c) = 1 + 4 = 5<br />
&#92;end{align}<br />
$$</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/bwt-4.png" width="252" height="209" class="aligncenter" /></p>
<p>This is the <em>fourth</em> and final stage of our backwards search for <code>'iss'</code> in the string <code>'mississippi'</code>. All the occurrences of <code>'iss'</code> lie in $SA[4..5]$.</p>
<p>It impresses me every time&#8230;</p>
<h1>Play Time</h1>
<p>No doubt you want to get your hands dirty. I have played around with <a href="http://code.google.com/p/libdivsufsort/">libdivsufsort</a> before, although I <em>think</em> you may have to implement backward search yourself (it&#8217;d be a good exercise), since it doesn&#8217;t appear to come with fast rank query providers. For rank structures for your BWT you might want to check out <a href="http://libcds.recoded.cl/">libcds</a>. In fact there are heaps out there, but I haven&#8217;t used them yet.</p>
<p>Also, please comment here if you develop something cool with it  :) and as always, if you have journeyed this far, consider following me on Twitter: <a href="http://www.twitter.com/alexbowe">@alexbowe</a>.</p>
<h1>Bibliography</h1>
<p>Ferragina, P. and Manzini, G. (2000). Opportunistic data structures with applications. Proceedings of the 41st Annual IEEE Symposium on Foundations of Computer Science, pages 390&ndash;398.</p>
<p>S. J. Puglisi, W. F. Smyth, and A. Turpin. A taxonomy of suffix array construction algorithms. ACM Computing Surveys, 39(2):1&ndash;31, 2007.<br />
Jared Simpson&#8217;s paper from 2010 called *Efficient construction of an assembly string graph using the FM-index.</p>
<p>Simpson, J. T. and Durbin, R. (2010). Efficient construction of an assembly string graph using the FM-index. Bioinformatics, 26(12):i367&ndash;i373.</p>
<p>The post <a href="http://alexbowe.com/fm-index/">FM-Indexes and Backwards Search</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p><img src="http://feeds.feedburner.com/~r/alexbowe/~4/aEfUCMlNKvI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://alexbowe.com/fm-index/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://alexbowe.com/fm-index/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=fm-index</feedburner:origLink></item>
		<item>
		<title>Wavelet Trees – an Introduction</title>
		<link>http://feedproxy.google.com/~r/alexbowe/~3/aoOFEpeQ-ws/</link>
		<comments>http://alexbowe.com/wavelet-trees/#comments</comments>
		<pubDate>Tue, 28 Jun 2011 11:35:50 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://alexbowe.com/?p=106</guid>
		<description><![CDATA[<p>Today I will talk about an elegant way of answering rank queries on sequences over larger alphabets &#8211; a structure called the Wavelet Tree. In my last post I introduced a data structure called RRR, which is used to quickly answer rank queries on binary sequences, and provide implicit compression. A Wavelet Tree organises a [...]</p><p>The post <a href="http://alexbowe.com/wavelet-trees/">Wavelet Trees &#8211; an Introduction</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://alexbowe.s3.amazonaws.com/blog/overview.png" width="336" height="220" class="aligncenter" alt="A Wavelet Tree provides fast querying over a string using a hierarchy of compressed bitmaps."/></p>
<p>Today I will talk about an elegant way of answering rank queries on sequences over <em>larger alphabets</em> &#8211; a structure called the Wavelet Tree. In <a href="http://www.alexbowe.com/yarrr-me-hearties">my last post</a> I introduced a data structure called RRR, which is used to quickly answer rank queries on <em>binary</em> sequences, and provide implicit compression.</p>
<p>A <em>Wavelet Tree</em> organises a string into a hierarchy of bit vectors. A rank query has time complexity is $&#92;mathcal{O}(&#92;log_2{A})$, where $A$ is the size of the alphabet. It was introduced by Grossi, Gupta and Vitter in their 2003 paper <em>High-order entropy-compressed text indexes</em> [4] (see the <em>Further Reading</em> section for more papers). It has since been featured in many papers [1, 2, 3, 5, 6].</p>
<p>If you store the bit vectors in RRR sequences, it may take less space than the original sequence. Alternatively, you could store the bit vectors in the rank indexes proposed by Sadakane and Okonohara [7]. It has a different approach to compression. I will talk about it another time ;) &#8211; fortunately, I will be studying under Sadakane-sensei at a later date (<em>update: now I&#8217;m doing my Ph.D. under him in Tokyo</em>).</p>
<p>In a different future post, I will show how Suffix Arrays can be used to find arbitrary patterns of length $P$, by issuing $2P$ rank queries.  If using a Wavelet Tree, this means a pattern search has $&#92;mathcal{O}(P &#92;log_2{A})$ time complexity, that is, the size of size of the &#8216;haystack&#8217; doesn&#8217;t matter, it instead depends on the size of the &#8216;needle&#8217; and size of the alphabet.</p>
<h2>Constructing a Wavelet Tree</h2>
<p>A Wavelet Tree converts a string into a balanced binary-tree of bit vectors, where a $0$ replaces half of the symbols, and a $1$ replaces the other half. This creates <em>ambiguity</em>, but at each level this alphabet is filtered and re-encoded, so the ambiguity lessens, until there is no ambiguity at all.</p>
<p>The tree is defined recursively as follows:</p>
<ol>
<li>Take the alphabet of the string, and encode the first half as $0$, the second half as $1$: $&#92;{ a, b, c, d &#92;}$ would become $&#92;{ 0, 0, 1, 1 &#92;}$;</li>
<li>Group each $0$-encoded symbol, $&#92;{ a, b &#92;}$, as a sub-tree;</li>
<li>Group each $1$-encoded symbol, $&#92;{ c, d &#92;}$, as a sub-tree;</li>
<li>Reapply this to each subtree recursively until there is only one or two symbols left (when a $0$ or $1$ can only mean one thing).</li>
</ol>
<p>For the string <code>"Peter Piper picked a peck of pickled peppers"</code> (spaces and a string terminator have been represented as $&#92;_$ and $&#92;$$ respectively, due to convention in the literature) the Wavelet Tree would look like this:</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/binwt.png" width="440" height="261" class="aligncenter" alt="A Wavelet Tree for the string 'Peter Piper picked a peck of pickled peppers'."/></p>
<p><em>note: the strings aren&#8217;t actually stored, but are shown here for convenience</em></p>
<p>It has the alphabet $&#92;{ &#92;$, P, &#92;_, a, c, d, e, f, i, k, l, o, p, r, s, t &#92;}$, which would be mapped to $&#92;{ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 &#92;}$. So, for example, $&#92;$$ would map to $0$, and $r$ would map to $1$.</p>
<p>The left subtree is created by taking just the 0-encoded symbols $&#92;{ &#92;$, P, &#92;_, a, c, d, e, f &#92;}$ and then re-encoding them by dividing this <em>new</em> alphabet: $&#92;{ 0, 0, 0, 0, 1, 1, 1, 1 &#92;}$. Note that on the first level an $e$ would be encoded as a $0$, but now it is encoded as a $1$ (it becomes a $0$ again at a leaf node).</p>
<p>We can store the bit vectors in RRR structures for fast binary rank queries (which are needed, as described below), and compression :) In fact, since it is a balanced tree, we can concatenate each of the levels and store it as one single bit vector.</p>
<h2>Querying a Wavelet Tree</h2>
<p>Recall from <a href="http://www.alexbowe.com/yarrr-me-hearties">my last post</a> that a rank query is the count of $1$-bits up to a specified position. Rank queries over larger alphabets are analogous &#8211; instead of a $1$, it may be any other symbol:</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/rankalpha.png" width="315" height="129" class="aligncenter" alt="An example of the rank function."/></p>
<p>After the tree is constructed, a rank query can be done with log $A$ ($A$ is alphabet size) <em>binary</em> rank queries on the bit vectors &#8211; $&#92;mathcal{O}(1)$ if you store them in RRR or another binary rank index. The encoding at each internal node may be ambiguous, but of course it isn&#8217;t useless &#8211; we use the ambiguous encoding to guide us to the appropriate sub-tree, and keep doing so until we have our answer.</p>
<p>For example, if we wanted to know $rank(5, e)$, we use the following procedure which is illustrated below. We know that $e$ is encoded as $0$ at this level, so we take the <em>binary</em> rank query of $0$ at position $5$:</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/binwt-query_1.png" width="378" height="136" class="aligncenter" alt="The first step in a Wavelet Tree rank query."/></p>
<p>Which is $4$, which we then use to indicate where to rank in the $0$-child: the $4^{th}$ bit (or the bit at position $3$, due to $0$-basing). We know to query the $0$-child, since that is what $e$ was encoded as at the parent level. We then repeat this recursively:</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/binwt-query.png" width="378" height="288" class="aligncenter" alt="A completed Wavelet Tree rank query."/></p>
<p>At a leaf node we have our answer. I would love to explain why this works, but it is fun and rewarding to think about it yourself ;)</p>
<p>There are also ways to provide fast select queries, but once again I will leave that up to you to research. The curious among you might also be interested in the Huffman-Shaped Wavelet Tree described by M&auml;kinen and Navarro [5].</p>
<h2>Using Your New Powers for Good</h2>
<p>Feel free to implement this yourself, but if you want to get your hands dirty right away, all-around-clever-guy <a href="http://fclaude.recoded.cl">Francisco Claude</a> has made an implementation available in his <a href="http://libcds.recoded.cl">Compressed Data Structure Library (libcds)</a>. If you create something neat with it be sure to report back ;)</p>
<p>Update: <a href="http://siganakis.com/challenge-design-a-data-structure-thats-small">Terence Siganakis</a> wrote a blog post about Wavelet Trees that made it to the front page of Hacker News, encouraging an interesting discussion. The discussion is <a href="http://news.ycombinator.com/item?id=3650657">here</a>.</p>
<p>And if you read this far, consider following me on Twitter: <a href="http://www.twitter.com/alexbowe">@alexbowe</a>.</p>
<h2>Further Reading</h2>
<p>I didn&#8217;t want to saturate this blog post with proofs and other details, since it was meant to be a light introduction. If you want to dive deeper into this beautiful structure, check out the following papers:</p>
<p>[1]  F. Claude and G. Navarro. Practical rank/select queries over arbitrary sequences. In Proceedings of the 15th International Symposium on String Processing and Information Retrieval (SPIRE), LNCS 5280, pages 176&ndash;187. Springer, 2008.</p>
<p>[2]  P. Ferragina, R. Giancarlo, and G. Manzini. The myriad virtues of wavelet trees. Information and Computation, 207(8):849&ndash;866, 2009.</p>
<p>[3]  P. Ferragina, G. Manzini, V. M ̈akinen, and G. Navarro. Compressed representations of sequences and full-text indexes. ACM Transactions on Algorithms, 3(2):20, 2007.</p>
<p>[4]  R. Grossi, A. Gupta, and J. Vitter. High-order entropy-compressed text indexes. In Proceedings of the 14th annual ACM-SIAM symposium on Dis- crete algorithms, pages 841&ndash;850. Society for Industrial and Applied Mathematics, 2003.</p>
<p>[5]  V. M&auml;kinen and G. Navarro. Succinct suffix arrays based on run-length encoding. Nordic Journal of Computing, 12(1):40&ndash;66, 2005.</p>
<p>[6]  V. M&auml;kinen and G. Navarro. Implicit compression boosting with applications to self-indexing. In Proceedings of the 14th International Symposium on String Processing and Information Retrieval (SPIRE), LNCS 4726, pages 214&ndash;226. Springer, 2007.</p>
<p>[7]  D. Okanohara and K. Sadakane. Practical entropy-compressed rank/select dictionary. Arxiv Computing Research Repository, abs/cs/0610001, 2006.</p>
<p>The post <a href="http://alexbowe.com/wavelet-trees/">Wavelet Trees &#8211; an Introduction</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p><img src="http://feeds.feedburner.com/~r/alexbowe/~4/aoOFEpeQ-ws" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://alexbowe.com/wavelet-trees/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://alexbowe.com/wavelet-trees/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=wavelet-trees</feedburner:origLink></item>
		<item>
		<title>RRR – A Succinct Rank/Select Index for Bit Vectors</title>
		<link>http://feedproxy.google.com/~r/alexbowe/~3/dltAXOqqk2s/</link>
		<comments>http://alexbowe.com/rrr/#comments</comments>
		<pubDate>Wed, 01 Jun 2011 15:12:40 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[data structure]]></category>
		<category><![CDATA[succinct]]></category>

		<guid isPermaLink="false">http://alexbowe.com/?p=123</guid>
		<description><![CDATA[<p>This blog post will give an overview of a static bitsequence data structure known as RRR, which answers arbitrary length rank queries in $&#92;mathcal{O}(1)$ time, and provides implicit compression. As my blog is informal, I give an introduction to this structure from a birds eye view. If you want, read my thesis for a version [...]</p><p>The post <a href="http://alexbowe.com/rrr/">RRR &#8211; A Succinct Rank/Select Index for Bit Vectors</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://alexbowe.s3.amazonaws.com/blog/intro.png" class="aligncenter" /></p>
<p>This blog post will give an overview of a static bitsequence data structure known as RRR, which answers arbitrary length rank queries in $&#92;mathcal{O}(1)$ time, and provides implicit compression.</p>
<p>As my blog is informal, I give an introduction to this structure from a birds eye view. If you want, <a href="https://github.com/alexbowe/wavelet-paper/raw/thesis/thesis.pdf">read my thesis</a> for a version with better markup, and follow the citations for proofs by people smarter than myself :)</p>
<p>My intended future posts will cover the other aspects of my thesis, including generalising RRR (for sequences over small alphabets), Wavelet Trees (which answer rank queries over bigger alphabets), and Suffix Arrays (a text index which &#8211; when combined with the above structures &#8211; can answer queries in $&#92;mathcal{O}(P &#92;log_2 A)$ time, when $P$ is the length of the search pattern, and $A$ is the alphabet size).</p>
<p><strong>Update:</strong> I have now posted about Wavelet Trees! Check it out <a href="http://alexbowe.com/wavelet-trees">here</a>.</p>
<h2>Example Problem</h2>
<p>Cracking the Oyster, the first column of <a href="http://www.cs.bell-labs.com/cm/cs/pearls/cto.html">Programming Pearls</a>, opens with a programmer asking for advice when sorting around ten million unique seven-digit integers &#8211; phone numbers.</p>
<p>After some discussion, the author <a href="http://www.cs.bell-labs.com/cm/cs/pearls/sec014.html">concludes</a> that a <a href="http://en.wikipedia.org/wiki/Bit_array">bitmap</a> should be used. If we wanted to store ten million integers, we could use an array of $32$-bit integers, consuming $38$ MB, or we could represent our numbers as positions on a number line.</p>
<p>All of these phone numbers will be within the range $[0000000, 9999999]$. To represent the presence of these numbers, we only need a bitmap $10^7$ bits long, about $1$ MB, which would represent our number line. Then, for a bitmap $M$, if we want to store phone number $p$, we set the  bit $M[p]$ to $1$. Sorting would involve setting the numbers that are present to $1$, then iterating over the bitmap, printing the positions of the $1$-bits &#8211; $&#92;mathcal{O}(N)$ time.</p>
<p>In the following sections, I will detail operations that can be done on bitmaps, named rank and select, and explain how to answer rank queries in $&#92;mathcal{O}(1)$ time, and implicitly compress the bitmap. Using rank and select, a compressed bitmap can be a very powerful way to store sets. This isn&#8217;t limited to just sets of numbers, all sorts of things, such as tree or graph nodes for example.</p>
<h2>Extension: Rank</h2>
<p>Allow me to extend the problem. I want to query our simple phone number database to see how many phone numbers are allocated within the range $[0005000, 0080000]$. I could iterate over that range and update a counter whenever I encounter a $1$-bit. Actually, this operation is what is known as a <strong>rank</strong> operation.</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/rankbin.png" width="250" height="124" class="aligncenter" /></p>
<p>The operation $rank(i)$ is defined as the number of set bits ($1$s) in the range $[0, i]$ (or $[0, i)$ in some papers). In the bitstring above, the answer to $rank(5)$ is $3$... This is a generalisation of the <a href="http://en.wikipedia.org/wiki/Popcount">popcount</a> operation which counts all set bits, which I have discussed before (<a href="http://alexbowe.com/metaprogramming-erlang/">here</a> and <a href="http://alexbowe.com/popcount-permutations/">here</a>). $rank(i)$ can be implemented by left-shifting $L - i$ bits (where $L$ is the length of the datatype you are using, int, long, etc) to remove the unwanted bits, then calling $popcount$ on the resulting value. This could be done iteratively over an array if you want, but I will discuss a much faster way below.</p>
<p>Then, the above question can be answered as:  $rank(0080000) - rank(0005000 - 1)$. This will give us just the number of $1$s between $0005000$ and $0080000$.</p>
<p>This isn't the only place we would use a popcounts; it happens that popcounts are common enough that we want to optimise them. Check out <a href="http://www.valuedlessons.com/2009/01/popcount-in-python-with-benchmarks.html">this blog post at valuedlessons.com</a> for a discussion and empirical comparison of several fast approaches.</p>
<h2>RRR</h2>
<p>As it happens, we can build a data structure for static bitmaps that answers rank queries in $&#92;mathcal{O}(1)$ time, <em>and</em> provides implicit compression. It is what is known as a succinct data structure, which means that even though it is compressed, we don't need to decompress the whole thing t operate on it efficiently.  Sadakane (a respected researcher in succinct data structures) gives a nice analogy in his <a href="http://www.nii.ac.jp/userimg/intro/en/sadakane_en.pdf">introduction of the field</a>, likening it to forcing dehydrated noodles apart with your chopsticks (decompression) as you are rehydrating them, but before the whole thing is fully cooked and separated. This allows you to keep some of the noodles compressed while you eat the decompressed fragment.</p>
<p>Since it is static it isn't well suited for a bitmap which you want to update (although work has been done toward this), it is still really cool :)</p>
<p>The structure I'm referring to is named RRR. It sounds like a radio station, but it is named after its creators: <a href="http://portal.acm.org/citation.cfm?id=545411">Raman, Raman, Rao, from their 2002 paper <em>Succinct indexable dictionaries with applications to encoding $k$-ary trees and multisets</em></a>. Its a data structure I had to become intimately involved with for <a href="https://github.com/alexbowe/wavelet-paper/raw/thesis/thesis.pdf">my honours thesis</a>, where I extended it for sequences of larger (but still small) alphabets. If you want to answer rank queries on large alphabets, a wavelet tree might be what you are after, but that will be covered in a different blog post (or you could read my thesis!).</p>
<p>In my <a href="http://www.alexbowe.com/48392639">last post (Generating Binary Permutations in Popcount Order)</a> I discussed how to compress a bitstring by replacing blocks of a certain blocksize with their corresponding pop number, and (variable length) offset into a lookup table. I briefly mentioned building an index over it to improve lookup as well.</p>
<h2>RRR: Construction</h2>
<p>To construct a RRR sequence we divide our bitmap into blocks, as I mentioned <a href="http://www.alexbowe.com/generating-binary-permutations-in-popcount-or">in my previous blog post</a>. These are grouped in <em>superblocks</em>, too, which allows us to construct an index to enable $&#92;mathcal{O}(1)$ rank queries. In the following image, I have fragmented the bitmap using a blocksize of $b = 5$, and grouped them with a superblock factor of $f = 3$ - so each superblock is three blocks.</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/blocks.png" width="500" height="149" class="aligncenter" /></p>
<p>First we replace the blocks with a pair of values, a <em>class</em> value $C$ and offset value $O$, which are used together as a lookup key into a table of precomputed (small - for each possible block only) ranks - this is demonstrated in the figure below. This is the same as <a href="http://www.alexbowe.com/generating-binary-permutations-in-popcount-or">the previous blog post</a>, although in that I called the "class" $P$. This is because the class of a block is defined as the popcount - the number of set bits - in the block: $class(B) = popcount(B)$ for block $B$.</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/compress.png" width="379" height="235" class="aligncenter" /></p>
<p>The table is shared among all your RRR sequences, and is in fact a table of tables, where $C$ points to the first element for the ranks of a given popcount:</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/binary-g-table.png" width="390" height="399" class="aligncenter" /></p>
<p>For this table (let's call it $G$), for a given class $C$, the sub-table at $G[C]$ has $b &#92;choose C$ entries, which correspond to all possible permutations that have a popcount of $C$. This means that while our $C$ values will always be $&#92;log{b + 1}$ (the number of bits to represent values $0, 1, 2&#8230; b$ &#8211; these are all possible popcount values for the blocksize), but our $O$ values will vary in size, requiring $&#92;log{b &#92;choose C}$ bits (oh yeah, and of course I&#8217;m using $&#92;log_2$ here :)). During a query, we can use our $C$ values to work out how many bits will follow for the $O$ values.</p>
<p>Using this approach alone we get the compression, but not $&#92;mathcal{O}(1)$ ranks. $C$ is fixed width, the compression comes from $O$ being varied width.</p>
<p>In order to get the $&#92;mathcal{O}(1)$ ranks we use a method discussed by <a href="http://www.springerlink.com/content/yv33538123433477/">Munro in <em>Tables</em>, 1996</a>. This is where the superblocks come in to play:</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/superblocks.png" width="476" height="304" class="aligncenter" /></p>
<p>For each superblock boundary we store the global rank up to that position. We also store a prefix sum of the bits, which gives us the address to the first block in the next superblock (since it is variable length!). This allows us to not require iterating over the whole RRR sequence, but instead going straight to the required superblock. We will only need to iterate over the blocks within a superblock, so it is now bound by whatever your superblock factor is.</p>
<h2>RRR: Querying</h2>
<p>To calculate $rank(i)$:</p>
<ol>
<li>Calculate which block our index is in as $i_b = &#92;frac{i}{b}$. ($i_b$ is the global index of the block)</li>
<li>Calculate which superblock our block resides in as $i_s = &#92;frac{i_b}{f}$. ($i_s$ is the index of the superblock)</li>
<li>Set result to the sum of previous ranks at is boundary (which is pre-calculated).</li>
<li>Using each blocks class-offset pair $(c,o)$ after the boundary at is, add the rank for that entire block to result.</li>
<li>Repeat previous step until we reach $i_b$. We then add $rank(j,c)$ (from $i_b$, not the global rank) to our result, where $j = i &#92;mod b$, and is the position we are querying local to $i_b$. Our final answer is the result.</li>
</ol>
<h2>Select</h2>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/selectbin.png" width="250" height="103" class="aligncenter" /></p>
<p>Select is the inverse operation to rank; it answers the question &#8220;at which position is the $i^{th}$ set bit?&#8221;. To tie this in with the phone numbers example, maybe we want  to find out the fiftieth phone number in the set (excluding unassigned numbers). This is a way we can index just the present elements of a bitmap. It turns out select can be answered in $&#92;mathcal{O}(1)$ time as well.  I won&#8217;t cover select here, as my future posts (and thesis) will mainly use rank. You can read about it in the <a href="http://portal.acm.org/citation.cfm?id=545411">RRR paper</a>.</p>
<h2>Go Forth and&#8230;</h2>
<p>Feel free to implement this (somewhat complicated) data structure yourself, or you can use a pre-rolled one by my friend <a href="http://fclaude.recoded.cl">Francisco Claude</a> in his <a href="http://libcds.recoded.cl">LIBCDS &#8211; Compressed Data Structure Library</a>.</p>
<p>If you read this far, consider <a href="http://www.twitter.com/alexbowe">adding me to twitter</a> :) or you may enjoy reading <a href="http://www.alexbowe.com/wavelet-trees">my post on Wavelet Trees</a>.</p>
<p>The post <a href="http://alexbowe.com/rrr/">RRR &#8211; A Succinct Rank/Select Index for Bit Vectors</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p><img src="http://feeds.feedburner.com/~r/alexbowe/~4/dltAXOqqk2s" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://alexbowe.com/rrr/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://alexbowe.com/rrr/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=rrr</feedburner:origLink></item>
		<item>
		<title>Generating Binary Permutations in Popcount Order</title>
		<link>http://feedproxy.google.com/~r/alexbowe/~3/x_SjAuAmneQ/</link>
		<comments>http://alexbowe.com/popcount-permutations/#comments</comments>
		<pubDate>Mon, 09 May 2011 00:11:05 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[bit hacks]]></category>

		<guid isPermaLink="false">http://alexbowe.com/?p=125</guid>
		<description><![CDATA[<p>I&#8217;ve been keeping an eye on the search terms that land people at my site, and although I get the occasional &#8220;alex bowe: fact or fiction&#8221; and &#8220;alex bowe bad ass phd student&#8221; queries (the frequency strangely increased when I mentioned this on Twitter) I also get some queries that relate to the actual content. [...]</p><p>The post <a href="http://alexbowe.com/popcount-permutations/">Generating Binary Permutations in Popcount Order</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://alexbowe.s3.amazonaws.com/blog/bitmap.png" width="241" height="114" class="aligncenter" /></p>
<p>I&#8217;ve been keeping an eye on the search terms that land people at my site, and although I get the occasional &#8220;alex bowe: fact or fiction&#8221; and &#8220;alex bowe bad ass phd student&#8221; queries (the frequency strangely increased when I mentioned this on <a href="http://www.twitter.com/alexbowe">Twitter</a>) I also get some queries that relate to the actual content.</p>
<p>One query I received recently was &#8220;generating integers in popcount order&#8221;, I guess because I mentioned popcounts (the number of 1-bits in a binary string) in a previous post, but the post wasn&#8217;t able to answer that visitors question.</p>
<p>What would this be used for? Among other applications, I have used it for generating a table of numbers ordered by popcount, which I used in a compression algorithm: by breaking a bitstring into fixed-length chunks (of B bits) and replacing them with a (P, O) pair, where P is the block&#8217;s popcount which can be used to point to the table where each entry has the popcount P, and O is the offset in that subtable. Then P can be stored with log2(B + 1) bits &#8211; we need to represent all possible P values from 0 to B &#8211; and O can be stored with log2(binomial(B, P)) bits.</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/compress.png" width="379" height="235" class="aligncenter" /></p>
<p>Note that the bit-length of P varies; binomial represents the binomial coefficient, which can be seen in Pascal&#8217;s triangle expanded to row 5:</p>
<p><img src="http://alexbowe.s3.amazonaws.com/blog/pascal.png" width="198" height="155" class="aligncenter" /></p>
<p>So binomial(5, x) for x = 0, 1, &#8230; , 5 yields the sequence 1, 5, 10, 10, 5, 1 &#8211; some things take more bits than others. Once you know the P value, you will know how many bits the O value is, so you can read it that way. This means access is O(N) (since each values position relies on the previous P values), but you can build an index on top of that to allow O(1) lookup. But all this is a story for another time ;) [1].</p>
<p>Here is the code:</p>
<pre><code>def next_perm(v):
    """
    Generates next permutation with a given amount of set bits,
    given the previous lexicographical value.
    Taken from http://graphics.stanford.edu/~seander/bithacks.html
    """
    t = (v | ( v - 1)) + 1
    w = t | ((((t &amp; -t) / (v &amp; -v)) &gt;&gt; 1) - 1)
    return w
</code></pre>
<p>This will take a number with a certain popcount, and generate the next number with the same popcount. For example, if you feed it 7, which is 111 in binary,<br />
you will get 1011 back &#8211; or 11 &#8211; the next number with the same popcount (lexicographically speaking).</p>
<p>To find the first number of a given popcount, you can use this:</p>
<pre><code>def element_0(c):
    """Generates first permutation with a given amount
       of set bits, which is used to generate the rest."""
    return (1 &lt;&lt; c) - 1
</code></pre>
<p>I should clear up what lexicographically means in the context of numbers. Well, it&#8217;s actually the same as any other symbols (such as an alphabet), 0 is the symbol that comes before 1 (if it helps, you can picture 0 as a and 1 as b):</p>
<pre><code>00111 aabbb
01011 ababb
01101 abbab
01110 abbba
10011 baabb
10101 babab
10110 babba
11001 bbaab
11010 bbaba
11100 bbbaa
</code></pre>
<h2>Psuedocode</h2>
<p>Looking at the above pattern, here is some loose pseudocode that may help us understand how the above bithacks work:</p>
<ol>
<li>Set i to the position of the rightmost bit</li>
<li>Stop if there are no set bits, or if we have looked at all the bits (i >= length of bitstring)</li>
<li>If the i+1th bit (one place to the left) is 0: move the ith bit left</li>
<li>Otherwise, if the i+1th bit (one place to the left) is 1:  set i to i + 1 and repeat from 2.</li>
<li>Shift the bits on the range [0, i] right so that the rightmost bit is in position 0</li>
</ol>
<h2>Explanation</h2>
<p>Understanding <code>element_0()</code> is pretty easy. <code>1 &lt;&lt; c</code> is the same as moving a <code>1</code> to position c, then -1 sets all the bits from 0 to c &#8211; 1, giving c set bits:</p>
<pre><code>c = 4
1 &lt;&lt; c = 10000
10000 - 1 = 01111
</code></pre>
<p><code>next_perm()</code> is a bit more complicated. The <code>v | (v -1)</code> in <code>t = (v | (v - 1)) + 1</code> right-propagates the rightmost bit. Allow me to show an example: <code>01110 | 01101 = 01111</code></p>
<p>In the case of 0, this isn&#8217;t quite correct: <code>00000 | 11111 = 11111</code> But it&#8217;s okay because we proceed to add 1 to this value (which returns it to zero). This increment, combined with the right-propagation, will do step 2, 3, and part of step 5 above. For example, <code>10100 -&gt; 10111 -&gt; 11000</code>.</p>
<p>We are on our way to generating integers by popcount in lexicographical order.</p>
<p>Now let&#8217;s break down the next line, <code>w = t | ((((t &amp; -t) / (v &amp; -v)) &gt;&gt; 1) - 1)</code>. Bitwise equations of the form <code>(x &amp; -x)</code> isolate the rightmost bit:<br />
<code>01110 &amp; 10010 (two's complement) = 00010</code></p>
<p>If you take the two&#8217;s complement, you invert a numbers bits and then add 1. If you think about it, this means there are 0s where there were 1s, and 1s where there were 0s, and adding 1 bumps the rightmost 1 left and sets the subsequent right bits to 0. This means that the only position that will remain set in both numbers is the the rightmost 1-bit.</p>
<p>So let R(x) denote the isolated rightmost bit of x, then for <code>x = 01110</code> we calculate <code>t = 10000</code>, <code>R(x) = 00010</code> and <code>R(t) = 10000</code>.</p>
<p>Following the calculation of w, we need to divide them: <code>R(t) / R(x) = 10000 / 00010 = 01000</code></p>
<p>Shift to the right by 1: <code>00100</code></p>
<p>Subtract 1: <code>00011</code></p>
<p>Then we bitwise-or them to stick them together: <code>10000 | 00011 = 10011</code>. This corresponds to our table above :)</p>
<p>So <code>w = t | ((((t &amp; -t) / (v &amp; -v)) &gt;&gt; 1) - 1)</code> corresponds to the rest of step 5 (the moving part, t was the zeroing part of moving the sub-range) in our pseudocode. Well, kind of anyway, there are a few steps happening in parallel, but the pseudocode was only loosely explaining what was happening :)</p>
<h2>Testing it out</h2>
<pre><code>def gen_blocks(p, b):
    """
    Generates all blocks of a given popcount and blocksize
    """
    v = initial = element_0(p)
    block_mask = element_0(b)

    while (v &gt;= initial):
        yield v
        v = next_perm(v) &amp; block_mask


&gt;&gt;&gt; for x in gen_blocks(3, 5): print bin(x, 5)
... 
00111
01011
01101
01110
10011
10101
10110
11001
11010
11100
</code></pre>
<p><em>Note</em>: <code>bin</code> is just a function I found online for printing binay numbers and isn&#8217;t important to this post, but you can find it <a href="http://www.gossamer-threads.com/lists/python/python/645216">here</a> if you need one.</p>
<p>Then of course you can loop through all values of P from 0 to B to build the complete table.</p>
<p>Questions? Comments? Flames? I wanna hear em :)</p>
<p>[1] &#8211; Check out <a href="http://www.springerlink.com/content/yv33538123433477/">Tables by Munro, 1996</a>, and <a href="http://portal.acm.org/citation.cfm?id=545411">Succinct indexable dictionaries with applications to encoding k-ary trees and multisets by Raman et al, 2002</a> for a first step into this stuff. Also <a href="github.com/alexbowe/honours-thesis/downloads">check out my honours thesis, 2010</a> for a recent look at succinct data structures. I will write a blog post about this stuff sooner or later :P</p>
<p>The post <a href="http://alexbowe.com/popcount-permutations/">Generating Binary Permutations in Popcount Order</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p><img src="http://feeds.feedburner.com/~r/alexbowe/~4/x_SjAuAmneQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://alexbowe.com/popcount-permutations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://alexbowe.com/popcount-permutations/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=popcount-permutations</feedburner:origLink></item>
		<item>
		<title>Some Lazy Fun with Streams</title>
		<link>http://feedproxy.google.com/~r/alexbowe/~3/lz3YwXiYgos/</link>
		<comments>http://alexbowe.com/streams/#comments</comments>
		<pubDate>Sun, 24 Apr 2011 05:17:16 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://alexbowe.com/?p=127</guid>
		<description><![CDATA[<p>Update:&#160;fellow algorithms researcher&#160;Francisco Claude&#160;just posted&#160;a great article about using lazy evaluation to solve Tic Tac Toe games in Common Lisp. Niki&#160;(my brother) also wrote a post using generators with asynchronous prefetching to hide IO latency.&#160;Worth a read I say! I&#8217;ve recently been obsessing over this programming idea called streams (also known as infinite lists or [...]</p><p>The post <a href="http://alexbowe.com/streams/">Some Lazy Fun with Streams</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://ian.umces.edu/imagelibrary/albums/userpics/12789/normal_ian-symbol-river-3d-braided-with-incoming-streams.png" width="400" height="188" class="aligncenter" /></p>
<p><strong>Update:&nbsp;</strong>fellow algorithms researcher&nbsp;<a href="http://fclaude.recoded.cl">Francisco Claude</a>&nbsp;just posted&nbsp;<a href="http://fclaude.recoded.cl/archives/177">a great article about using lazy evaluation to solve Tic Tac Toe games in Common Lisp</a>. <a href="http://niki.code-karma.com">Niki</a>&nbsp;(my brother) also wrote a post using <a href="http://niki.code-karma.com/2011/05/hiding-io-latency-in-generators-by-async-prefetching/">generators with asynchronous prefetching to hide IO latency</a>.&nbsp;Worth a read I say!</p>
<p>I&rsquo;ve recently been obsessing over this programming idea called <em>streams</em> (also known as <em>infinite lists</em> or <em>generators</em>), which I learned about from the <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html">Structure and Interpretation of Computer Programs</a> book. It is kind of like an iterator that creates its own data as you go along, and it can lead to performance increases and wonderfully readable code when you utilise them with <a href="http://en.wikipedia.org/wiki/Higher-order_function">higher order functions</a> such as <a href="http://en.wikipedia.org/wiki/Map_(higher-order_function)">map</a> and <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">reduce</a> (which many things can be rewritten in). It also allows you to express infinitely large data structures.</p>
<p>When regular lists are processed with higher order functions, you need to compute the entire list at each stage; if you have 100 elements, and you map a function to them, then filter them, then partially reduce them, you may be doing up to 300 operations, but what if you only want to take the first 5 elements of the result? That would be a waste, hence streams are sometimes a better choice.</p>
<p>Although SICP details how to do it in Scheme, in this blog post I will show some languages that have it built in &#8211; Haskell and Python &#8211; and how to implement streams yourself if you ever find yourself in a language without it<a id="fnref:1" class="footnote" title="see footnote" href="http://#fn:1">1</a>.</p>
<h2 id="haskell">Haskell</h2>
<p>Haskell is a lazy language. It didn&rsquo;t earn this reputation from not doing the dishes when you ask it to (although that is another reason it is lazy). What it means in the context of formal languages is that evaluation is postponed until <em>absolutely necessary</em> (<a href="http://blog.ezyang.com/2011/04/the-haskell-heap/">Here</a> is a cute (illustrated) blog post describing this lazy evaluation stuff). Take this code for example:</p>
<pre><code>Prelude&gt; let x = [1..10]</code></pre>
<p>At this stage you might be tempted to say that x is the list of numbers from 1 to 10. Actually it only represents a <em>promise</em> that when you need that list, x is your guy. The above code that creates a list from 1 to 10 still hasn&rsquo;t been executed until I finally ask it to be (by referring to x):</p>
<pre><code>Prelude&gt; x
[1,2,3,4,5,6,7,8,9,10]</code></pre>
<p>It is kind of like telling your mum you&rsquo;ll do the dishes, but waiting until she shouts your name out again before you put down your DS. Actually, it is sliiiiightly different &#8211; if I instead wrote:</p>
<pre><code>Prelude&gt; let x = [1..10]
Prelude&gt; let y = x ++ [11..20]</code></pre>
<p>I have referred to x again when I declared y, but x <em>still</em> hasn&rsquo;t evaluated. Only after I shout y&rsquo;s name will y shout x&rsquo;s name and give me back my whole list:</p>
<pre><code>Prelude&gt; y
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]</code></pre>
<p>Here you ask your robot to wash half the dishes, but he is too busy playing DS too (stupid robot). Finally when your mum shouts, you shout at the robot, and he does his set of dishes, and you do yours. But what is the benefit here? It isn&rsquo;t that I can get more DS time in&hellip;</p>
<p>Take for example a list of positive integers from 1. Yes, all of them. In other languages it might be hard to express this, but in Haskell it is as simple as <code>[1..]</code>. This means we have a list of infinite integers, but we will only calculate as far as we need:</p>
<pre><code>Prelude&gt; let z = [1..]
Prelude&gt; head z
1
Prelude&gt; take 5 z
[1,2,3,4,5]</code></pre>
<p>The syntax here is amazingly terse, and it may make your code more efficient. But even if we don&rsquo;t have the syntax for it in another language, we can provide it ourselves very easily.</p>
<h2 id="python">Python</h2>
<p>Python has a similar concept called <em>generators</em>, which are made using the <code>yield</code> keyword in place of <code>return</code>, more than one time (or in a loop) in a function:</p>
<pre><code>def integers_from(N):
     while(1):
         yield N
         N += 1

&gt;&gt;&gt; z = integers_from(1)
&gt;&gt;&gt; z.next()
1
&gt;&gt;&gt; z.next()
2</code></pre>
<p><strong>Note</strong>: Python generators are stateful and are hence slightly different to an infinite list in Haskell. For example <code>z.next()</code> returns different values in two places, and thus is time sensitive &#8211; we cannot get z to &lsquo;rewind&rsquo; like we could in Haskell, where <code>z</code> is stateless. Statelessness can lead to easier to understand code, among other benefits.</p>
<h2 id="rollingourown">Rolling Our Own</h2>
<p>Let&rsquo;s reinvent this wheel in Python (but in a stateless manner), so if we ever find ourselves craving infinite lists we can easily roll our own in pretty much any language with <a href="http://en.wikipedia.org/wiki/Lambda_(programming)">Lambdas</a>.</p>
<p>I have chosen Python to implement this, even though it already supports infinite lists through generators, simply because its syntax is more accessible. Indeed, the below can already be done with Python&rsquo;s built-in-functions (although with state). It is probably <em>not a great idea to do it this way in Python</em>, as it doesn&rsquo;t have <a href="http://stackoverflow.com/questions/310974/what-is-tail-call-optimization">tail call optimisation</a> (unless you use <a href="http://code.activestate.com/recipes/474088/">this hack</a> using decorators and exceptions).</p>
<p>First we&rsquo;ll look at adding lazy evaluation, however the syntax requires it to be explicit:</p>
<pre><code>&gt;&gt;&gt; x = lambda: 5
&gt;&gt;&gt; y = lambda: 2 + x()</code></pre>
<p>Here, <code>x</code> is <em>not</em> 5, and <code>y</code> is <em>not</em> 7, they are both functions that will evaluate to that when we finally run them; the expression inside the lambda won&rsquo;t be evaluated until we do so explicitly:</p>
<pre><code>&gt;&gt;&gt; x()
5
&gt;&gt;&gt; y()
7</code></pre>
<p>And that&rsquo;s pretty much all the heavy lifting. To make an infinite list, we basically make a linked list where we generate each node as we need it:</p>
<pre><code>def integers_from(N): return (N, lambda: integers_from(N+1))

def head((H, _)): return H

def tail((_, T)): return T()</code></pre>
<p>And there is our infinite list. To access it use <code>head()</code> and <code>tail()</code> (recursively if necessary):</p>
<pre><code>&gt;&gt;&gt; z = integers_from(1)
&gt;&gt;&gt; head(z)
1
&gt;&gt;&gt; head(tail(z))
2</code></pre>
<h2 id="helperfunctions">Helper Functions</h2>
<p>First we should make a way for us to look at our streams:</p>
<pre><code>def to_array(stream):
    return reduce(lambda a, x: a + [x], [], stream)</code></pre>
<p>Which is a <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">reduce</a> operation that puts each head element into an array (which is carried along as a parameter to <code>reduce()</code>). Here is <code>reduce()</code> (<code>map()</code> can be found in this <a href="https://gist.github.com/938886">gist</a>):</p>
<pre><code>null_stream = (None, None)
def reduce(f, result, stream):
    if stream is null_stream: return result
    return reduce(f, f(result, head(stream)), tail(stream))</code></pre>
<p>We needed some way to tell if we had reached the end of a stream &#8211; not all streams are infinitely long. Meet our next function, which will help us terminate a stream:</p>
<pre><code>def take(N, stream):
    if N &lt;= 0 or stream is null_stream: return null_stream
    return (head(stream), lambda: take(N-1, tail(stream)))</code></pre>
<p>This will take the first <code>N</code> elements from the specified stream. So now we can inspect the first <code>N</code> elements:</p>
<pre><code>&gt;&gt;&gt; to_array(take(10, integers_from(1)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code></pre>
<p>For our upcoming example, we also need a <code>filter()</code> method, which will filter out elements that meet a provided predicate:</p>
<pre><code>def filter(pred, stream):
    if pred(head(stream)):
        return (head(stream), lambda: filter(pred, tail(stream)))
    return filter(pred, tail(stream))</code></pre>
<p>Now onto our example :)</p>
<h2 id="textbookexample">Textbook Example</h2>
<p>Here is the standard example to demonstrate the terseness of streams:</p>
<pre><code>def sieve(stream):
    h = head(stream)
    return (h, lambda: sieve(
        filter(lambda x: x%h != 0, tail(stream))))</code></pre>
<p>Here is a function which recursively filters anything which is divisible by any number we have previously seen in our stream. Math aficionados will notice that this is the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a> algorithm.</p>
<pre><code>&gt;&gt;&gt; primes = sieve(integers_from(2))
&gt;&gt;&gt; to_array(take(10, primes))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]</code></pre>
<p>Recursively defined data, and only as much of it as we want &#8211; pretty neat.</p>
<h2 id="andnowforsomethingalmostcompletelydifferent">And Now For Something Almost Completely Different</h2>
<p>When I first saw this, I wondered what application there might be to have a stream of functions. Here I have defined a stream which recursively applies a function to itself:</p>
<pre><code>def rec_stream(f):
    return (f, lambda: rec_stream(lambda x: f(f(x))))</code></pre>
<p>When might this be useful? It might yield speed improvements if you commonly want to recursively apply a function a certain amount of times, but have costly branching (so the condition check at each level is slow). It could also be used as a abstraction for recursive iteration <a id="fnref:2" class="footnote" title="see footnote" href="http://#fn:2">2</a>, which gives you back the function &#8216;already recursed&#8217; so to speak (although lazily).</p>
<p>One such recursive process I can think of is <a href="http://en.wikipedia.org/wiki/Newton's_method">Newton&rsquo;s method for approximating roots</a>, defined recursively as:</p>
<p>http://mathurl.com/3wb4xea.png</p>
<p>When <code>f(x) = 0</code>.</p>
<p>The more iterations you do the more accurate the solution becomes. One use of Newton&rsquo;s method is to use it until you have reached a certain error tolerance. Another way, which I learned about recently when reading about the <a href="http://en.wikipedia.org/wiki/Fast_inverse_square_root">fast inverse square root algorithm</a>, which uses just one step of Newton&rsquo;s method as a cheap way to improve it&rsquo;s (already pretty good) initial guess. There is a really great article <a href="http://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/">here</a> which explains it very well.</p>
<p>After reading that, I wondered about a stream that would consist of functions of increasing accuracy of Newton&rsquo;s method.</p>
<pre><code>def newton(f, fdash):
    return lambda x: x - f(x)/float(fdash(x))</code></pre>
<p>The <code>newton()</code> function accepts <code>f(x)</code> and <code>f'(x)</code>, and returns a function that accepts a first guess.</p>
<pre><code>def newton_solver(iters, f, fdash):
    def solve(v):
        n = newton(lambda x: f(x) - v, fdash)
        stream = rec_stream(n)
        return to_array(take(iters, stream))[-1]
    return solve</code></pre>
<p>This one is a little more complicated. In order to have it solve for a value other than zero, I needed to either define it in <code>f(x)</code>, since <code>f(x)</code> must equal zero, but I didn&rsquo;t want the user to have to iterate over the stream each time they wanted to compute the square root of a different number, say. To allow it to return a function that solved for square roots in the general case, I had to make the internal function <code>solve()</code>, which would bind for the value the caller specifies, hence solving <code>f(x) = v</code> for <code>x</code>. Hopefully this becomes clearer with an example:</p>
<pre><code>&gt;&gt;&gt; sqrt = newton_solver(1, lambda x: x**2, lambda x: 2*x) # 1 iter
&gt;&gt;&gt; sqrt(64)(4) # Sqrt of 64 with initial guess of 4
10.0
&gt;&gt;&gt; sqrt = newton_solver(3, lambda x: x**2, lambda x: 2*x) # 3 iters
&gt;&gt;&gt; sqrt(64)(4)
8.000000371689179</code></pre>
<p>Now we can pass around this square root function and it will always do 3 iterations of Newton&#8217;s method.</p>
<p>This may not be practical unless compilers can optimise the resulting function (or if there is a way to do the reduction myself easily), but it was fun to do :) As always comments and suggestions are appreciated. If anyone who reads this is good with compilers, advice would be great :D</p>
<p>What you can do now is read <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html">SICP</a> for more cool things like streams and functional programming, or check out <a href="http://graphics.stanford.edu/~seander/bithacks.html">Sean Anderson&rsquo;s bit hacks page</a> for more cool hacks like the fast inverse square root. Or refactor your code to use map, reduce and streams :)</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn:1">
<p>The reason I have chosen Python for this exercise is for reasons of accessibility. <a href="http://chneukirchen.org/blog/archive/2005/05/lazy-streams-for-ruby.html">Here</a> is a post about implementing streams in Ruby, and <a href="http://khigia.wordpress.com/2007/05/07/44/">here</a> is one for Erlang :) but of course it&rsquo;s all pretty much the same deal.<a class="reversefootnote" title="return to article" href="#fnref:1">&nbsp;↩</a></p>
</li>
<li id="fn:2">
<p>If a compiler could optimise this, simplifying the reapplied function, but keeping the generality, that&rsquo;d be really cool :) I don&rsquo;t think many compilers would/could do that for lambdas though. Any information would be great.<a class="reversefootnote" title="return to article" href="#fnref:2">&nbsp;↩</a></p>
</li>
</ol>
</div>
<p>The post <a href="http://alexbowe.com/streams/">Some Lazy Fun with Streams</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p><img src="http://feeds.feedburner.com/~r/alexbowe/~4/lz3YwXiYgos" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://alexbowe.com/streams/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://alexbowe.com/streams/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=streams</feedburner:origLink></item>
		<item>
		<title>Design Pattern Flash Cards</title>
		<link>http://feedproxy.google.com/~r/alexbowe/~3/aNSXCpIeBhI/</link>
		<comments>http://alexbowe.com/design-pattern-flash-cards/#comments</comments>
		<pubDate>Sun, 17 Apr 2011 22:03:04 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[education]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://alexbowe.com/?p=136</guid>
		<description><![CDATA[<p>Last year I studied a subject which required me to memorise design patterns. I tried online flash card web sites, but I was irritated that I didn&#8217;t own the data I put up (they had no export option). So I wrote a something in Python to generate flash cards for me using LaTeX and the [...]</p><p>The post <a href="http://alexbowe.com/design-pattern-flash-cards/">Design Pattern Flash Cards</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://alexbowe.com/wp-content/uploads/2011/04/flashcards.png" alt="flashcards" width="675" height="388" class="aligncenter size-full wp-image-286" /></p>
<p>Last year I studied a subject which required me to memorise design patterns. I tried online flash card web sites, but I was irritated that I didn&#8217;t own the data I put up (they had no export option). So I wrote a something in Python to generate flash cards for me using LaTeX and the Cheetah templating library. The repository is hosted <a href="https://github.com/alexbowe/cardgen">here</a>, although it could do with a refactor.</p>
<p>If you don&#8217;t want to generate your own, you can download the pre-generated design pattern intent flash cards <a href="https://github.com/alexbowe/cardgen/raw/master/intents.pdf">here</a> which contains the 23 original design patterns from the Gang Of Four.</p>
<p>To generate your own flash cards, create an input text file with this structure:</p>
<pre><code>Front text (such as pattern name):
Definition line 1.
Definition line 2.
</code></pre>
<p>For example:</p>
<pre><code>Abstract Factory:
Provides an interface for creating families of related or
dependent objects without specifying their concrete classes.
</code></pre>
<p>Currently the front text is single-line only. The regex could be updated of course (if you do, feel free to send a pull request!).</p>
<p>To compile this:</p>
<pre><code>./cardgen.py -i inputfile -o outputfile
pdflatex outputfile
</code></pre>
<p>Then just print it out on a double side printer (or glue the two sheets together). I carried these around with me all the time during the lead-up to the exam, and I was scay-fast when it came to recalling which design pattern did what. Just flick through them (shuffle first) in forward or reverse order when you are on the train next :)</p>
<p>The post <a href="http://alexbowe.com/design-pattern-flash-cards/">Design Pattern Flash Cards</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p><img src="http://feeds.feedburner.com/~r/alexbowe/~4/aNSXCpIeBhI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://alexbowe.com/design-pattern-flash-cards/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://alexbowe.com/design-pattern-flash-cards/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=design-pattern-flash-cards</feedburner:origLink></item>
		<item>
		<title>Metaprogramming Erlang the Easy Way</title>
		<link>http://feedproxy.google.com/~r/alexbowe/~3/R0ECqvdC8kk/</link>
		<comments>http://alexbowe.com/metaprogramming-erlang/#comments</comments>
		<pubDate>Mon, 04 Apr 2011 17:49:46 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[metaprogramming]]></category>

		<guid isPermaLink="false">http://alexbowe.com/?p=138</guid>
		<description><![CDATA[<p>I&#8217;ve recently taken Erlang back up1, and I wanted to use this blog post to talk about something cool I learned over the weekend. I am implementing a data structure. Reimplementing actually, as it is the structure from my thesis &#8211; a succinct text index (I will post a blog on this soon). Why am [...]</p><p>The post <a href="http://alexbowe.com/metaprogramming-erlang/">Metaprogramming Erlang the Easy Way</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://alexbowe.com/wp-content/uploads/2011/04/a_hyper_cube.gif" alt="A Hyper Cube" width="398" height="339" class="aligncenter size-full wp-image-288" /></p>
<p>I&rsquo;ve recently taken <a href="http://www.erlang.org/">Erlang</a> back up<a id="fnref:0" class="footnote" title="see footnote" href="#fn:0">1</a>, and I wanted to use this blog post to talk about something cool I learned over the weekend.</p>
<p>I am implementing a data structure. Reimplementing actually, as it is the structure from my <a href="https://github.com/alexbowe/honours-thesis/downloads">thesis</a> &#8211; a succinct text index (I will post a blog on this soon).</p>
<p>Why am I reimplementing it in Erlang? The structure involves many bit-level operations, and I wanted to try out Erlang&rsquo;s <a href="http://www.erlang.org/doc/programming_examples/bit_syntax.html">primitive Binary type</a>, which seems to be allow efficient splitting and concatenation (which I require). Erlang&rsquo;s approach to concurrency will hopefully assist me to experiment with distributing the structure, too. As a bonus, the functional approach has lent itself well to this math-centric data structure, and my code is much, MUCH cleaner because of it (I love <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">reduce</a> and other <a href="http://en.wikipedia.org/wiki/Higher-order_function">higher order functions</a>).</p>
<p>One function I needed to implement was <a href="http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable">popcount</a> (the sum of set set bits in a bitvector). For example, if <code>b = 1010</code> then <code>pop(b)</code> is 2.</p>
<p>There are many methods listed on <a href="http://www.valuedlessons.com/2009/01/popcount-in-python-with-benchmarks.html">this blog</a>. One of them is the table method, which precomputes all popcounts for 16 bit integers (or any length you have space for):</p>
<pre><code>POPCOUNT_TABLE16 = [0] * 2**16
for index in xrange(len(POPCOUNT_TABLE16)):
    POPCOUNT_TABLE16[index] = (index &amp; 1)
    + POPCOUNT_TABLE16[index &gt;&gt; 1]</code></pre>
<p>I translated this to Erlang:</p>
<script src="https://gist.github.com/901235.js"></script><noscript><p>View the code on <a href="https://gist.github.com/901235">Gist</a>.</p></noscript>
<p>So now <code>gen_table(Bits)</code> will generate a tuple for me with all popcounts from 0 to $2^Bits$. However, we may gain performance<a id="fnref:1" class="footnote" title="see footnote" href="http://#fn:1">2</a> from knowing how big we want the table to be at compile time. If we know the amount of bits we want our popcount table to work for, we could type the table directly into the source. But that would impede our flexibility, and make our code ugly.</p>
<p>Enter <a href="https://github.com/esl/parse_trans"><code>ct_expand</code></a>. We can use <code>ct_expand:term( &lt;code to execute&gt; )</code> to run <code>gen_table()</code> for us at compile time! Now we only run <code>gen_table()</code> whenever we compile the module &#8211; after that the table is embedded in the binary.</p>
<p>First, check out ct_expand (<code>git clone https://github.com/esl/parse_trans.git</code>), and compile it with <code>make</code><a id="fnref:2" class="footnote" title="see footnote" href="#fn:2">3</a>. Then just move the <code>.beam</code> files into your project directory. Now we&rsquo;re ready for some metaprogramming :)</p>
<p>I created a new module for generating our table at compile time:</p>
<script src="https://gist.github.com/901242.js"></script><noscript><p>View the code on <a href="https://gist.github.com/901242">Gist</a>.</p></noscript>
<p>The reason we must be in a new module is because <code>ct_expand:term()</code> requires it&rsquo;s parameter to be something it will know about at compile time. This could be an inline fun (which I tried, but it wasn&rsquo;t pretty), or it can be something you compile before <code>ct_expand:term()</code> is executed (see line 3). Note on line 2 that we also need to compile <code>parse_transform</code> and <code>ct_expand</code> with our module.</p>
<p>Let&rsquo;s test it out:</p>
<pre><code>1&gt; c(popcount).
{ok,popcount}
2&gt; popcount:popcount16(2#1010).
2
3&gt; popcount:popcount16(2#101011).
4</code></pre>
<p>Nice! Thanks to <a href="http://ulf.wiger.net/weblog/">Ulf Wiger</a> for making that so easy :)</p>
<p>( Image stolen from&nbsp;http://improvisazn.wordpress.com/2010/02/22/meta/ )</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn:0">
My only other encounter with it was when I wrote an essay on the rationale of Erlang, which is something I will convert to blog format and post later if anyone is interested.<a class="reversefootnote" title="return to article" href="http://#fnref:0">&nbsp;↩</a>
</li>
<li id="fn:1">
The compiler may be able to apply further optimisations, so table access might be faster itself, but the main benefit comes from not having to generate the table while your code is running. Note that I haven&rsquo;t experimented with it. I will try to run some tests this week and update the blog post.<a class="reversefootnote" title="return to article" href="#fnref:1">&nbsp;↩</a>
</li>
<li id="fn:2">
If rebar gives you an error about crypto being undefined, you will need the <code>erlang-crypto</code> package. On Mac OS X: <code>sudo port install erlang +ssl</code>. (I had this issue)<a class="reversefootnote" title="return to article" href="http://#fnref:2">&nbsp;↩</a>
</li>
</ol>
</div>
<p>The post <a href="http://alexbowe.com/metaprogramming-erlang/">Metaprogramming Erlang the Easy Way</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p><img src="http://feeds.feedburner.com/~r/alexbowe/~4/R0ECqvdC8kk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://alexbowe.com/metaprogramming-erlang/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://alexbowe.com/metaprogramming-erlang/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=metaprogramming-erlang</feedburner:origLink></item>
		<item>
		<title>Au Naturale – an Introduction to NLTK</title>
		<link>http://feedproxy.google.com/~r/alexbowe/~3/BaflknuDmd0/</link>
		<comments>http://alexbowe.com/au-naturale/#comments</comments>
		<pubDate>Sun, 20 Mar 2011 15:14:31 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[Language]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[nlp]]></category>
		<category><![CDATA[nltk]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://alexbowe.com/?p=142</guid>
		<description><![CDATA[<p>This blog post is an introduction on how to make a key phrase extractor in Python, using the Natural Language Toolkit (NLTK). But how will a search engine know what it is about? How will this document be indexed correctly? A human can read it and tell that it is about programming, but no search [...]</p><p>The post <a href="http://alexbowe.com/au-naturale/">Au Naturale &#8211; an Introduction to NLTK</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://data.whicdn.com/images/1396251/tumblr_kwukdtbqLx1qargqko1_400_large.jpg " width="400" height="400" class="aligncenter" /><br />
This blog post is an introduction on how to make a key phrase extractor in Python, using the <a href="http://www.nltk.org/">Natural Language Toolkit (NLTK)</a>.</p>
<p>But how will a search engine know what it is about? How will this document be indexed correctly? A human can read it and tell that it is about programming, but no search engine company has the money to pay thousands of people to classify the entire Internet for them. Instead they must reasonably predict what a human may decide to be the key points of a document. And they must automate this.</p>
<p>Remember how proper sentences need to be structured with a <a href="http://hubpages.com/hub/Grammar_Mishaps__Building_a_Sentence">subject and a predicate</a>? A subject could be a noun, or a adjective followed by a noun, or a pronoun&#8230; A predicate may be or include a verb&#8230; We can take a similar approach by defining our key phrases in terms of what types of words (or parts-of-speech) they are, and the pattern in which they occur.</p>
<p>But how do we know what words are nouns or verbs in an automated fashion?</p>
<p>Throughout this post I will use an excerpt from <a href="http://www.amazon.com/gp/product/0061673730/alexbowecom-20">Zen and the Art of Motorcycle Maintenance</a> as an example:</p>
<blockquote><p>
  The Buddha, the Godhead, resides quite as comfortably in the circuits of a digital computer or the gears of a cycle transmission as he does at the top of a mountain or in the petals of a flower. To think otherwise is to demean the Buddha&#8230;which is to demean oneself.
</p></blockquote>
<p>Before proceeding, make a (mental) note of the key phrases here. What is the document about?</p>
<h2>Tokenizing</h2>
<p>In a program, text is represented as a string of characters. How can we go about moving <em>one</em> level of abstraction up, to the level of words, or <em>tokens</em>? To tokenize a sentence you may be tempted to use Python&#8217;s <code>.split()</code> method, but this means you will need to code additional rules to remove hyphens, newlines and punctuation when appropriate.</p>
<p>Thankfully the <a href="http://www.nltk.org/">Natural Language Toolkit (NLTK)</a> for Python provides a regular expression tokenizer. There is an example of it (including how it fares against Pythons regular expression tokenization method) in <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch03.html">Chapter 3</a> of the <a href="http://www.nltk.org/book">NLTK book</a>. It also allows you to have comments:</p>
<pre><code># Word Tokenization Regex adapted from NLTK book
# (?x) sets flag to allow comments in regexps
sentence_re = r'''(?x)
  # abbreviations, e.g. U.S.A. (with optional last period)
  ([A-Z])(\.[A-Z])+\.?
  # words with optional internal hyphens
  | \w+(-\w+)*
  # currency and percentages, e.g. $12.40, 82%
  | \$?\d+(\.\d+)?%?
  # ellipsis
  | \.\.\.
  # these are separate tokens
  | [][.,;"'?():-_`]
'''
</code></pre>
<p>Once we have constructed our regex for defining what sort of format our words should be in, we call it like so:</p>
<pre><code>import nltk
#doc is a string containing our document
toks = nltk.regexp_tokenize(doc, sentence_re)

&gt;&gt;&gt; toks
['The', 'Buddha', ',', 'the', 'Godhead', ',', 'resides', ...
</code></pre>
<h2>Tagging</h2>
<p>The next step is tagging. This uses statistical data to apply a Part-of-speech tag to each token, e.g. ADJ, NN (Noun), and so on. Since it is statistical, we need to either train our model or use a pre-trained model. NLTK comes with a pretty good one for general use, but if you are looking at a certain kind of document you may want to train your own tagger, since it may greatly affect the accuracy (think about very vocabulary-dense fields such as biology).</p>
<p>Note that to train your own tagger you will need a pre-tagged corpus (NLTK comes with some) or use a <em>bootstrapped</em> method (which can take a long time). Check out  <a href="http://streamhacker.com/2010/04/12/pos-tag-nltk-brill-classifier/">Streamhacker</a> and <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch05.html">Chapter 5 of the NLTK book</a> for a good discussion on training your own (and how to test it empirically).</p>
<p>For the sake of this introduction, we will use the default one. The result is a list of token-tag pairs:</p>
<pre><code>&gt;&gt;&gt; postoks = nltk.tag.pos_tag(toks)
&gt;&gt;&gt; postoks
[('The', 'DT'), ('Buddha', 'NNP'), (',', ','), ('the', 'DT'), ...
</code></pre>
<h2>Chunking</h2>
<p>Now we can use the part-of-speech tags to lift out noun phrases (NP) based on patterns of tags.</p>
<p><img src="http://nltk.googlecode.com/svn/trunk/doc/images/chunk-segmentation.png" width="600" height="405" class="aligncenter" /></p>
<p><em>Note: All diagrams have been stolen from the NLTK book (which is available under the Creative Commons Attribution Noncommercial No Derivative Works 3.0 US License).</em></p>
<p>This is called chunking. We can define the form of our chunks using a regular expression, and build a chunker from that:</p>
<pre><code># This grammar is described in the paper by S. N. Kim,
# T. Baldwin, and M.-Y. Kan.
# Evaluating n-gram based evaluation metrics for automatic
# keyphrase extraction.
# Technical report, University of Melbourne, Melbourne 2010.
grammar = r"""
    NBAR:
        # Nouns and Adjectives, terminated with Nouns
        {&lt;NN.*|JJ&gt;*&lt;NN.*&gt;}

    NP:
        {&lt;NBAR&gt;}
        # Above, connected with in/of/etc...
        {&lt;NBAR&gt;&lt;IN&gt;&lt;NBAR&gt;}
"""

chunker = nltk.RegexpParser(grammar)
tree = chunker.parse(postoks)
</code></pre>
<p>It is also possible to describe a Context Free Grammar (CFG) to do this, and help deal with ambiguity - information can be found in <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch08.html">Chapter 8 of the NLTK book</a>. Chunk regexes can be much more complicated if needed, and support <em>chinking</em>, which allows you to specify patterns in terms <em>what you don't want</em> - see <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch07.html">Chapter 7 of the NLTK book</a>.</p>
<p>The output of chunking is a tree, where the noun phrase nodes are located just one level before the leaves, which are the words that constitute the noun phrase:</p>
<p><img src="http://nltk.googlecode.com/svn/trunk/doc/images/chunk-treerep.png" width="600" height="696" class="aligncenter" /></p>
<p>To access the leaves, we can use this code:</p>
<pre><code>def leaves(tree):
    """Finds NP (nounphrase) leaf nodes of a chunk tree."""
    for subtree in tree.subtrees(filter = lambda t: t.node=='NP'):
        yield subtree.leaves()
</code></pre>
<h2>Walking the tree and Normalisation</h2>
<p>We can now walk the tree to get the terms, applying normalisation if we want to:</p>
<pre><code>def get_terms(tree):
    for leaf in leaves(tree):
        term = [ normalise(word) for word, tag in leaf
            if acceptable_word(word) ]
        yield term
</code></pre>
<p>Normalisation may consist of lower-casing words, removing stop-words which appear in many documents  (i.e. if, the, a&#8230;), stemming (i.e. cars $&#92;rightarrow$ car), and lemmatizing (i.e. drove, drives, rode $&#92;rightarrow$ drive). We normalise so that at later stages we can compare similar key phrases to be the same; <code>'the man drove the truck'</code> should be comparable to <code>'The man drives the truck'</code>. This will allow us to better rank our key phrases :)</p>
<p>Functions for normalising and checking for stop-words are described below:</p>
<pre><code>lemmatizer = nltk.WordNetLemmatizer()
stemmer = nltk.stem.porter.PorterStemmer()

def normalise(word):
    """Normalises words to lowercase and stems and lemmatizes it."""
    word = word.lower()
    word = stemmer.stem_word(word)
    word = lemmatizer.lemmatize(word)
    return word

def acceptable_word(word):
    """Checks conditions for acceptable word: length, stopword."""
    from nltk.corpus import stopwords
    stopwords = stopwords.words('english')

    accepted = bool(2 &lt;= len(word) &lt;= 40
        and word.lower() not in stopwords)
    return accepted
</code></pre>
<p>And the result is:</p>
<pre><code>&gt;&gt;&gt; terms = get_terms(tree)
&gt;&gt;&gt; for term in terms:
...    for word in term:
...        print word,
...    print
buddha
godhead
circuit
digit comput
gear
cycl transmiss
mountain
petal
flower
buddha
demean oneself
</code></pre>
<p>Are these similar to the key phrases you chose? There are lots of areas above that can be tweaked. Let me know what you come up with :) (the code can be found in <a href="https://gist.github.com/879414">this gist</a>).</p>
<p>In future posts I will talk about how to rank key phrases. I will also discuss how to scale this to process many documents at once using MapReduce.</p>
<p>In the mean time check out the <a href="http://text-processing.com/demo/">demos</a> on <a href="http://streamhacker.com/">Streamhacker</a>, solve the problems in the <a href="http://www.nltk.org/">NLTK book</a>, or read the <a href="http://www.amazon.com/gp/product/1849513600/alexbowecom-20">NLTK Cookbook</a> :)</p>
<p>The post <a href="http://alexbowe.com/au-naturale/">Au Naturale &#8211; an Introduction to NLTK</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p><img src="http://feeds.feedburner.com/~r/alexbowe/~4/BaflknuDmd0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://alexbowe.com/au-naturale/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://alexbowe.com/au-naturale/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=au-naturale</feedburner:origLink></item>
		<item>
		<title>Advice to CS Undergrads</title>
		<link>http://feedproxy.google.com/~r/alexbowe/~3/x5-Qja_cvQo/</link>
		<comments>http://alexbowe.com/advice-to-cs-undergrads/#comments</comments>
		<pubDate>Mon, 07 Feb 2011 21:35:49 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[education]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[reading]]></category>

		<guid isPermaLink="false">http://alexbowe.com/?p=149</guid>
		<description><![CDATA[<p>Since I&#8217;m starting my PhD this year, I have been reflecting on how I would be different if I went back in time and started my degree all over again. I am also continuing tutoring, in my 4th year, and I have been occasionally approached by students and asked for general advice with their studies. [...]</p><p>The post <a href="http://alexbowe.com/advice-to-cs-undergrads/">Advice to CS Undergrads</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><img src="http://alexbowe.com/wp-content/uploads/2011/02/hup-board-1024x565.jpg" alt="Lecture theatre" width="620" class="aligncenter size-large wp-image-176" /></p>
<p>Since I&rsquo;m starting my PhD this year, I have been reflecting on how I would be different if I went back in time and started my degree all over again. I am also continuing tutoring, in my 4th year, and I have been occasionally  approached by students and asked for general advice with their studies.</p>
<p>I repeat the same advice to most students, so I&rsquo;ll attempt to distill it  into the points below. Bear in mind that I am writing from a Computer Science  perspective, although some of the advice can be applied to any field.</p>
<p>I didn&rsquo;t do most of this stuff during my undergrad years. I still did well, but I think I would have had more fun if I followed this advice. If you&rsquo;re not  doing all the stuff on this list, that&rsquo;s okay. Come back and try again later.</p>
<p><span id="more-149"></span></p>
<p>Here&rsquo;s the advice in no particular order:</p>
<p><strong>Decide to get Good.</strong> I know a lot of students who aren&rsquo;t sure if they are in  the right degree. Computer Science isn&rsquo;t for everyone, but if you are far enough  in (&gt; 1 year) I recommend riding it out. I even had my own doubts; While  programming was a hobby for me prior to uni, most subjects at uni left me disappointed. When I started searching for parts of it that interested me, I  found it much more creative and fun.</p>
<p>After your degree, you can do Masters in something else, and it will only take  1.5 or 2 years. Or you can study other things in your spare time. Don&rsquo;t bite off  too much though&hellip;</p>
<p>Supposedly it takes <a href="http://norvig.com/21-days.html">10,000 hours to become an expert at anything</a>, but  after that I bet it is faster to become an expert at other things; many of the  10,000 hours you spend will be self-learning that can be applied to the next.</p>
<p><strong>Learn More Languages.</strong> Everyone gives this advice, but they usually suggest  it because it will give you a perspective on different ways to do things. I think you should learn Python (or Ruby) in order to remove the friction from  learning (try the book <a href="http://learnpythonthehardway.org/">Learn Python The Hard Way</a> by Zed Shaw).</p>
<p>Python has been dubbed &ldquo;executable pseudocode&rdquo;, so this will help you when  reading algorithm books. They are both dynamically typed, which means you don&rsquo;t  have to tell the computer when you are talking about a number vs a string. They  also come with an interactive shell where you can test ideas and easily  enter/modify examples from books.</p>
<p>Since their syntaxes are C-like, you can start your assignments in one of these  languages, and easily translate it by hand to Java or C. Build one to throw  away (thanks, <a href="http://www.amazon.com/gp/product/0201835959/alexbowecom-20">Fred Brooks</a>) so you can learn about the pitfalls of the  problem before you have to deal with pointers or boiler-plate code.</p>
<p>Lisp is also recommended. It can be daunting to choose a dialect when you know  nothing about it&hellip; Just learn Scheme (you can learn Common Lisp or Clojure  later). There is really amazing free material that you&rsquo;ll probably want to  <a href="http://mitpress.mit.edu/sicp/">read</a> or <a href="http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/">watch</a> at some point anyway. It will be less  practical for your uni years, but will give you a depth of knowledge that will  carry you through your entire career.</p>
<p>Oh yeah, and learn and use regular expressions the next time you need to process  text.</p>
<p><strong>Manage Your Time.</strong> Okay, this is a no-brainer, but I still didn&rsquo;t do it that well. The day you get an assignment, put it on your calendar and set a reminder.  After you&rsquo;ve done that, start working on it right away.</p>
<p>Remember, you aren&rsquo;t committed to whatever you write down, until you hand it in;  once again, build one to throw away. Even a mind-map or just writing headings  can help a lot. Inevitably you&rsquo;ll rush it at the last minute, but having  previous work to reference rather than a blank page is so much more comforting.  I&rsquo;ll write more productivity advice in a later post, so keep checking back.</p>
<p><strong>Read!</strong> I don&rsquo;t mean the prescribed text-book &#8211; I only read a few of those,  and sometimes they are only recommended because the lecturer is somehow invested  in it (don&rsquo;t get me wrong, some are great, but you&rsquo;ll find out about those books  anyway).</p>
<p>I recommend starting with <a href="http://www.amazon.com/gp/product/020161622X/alexbowecom-20">The Pragmatic Programmer</a>; It&rsquo;s nice and  small, very practical, acclaimed, and it will point you in the direction of  other good books to read when you&rsquo;ve finished.</p>
<p>Other than that, check out some recommended reading lists <a id="fnref:reading" class="footnote" title="see footnote" href="#fn:reading">1</a>, and  subscribe to blogs <a id="fnref:blogs" class="footnote" title="see footnote" href="#fn:blogs">2</a>. I&rsquo;ll also discuss my reading workflow at a later  date, as you have to be careful of information-glut.</p>
<p><strong>Sharpen Your Tools.</strong> Here are some tools that will help you make learning an enjoyable process:</p>
<ul>
<li>Get a laptop. I feel bad saying that coz it will cost you money, but it  really helps to have your coding environment ready to go.</li>
<li>Use Unix. I only did this after I switched to Mac OS X, but there are free alternatives. It&rsquo;s just a nicer environment for coding. It will also reduce the amount of time you spend on games.</li>
<li>Use Git and GitHub. Often, I would try to fix a bug in an assignment only to introduce more. Sometimes I would make backups of the project folder, but this was usually confusing and has led to me losing major chunks of work. Every project you do should be on GitHub to help you manage this, enable you to have pride in your work (by displaying it publicly), and having an  off-site backup.</li>
<li>Start learning Vim during a break. It has a steep learning curve, but will  make you faster in the end.</li>
</ul>
<p><strong>Start Your Career Early.</strong> Another thing I didn&rsquo;t do. Here are some things you  can do to help you hit the ground running when you finish uni:</p>
<ul>
<li>Contribute to open source. It looks good on your resume, and (as japerk commented) will help you learn about real world programming and software in the wild. You can find beginner-level bugs on  <a href="https://openhatch.org/search/?toughness=bitesize">openhatch</a>.</li>
<li>Maintain a resume and apply for jobs (even if they are out of your league). Worst-case, you don&rsquo;t get it, but it will may help you spot holes in your  knowledge and experience (failing a Google interview was a big reality check  for me). Best-case, you get relevant work while at uni.</li>
<li>Tutor people. Studies have shown that we learn best when we are teaching.</li>
</ul>
<p><strong>Don&rsquo;t Forget: People Matter!</strong> It&rsquo;s easy for a geek to forget this, but I  think it&rsquo;s the lynchpin to good education.</p>
<p>The friends you make, even if less intelligent, will drive you to  do Computer Science for fun. They will either show you the cool stuff they  learn, or challenge you to do better than them. But it doesn&rsquo;t stop with your  classmates.</p>
<ul>
<li>Write a blog. This will refine your communication skills, but I still get  emails from people thanking me for my (simple) <a href="http://www.alexbowe.com/education/nanosecond-timing">nanosecond time wrapper</a>. It&rsquo;s fun and rewarding. If you are having  trouble maintaining it persistently, <a href="mailto:bowe.alexander@gmail.com">email me</a> and I&rsquo;ll tell you  about a relevant project of mine that might help&hellip;</li>
<li>Tweet about your programming interests. This will build a network outside of  uni, that will remind you why you like doing this. Follow me on twitter:  <a href="http://www.twitter.com/alexbowe">@alexbowe</a> :)</li>
<li>Email your idols. It can be really helpful and exciting to get a response  from someone whose blog you read, or who has written a book or paper you read. This really helped me with my thesis last year. It might also give  you something to blog about ;)</li>
</ul>
<p>To me, these are the most important pieces of advice to take while studying (or as soon as you are ready). Criticism, suggestions, and comments of any other type are welcome, as always. It&rsquo;d also be cool to hear about things you think paint CS in a cool light for students (The game of life is one example).</p>
<p>For more blog posts on similar matters by much better writers and programmers  than me, check out:</p>
<ul>
<li><a href="http://www.catb.org/~esr/faqs/hacker-howto.html">Eric Raymond &#8211; How To Become A Hacker</a></li>
<li><a href="http://www.paulgraham.com/college.html">Paul Graham &#8211; Undergraduation</a></li>
<li><a href="http://www.paulgraham.com/undergrad2.html">Paul Graham &#8211; More Advice for Undergrads</a></li>
<li><a href="http://www.joelonsoftware.com/articles/CollegeAdvice.html">Joel Spolsky &#8211; Advice for Computer Science College Students</a></li>
<li><a href="http://programmers.stackexchange.com/questions/44177/what-is-the-single-most-effective-thing-you-did-to-improve-your-programming-skill">Quesiton on Stack Overflow: What is the single most effective thing you did to improve your programming skills?</a></li>
</ul>
<div class="footnotes">
<hr />
<ol>
<li id="fn:reading">
<p>After <a href="http://www.amazon.com/gp/product/020161622X/alexbowecom-20">The Pragmatic Programmer</a>, try <a href="http://www.amazon.com/gp/product/1934356344/alexbowecom-20">The Passionate Programmer</a>. If you want a good book to help you with your people skills, try <a href="http://www.amazon.com/gp/product/1439167346/alexbowecom-20">How To Win Friends And Influence People</a>. <a href="http://www.codinghorror.com/blog/2004/02/recommended-reading-for-developers.html">Coding Horror</a> and <a href="http://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read">Stack Overflow</a> have great book recommendations too. And a list of <a href="http://stackoverflow.com/questions/194812/list-of-freely-available-programming-books">FREE books</a>.<a class="reversefootnote" title="return to article" href="#fnref:reading">&nbsp;↩</a></p>
</li>
<li id="fn:blogs">
<p>Too many great blogs to list. Start at <a href="http://news.ycombinator.com">Hacker News</a> and you&rsquo;ll soon find some great blogs to follow. Theres also a recommendations <a href="http://news.ycombinator.com/item?id=128762">thread there already</a>.<a class="reversefootnote" title="return to article" href="#fnref:blogs">&nbsp;↩</a></p>
</li>
</ol>
</div>
<p>The post <a href="http://alexbowe.com/advice-to-cs-undergrads/">Advice to CS Undergrads</a> appeared first on <a href="http://alexbowe.com">Alex Bowe</a>.</p><img src="http://feeds.feedburner.com/~r/alexbowe/~4/x5-Qja_cvQo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://alexbowe.com/advice-to-cs-undergrads/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://alexbowe.com/advice-to-cs-undergrads/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=advice-to-cs-undergrads</feedburner:origLink></item>
	</channel>
</rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced
Object Caching 1668/1820 objects using apc

Served from: alexbowe.com @ 2013-01-21 05:29:47 -->
