Wednesday, May 18, 2011

Note about the sum of cosines formula

I was showing someone the derivation of the formulas for sums and differences of sines and cosines (my post here). Unfortunately, I have some trouble remembering these. The trick I used was to try to recall that the derivation started by analyzing the difference cos(s-t) and it's a particularly easy form:

cos(s-t) = cos s cos t + sin s sin t

Then it occurred to me that there is a fairly obvious point about this that should make it even clearer. Just remember that pattern is sine sine, cosine cosine, both terms positive.
Then suppose s = t, we have

cos2(s) + sin2(s) = 1

So, which function and for what combination of s with itself would we always get 1? Well, it's obviously the difference, which always equals zero (the sum, 2s, could be any angle). And which function always gives 1 with an argument of 0? The cosine, of course.

cos(s-t) = cos s cos t + sin s sin t

Getting to the formula for cos(s+t) just involves realizing that if we plug in u = -t we have

cos(s+u) = cos s cos(-u) + sin s sin(-u)

but

cos(-u) = cos(u)
sin(-u) = - sin(u)

So it's the sine term in the formula that changes sign when we add.

cos(s+u) = cos s cos u - sin s sin u

As for the other one, perhaps the easiest is Euler:

eis = cos s + i sin s
ei(s+t) = cos(s+t) + i sin(s+t)

ei(s+t) = eis eit
= (cos s + i sin s) (cos t + i sin t)
= cos s cos t - sin s sin t + i (sin s cos t) + i (cos s sin t)

The real part gives us what we had before,

cos(s+t) = cos s cos t - sin s sin t

and the imaginary part is equal to the imaginary part of the sum from the previous line:

i sin(s+t) = i (sin s cos t) + i (cos s sin t)
sin(s+t) = sin s cos t + cos s sin t

In fact, maybe this is enough by itself. :)

Sunday, May 15, 2011

Law of sines, and cosines



Continuing with some homework, we're going to use vector algebra to prove two geometric theorems.

[This is a similar diagram to the one from last time, but with labels switched around--sorry for any confusion].

We have vectors (a, b and c) and the lengths of the corresponding sides (|a| = a, etc.); also, the angle opposite side a is labeled A and so on.

The law of sines states that the ratio of the length of each side to the sine of the angle opposite is the same:

a/sin(A) = b/sin(B) = c/sin(C)

Recall that the area of the parallelogram formed by a and b is given by the absolute value of the cross-product:

|a X b| = a b sin(C)

And the area of the triangle is one-half that. But we must obtain the same area no matter which two vectors we use to compute the cross-product, and no matter which orientation. Thus:

|c X -a| = a c sin(B)
|-b X c| = b c sin(A)


also have the same area.

a b sin(C) = a c sin(B) = b c sin(A)

This leads directly to the law of sines. Now let's relabel the triangle slightly.


If b - a looks a little funny, just consider that

a + b - a = b

The law of cosines states that:

c2 = a2 + b2 - 2 a b cos(C)

where c = |b - a|.
We can obtain this simply by expanding the dot product:

(b - a) • (b - a) =
= b • b - b • a - a • b + a • a
= b2 + a2 - 2 a b cos(C)


But

(b - a) • (b - a) = c2

So finally:

c2 = b2 + a2 - 2 a b cos(C)

Using vectors makes it easy.

Wednesday, May 11, 2011

Ceva using vectors--special case

Some time ago we looked at Ceva's theorem (post). I'm starting on a book about Vector Calculus, and saw this question early in Chapter 1.

Using vectors, prove that the lines from each vertex of a triangle to the midpoint of the opposite side cross at a single point. The picture is as shown below:


We solve this by constructing parametric equations for the midpoint lines. The first one starts at O and travels along the vector a + (b-a)/2, which is the diagonal of the parallelogram formed by a and b. The equation is:

u[a + (b-a)/2]

where u is the parameter. Similarly, construct the line extending from A to its opposing side. It starts from A and travels along the vector b/2 - a. The equation is:

a + v(b/2 - a)

At the point where the vectors cross, these are equal:

u[a + (b-a)/2] = a + v(b/2 - a)

I had a little trouble at this point, and I must confess I peeked at the answer. We can solve this by considering that both the a and the b terms must balance. (Even though a isn't perpendicular to b, the part of b which is perpendicular to a is a constant fraction k of the whole).

This leads to:

½ k ub = ½ k vb
u = v = ⅔


ua - ½ ua = a - va
½ u + v = 1
u = v = ⅔


Given this suggested solution u = v = ⅔ , we can easily verify that

u[a + (b-a)/2]
⅔[a + (b-a)/2]
= ⅔ a + ⅓ b - ⅓ a = ⅓ (a + b)

a + v(b/2 - a)
a + ⅔(b/2 - a)
= a + ⅓ b -⅔ a = ⅓ (a + b)

Now consider the third side. The midpoint line starts from B and travels along the vector a/2 - b. The equation is:

b + w(a/2 - b)

We observe that for w = ⅔ this becomes:

b + w(a/2 - b)
b + ⅔(a/2 - b)
b + ⅓ a - ⅔ b = ⅓ (a + b)

Thus, all three lines intersect at the same point.

I haven't got an extension to the general case just yet (i.e. any point, not just the midpoint).

Friday, May 6, 2011

Flag update




AM   Armenia
BD Bangladesh
CU Cuba
DO Dominican Republic
JO Jordan
KH Cambodia
LA Laos
LB Lebanon
LV Latvia
MK Macedonia
MW Malawi
NP Nepal
SY Syria
UG Uganda
UZ Uzbekistan
VG Virgin Islands (British)


Thanks for reading!

Thursday, May 5, 2011

Wednesday, May 4, 2011

Intro to ANOVA


This is an introductory post on ANOVA (analysis of variance). We ask the question: given three (or more) groups of observations, is one or more of the group means significantly different from the others. We will compute an F-statistic, and compare that with an F-distribution (carry out an F-test). If the statistic exceeds the 95% quantile, we will reject the null hypothesis that the means are the same.

According to wikipedia:


the two-group case can be covered by a t-test (Gosset, 1908). When there are only two means to compare, the t-test and the ANOVA F-test are equivalent; the relation between ANOVA and t is given by F = t2.


ANOVA is a versatile (and complex) set of methods. This is just an elementary application, where we'll use the R implementation on three simple groups of data, and then compute the result ourselves in Python to see how it works internally.

To begin with, we follow the simple example from Dalgaard. You will need R and the ISwR package (or just construct the "data frame" yourself). R code:


> library(package=ISwR)
> data(red.cell.folate)
> summary(red.cell.folate)
folate ventilation
Min. :206.0 N2O+O2,24h:8
1st Qu.:249.5 N2O+O2,op :9
Median :274.0 O2,24h :5
Mean :283.2
3rd Qu.:305.5
Max. :392.0
> red.cell.folate
folate ventilation
1 243 N2O+O2,24h
2 251 N2O+O2,24h
3 275 N2O+O2,24h
4 291 N2O+O2,24h
5 347 N2O+O2,24h
6 354 N2O+O2,24h
7 380 N2O+O2,24h
8 392 N2O+O2,24h
9 206 N2O+O2,op
10 210 N2O+O2,op
11 226 N2O+O2,op
12 249 N2O+O2,op
13 255 N2O+O2,op
14 273 N2O+O2,op
15 285 N2O+O2,op
16 295 N2O+O2,op
17 309 N2O+O2,op
18 241 O2,24h
19 258 O2,24h
20 270 O2,24h
21 293 O2,24h
22 328 O2,24h


We have 22 values in 3 groups.


> attach(red.cell.folate)
> anova(lm(folate~ventilation))
Analysis of Variance Table

Response: folate
Df Sum Sq Mean Sq F value Pr(>F)
ventilation 2 15516 7757.9 3.7113 0.04359 *
Residuals 19 39716 2090.3
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
>


The attach gives us access to the names of the columns of values (folate) and factors (ventilation). We make a plot (shown at the top of the post):


> plot( folate ~ ventilation, data = red.cell.folate )
> stripchart(x=folate~ventilation,
pch=16,vertical=T,add=T,col='blue')


The value 0.04359 indicates that we have P < 0.05.

We write the data to disk, and remember that the groups have (respectively) 8, 9 and 5 values.


> setwd('Desktop')
> write.table(folate,'data.txt',row.names=F,col.names=F)


We use the Python script below to compute the F-statistic:


python script.py
..
MS_W 2090.32
MS_X 7757.88
F_stat 3.71


If you look in the R output above, you'll see the same values as given here for MS_W and MS_X and the F-statistic.

To get the right F-distribution, we need to know that the degrees of freedom are:


k-1 = 2  # k = number of groups
N-k = 19 # N = total observations


Since 3.71 is just higher than the 95% quantile of this F-distribution we can reject the null hypothesis H0.

I found a calculator online. You can see the results in the screenshot.



The underlying calculation is pretty simple. We compute sumsq, the sum of the squares of the differences from the mean for several sets of values and the relevant means.

For the within groups comparisons, using mathematical notation this is (i groups with j observations in each group):


    Σ         Σ     (xij - mi)2
(over i) (over j)


In Python, for each group we sumsq for the group compared with the group mean, and add the results for all three groups to give SSD_W.

To carry out the between groups comparisons, we first compute the grand mean m (of all of the samples). Then for each group we compute:


    Σ        Σ     (mi - m)2
(over i) (over j)


Since the squared value is the same within each group, this is equivalent to:


    Σ      ni (mi - m)2
(over i)


In the Python code this becomes:


len(g)*(mean(g)-m)**2


and sum these over all the groups to give SSD_X. This is a sum of squares of the group means.

Finally, we compute:


MS_W = SSD_W/(N-k)
MS_X = SSD_X/(k-1)
F_stat = MS_X/MS_W


As to why we do this, for now you will have to go read the article. The explanation in Dalgaard is particularly clear, indeed, the whole book is excellent.

There is a SciPy function to carry out ANOVA (stats.f_oneway), but I don't have SciPy installed right now at home, and this post is long enough already. That's for another day.

Python code:


fn = 'data.txt'
FH = open(fn,'r')
data = FH.read().strip().split()
FH.close()

data = [int(n) for n in data]
A = data[:8]
B = data[8:17]
C = data[17:]

#A = [243,251,275,291,347,354,380,392]
#B = [206,210,226,249,255,273,285,295,309]
#C = [241,258,270,293,328]

def mean(L):
return sum(L)*1.0/len(L)

def sumsq(L):
m = mean(L)
print 'sumsq'
rL = [(x-m)**2 for x in L]
for n,p in zip(L,rL):
print n, round(p,1)
S = sum(rL)
print 'total', round(S,1), '\n'
return S

def ANOVA(G):
# variation within groups
SSD_W = 0
for g in G:
SSD_W += sumsq(g)

# a bit awkward, just flattening the list of lists
# to get the mean and N
T = list()
for g in G:
T.extend(g)
m = mean(T)

# variation between groups (X for 'cross')
SSD_X = 0
for g in G:
SSD_X += len(g)*(mean(g)-m)**2

N = len(T) # 22
k = len(G) # 3
MS_W = SSD_W*1.0/(N-k)
MS_X = SSD_X*1.0/(k-1)
F_stat = MS_X/MS_W
return MS_W, MS_X, F_stat

MS_W, MS_X, F_stat = ANOVA([A,B,C])
print 'MS_W', round(MS_W,2)
print 'MS_X', round(MS_X,2)
print 'F_stat', round(F_stat,2)

Wednesday, April 13, 2011

Information

I just finished reading James Gleick's new book, The Information (link).

The book features Claude Shannon prominently. It's unusual, including long discussions of (among other topics): African drum language, Charles Babbage, Shannon's information, Turing, quantum computing, and Wikipedia. It's broader and not as technical as I'd hoped, but very enjoyable and highly recommended. Gleick is a talented writer (I loved his book about Richard Feynman and the biography of Newton is also excellent).

Gleick introduces the famous equation from information theory (and entropy)

H = Σpi log2pi

and quotes Shannon:

"The resulting units may be called binary digits, or more briefly, bits."


Gleick:

"As the smallest possible quantity of information, a bit represents the amount of uncertainty that exists in the flipping of a coin. The coin toss makes a choice between two possibilities of equal likelihood: in this case p1 and p2 each equal 1/2; the base 2 logarithm of 1/2 is -1; so H = 1 bit. A single character chosen randomly from an alphabet of 32 conveys more information: 5 bits, to be exact, because there are 32 possible messages and the logarithm of 32 is 5."


He goes on to describe a test Shannon performed:

".. in point of fact his test subject was his wife, Betty. He pulled a book from the shelf (it was a Raymond Chandler detective novel, Pickup on Noon Street), put his finger on a short passage at random, and asked Betty to start guessing the letter, then the next letter, then the next. The more text she saw, of course, the better her chances of guessing right. After 'A SMALL OBLONG READING LAMP ON THE' she got the next letter wrong. But once she knew it was D, she had no trouble guessing the next three letters. .. Quantifying predictability and redundancy in this way is a backward way of measuring information content."


Later in the book Gleick describes measuring complexity or information content by asking how far we can compress a message. For example, the message:

DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD

might be given as

Dx50

So it has very little information.

But this example leads to something that's counterintuitive. Namely, the least compressible message is a completely random string of the allowed characters, and by this argument such a string has the highest possible information content. In a way that makes sense, I suppose. If we happen to possess just the right one-time pad, such a message could be very informative. But I find it pretty confusing.

Saturday, April 2, 2011

Arcs of a circle

In calculus and analytical geometry it is usual to define angles in terms of radians of arc. For a unit circle with radius = 1, the total circumference is 2π, so the arc swept out by the angle θ is in the same ratio to π as the ratio of the angle's measure in degrees to 180°. We say that the angle θ in this figure is equal to the arc it sweeps out on the circumference. And we substitute measures of angles in radians for the ones in degrees:

180° = π
90° = π/2
60° = π/3
45° = π/4
30° = π/6

Now, think of the same points on the circumference of the circle as forming a triangle. If two points are on a diameter of the circle, the angle at any third point is always a right angle.

To prove: angle PRQ is a right angle.Solution:
Draw the radius OR. Notice that triangles OPR and OQR are both isosceles.
Label the respective base angles a and b.

2a + φ = π
2b + θ = π
2a + 2b + φ + θ = 2π

φ + θ = π

By subtraction (or just by considering that they comprise the angles of triangle PQR):

2a + 2b = π
a + b = π/2

In addition:
The arc swept out by angles a and b (OPR and OQR on the diameter) clearly add up to π. This suggests that:

a = 1/2 θ
b = 1/2 φ

Solution:

2a + 2b = π = 2a + φ
φ = 2b

Consider the chord PR and draw the tangent at P.The arc between the tangent and the chord equals 2b because it is the same arc as cut off by angle PQR (which is angle b).

Take a chord of the circle, draw the diameter and the tangent.
The same rule applies to both angles: one between the chord and the diameter, and the second between the chord and the tangent. The arc is twice the measure of the angle.


Generalized arc


Having established these basic facts we can do a bit more.
One is to generalize the result for all arcs. The examples so far contain the diameter in some way. Consider the arc swept out by the angle θ in this figure.We can prove that the measure of the angle θ is equal to the 1/2 the arc swept out between P and Q. For a simple proof, draw the diameter:By our previous work:

b = 1/2 t
a = 1/2 s
θ = a + b = 1/2 (s + t)



Intersecting chords.


Given two chordsTo prove:

θ = 1/2 (s + t)

θ is the average of the two arc lengths.
Solution:
Draw a triangle.


a = 1/2 s
b = 1/2 t
a + b = θ = 1/2(s + t)



Tangent and secant


Rather than having all three points on the circle, one is now outside. We have the same arc swept out by the endpoints (t), but the included angle is now smaller, and there is a new smaller arc of length s. To prove:

θ = 1/2(t - s)

Solution:
Draw the triangle. By our previous work (and supplementary angles):

φ = 1/2 s
a = 1/2 t

by supplementary angles:

θ + φ = a
θ = 1/2 t - 1/2 s
= 1/2(t - s)



Two tangents

Draw a secant line. By our previous work:

θ1 = 1/2 (t1 - s1)
θ2 = 1/2 (t2 - s2)

By addition:

θ = 1/2 (t - s)



Two secants


Draw a tangent line.By our previous work:

θ + φ = 1/2(t - s) + 1/2(v - u)
φ = 1/2(v - u)

By subtraction:

θ = 1/2(t - s)



Chord segments


Finally, there is a simple algebraic relationship between chord segments. Draw two chords of the circle and label the lengths of the segments as shown (note: s and t do not refer to arcs any more).To prove:

st = uv

Solution:Draw the two triangles.
Notice that the two angles labeled a are equal because they sweep out the same arc of the circle, and similarly for the two angles labeled b. By similar triangles:

s/u = v/t
st = uv

Friday, April 1, 2011

Ellipse, again

Michael Starbird is a professor at UT Austin and quite well-known for mathematics teaching (here, here). I've seen (parts of) a bunch of videos he made for The Teaching Company. I like the videos that I got through pretty well, but found them a bit slow-developing. You have to love his energy and enthusiasm though.

Since I was working with ellipses the other day (here), I was reminded of a demonstration he shows in one of the videos, attributed to ____. (Unfortunately, I don't have the videos now, and I've forgotten the name. He's a French mathematician from the early 19th century. If you know, please speak up in comments).

Start with a cylinder, shown in cross section in the graphic (in black).



The two blue spheres just fit inside the cylinder, but the cylinder is tall enough that the two spheres don't touch, there is some distance between them. We take a cross section of the cylinder (shown in red), and the cross-section is level, so that the two points of the cross-section at each horizontal position are at the same height (the cross-section's extreme bottom and top are at the extreme left and right). The cross-section is an ellipse.

Alternatively, start with an ellipse whose minor axis is the same length as the radius of the cylinder and wedge it tightly inside, then add the spheres so they just touch the ellipse.

We claim that the points where the spheres touch the ellipse are the foci of the ellipse.

That's pretty remarkable. Here is the proof.

In the next figure below, consider any point on the ellipse.



On the left, we see the point together with the two foci, and a line drawn from our point to one of the foci. On the right is the cross-section again (foci not shown).

We said that this left focus is the point where the ellipse touches the lower sphere. That is, the line to the focus is a tangent to the sphere. All the tangents to the sphere from this point on the ellipse form a circle. The second tangent of interest is the perpendicular dropped down the surface of the cylinder, shown in the right panel. This line is the same length as line to the focus.

This equality holds for any point on the ellipse.



Finally, this is true for both spheres. The last figure illustrates that the sum of the perpendicular tangents for any point is a constant. Thus, the points where the spheres touch the ellipse are its foci, because the sum of the distances to any point on the ellipse, which is equal to the sum of the vertical tangents, is a constant.

Simply stunning.

Pythagorean Theorem



I am a little hesitant to post about a subject (the Pythagorean theorem), which is so well-known and covered so thoroughly on the web. Bronowski calls this relationship the "the most important single theorem in the whole of mathematics." (Ascent of Man: Ch. 4, Music of the Spheres). And I find these geometric proofs really wonderful to behold.

The graphic shows a right triangle and the squares of the sides in what is sometimes called the "Bride's Chair" form.

Let's start with the end rather than the beginning, and consider the last step. Drop an altitude in the right triangle as indicated by the dotted line. The argument will demonstrate that the two shaded areas in the figure (plum and red) are equal. That is the crux of the proof.

Then, by considering the symmetry of the figure, it is easy to see that the whole area of the red square is equal to the sum of the other two squares.

Now go back one step to the middle of the proof. The insight of the mathematician (who is really unknown) was to consider two special triangles as shown in the second figure (ADE on the left and ABG on the right).



Start with ADE. We take AE as the base of the triangle. Because the vertex D is on a line extended through FG, the height of the triangle is equal to EF, and therefore its area is one-half the area of the plum-colored square in the first figure.

Now look at ABG in the right panel. The altitude we dropped crosses AD at point H (marked as a red dot), and the shaded area we want is that part of the red square to the left of the dotted line, the area of rectangle ABIH. Take AB as the base of the triangle ABG. Then its height is equal to AH, and therefore its area is one-half the area of ABHI.

The first part of the proof is to show that these two carefully chosen triangles, ADE and ABG, are congruent (equal). The reason is SAS (side-angle-side). The side part is obvious. To get the angle, notice that ABG is just ADE rotated clockwise 90 degrees. Or, let the angle GAD = θ. Then, angle EAD = 90° + θ, but angle GAB = θ + 90°, which is the same.

This first proof illustrates a point about mathematical and scientific insight---its stepwise or incremental nature. We reach the summit by finding the crucial intermediate hand- and toe-holds.

There are many, many proofs of the Pythagorean theorem (e.g. here).

My absolute favorites are the geometric ones (#3 and #9), which are so simple that they really require no words. Here is #9, redrawn:



And finally, we can do it algebraically, although it feels a bit like cheating. Using the figure above, label the sides of the right triangle as a, b and the hypotenuse h. Then the sides of the large square on the left are a + b and its area is:

(a + b)2 = a2 + 2ab + b2

while the individual pieces are:

  = 4(1/2)ab + h2

Cancel and obtain:

a2 + b2 = h2


For a second method, drop the altitude h in the right triangle below, to divide the hypotenuse c into d + e. Notice that the two smaller triangles are similar to the original large one.



By similar triangles:


c/a = a/d
cd = a2

c/b = b/e
ce = b2

a2 + b2 = cd + ce
= c(d + e) = c2

Sunday, March 27, 2011

Equation of the ellipse



Here is a simple derivation of the equation for an ellipse. It is taken from Morris Kline's book: Calculus, An intuitive and Physical Approach.

We place the two foci of an ellipse (F and F') at the coordinates (c,0) and (-c,0). Each point on the ellipse is defined by the property that the sum of the distances to F and to F' is constant, which we define as equal to 2a. Our old friend Pythagoras helps us find the distances in terms of x,y and c.


PF  = √[y2 + (x-c)2]
PF' = √[y2 + (x+c)2]

2a = PF + PF'
PF = 2a - PF'
√[y2 + (x-c)2] = 2a - √[y2 + (x+c)2]


Square both sides (and expand):


y2 + x2 - 2xc + c2 = 4a2 - 4a √[y2 + (x+c)2] + y2 + x2 + 2xc + c2


Cancel terms (x2, y2, and c2) and rearrange to isolate the remaining square root:


- 2xc = 4a2 - 4a √[y2 + (x+c)2] + 2xc
4a √[y2 + (x+c)2] = 4a2 + 4xc
a √[y2 + (x+c)2] = a2 + xc


Square both sides again and expand:


a2 (y2 + x2 + 2xc + c2) = a4 + 2a2xc + x2c2
a2y2 + a2x2 + a2c2 = a4 + x2c2
a2x2 - x2c2 + a2y2 = a4 - a2c2


Factor out a2 - c2:


x2 (a2 - c2) + a2y2 = a2(a2 - c2)


Define b2 = a2 - c2


b2x2 + a2y2 = a2b2


Divide to obtain the familiar form:


x2/a2 + y2/b2 = 1


Note that when


x = 0, y = +/- b
y = 0, x = +/- a


The squaring method allows the possibility that the simplified equation has solutions that are not valid for the original version. This turns out not to be the case, and Kline deals with this issue in the book.

Also, we might note that since

b2 = a2 - c2

if a and b are fixed, then c is determined. For the figure shown here, b = c and hence a = √2 b.

UPDATE: A virtually identical proof can be found in Wikipedia (here)---should have looked first.

Flags, detail

A quick note about the flags. There are enough now that it's hard to be sure I got them all. So.. I went to the Flag Counter site (this page, and the next). Rather than do anything fancy, I just copied the text to a file and then processed it with Python. My database of flag images is from Wikipedia, and I shortened the file names by the country code. Since I can't remember a number of them, I wrote a Python script to harvest the Flag Counter entries and match them with the country codes (from here).

I checked the directory with the flag images by eye, which is almost certainly a mistake.

Here is the list of countries from which visitors to this site have come, in alphabetical order. The script is at the end. It shows a number of typical issues you run into with this kind of processing.


AE  United Arab Emirates
AL Albania
AN Netherlands Antilles
AR Argentina
AT Austria
AU Australia
BB Barbados
BE Belgium
BG Bulgaria
BH Bahrain
BR Brazil
BY Belarus
CA Canada
CH Switzerland
CL Chile
CN China
CO Colombia
CR Costa Rica
CS Serbia
CV Cape Verde
CY Cyprus
CZ Czech Republic
DE Germany
DK Denmark
DZ Algeria
EC Ecuador
EE Estonia
EG Egypt
ES Spain
FI Finland
FR France
GH Ghana
GR Greece
HK Hong Kong
HR Croatia
HU Hungary
ID Indonesia
IE Ireland
IL Israel
IN India
IS Iceland
IT Italy
JM Jamaica
JP Japan
KR South Korea
LT Lithuania
LU Luxembourg
MA Morocco
MD Moldova
MT Malta
MU Mauritius
MX Mexico
MY Malaysia
NL Netherlands
NO Norway
NZ New Zealand
PA Panama
PE Peru
PH Philippines
PK Pakistan
PL Poland
PR Puerto Rico
PT Portugal
QA Qatar
RO Romania
RU Russia
SA Saudi Arabia
SE Sweden
SG Singapore
SI Slovenia
SK Slovakia
SV El Salvador
TH Thailand
TN Tunisia
TR Turkey
TT Trinidad and Tobago
TW Taiwan
UA Ukraine
UK United Kingdom
US United States
UY Uruguay
VE Venezuela
VN Vietnam
ZA South Africa



from utils import load_data

specials = { 'South_Korea':'Korea_(South)',
'Russia':'Russian_Federation',
'New_Zealand':'New_Zealand_(Aotearoa)',
'Serbia':'Serbia_and_Montenegro',
'Croatia':'Croatia_(Hrvatska)',
'Vietnam':'Viet_Nam' }

data = load_data('country-codes.txt')
D = dict()
for line in data.strip().split('\n'):
L = line.strip().split()
D['_'.join(L[1:])] = L[0]

cL = list()
data = load_data('scraped.txt')
for line in data.strip().split('\n'):
L = line.strip().split()
i = len(L) - 4
country = '_'.join(L[1:i])
cL.append(country)
if country in specials:
k = specials[country]
D[country] = D[k]

def f(k): return D[k]
for country in sorted(cL, key=f):
print D[country],'\t', country.replace('_',' ')

Flag update


We continue to accumulate unique visitors from new countries. Here are the flags of 16 more.

Thanks for reading!

Friday, March 18, 2011

nothing in biology makes sense except in the light of evolution

I've been reading Mike Yarus's book: Life from an RNA world (Amazon). It's a very readable account of evolution from the perspective of sequences and the RNA world. Mike's a highly intelligent guy, and that and his wit inform every page. In one chapter, he gets Rob Knight and Steve Freeland to do an evolution simulation.

we let a computer write out a random string, mutate 1 in 100 characters in each generation, and select changes only if they match Dobzhansky


In my version:
  • in each generation we pick one position
  • if it already matches Dobzhansky, continue to the next generation
  • mutate to a random choice from the set of symbols

    This isn't a very good model of evolution. It was just fun to spend a few minutes coding it.

    Here is the beginning, middle and end of one run:


    > python evolve.py 
    0 LVSTUknwIfGIRHFgHESZ M zthWtNQTk qgtoeMvjeJAzOidKWEZO ZwNjDyCvq
    100 LVSTUknwIfGIRHFgHESZ M zthetNQTk qgtoeMvjeJAzOidKWEZO ZwNjDyCvq
    200 LVSTUknwIfGIRHFgHESZ M zthetNQTk qgtoeMvjeJAzOidhWEZO ZwNjDyCvq
    300 LVSTiknwIfGIRHFgHESZ M zthetNQ k qgtoeMvjeJAzOidhWEZO ZwNjuyivq

    6100 notTing if biHlogy makes sense except iv the Oight of Zvolution
    6200 notTing if biHlogy makes sense except iv the Oight of Zvolution
    6300 nothing if biHlogy makes sense except iv the Oight of Zvolution
    6400 nothing if biHlogy makes sense except iv the Oight of Zvolution

    13800 nothing in biHlogy makes sense except in the light of evolution
    13900 nothing in biHlogy makes sense except in the light of evolution
    14000 nothing in biHlogy makes sense except in the light of evolution
    14100 nothing in biHlogy makes sense except in the light of evolution

    14167 nothing in biology makes sense except in the light of evolution
    14167 nothing in biology makes sense except in the light of evolution



    import random
    s = 'nothing in biology makes sense'
    s += ' except in the light of evolution'
    N = len(s)

    symbols = 'abcdefghijklmnopqrstuvwxyz '
    symbols += symbols.upper()
    L = [random.choice(symbols) for i in range(N)]
    print ' 0 ' + ''.join(L)

    i = 0
    while L != list(s):
    i += 1
    v = i and not i % 100
    if v: print str(i).rjust(5),
    j = random.choice(range(N))
    if L[j] == s[j]:
    if v:
    print ''.join(L)
    continue
    c = random.choice(symbols)
    if c == s[j]: L[j] = c
    if v: print ''.join(L)

    print
    print str(i).rjust(5), s
    print str(i).rjust(5), ''.join(L)
  • Mutual Information (3)


    We're working on a paper from Michael Laub's lab at MIT (Skerker et al 2009 PMID 18555780). Previous posts here and here.

    Now it's time to analyze the data. The self comparisons (a single position in the alignment, analyzed for mutual information against itself) yield info values ranging from 4.1 to 0.01.


     90 4.102
    260 4.025
    122 3.993
    209 3.976
    234 3.944
    101 3.939
    235 3.938
    152 3.935
    63 3.91
    222 3.887

    159 0.191
    250 0.138
    132 0.133
    291 0.086
    199 0.067
    242 0.052
    16 0.012
    106 0.012
    156 0.012
    158 0.012


    As you can see in the screenshot, the residue in column 16 (1-based indexing), which has a very low score, is the conserved (catalytic) histidine.



    We'll filter out the self comparisons for the plots. Here is the histogram of information values that I got. It's a bit different from the paper, but not much.



    In the next part, we'll try to match up the residues which look like they might interact (that have high mutual information) and see if that makes sense in terms of the protein structures.

    I picked a familiar HK/RR pair to do this: EnvZ and OmpR. This screenshot of part of Fig 2 shows a section of each protein.



    Searching in the alignment file (the alignments don't have titles that I recognize), I recovered a sequence that I think is probably the right one. It matches the Figure as far as I checked:


    >26250004-26250005/1-457
    KQLADDRTLLMAGVSHDLRTPLTRI
    RLATEMMSAESINKDIEECNAIIEQ
    FIDYLRTGMADLNAVLGEVIA--AE
    SGYEREIETAL-YVKMHPLSIKRAV
    ANMVVNAARY-GNGWIKVSSGTEAW
    FQVEDDGPGIAPEQRKHLFQPFVRG
    DISGTGLGLAIVQRIVDNHNGMLEL
    GTSERGGLSIRAWLPNYKILVVDDD
    MRLRALLERYLTEQGFQVRSVANAE
    QMDRLLTRESFHLMVLDLMLPGEDG
    LSICRRLRSQSPMPIIMVTAKGEEV
    DRIVGLEIGADDYIPKPFNPRELLA
    RIRAVLRR


    I put the newlines in to help me count. The alignment is 308 residues total. From Fig 2,

    EnvZ (the HK) sequence starts with:


    AGVKQLADDRTLLMAGVSHDL
    KQLADDRTLLMAGVSHDL


    The second line above is from the alignment. The sequence doesn't start at residue 1, however. By my calculation, residue 0 in the alignment (the K) is residue 15 in the protein (1-based index). So we'll adjust the indexes we obtain by adding 15 to compare with the actual protein sequence.

    OmpR (the RR) sequence starts with


    MQENYKILVVDDDMRLRALLER
    NYKILVVDDDMRLRALLER


    The second line above is from the alignment, where there's an N at position 0 in this fragment. By my calculation, that N is residue 3 of OmpR in Fig 2 (1-based index), and residue 190 of the alignment, so we subtract 187 for values >= 190.

    Going back to the plotting script, we filter the data for pairs in which one comes from the HK and one from the RR, and print the top 20. We do the math as outlined above. As a check, we grab the putative EnvZ/OmpR sequence from the alignment file and print the sequence starting at the position we've identified. Here are the results for the top 20 (in each pair the RR is printed first and the HK second).

    [Note: to keep the code simple, I ignored the situation where a column contains '-' a gap in the alignment for some of the sequences. That's what's giving us the two strange results below at position 16 and 20.]


    > python plot.py 
    14 RLRAL 42 ATEMM 0.822
    18 LLERY 42 ATEMM 0.816
    22 YLTEQ 42 ATEMM 0.769
    15 LRALL 37 TRIRL 0.730
    15 LRALL 42 ATEMM 0.694
    56 MLPGE 54 DIEEC 0.688
    14 RLRAL 54 DIEEC 0.678
    21 RYLTE 42 ATEMM 0.677
    14 RLRAL 38 RIRLA 0.668
    83 KGEEV 22 TLLMA 0.667
    22 YLTEQ 21 RTLLM 0.663
    4 YKILV 42 ATEMM 0.658
    83 KGEEV 54 DIEEC 0.657
    22 YLTEQ 18 ADDRT 0.650
    22 YLTEQ 54 DIEEC 0.646
    18 LLERY 86 --AES 0.644
    15 LRALL 54 DIEEC 0.643
    18 LLERY 38 RIRLA 0.636
    22 YLTEQ 45 MMSAE 0.633
    22 YLTEQ 86 --AES 0.631


    The two residues with highest mutual information are OmpR residue 14 and EnvZ residue 42. It looks pretty good to me.

    [ UPDATE: The heatmap looks pretty boring, so I'm going to skip it.
    But I plotted the top 20 interactions (graphic at the top of the post), the repetition indicates we're on the right track.. ]


    import sys
    from utils import load_data
    import matplotlib.pyplot as plt

    data = load_data('results.2.txt')
    data = data.strip().split('\n')
    data = [e.split() for e in data]
    data = [(int(t[0]), int(t[1]), float(t[2])) for t in data]

    def f(t): return float(t[2])
    def part1():
    L = [t for t in data if t[0] == t[1]]
    L = sorted(L,key=f,reverse=True)
    for t in L[:10]: print str(t[0]+1).rjust(3),round(t[2],3)
    print
    for t in L[-10:]: print str(t[0]+1).rjust(3),round(t[2],3)
    sys.exit()

    #part1()


    L = [t[2] for t in data if t[0] != t[1]]
    X = 1.0
    plt.hist(L,bins=X*50)
    ax = plt.axes()
    ax.set_xlim(0,X)
    plt.savefig('example.png')

    # t[0] always > t[1]
    N = 190
    data = [t for t in data if t[0] >= N and t[1] < N]

    aln = load_data('cell3925mmc4.fa')
    aln = aln.strip().split('>')[1:]
    aln = [e for e in aln if e.startswith('26250004-26250005/1-457')]
    envZ_ompR = aln[0].split('\n')[1]

    for t in sorted(data,key=f,reverse=True)[:20]:
    i = t[0]
    rr = i - 187
    j = t[1]
    hk = j + 15
    print str(rr).rjust(3), envZ_ompR[i:i+5],
    print str(hk).rjust(3), envZ_ompR[j:j+5],
    print '%3.3f' % t[2]

    Mutual information (2)

    We're working on a paper from Michael Laub's lab at MIT (Skerker et al 2009 PMID 18555780). The first post is here.

    In this part we'll load the alignment (supplementary data file S4---the annotation on the page is incorrect), and crunch the numbers. I just write the results to disk.

    We'll do the analysis in another post.

    python info.py > results.txt


    import sys
    from utils import load_data
    import info_helper as ih

    #aln = 'AASSASSTTT\nNMWWNTTKKS\nGTSNTYRSTA\nGGGGGGGGGG'
    fn = 'cell3925mmc4.fa'
    data = load_data(fn)
    data = data.strip().split('>')[1:]
    data = [e.split('\n')[1].strip() for e in data]

    def show(data):
    print 'starting:', len(data)
    for i in range(7):
    print i,
    L = [e for e in data if e.count('-') <= i]
    print len(L)
    sys.exit()
    #show(data)

    def transpose(L):
    R = range(len(L[0]))
    rL = list()
    for i in R:
    rL.append(''.join([item[i] for item in L]))
    return rL

    data = [e for e in data if e.count('-') <= 4]
    #data = data[:100]
    cols = transpose(data)
    pD = ih.make_prob_dict(cols)
    info = dict()

    for i in range(len(cols)):
    for j in range(i+1):
    info[(i,j)] = ih.get_info(i,j,cols,pD,v=False)
    for i,j in sorted(info.keys()):
    print i,j,round(info[(i,j)],3)

    Thursday, March 17, 2011

    Fun with geometry (1)



    I found a a couple of fun books of problems in geometry, algebra and probability (geometry book here).

    This is one of the problems: given the red circles with radius one-half the large black circle, and the blue circle inscribed so as to just fit inside, derive a relation between the radius of the blue circle and the others. This had me scratching my head for a few minutes before the aha moment.

    The challenge question is perhaps easier: prove that the filled-in gray area is equal to the area of one of the red circles.

    And a hint for the first problem comes from the next graphic, where I've made a copy of the blue circle and positioned it strategically:


    Tuesday, March 15, 2011

    Mutual information

    I want to talk about a really nice paper from Michael Laub's lab at MIT (Skerker et al 2009 PMID 18555780). It'll give us an opportunity to exercise our matplotlib skills.

    We're going to try to recreate Fig 1, which is visible in the PubMed page, or you can get the original paper from the link to Cell.

    Two-component signal transduction systems are ubiquitous in bacteria (wikipedia). The canonical design consists of a membrane-bound sensor (histidine) kinase (HK) and a cytoplasmic response regulator (RR). E. coli contains about 30 such pairs. The members of each pair have substantial specificity. The HK of the ntr system has specificity for its own RR, and likewise in the phoBR system, phoB has specificity for phoR. We may speak of a HK and its cognate RR.

    For our purposes the important thing is that each system comprises (in the simplest design) two protein partners with complementary surfaces. These systems (a pair of proteins) are the products of ancient gene duplication events, and have since diverged over time. Amino acids at interacting sites are constrained to co-evolve in each pair.

    If this sounds too vague or too complicated, consider an even simpler example: a stem of paired RNA residues in rRNA named H15.

    Here is the H15 sequence in 1D (the parentheses indicate residues involved in pairing---see the link above for details):


    ((((   (((((    ))))) ))))
    TGCACAATGGGCGCAAGCCTGATGCA


    And here is the inner stem drawn in 2D to show the base-pairing more directly:


    TGGGC
    GTCCG


    The base-pairing of this stem is more important to rRNA function than the identities of the bases. The result is that in some bacteria the identities of the central bases have been switched:


    original   co-evolved

    TGGGC TGCGC
    GTCCG GTGCG


    Presumably this happened in 2 discrete steps, but I don't know of any examples where the intermediate state has been preserved. Maybe we should look for some, and it's undoubtedly been studied.

    To quantify this kind of coevolution, we'll draw on a concept (and mathematical definition) called mutual information. The steps in the calculation will be:

  • make a multiple sequence alignment
  • compare column X and column Y
  • total number of sequences (length of each column) = c

  • for each residue x in column X calculate px
  • for each residue y in column Y calculate py
  • px is the probability of residue x in column X

    We'll write the columns horizontally to save space.
    Suppose column X and Y are:


    X:  AASSASSTTT
    Y: NMWWNTTKKS


    For column X we have:
    pA = 0.3 (3 A out of a total of 10 residues)
    pS = 0.4
    pT = 0.3

    For column Y:

    pK = 0.2
    pM = 0.1
    pN = 0.2
    pS = 0.1
    pT = 0.2
    pW = 0.2

    We pre-calculate these values for each column. When we calculate the information, we'll refer to the probabilities for column Y as q rather than p, to keep them straight from the p's for column X.

    Now, we consider each pair of residues, one from column X and one from column Y. This pair is made up of residues in two interacting protein surfaces or rRNA chains, that may have co-evolved.

  • pxy is the number of sequences with x in column X and y in column Y
  • divided by c, the total number of pairs:


    X:  AASSASSTTT
    Y: NMWWNTTKKS


    pAM = 0.1
    pAN = 0.2
    pST = 0.2
    pSW = 0.2
    pTK = 0.2
    pTS = 0.1

    Finally, to compute the mutual information for this pair of columns, we do this calculation for each individual pair of residues and then sum:

    pAM * log (pAM / pAqM) = 0.1 * log (0.1 / (0.3 * 0.1)) = 0.0523
    I would have used log2, but Skerker et al used log10, so I matched them.

    Here is part of the output of the script below:


    NMWWNTTKKS
    AASSASSTTT
    pKT 0.2 pK 0.2 qT 0.3 temp 3.33 final 0.1
    pMA 0.1 pM 0.1 qA 0.3 temp 3.33 final 0.05
    pNA 0.2 pN 0.2 qA 0.3 temp 3.33 final 0.1
    pST 0.1 pS 0.1 qT 0.3 temp 3.33 final 0.05
    pTS 0.2 pT 0.2 qS 0.4 temp 2.50 final 0.08
    pWS 0.2 pW 0.2 qS 0.4 temp 2.50 final 0.08
    info 0.47


    temp is the result of the calculation inside the parentheses, above. Next time we'll apply this method to the data from Skerker.


    from math import log
    def log2(n): return log(n)*1.0/log(2)
    def log10(n): return log(n)*1.0/log(10)

    # cache character probabilities for each column
    def make_prob_dict(cols):
    # input is a list of columns
    # c is the number of sequences in the alignment
    c = len(cols[0])
    pD = list()
    for col in cols:
    char_kinds = list(set(col))
    values = [col.count(k)*1.0/c for k in char_kinds]
    pD.append(dict(zip(char_kinds,values)))
    return pD

    def get_info(i,j,cols,pD,v=False):
    col1, col2 = cols[i], cols[j]
    if v: print col1 + '\n' + col2
    # as before, c is the number of sequences
    c = len(col1)
    assert c == len(col2)
    info = 0
    pairs = [col1[k] + col2[k] for k in range(c)]
    pL = sorted(list(set(pairs)))
    for p in pL:
    pXY = pairs.count(p)*1.0/c
    pX = pD[i][p[0]]
    pY = pD[j][p[1]]
    inside = (pXY * 1.0) / (pX * pY)
    if v: print 'p' + p, pXY,
    if v: print 'p' + p[0], pX,
    if v: print 'q' + p[1], pY,
    if v: print 'temp', '%3.2f' % round(inside, 2),
    outside = pXY * log10(inside)
    if v: print 'final', round(outside,2)
    info += outside
    if v: print 'info', round(info,2)
    return info

    if __name__ == '__main__':
    aln = 'AASSASSTTT\nNMWWNTTKKS\nGTSNTYRSTA\nGGGGGGGGGG'
    cols = aln.split('\n')
    pD = make_prob_dict(cols)
    info = dict()
    for i in range(len(cols)):
    for j in range(i):
    info[(i,j)] = get_info(i,j,cols,pD,v=True)
  • Sunday, March 13, 2011

    Cocoa: where to start?

    Recommended resources for beginning Cocoa with Objective-C
    NSOrderedDescending

  • do the temperature converter in the Cocoa Application Tutorial
  • short articles at Cocoa Dev (here much more here; C review)
  • Aaron Hillegass's book
  • Cocoa Fundamentals Guide (here)

    Specific to PyObjC:

  • Will Larson's tutorials (here here here here here)
  • Apple's page including a version of the temperature converter
  • Read the official introduction carefully (my biggest problem)

    A page of links to old material with simple demos of specific Cocoa features that mostly still work here.

    Code a simple game like TicTacToe, Fifteen, or Color Sudoku.

    After that, I've got tons of projects here and here. Get started with bindings (here), then move on to Vlad the Impaler (here).

    Learn specific topics by reading the Apple docs (slowly and repeatedly, it can take a while to get it, by building a simple demo project that does only that one thing. Like NSPredicate which we've done in six posts (here here here here here & one to come).

    And if you want the PyObjC templates for Xcode see here.