Sunday, March 28, 2010

Ridiculous Claims

An item last week in GenomeWeb covered a new analysis by Robin Cook-Deegan and colleagues of the Myriad BRCA patents. One bit in particular in the article has stuck in my craw & I need to spit it out.

This finding, involving an expressed sequence tag application filed by the NIH, was published in 1992 and the NIH abandoned its application two years later. Based on USPTO examiner James Martinell's estimation at the time, a full examination of all the oligonucleotide claims in the EST patent would have taken until 2035 "because of the computational time required to search for matches in over 700,000 15-mers claimed."

According to Kepler et al., this comprises "roughly half the number of molecules covered by claim 5 of Myriad's '282 patent."

While improvements in bioinformatics and computer hardware have made sequence comparisons much easier than they were in the early 1990s, the study authors arrive at no conclusions about why the USPTO granted Myriad claim 5 in patent '282 and not NIH's EST patent.


The claim by the USPTO examiner is bizarre, to say the least. The claim is 55 years to analyze 700,000 15mers for occurrence in other sequences. This works out to testing about 40 oligos per day. What algorithm were they using??

To look at it another way, if you use 2 bit encoding for each base, then the set of all 15mers can be described by 2^30 different bitstrings -- potentially storable in memory of the 32 bit machines available at the time (which can, of course, address 2^32 words of memory). Furthermore, this is a trivially splittable algorithm -- you can break the job into 2^N different jobs by having each run look only at sequences with a given bit prefix of length N. When I started as a grad student in fall 1991, one of my first projects involved a similar trivial partitioning of a large run -- each slice was its own shell script which was forked onto a machine.

Furthermore, anyone claiming that a job will take 50+ years really needs to make some reasonable assumptions about growth in compute power -- particularly since 64-bit machines were becoming available around that time (e.g. DEC Alpha). Sure, it's dangerous to extrapolate out 50 years (after all, progress in Moore's law from shrinking transistors will hit a wall at one atom per transistor), but this was a ridiculous bit of thinking.

Tuesday, March 23, 2010

What should freshman biology cover?

I've spent some time the last few weeks trying to remember what I learned in freshman biology. Partly this has been triggered by planning for my summer intern (now that I have a specific person lined up for that slot) -- not because of any perceived deficiencies but simply being reminded of the enormous breadth of the biological sciences. It's also no knock on my coursework -- I had a great freshman biology professor (who team-taught with an equally skilled instructor). It was a bit bittersweet to see his retirement announcement last year in the alumni newsletter; he certainly has earned a break but future Blue Hens will have to hope for a very able replacement.

It is my general contention that biology is very different from the other major sciences. My freshman-level physics class (which I couldn't schedule until my senior year) had a syllabus which essentially ended at the beginning of the 1900s. Again, this is no knock on the course or its wonderful professor; it's just that kinetics and electromagnetics on a macro scale was pretty much worked out by then. We had lots of supplementary material on more modern topics such as gravity assists from planets, fixing Hubble's mirror problem and quantum topics, but that was all gravy.

Similarly, my freshman chemistry course (again, quite good) covered science up to about World War II. My sophomore organic chemistry course pushed a little further in the century. It's not that these are backwards fields but quite the opposite -- enough had been learned by those time points to fill two semesters of introductory material.

But, I can't say the same about biology. In the two decades and change since my freshman biology coursework, I can certainly think of major discoveries either made or cemented in that time which deserve the attention of the earliest students. Like the course I assisted with at Harvard, my course had one semester of cells and smaller biology and one of organisms and bigger; I'll mostly focus on the cells and smaller because that's where I spend most of my time. But, there are certainly some strong candidates for inclusion in that other course. I'll also recognize the fact that perhaps for space reasons some of these topics would necessarily be pushed into the second tier courses which specialize in an area such as genetics or cell biology.

One significant problem I'll punt on: what to trim down. I don't remember much fat in my course (indeed, beyond the membrane we didn't speak much at all on it that year!). Perhaps that's what I have forgotten, but I think it more likely it was already pretty packed. I can think of some problem set items that can be jettisoned (Maxam-Gilbert sequencing is a historical curiosity at this point; I can think of much more relevant procedures to do on paper).

One topic I've convinced myself belongs in the early treatment is the proteasome, and not because I once spent a lot of time thinking about it (and also saw some financial gain -- though I no longer have such an interest in it). This is definitely a field which didn't exist on solid ground when I went through school, so it's absence from my early education First, it fits neatly into one of the key themes of introductory biology: homeostasis. Cells and organisms have mechanism for returning to a central tendency, and the proteasome plays a role for proteins. Proteasomes also form a nice bookend with ribosomes -- we learned that proteins are born but not how they die. Furthermore, not only do proteins have a lifespan, but not every protein has the same lifespan -- and lifespans are not fixed at birth. Finally, another great learning in freshman bio is around enzyme inhibitor types -- and the proteasome is the ultimate enzyme inhibitor. Plus, I'd try to mention the case of "the enemy of my enemy protein is my friend" -- proteasomes can activate one protein by destroying its inhibitor.

That's also a nice segue into another major there worth developing: regulation. I think the main message here is that any time a cell needs to process an mRNA or protein, it's an opportunity for regulation. Post-translational modifications of proteins play a key role here.

Furthermore, it's worth noting that regulation often uses chains of proteins ("pathways"). These chains offer both new opportunities for regulation and signal amplification. We spent a lot of time looking at the chains of enzymes that turn sugars into energy. Of nearly equal importance is the idea that chains of proteins (and not all of them enzymes) can control a cell. In addition, it is important to recognize that these pathways are organized into functional modules, reflecting both opportunities for control and their evolution.

Clearly in this spot the fact that we can now sequence entire genomes deserves mention. Beyond that, I think the most important fact to impress on young minds is how bewildered we still are by even the simplest genomes.

Stem cells are an important concept, and not only because they are a hot topic in the popular press and political arena. This is a key idea -- cell divisions which proceed in an asymmetric pattern.

One final clear concept for inclusion at this level is epigenetics. It is key to underline that there are means to transmit information in a heritable way which are not specifically encoded in the DNA sequence -- as important as that sequence is.

I'm sure I've missed a bunch of topics. There are a lot of ideas in the grey zone -- I haven't quite convinced myself they belong in freshman bio but certainly belong a course up. For example, the fact that organisms can borrow from other genomes (horizontal transfer) or even permanently capture entire organisms (endosymbionts) certainly belongs in cell bio or genetics, but I'm not sure it quite fits freshman year (but nor am I certain it doesn't). Lipid rafts and primary cilia and all sorts of other newly discovered (or re-discovered) subcellular structures definitely would fit in my curriculum there. Gaseous signalling molecules would definitely warrant mention, though perhaps along with the hormones in the organisms and bigger semester.

With luck, many will read this and be kind enough (and kind while doing it) to point out the big advances of the last score of years which deserve inclusion as well -- and I also have little doubt that many freshman this year are being exposed to many topics I wasn't because exist they didn't.

Thursday, March 18, 2010

Second Generation Sequencing Sample Prep Ecosystems

A characteristic of each of the existing second generation sequencing instruments is that each manufacturer provides its own collection of sample preparation reagents and kits.

Some of this variation is inherent to a particular platform. For example, the use of terminal transferase tailing is part of the supposed charm of the Helicos sample prep. Polonator needs to use a series of tag generation steps to overcome its extremely short read length. Illumina's flowcells need to be doped with specific oligos. So, some of this is natural.

On the other hand, it does complicate matters -- especially for various third parties which are producing sample preparation options. For example, targeted resequencing using hybridization really needs to have the sequencing adapters blocked with competing oligos -- and those will depend on which platform the sample has been prepared for. Epicentre has a clever technology using engineered transposases to hop amplification tags into template molecules -- but this must be adapted for each platform. Various academic protocols are developed with one platform in mind, even when there is really no striking functional reason for platform-specificity -- but a protocol developed on one really needs to be recalibrated for any other. And in any case, it would great for benchmarking instruments if precisely the same library could be fed into multiple machines -- and it would be great for researchers looking to buy sequencing capacity on the open market to be able to defer committing to a platform to the last minute.

In light of all this, it is interesting to contemplate whether this trend will continue. One semi-counter trend has been for all three major players, 454, Illumina and SOLiD, to announce smaller versions of their top instruments. Not only will these require less up-front investment, but they will apparently use all the same consumables as their big siblings -- but not as efficiently. So if you are looking at cost per base in reagents, they won't look good.

However, an even more interesting trend that might emerge is for new players to piggy-back atop the old. Ion Torrent has dropped a hint that they might pursue this direction -- while the precise sample preparation process has yet to be announced (and the ultimate stages prior to loading on the sequencer are likely to be platform-specific), Jonathon Rothberg suggested in his Marco Island talk (according to reports) that the instrument could sequence any library currently in existence. This suggests that they may be willing to encourage & support preparing libraries with other platform's kits.

Of course, for the green eyeshade folks at the companies this is a big trade-off. On the one hand, it means a new entrant can leverage all the existing preparation products and experience. Furthermore, it means a new instrument could easily enter an existing workflow. The Ion Torrent machine is particularly intriguing here as a potential QC check on a library prior to running on a big machine -- at $500 a run (proposed) it would be worth it (particularly if playing with method development) and with a very short runtime it wouldn't add much to the overall time for sequencing. PacBio may play in this space also, if libraries can be easily popped in. This also acts as a "camel's nose in the tent" strategy for gaining adoption -- first come in as a QC & backstop, later munch up the whole process.

Of course the other side of the equation for the money counters is that selling kits is potentially lucrative. Indeed, it could be so lucrative that an overt attempt to leverage other folks kits might meet with nasty (and silly) legal strategies -- such as a kit being licensed only for use with a particular platform. That would be silly -- if you are making money off every kit, why not market to all comers?

Thursday, March 11, 2010

Playing Director

Last weekend was the Academy Award presentations. Fittingly, just before I had my first theatrical success -- with Actors.

Actors are a Scala abstraction for multiprocessing. I've only really played with multiprocessing once, back in my waning days at Harvard. I tried writing some multithreaded Java code, and the results were pretty ugly. The code soon became cluttered with locks and unlocks and synchronized keywords, but my programs still locked up consistently. Multiple processes can be a real headache.

But, there's also the benefit -- especially since I have a brand new smoking fast oligoprocessor box (I keep some mystery in the precise number). Tools such as bowtie and BWA are multithreaded, but it would be useful to have some of the downstream data crunching tools enabled as well.

Actors are a high level abstraction which relies on message passing. Each Actor (or non-Actor process) communicates with other Actors by sending an object. The Actor figures out what sort of object has been thrown its way and acts on it. A given Actor will execute its tasks in the order given, but across the cast there is no guarantees; everything is asynchronous. Each Actor behaves as if it has its own thread, though in reality a pool of worker threads manages the execution of the Actors -- threads tend to be heavyweight to start up, so this scheme minimizes that overhead and thereby encourages casts of millions -- but I won't emulate de Mille for some time.

My first round of experiments left me with new bruises -- but I did come out on top. Some lessons learned are below.

First, get the screenplay nailed down as much as possible before involving the Actors. Debugging multithreaded code brings on its own headaches; don't bring down that mess of trouble before you need to. For example, in the IDE I am using (Eclipse with the Scala plug-in, which some day I will rant about) if you hit a debugging breakpoint in one thread the others keep going. In my case, that meant a println statement from my master process saying "I'm waiting for an Actor to finish" -- which kept printing and thereby prevented me from examining variables (because in Eclipse, if Console is being written to it automatically pops to center stage).

A corollary to this is after several iterations I had improved the algorithm so much it probably didn't need Actors any more! I really should time it with 0, 1 and 2 Actors (and both permutations of 1 actor -- the code runs in 3 stages and a single actor can do either the last one or the last two) -- the code is about 2/3 of the way to enabling that. Actually, one reason I went through a final bit of algorithmic rethink was the fact that the Actor enabled code was still a time pig -- the rethought version ran like a greased pig.

Second, remember the abstraction -- everything is passed as messages and these messages may be processed asynchronously. More importantly, always pretend that the messages are being passed by some degree of copying. An early version of my code ignored this and had code trying to change an object which had been thrown to an Actor. This is a serious no-no and leads to unpredictable results. You give stage commands to your Actors and then let them work!

Third, make sure you let them finish reciting their lines! My first master thread didn't bother to check if all the Actors were done -- which led to all sorts of interesting run-to-run variation in output which was mystifying (until I realized it was the synchrony problem). Checking for being done isn't trivial either. One way is to have a flag variable in your Actor which is set when it runs out of things to do. That's good -- as long as you can easily figure out how to set it. You can also look to see if an Actor is done processing messages -- except checking for an empty mailbox doesn't guarantee it is done processing that last message, only that it has picked it up. One approach that worked for my problem, since it is a simple pipelining exercise, is to have Actors throw "NOP" messages at themselves prior to doing any long process -- especially when the master thread sends them a "FLUSH" command to mark the end of the input stream. Such No OPeration messages keep the mailbox full until it gets done with the real work.

So, I have a working production. I'll be judicious in how I use this, as I have discovered the challenges (in addition to the problems I solved above, there is a way to send synchronous messages to Actors -- which I could not get to behave). But, I am already thinking of the next Actor-based addition to some of my code -- and my current treatment is pretty complicated. But, a plot snip here and a script change there and I should be ready for tryouts!

Sunday, February 28, 2010

Programming Fossil Stumble, but Scala School Progresses

If you watch this space by RSS, make sure you catch the additions and corrections by BioIT World's Kevin Davies and my fellow Codon Devices alum Jack Leonard on the Ion Torrent technology (as well as Daniel MacArthur's piece on the last day of AGBT). All were on site & actually saw the machine -- it's a bit scary to see my piece on the PARE technology tweeted (and retweeted) as a substitute for a missed session.

I'll take a break for at least a few days from AGBT & try to regain some calm -- a sequencing instrument that you can buy with a home equity loan is a dangerous temptation.

I've been having trouble carving out time -- and enthusiasm -- for my Scala retraining exercise. A week or so ago I did make one try and hit an annoying roadblock. I had previously worked through online examples to automagically convert Java iterators into a clean Scala idiom. So, I decided to try this with BioJava sequence iterators -- and had the rude surprise that these don't implement the Iterator interface! Aaarggh! The documentation is suggestive of the reason -- when BioJava sequence iterators were created, Java didn't support typesafe iterators (due to a lack of generic types). That's since been grafted onto Java, but BioJava hasn't updated to embrace this. Most likely this is to guarantee backwards compatibility -- in a sense it is a fossil record of what Java once was.

On Friday I had a big block of meeting-free time and resolved to attack things again. It's a big jump really switching over to a functional programming style (and taking the leap of faith that the scala compiler and JVM JIT will make some efficient code out of it). Scala also is very forgiving of syntax marks -- but in a very context dependent manner. Personally, I'd prefer a stricter taskmaster as being rapped on the knuckles for every infraction tends to reinforce the lesson faster.

For my problem, I chose to write a tool which would stream through a SAM format second gen sequencing alignment file and compute the number of reads covering each position. The program assumes that the SAM file is sorted by chromosome and then by position. Also, this first cut can't work on a very large file -- memory conservation was not a design constraint (though I did try to work some in).

Now, in some sense this is not a good problem to tackle -- not only will I avoid using the Picard library for processing SAM but there are already tools out there to perform the calculation. So I'm guilty of the sin of reinventing the wheel. But, it is a simple problem to formulate and has a nice trajectory forward for exploring multiprocessing and other fun topics. Plus, I'll try to couple things loosely enough that dropping in Picard should be possible without much acrobatics.

The topmost code is a bit boring, opening a file of SAM data with a class that parses it (SamStreamer) and one to count coverage (chrCoverageCollector)

object samParser extends Application
{
val filename="chr21.20k.sam"
val samFile=new SamStreamer(filename)
var lineNumber = 0
val ccc = new chrCoverageCollector();
for (read <- samFile.typicalFragmentFronts )
ccc.addCoverage(read)
ccc.dump
}

SamStreamer has four parts. The first one (fromSamLine) converts a line from SAM into an object of class AlignedPairedShortRead -- pretty dull. The second one (reads) demonstrates some key concepts. First, it looks like the definition of a value type variable (immutable), but has a function body instead of a direct assignment. Second, it goes through the lines of the file with a "for comprehension" -- which also filters out any lines starting with "@" (header lines). Finally, it ends with a yield statement -- meaning this acts like an iterator over the set. The other three parts follow the same pattern -- iterate over a collection or stream, with a yield delivering each result. Iterators naturally -- without any special declarations!

class SamStreamer(samFile: String)
{
def fromSamLine (line : String): AlignedPairedShortRead =
{
var fields : Array[String] = line.split("\t")
return new AlignedPairedShortRead(
fields(0),fields(1),fields(2),
Integer.parseInt(fields(3)),
fields(9), fields(5),fields(6), Integer.parseInt (fields(7) ))
}
val reads = for { line <- Source.fromFile(samFile).getLines
if !line.startsWith("@") } yield fromSamLine(line)
val typicalFragmentFronts
= for { read <- reads
if (read.frontOfTypicalFragment) } yield read
val mapped = for { read <- reads
if (read.mapped) } yield read
}

AlignedPairedShortRead is mostly a collection of fields and accessors for them. I could have coded this much more compactly -- I think. But that will be another lesson, as I just stumbled on it. The other bit of methods are a lot of tests for various states. For this example, "frontOfTypicalFragment" returns true if a read is the lower coordinate member for a read pair which maps within a short distance of one another on the same chromosome. Actually, for this example calling into this is a bug -- I should have a method in SamStreamer to screen for all mapped reads. Actually, a more clever way would be to pass the filtering function in to a more generic scanner function -- another exercise for a future session.

class AlignedPairedShortRead(fragName: String, flag: String, chr: String, pos: Int,
read: String, cigar: String, mateChr: String, matePos: Int)
{
def mapped : Boolean = { return chr.startsWith("chr") && !cigar.equals("*") }
def mateMapped : Boolean = { return (mateChr.equals("=") && pos!=matePos) || mateChr.startsWith("chr") }
def bothMapped : Boolean = { mapped && mateMapped }
def frontOfTypicalFragment : Boolean = { return bothMapped && mateChr.equals("=") && pos < matePos+read.length }
def id : String = { return fragName }
def bounds : (Int,Int) = { return (pos,pos+read.length)}
def Chr : String = { return chr }
}

chrCoverageCollector (gad! no consistency in my naming convention!) takes reads and assigns them to a CoverageCollector according to which chromosome they are on (addCoverage). Another method dumps the results in BED format.

class chrCoverageCollector()
{
val Coverage=new HashMap[String,CoverageCollector]
def addCoverage(read: AlignedPairedShortRead)=
{
if (!Coverage.contains(read.Chr)) Coverage(read.Chr)=new CoverageCollector
Coverage(read.Chr).increment(read)
}
def dump()
{
for( chr:String <- Coverage.keys )
{
for (pc:RangeCoverage <- Coverage(chr).MergedSet )
{
println(pc.BedGraph(chr))
}
}
}
}

CoverageCollector does most of the real work -- except for one last class it introduces (I'm starting to wish I had written this from bottom up rather than top down!), RangeCoverage. CoverageCollector keeps a stash of RangeCoverage to store the coverage at individual positions. The one, mostly impotent attempt at memory conservation is a method (thin) to consolidate runs of the same coverage level -- but only those safely outside the last region incremented (remember, the reads come in sorted order!). allElemSorted can deliver all the RangeCoverage objects in positional order and MergedSet delivers the same, but with consolidation of merged elements.

class CoverageCollector()
{
val Coverage = new HashMap[Int,RangeCoverage]
def getCoverage (st:Int,en:Int) =
{ for (pos <- st to en )
yield { if (!Coverage.contains(pos)) Coverage(pos)=new RangeCoverage(pos);
Coverage(pos) }
}
var lastThin:Int = 0
def increment(read: AlignedPairedShortRead)=
{
val(st:Int,en:Int)=read.bounds;
for (coverCnt:RangeCoverage <- getCoverage(st,en ) ) coverCnt.increment
lastThin+= 1
if (lastThin>100000) thin(st-500)
}
def thin(thinMax:Int)
{
var prev=new RangeCoverage( -10 )
for (rc:RangeCoverage <- Coverage.values.toList.filter( p=> p.St < thinMax ) )
{
if (prev.mergable(rc))
{
prev.engulf(rc)
Coverage-=rc.St
}
prev=rc
}
lastThin=0
}
def allElemSorted:Array[RangeCoverage] =
Sorting.stableSort(Coverage.values.toList)
def MergedSet : List[RangeCoverage] = {
val rcf = new RangeCoverageMerger();
return allElemSorted.toList.filter(rcf.mergeFilter ) }
}

Finally, the two last classes (okay, I claimed only one more before -- forgot about one). RangeCoverage extends the Ordered trait so it can be sorted. Traits are Scala's approach to multiple inheritance (MI). I played with MI in C++ and got my fingers singed by it; traits will require some more study as it seems to be very controversial whether they really are a good solution. I'll need to play some more before I can give anything resembling an informed opinion. RangeCoverageMerger is a little helper class to consolidate RangeCoverage objects which are adjacent and have the same coverage. I probably could have buried this in RangeCoverage with a little more cleverness, but I ran out of time & cleverness. One final language note: the "override" keyword is required whenever you override an underlying method -- though Scala lacks the requirement to declare the parent method "virtual" to enable overriding (I think I have that all right)

class RangeCoverage (st:Int) extends Ordered[RangeCoverage] {
var coverage:Int =0
var en:Int=st
override def compare(that:RangeCoverage):Int = this.st compare that.en
def increment = { coverage+= 1 }
def Coverage:Int = { return coverage }
def St:Int = { return st}
def En:Int = { return en}
def BedGraph(Chr:String):String = { return
Chr+"\t"+st.toString+"\t"+en.toString+"\t"+coverage.toString }
def mergable(next:RangeCoverage):Boolean = (en+1==next.St && coverage==next.coverage)
def engulf(next:RangeCoverage) = { en=next.en }
}
class RangeCoverageMerger
{
var prev = new RangeCoverage(-1)
def mergeFilter (rc:RangeCoverage):Boolean = {
if (prev.St== -1 || !prev.mergable(rc)) { prev=rc; return true; }
prev.engulf(rc); return false
}
}

So, if I've copied this all correctly and with the bit below, one should be able to run the whole code (if not, my profuse apologies). On my laptop, it can get through 20,000 lines of aligned SAM data (which I can't post, both due to space and because it's company data) and not explode, though 50K blows out the Java heap. A next step is to deal with this problem -- and at set the stage for multiprocessing.

Okay, one final really dull, but important bit. This actually goes at the top, as these are the import declarations. Dull, but critical -- and I always gripe about folks leaving them out.

import scala.io.Source
import scala.collection.mutable.HashMap
import scala.util.Sorting

Saturday, February 27, 2010

Last Day of Eavesdropping on Marco Island

Today was the last day of the Marco Island conference, so I won't be hammering Twitter again for quite a while. The afternoon session focused on emerging technologies.

Complete Genomics appears to have dispelled the skepticism they had been met with last year. It certainly helped that two customers presented data (Anthony Fejes' notes on CG workshop). Apparently they hinted at some additional technological improvements coming down the pike to get even more data out.

Life Technologies presented on their single molecule system, which they hope to get to early access customers by the end of the year. It's a single molecule system with many similarities to Pacific Biosciences. One interesting twist is that they can add new polymerase when the old ones die, so in theory they can keep sequencing to extremely long lengths. This could be a huge plus for the system in de novo and metagenomic settings.

One other neat PacBio tidbit, thanks to Dan Koboldt, is that the polymerase reaction rates are so uniform that fragments can be sized (and therefore structural variants detected) by the time required to go from end-to-end.

Ion Torrent presented and apparently was received well, though the amount of detail available remotely is still frustratingly thin. A lot of key questions I have don't seem to have been answered, which I'm guessing is due to limited information in their presentation (though one can't rule out blogging fatigue hitting my sources). It also isn't helping that Twitter seems to be experiencing difficulty, perhaps because of the traffic due to the natural catastrophe in Chile & curiosity about tsunamis in the Pacific.

Ion Torrent's general scheme is to trap DNA (single molecules or clusters?) in wells in a micromachined plate (much like 454, though apparently no beads) and detect the release of a proton each time a nucleotide is incorporated. Detection is via a proprietary semiconductor detector built into the bottom of each well.

It isn't clear, for example, whether each of the micromachined wells in the system is watching a single DNA molecule or some sort of cluster of molecules. If the latter, what is the amplification scheme? The run times described seem incompatible with amplification.

How much sample goes in? What preparation is needed upstream? What sort of tagging is needed? Can, for example, the Ion Torrent machine be used to resequence (or QC) libraries from the other systems? Does the sample need to be linear, or can you sequence plasmids directly (I doubt it, due to supercoiling, but it's worth asking).

Ion Torrent is making several bold assertions. One is "The Chip is the Machine", which decodes to the fact that the chips (now seen on the website) determine the key performance attributes of the system; the box (reputedly $50K) is simply interface, data collection and reagent fluidics. Another bold claim is that the chips can be fabricated in any CMOS fab in the world. Of course, that presumably leaves out the specialized microfluidic setup on top. Still, that is an impressive supplier base.

Somewhere I saw a throughput of 160Mb per 1 hr experiment for $500 in consumables. The Ion Torrent website's video hints that part of their business model will be selling different chips of different densities for different applications. One nice feature of the consumables is that they should be just standard polymerases and unlabeled nucleotides. Of course, there could easily be some magic buffer components, but one part of the cost of many of the other systems is the need for either labeled nucleotides (everybody but 454) or complicated enzyme cocktails (454). Furthermore, it is the presence of unlabeled nucleotides in the reagents that are a major contributor to loss-of-phase in clonal systems and probably to "dark bases" in single molecule systems. Simple reagents should translate to low costs, and perhaps to high reliability and long reads.

How long? That's another key attribute I haven't seen. Again, knowing whether this is a single molecule system (in which case what would kill reads?) or clonal (with the dephasing problem) would be informative. How many reads per run? For some applications, getting lots of reads is more important than long reads -- and of course for others length is really important.

Error rates or modes? I haven't seen anything beyond an apparent bulletpoint that Ion Torrent sequenced E.coli (in a single run?) to 13X coverage, 99+% of genome in assembly and 99.9+% accuracy. Supposedly homopolymeric runs can be read out, but how accurately? Is there a length beyond which things get confusing?

One more neat aspect of the Ion Torrent system: no images. Sure, the traces from each pH run (the world's smallest pH meters, according to the website) should be much more compact, but not nothing -- though it is implied that the signal is sharp enough that there is no need to store them. Hence, unlike all the other systems there's no need for beefy on-board computers and no headache of storing enormous numbers of high resolution images.

A final thought: $500 per 1 hour run is attractive, but if you really kept one instrument going quite a tab would run up. Suppose one got in 10 runs in a day (does it have any autoloading capability?) -- that's $5K/day. Even keeping that up in the approximately 200 business days in a year is $1M in chips -- something Ion Torrent and their backers are licking lips over but will have to be faced by those who get the machines. Of course, you don't have to run the system constantly (and that's hardly constantly!) -- but if I had one, I'd certainly want to!

Thursday, February 25, 2010

Personalized Annoyance of Research Enthusiast (PARE)

Last night I finally got my paws on a paper which started out on a frustrating tack. Last week, a flurry of news items heralded a new approach from Vogelstein's group at Johns Hopkins that involved second generation sequencing of patient tumor samples. But, the early reports claimed it had been published in Science Translational Medicine, whereas it most certainly wasn't there except a suggestive teaser about the next week's issue. I thought perhaps someone had really blown it and ignored an embargo, but then it turned out the AAAS meeting is going on and the work was presented there. Few things more irritating than a paper being bandied about that I can't get my eyes on! Plus, I have a manuscript due next week that this might be relevant to, so the desire to get a copy was intense!

Yesterday, it really did come out. You'll need a subscription to read it -- though that is only $50 for online access if you already have a Science personal subscription. The gist of the paper showed up in the reports. Using SOLiD, they sequenced cancer genomes around 1X coverage using 1.5Kb mate-paired libraries using 25 long reads. For copy number analysis they also used single end reads. The key point is to identify rearrangements using the mate-paired fragments.

Now, many papers have looked at rearrangements in cancer using mate paired or paired end strategies. What sets this paper apart is doing something with it: turning these into patient specific tumor markers (an approach they call PARE for personalized analysis of rearranged ends). Because rearrangements are specific to the tumor and not at all like what is in the patient's normal DNA, they make great PCR amplicons for finding the tumor. Indeed, they were able to detect tumor DNA in blood with their assays.

This is an example of second generation sequencing getting very close to the clinic. But what will it take to get it there? Many of the news items claimed the cost might be soon down around $3K. Now, to do this properly you really need to either do the sequencing on both normal and tumor DNA or make a bunch of assays and expect some to be duds. Why? Because some of these structural changes will either be alignment noise or private germline structural variants. They do use copy-number analysis to filter the list -- many tumor rearrangments will be associated with local copy number amplification. But more importantly, the cost numbers sound suspiciously like reagent-only cost, not fully-loaded. Fully loaded costs include the ~$1.5M sequencing center (SOLiD + prep gear + compute farm), real estate & salaries. These could easily double or triple that cost, though someone who actually owns a green eyeshade should figure that out for sure.

The paper talks a little bit about the risk that as a tumor evolves one of these markers might be lost. This is particularly the case here because, unlike many papers, they really aren't worried if the rearrangement is driving the tumor. It's a handy landmark, though you would find driving rearrangements with it too. But, one particular worry is that a given rearrangement might not be in the dominant clone or a clone which treatment selects for survival. So having multiple markers will be a useful protection -- though that will up costs.

But back to irritating: a key value left out of this paper (and unfortunately most such papers) is the amount of input DNA for sequencing. Many of these sorts of protocols start with 5-10 micrograms of DNA, though some mate-pair schemes call for 5 to 10 times that. For some tumor types, that's a kings's ransom -- particularly for recurrent tumors or inoperable ones. Even beyond that, large scale application of this approach will require automating the library construction process end-to-end.

It's also worth noting that this is an application where absolute speed isn't critical . For generating a marker to be used for long-term following of the tumor, needing two weeks for SOLiD library prep & assembly and another few weeks to develop the PCR assays won't be a major roadblock. But, any sequencing-based approach used to determine treatment strategy needs to turn around results in not much more than 1-2 days. That's a high hurdle, and a wide open spot for fast sequencing technologies such as 454, PacBio, nanopores & Ion Torrent.

This is also an approach where someone with a long but noisy sequencing technology should take a hard look. Calling rearrangements with very long reads shouldn't require nearly the level of accuracy as calling point mutations.

ResearchBlogging.org
Leary, R., Kinde, I., Diehl, F., Schmidt, K., Clouser, C., Duncan, C., Antipova, A., Lee, C., McKernan, K., De La Vega, F., Kinzler, K., Vogelstein, B., Diaz, L., & Velculescu, V. (2010). Development of Personalized Tumor Biomarkers Using Massively Parallel Sequencing Science Translational Medicine, 2 (20), 20-20 DOI: 10.1126/scitranslmed.3000702

Wednesday, February 24, 2010

Marco Island is HOT!

The Marco Island Advances in Genome Biology and Technology, or AGBT (or just Marco Island) conference started up today. Whatever weather they're having is better than the cold rain that soaked my commute.

A sure sign a conference is hot is that there are lots of announcements prior to the conference that could be at the conference. So, we've been treated to lots of announcements from established players (such as Illumina and ABI) and new entrants -- Pacific Biosciences has announced that they will launch their system there and has already been lining up sample prep & informatics partners and announcing their early access sites. PacBio has also started making noise about a follow-on instrument that will be for clinical apps -- launched in 2014!! Puh-leeze, that is the inconceivable future!

ABI had a new announcement today -- they're own baby SOLiD (officially the P1) to come out later this year, joining the previously announced 454 junior and Illumina IIe. The claim of "cost per sample as low as $200" is a eyebrow raiser -- I'm guessing that is for a highly multiplexed sample mix. List price at $230K and 50Gbases per run is the claim.

Ion Torrentcompany has been in a very noisy stealth mode -- founder Jonathon Rothberg gave a huge tease of a talk at the Providence meeting that ended just before giving anything specific. Of course, given that he launched 454, he gets a little slack in the hype department as he has delivered. BioIT World has a very nice writeup (which editor Kevin Davies was kind enough to point out to me about 2 weeks ago -- a sign of sloth on my part that I haven't mentioned it earlier). They didn't exactly succeed in peeling off the layers of secrecy, but it is far more detail than I've seen anywhere else (but in line with the few rumors I did hear). Rothberg will be giving the final talk at AGBT, and was expected to actually reveal some details. The general buzz is 454-style chemistry but with electronic -- not optical -- detection.

So it dropped my jaw through the floor today when Ion Torrent announced that they will be launching in April, starting with the gifting of two systems through a grant competition. I'd figured from what I heard & from the general pattern with AGBT that this year would bring the wraps off but nothing would be operating for another year or two (some previous AGBT announcees have seemingly faded to oblivion).

Of course, the devil is in the execution. Will they actually be able to deliver working systems? What will the reagent costs run? How reliable will the instruments be? And what will the performance profile look like -- run lengths, error rates & error modes and input DNA amounts & preparation.

Hold onto your seats -- and watch the #AGBT Twitter feed! Things will continue to get interesting.

Friday, February 19, 2010

To Stockholm via Ph.D. Thesis

The Scientist has a profile of Aaron Ciechanover, who shared the Nobel Prize for work on the proteasome. His Nobel-cited work began in his Ph.D. thesis.

In one of the physics books I was recently reading (I forget which one now, might have been How to Teach Physics to Your Dog, but I think it was Six Easy Pieces) it was mentioned that Louis de Broglie's committee wasn't sure what to do with his crazy proposal that everything has both particle and wave natures, but after consulting with Einstein awarded him his degree. Of course, this proposal withstood experimental test and led to a Nobel.

Anyone know other examples of Nobels which cite the laureate's thesis work?

Thursday, February 18, 2010

Non-benign genetic carrier status

Earlier this week the Wall Street Journal carried an article addressing the growing interest in finding health issues related to being a carrier of a recessive genetic disease.

Three diseases were discussed in some detail. Sickle-cell anemia is generally thought of as being very harmful when homozygous but essentially benign when heterozygous. But, it has been known for a while that heterozygotes (called sickle trait) can experience red blood cell sickling (and the accompanying pain and tissue damage) under low oxygen tension. The WSJ journal article points out that such sickling can also occur during strenuous physical exercise; the NCAA even has specific guidelines for extra rest for sickle cell heterozygotes.

An emerging story mentioned in the article is the risks of being a carrier for fragile X, an X-linked disorder which can severely impede mental development. Fragile X is a nucleotide triplet repeat expansion disease, meaning that some males who have a disease allele will have mild or no symptoms but can transmit a more severe form of the disease. Male carriers of these alleles can develop severe neurodegeneration late in life, a condition called FXTAS. Female carriers appear to be at greater risk for anxiety and depression as well as premature ovarian failure.

Other examples mentioned are a greater risk of Parkinson's in Gaucher's disease carriers (at about 5-fold greater risk than the general population) and increased risks of chronic sinus disease and asthma in cystic fibrosis carriers.

Touched on in the article is the fact that many carriers are completely unaware of the fact. Most testing is done if someone is (a) aware of the disease in the family and (b) considering having children. Even then, not everyone is tested. Many of these diseases are rare enough that many carriers could be unaware of the disease being present in the family -- if it never happened to manifest or be correctly diagnosed. Other persons may have missing knowledge about their parentage.

I don't know for certain, but I doubt many of these disease-causing mutations are in the tests used by most personal genetic profiling companies, other than the emerging ones focused on reproductive counseling. The availability in the near future of cheap whole genome sequencing in the near future could lead to huge numbers of people discovering these genetic issues. But, for most recessive diseases we do not know any possible negative effects of carrier status. Much more research will be needed to tease out additional issues.

Wednesday, February 17, 2010

Anybody know some good bioinformatic programming problems?

I recently found out that I've received a summer undergraduate intern slot. I have a soft spot for summer internships -- my own was a great experience -- and the company runs a very nice program, with specific social and learning experiences for the cadre. Anyone interested in applying should do so through the company website (and not here!). I do promise not to fill this space with "can you believe what the intern did today?!?!?", though executing "sudo rm -r /" might earn a slot!

I'm still trying to sketch out a grand scheme for the internship. But, it will certainly combine a certain amount of data analysis with a certain amount of programming. One person I've phone-screened has already asked about suggestions for programming problems to practice on. It's a great show of initiative, which I like but discovered for which I wasn't really prepared.

The challenge for me is to rewind my brain back to an early stage and remember what makes a good -- but doable -- problem. In my head, everything either seems too trivial or potentially discouragingly difficult. So, I'd be very interested in examples of programming challenges given to early programmers with a significant bioinformatics angle -- no bubble sorts or games of Wumpus!

I did find a couple of links with some examples: one from MIT and another from Duke (these links are really a level above). I'd love to find other examples -- and mostly don't care about the language used in the examples. I'm probably going to nudge my intern towards Java/Scala (leveraging BioJava as much as possible), perhaps if only to encourage me to put some more time in on my own retraining project.

So, any suggestions?

Tuesday, February 16, 2010

More Than One Way to Skin a Kumquat

My recent piece on citrus seems to have struck a chord, based on the multiple comments and the fact that GenomeWeb's blog picked up on it as well. That's all very gratifying, tbut also stirred me to notice what I had missed on the subject. No, not the obvious point that getting some genome sequences is just a tiny first step to my grand bioengineering dream. And not what the TIGS review pointed out, that American markets in particular have tended to favor uniformity over quality or novelty (though perhaps that is changing, at least in high-end markets). Nope, what bugs me now is missing the obvious about kumquats.

Now, as I mentioned, they're hard to find. I checked some mail order places and the seasons apparently vary depending on where they are grown. But at Christmas time I could find only one market -- and I checked a half dozen -- which was selling them. Even the same high end chain that sold them next to work didn't offer them at the outlet nearest my home. So, don't be embarassed if you've never tried one.

The first beauty of a kumquat is you eat the whole thing -- skin and all (it is advisable to spit the pip). But the second beauty is within that -- the two very different tastes. The skin is thin but very sweet, whereas the flesh is tart.

Natural kumquats therefore are a binary package, and an unusual one. I'm trying to think of other fruits eaten skin-on for which the skin has a distinctive and pleasant taste. I eat lots of fruit skins, but most are just texture & roughage as far as I can tell. Concord grapes are an obvious exception -- I'll confess to swiping them from my neighbor's trellis growing up. The pulp is gteen and much like a seedless green grape in taste (but decidedly NOT seedless!) whereas the skin has the delicious Concord-ness to it. Many other grapes are probably similar. Certainly the winemakers use skin-in or no skin as a point of control over taste.

Now, with all citrus the skin and pulp can have very different aromas. Orange zest adds a distinctive flavor which is different than adding orange juice to a recipe. With a bit of genetic sleuthing (GFP limes?), the promoters responsible for specific production in skin and flesh can be worked out. And then the engineering can get another dimension -- different tastes in kumquat skin and pulp.

Clearly what I have in mind is a lot of genetically engineered fruit, which I will be happy to taste. GMO foods have not met much acceptance, but as some have pointed out before a significant issue is that most engineered traits have been to benefit producers (pest / pesticide resistance) with no benefit to the consumer beyond price. Early attempts at longer shelf life tomatoes and carrots flopped, but that's still more of a benefit for the producer than the consumer. Nutritionally-augmented foods (e.g. "golden rice") address nutritional needs which Western activists don't face.

Present something really novel and exciting in terms of flavor experience, and then you'll see a real separation of those who are truly committed to a no-GMO purity and those who can be tempted away. Furthermore, simply rewiring existing citrus biosynthetic pathways would dodge some of the other arguments raised against GMOs, in terms of introducing allergens or such.

It is a bit of optimistic to think I'll ever see a line of flavor-augmented mix-and-match kumquats. But if anyone starts making some, I'll be happy to volunteer for the taste testing squad.

Friday, February 12, 2010

Celebrating Citrus


I've been on a citrus kick at work lately, trying out different varieties I picked up at one of the adjacent grocery stores (curiously, we're sandwiched between 2). When I was growing up I think I knew only seeded oranges, navel oranges, tangerines, tangelos, grapefruit, lemons and limes. Through some combination of better awareness and better availability, there's a lot more I can find. I gained some notoriety this week by bringing a pummelo to a breakfast meeting; if you haven't seen one, they make grapefruit look small. Tastewise, it's a bit milder and a bit sweeter than a grapefruit.

A lot of this is seasonal, as I've been finding. Kumquats are a nearly perfect desk snack -- completely neat except for the need to spit the pips -- but seem to be available only around the New Year -- and then only in a few stores. Amongst the treats currently available are clementines -- almost as good a desk snack as kumquats though you do need to peel them and some wonderful non-orange oranges. Cara cara oranges turn out to be delightfully pink on the inside whereas the blood oranges are precisely named -- after one knife slip I found myself searching my skin in vain for the source of the red spots on the table.

What I can find in the store is still just a tiny sample of all the citrus known to exist. My brother sent me a New Yorker article on professional flavorists which mentioned many more, including pummelos with quite foul-smelling rinds but yet another delicious flavor of pulp.

Just after the turn of the century, a very good review of citrus genetics was published in Trends in Genetics. The molecular story appears to point to all this wonderful diversity originating from three wild species. Amazing! It gets stranger when you delve into the reproductive biology of citrus -- not only can they be propagated sexually or by cuttings, but they are quite adept at apomixis, the development of a new individual from an unfertilized ovum.

There is, of course, a citrus genome project, hosted at the JGI. And perhaps more predictably, I'm a bit impatient for completion. As the rationale page explains (and from which I've stolen the wonderful image of citrus diversity above), the sweet orange genome is only 382 Mb. When the new HiSeq and SOLiD instruments come on-line, they could sequence several individuals at 40X coverage in one run.

What I'd really like is to have the genetic blueprint for all those wonderful flavors and colors in order to repackage them. Keeping in mind, of course, that some useful characteristics (such as seedlessness) aren't simple traits but products of karytype (I would love a fully seedless kumquat!). Imagine if you could have a whole series of clementine-like fruits, with the size & easy peeling characteristics but with the whole range of other citrus flavors and colors genetically grafted in -- cara cara clementines and blood clementines and ruby red clementines and perhaps even sweet lemontines and key clemenlimes. What a wonderfully healthy snacking then!

Thursday, February 04, 2010

Disagreeing to Disagree

A year ago (almost exactly) I wrote an entry taking to task a paper analyzing protein kinases in the draft chimpanzee genome. After writing that entry, I felt it proper to leave a comment at the journal (BMC Genomics). Instead of publishing the comment, the editor invited me to formalize my criticisms and perhaps give positive suggestions of how to do such an analysis. Between Codon dissolving, my interlude of consulting and starting Infinity this got pushed to late May, it went out for review & a round of revision & then the original authors were invited to write a rebuttal. By the time their rebuttal came back (late fall), I decided I was getting a bit worn on the whole thing and just tweaked my submission to underline a few things rather than go hammer-and-tongs for a counter-rebuttal.

Anyhow, my criticism and the authors' response is now up on the BMC Genomics website & indexed in Medline (hooray!). I won't go hammer-and-tongs here either. But, whereas sometimes two parties in an argument agree to disagree, having established consensus on what they are arguing about, I would characterize this with this post's title: the authors' pretty much argue that all of my points are based on misunderstandings and misinterpretations of what they wrote. I of course don't agree on that point.

In the end, one key point is that they are arguing they did the best with the dataset they chose to use as a source and I argue that they should have been more skeptical of the source. In the end, what I believe is that many of their unusual results will go away if the chimp genome is finished or if the chimp mRNAs under dispute are questioned.

So, this ends up as another project for my "Proposal to sequence genomes KR thinks deserve sequencing" grant. Ha! It would be fun to have a slush fund to pursue these sorts of things. $10K and access to chimp poly-A RNA is all this problem would need. But, I'm not independently wealthy so it will remain a pipe dream. Of course, there is a bonobo sequencing project and that would be somewhat useful. But if you go looking for such, make sure you google "Bonobo ensembl" not "Bonobo ensemble" as my smartphone helped me do -- you get some bizarre links but nothing to do with great ape sequencing.

Friday, January 29, 2010

Whither science museums?

Last week at this time I was surviving a terrible electrical storm -- tremendous cracks and crackles all around me. Luckily, it was just the lightning show at the Boston Museum of Science, featuring the world's largest Van de Graaf generator and a pair of huge Tesla coils and other sparking whatnots. TNG was part of a huge overnight group.

I love the MoS and always enjoy a trip there. But it isn't hard to go there and wonder what the future of such museums are and how the current management is taking them.

Exhibit #1: The big event at the MoS right now is the traveling Harry Potter show. We of course got tickets and lumped on audio tour. It's great fun, especially if you enjoyed the movies (it is mostly movie props & costumes), but makes absolutely no pretensions of having even a veneer of science. I've seen movie-centric exhibits at science museums before and they usually try to at least portray how movie technology works. None of that here, other than an occasional remark on the audio tour. Clearly, this is a money maker first and a big draw. But do such exhibits represent a dangerous distraction from the mission of a science museum? Would such a show be more appropriate in an art museum (it apparently was in the art museum in Chicago)?

Another exhibit could also could be described as more art than science -- but is that necessarily a bad thing. It was an exhibit of paintings by an artist who attempts to portray large numbers to make them comprehensible. The exhibit was sparse -- a small number of paintings in a large space, and they really didn't do much for me. Many had a pontillist style -- the dots summing to whatever the number was. One even aped Sunday in the Park. But were they really effective?

Art and science are overlapping domains, so please don't lump me as a philistine trying to keep art out. But I still think there are better ways to host art in a science museum. An in depth exhibit on detecting forgeries or verifying provenance would be an obvious example. The exhibit on optical illusions features a number of artworks which can be viewed in multiple ways.

We actually slept in an exhibit called "Science in the Park", which has a number of interactive exhibits illustrating basic physics concepts. It is certainly popular with the kids, but sometimes you wonder if they are actually extracting anything from it. Could such an exhibit be too fun? One example is a pair of swings of different lengths, to illustrate the properties of pendulums. A saw a lot of swinging, but rarely would a child try both. The exhibit also illustrated a serious challenge with interactive exhibits: durability. The section to illustrate angular momentum was fatally crippled by worn out bearings -- the turntable on which to spin oneself could barely allow 2 rotations. Two exhibits using trolleys looked pretty robust -- but then again some kids were slamming them along the track with all their might.

The lightning show is impressive. I think most kids got a good idea of the skin effect (allowing the operator to sit in a cage being tremendously zapped by the monster Van de Graaf). But how much did they take away? How much can we expect?

Some of the exhibits at the museum predate me by a decade or more. There are some truly ancient animal dioramas that don't seem to get much attention. Another exhibit that is quite old -- but has worn well -- is the Mathematica exhibit. There was only two obvious updatings (a computer-generated fractal mountain and an addendum to the wall of famous mathematicians). It has a few interactive items, and most were working (alas, the Moebius strip traverser was stuck).

One of the treats on Saturday morning was a movie in the Omnimax screen, a documentary on healthy and sick coral reefs in the South Pacific. It's an amazing film, and does illustrate one way to really pack a punch with photos. While the photos of dying and dead reefs are sobering, to me the most stunning photo was of a river junction in Fiji. One river's deep brown (loaded with silt eroded from upstream logging) flowed into another's deep blue. I grew up on National Geographic Cousteau specials, and could also appreciate the drama of one of the filmmakers' grim brush with the bends.

One last thought: late last fall I stumbled on a very intriguing exhibit, though it is unlikely to be the destination of any school field trip. It's the lobby of the Broad Institute, and they have a set of displays aimed at the street outside which both explain some of the high-throughput science methods being used and show data coming off the instruments in real time (some cell phone snapshots below). The Broad is just over a mile from the MoS and there's probably a really fat pipe between them -- it would be great to see these exhibits replicated where large crowds might see them and perhaps be inspired.






(01 Feb 2010 -- fixed stupid typo in title & added question mark)

Thursday, January 28, 2010

A little more Scala

I can't believe how thrilled I was to get a run-time error today! Because that was the first sign I had gotten past the Scala roadblock I mentioned in my previous post. It would have been nicer for the case to just work, but apparently my SAM file was incomplete or corrupt. But, moments later it ran correctly on a BAM file. For better or worse, I deserve nearly no credit for this step forward -- Mr. Google found me a key code example.

The problem I faced is that I have a Java class (from the Picard library for reading alignment data in SAM/BAM format). To get each record, an iterator is provided. But my first few attempts to guess the syntax just didn't work, so it was off to Google.

My first working version is

package hello
import java.io.File
import org.biojava.bio.Annotation
import org.biojava.bio.seq.Sequence
import org.biojava.bio.seq.impl.SimpleSequence
import org.biojava.bio.symbol.SymbolList
import org.biojava.bio.program.abi.ABITrace
import org.biojava.bio.seq.io.SeqIOTools
import net.sf.samtools.SAMFileReader

object HelloWorld extends Application {

val samFile=new File("C:/workspace/short-reads/aln.se.2.sorted.bam")
val inputSam=new SAMFileReader(samFile)
var counter=0

var recs=inputSam.iterator
while (recs.hasNext)
{
var samRec=recs.next;
counter=counter+1
}

println("records: ",counter);

Ah, sweet success. But, while that's a step forward it doesn't really play with anything novel that Scala lends me. The example I found this in was actually implementing something richer, which I then borrowed (same imports as before)

First, I define a class which wraps an iterator and defines a foreach method:

class IteratorWrapper[A](iter:java.util.Iterator[A])
{
def foreach(f: A => Unit): Unit = {
while(iter.hasNext){
f(iter.next)
}
}
}

Second, is the definition within the body of my object of a rule which allows iterators to be automatically converted to my wrapper object. Now, this sounds powerfully dangerous (and vice versa). A key constraint is Scala won't do this if there is any ambiguity -- if there are multiple legal solutions to what to promote to, it won't work. Finally, I rewrite the loop using the foreach construct.

object HelloWorld extends Application {
implicit def iteratorToWrapper[T](iter:java.util.Iterator[T]):IteratorWrapper[T] = new IteratorWrapper[T](iter)

val samFile=new File("C:/workspace/short-reads/aln.se.2.sorted.bam")
val inputSam=new SAMFileReader(samFile)
var counter=0

for (val samRec<-recs)
{
counter=counter+1
}
println("records: ",counter);

Is this really better? Well, I think so -- for me. The code is terse but still clear. This also saves a lot of looking up some standard wordy idioms -- for some reason I never quite locked in the standard read-lines-one-at-a-time loop in C# -- always had to copy an example.

You can take some of this a bit far in Scala -- the syntax allows a lot of flexibility and some of the examples in the O'Reilly book are almost scary. I probably once would have been inspired to write my own domain specific language within Scala, but for now I'll pass.

Am I taking a performance hit with this? Good question -- I'm sort of trusting that the Scala compiler is smart enough to treat this all as syntactic sugar, but for most of what I do performance is well behind readibility and ease of coding & maintenance. Well, until the code becomes painfully slow.

I don't have them in front of me, but I can think of examples from back at Codon where I wanted to treat something like an iterator -- especially a strongly typed one. C# does let you use for loops using anything which implements the IEnumerable interface, but it can get tedious to wrap everything up when using a library class which I think should implement IEnumerable but the designer didn't.

I still have some playing to do, but maybe soon I'll put something together that I didn't have code to do previously. That would be a serious milestone.

Wednesday, January 27, 2010

The Scala Experiment

Well, I've taken the plunge -- yet another programming language.

I've written before about this. It's also a common question on various professional bioinformatics discussion boards: what programming language.

It is a decent time to ponder some sort of shift. I've written a bit of code, but not a lot -- partly because I've been more disciplined about using libraries as much as possible (versus rolling my own) but mostly because coding is a small -- but critical -- slice of my regular workflow.

At Codon I had become quite enamored with C#. Especially with the Visual Studio Integrated Development Environment (IDE), I found it very productive and a good fit for my brain & tastes. But, as a bioinformatics language it hasn't found much favor. That means no good libraries out there, so I must build everything myself. I've knocked out basic bioinformatics libraries a number of times (read FASTA, reverse complement a sequence, translate to protein, etc), but I don't enjoy it -- and there are plenty of silly mistakes that can be easy to make but subtle enough to resist detection for an extended period. Plus, there are other things I really don't feel like writing -- like my own SAM/BAM parser. I did have one workaround for this at Codon -- I could tap into Python libraries via a package called Python.NET, but it imposed a severe performance penalty & I would have to write small (but annoying) Python glue code. The final straw is that I'm finding it essential to have a Linux (Ubuntu) installation for serious second-generation sequencing analysis (most packages do not compile cleanly -- if at all -- in my hands on a Windows box using MinGW or Cygwin).

The obvious fallback is Perl -- which is exactly how I've fallen so far. I'm very fluent with it & the appropriate libraries are out there. I've just gotten less and less fond of the language & it's many design kludges (I haven't quite gotten to my brother's opinion: Perl is just plain bad taste). I lose a lot of time with stupid errors that could have been caught at compile time with more static typing. It doesn't help I have (until recently) been using the Perl mode in Emacs as my IDE -- once you've used a really polished tool like Visual Studio you realize how primitive that is.

Other options? There's R, which I must use for certain projects (microarrays) due to the phenomenal set of libraries out there. But R just has never been an easy fit for me -- somehow I just don't grok it. I did write a little serious Python (i.e. not just glue code) at Codon & I could see myself getting into it if I had peers also working in it -- but I don't. Infinity, like many company bioinformatics groups, is pretty much a C# shop though with ecumenical attitudes towards any other language. I've also realized I need as basic comprehension of Ruby, as I'm starting to encounter useful code in that. But, as with Python I can't seem to quite push myself to switch over -- it doesn't appeal to me enough to kick the Perl habit.

While playing around with various second generation sequencing analysis tools, I stumbled across a bit of wierd code in the Broad's Genome Analysis ToolKit (GATK) -- a directory labeled "scala". Turns out, that's yet another language -- and one that has me intrigued enough to try it out.

My first bit of useful code (derived from a Hello World program that I customized having it output in canine) is below and gives away some of the intriguing features. This program goes through a set of ABI trace files that fit a specific naming convention and write out FASTA of their sequences to STDOUT:

package hello
import java.io.File
import org.biojava.bio.Annotation
import org.biojava.bio.seq.Sequence
import org.biojava.bio.seq.impl.SimpleSequence
import org.biojava.bio.symbol.SymbolList
import org.biojava.bio.program.abi.ABITrace
import org.biojava.bio.seq.io.SeqIOTools
object HelloWorld extends Application {

for (i <- 1 to 32)
{
val lz = new java.text.DecimalFormat("00")
var primerSuffix="M13F(-21)"
val fnPrefix="C:/somedir/readprefix-"
if (i>16) primerSuffix="M13R"
val fn=fnPrefix+lz.format(i)+"-"+primerSuffix+".ab1"
val traceFile=new File(fn)
val name = traceFile.getName()
val trace = new ABITrace(traceFile)
val symbols = trace.getSequence()
val seq=new SimpleSequence(symbols,name,name,Annotation.EMPTY_ANNOTATION)
SeqIOTools.writeFasta(System.out, seq);
}
}

A reader might ask "Wait a minute? What's all this java.this and biojava.that in there?". This is one of the appeals of Scala -- it compiles to Java Virtual Machine bytecode and can pretty much freely use Java libraries. Now, I mentioned this to a colleague and he pointed out there is Jython (Python to JVM compiler) which reminded me of reference to JRuby (Ruby to JVM compiler). So, perhaps I should revisit my skipping over those two languages. But in any case, in theory Scala can cleanly drive any Java library.

The example also illustrates something that I find a tad confusing. The book keeps stressing how Scala is statically typed -- but I didn't type any of my variables above! However, I could have -- so I can get the type safety I find very useful when I want it (or hold myself to it -- it will take some discipline) but can also ignore it in many cases.

Scala has a lot in it, most of which I've only read about in the O'Reilly book & haven't tried. It borrows from both the Object Oriented Programming (OOP) lore and Functional Programming (FP). OOP is pretty much old hat, as most modern languages are OO and if not (e.g. Perl) the language supports it. Some FP constructs will be very familiar to Perl programmers -- I've written a few million anonymous functions to customize sorting. Others, perhaps not so much. And, like most modern languages all sorts of things not strictly in the language are supplied by libraries -- such as a concurrency model (Actors) that shouldn't be as much of a swamp as trying to work with threads (at least when I tried to do it way back yonder under Java). Scala also has some syntactic flexibility that is both intriguing and scary -- the opportunities for obfuscating code would seem endless. Plus, you can embed XML right in your file. Clearly I'm still at the "look at all these neat gadgets" phase of learning the language.

Is it a picnic? No, clearly not. My second attempt at a useful Scala program is a bit stalled -- I haven't figured out quite how to rewrite a Java example from the Picard (Java implementation of SAMTools) library into Scala -- my tries so far have raised errors. Partly because the particular Java idiom being used was unfamiliar -- if I thought Scala was a way to avoid learning modern Java, I'm quite deluded myself. And, I did note that tonight when I had something critical to get done on my commute I reached for Perl. There's still a lot of idioms I need to relearn -- constructing & using regular expressions, parsing delimited text files, etc. Plus, it doesn't help that I'm learning a whole new development environment (Eclipse) virtually simultaneously -- though there is Eclipse support for all of the languages I looks like I might be using (Java, Scala, Perl, Python, Ruby), so that's a good general tool to have under my belt.

If I do really take this on, then the last decision is how much of my code to convert to Scala. I haven't written a lot of code -- but I haven't written none either. Some just won't be relevant anymore (one offs or cases where I backslid and wrote code that is redundant with free libraries) but some may matter. It probably won't be hard to just do a simple transformation into Scala -- but I'll probably want to go whole-hog and show off (to myself) my comprehension of some of the novel (to me) aspects of the language. That would really up the ante.

Thursday, January 21, 2010

A plethora of MRSA sequences

The Sanger Institute's paper in Science describing the sequencing of multiple MRSA (methicillin-resistant Staphylococcus aureus) genomes is very nifty and demonstrates a whole new potential market for next-generation sequencing: the tracking of infections in support of better control measures.

MRSA is a serious health issue; a friend of mine's relative is battling it right now. MRSA is commonly acquired in health care facilities. Further spread can be combated by rigorous attention to disinfection and sanitation measures. A key question is when MRSA shows up, where did it come from? How does it spread across a hospital, a city, a country or the world?

The gist of the methodology is to grow isolates overnight in the appropriate medium and extract the DNA. Each isolate is then converted into an Illumina library, with multiplex tags to identify it. The reference MRSA strain was also thrown in as a control. Using the GAII as they did, they packed 12 libraries onto one run -- over 60 isolates were sequenced for the whole study. With increasing cluster density and the new HiSeq instrument, one could imagine 2-5 fold (or perhaps greater) packing being practical; i.e. the entire study might fit on one run.

The library prep method sounds potentially automatable -- shearing on the covaris instrument, cleanup using a 96 well plate system, end repair, removal of small (<150nt) fragments with size exclusion beads, A-tailing, another 150nt filtering by beads, adapter ligation, another 150nt filtering, PCR to introduce the multiplexing tags, another filtering for <150nt, quantitation and then pooling. Sequencing was "only" 36nt single end, with an average of 80Mb, Alignment to the reference genome was by ssaha (a somewhat curious choice, but perhaps now they'd use BWA) and SNP calling with ssaha_pileup; non-mapping reads were assembled with velvet and did identify novel mobile element insertions. According to GenomeWeb, the estimated cost was about $320 per sample. That's probably just a reagents cost, but gives a ballpark figure.

Existing typing methods either look at SNPs or specific sequence repeats, and while these often work they sometimes give conflicting information and other times lack the power to resolve closely related isolates. Having high resolution is important for teasing apart the history of an outbreak -- correlating patient isolates with samples obtained from the environment (such as hospital floors & such).

Phylogenetic analysis using SNPs in the "core genome" showed a strong pattern of geographical clustering -- but with some key exceptions, suggesting intercontinental leaps of the bug.

Could such an approach become routine for infection monitoring? A fully-loaded cost might be closer to $20K per experiment or higher. With appropriate budgeting, this can be balanced against the cost of treating an expanding number of patients and providing expensive support (not to mention the human misery involved). Full genome sequencing might also not always be necessary; targeted sequencing could potentially allow packing even more samples onto each run. Targeted sequencing by PCR might also enable eliding the culturing step. Alternatively, cheaper (and faster; this is still a multi-day Illumina run) sequencers might be used. And, of course, this can easily be expanded to other infectious diseases with important public health implications. For those that are expensive or slow to grow, PCR would be particularly appropriate.

It is also worth noting that we're only about 15 years since the first bacterial genome was sequenced. Now, the thought of doing hundreds a week is not at all daunting. Resequencing a known bug is clearly bioinformatically less of a challenge, but still how far we've come!

ResearchBlogging.org

Simon R. Harris, Edward J. Feil, Matthew T. G. Holden, Michael A. Quail, Emma K. Nickerson, Narisara Chantratita, Susana Gardete, Ana Tavares, Nick Day, Jodi A. Lindsay, Jonathan D. Edgeworth, Hermínia de Lencastre, Julian Parkhill, Sharon J. Peacock, & Stephen D. Bentley (2010). Evolution of MRSA During Hospital Transmission and Intercontinental Spread Science, 327 (5964), 469-474 : 10.1126/science.1182395

Wednesday, January 20, 2010

I'm definitely not volunteering for sample collection on this project



My post yesterday was successful at narrowing down the identity of the mystery creature to a spider of the genus Araneus. Another victory for crowd sourcing! It also points out the value of questioning your assumptions & conclusions. My initial thought on looking at the photos was that the body plan looked spider-like and details of the head and abdomen sometimes pointed me that way -- but then the lack of eight legs convinced me it must be an insect (I thought I could count six in some photos).

One of the commenters addressed my mystery vine with a suggestion that underscored a key detail I inadvertantly left out. The vine raised welts on my legs when it grabbed me -- not in some exaggerated sense, but it definitely had some sort of fine projections (trichomes?) which were not what I'd call thorns, but which stuck to me (and my clothes) like velcro & left behind the small red welts.

The commenter asked if it could have been poison ivy, and I must confess a chuckle. I know that stuff! Boy do I! I've gotten that rash on most of both legs at one point, and all over my neck and arms another time. Numerous cases on my hands over time. It's definitely a very different rash -- much slower to come on, much more itchy with huge welts and very slow to disappear. My clinging plant's rash was short lived.

Poison ivy is easy to identify too. It's truly simple. First, you can start with the old saw "leaves of three, let it be". But, a lot of plants have leaves divided into three parts. Some are yummy: raspberries and strawberries. Others are pretty: columbines. And far more. Also, sometimes it's hard to count -- what else could explain the common confusion of virginia creeper (5-7 divisions) with poison ivy.

Some other key points which make identification simple:
Habitat: Woods, fields, lawns, gardens, roadsides, parking lot edges. Haven't seen it grow in standing water, but I wouldn't rule it out
Size: Tiny plantlets; vines climbing trees for 10+ meters
Habit: Individual plantlets, low growing weed, low growing shrub, climbing vine
Color: Generally dark green, except when not. Red in fall, except when not
Sun: Deep shade to complete sun

Now, this is the pattern where I grew up; my parents joke that it is the county flower. Here in Massachusetts, I don't see quite as much of it and it is very patchy. Wet areas are favorites, but there are also huge stands in non-wet areas. Landward faces of beach dunes are a spot to really watch out for it; Cape Cod is seriously infested.

While it causes humans great angst, poison ivy berries are an important wildlife food source. Indeed, at our previous house I had to be vigilant for sprouts along the flyways into my bird feeder. I've never seen Bambi or Thumper covered with ugly red welts; I'm not sure of the actual taxonomic range of the reaction to the poison (urushiol). Could it really be restricted to humans?

So, here you have a plant which thrives in many ecological niches, is important ecologically, a modest to major pest (inhalation of urushiol is quite dangerous & a hazard for wildfire fighters), an interesting secondary metabolites, and is related to at least two economically important plants (mangoes and cashews, which should be eaten with care by persons with high sensitivity to urushiol). Sounds like a good target for genome sequencing!

Tuesday, January 19, 2010

Green Krittah





As a youth, I was fortunate enough to spend four summers working as a camp counselor. Three of those were spent in the Nature Department, performing all sorts of environmental education functions (one year I taught archery).

One of my enjoyable duties was to wander the wilds of the camp looking for interesting living organisms to put in our terraria and aquaria, a job I relished -- though the campers could often top me for interesting (I never could find a stick insect, but we rarely lacked for one).

During one of those forays, most likely in my favorite sport of hand-catching of frogs, I stumbled onto a patch of a plant I did not recognize. I still remember it rather well -- perhaps because of the small itchy welts it raised on my unprotected legs. No, not nettles (we had plenty of those, and I often stumbled into them when focused on froggy prey), but rather a vining plant with light green triangular leaves about 5 cm on a side. Indeed, the leaves were nearly equilateral.

So, I took a sample back and poured through our various guides. Now, in an ideal world you would have a guide to every living plant expected in that corner of southeastern Pennsylvania -- which might be a tad tricky as we were on the edge of an unusual geologic formation (the Serpentine Barrens) which has unusual flora. But in general, such general plant guides are hard (or impossible) to come by. What I did have was a great book of trees -- but this wasn't a tree. I had several good wildflower books -- but I saw no blooms. I couldn't find it in the edible wild plant books -- so it was neither edible nor likely to be mistaken for one (rule #1 of wild foraging: never EVER collect "wild parsnips" -- if you're wrong they're probably one of several species which will kill you; if you are right and handle them incorrectly the books say you'll get a vicious rash).

But, being a bit stubborn, I didn't give up -- I kicked the problem upstairs. Partly, this was curiosity -- and partly dreams of being the discoverer of some exotic invader. I mailed a carefully selected sample of the plant along with a description to the county agricultural agent. At the end of the summer, I contacted him (I think by dropping in on his office). He was polite -- but politely stumped as well. So much for the experts.

I'm remembering this & relating it because I've come into a similar situation. My father, who is no slouch in the natural world department, spotted this "green krittah" (as he has named it) on his car last summer. Not recognizing it, and wanting to preserve it (plus, he is an inveterate shutterbug), he shot many closeups of it (the red bar, if I remember correctly, is about 5 mm) -- indeed, being ever the one to document his work he shot the below picture of his photo setup (the krittah is that tiny spot on the car). He even ran it past my cousin the retired entomologist, but he too protested overspecialization -- if it wasn't a pest for the U.S. Navy, he wouldn't know it. At our holiday celebration he asked if I recognized it. I didn't, but given this day of the Internet & my routine use of search tools, surely I could get an answer?


Surely not (so far). I've tried various image-based searches (which were uniformly awful). I've tried searching various descriptions. No luck. Most maddening was a very poetic description on a question-and-answer site, seemingly my krittah but far more imaginative than I would have ever cooked up: "What kind of spider has a lady's face marking it's back? Name spider lady's face markings and red or yellow almond shaped eyes?". Unfortunately, the answer given is a mixture of non sequitur and incoherence -- plus I'm pretty much certain this krittah has 6 legs, not 8. Attempts to wade through image searches were hindered by too few images per gallery and far too few completely useless photos -- of entomologists, of VWs, of spy gear & rock bands & other stuff. I've even tried one online "submit your bug" sort of site, but heard nothing.

I've also tried various insect guides online. The ones I have found are based on the time-tested scheme of dichotomous keys. Each step in the key is a simple binary question, and based on the answer you go to one of two other steps in the key. A great system -- except when it isn't. For one thing, I discovered at least one bit of entomological terminology I didn't know -- so I checked both branches. That isn't too bad -- but suppose I hit more? Or, suppose I answer incorrectly -- or am not sure. It took a lot of looking at Dad's fine photos to absolutely convince myself that the subject has only 6 legs (insect) and not 8 (mite or spider). It also doesn't help that some features (such as the spots on the back) appear differently in different photos. More seriously, the keys I found almost immediately are clearly assuming you are staring at a mature insect -- if you are looking at some sort of larvae they will be completely useless. So perhaps I'm looking at an immature form -- and the key will not help any. In any case, the terminal leaves of the keys I found were woefully underpopulated.



What I would wish for now is a modern automated sketch artist slash photo array. It would ask me questions and I could answer each one yes, no or maybe -- and even it I answered yes it wouldn't rule anything out. With each question the photo array would update -- and I could also say "more like that photo" or "nothing like that photo".

Of course, Dad could have sacrificed the sample for what might seem the obvious approach -- DNA knows all, DNA tells all. That would have nailed it (much as some high school students recently used DNA barcoding to find a new cockroach in their midst), but I think neither of us would want to sacrifice something so beautiful out of pure curiosity (if confirmed to be something awful on the other hand, neither of us would hesitate). Alas, in the mid 1980's I didn't think that way, so I don't have a sample of my vine for further analysis.


If anyone recognizes the bug -- or my vine -- please leave a comment. I'm still curious about both.


(01 Feb 2010 -- corrected size marker to 5 mm, per correspondence with photographer)