Showing posts with label Github. Show all posts
Showing posts with label Github. Show all posts

Wednesday, 18 December 2013

Installing and using Sage just got even easier.

+Sage Mathematical Software System just moved to git!

https://plus.google.com/113421169347512599264/posts/a6avm2VUL39


This is awesome news for a variety of reasons. First of all it's great for development (you can take a look at the github repo here: https://github.com/sagemath/sage. There's a good talk about the git workflow for development by +Volker Braun here: http://www.youtube.com/watch?v=0tejiKN5ctY.

The other great reason why this is awesome is that it just got really easy to use and install Sage.

Here's a short video demonstrating everything I've done below:



If you're familiar with git then you know this but if you're not then you can simply open up a terminal on anything *nix (linux/Mac OS) and type the following:

$ cd ~
$ git clone git://github.com/sagemath/sage.git 

This basically goes to the git repository on github and clones it to a folder called sage in your home directory (if you don't have git installed you'll have to do that first).

Once you've done that you need to 'make' sage:

$ cd ~/sage
$ make

This will take a little while (it goes and gets most of what you need so it's hard to say how long as it depends on your machine) but after that you'll have Sage on your machine. If you're still in the ~/sage directory you can simply type ./sage to start sage.

You'll want to add sage to your path so that you can use it from any directory. In this video I did this by using a bit of a trick but here's I'll do something simpler: create a symbolic link to the sage file in ~/sage directory and place that symbolic link in your path (in /usr/bin/local). To do that type this:

$ ln -s ~/sage/sage /usr/local/bin/sage

Now you can type sage anywhere and you'll get sage up and running.

What's really great about all this is that if and when updates/development happens you can just git pull to get all up to date changes. Based on the +Sage Mathematical Software System post on G+: here: it looks like you can already play around with the develop branch...

Awesome.

Of course if you want the easiest way to use Sage then simply grab an account on +The Sagemath Cloud. I gave a talk last week at the Cardiff Django/Python user group about it and  +William Stein was kind enough to drop in and take some questions: http://www.youtube.com/watch?v=OYVLoTL4xt8 (sound quality isn't always great because I move around a fair bit...)

Tuesday, 20 August 2013

A very brief and shallow analysis of the funniest jokes.

The Edinburgh Fringe Festival takes place every year and according to Wikipedia "is the world's largest arts festival, with the 2012 event spanning 25 days totalling over 2,695 shows from 47 countries in 279 venues". Every year at the festival there is a competition for the funniest one line joke. The winner for 2013 was this joke by Rob Auton:
"I hear a rumour that Cadbury is bringing out an oriental chocolate bar. Could be a Chinese Wispa"
You can see all the top 10s over the past year here:
I've spent an hour or so this evening grabbing all the jokes and doing some very basic analysis of them in Python. The full github repo with all the code (and the data set) can be found here.

Shorter jokes are better

The mean length of the jokes are 88 characters and 17 words. Taking a look at the distribution of the word counts we see that quite a large proportion of the jokes have between 10 and 15 words in them even though there are some jokes that are twice as long.



This does not necessarily imply anything but if we take a look at the rank of a joke against the number of words we see (a very slight) trend towards an affirmation of the fact that shorter jokes rank better:


Joking often does not necessarily help

There are certain comedians who has more than 1 joke in the list of top tens (this does not necessarily imply that they were joking at multiple festivals as some comedians had multiple jokes ni the top 10 of a given year). If we look at the mean and minimum (best) rank per number of jokes:





we see that a part from the 1 comedian who has four jokes there does not necessarily seem to be an advantage of joking often...

The words don't seem too important

One final bit of preanalysis done is to look at the words in each joke. Before removing the common words (I use the nltk python library which has a set of common words) the distribution is given below:


Once we remove the common words we get:



A part from the word 'FAT' which appears in 3 jokes I can't say I recognise any words that I'd normally associate with jokes so I don't suppose there's any particular words worth honing in to.

Conclusion

I can't say that I've found anything too amazing here but if anything the python file in the github repo contains the data from the past 5 years so if I (or anyone else) had time I'd take a closer look at some things...

On a technical note, pretty much everything above was done in pure matplotlib and the nltk library is very easy to use. This is all in the github repo...

Sunday, 16 June 2013

Why and how: open education resources.

This is the fourth post in a series of posts reflecting on the teaching and learning in a recent course I've taught on SAS and R. This post will be quite different in nature to the previous posts which looked at students choices between SAS and/or R in their assessment:
Here I would like to talk about how I deliver teaching materials (notes, exercises, videos etc) to my students.

All of the teaching materials for the course can be found here: drvinceknight.github.io/MAT013/.

How they got there and why I think it's a great place for them to be will be what I hope to discuss...

A Virtual Learning Environment that was not as good as alternatives.

At +Cardiff University we have a VLE provided that is automatically available to all our students that all lecturers are encouraged to use. So when I started teaching I diligently started using the service but it had various aspects that did not fit well with my workflow (having to upload files on every change, clunky interface that actually seemed optimised for IE and various other things). It was also awkward (at the time, I believe that this has been addressed now) for students to use the environment on smart phones etc...

As an alternative, I setup a very simple website using google sites and would use +Dropbox's public links to link pdfs and other resources for my students. An example of such a delivery is these basic Game Theoretical materials. This gave me great control, I no longer had to mess around with uploading versions of files, every change I made was immediately online and also as the site was pretty simple (links and pdfs) it was easily accessible to students on all platforms (I could also include some YouTube videos).

An immediate consequence of this approach is that my materials are all publicly available online.

To anyone, our students or not. The first thing I did was check with +Paul Harper: the director of the MSc course that I was only teaching on at the time that this was ok. We chatted about it a bit and were both happy to carry on. My main train of thought was that there are far better resources already available online so mine might as well be. (I've subsequently checked with our School's director of learning and teaching and there's no internal regulations against it which is nice to know about +Cardiff University)

There is a huge amount of talk about open access in research (I won't go in to that here) but less so to some extent in teaching. I did find this interesting newspaper article that ponders as to "Why don't more academics use open educational resources?". This offers a good general discussion about open education resources.

I would feel very very humbled if anyone chose to actually use my resources. I'm at the early part of my career and am still learning so I don't think that will happen anytime soon but there is another more important benefit to having my teaching stuff online for everyone.

I always post about any new courses I'm working on, on G+ and am grateful to get a fair bit of feedback from other academics around the world. This in itself gives me a certain level of confidence in front of my students who know that what I'm teaching them is verifiable by anyone in the world. I've often changed a couple of things based on feedback by other academics and I think that's brilliant.

To some extent my teaching resources are not just reviewed by a couple of peers in my university but also by anyone online who might be interested in them.

(It would be great if research worked this way too)

Through G+ (I've posted about how awesome a tool G+ is as an academic personal development tool) I learnt about git and github. If you don't know about git watch this video by +Zoë Blade is very helpful:


After a while I jumped in and starting using it. After a little longer while I found out that you can use github to host a website:


Using this I it is really easy to put together a very basic website that has all the teaching materials. The added benefit is that the materials are now all in a github repo which opens them up even more (using dbox, only the pdf files were in general in view) whereas now everything is (md, tex source files etc...) and theoretically if anyone wanted to they could pull etc...

I'm certainly not the first person to put teaching stuff up on github, (watching people like +Dana Ernst+Theron Hitchman and various others do it is what made me jump in).

The github repo for my R and SAS course can be found here and here are some other teaching things I have up on github (with the corresponding webpage if I've gotten around to setting it up):
To finish off here are the various reasons I have for putting my teaching stuff up on github:
  • Openness:
    • my students know that this is viewable by everyone which hopefully gives the resources a level of confidence;
    • people on G+ and elsewhere are able to point out improvements and fixes (if and when they have time);
  • Access: the sites are really simple (basic html with links) so they can be viewed on more or less anything;
  • Ease of use: I don't have to struggle to use whatever system is being used. If it's an option I kind of refuse to use stuff that makes me less efficient (an example of this is our email system: I use gmail). At the moment the system I like is github + git.
I wrote a blog post (which is the most read thing I've ever written - online or offline - I think) showing how to combine various things like tikz, makefiles, +Sage Mathematical Software System etc to automate the process of creating a course site so I'll put a link to that here.

Monday, 3 June 2013

An online list of mathematics books

A couple of days ago +James Noble posted a link on G+ to a spreadsheet on G+ that is editable publicly inviting people to contribute mathematics books.


The link to the sheet it here and so far it has 65 books on it (there is also a meta list of lists that has 8 lists of books; to which I've added these 2 previous posts: about mathed and about game theory) and a website I've put together that uses it as an underlying database (which I'll talk about below) can be found here.

I think this is a great idea!

It's completely open and anyone can add to it and also benefit from it. I've used various keywords to search and have found 1 or 2 books that I didn't know about.

Some initial analysis of the list

I decided I'd throw some python at this spreadsheet and first of took a look at the contributors. In particular how many books are individuals contributing (a link to all the python code is available here).



As you can see about 50% of people contribute more than 1 book (including yours truly).

I was also curious as to how many authors were listed:



Here however it seems rare for an author to have more than 1 book in the list. The most prolific author is J. SCOTT CARTER with 5 books.

Some very basic natural language analysis

Two fields in the data set that I have not yet mentioned are the 'Overview' field and the 'Target' field. These two allow for some free text describing what the book is about and who it is aimed at. I used the nltk python library (python really is crazy, anything and everything has a library) to take a look at the frequency of "uncommon" words in these two fields.

First of all the description of the books:



Nothing too surprising here (I should perhaps remove certain words from this frequency analysis) but it's cool to see that "History" is pretty high up, as well as "Teaching" and "Philosophy".

The final piece of analysis is the frequency of the words in the description of who the book is for:



An initial glance at this seems to indicate that the books on the list are mainly aimed at students and or/teachers. It would be nice I suppose to see more books for research...

A very basic static website

The other thing that the code I've put together does is write a website that is hosted using (github pages) and lists the various books (as well as gives up an up to date analysis of what you see above). The website can be found here


The website is very very basic and all static but I've scripted everything (including the download of the spreadsheet although I haven't included that on github yet) so if it's helpful and anyone wants me to update the site just let me know (give me a nudge on G+ and I even check twitter sometimes).

The github repo for all this is here. If you have any ideas for further stuff that could be done to this data set then please improve my analysis or just let me know :) It would be nice to do something slightly smarter with the nltk and also do some analysis of the links between the books (although it would probably need a bunch more books... for that to be insightful)...

A really great job by +James Noble 

I think stuff like this is really great and it's been nice chatting to James about it.


It was cool to watch the list grow (I saw James's post pretty early so go to watch people make a bunch of contributions) and it'd be nice to see it grow even more.


Sunday, 5 May 2013

Using Monte Carlo Simulation for the Estimation of Pi

A while ago on G+, +Sara Del Valle posted a link to this article The 12 Most Controversial Facts In Mathematics. Whether or not the title of that article is precise is a whole other question but one of the problems in there discusses the use of probability to estimate $\pi$.

At the time I wrote a small python script to randomly generate points (this approach of continuous random sampling is called Monte Carlo simulation) that lie in a square of length $2r$. If we let $S$ be the total number of points and $C$ to be the points that lie in an inscribed circle of radius $r$ then:

$$P(\text{point in circle})=\frac{\pi r^2}{4r^2}$$



Using this if we generate a high enough number of points we can estimate P(point in circle). We generate a point $(x,y)$ and check if that point is in the circle by checking if $x^2+y^2\leq r^2$. Using all this we get:

$\pi\approx \frac{4C}{S}$

This morning I've modified the script slightly so that it generates a few more plots:
  • If the relevant option is set it will generate a new plot for every single plot;
  • A plot of the estimate of $\pi$ as a function of the number of points.
Here's a plot of the estimate of $\pi$:



The main point of me changing this was to put together this screencast that describes the process:



If it's of interest the github repo with the code is available here.

On a related note, here's another video I put together a while back showing the basic process that can be used to simulate a queueing process:


Friday, 26 April 2013

Invitation to play a game

So I've blogged about the two thirds of the average game quite a few times now. The latest pos that is kind of a summary of the other posts can be found here.

This post is however a bit different. I'm teaching a new game theory course next year and am busy preparing that. I'm planning on using various interactive games to help with my teaching. As a result I've been figuring out google's app engine so that I can host some of these games online.


The result of this is that I've put together an online open version of the two thirds of the average game that I'd really appreciate you taking the time to play.

The website is: twothirdsoftheaveragegame.appspot.com/ and it will take you 3 minutes to make a guess (you're welcome to guess a bunch of times, only your last guess will count).

Thanks to +Leanne Smith+Zoe Prytherch+Izabela Komenda+Penny Holborn and +Angelico Fetta for testing it for me. Hopefully the bugs are all gone :)

I'll let this run for a week and pick the winner(s) on the 3rd of May at 1200 GMT. That's a week away. I would really aprpeciate you taking the time to play and can't offer much to the winners a part from being named (if you would like me to) in my blog post I write next week :)

So please do take the take to guess, more details about the game itself can be found at the site:




All the code for the site can be found at this github repo.

Wednesday, 10 April 2013

Two thirds of the average game

The two thirds of the average game is a great way of introducing game theory to students.


I've used this game on outreach events with +Paul Harper, at conferences with +Louise Orpin (when describing my outreach activities with other academics) and also in my classroom. I've blogged about the results before:
The definition of the game from the wiki page is given here:
"In game theory, Guess 2/3 of the average is a game where several people guess what 2/3 of the average of their guesses will be, and where the numbers are restricted to the real numbers between 0 and 100, inclusive. The winner is the one closest to the 2/3 average."
I run this game once without any instruction. I just explain the rules and let them fill in the form in front of them (contained in this repo).

I then bring up slides discussing how iterated elimination of weakly dominated strategies leaves the "rational" strategy to be that everyone guesses 0.


After this I invite the participants to have a second guess. In general the results are pretty cool as you see the initial shift towards equilibrium. The fact that the winning guess in the second play of the game is in fact not 0 gives an opportunity to discuss irrational behaviour and also what would happen if we played again (and again...).

I've run this game a couple of times now and here's the graph of the histogram showing the results for all guesses I've recorded.




You certainly see that the guesses move after rationalising the strategies. Funnily enough though no one has guessed 100 during the first guess but a couple of people have in the second guess. I assume this is either some students trying to tell me that I'm boring them, trying to help a colleague win or I'm perhaps not doing a great job of explaining things :)

Here's some graphs from the individual events that I've collected data for:
  • A talk I gave during a high school revision week:

  • An outreach event with the MSI:

  • MSc students from the 2012-2013 cohort:

  • Academics at a talk on outreach at OR54 (the OR society annual conference):

  • The OR society student conference SCOR2012:

  • Academic at a talk on outreach at YOR18 (The OR society conference for early career academics):


Despite the low number of participants in some of the events they all show a a similar expected trend: the second guesses are lower. Surprisingly on one occasion the second winning guess was actually 1! This is a very quick move towards the theoretical equilibrium.

These experiments have been done on a much wider scale and in a much more rigorous way than my humble "bits of fun" for example the coursera game theory MOOC collect a bunch of data on this game and there's also a pretty big experiment mentioned in this talk:



Having said that I can't recall if other experiments look at successive guesses following an explanation of rational behaviour...

Github repo


I've put all the code used to analyse a game on github. It's a simple python file that can be pointed at a directory or a file and will produce the graph (using matplotlib) as well as spit out some other information. The data set for all these events (the first graph on this post) is also on there and if anyone would like to add to it please let me know :)

(There's also the handout that I use to get the student answers in the repo)

(If you found your way here because of interests in game theory this previous post of mine listing free OSS software for game theory might be of interest)

Monday, 8 April 2013

Using sed to make sure hyper links refer to the correct format of file when using pandoc

In a previous post (which is by far the most popular thing on this blog which is mainly due I believe to a kind retweet by +John Cook and SciPyTip) I describe the makefiles I use to write large documents containing Tikz diagrams and +Sage Mathematical Software System plots in multiple formats (pdf, html and docx) using markdown and pandoc.

This is a short follow up post to fix one minor thing. In the previous post if you created hyper links in your markdown file (say pointing to another markdown document, which for my purposes was multiple chapters in some teaching notes) then all the formats (pdf, html and docx) would all point to the same format.

Here's a slight modification of the pandocipy_given_file.py script (from the previous post) which will use sed to replace the .md to the relevant format in all links.

#!/usr/bin/env python
from sys import argv
from os import system

e = argv[1][:-3]
print e

system("sed 's/.md/.html/g' %s > tmp" % (e + ".md"))
system("pandoc -s tmp -N -o " + e + ".html --mathjax")
system("sed 's/.md/.docx/g' %s > tmp" % (e + ".md"))
system("pandoc tmp -o " + e + ".docx")
system("sed 's/.md/.pdf/g' %s > tmp" % (e + ".md"))
system("pandoc tmp -N -o " + e + ".pdf --latex-engine=xelatex")
system("rm tmp")

This script creates a temporary file (tmp- this is actually important to make sure that the makefile doesn't think that you're recurrently changing the md files) that sed makes sure has the correct format for each link and pandoc can use to get the required files. For example the sed 's/.md/.html/g' command will replace all instances of ".md" with ".html". If you're not familiar with sed it's a *nix program that allows you to do find and replace in files "easily" (it's still a bit of voodoo to me). The script can be used by simply typing:

python pandocipy_given_file.py file.md

(Which assumes that file.md has all links sending to other md files.)

I use this script in the makefile as I did in the previous post:

md = $(wildcard *.md)
htmls = $(md:%.md=%.html)

all: $(htmls)

%.html: %.md
    ./pandocipy_given_file.py $<
    ../Scripts/generate_website.py

The final line of that file is not relevant to this blog post but it just runs a python script that will generate the website for the course (which is still a work in progress!). That python script doesn't do anything fancy but it goes in to each Chapter document for example and reads the Chapter title which it uses to write the index.html file. All this allows me to modify a given md file and simply run make to update the website file.

If any of this is of interest the github repo is here.

Note that in this particular case the links being "format loyal" is mainly useful for the `html` files to the general audience. The loyal links in pdf and docx format are mainly useful to me as all the paths are relative to my setup. I'm posting this again so that I don't forget it but also in case it's useful to others (you can obviously use sed to replace other things).

Sunday, 7 April 2013

Makefiles for tikz sagemath and teaching notes written in markdown

So I've posted before on multiple occasions about PCUTL which is a higher education certification process I'm currently undergoing. One of the things I paid particular attention to in my latest portfolio (a copy of which can be found at the previous link) is accessibility of teaching notes.

Generally this implies making sure students have notes in a format that they can easily manipulate (for example change font size and color). This is often implied to mean that notes should be written in .doc format. As a mathematician this isn't really an option as all our teaching material really requires to be written in LaTeX.

I have spent some time being amazed by pandoc which is a really smart piece of software that allows you to take documents in various languages and output to a variety of other languages. Here's a video I made showing how I use like to use pandoc to get notes in html,pdf and .docx format (I wrote a blog post here about it):



My entire SAS/R programming course I'm currently teaching was written this way (you can find the notes etc here).

I've recently started writing a new course: a game theory course.

This course needs a bunch of diagrams and plots (as opposed to the previous that basically had a bunch of screenshots). I wanted to use the same overall system but planned on using tikz for the diagrams (tikz lets you draw nice diagrams using code) and perhaps thought about using sagetex (I use +Sage Mathematical Software System a lot but have never used sagetex which lets you have sage code inside of a LaTeX document) for the plots.
After searching around for a bit I didn't see how I was going to be able to use the awesome pandoc to create teaching notes in multiple formats using the above approach. There was no way for pandoc to take the tikz code and output a separate image file for the html (and whatever it needs for .docx).

This blog post is a summary of my approach.

Which basically uses a couple of things:
  • Some tikz code that creates a standalone pdf image;
  • A script that converts a pdf to a png (so that it can be used in html);
  • A makefile so that I can recompile only the tikz code that needs to be recompiled;
That is how I get my tikz diagrams.

I also have a similar system to create plots from sage and I'll also show the makefile I use to get pandoc to sort out the files I want.

Creating standalone pngs with tikz and makefiles


To create a standalone tikz image you need to use the standalone document class. Once you've done that you can just use normal tikz code:

\documentclass[tikz]{standalone}
\usepackage{tikz,amsmath}
\tikzstyle{end} = [circle, minimum width=3pt, fill, inner sep=0pt, right]
\begin{document}
\begin{tikzpicture}
    \draw (0,0) -- (4,0) node [below] {$u_1$};
    \draw (0,0) -- (0,4) node [left] {$u_2$};
    \draw (3,0) node[end] (A) {} node [above=.3cm,right] {$(3,0)$};
    \draw (0,3) node[end] (B) {} node [above=.3cm,right] {$(0,3)$};
    \draw (1,1) node[end] (C) {} node [below,left] {$(1,1)$};
    \draw (2,2) node[end] (D) {} node [above=.3cm,right] {$(2,2)$};
    \draw (A) -- (D);
    \draw (D) -- (B);
    \draw (B) -- (C);
    \draw (C) -- (A);
    \draw [dashed,thick] (C) -- ++(0,1.5);
    \draw [dashed,thick] (C) -- ++(1.5,0);
    \draw [->] (2,3.5) node[above] {\tiny{Feasible average payoffs}} -- (.75,2);
    \draw [->] (4,1.5) node[above] {\tiny{Individually rational payoffs}} -- (1.5,1.25);
\end{tikzpicture}
\end{document}

The above for example creates the following standalone image (note that if you pdflatex it you obviously get a pdf which would be great if you were just pdflatex'ing a bigger document but I'll get to creating a png next):



I've then written a short python script (I'm sure this could be done as easily in bash but I'm just more comfortable in python) that can act on any given tex file to convert it to png:

#!/usr/bin/env python
from sys import argv
from os import system

system("pdflatex %s" % (argv[1]))
system("convert -density 300 %s.pdf %s.png" % (argv[1][:-4], argv[1][:-4]))

This makes use of convert which is a program that can convert pdf to png (more info here but it's natively on Mac OS and *nix I believe).

I call that python file convert_tex_to_png.py and so I can convert any tex file by doing:

python convert_tex_to_png.py file.tex

I'm going to put all these image files (tex and png) in a folder called images and there's (now that I'm done) about 70 image files in there so every time I change or write a new tex file I don't want to compile all the files and I also don't want to have to waste time compiling the particular file I've written.

So I've used makefiles.

Now I've tried to use makefiles before but in all honesty they confuse the heck out of me. I spent a while going through a bunch of tutorials but most of them look at c code. For those who don't know, a makefile is basically a short program that gives instructions to compile certain files. When written well these are great as by simply typing make you can recompile any file that has been modified (and not necessarily all of them!).

So here's the makefile I've converged to using (after heuristically trying a bunch of stuff from stackoverflow):

tex  = $(wildcard *.tex)
pngs = $(tex:%.tex=%.png)

all: $(pngs)

%.png: %.tex
    ./convert_tex_to_png.py $<;

clean:
    rm *.aux
    rm *.log
    rm *.pdf

I save the above file calling it `makefile` so that it is run by default when calling `make`. This will take all the tex files (that have been modified) and output the corresponding png files as required. Note I can also type make clean to remove all auxiliary files (aux, log and pdf).

I find this really useful as I can modify a bunch of tex files and once I'm ready simply run make to get all the pngs as required.

I'll briefly show the (basically same) code I use to get plots from sage as standalone pictures.

Creating standalone pngs with sage and makefiles


I put all the plots created via sage in a plots directory. Here's an example graph created with sage:



The sage code to do that is here:

f(a,b)=a^3/3+3/4*b^2+(1-a-b)^2/2
p = contour_plot(f,(0,.5),(0,.5),colorbar=True,axes_labels=["$\\alpha$","$\\beta$"],contours=100, cmap='coolwarm',fill=True)
p.axes_labels(['$\\alpha$','$\\beta$'])
p.save("L18-plot01.png")

The makefile (which will keep all png files up to date based on the sage files in the directory):

sage  = $(wildcard *.sage)
pngs = $(sage:%.sage=%.png)

all: $(pngs)

%.png: %.sage
    sage $<;

clean:
    rm *.py

(I can similarly use make clean to remove the .py files that get created when running sage in cli).

The final thing I'll show is how to write a makefile to get pandoc to output the required file formats.

Using a makefile with pandoc


So I write all of my notes in markdown. For various reasons which include:
  • Pandoc likes markdown as input (it can also handle tex and html though);
  • I like markdown;
  • I can incorporate latex in markdown when needed.
  • If a student ever wanted to modify the markdown but didn't know LaTeX they'd have an honest chance of knowing what was going on (if you don't know markdown it really is worth taking a look at this short video)
Thus my makefile must be able to compile all modified markdown files. I use a similar approach to the approach I had for tikz diagrams which is to write a short python script:

#!/usr/bin/env python
from sys import argv
from os import system

e = argv[1][:-3]
print e

system("pandoc -s " + e + ".md -N -o " + e + ".html --mathjax")
system("pandoc " + e + ".md -o " + e + ".docx")
system("pandoc " + e + ".md -N -o " + e + ".pdf --latex-engine=xelatex")

(pandocipy_given_file.py is the name of the above python script).

There are basically three pandoc commands going on there. The first creates the html with the LaTeX math being rendered by mathjax, the second creates the .docx format and the last one creates the pdf (using the xelatex engine).

The final piece of the puzzle is to use the following makefile:

md = $(wildcard *.md)
htmls = $(md:%.md=%.html)

all: $(htmls)

%.html: %.md
    ./pandocipy_given_file.py $<;

The way that makefiles work (I think) is to indicate what files you want as an output (and what those files are dependent on). So for example my previous makefiles wanted to output pngs with tex and sage files as dependencies. Here I use the required output as html and the dependencies are the md files.

Using the above I can change any md file and simple type make to get all the pdf, html and docx files updated.

Summary and a couple of things I don't want to forget


I have 3 directories here. The first: Course_notes contains the md files and corresponding python script and makefile. Course_notes also contains 2 other directories: images and plots which both contain the images and plots as I've described above.

So in the md files I refer to an image as so:

![A pic for C1](images/C01-img03.png)


I'm using pdf as the prescribed format of the notes for the course (students are welcome to use html and docx if they wish but I'm recommending pdf) and in general xelatex will sometime move images around to better format the text.

To make sure things don't get confusing I want to be able to \ref and \label images. The easiest way I've found to do this without messing around with the html (who knows what happens with docx, life is too short to worry about everything) is to use the \text:

In the excellently drawn image shown\text{ in Figure \ref{C01-img03}} we see that...

![A pic for C1\label{C01-img03}](images/C01-img03.png)

Pandoc is clever enough to simply ignore what is in the \text when converting to html and docx so that you get documents in html and docx that won't have a reference to the figure (but in general they won't reorder the images) and the pdf will have the documents referenced as you can see in these screenshots (showing pdf and html):

pdf:

html:


I've mainly posted this to make sure I remember how to do it but it might be helpful for others. I'm sure it could be improved by getting rid of my python scripts and having everything in the makefile. I tried that but had a hard time getting wildcards to work as I did so I didn't try anything more complicated. Finally there are ways to get makefiles to run makefiles in subdirectories so it would be nice I guess to also do that so that a single `make` in the highest directory would sort out everything.

I'll be putting all the teaching notes up on github so will link to that repository when I've done it.

EDIT: Here's the github repo and here's a website with all the content (which will eventually become the class website).

ANOTHER EDIT: Here's a follow up post which uses sed to keep the links in the right format.

Sunday, 24 March 2013

Open Source and/or Free Game Theory Software

Last week I posted some python code I've been putting together:
  • The github repo is here
  • A website with user guide and some videos is here
The code is currently a collection of 4 tools that can solve 4 type of game theoretical problems:
  • Shap.py which calculate the shapley value in a cooperative game;
  • Gale_Shapley.py an implementation of the extended Gale Shapley algorithm for matching games;
  • lrs_nash.py a (clumsy) python wrapper for the lrs library which can be used to solve normal form games. (If anyone wants to contribute to how I speak to the c library please do! - I sadly know pretty much no c yet...)
  • Abm.py which can be used to carry out agent based models of normal form games (to see emergent behaviour).
Here's a screencast demonstrating that last program:


The point of this blog post is to list some of the other pieces of software available that can be used in Game Theory.

List of game theory tools


  1. The lrs library
What it does: This is a self-contained ANSI C implementation as a callable library of the reverse search algorithm for vertex enumeration/convex hull problems and comes with a choice of three arithmetic packages. Basically it's a really smart package that does a lot of things. One of those things is solving normal form games.

Ease of use: Pretty straight forward on a *nix machine. Download a tar file and make the contents of the unpack directory. To use the package you simply pass it a couple of text files as arguments.
  1. The banach.lse.ac.uk/ website.
What it does: This is actually just an online interface making use of the above mentioned lrs library to solve normal form games.

Ease of use: Very very easy. Just point and click and enter in your normal form game.
As far as I can tell that website was put together by +Rahul Savani who is actually connected to the next item on this list.
  1. The Gambit library
What it does: As a disclaimer I haven't actually used Gambit yet. Here's the blurb from the website: Gambit is a library of game theory software and tools for the construction and analysis of finite extensive and strategic games. Gambit is designed to be portable across platforms, and runs on Linux, Mac OS X, and Windows. Reading through the website it looks like it can be used to solve normal and extensive form games. Development seems fairly active with various suggestions (including an implementation of the lrs library) for contributions. It basically looks like a C++ library with a nice GUI also available.

Ease of use: Can't say :) When I get a moment I'm sure I'll try it out...
  1. My Sage interact for 2 by 2 games
What it does: If you're not familiar with +Sage Mathematical Software System I can't recommend it enough. It's an open source mathematics package (Maple, Mathematica etc). It's a very powerful package with a very active community of developers and users. One of the neat tools is the interact website which lets you put up small bits of code online for anyone to use. This is one of those small bits of code that can be used to solve any 2 by 2 game ("any" is a bit of a lie as someone has pointed out that it crashes for some sets of inputs). It's very basic and solves the game algebraically. I actually put this together as a teaching tool (interacts are great for that) and here's the screencast I shared with my students:



Ease of use: Pretty easy, it's again a simple point and click interface available in a browser but it is very limited: it just solves 2 by 2 games.
  1. William Spaniel's calculator
What it does: I've only played with this for a couple of minutes so I won't comment too much but it looks like a solver implemented in VBA for excel for 2 by 2 games. It also looks at the repeated game aspect a bit looking at whether or not a game is a Prisoners Dilemma and what discount factor would be needed to induce cooperation in an infinitely repeated game context.

Ease of use: On a personal level I don't really like opening up an excel file unless I have to (as it usually starts up the various updates and what not) and this also won't run on linux (unless using wine etc...). Having said that it does do what it says on the tin. The VBA seems to be nicely written so that all the results are just shown immediately without the need to run any macros.
  1. My Sage interact for the Shapley value
What it does: This is another code snippet on the +Sage Mathematical Software System interact site which I wrote to accompany a screencast I did for my students showing how to calculate the Shapley value for a cooperative game (note that there's a small error at 3:51):


Ease of use: This is again pretty easy to use. It's a point and click interface in a web browser where one simply says how many players are in the game as well as the characteristic function.
  1. The Gametheory.net list
A list of (mainly Java) programs. Mostly normal form games (some of which are constrained to zero sum games). I haven't tried many of these but I'll mention this one which is written in javascript and lets you play (and find equilibria) for zero sum games of size up to 5 by 5.
  1. Some github repos
A quick search seems to identify two repos on github that are connected to game theory (I restricted my search to python):
Both these repos seem concerned with normal form games but I have not used them.

Conclusions


There is a fair bit of stuff out there for solving normal form games (and the screenshots of Gambit's GUI seem to show a nice ability to handle extensive form games). For larger scale games it seems that something that makes use of the lrs library is the best bet. There does not seem to be much in the form of agent based models and/or other type of games (such as the Gale Shapley algorithm or code to handle the calculation of the Shapley value in cooperative games apart from my humble contributions). In the gametheory.net list there is broken link to something that supposedly would calculate voting indices.

Everything that is out there is pretty easy to use though and there's a lot of open source stuff that people could contribute to :)

On a personal level I'm hoping to continue to develop my packages and I would really like to implement them in +Sage Mathematical Software System at some point if only to have them available as a great and easy to access teaching tool.

I'm sure I must have missed some so I apologise for that (and would love to know about them).

(Here's another game theory related list: A reading list)

Sunday, 30 December 2012

Some analysis of the game shut the box

This Christmas, +Zoe Prytherch and I got my mother a small board game called: "Shut the Box" (also known as "Tric-Trac", "Canoga", "Klackers", "Zoltan Box", "Batten Down the Hatches", or "High Rollers" according to the wiki page). It's a neat little game with all sorts of underlying mathematics.
Here's a picture of us playing:


Here's a close up of the box:


A good description of the game can be found on the wiki page but basically the game can be described as follows:
  • It is a Solitaire game that can be played in turns and scores compared (but no strategies arise due to interactions of players).
  • The aim is to "shut" as many tiles (each being one of the digits from 1 to 9) as possible.
  • On any given go, a player rolls two dice and/or has a choice of rolling one dice if the tiles 7,8,9 are "shut".
  • The sum total of the dice roll indicates the sum total of tiles that must be "shut". If I roll 11, I could put down [2,9],[3,8],[1,2,8] etc...
  • The game ends when a player can't "shut" tiles corresponding to the dice roll (including the case when all tiles are "shut").
Here's a plot of a game we played with a few of my mother's friends:



You can see that myself and Jean did fairly poorly while Zoë made the difference just at the end to win :)

The game could be modelled as a Markov decision process but over the past few days I decided to code it in Sage and investigate whether or not I could find out anything cool with regards to strategies. If you're not aware of Sage I thoroughly recommend you taking a look, it's an awesome open source mathematics package. In this instance I used the Partitions function to rapidly obtain various combinations of dice rolls and/or tile options to get the results I wanted.

The code is all in a github repo and I feel I've written an ok README file explaining how it works so if you're interested in playing with it please do! The code basically has two parts, the first allows you to play using the program instead of a game board (with prompts telling you what your available plays are).

Here's a quick screencast of me demonstrating some of the code:



The second part of the code allows for strategies to be written that play the game automatically ("autoplay"). I've considered 4 strateges:
  • Random (Just randomly pick any potential tile combination)
  • Shortest (Choose the tile combination that has shortest length: i.e. [3] instead of [1,2] ~ in case of a tie pick randomly)
  • Longest (Choose the tile combination that has longest length: i.e. [1,2] instead of [3] ~ in case of a tie pick randomly)
  • Greedy. This chooses the tile combination that ensures the best possible chance of the game not ending on the next go. This is calculated by summing the probabilities of obtaining a dice roll that could be obtained.
I've been leaving my computer run the code in the background for a while now so here are some early results. I've got over 90000 instances for Greedy and Random with over 40000 instances for the other two which I thought of later (EDIT: I know have over 400000 instances...). I've collected (as and when one of my home boxes was ideal) more data since writing this and the file is available for anyone to play with here. If I've made any mistakes with my analysis, I'd love to hear it!.

First of all what does the average score look like:

Greedy_Score   Random_Score     Longest_Score   Shortest_Score  
Min.   : 0.00  Min.   : 0.00    Min.   : 0.00   Min.   : 0.00  
1st Qu.: 6.00  1st Qu.:14.00    1st Qu.:18.00   1st Qu.: 7.00   
Median :11.00  Median :21.00    Median :24.00   Median :11.00
Mean   :11.42  Mean   :20.45    Mean   :24.16   Mean   :12.06  
3rd Qu.:16.00  3rd Qu.:27.00    3rd Qu.:30.00   3rd Qu.:17.00  
Max.   :43.00  Max.   :43.00    Max.   :43.00   Max.   :43.00  

Shortest and Greedy seem to do a fair bit better then the other two. If we take a look at the distribution of the scores that is confirmed:




If we also take a look at the length of the game (i.e. how many total dice rolls there were):

Greedy_Length  Random_Length  Longest_Length  Shortest_Length
Min.   :1.000  Min.   :1.000  Min.   :1.00    Min.   :1.00    
1st Qu.:4.000  1st Qu.:3.000  1st Qu.:2.00    1st Qu.:4.00    
Median :5.000  Median :3.000  Median :3.00    Median :5.00    
Mean   :4.897  Mean   :3.414  Mean   :2.86    Mean   :4.82    
3rd Qu.:6.000  3rd Qu.:4.000  3rd Qu.:4.00    3rd Qu.:6.00    
Max.   :9.000  Max.   :9.000  Max.   :8.00    Max.   :9.00    
                                                             

We see that games last longer when using Greedy and Shortest. If we look at the distribution we see (I've updated this graph since first publishing this post):



It looks like Greedy might allow for slightly longer games than Shortest. Whether or not playing Shortest or Greedy is actually any different seems interesting. A simple analysis of variance (ANOVA) seems to indicate that there is a significant effect:
Df Sum Sq Mean Sq F value P
stbaov$Method 1 11337 11337 196.3 2e-16
Residuals 127169 7345725 58

This is all experimental of course and analysing whether or not my suggested greedy strategy is indeed the optimal strategy would require some markov decision process modelling. I might look in to this with an undegraduate project student next year.

The tricky part about using the greedy method whilst actually playing the game with friends is that it requires a fair bit of calculation. Nothing that Sage can't handle in a split second but something that could keep people waiting a fair bit if you were to work it out with a pen and paper. Despite the significant statistical difference between the methods this analysis seems to indicate that choosing the shortest set of tiles is a pretty good strategy so if in doubt I recommend choosing that...

If anyone cares enough about all this to fork the code or suggest a different strategy I'd be delighted :) In case you missed it above, here's the github repo:

https://github.com/drvinceknight/Shut_The_Box

(On a technical note some of the pre analysis is done using python and the actual graphs seen here are done using R)

Saturday, 17 November 2012

Blog/YouTube Channel

I don't post to my blog very often yet I have started making a few more videos on my YouTube channel in one of three categories I guess:

- "Tech" (for want of a better name) how to's (or more exactly how I've figure out how to do stuff which might not be the best way...)
- "Education" (for want of a better name) stuff
- Research presentations

I've decided that I'll also throw those videos on here when I put them together (not too sure why, perhaps the best reason is "why not?"). To get started here are 3 past videos:

- Using GitHub to host a website:



- Simulating a Queue: Basic Discrete Event Simulation



- A game theoretical approach to the EMV ED interface