Using R to Do Your Statistics and Crush Your Enemies (Maybe)



Over the course of my checkered career as a graduate student drudge, one of the best resources I have found for learning R, and, more importantly, actually getting it to do useful stuff, is the R guide from the Personality Project over at OSU. I encourage anyone interested in R to check it out, especially since my own experience with R got off to a rocky start; my introductory graduate course in statistics used R, but the instruction was so spotty and the concepts so difficult to understand that one day, instead of calculating a simple t-test like I wanted to, I accidentally ended up bypassing the Pentagon's firewall and starting a countdown for a nuclear warhead to be launched at Zimbabwe, which was stopped remotely at the last second by Edward Snowden.

The point is that R is a powerful language and that, once you become even partially familiar with it, you will be able to carry out basic statistical tests quickly and easily. One of the most instructive sections of the website, for me, is the one on ANOVAs, since I often use this to compare beta weights extracted across different regions of interest and test for double dissociations. Other sections give advice on how to restructure your data to be analyzed in different ways by R, linear regression, and multivariate statistics.

P.S. Some of the examples require links to datasets on the R project website which may no longer be properly linked (e.g., the ANOVA examples use commands like [datafilename = "http://personality-project.org/r/datasets/R.appendix1.data"], but give errors when attempting to read them into a table). I've converted some of them to my personal website, which should make them able to fit into tables without any errors. So, for example, you would use a command like [datafilename=""http://mypage.iu.edu/~ajahn/docs/R.appendix1.data.txt"], and so on for the other datasets.

P.P.S. I was planning to make a short video touring the personality project website and a few of the examples, but I've caught a cold recently, and right now my voice sounds mucusy and gravelly and full of sputum. While it may be pleasing for the ladies to hear my voice like this, it isn't as useful for instructional purposes; and really, that's what I'm all about.

How to Write a Dissertation Prospectus

Before beginning work on a dissertation, one has to put together and submit a prospectus, which is from the ancient Greek pro, meaning "Stuff," and spectus, meaning "One who writes." A prospectus is, in condensed form, what you will be writing about in your dissertation. This provides your dissertation committee, over a period of roughly two presidential administrations, a chance to read a brief, concise, single-spaced 50-page report about whether they should take the trouble to read a future dissertation that, for practical purposes, is measured not in pages but metric tons. Some students, knowing that a picture is worth a thousand words, merely substitute a diagram to helpfully outline what will be covered in their dissertation:



For those of us who aren't savvy enough with Google Images to produce an informative picture, however, we will need to rely on good, old-fashioned scientific prose. But first, let's cover the basic structure of your prospectus. Remember, by following these time-tested principles and recommendations, you will at least somewhat entertain your committee before they reject your dissertation proposal as completely ridiculous and holding about as much scientific merit as a can of Cheez-Whiz.


1. The Cover Page

A strong prospectus starts out with a cover page, containing the title of your dissertation, the names of the members of your dissertation committee, and possibly a dedication to someone who has had an immense and positive influence on your life, such as your parents, your girlfriend, or Tony Soprano. Feel free to embellish your cover page with depictions of cherubs and muses.

Example cover page from Edward Grieg's dissertation prospectus.



2. Personal Photo

Even after four years of working with your adviser, you shouldn't make any rash assumptions, such as that he or she will know what you look like. In order to help out your adviser, you should attach a professionally done personal photo showing you looking as serious and scientific as possible. This can score you major points with your committee, as they will now have a mental image of you as a serious, cultured individual, unlike all the other hirsute weirdos wandering around the department:


Source: Calvin Klein


3. Body of the Prospectus

Once you have successfully completed your cover page and personal photo, you're now ready for the most important and weightiest section of your prospectus - by which I mean, of course, that you actually have to write something related to the work that you have been doing over the past several years. A good prospectus should start out with something that immediately entices and intrigues the reader, such as the following:

Most honorable, sovereign, and magnificent lords,

I herewith enclose the following enclosements; a prospectus designed to please both one's innate curiosity and satisfy his critical faculties, by expounding upon the work of my graduate career, which has definitely involved reading only scientific articles and books, and not bootlegged copies of Humungo Garbanzo BOLD Responses. It is my utmost belief, penetrating my entire being and reaching even so far as the pyloric sphincter, that this prospectus will contribute to the PUBLIC WEAL and common good of academia and the scientific committee, viz., all of you, etc., et al, ora pro nobis.

The dissertation which I hereafter propose is that, in order to determine the neural mechanisms and correlates of prospective model-free decision-making, one must bring to bear several unique methodologies, such as functional and structural connectivity, multivoxel pattern analysis, univariate mastication, seed-based cortical peristalsis, dynamic CSF segmentation and haustral movements, computational modeling region of interest corrected thresholding bread milk Astroglide tortillas refried beans.

Deign, most honourable, magnificent and sovereign lords, to receive, and with equal goodness, this respectful testimony of the interest I take in whatever it is I have been studying the past several years. And, if I have been so unhappy as to be guilty of any indiscreet transport in this glowing effusion of my heart, I beseech you to pardon me, and to attribute it to the tender affection of a true student, and to the ardent and legitimate zeal of a man, who can imagine for himself no greater felicity than to see you happy.

Also, if somehow one of you manages to come across one of my old issues of Humungo Garbanzo stuffed in the back of the lowest drawer of my filing cabinet, I know nothing about that.

Most honourable, magnificent and sovereign lords, I am, with the most profound respect,

Your most humble and obedient servant and fellow-citizen,



Don't worry if you have a difficult time coming up with anything that sounds remotely plausible or scientific; if you've written a prospectus like the one above, odds are that your committee, satisfied that you are fluent in academic bullshit, will stop reading somewhere around the second paragraph, and fail to note that once you ran out of buzzwords you started supplying items from your grocery shopping list.

How to Avoid Common Cluster-Extent Thresholding Pitfalls in FMRI Analyses

Just when FMRI researchers were feeling good and secure about the methods they were using, yet another paper has come out in the journal Neuroimage about how everything you are doing is, to put it mildly, totally wrong.

The article, by Woo, Krishnan, and Wager, points out that one of the most popular correction methods for FMRI data - namely, cluster-correction, or cluster-extent thresholding - is routinely mishandled. This is not to say that you, a typical FMRI researcher, has no idea what he is doing. It is just that, when it comes to cluster-correction thresholding, you are about as competent as a bean burrito.

Cluster-correction is based on the assumption that in an FMRI dataset composed of several tens of thousands of voxels all abutting each other, there is likely to be some correlation in the observed signal between adjacent voxels. That is, one voxel immediately surrounded by several other voxels is not completely independent of its neighbors; the signal in each will be somewhat similar to the others, and this similarity is roughly related to how close the voxels are to each other. Smoothing, another common preprocessing practice, also introduces more spatial interpolations by averaging the signal over several voxels of a specified range, or kernel. Cluster-correction then uses an algorithm, such as Gaussian Random Field (GRF) Theory or Monte Carlo simulations, to determine what number of contiguous voxels at an individual, voxel-wise p-threshold (here in the paper referred to as a primary p-thresholds) would be found due to chance alone; if a cluster of a certain size is exceedingly rare, then most researcher reject the null hypothesis and state that there is a significant effect in that cluster.

However, the authors point out that this can lead to erroneous interpretations about where, exactly, the significant effect is. All that you can say about a significant cluster is that the cluster itself is significant; cluster-correction makes no claims about which particular voxels are significant. This can be a problem when clusters span multiple anatomical areas, such as a cluster in the insula spreading into the basal ganglia; it is not necessarily true that both the insula and basal ganglia are active, just that the cluster is. Large cluster sizes and lax primary p-thresholds, at the extremes, can lead to cluster sizes that are, relative to the rest of the brain, the size of a Goodyear Blimp.






Figure 1 from Woo et al (2014). A: Demonstration of how all of the different correction techniques, when plotted together, looks like a doughnut. Also, cluster-correction is the most popular technique. B and C: Clusters can span several areas, leading to erroneous interpretations about the spatial specificity of activation.

Another issue is that large primary p-thresholds are correlated with larger cluster sizes passing correction. That is, only cluster sizes that are huge will be deemed significant. Obviously, this loss of spatial specificity can be a problem when attempting to study small areas, such as the periaqueductal gray, which is about the size of a strip of Stride gum, as shown in the following figure:

From left to right: Periaqueductal gray, Stride gum, Tom Cruise (all images shown to size)





Lastly, the authors ran simulations to show that, even in a simulated brain with clearly demarcated "true signal" regions, liberal primary p-thresholds led to excessively high false discovery rates, a measurement of the number of false positives within a given dataset. (False discovery rate, or FDR, can be used as an alternative significance measurement, in which one is willing to tolerate a given percentage of false positives within a dataset - such as 5% or less - but is agnostic about which voxels are false positives.) This also led to a high amount of clusters smearing across the true signal regions and into areas which did not contain signal:


Figure 3 from Woo et al, 2014

Problems like these can be ameliorated by choosing more stringent primary p-thresholds, such as a voxelwise p less than 0.001, and in cases where power is sufficiently high or in cases where you might suspect that the intrinsic smoothness of your dataset is highly irregular, you may want to eschew cluster correction altogether and use a voxel-wise correction method such as family-wise error (FWE) or FDR. If you do use cluster correction, however, and you still get blobs that look like messy fingerpaintings, it can help the reader to clearly demarcate the boundaries of the clusters with different colors, thereby helping visualize the size and extent of the clusters, and fulfilling some of your artistic needs.


Now go eat your bean burrito.



The Beethoven Piano Sonatas

Warning: Classical music nerditry ahead.  (And some domestic violence.)

One evening while discussing the music of Beethoven with a friend (as is my wont), my conversation companion mentioned that, although Beethoven's music was very beautiful, she didn't see what, exactly, all the fuss was about. "He seems to have figured it out early on in the game, and then didn't change very much," she said. "He just knew what worked, and - OW!!!"

Although I felt bad about strongly pinching her thigh before she could complete her sentence, obviously I could not allow her to continue spewing such mendacity. However, even though our friendship was terminated shortly thereafter, I continued to be needled by her remarks, as her thoughts on the matter are not, it seems to me, an isolated incident. Beethoven seems to be not so much listened to as he is admired, not so much admired as merely accepted. Although plenty of his more popular melodies have permeated our collective ear, several of them have become diluted through overexposure of limited fragments. (How many are aware, for example, that there is more than one musical section in his "Für Elise" bagatelle?) The acquaintance that many have with Beethoven's work is, at best, incomplete; indeed, a recent survey showed that eighty percent of Americans believe Beethoven to be a limited edition line of Old Spice deodorant. To be surrounded by the music of today without a sense of where it has come from, without a proper perspective of Beethoven's role, is to be partially blind.

Beethoven's life and work are of one piece: Suffering, redemption, and extravagances of conduct mark both. Like the music he composed,  Beethoven was a force of nature. However, Beethoven was also by nature a developer - unsatisfied with the limitations of the musical forms of his day, Beethoven paved the way from the classical traditions of Haydn and Mozart to the new era of Romanticism, influencing virtually every major Western composer that came after him. And, while he innovated in nearly every major musical genre - a remarkable collection of violin and cello sonatas, piano trios, sixteen string quartets, and the monumental nine symphonies - it is the piano sonatas that most closely follow the trajectory of his compositional evolution. And they are perfection.

One of the most outstanding examples of his genius is the final movement of his piano sonata No. 17 in d minor, which begins with a four-note gesture starting on the dominant and circling from above to come down to the tonic. Problem: How to spin seven minutes of music out of a four-note motive? Through a series of transpositions, imitations, inversions, and unexpected shifts in register and dynamic, Beethoven manages to observe the motive through every possible angle, introducing subtle variations that heighten the drama and increase the tension. His suprametrical increases of the final note of the motive, for example, outlines larger-scale harmonic changes taking place over several measures, still foregrounding the swirling melody while driving the harmony through a longer musical architecture. When listening to it, note how the motive sometimes lands on accidentals (so-called because they actually are "accidents," where the composer screwed up but was too proud to admit their mistake) in order to segue into a new section. The result is an organic whole, linked by an obsessive, haunted idée fixe four-note gesture.


Beethoven's compositional vision was on a larger scale as well. Beginning with the trio of piano sonatas of Op. 2, Beethoven shows an adherence to the classical sonata form while hinting at future developments finally culminating in his sonata No. 21, Op. 53, the "Waldstein" sonata. While Beethoven wrote several piano sonatas in the "grand" style - most notably, the Waldstein, "Appassionata" (Op. 57) and "Hammerklavier" (Op. 106) sonatas - it is really the Waldstein that announces its themes and methods. Everything about the sonata's first movement, from the exposition to the development to the coda and the following rondo, is colossal in scope, and stretches the sonata-allegro form to extremes that could only have been thought of by Beethoven. Certainly it is the most trailblazing in technique, and one of the most important milestones in the art of writing orchestrally for the piano. The Hammerklavier sonata - containing a finale which, in the words of one of my former composition teachers, is a "fugue on acid" - would later outline all of the aspects and characteristics of the grand sonata form, and then exhaust all of their possibilities.



At the same time it is astounding that this notoriously difficult man, containing such volcanic, baffled passions, should have also been capable of musical ideas of such profound beauty, lyricism, and, sometimes, humor. (Several times I have observed that when Beethoven writes for the lowest registers of the piano, it is either to express emotions of titanic, epic proportions - or to make a musical joke.) The melody of his piano sonata in A major, Op. 101, for example, is one of the most tender outpourings ever conceived, occasionally pausing to breathe and collect itself, dissolving barlines but never stopping. It is the harbinger of his last decade of composition, during which Beethoven, increasingly ill and in pain, totally deaf and increasingly withdrawn into his own enigmatic inner world, managed to call forth his most spiritual and exalted music. A man who begins a sonata with the instructions Etwas lebhaft und mit der innigsten Empfindung is imitating no one. He is not writing exercises. It is escapism, but of a very different order. Escapism, in the everyday sense of the term, is contemptible; here, it is an escape, but - like all great works of art - into a deeper, greater reality. Ideally, one where nobody can pinch you.



I think that I now have an answer for my former friend. Once she recovers and lifts the restraining order, that is.


======================

The pianist in a couple of the videos I just posted - András Schiff - has also made a lecture series covering the entire cycle of Beethoven sonatas. The lectures are rewarding experiences for both veteran and novice listener alike; and while one can profitably listen to any of them in isolation, there are a few particularly noteworthy lectures that I recommend to your attention: Sonata No. 7, Op. 10, No. 3; Sonata No. 21, Op. 53 ("Waldstein"); and the three last sonatas, Opp. 109, 110, and 111.

Anterior Cingulate Neurons and Postdecisional Variables in a Foraging Task (Or: How to Get Laid Just by Staring at Somebody!)

A couple of my colleagues at the University of Rochester, Tommy Blanchard and Ben Hayden, recently published a single-cell recording study in the prestigious Journal of Neuroscience. Publishing in that journal is a big deal which everyone in my area aspires to, since it contains cutting-edge science that is read by several leading authorities in the field. (I, on the other hand, having neither the talent nor the motivation to do anything nearly that impressive but still craving attention, recently posted a video where I stuffed fourteen marshmallows into my mouth - and was still able to say "Chubby Bunny". Not that I'm bragging or anything.)

Blanchard and Hayden pin their colors to the mast at once. While some theories posit that the dorsal anterior cingulate cortex (dACC) represents the value of a choice - in other words, that the dACC encodes information about options before a decision is made - the authors argue in the present study that the dACC monitors specific variables about the chosen option and about its outcome, in effect encoding information after a decision is made. In addition, this implies that the observed dACC signals will be affected by not only the type of choice made, but also by variables about the foregone (not chosen) option.

To test this, the researchers tested  rhesus macaque monkeys used a paradigm known as a "diet selection task." In this task, the monkeys looked at a bar descending across a screen. The length of the bar determined how long the monkeys needed to fixate on the bar to receive a reward, while the color of the bar represented the size of the reward. If the monkeys fixated on the bar long enough, after a certain amount of time they would get the reward. The paradigm, I presume, was based off of the observation that young men at nightclubs and bars apparently believe that if they stare long enough at a female across the room, eventually she will become so overwhelmed with passion that she will tear off all of her clothes, even if the male who is staring happens to possess the sex appeal of a deceased gerbil. The fact that this rarely occurs, they think, is probably because they are not given enough time to stare; with a sufficiently long period of ogling, success would be virtually guaranteed.

Figure 1 reproduced from Blanchard & Hayden (2014). A: Monkey either does not fixate and does not get a reward (i.e., does not choose the option), or fixates on the bar, which progressively shrinks until reward is obtained. B: Reward sizes and fixation times for bar lengths. C: Recording site in dACC.


The recordings from single cells within the dACC showed a pattern of increased firing rate when an option was presented, along with a period of ramping-up in activity right before the reward was expected to appear (as shown in panel A of figure 3). Within this same cortical region, relatively high percentages of the neurons showed high correlations between their neural firing and reward, between the neural firing and the delay when they would receive the reward, or between the neural firing and both the size of the reward and the time it would take to receive the reward (panel B of figure 3).


Figure 3 of Blanchard & Hayden (2014)

A crucial test between the competing hypotheses, therefore, would be to examine whether the firing patterns of the dACC were qualitatively different depending on whether the option was accepted or not, and furthermore whether certain properties of the option (such as its reward size and the delay time) would be preferentially encoded depending on whether the option was accepted or not. It was found that on accept trials, more neurons tended to signal the delay of the reward rather than the size of the reward, while during reject trials, more neurons tended to signal the size of the reward than the delay time for the reward (Figure 4, panels C and D). Encoding the reward of the option that was not chosen is also known as a foregone option, since it was not selected but still apparently exerted an effect on neuronal firing.


Figure 4 of Blanchard & Hayden (2014)

Finally, the researchers observed that profitability - the ratio of reward size to delay - was significantly different depending on whether the monkeys decided to accept or reject the given option. Both this and the previous observations can all be described as postdecisional; the variables studied here show significant differences based on whether an option is chosen or rejected, and only specific aspects of that option are preferentially encoded by neurons in the dACC once the decision is made. This is in contrast to a predecisional framework of the dACC, which should encode aspects about the presented option, such as reward size and delay, regardless of whether the option is selected or not.



Link to paper: http://www.jneurosci.org/cgi/content/abstract/34/2/646

How I Feel When Writing My Dissertation

I've undergone quite a change in the past couple of months - my voice has deepened, my hips have widened, and those once-nascent dark patches of hair sprouting under my armpits and within my nostrils have now become so thick that they require maintenance at least twice a week with a weed-whipper.

I am referring, of course, to starting my dissertation.

Starting one's dissertation is accompanied not only by physical developments, however, but by drastic psychological changes as well. Such monomaniacal devotion of mental energy to such a specialized area of research studied by literally tens of persons around the world can lead to bizarre alterations in one's perceptions and behavior, including paranoia, cerebral hemorrhaging, grand mal seizures, clubbed fingers, piles, scrofula, scrapie, delusions of persecution, listening to Nickelback, demonic possession, and Nutella-induced comas. All of these symptoms have been declared normal and well within the safety margins of the International Dissertation Committee Panel (or IDCP, pronounced "eye-dick-pee").

In addition, dissertation writers are notorious for their trademark reclusive lifestyle and cantankerous mood. Someone who used to be social and outgoing will now refuse to go out with their friends or interact with anybody, claiming that they have to work on their dissertation. What this really means is that they used to hate everybody anyway, and now they just have a valid excuse for refusing to attend any event that doesn't offer free food.

However, probably the most distinguishing characteristic of a dissertation writer is his inability to talk about anything other than his dissertation; somehow, the conversation keeps coming back to the 200-pound - I mean, 200-page! - gorilla in the room:


BRAD: I'm having a really difficult time right now; my hemorrhoids are acting up again, my hairplugs aren't taking, and last week my parents were brutally murdered.

TOM: I know how you feel; right now I'm writing my dissertation.

BRAD: I'm so sorry.


Even if they don't directly reference their dissertation, you can bet your gorilla that they are worrying about it, constantly. To help you out, here are translations of some oblique dissertation references that you might otherwise miss:

WHAT THEY SAY: I'm going to work for eighteen hours straight today, no distractions whatsoever, unplugging my Internet and turning off my phone and euthanizing my pets, operating only on coffee strong enough to melt through several layers of reinforced steel similar to that one scene with the facehugger blood in the movie Alien.
WHAT THEY MEAN: I'm going to sit around for eighteen hours straight marathoning seasons of Breaking Bad, and probably will spend a grand total of about two hours on my dissertation. And by that, I mean thinking about my dissertation.

WHAT THEY SAY: My life is hard.
WHAT THEY MEAN: I have, quite possibly, the most arduous life in existence. I mean, for example, those people fighting in World War II, yeah, they had it rough, with D-Day and the siege of Stalingrad and everything, but did they have to write their dissertation? No.

WHAT THEY SAY: I'm going to work from home today.
WHAT THEY MEAN: I'm going to do some drugs today.


As we can see, writing a dissertation is a trying experience for any individual, no matter how hurly-burly a soul he or she may be. However, even after the months and years of dissertation writing, even after the numerous and hard-fought battles with one's committee about what studies to run, even after the premature aging leading to whitened hair, strained eyes, and hardened arteries - even after all that, it's worth that moment when half of your four-person committee reads at least a few pages of your dissertation on the day of your defense, looks at you with quizzical expressions usually reserved for grotesque carnival exhibits, and asks you questions that are so unrelated to anything you ever wrote and anything you ever experienced that if you weren't in academia you would swear you were surrounded by certified space loons.

If that still doesn't do it for you, you will still have the ecstatic experience of paying upwards of $2,000 for binding and printing your dissertation (based on your number of dependents and whether you select optional dissertation rhinestone gilding), after which a copy of your thesis will be stored in a remote warehouse in Zimbabwe, along with some extra weed-whippers.


To help you better understand the whole dissertation experience - and keep in mind, I am VERY aware of my audience - I've included the following scene from Metal Gear Solid 4: Guns of the Patriots. In what I believe is a thinly veiled metaphor for dissertation writing, I've broken down what everything means:

Solid Snake: You
Microwave hallway: Dissertation
Crawling through the microwave hallway: Writing your dissertation
Wait, hold on a second here - microwave hallway? That's how the bad guys defend the most valuable part of their fortress? With microwaves?: Yes
Why not machine guns or mines or something?: The game was made in Japan.
Otacon: Your adviser
Extremely awkward camera placement behind Snake's derriere: The extraordinary sense of humility you feel taking part in such a noble enterprise, making an original contribution to the body of knowledge and maybe, just maybe, making the world a better place. Or something. I really had to make a stretch for this one.
Other people: The friends and family in your life who, while you were writing your dissertation, were busy fighting genetically-modified supersoldiers and terrifying biped war machines. Which is what they do anyway.



FIR Models Redux

As promised, here is a tutorial video on how to set up Finite Impulse Response (FIR) models in AFNI. The previous post contained the code for using FIR basis functions instead of traditional Gamma basis functions, which then spews estimates for activity at each time point you specify, which can be in as long or as short of a time window that you like. You can then extract these using a command like 3dbucket, e.g.

3dbucket -prefix VisCoeffs cstats.FT+orig'[12..22]'

You can then extract these timecourses by loading up a statistical dataset and overlaying blobs at certain thresholds, or just overlaying an ROI that you created and highlighting it through the "Rpt" button in the AFNI interface. Choose "Aux Dataset", load up the coefficients you extracted, and make a neat line, like this:

 Keep in mind that this was a block design, and that these were coefficients extracted from a visual ROI from a visual condition; so naturally the hemodynamic response will increase and plateau for the duration of the block. Often you will get much more complex shapes, which contains information about how timepoints along the hemodynamic response can differ across conditions, as well as hierophanies, if you look closely enough. In any case, don't get too carried away.





Temporal Basis Functions and the Finite Impulse Response (FIR)

We neuroscientists tend to make a lot of assumptions about the brain: First, that everybody has one; second, that the more your neurons fire, the more blood will flow to those neurons; and third, that from the first two assumptions we can create sophisticated, impressive-sounding models and theories about the brain that explain everything, from consciousness and being to schizophrenia and Nutella addiction. Not that we aren't humble about it.

However, one of the most tenuous, sometimes ridiculous notions we have is that this blood flow, this continuous lifestream attempting to quench the brain's unslakable thirst with each pulse, is the same, acts the same, looks the same in every nook and cranny, every bump and crevice, every gyrus and sulcus of cortical and subcortical real estate. Why would we maintain such a clearly psychotic fantasy in the first place? Assumptions, madame, pure assumptions.

A word or two is in order about the origins of this one assumption in particular. In the beginning, a band of intrepid scientists observed that blood flow changes in primary sensory areas resulted in a gamma-shaped curve that peaks around five seconds followed by a long-lasting decline and undershoot around the thirty-second mark; at high field strengths, sometimes a small initial undershoot can also be observed. The results were so consistent in these areas, and the effects so strong, that these observations were soon cast into a model called the canonical hemodynamic response function (HRF), which has been widely used ever since.

And, for the most part, it has done pretty well. Typically a young, ambitious researcher, fueled by nothing more than the lust for knowledge and fame, for girls and gold and hazelnut spread - possibly even a swimming pool with all of the above mixed in there - will carry out his analyses using a whole-brain approach; that is, where the onset of each condition in each voxel is convolved with the hemodynamic response function. The height of the HRF is then estimated for each condition and averaged across trials, and contrasts can be carried out on these estimated heights. So far, so good; and plenty of high-quality research has been done using just this technique.

However, this is only a single parameter we are estimating for each condition; and if you happen to be a nerd, or a masochist, or a person who likes to do things the hard way - in other words, if you are in academia - you will doubtless be curious about other parameters you can harvest from your data. Sure enough, likeminded nerds have made these options available in the form of Finite Impulse Response (FIR) functions, which do not make any assumptions about the shape of the neural activity following a stimulus onset, and can therefore provide more detailed, flexible information about what is going on. All you do is specify that you wish to use that type of basis function, as well as the length of the interval you are interested in and how many time points you wish to estimate. Usually, FIR analyses are most interpretable when specified over a timecourse that doesn't include significant overlap with another condition, and when the timecourse is partitioned into units that are the same length as the time it takes to acquire each scan.

For now, I will focus on how to do this in AFNI. AFNI's version of FIR functions includes several ways to estimate each timepoint after a specified onset, including TENT, CSLPIN, and SIN basis functions, although for most purposes you will use TENT. (The TENT function uses a piecewise linear spline method to estimate brain activity at each timepoint; the details of this method are pretty complicated, which is a classy way of saying that I don't completely understand it.) The TENT function takes in three arguments: The beginning and ending times relative to the onset of a stimulus, or whatever timepoint you are interested in; and how many parameters to estimate. If b is the beginning and c is the end, with n being the number of parameters to estimate, then the time interval is (c-b)/(n-1). For example, if I wanted to estimate 5 parameters within a window from 0-8 seconds after a specified time, then the time interval between each point would be (8-0)/(5-1) = 2.

Although this would be usually implemented with event-related designs, I'll stick with AFNI's dataset #6, which uses a block design. Note that some of the shapes of the HRF can look pretty funky, compared to what you would expect when convolving with a canonical HRF; this should increase the already profound feelings of despair you have about cognitive neuroscience, and spur you to search for fields of more meaningful endeavor, such as specializing in pottery, martial arts, or poetry slams; specifically, slamming the country of Chile.


Here is what the code would look like for a typical FIR analysis in AFNI, assuming (har!) that you have already analyzed dataset #6:


#!/bin/tcsh

setenv subj = 'FT'

3dDeconvolve -input pb.$subj.r*.scale+orig.HEAD
-polort 3
-num_stimts 2
-stim_times 1 stimuli/AV1_vis.txt 'TENT(0,20,11)'
-stim_label 1 Vrel
-stim_times 2 stimuli/AV2_aud.txt 'TENT(0,20,11)'
-stim_label 2 Arel
-x1D X.xmat.1D -xjpeg X.jpg
-cbucket cstats.$subj


More information coming soon, but right now I have a bus to catch back to warm, sunny Minnesota! At least that's how my online travel agent, Amir, described it before I paid him five thousand dollars to arrange my trip and give me advice on how to woo the locals. Apparently, bright orange ski parkas are in style. Ladies?

Introduction to Reinforcement Learning Models

Someone very near and dear to me just sent me a picture of herself cuddled up on the couch in her pajamas with an Argentinian Tegu. That's right lady, I said Tegu. The second coming of Sodom and Gomorrah - you heard it here first, folks! I mean, I know it's the twenty-first century and all, but what the heck.

Looks like I'll be pushing her to buy that lucrative life insurance policy much earlier than planned!

Anyway, I think that little paroxysm of righteous anger provides an appropriate transition into our discussion of reinforcement learning. Previously we talked about how a simple model can simulate an organism processing a stimulus, such as a tone, and begin to associate that with rewards or lack of rewards, which in turn leads to either greater levels of dopamine firing, or depressed levels of dopamine firing. Over time, dopamine firing begins to respond to the conditioned stimulus itself instead of the reward as it becomes more tightly linked to receiving the reward in the near future. This phenomenon is so strong and reliable across all species, it can even be observed in the humble sea slug Aplysia, which is one ugly sucker if I've ever seen one. Probably wouldn't stop her from cuddling up with that monstrosity, though!

Anyway, that only describes one form of learning - to wit, classical conditioning. (Do you think I am putting on airs when I use a phrase like "to wit"? She thinks that I do; but then again, she also has passionate, perverted predilections for cold-blooded wildlife.) Obviously, any animal in the food chain - even the ones she associates with - can be classically conditioned to almost anything. Much more interesting is operant conditioning, in which an individual has to make certain choices, or actions, and then evaluate the consequences of those choices. Kind of like hugging reptiles! Oh hey, she probably thinks, let's see if hugging this lizard - this pebbly-skinned, fork-tongued, unblinking beast - results in some kind of reward, like gold coins shooting out of my mouth. In operant conditioning parlance, the rush of gold coins flowing out of one's orifice would be a reinforcer, which increases the probability of that action in the future; while a negative event, such as being fatally bitten by the reptile - which pretty much any sane person would expect to happen - would be a punisher, which decreases the probability of that action in the future.

The classically conditioned responses, in other words, serve the function of a critic which monitors for stimuli and reliably-predicted reinforcers or punishers following those stimuli, while operant conditioning can be thought of as an actor role, where choices are made and the results evaluated against what was expected. Sutton and Barto, a pair of researchers considerably less sanguinary than Hodgkin and Huxley, were among the first to propose and refine this model, assigning the critic role to the ventral striatum and the actor role to the dorsal striatum. So, that's where they are; if you want to find the actor component of reinforcement learning, for example, just grab a flashlight and examine the dorsal striatum inside someone's skull, and, hey presto! there it is. I won't tell you what it looks like.

However, we can form some abstract idea about what the actor component looks like by simulating it in Matlab. No, just in case you were wondering, this won't help you hook up with Komodo Dragons! It will, however, refine our understanding of how reinforcement learning works, by building upon the classical conditioning architecture we discussed previously. In this case, weights are still updated, but now we have two actions to choose from, which results in four combinations: either one or the other, both at the same time, or neither. In this example, only doing action 1 will lead to a reward, and this gets learned right quick by the simulation. As before, a surface map of delta shows the reward signal being transferred from the actual reward itself to the action associated with that reward, and a plot of the vectors shows action 1 clearly dominating over action 2. The following code will help you visualize these plots, and see how tweaking parameters such as the discount factor and learning rate affect delta and the action weights. But it won't help you get those gold coins, will it?




clear
clc
close all

numTrials = 200;
numSteps = 100;
weights = zeros(100,200); %Array of weights from steps 1-100, initialized to zero

discFactor = 0.995; %Discounting factor
learnRate = 0.3; %Learning Rate
delta = zeros(100,200); %Empty vector
V = []; %Empty vector
x = [zeros(1,19) ones(1,81)];

r = zeros(100,200); %Reward vector, which will be populated with 1's whenever a reward occurs (in this case, when action1 == 1 and action2 == 0)

W1=0;
W2=0;
a1=zeros(1,numTrials);
a2=zeros(1,numTrials);


for idx = 1:numTrials
   
    for t = 1:numSteps-1
        if t==20
            as1=x(t)*W1; %Compute action signals at time step 20 within each trial
            as2=x(t)*W2;
           
            ap1 =  exp(as1)/(exp(as1)+exp(as2)); %Softmax function to calculate probability associated with each action
            ap2 =  exp(as2)/(exp(as1)+exp(as2));
           
            n=rand;
            if n<(idx)=1;
            end
           
            n=rand;
            if n<ap2                a2(idx)=1;
            end
        
            if a1(idx)==1 && a2(idx)==0 %Only deliver reward when action1 ==1 and action2 ==0
                r(50:55,idx)=1;
            end                       
        end
       
        V(t,idx) = x(t).*weights(t, idx);
        V(t+1,idx) = x(t+1).*weights(t+1, idx);
       
        delta(t+1,idx) = r(t+1,idx) + discFactor.*V(t+1,idx) - V(t,idx);
       
        weights(t, idx+1) = weights(t, idx)+learnRate.*x(t).*delta(t+1,idx);
       
        W1 = W1 + learnRate*delta(t+1,idx)*a1(idx);
        W2 = W2 + learnRate*delta(t+1,idx)*a2(idx);
       
    end
   
    w1Vect(idx) = W1;
    w2Vect(idx) = W2;

   
   
end


figure
set(gcf, 'renderer', 'zbuffer') %Can prevent crashes associated with surf command
surf(delta)

figure
hold on
plot(w1Vect)
plot(w2Vect, 'r')

 





======================

Oh, and one more thing that gets my running tights in a twist - people who don't like Bach. Who the Heiligenstadt Testament doesn't like Bach? Philistines, pederasts, and pompous, nattering, Miley Cyrus-cunnilating nitwits, that's who! I get the impression that most people have this image of Bach as some bewigged fogey dithering around in a musty church somewhere improvising fugues on an organ, when in fact he wrote some of the most hot-blooded, sphincter-tightening, spiritually liberating music ever composed. He was also, clearly, one of the godfathers of modern metal; listen, for example, to the guitar riffs starting at 6:38.


...Now excuse me while I clean up some of the coins off the floor...

Master's Recital Music Videos

Since there are several haters out there who doubt that I can play piano, here, finally, is video evidence from a recent recital. In case you're confused, I'm the tall guy at the keyboard wearing all black.

Any mistakes, ensemble slipups, or counting errors are solely my fault, and in no way reflect on Sonja. (I said I could play; I didn't say anything about playing well.) Make sure to buy a bunch of hand lotion and Kleenex before listening to these masterpieces.