Sunday, September 18, 2016

Something for your mind: Polymath Podcast launched


Some episodes
will have more Art content, some will have more Business content, some will have more Science content, and some will be a nice blend of different things. But for sure, the show will live up to its name and provide you with “something for your mind”. It might raise more questions than it answers, and that is fine too.

Episode 000
Listen to Something for your mind on http://Artchiv.es

Francois Dion
@f_dion

Monday, April 18, 2016

Los Alamos 10742: The Making of

Modern rendering of the original 1947 Memo 10742

Before reading


If you've not read the first part (The return of the Los Alamos Memo 10742) of this blog, go there now. There will be a link to come back here at the end, so you don't forget ...


Your assignment


If you remember, in the previous article, I had asked the students (and, you, the reader) to try this exercise:

"Replicate either:
a) the whole memo
or
b) the list of numbers 
Whichever assignment you choose, the numbers must be generated programmatically."

One possible way

We'll use Python 3 and do b):

In [1]:
def num_to_words(n):
    """Returns a number in words, covering 0 to 100 inclusive."""
    n2w = {
        0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six',
        7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'a dozen',
        13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen',
        18: 'eighteen', 19: 'nineteen', 
        20: 'twenty', 30: 'thirty', 40: 'fourty', 50: 'fifty', 60: 'sixty', 70: 'seventy',
        80: 'eighty', 90: 'ninety', 100: 'one hundred'
    }
    try:
        return n2w[n]
    except KeyError:
        return n2w[n-n%10] + ' ' + n2w[n%10]
The famous twelve as 'a dozen'
In [2]:
num_to_words(12)
Out[2]:
'a dozen'
In [3]:
num_to_words(7)
Out[3]:
'seven'
In [4]:
num_to_words(67)
Out[4]:
'sixty seven'
In [5]:
num_to_words(100)
Out[5]:
'one hundred'
Generating the alphabetical word list, not including number 10
In [6]:
word_tuples = sorted([(num_to_words(num),num) for num in range(101) if num != 10])
Now that the list is sorted alphabetically, just want the second item of each tuple [1]
In [7]:
result = list(zip(*word_tuples))[1]
Let's print this.
In [8]:
print(str(result)[1:-1])
12, 8, 18, 80, 88, 85, 84, 89, 81, 87, 86, 83, 82, 11, 15, 50, 58, 55, 54, 59, 51, 57, 56, 53, 52, 5, 4, 14, 40, 48, 45, 44, 49, 41, 47, 46, 43, 42, 9, 19, 90, 98, 95, 94, 99, 91, 97, 96, 93, 92, 1, 100, 7, 17, 70, 78, 75, 74, 79, 71, 77, 76, 73, 72, 6, 16, 60, 68, 65, 64, 69, 61, 67, 66, 63, 62, 13, 30, 38, 35, 34, 39, 31, 37, 36, 33, 32, 3, 20, 28, 25, 24, 29, 21, 27, 26, 23, 22, 2, 0
In [ ]:

If you read the commentaries for the previous article on the subject, you surely ran into Edward Carney's almost working proposed solution. I am adding it here as another way of attacking the problem. Edward used a module named num2words. As you'll discover over years of writing python code, most anything you can think of has already been done. And in some cases, multiple times.

Why did I say almost working? Let's see if somebody finds the issue. If not I'll post the correction in a future post (the very next one will diverge from this subject to talk about fractals). I'll also introduce the inflect module and since we're introducing some NLP concepts, I'll bring in NLTK too.

In [1]:
import num2words as n2w
In [2]:
key_set = []
[key_set.append(n2w.num2words(i)) for i in list(range(101))]
key_set[12] = 'dozen'
key_set[100] = 'one hundred'
numset_dict = dict(zip(key_set,list(range(101))))
line_breaks = [14, 30, 46, 62, 78, 94]
for i, k in enumerate(yvals):
    print('{} '.format(k[1]),end='')
    if i in line_breaks:
        print('\n')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-6c7998a49267> in <module>()
      5 numset_dict = dict(zip(key_set,list(range(101))))
      6 line_breaks = [14, 30, 46, 62, 78, 94]
----> 7 for i, k in enumerate(yvals):
      8     print('{} '.format(k[1]),end='')
      9     if i in line_breaks:

NameError: name 'yvals' is not defined



You know the solution? Post it in the comments section.

Francois Dion
@f_dion

Monday, March 14, 2016

The date is the title...

J. Venn - Logic of Chance


Turtle Graphics?


The above, looks suspiciously like a printout from my first session with Apple Logo (the language, not the branding), before I figured the command for "pen up"...

A few months back, I was reading a few books and found the above in one of them. It is titled "Logic of Chance", by John Venn (mostly known for the Venn diagram). The year? 1866.

So, where were we? Ah yes...

3/14/16


Yes, that famous sequence of number. What was the story with John Venn and pi, here? Whereas I used digits 0-9 in "the 10 colors of pi", John used digits 0-7, discarding all 8s and 9s. Since back then there were no computers, he picked his numbers from a book (by R. Shank) which had 707 digits of pi, leaving him with 568 digits between 0 and 7. He mapped 0 to 7 to directions (10 directions might have felt a bit odd, at 36 degrees, versus nice 45 degree lines):



Although he doesn't specify the mapping, it is easy to infer from the graph. The first digit after the decimal is 1, then 4 and we can see the path as NE, then S, so:


0 N
1 NE
2 E
3 SE
4 S
5 SW
6 W
7 NW

The random walk

He would then move by 1 unit in the direction of each digit / direction mapping. NE, S, NE, SW, skip 9, E, so on and so forth. (NB: This is easy to reproduce in python with the turtle module. A quick search of my blog will get you started on this, from a pi generator to import turtle.)

His conclusion stated: 
"The result seems to me to furnish a very fair graphical indication of randomness". 

Francois Dion
@f_dion

Saturday, March 5, 2016

The return of the Los Alamos Memo 10742 -

Modern rendering of the original 1947 Memo 10742

The mathematician prankster


Can you imagine yourself receiving this memo in your inbox in Washington in 1947? There's a certain artistic je ne sais quoi in this memo...

This prank was made by J Carson Mark and Stan Ulam.  A&S was Administration and Services.

And Ulam, well known for working on the Manhattan project, also worked on really interesting things in mathematics. Specifically, a collaboration with Nicholas Constantine Metropolis and John Von Neumann. You might know this as the Monte Carlo method (so named due to Ulam's uncle always asking for money to go and gamble in a Monte Carlo casino...). Some people have learned about a specific Monte Carlo simulation (the first) known as Buffon's needle.

Copying the prankster

When I stumbled upon this many years ago, I decided that it would make a fantastic programming challenge for a workshop and/or class. I first tried it in a Java class, but people didn't get quite into it. Many years later I redid it as part of a weekly Python class I was teaching at a previous employer.

The document is the output of a Python script. In order to make the memo look like it came from the era, I photocopied it. It still didn't look quite right, so I then scanned that into Gimp, bumped the Red and Blue in the color balance tool to give it that stencil / mimeograph / ditto look.


Your assignment


Here is what I asked the students:

"Replicate either:
a) the whole memo
or
b) the list of numbers 
Whichever assignment you choose, the numbers must be generated programmatically."

That was basically it. So, go ahead and try it. In Python. Or in R, or whatever you fancy and post a solution as a comment.

We will come back in some days (so everybody gets a chance to try it) and present some possible methods of doing this. Oh, and why the title of "the return of the Los Alamos Memo"? Well, I noticed I had blogged about it before some years back, but never detailed it...

Learning more on Stan Ulam


See the wikipedia entry and also:

LOS ALAMOS SCIENCE NO. 15, 1987



[EDIT: Part 2 is at: los-alamos-10742-making-of.html]

Francois Dion
@f_dion

Monday, January 4, 2016

Stack overflow en espanol

En caso que no lo ha encontrado, el sitio stack overflow ahora es disponible en español. Y, no todas las respuestas son las mismas que la del stack overflow en ingles. Hay una buena cantidad de contenido exclusivo.

#Python

Por ejemplo, alguien pregunto: Cómo instalar MySQLdb en OS X?

Hay varias respuestas, pero yo se que la mía es algo que yo he escrito solamente en español:


Mysql-python solo es compatible con python 2 (Python3 WOS), y el pip es de python 3:
$ which pip
Muy probablemente devolverá algo similar a:
/Library/Frameworks/Python.framework/Versions/3.x/bin/pip
Para hacer la instalación bajo python 2, hay que seleccionar el pip de python 2:
$ sudo pip2 install MySQL-python
La otra opción es un módulo puro python que es compatible python 2 y 3, como pymysql.
Al final, para evitar los conflictos de versiones y también los python de Apple (con varios problemas) es mejor hacer la instalación de python 2.x y 3.x con homebrew, y utilizar virtualenv que permite la creación de entornos virtuales python, cada cual con solo los requisitos para el entorno. Sin entornos virtuales hay que siempre ser explicito: pip2 o pip3 en vez de pip.




Francois Dion
@f_dion

Thursday, December 31, 2015

And thus ends 2015...

Yet it is also just the beginning

This is not going a long review of the year. Perhaps in January I'll do that. But I did want to point out that it was a good year for python. Earlier this month I looked at the TIOBE ratings for Python, R and Scala, the main languages I use on a regular basis (and in decreasing order of use by me - I might do java, C++ or javascript on occasion, but not on a regular basis anymore):

And that was a peak for Python at #4. Back in 2007, you might remember, TIOBE had named Python "Language of the year". And if we do a quick check on google trends of a good indicator of the popularity worldwide ("learn python"), we see that this is when it started to pick up some steam. For some fun, I'm comparing to "learn java" (ranked #1 on latest TIOBE rating):

Hey wait, what is going on in November / December 2015? :P

Let's zoom in and take a closer look at 2015:


It appears it might be overtaking Java there... It is quite early to really see if this is just a fluke, only the next few months will reveal this.

That credit card sized computer thingy

What is also worth mentioning is that the level of interest in learning Python and the Raspberry Pi seem to follow a similar path, but that will be for a follow up post. See you next year!

Francois Dion
@f_dion

Wednesday, December 30, 2015

The Star Wars star ships

How fast are they?

Added full size version, just click on the above
I posted the above on linkedin earlier this month. I hinted at the code in the header picture, but no code. Ok, so let's get into some code here.

WARNING: Once you discover this API, you are guaranteed to wastespend a lot of time with it. It's not too late to turn around, you've been warned!

REST API

The main thing I want to point out tonight, is how easy it is to interact with web services in python. In this case, the Star Wars API (swapi). First, import the usual suspects for visualization and analytics, and add some json handling:

In [1]:
%matplotlib inline
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
In [2]:
import requests
import json
from pandas.io.json import json_normalize


Ok, what next? Let's first check the swapi api:

In [4]:
r = requests.get('http://swapi.co/api/')
urls = r.json()
urls
Out[4]:
{'films': 'http://swapi.co/api/films/',
 'people': 'http://swapi.co/api/people/',
 'planets': 'http://swapi.co/api/planets/',
 'species': 'http://swapi.co/api/species/',
 'starships': 'http://swapi.co/api/starships/',
 'vehicles': 'http://swapi.co/api/vehicles/'}
 

Each service will spit back out only part of the data, so we need to follow the link to the next page. Let's write up a function, something quick as a helper. It is not the most efficient, but it is the most readable way of doing this, and for a blog that's important.
In [5]:
def get_swapi(url):
    r = requests.get(url)
    data = r.json()
    df = json_normalize(data['results'])
    while len(df.index) < data['count']:
        r = requests.get(data['next'])
        data = r.json()
        df = pd.concat([df,json_normalize(data['results'])])
    return df

Chewie, we're home

And now to use it:

In [6]:
df = get_swapi(urls['starships'])
Finally, let's clean up the data to correct the 1000km into 1000, remove the unknowns etc, then we can display the full table.

In [7]:
df['max_atmosphering_speed'][df['max_atmosphering_speed']=='1000km'] = 1000
df = df[~(df['hyperdrive_rating']=='unknown')]
df = df[~(df['max_atmosphering_speed'].isin(['unknown','n/a']))]
In [8]:
df['max_atmosphering_speed'] = df['max_atmosphering_speed'].astype(int)
In [9]:
df['hyperdrive_rating'] = df['hyperdrive_rating'].astype(float)
df.sort_values(by='hyperdrive_rating', inplace=True)
df
Out[9]:

MGLT cargo_capacity consumables cost_in_credits created crew edited films hyperdrive_rating length manufacturer max_atmosphering_speed model name passengers pilots starship_class url
2 75 100000 2 months 100000 2014-12-10T16:59:45.094000Z 4 2014-12-22T17:35:44.464156Z [http://swapi.co/api/films/7/, http://swapi.co... 0.5 34.37 Corellian Engineering Corporation 1050 YT-1300 light freighter Millennium Falcon 6 [http://swapi.co/api/people/13/, http://swapi.... Light freighter http://swapi.co/api/starships/10/
0 unknown unknown unknown unknown 2014-12-20T19:55:15.396000Z 3 2014-12-22T17:35:45.258859Z [http://swapi.co/api/films/6/] 0.5 29.2 Theed Palace Space Vessel Engineering Corps/Nu... 1050 J-type star skiff Naboo star skiff 3 [http://swapi.co/api/people/10/, http://swapi.... yacht http://swapi.co/api/starships/64/
7 unknown unknown 1 year 2000000 2014-12-20T11:05:51.237000Z 5 2014-12-22T17:35:45.124386Z [http://swapi.co/api/films/5/] 0.7 39 Theed Palace Space Vessel Engineering Corps, N... 2000 J-type diplomatic barge J-type diplomatic barge 10 [] Diplomatic barge http://swapi.co/api/starships/43/
0 unknown unknown unknown unknown 2014-12-20T17:46:46.847000Z 4 2014-12-22T17:35:45.158969Z [http://swapi.co/api/films/5/] 0.9 47.9 Theed Palace Space Vessel Engineering Corps 8000 H-type Nubian yacht H-type Nubian yacht unknown [http://swapi.co/api/people/35/] yacht http://swapi.co/api/starships/49/
2 100 110 5 days 155000 2014-12-20T20:03:48.603000Z 3 2014-12-22T17:35:45.287214Z [http://swapi.co/api/films/6/] 1.0 14.5 Incom Corporation, Subpro Corporation 1000 Aggressive Reconnaissance-170 starfighte arc-170 0 [] starfighter http://swapi.co/api/starships/66/
1 unknown 60 2 days 320000 2014-12-20T19:56:57.468000Z 1 2014-12-22T17:35:45.272349Z [http://swapi.co/api/films/6/] 1.0 5.47 Kuat Systems Engineering 1500 Eta-2 Actis-class light interceptor Jedi Interceptor 0 [http://swapi.co/api/people/10/, http://swapi.... starfighter http://swapi.co/api/starships/65/
9 unknown 20000000 2 years 59000000 2014-12-20T19:52:56.232000Z 7400 2014-12-22T17:35:45.224540Z [http://swapi.co/api/films/6/] 1.0 1137 Kuat Drive Yards, Allanteen Six shipyards 975 Senator-class Star Destroyer Republic attack cruiser 2000 [] star destroyer http://swapi.co/api/starships/63/
3 unknown 50000 56 days 1000000 2014-12-20T19:48:40.409000Z 5 2014-12-22T17:35:45.208584Z [http://swapi.co/api/films/6/] 1.0 18.5 Cygnus Spaceworks 2000 Theta-class T-2c shuttle Theta-class T-2c shuttle 16 [] transport http://swapi.co/api/starships/61/
9 unknown 60 7 days 180000 2014-12-20T17:35:23.906000Z 1 2014-12-22T17:35:45.147746Z [http://swapi.co/api/films/5/, http://swapi.co... 1.0 8 Kuat Systems Engineering 1150 Delta-7 Aethersprite-class interceptor Jedi starfighter 0 [http://swapi.co/api/people/10/, http://swapi.... Starfighter http://swapi.co/api/starships/48/
5 unknown 60 15 hours 102500 2014-12-20T20:43:04.349000Z 1 2014-12-22T17:35:45.396711Z [http://swapi.co/api/films/6/] 1.0 7.9 Kuat Systems Engineering 1050 Alpha-3 Nimbus-class V-wing starfighter V-wing 0 [] starfighter http://swapi.co/api/starships/75/
4 unknown 65 7 days 200000 2014-12-19T17:39:17.582000Z 1 2014-12-22T17:35:45.079452Z [http://swapi.co/api/films/5/, http://swapi.co... 1.0 11 Theed Palace Space Vessel Engineering Corps 1100 N-1 starfighter Naboo fighter 0 [http://swapi.co/api/people/11/, http://swapi.... Starfighter http://swapi.co/api/starships/39/
0 70 180000 1 month 240000 2014-12-10T15:48:00.586000Z 5 2014-12-22T17:35:44.431407Z [http://swapi.co/api/films/1/] 1.0 38 Sienar Fleet Systems, Cyngus Spaceworks 1000 Sentinel-class landing craft Sentinel-class landing craft 75 [] landing craft http://swapi.co/api/starships/5/
3 80 110 1 week 134999 2014-12-12T11:00:39.817000Z 2 2014-12-22T17:35:44.479706Z [http://swapi.co/api/films/3/, http://swapi.co... 1.0 14 Koensayr Manufacturing 1000 BTL Y-wing Y-wing 0 [] assault starfighter http://swapi.co/api/starships/11/
1 120 40 1 week 175000 2014-12-18T11:16:34.542000Z 1 2014-12-22T17:35:44.978754Z [http://swapi.co/api/films/3/] 1.0 9.6 Alliance Underground Engineering, Incom Corpor... 1300 RZ-1 A-wing Interceptor A-wing 0 [http://swapi.co/api/people/29/] Starfighter http://swapi.co/api/starships/28/
4 100 110 1 week 149999 2014-12-12T11:19:05.340000Z 1 2014-12-22T17:35:44.491233Z [http://swapi.co/api/films/3/, http://swapi.co... 1.0 12.5 Incom Corporation 1050 T-65 X-wing X-wing 0 [http://swapi.co/api/people/1/, http://swapi.c... Starfighter http://swapi.co/api/starships/12/
5 105 150 5 days unknown 2014-12-12T11:21:32.991000Z 1 2014-12-22T17:35:44.549047Z [http://swapi.co/api/films/1/] 1.0 9.2 Sienar Fleet Systems 1200 Twin Ion Engine Advanced x1 TIE Advanced x1 0 [http://swapi.co/api/people/4/] Starfighter http://swapi.co/api/starships/13/
8 50 80000 2 months 240000 2014-12-15T13:04:47.235000Z 6 2014-12-22T17:35:44.795405Z [http://swapi.co/api/films/3/, http://swapi.co... 1.0 20 Sienar Fleet Systems 850 Lambda-class T-4a shuttle Imperial shuttle 20 [http://swapi.co/api/people/1/, http://swapi.c... Armed government transport http://swapi.co/api/starships/22/
6 unknown 2500000 30 days 55000000 2014-12-20T09:39:56.116000Z 1 2014-12-22T17:35:45.105522Z [http://swapi.co/api/films/4/] 1.5 26.5 Republic Sienar Systems 1180 Star Courier Scimitar 6 [http://swapi.co/api/people/44/] Space Transport http://swapi.co/api/starships/41/
2 unknown 50000000 4 years 125000000 2014-12-20T19:40:21.902000Z 600 2014-12-22T17:35:45.195165Z [http://swapi.co/api/films/6/] 1.5 1088 Rendili StarDrive, Free Dac Volunteers Enginee... 1050 Providence-class carrier/destroyer Trade Federation cruiser 48247 [http://swapi.co/api/people/10/, http://swapi.... capital ship http://swapi.co/api/starships/59/
8 unknown 240 7 days 35700 2014-12-20T18:37:56.969000Z 3 2014-12-22T17:35:45.183075Z [http://swapi.co/api/films/5/] 1.5 15.2 Huppla Pasa Tisc Shipwrights Collective 1600 Punworcca 116-class interstellar sloop Solar Sailer 11 [] yacht http://swapi.co/api/starships/58/
5 unknown unknown unknown unknown 2014-12-19T17:45:03.506000Z 8 2014-12-22T17:35:45.091925Z [http://swapi.co/api/films/4/] 1.8 76 Theed Palace Space Vessel Engineering Corps, N... 920 J-type 327 Nubian royal starship Naboo Royal Starship unknown [http://swapi.co/api/people/39/] yacht http://swapi.co/api/starships/40/
6 60 3000000 1 year 3500000 2014-12-10T14:20:33.369000Z 165 2014-12-22T17:35:45.408368Z [http://swapi.co/api/films/6/, http://swapi.co... 2.0 150 Corellian Engineering Corporation 950 CR90 corvette CR90 corvette 600 [] corvette http://swapi.co/api/starships/2/
1 60 36000000 2 years 150000000 2014-12-10T15:08:19.848000Z 47060 2014-12-22T17:35:44.410941Z [http://swapi.co/api/films/3/, http://swapi.co... 2.0 1,600 Kuat Drive Yards 975 Imperial I-class Star Destroyer Star Destroyer 0 [] Star Destroyer http://swapi.co/api/starships/3/
9 40 6000000 2 years 8500000 2014-12-15T13:06:30.813000Z 854 2014-12-22T17:35:44.848329Z [http://swapi.co/api/films/3/, http://swapi.co... 2.0 300 Kuat Drive Yards 800 EF76 Nebulon-B escort frigate EF76 Nebulon-B escort frigate 75 [] Escort ship http://swapi.co/api/starships/23/
2 91 45 1 week 220000 2014-12-18T11:18:04.763000Z 1 2014-12-22T17:35:45.011193Z [http://swapi.co/api/films/3/] 2.0 16.9 Slayn & Korpil 950 A/SF-01 B-wing starfighter B-wing 0 [] Assault Starfighter http://swapi.co/api/starships/29/
3 unknown unknown unknown unknown 2014-12-19T17:01:31.488000Z 9 2014-12-22T17:35:45.027308Z [http://swapi.co/api/films/4/] 2.0 115 Corellian Engineering Corporation 900 Consular-class cruiser Republic Cruiser 16 [] Space cruiser http://swapi.co/api/starships/31/
7 70 70000 1 month unknown 2014-12-15T13:00:56.332000Z 1 2014-12-22T17:35:44.716273Z [http://swapi.co/api/films/5/, http://swapi.co... 3.0 21.5 Kuat Systems Engineering 1000 Firespray-31-class patrol and attack Slave 1 6 [http://swapi.co/api/people/22/] Patrol craft http://swapi.co/api/starships/21/
5 20 19000000 6 months unknown 2014-12-15T12:34:52.264000Z 6 2014-12-22T17:35:44.680838Z [http://swapi.co/api/films/3/, http://swapi.co... 4.0 90 Gallofree Yards, Inc. 650 GR-75 medium transport Rebel transport 90 [] Medium transport http://swapi.co/api/starships/17/
4 unknown 140 7 days 168000 2014-12-20T20:38:05.031000Z 1 2014-12-22T17:35:45.381900Z [http://swapi.co/api/films/6/] 6.0 6.71 Feethan Ottraw Scalable Assemblies 1100 Belbullab-22 starfighter Belbullab-22 starfighter 0 [http://swapi.co/api/people/10/, http://swapi.... starfighter http://swapi.co/api/starships/74/


That'll be it for tonight, enjoy playing around with swapi, but as the intro mentions, be warned (and it is the disclaimer I've used each time I've introduced the api into a data science class), you can spend a lot of time with this...

Francois Dion
@f_dion