Friday, March 1, 2013

JavaScript and HTML5 for Physics


Like a number of other physics educators, I’ve invested a fair amount of time and energy over the last decade creating educational software in the form of Java applets.

I love Java for several reasons. It’s a reasonably easy language to learn and use, with logical rules and few exceptions. It gives very good performance, typically within a factor of 2 of native code. And, crucially, for a long time it was installed on nearly everyone’s computers, so most students and others could run my applets immediately, without any huge downloads or configuration hassles.

Unfortunately, that last advantage is now disappearing. For one thing, more and more people are replacing their computers with mobile devices that can’t run Java. Compounding the problem, security concerns have recently prompted many people (and companies) to disable Java on their computers. Some tech pundits have gone so far as to pronounce client-side Java dead.

While it’s likely that Java can be kept on life-support for several more years, its long-term prospects appear grim. So it’s time for us Java applet programmers to abandon this obsolescent technology and find an alternative. But is there one?

Until very recently, I thought the answer was no. Sure, I was aware of the new HTML5 canvas element, which allows drawing directly to the screen via JavaScript, right inside any web page, with no plugins. But this technology has mostly been described as a replacement for Flash, not Java, and I assumed that, like Flash, it would mean sacrificing a lot of performance. I couldn’t imagine that a scripting language could ever approach Java’s speed. Indeed, in an early test of a canvas animation a few years ago, I found the performance to be so poor that computationally intensive physics simulations were unthinkable.

I then avoided thinking about the issue until this winter, when the repeated Java security alerts provided an abrupt wake-up call. Apparently knowledgable geeks all over the internet were telling the public to disable Java, insisting that nobody should ever need to use it again.

So I decided it was time to give JavaScript the HTML5 canvas another try—and I was simply stunned. At least under Chrome, I found that graphics-intensive physics simulations run about half as fast in JavaScript as they do in Java. I can absolutely live with that factor of one-half.

My specific tests were with three simulations that I’ve spent a lot of time with over the years. First I coded a basic Ising model simulation to go with the corresponding section in my Thermal Physics textbook. Then I tried a molecular dynamics simulation, similar to the computational physics project I’ve assigned many times and the applet I wrote a few years ago. Finally, encouraged by these successes, I coded a fluid dynamics simulation using the lattice-Boltzmann algorithm, which I learned with the prodding and help of a student, Cooper Remkes, as he worked on a class project in late 2011.

As the following graphs show, the choice of browser can make a big difference. Each graph shows the relative number of calculation steps per unit time, so higher is better in all cases. I ran the simulations on my new MacBook Pro with a 2.3 GHz i7 processor, and also on one of the Windows 7 desktop PCs in the student computer lab down the hall from my office, with a 2.93 GHz i3 chip. Comparing these two machines to each other wouldn’t be fair at all, and comparisons of the three different simulations wouldn’t be meaningful either, so I’ve normalized each group of results to the highest (fastest) value in the group. The browser versions were Chrome 25, Firefox 19, Safari 6, Opera 12, and Internet Explorer 9; all but the last of these are current, as far as I can tell.  (I tried I.E. 10 on a different Windows machine and found it to be only a little faster than I.E. 9, in comparison to Chrome. I couldn’t easily find a Windows PC with Safari or Opera installed.)



The Ising model benchmark tests a mix of tasks including basic arithmetic, if-else logic, accessing a large two-dimensional array, random number generation, evaluating an exponential function, and drawing to the canvas via context.fillRect. By contrast, the molecular dynamics (MD) and fluid dynamics (FD) simulations heavily emphasize plain old arithmetic. The fluid simulation, however, does more calculation between animation frames, uses much larger arrays, and uses direct pixel manipulation (context.putImageData) to ensure that graphics isn’t a bottleneck. The MD simulation seems to be limited, at least on the fastest platforms, by the targeted animation frame rate.

As you can see, the performance of Opera and I.E. on the MD and FD simulations is a major disappointment. Let’s hope the JavaScript engines in these browsers get some big speed boosts in the near future. Safari and Firefox seem to give acceptable performance in all cases, though neither measures up to Chrome on the demanding FD benchmark. Chrome is the clear all-around winner, although it’s a bit disappointing on the Ising simulation under Windows.

And how does this performance compare to Java? It’s hard to make a comparison that’s completely fair, because of differences in the languages and, especially, the available graphics APIs. But in general, I’ve found that similar simulations in Java run about twice as fast as the best of these JavaScript benchmarks.

The bottom line is that if you choose your browser carefully, JavaScript on a new computer is significantly faster than Java was on the computers we were using during its heyday (a decade ago). And of course, for simulations that don’t require quite as much computational horsepower, JavaScript and canvas can also reach the proliferating swarms of smartphones and tablets. I’m therefore a bit puzzled by the apparent shortage, at least so far, of physics educators who are creating JavaScript/canvas simulations. I’m sure this shortage won’t last much longer.

[Update: See the comments below for further details on the benchmarks, especially for the Ising model simulation.]

Wednesday, June 20, 2012

Intellectual Toughness


As the author of a widely used thermal physics textbook, I get a steady stream of email from students around the world who are using the book. By far the most common type of inquiry is requests for answers to the end-of-chapter problems. Some students ask for the answer to a particular problem; others want copies of the entire solution manual.

To most of these students, my standard response is “Ask your instructor.” However, not all of them are using the book in a traditional classroom setting. Some have moved on to advanced studies or workplace settings where for various reasons they need to go back and brush up on their undergraduate thermal physics.

Of course I’m delighted that people are using the book in such diverse ways. But I’m also dismayed that, even after earning an undergraduate degree, so many scientists and engineers still believe that answers come from textbook authors.

The whole point of science is that you can figure out answers for yourself, without relying on any authority. For physics textbook problems, that usually means you have to do some sort of calculation. And how do you know if the calculation is correct? Not by consulting a teacher or solution manual or some other authority! Mathematics has its own internal logic that tells you whether it’s correct, without reference to anything external.

But what about careless errors, which everyone makes from time to time? There are endless ways to catch them without any appeal to authority. Do the calculation a different way. Compare the answer to other known facts. Ask one of your peers to check your work.

Our educational system does a lousy job teaching these skills. In our fervent desire to “cover” as much material as possible in our courses, we don’t give students time to ponder their results and root out their own mistakes. Instead, we authoritatively mark their answers right or wrong, then hurry on to the next problem.

Nor is this situation unique to the mathematical sciences. Students of biology, economics, sociology, and history must all learn to distinguish truth from falsehood without an instructor’s help. Critically examining one’s methods, and thus developing confidence in one’s answers, is fundamental to every discipline that deals in hard facts.

It’s not enough to teach facts, or even to teach specific technical skills. We somehow need to help our graduates develop the intellectual toughness to know when they’re right, so they can become leaders in their chosen fields.

Saturday, May 26, 2012

Adopt-a-Weed Report, May 2012


It’s been a productive weed-pulling season in Ogden’s foothills.

Our most visible weed is dyer’s woad, with its upright stalks topped with a head of yellow during May. Ridding the foothills of this invasive plant may seem hopeless, but the Ogden Sierra Club has made a significant dent by “adopting” a 10-acre area above the 22nd Street trailhead and returning there to pull the dyer’s woad each spring. If I’ve counted correctly, this was our eighth year working in this area, and I’m delighted to report that we’ve made great progress. The plants do keep coming back, but they’re much thinner than before. This year it took only two hours for four of us to cover the entire area. (I went back for another half hour, a week later, to get the late bloomers.) In coming years we should be able to expand our adopted area to the north and/or south.


Most of Ogden’s trail users now seem to be aware of the dyer’s woad problem, and many will pause along a hike to pull a few plants. But to make real headway against this weed, our “adoption” method—spending a few hours working the same area each year—seems to be the key. I hope more groups will try it.

Meanwhile, two years ago I learned about myrtle spurge, a weed that’s still far less widespread than dyer’s woad but well established in a few dense infestations. One of those is at the 27th Street trailhead, and I personally adopted it two years ago. The strategy was to start pulling plants at the perimeter of the infestation and gradually work inward, containing and reducing the affected area.


Follow-up is also crucial with myrtle spurge, but it’s much easier because the plant grows more slowly than dyer’s woad. It’s taken me only about an hour each season to pull the small plants that are trying to come back in the areas that are already purged of mature plants. Now, after three seasons of work, the infestation is reduced to a single patch between the westernmost trail and a resident’s fence.

Saturday, October 8, 2011

Inside Macintosh


The web is currently flooded with eloquent tributes to Steve Jobs. I’ll chime in with a personal footnote.

In 1985, when I was a graduate student at Stanford, I bought my first Macintosh computer. Like so many others, I was stunned by its elegant graphics-based interface. Like fewer others (though quite a few at Stanford), I had to learn to program it.

The programmer’s manual, Inside Macintosh, was still a work in progress and hadn’t been officially published. But in response to the tremendous demand, Apple put out a “promotional edition” printed on cheap paper in a typewriter font, bound in a thick volume resembling a phone book. For a short time you could get a copy for only $25, and my check was in the mail as soon as I learned about the offer.

My original Mac is now long gone, but I still have that promotional edition of Inside Macintosh. Paging through it brings back a flood of memories.

Most of the manual, of course, is nuts-and-bolts technical details—what programmers would now call “API reference” material. But as you study it, a bigger picture comes into view: the exquisite care that went into the design of the Mac operating system, built from the inside out with the user in mind. The enthusiasm of the Mac development team occasionally bursts out in a word like “remarkable” or “amazing” amidst the manual’s otherwise dry prose. Even though this edition of the manual was hastily assembled and printed, someone made sure it had a full-color cover with that classic minimalist line drawing of a Mac.

The most important chapter of the manual, up at the front, is titled User Interface Guidelines. Rather than describing the operating system from a programmer’s point of view, this chapter instructs the reader on the underlying principles of Mac software, and firmly invites the reader to conform to these principles:
“The Macintosh is designed to appeal to an audience of nonprogrammers, including people who have previously feared and distrusted computers. To achieve this goal, Macintosh applications should be easy to learn and to use. To help people feel more comfortable with the applications, the applications should build on skills that people already have, not force them to learn new ones. The user should feel in control of the computer, not the other way around. This is achieved in applications that embody three qualities: responsiveness, permissiveness, and consistency.”
These words were revolutionary in 1985, and they made a lasting impression on me. Even today, most programmers need to pay more attention to them.

More generally, Apple has set an example for creative people everywhere: Don’t settle for mediocrity and mere functionality. Always strive for excellence, and be sure to incorporate the joy of the creative process into your work. Patiently refine every detail of your creation, while staying focused on its ultimate purpose.

That was the ethos that Steve Jobs brought to Apple, and to so much of the world.

Tuesday, October 4, 2011

The Probability of Zero


Good news: Ogden has had zero homicides so far in 2011 (probably).

Bad news: Journalists don’t understand statistics (still).

“Killings down in Ogden,” proclaimed the headline across the top of Sunday’s front page, with a great big zero on one side. Pending a final ruling on whether a fatal July shooting was accidental, Ogden has probably gone for nine months without a murder or automobile homicide. This isn’t just great news; it’s historic.

The article falls short, though, in discussing the possible causes of this unprecedented drop in killings. Relying entirely on statements from the police chief and the county attorney, the article mentions three possible contributing factors: a new police “Crime Reduction Unit” created four years ago; a year-old injunction against the city’s oldest street gang; and a shift over the last several years toward handling gun-related crimes in federal court.

Of course, all of these factors could very well be contributing to a long-term reduction in crime, and the lack of recent homicides could very well be part of that long-term trend. But statistically, you just can’t tell.

You see, Ogden’s homicide rate was already pretty low. According to a data table printed on page 5, Ogden hasn’t had more than four homicides in a calendar year since 2001. During the last nine years, the average number in any nine-month period was only two and a half.

With this data and a simple formula from elementary statistics, we can answer the obvious question: Given this average rate of homicides, what’s the probability of getting zero homicides in any given nine-month period? The answer is one in e2.5, where e is the famous mathematical constant 2.718 (approximately). Do the math and you find that the probability is about one in 12. (Note that e2.5 means e times e times the square root of e, or about 2.7 times 2.7 times 1.6.)

I’m assuming, though, that each homicide is an independent event. In fact, some homicides occur in related groups. If the average number of independent homicide groups during any nine-month period is only 2.0, then the probability of getting zero in such a period is one in e2, or about one in 7.

If these probabilities still seem rather low, remember that the zero didn’t have to occur this year. Now that the average homicide rate has been at this level for about a decade, we’ve had ten one-in-seven chances so far to get zero homicides during the first nine months of a year. In other words, we were over-due.

It’s understandable that the police chief and county attorney would attribute the lack of homicides to their own efforts. It’s also human nature to look for simple cause-effect relationships. But at this point, the most natural explanation for Ogden’s zero homicides in 2011 (so far) is a mere statistical fluctuation. The article doesn’t even mention this possibility, and it should.

What can’t be explained by mere statistics is the long-term trend. Homicide rates across the U.S. have steadily declined for the last two decades, and Ogden appears to be following this trend. Social scientists have proposed a host of possible reasons for the decline, including better policing and increased incarceration rates, but also including our aging population, changes in immigration, shifts in the illegal drug trade, and availability of abortions (resulting in fewer unwanted children). The even more striking decline over the very long term is probably a result of improving economic conditions, gradually changing attitudes toward killing, and/or increased acceptance of government as the enforcer of laws.

Let’s hope these long-term trends continue, but let’s not jump to conclusions based on local short-term fluctuations.

Thursday, September 22, 2011

Supernova!

Thanks to some prodding from my astronomy students, I've now seen my first supernova. Practiced finding it two nights in a row, then invited students and friends for a supernova party up in the mountains last night. Most worthwhile.

Oddly, I couldn't find a good image online that showed what it actually looks like through the eyepiece of a small telescope. (By small, I mean my 10-inch Newtonian reflector, or the 6-inch reflector that one of my students brought last night.) Most of the photos online are exposed to bring out lots of detail in the Pinwheel Galaxy, de-emphasizing the supernova itself.

So in an attempt to help others who are looking for it, I just whipped up this simulated image using Stellarium and Photoshop (click for a larger version):



The circle shows a 1.5 degree field of view, which is typical for a small reflector using a low-power eyepiece. The smudge in the center (which is actually much fainter than shown here, even from a very dark site) is the galaxy. Look for it with averted vision. The point of light closest to the center of the smudge, oriented at about two o'clock in the image, is the supernova. This is the orientation you'll see in a Newtonian reflector eyepiece at the best viewing time, soon after dark.

Other web sites, like this one, can help you point your telescope to the right part of the sky.

The supernova is already starting to fade, so hurry and look while you can!

Wednesday, July 6, 2011

The Space Shuttle: Inspiration or Distraction?


The news sites are devoting quite a bit of space to this Friday’s final launch of the Shuttle. Perhaps the best discussion I’ve seen is Dennis Overbye’s essay in the New York Times.

The Salt Lake Tribune, understandably, is covering the story from more of a local perspective, emphasizing the Utah jobs and educational opportunities that have depended on the Shuttle over the years.

One of the quotes in the Tribune, though, was over the top. A Utah State University student, whose research has been tied to the shuttle program, said the following:
“Without having a space shuttle or have something that America can send Americans up in, we don’t have anything that can inspire the next generation. I’ve been watching a lot about the Apollo program, and it was awesome that we could build that and then the space shuttle. But now, we have nothing.”
Upon reading this, I left a comment suggesting that this student become just a tad more open-minded about what he considers inspiring. And as an example, I picked NASA’s most important scientific mission: the James Webb Space Telescope (JWST).


Most Americans have never heard of the JWST, because no humans will be flying on the rocket that launches it. But it will be an immensely powerful instrument, probing the early stages of the formation of planets and galaxies, peering billions of years back in time. Anyone who can think for even ten seconds should find that far more inspiring than a publicly funded billion-dollar amusement park ride, only a couple hundred miles above earth’s surface, repeated 135 times.

Then, a few hours later, I saw something on Cosmic Variance about the JWST now being in jeopardy. I won’t try to defend the cost overruns and mismanagement, which are rightly being compared to the SSC. But if JWST gets canceled it will be a genuine tragedy for this generation and the next.

I’ll be watching to see if the Utah newspapers even cover the story.