User Tools

Site Tools


analysis:nsb2015:week3short

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
analysis:nsb2015:week3short [2015/07/16 17:46]
mvdm created
analysis:nsb2015:week3short [2018/07/07 10:19] (current)
Line 46: Line 46:
 <code matlab> <code matlab>
 %% cd to data folder -- replace this with yours %% cd to data folder -- replace this with yours
-fd = '​D:​\data\DataAnalysisTutorial\R042-2013-08-18';​+fc = '​D:​\data\DataAnalysisTutorial\R042-2013-08-18';​
 cd(fc); cd(fc);
  
Line 54: Line 54:
 </​code>​ </​code>​
  
-If you are using your own data that has a missing or bad .clusters file, do this:+If you are using your own data that has a missing or bad .clusters file, do this instead:
  
 <code matlab> <code matlab>
Line 76: Line 76:
 </​code>​ </​code>​
  
-The details of this are discussed in [[analysis:​nsb2015:​week2|Module 2]]. In brief, each cell of ''​S.t''​ contains the spike times from a putative neuron. The qualifier "​putative"​ is used because this is extracellular data and [[analysis:nsb2014:​week4|spike-sorting]] is not perfect, so it's likely there will be some spikes missing and some spikes included that are not from this neuron. Always remember this even if I will omit the "​putative"​ from now on for short. You can see we have loaded 67 neurons for now.+The details of this are discussed in [[analysis:​nsb2015:​week2|Module 2]]. In brief, each cell of ''​S.t''​ contains the spike times from a putative neuron. The qualifier "​putative"​ is used because this is extracellular data and [[analysis:nsb2015:​week4|spike-sorting]] is not perfect, so it's likely there will be some spikes missing and some spikes included that are not from this neuron. Always remember this even if I will omit the "​putative"​ from now on for short. You can see we have loaded 67 neurons for now.
  
 Let's also load a LFP: Let's also load a LFP:
Line 103: Line 103:
 ''​csc''​ is the common Neuralynx designation for "​continuously sampled channel"​ and typically is an EEG or LFP type signal sampled and filtered so that high-frequency components such as spikes are not accessible. It is possible to have wide-band, 32kHz CSCs suitable for spike extraction, but these are not included in the current dataset. As discussed in [[analysis:​nsb2015:​week2|Module 3]] a LFP **tsd** is defined by matching sets of sample timestamps (''​csc.tvec''​) and sampled data (''​csc.data''​). ''​csc''​ is the common Neuralynx designation for "​continuously sampled channel"​ and typically is an EEG or LFP type signal sampled and filtered so that high-frequency components such as spikes are not accessible. It is possible to have wide-band, 32kHz CSCs suitable for spike extraction, but these are not included in the current dataset. As discussed in [[analysis:​nsb2015:​week2|Module 3]] a LFP **tsd** is defined by matching sets of sample timestamps (''​csc.tvec''​) and sampled data (''​csc.data''​).
  
-==== ts objects: ​basic methods ​====+==== Plotting ​basic spike rasters ​====
  
 The ''​S''​ variable that contains our spike times is a MATLAB struct that conforms to the ''​ts''​ ("​timestamp"​) format introduced in [[analysis:​nsb2015:​week2|Module 2]]. Its ''​.t''​ field contains spike trains as lists of numbers, corresponding to the timestamps of the spikes. So, to plot a raster with the spikes of the first cell in our data set: The ''​S''​ variable that contains our spike times is a MATLAB struct that conforms to the ''​ts''​ ("​timestamp"​) format introduced in [[analysis:​nsb2015:​week2|Module 2]]. Its ''​.t''​ field contains spike trains as lists of numbers, corresponding to the timestamps of the spikes. So, to plot a raster with the spikes of the first cell in our data set:
Line 116: Line 116:
 ☛ Extend the example code above to make a rasterplot containing the spikes for all cells in ''​S''​. To facilitate re-use later, wrap your code in a function, %%PlotSpikeRaster%%,​ that plots the raster for any ''​ts''​ input. ☛ Extend the example code above to make a rasterplot containing the spikes for all cells in ''​S''​. To facilitate re-use later, wrap your code in a function, %%PlotSpikeRaster%%,​ that plots the raster for any ''​ts''​ input.
  
-You should find that it takes a significant amount of time to plot that many spikes. In practice we often want to plot spikes for specific time intervals.+You should find that it takes a significant amount of time to plot that many spikes. In practice we often want to plot spikes for specific time intervals; we will do this belowAlternatively,​ there exists code that is much faster at plotting rasters (albeit more obscure; implemented in ''​PlotSpikeRaster2()''​ if you want to see an example). 
 + 
 +==== Temporally restricting ts and tsd objects ====
  
 A useful function that works on ''​ts'',​ ''​tsd''​ and ''​iv''​ objects is ''​restrict()''​. A useful function that works on ''​ts'',​ ''​tsd''​ and ''​iv''​ objects is ''​restrict()''​.
Line 124: Line 126:
 Calling your %%PlotSpikeRaster%% function on this restricted data should be much faster. Now that we are a bit more zoomed in, some interesting features of the rasterplot become visible. For instance, at time 5967, many cells are synchronously active. Could this be a sharp wave-ripple event (SWR)? Calling your %%PlotSpikeRaster%% function on this restricted data should be much faster. Now that we are a bit more zoomed in, some interesting features of the rasterplot become visible. For instance, at time 5967, many cells are synchronously active. Could this be a sharp wave-ripple event (SWR)?
  
-☛ Restrict the csc to the same time (5950 to 6050) and plot it in the same figure. You can use the ''​rescale()''​ function to fit the csc into a convienient ​data range (e.g. ''​rescale(csc.data,​-5,​0)''​).+☛ Restrict the csc to the same time (5950 to 6050) and plot it in the same figure. You can use the ''​rescale()''​ function to fit the csc into a convenient ​data range (e.g. ''​rescale(csc.data,​-5,​0)''​).
  
 You should see that the synchronous activation around time 5967 is indeed associated with a striking oscillation in the LFP: You should see that the synchronous activation around time 5967 is indeed associated with a striking oscillation in the LFP:
Line 132: Line 134:
 This high-frequency osillation (the "​ripple"​) superimposed on a slower oscillation (the "sharp wave") is the signature associated with "​replay"​ events in the hippocampus. We will explore this phenomenon in detail in later modules. This high-frequency osillation (the "​ripple"​) superimposed on a slower oscillation (the "sharp wave") is the signature associated with "​replay"​ events in the hippocampus. We will explore this phenomenon in detail in later modules.
  
-==== Figure properties, handles, and exporting ​====+==== Exporting figures ​====
  
-(Remember ​to execute the commands below from your ''​sandbox.m''​ file, not from the command line! That way you can more easily retrieve what you did later.) +A good way to save figures ​you may want to keep is:
- +
-A MATLAB figure ​is actually a collection of objects, all with their own properties which you can access and edit. For instance, to change the figure background to black, do+
  
 <code matlab> <code matlab>
-set(gcf,'Color',[0 0 0]);+print(gcf,'-dpng','​-r300','​R042-2013-08-18-LFPsnippet.png'​);
 </​code>​ </​code>​
  
-''​gcf''​ is MATLAB'​s name for "​get ​current figure". The above command set its '''​Color''' ​property to ''​[0 0 0]''​ which is black (zero red, zero green, zero blue in the RGB world).+Notice that the first argument of ''​print''​ is the current figure ​(''​gcf''​). The other arguments specify that we want a ''​PNG'' ​file, with 300dpi resolution. PNG format is a good choice for saving figures because it uses lossless compression,​ JPG images, which use lossy compression,​ can have ugly artifacts (but more colors). Other useful save formats are ''​-dill'' ​which saves ''​.ai''​ Illustrator files, and ''​-depsc''​ which saves an embedded %%PostScript%% file (both vector formats).
  
-☛ Set the background ​of the current //​axes// ​to black (''​gca''​ is MATLAB'​s name for the current axes object; notice that the axes background is currently white, which looks ugly).+☛ Critically evaluate ​the formatting ​of figure shown above. What are some missing elements you would want to see if this figure were to be used in a talk or paper? What changes could you make to improve legibility?
  
-Notice that now you can't see the axis lines and labels anymore, because they too became black when you changed the color of the axes. You want to set their color to be white, but you might not know the name of the relevant property.+==== A fully featured plotting function ====
  
-☛ Use ''​get(gca)'' ​to get list of all the axes properties. Find the properties that correspond to the axes color and set them to white.+''​MultiRaster()'' ​is versatile ​and fast plotting function, with many different options and features.
  
-Now that our figure looks nice, let's save it as an image file:+The most basic usage is simply:
  
 <code matlab> <code matlab>
-print(gcf,'​-dpng','​-r300','​R042-2013-08-18-LFPsnippet.png'​);+MultiRaster([],S)
 </​code>​ </​code>​
  
-Notice ​that the first argument ​of ''​print'' ​is the current figure. The other arguments specify that we want a ''​PNG'' ​filewith 300dpi resolution. PNG format ​is a good choice for saving figures because it uses lossless compression,​ JPG images, which use lossy compression,​ can have ugly artifacts (but more colors). Another useful save format is ''​-dill'' ​which saves ''​.ai''​ Illustrator files. +Note that the first argument ​in this case is the empty matrix ​''​[]''​. For more featuresthis argument ​is used as a ''​cfg'' ​variable with several optionsfor instance:
- +
-☛ Look at the image file. The colors are all wrong! Solve this problem by turning off the ''​InvertHardCopy''​ property of the figureand save again. (MATLAB does this by default to facilitate printing images on white paper.) +
- +
-Let's add some moderately fancy features to our plot. Starting from a currently selected rasterplot, do the following:+
  
 <code matlab> <code matlab>
-%% add multi-unit activity to rasterplot +plot_cfg ​= []; 
-ax1 = gca; ax1_pos = get(ax1,'​Position'​);​ +plot_cfg.lfp = csc; 
-ax2 = axes('​Position',​ax1_pos);​ % new axes with same position as first +plot_cfg.spkColor ​= 'hsv'; 
- +MultiRaster(plot_cfg,S)
-cfg = []; cfg.tvec = csc.tveccfg.sigma 0.1; +
-mua = getMUA(cfg,​S);​ % obtain multi-unit activity +
- +
-xr = get(ax1,'XLim')+
-mua_r = restrict(mua,xr(1),xr(2)); % only keep the data we need +
- +
-axes(ax2);​ +
-mua_hdl = plot(mua_r.tvec,​mua_r.data,'​Color',​[0.7 0.7 0.7]); +
- +
-set(gca,'​YAxisLocation','​right','​Box','​off','​XTick',​[],'​Color','​none'​) +
-linkaxes([ax1 ax2],'​x'​);​+
 </​code>​ </​code>​
  
-A few things to note here: +This particular data set also has some experimenter annotations associated with it, for example ​in the %%ExpKeys%% file:
-  * Using the ''​Position''​ property of the current axes (ax1, containing the rasterplot) we created a new set of axes (ax2). +
-  * In these new axes, we plotted the multi-unit activity, obtaining an output argument. Like ''​gca''​ and ''​gcf''​ this is a **handle** to graphics object; in this case, a handle to the multi-unit activity signal we just drew. +
-  * We set the properties of the new multi-unit axes to have the y-axis on the right (plus a few other properties). +
-  * ''​linkaxes()''​ was used to link the x-axis of both axes so that both update when zooming in. Try it!  +
- +
-☛ Change the properties of ''​mua_hdl''​ so that the line is reddashed, and of width 2.  +
- +
-100 seconds of LFP is a lot to display.  +
- +
-☛ Use the '​XLim'​ axes property to zoom in to 5989 to 5990 s; while you are at it, increase ​the font size to 24. (You can change multiple properties with the same command, just keep adding property-value pairs.) +
- +
-It would be nice to be able to update what time window of the data we are looking at, without having to type these ''​XLim''​ commands. To do this we need to use a special Figure property, introduced in the next section.  +
- +
-One final point of interest: different graphics objects are often (hierarchically) related. For instance, our figure currently contains one set of axes. We can obtain the axes handle directly, ''​axes_handle = gca;'',​ but also indirectly, ''​axes_handle = get(gcf,'​Children'​);''​. This works because currently, the axes are the only child of the figure. +
- +
-==== Figure callback functions ==== +
- +
-First, another basic MATLAB skill: anonymous functions. Consider:+
  
 <code matlab> <code matlab>
-sqr_fn = @(x) x.^2; +>> LoadExpKeys 
-sqr_fn(2) +>> ExpKeys
-</code>+
  
-''​sqr_fn''​ defines a **function handle** to a so-called anonymous function, i.e. a function that is not in .m file form. The above example basically says "​sqr_fn is a function of x, and should return x squared."​ (if you don't understand the ''​.''​ notation, it is important to look this up!)+ExpKeys = 
  
-Look at the [[http://www.mathworks.com/​help/​matlab/​ref/​figure_props.html|KeyPressFcn]] figure propertyThis property specifies the function to call whenever a key is pressed with the figure active..+                Behavior: '​MotivationalT'​ 
 +         ​RestrictionType:​ '​water'​ 
 +                 ​Session:​ '​standard'​ 
 +                  Layout: '​foodLeft'​ 
 +                Pedestal: '​R'​ 
 +                nPellets: 5 
 +             ​waterVolume: ​[
 +                 ​nTrials:​ 18 
 +            forcedTrials: ​[
 +    nonConsumptionTrials[] 
 +               ​badTrials:​ [] 
 +              pathlength: 318 
 +                patharms: 369 
 +           ​realTrackDims:​ [139 185] 
 +                convFact: [2.9176 2.3794] 
 +             ​TimeOnTrack:​ 3240 
 +            TimeOffTrack:​ 5645 
 +               ​prerecord:​ [2.1266e+03 3.2141e+03] 
 +                    task: [3.2387e+03 5.6452e+03] 
 +              postrecord: [5.6564e+03 6.5635e+03] 
 +                 ​goodSWR:​ {1x2 cell} 
 +               ​goodTheta:​ {'​R042-2013-08-18-CSC07a.ncs'}
  
-☛ Implement the example shown in the page above. Notice the properties of the ''​evt''​ object passed to the keypress function, and that this function also gets passed the handle of the figure that generated the keypress event. 
- 
-The keypress function thus has access to everything we need to implement some useful navigation functionality. 
- 
-☛ Create a keypress function that moves the x-limits of the current figure'​s axes to the left or right by 50% (i.e. if the current axes are from 1 to 2s, then pressing the right arrow key takes it to 1.5-2.5 s. It will be easier to do this with a ''​.m''​ file given the length of what you need to do. 
- 
-Hint: model your ''​.m''​ file on the template in the example given in the KeyPressFcn section of the [[http://​www.mathworks.com/​help/​matlab/​ref/​figure_props.html|Figure properties ]] page, and define it thus: ''​f_hdl = figure('​KeyPressFcn',​@your_function);''​ if your function is called ''​your_function.m''​. Please keep in mind of the difference between ”==” and “strcmp” operators. The former treats two strings as vectors and does letter-wise comparison. Thus the two strings ought to be of the same dimension. The latter operator does lexical comparison and returns “1” if the two strings are identical, “0” otherwise. ​ 
- 
-==== Varargins ==== 
- 
-A standard function definition specifies the exact number of input and output arguments the function expects: ''​function y = sqrt(x)''​ has one input and one output argument. However, it is often useful to have a variable number of input arguments, so that you can override defaults or specify additional options as needed without complicating simple function calls. For instance, you want to be able to make quick plots with ''​plot(x)''​ but specify extra stuff when needed (''​plot(x,'​LineWidth',​2)''​). This is accomplished with the special argument ''​varargin''​. 
- 
-Here is the idea: 
- 
-<code matlab> 
-function test_fun(a,​varargin) 
- 
-b = 2; % set defaults for b and c 
-c = 3; 
- 
-extract_varargin;​ % override b and c if specified 
- 
-fprintf('​a is %d, b is %d, c is %d\n',​a,​b,​c);​ 
 </​code>​ </​code>​
  
-Test it:+The meaning of these fields is explained in more detail in the full [[task description]],​ but for now we will just use the start and end times for the '​prerecord'​ segment of the data to highlight ​it visually:
  
 <code matlab> <code matlab>
->> test_fun(1+plot_cfg = []; 
-a is 1, b is 2, c is 3 +plot_cfg.evt = iv(ExpKeys.prerecord); 
->> test_fun(1,'​b',​1) +plot_cfg.evtColor = [0 0 0.5]; 
-a is 1, b is 1, c is 3 +MultiRaster(plot_cfg,S)
->> ​+
 </​code>​ </​code>​
  
-Note how specifying a "​key-value"​ pair (''​'​b',​1''​) overwrote the default for ''​b''​. ''​extract_varargin''​ basically goes through the varargins and assigns each value to the corresponding key. +''​MultiRaster()''​ is interactiveallowing ​the user to scrollzoommove from one event to anotheret ceteraTo see the full list of keybindingstype ''​help navigate''​.
- +
-☛ Verify your understanding by calling ''​test_fun''​ such that ''​b''​ and ''​c''​ are both set to ''​0''​. Also note what happens when you do ''​test_fun(1,'​B',​1)''​+
- +
-A different way of flexibly specifying function inputs ​is through the use of a ''​cfg''​ (configuration) input. An example of how this works can be seen in the ''​getMUA()''​ function used above. +
- +
-==== Exercise ==== +
- +
-☛ Extend your %%PlotSpikeRaster%% function as followsusing either ​the varargin or cfg strategy, and your knowledge of object handles. +
- +
-<code matlab>​ +
-% required inputs: +
-+
-% spikes: ts object with spike train +
-+
-% optional inputs: +
-+
-% csc: tsd object with LFP data (bonus points for accepting more than one gracefully) +
-+
-% cscColor: [nCSC x 3] RGB values ​to plot CSCsdefaults to red +
-% spikeColor: [nCells x 3] RGB values to plot spikesdefaults to black +
-+
-% evt: ts object with event times to plot as vertical linesdefaults to none +
-+
-% interactiveMode:​ boolean to enable/​disable arrow key navigation of time axis +
-</​code>​ +
- +
-This function should produce a rasterplot of spikes -- one neuron per row -- with one or multiple LFPs plotted above it, similar to panel Aa of the Dragoi and Tonegawa figure aboveThe values on the y-axis are not important for now, so you can feel free to hide this axis and rescale everything to look good. Set the default x range to 2 seconds. +
- +
-Also, we want to be able to overlay events ​of interest on this plot (such as times when the animal received rewardor brain stimulation was triggered); these can be simple vertical lines that extend all the way through the plot. You can make up a few event times yourself for testing. +
- +
-Finally, for data exploration it is helpful to be able to skip through the data with the arrow keys; set it up so that the left and right arrows can be used to scroll left and right. For extra awesomeness,​ add zoom functionality that scales the LFPs when pressing the up and down arrows. +
- +
-☛ When you are satisfied with your work, save a copy in your project folder and push it to GitHub. Verify that your version is visible from the web. +
- +
-=== Hints === +
- +
-Everything you need to know to make this work has been introduced in this module: beyond this (and basic MATLAB) no special functions or tricks are neededA few suggestions:​+
  
-  * Start simple. Instead ​of trying ​to implement everything at once, take it one step at a time. First, plot a single line (corresponding to one spike). Then, plot a spike train for one neuron, and keep building. +The [[analysis:​nsb2015:​week3long|long version]] ​of this module challenges you to write version ​of this visualization function yourself, so you can understand how it is doneand customize it for your application.
-  * Don't test on the full data set. Things will be faster if you use restricted data for testing. +
-  * Plot everything in single set of axesi.e. without using ''​subplot()''​ or ''​axes()'';​ this means you have to rescale and add a baseline offset (a.k.a. DC component) to the LFP signals ​so that they don't overlap.  +
-  * Develop in the ''​sandbox''​ file so that you can use cell mode and have easy access to the workspace. Only when everything ​is basically workingmove to putting everything inside a function.+
analysis/nsb2015/week3short.1437083188.txt.gz · Last modified: 2018/07/07 10:19 (external edit)