Monday, February 18, 2013

Triangulations...

... or how I learned that eventually I'll have to stop worrying and love a compiler.

Doubly-indexed comprehensions

A nonintuitive (for me) feature of comprehensions in Python:

Python supports doubly (triply...) indexed list/generator comprehensions. Let's say we want to do something equivalent to the following:
foo = []
for iter1 in range(6):
 for iter2 in range(7):
    foo.append(bar(iter1,iter2))
but without the double loop or initialization. This can be done in just one list comprehension as follows:
foo = [bar(iter1,iter2) for iter1 in range(6) for iter2 in range(7)]
What's surprising about this to me is that, when trying to parse this, my instinct is to associate the for loops in such a way that the range(7) loop is outermost, because the whole statement (bar(iter1,iter2) for iter1 in range(6) looks to me like the body of the range(7) loop. However, the Python team decided to do it the other way: loops in a comprehension evaluate left to right outer to inner.

The reason for this, I'm sure, is so that a developer can take code written with old-style loops and refactor it into a generator expression without the added pain and suffering of reversing the order the loops are written in. A noble goal, to be sure.

Thursday, February 14, 2013

On objects

I haven't had cause to blog about it much at all, but the only course I'm taking this semester is a for-fun course on approximation theory, or more specifically splines.

The guy teaching it, Larry, is... shall we say, old-school. I don't mean that in any way negatively; just that he remembers the days of punch-cards first-hand. However, I do mean to say that his way of computer programming is very different from my own -- at least, as I am now. The computational part of the course has given me an opportunity to reflect on my own changing thoughts, intuitions and preferences when it comes to programming.

Tuesday, February 12, 2013

POTUS' head talks

SOTU:

Yay for deficit reduction! Except the sequester... That's the BAD kind of deficit reduction.

"Our government must not make promises it cannot keep; but we must keep the promises we've already made."

How does Obama plan to put real money into "smart investment in our future" without adding to the deficit?

And it's more of this "add nothing to the deficit" bullshit. FUCK. EVERYTHING.

Strong words on climate change. Bonus points for indicting Boehner for his chickening out in the face of the carbon lobby.

I spoke too soon. More gas permits? Yeah, that'll help.

I like this bridges idea. I liked it when I heard it in 2008 too.

Universal pre-k? I like it! Sounds like a way to boost education and spend lots of sweet, sweet stimulative dollars.

"Let's redesign the american high school." I agree. Let's start by trashing standardized tests.

"A path to earned citizenship... Back of the line..." So tell me again what is the incentive for an undocumented immigrant to initiate that process, if the line is as dysfunctional (and long) as it currently is?

No comment on the endorsement of stereotypical gender roles.

"The group that attacked us on 9/11 is a shadow of its former self"... but you'll still have to take your shoes off at the airport.

North Korea? Come on, Mr President, don't feed the troll.

Obama has more credibility on supporting democracy than any president in my lifetime... I mean, in Egypt, we let them get away with electing the wrong people. I'm glad that the messiness of democracy gets a nod here.

I do like how MSNBC cuts to SCOTUS when the topic of voting comes up.

"Gabby Giffords deserves a vote. The families of Newtown deserve a vote..." Is Obama talking to Mitch, or to Harry Reid?

Monday, February 11, 2013

Using counters to correctly number out-of-order theorem environments

A little trick I had to figure out today while writing up the joint paper Ralph and I want to have done soon.

For stylistic reasons, I find myself frequently wanting to state a main theorem, then state and prove a bunch of lemmas, then come back and prove the main theorem. Also, frequently, I'll want to have automatically numbered claims within that proof:

Theorem 1.1: The moon is made of green cheese.

Theorem 1.2: The moon is not made of rock.

Proof: Clear.

Lemma 1.3: The moon is organic.

Proof: Use spectroscopy.

Proof of Theorem 1.1: We have established that the moon is organic.

Claim 1.1.1: The organic material of the moon is cheese....

The problem, of course, is that \(\LaTeX\) keeps a counter of what Theorem I'm on, and if I just tell it to insert a claim where you see one in the example, it will number that claim 1.3.1 instead of 1.1.1. (I number all theorems, definitions, lemmas etc in one sequence using the counter 'thm'.)

The way to fix this is to use "counters", which is basically \(\LaTeX\)-speak for variables.

First: in the preamble to the document, put the following:

\newcounter{delayedthm}
\newcounter{restoredthm}

Next, put the following immediately after the \end{thm} of Theorem 1.1:

\setcounter{delayedthm}{\value{thm}}

and put a similar definition

\setcounter{restoredthm}{\value{thm}}

after the \end{lemma} of Lemma 1.3. Note: for reasons that aren't entirely clear to me, commands that manipulate counters, such as \value{} or \addtocounter{}{}, use the unslashed name of the counter.

Now, right before the \begin{proof} of the proof of Theorem 1.1, put

\setcounter{thm}{\value{delayedthm}}

and

\setcounter{thm}{\value{restoredthm}}

after \end{proof}. Voila! Renumbering on the fly!

Friday, February 8, 2013

Changing the viewing angle of a Matplotlib plot from command line

One annoying feature/bug of working with IPython in the notebook environment is that, when it draws a graphic for you, it freezes the image so that it's no longer possible to interact with it. What to do if, for example, you're plotting a 3d surface, and the default viewing angle doesn't display what you think of as the interesting features of the surface?

Thanks to a nice question on stackexchange, I now know how to not settle for the defaults.

Let's use a specific example: here's the graph of a function which I want to plot:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
sigmoid = lambda x,y: 1/sqrt(1 + 2*exp(20.1-27*(x**2 + y**2)))
ts = arange(0,1.001,.01)
fig = plt.figure()
ax = fig.gca(projection='3d')
(XX,YY) = meshgrid(ts,ts)
ZZ = vectorize(sigmoid)(XX,YY)
ax.plot_surface(XX,YY,ZZ,rstride = 5, cstride = 5, cmap = cm.jet)

This produces the following graphic:
Now, this isn't awful, but it's not the angle that I really want to be looking at this function from. What I'd really like is to be looking approximately down the line \(y = x \) and not be nearly so far "above" the plot.

The way to change this is to change the azim(uth) and elev(ation) attributes of the axis (the object called ax in the code above). Elevation refers to the angle between the top plane of the axis (the red stuff in the image) and the viewer's eye; in the picture above, it's about 30 degrees. (Python uses degrees instead of radians for these parameters, btw.) Azimuth refers to the direction that the viewer is facing, but be careful! In the image above, we're looking along the line \(y = - \frac{1}{\sqrt{3}} x \), which is a 120-degree rotation from the \(x\)-axis; however, if you type in ax.azim you'll get -60 out, not 120. That's because ax.azim is the angular position of the viewer, and not of their gaze.

ax.plot_surface(XX,YY,ZZ,rstride = 3, cstride = 3, cmap = cm.jet)
ax.view_init(azim = 180+40,elev = 22) 



I've adjusted the rstride and cstride parameters also, which determines how densely spaced the grid lines on the surface are. Notice how in this image, our view goes out along the line with slope \( \tan 40^\circ \), corresponding to the azimuth entered above.

On the getting of gigs

A wonderful list of questions to have ready answers for, when interviewing for faculty jobs:

AMS "On the market" blog

Sunday, February 3, 2013

Stout chili

Big Game Chili:
Dice one yellow onion and three cloves garlic, and brown with 2 lb ground beef. Drain fat, then put the meat into crock pot. Add one large (28 oz) can diced tomatoes, one regular size can of chili beans (as hot as you can stand), two anaheim peppers cut into loops, and 12 oz dark beer (such as porter or stout).
Stir in 1 tablespoon each chili powder, cayenne pepper, black pepper, and cumin powder. I also like to shake in some Tony Chacheres too.
Cook on high for 3-4 hours. Serve at Big Game Watch.

Boom, bitches

Hey Marsha Blackburn (and the rest of the right wing noise machine): do you ever get tired of playing checkers when the President's playing chess?
Blackburn:
"If he is a skeet shooter, why have we not heard of this? Why have we not seen photos? Why has he not referenced it at any point in time as we have had this gun debate that is ongoing?"
Obama:

Look, people: the POTUS is an infuriating negotiator to watch... but he's a heluvagood poker player. And this kind of story is poker, and Marsha, bless your heart but you've got a pair of threes.

Friday, February 1, 2013

Dear Huffington Post: you are part of the audience for this one

The Huffington Post apparently now runs a TEDWeekends feature, each a
curated weekend program that introduces a powerful "idea worth spreading" every Friday, anchored in an exceptional TEDTalk.
Aside from the fact that whoever did the web design forgot to create permalinks to such features, I think this is as good an idea as TED more generally (i.e. cool, if somewhat masturbatory and promotive of quick-fix-thinking).

I also like the focus of this week's: Why We Deceive Ourselves (Sometimes). Anchored by Michael Shermer, whose "Why People Believe Weird Things" should be somewhere in every high school student's reading list, with contributions by Laura Kray, Laura Cococcia, and Art Markman, it's a topic near to my heart (though as has been discussed recently, e.g. at Pharyngula, Shermer sets out a somewhat narrower bailiwick for skepticism than I do).

I surely hope the editorial board at HuffPo has a nice, slow Friday in front of them, so they can pour a cup of coffee, put their feet up on the desk, and read all about how the woo they're in the habit of pitching to the masses is bullshit.

Shorter Justin E.H. Smith

The concept of God is incoherent already, so stop ragging on me for believing in it!

My Faith: Some Clarifications (with Special Reference to Emerson) - Justin Erik Halldór Smith