2015-01-18

Spiral Matrix

Have you ever tried to assign integer values to a square matrix in spiral order? Eg. for a 5x5 matrix this would look as follows:

1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

If this is what you have been lying wake at night for, here comes an iterative solution using Python/Numpy:

#!/usr/bin/env python
""" create a spiral array """

import numpy

def spiral(n):

     mat = numpy.zeros([n,n])

    dirs = [
        numpy.array([0,1]),  #right
        numpy.array([1,0]),  #down
        numpy.array([0,-1]), #left
        numpy.array([-1,0]), #up
    ]

    ptr = numpy.array([0,-1])
    ptr_prime = ptr
    cur_dir_ind = 0
    for i in range(1,n*n+1):
        #adjust direction if necessary
        while(True):
                ptr_prime = ptr + dirs[cur_dir_ind]

                if ptr_prime[0]<0 or ptr_prime[0]>=n or ptr_prime[1]<0 \\ 
                   or ptr_prime[1] >= n:
                        cur_dir_ind = (cur_dir_ind + 1) % len(dirs)
                elif mat[ptr_prime[0],ptr_prime[1]] > 0.0:
                        cur_dir_ind = (cur_dir_ind + 1) % len(dirs)
                else:
                    break

        #update ptr;
        ptr = ptr_prime
        mat[ptr[0],ptr[1]] = i
    
    return mat

2015-01-17

7 Wonders

This post is about the board game 7 Wonders. Sometimes there is a bit of confusion about calculating the victory points from the green cards (scientific structures). Each of the green cards has a symbol (tablet, compass or gear). The player receives 7 victory points for a set of all three symbols and additionally the number of the symbols squared for every symbol. Moreover there is a purple 'joker' card (guild) that can count as any type of green card.

The following few lines of Python can be used to compute the maximum amount of victory points that can be obtained for a given amount of tablet, compass, gear and joker cards. It does this by recursively finding the best allocation for the purple joker cards.

 
#!/usr/bin/env python
""" compute max nr of points for science cards """

#type1 : gear
#type2 : tablet
#type3 : compass

def get_score(type1, type2, type3):

    a = type1**2+type2**2+type3**2
    b = min([type1, type2, type3]) * 7 #sets

   return a+b


def max_points(type1=0, type2=0, type3=0, joker=0):

    if joker==0:
        return get_score(type1, type2, type3)
    else:
        return max([
            max_points(type1+1,type2 , type3 , joker-1),
            max_points(type1 ,type2+1, type3 , joker-1),
            max_points(type1 ,type2 , type3+1, joker-1)
        ])

2014-12-22

Exercise Sounds with SuperCollider

Imagine you are instructing a group of athletes doing circuit training. The circuit training consists of stress and relaxation phases, which will be repeated in multiple series. At the end of a series there is usually a longer relaxation phase ('Serienpause').

To determine beginning and end of the individual phases, it is straight forward to use a stopwatch. However, the stopwatch will draw away most of your attention and you will not be able to correct the athletes any longer. Therefore, an acoustic signal is desirable that indicates the individual phases. The waveform of the signal might look as shown below:
The pulses indicate the seconds during the stress phase and the noisy parts mark the relaxation phase.
Such an audio signal can be synthesized using a software synthesizer, eg. SuperCollider. An exemplary audio file that was created with SuperCollider can be listened to here. It consists of 3 series with 2 stress phases (30s), a relaxation phase (20s) and a longer relaxation phase at the end of the series (30s).

The SuperCollider code, that was used to generate the audio file, can be downloaded here. It can be easily adapted to account for other durations of the individual phases.

2014-09-02

Presentations and Age-related Vision Changes

It is well known that people's vision degrades as they age. Imagine you are making slides for a presentation and want to optimize them for an audience with potential vision difficulties.

This script can be used to estimate how an elderly person  might perceive your slides (needs ImageMagick, GMIC). An example slide is shown below.

The script applies a general blur to the slides, a yellow tint to account for yellowing of the lens and reduced color vision. At last, it applies a vignette to account for the loss of peripheral vision.

2014-07-22

Presenting a Bibtex Bibliography on a Website

Imagine you are given a long Bibtex file, that needs to be presented on a website. In order to achieve some flexibility in presenting the data, a MySQL database is to be used. This rules out alternatives such as bibtex2html, which creates static html pages.

A Python script that can be used to parse the Bibtex file and write it into the database can be downloaded here. Pybtex is used to conveniently parse the Bibtex file. The database layout for the different publication types (article, inproceedings, incollection, etc.) is hardcoded into the script, but should be easily adaptable to your needs.

2014-06-24

Ordering Pictures by Dissimilarity

Imagine you want to post some pictures on the web, eg. for a social media post or a picture gallery on the web. Sometimes the context defines how the pictures have to be ordered, eg. in chronological order, but sometimes you also have the freedom to order the pictures, such that the presentation becomes more interesting.

The question is whether it is possible to automatically find an ordering for the pictures that makes the presentation more interesting to the user. The idea of this post is that the pictures should be ordered to maximize dissimilarity between consecutive pictures. It should catch the the viewers attention if the visual impression of two consecutive pictures is as different as possible.

A metric is required to formalize 'dissimilarity'. Different options exist here, but one approach is to look at the histograms of every picture and quantify the similarity between two pictures as the statistical distance between their histograms.

A script that implements this idea can be downloaded here (needs OpenCV). The Bhattacharyya distance is used as one example of a statistical distance. An example of a picture set in 'boring order' and a picture set that has been sorted as outlined above is shown below:

Lenna in 'boring order'

Lenna in 'interesting order'

2014-05-30

DDNS and IPv6?

Ever tried setting up DDNS with IPv6? I recently had to learn that there is a remarkable range of tools and services that do not work with IPv6.

ddclient does not support IPv6, nor does inadyn.
inadyn-mt claims to support IPv6, but if that is true, it is at least hard to configure.

Also not all DDNS-Services offer IPv6 support with freedns.afraid.org being one notable exception. This service also allows setting the IPv6 via a URL.

A pragmatic solution to get DDNS working with IPv6 could be running the following Python script periodically using a cronjob:
 
#!/usr/bin/env python
''' update ipv6 record on freedns.afraid.org '''

import netifaces
import subprocess
import sys

iface_name = "eth0"
pwd_hash = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr"

try:
addrs = netifaces.ifaddresses(iface_name)
ipv6_str = addrs[netifaces.AF_INET6][0]['addr']
#check if link local adress
if ipv6_str[0:5] == "fe80:":
raise Exception()

except:
sys.exit("could not determine ipv6 address");


subprocess.call(
[
"wget",
"-q",
"--read-timeout=0.0",
"--waitretry=5",
"--tries=400",
"https://freedns.afraid.org/dynamic/update.php?"+pwd_hash+"&address="+ipv6_str
]
)

The script can also be downloaded here. It requires the package netifaces, which can be installed using pip. Moreover wget needs to be installed. You need to adjust the interface name and the password hash manually.
$> sudo apt-get install python-pip
$> sudo pip install netifaces

I suggest simply copying the script to /opt, making it executable and adding a cronjob for it.
$> sudo crontab -e

add the following line to the crontab
 */30 * * * *    /opt/ipv6_update.py

and restart the cron daemon
$> sudo /etc/init.d/cron restart

If you are using a network manager, eg. wicd or network-manager, the Python script above can be hooked in there. For wicd the script would have to be copied to
/etc/wicd/scripts/postconnect