#! /bin/bash

# Outputs an HTML report.

figs=( ) # Figures used

function monoplot() {
  # Shows plot of a run without its spectrum.
  run="$1"; shift     # Name of the run file, minus the ".txt"
  pwidth="$1"; shift  # Width as percentage of widow width.
  printf "  <br/>\n"
  printf "  <center>\n"
  printf "    <small><b>${run##*/}</b></small><br/>\n"
  printf "    <a href=\"${run}.png\"><img src=\"${run}.png\" width=\"${pwidth}%%\"></a><br/>\n"
  printf "  </center>\n"
  printf "  <br/>\n"
  figs[${#figs[@]}]="${run}.png"
}

function biplot() {
  # Shows plots of a run and its spectrum.
  run="$1"; shift     # Name of the run file, minus the ".txt"
  pwidth="$1"; shift  # Width as percentage of widow width.
  printf "  <br/>\n"
  printf "  <center>\n"
  printf "    <small><b>${run##*/}</b></small><br/>\n"
  printf "    <a href=\"${run}.png\"><img src=\"${run}.png\" width=\"${pwidth}%%\"></a>\n"
  printf "    <a href=\"${run}_pwr.png\"><img src=\"${run}_pwr.png\" width=\"${pwidth}%%\"></a><br/>\n"
  printf "  </center>\n"
  printf "  <br/>\n"
  figs[${#figs[@]}]="${run}.png"
  figs[${#figs[@]}]="${run}_pwr.png"
}

function twoplots() {
  # Shows two figures side by side.
  filea="$1"; shift     # Name of the first file, minus the ".png"
  fileb="$1"; shift     # Name of the first file, minus the ".png"
  pwidth="$1"; shift  # Width as percentage of widow width.
  printf "  <br/>\n"
  printf "  <center>\n"
  printf "    <table cellpadding=\"2px\" border=\"0px\" cellborder=\"0px\">\n"
  printf "      <tr>\n"
  printf "        <td align=center><small><b>${filea##*/}</b></small></td>\n"
  printf "        <td>&nbsp;</td>\n"
  printf "        <td align=center><small><b>${fileb##*/}</b></small></td>\n"
  printf "      </tr>\n"
  printf "      <tr>\n"
  printf "        <td width=\"${pwidth}%%\" align=center><a href=\"${filea}.png\"><img src=\"${filea}.png\" width=\"95%%\"></a></td>\n"
  printf "        <td width=\"10px\">&nbsp;</td>\n"
  printf "        <td width=\"${pwidth}%%\" align=center><a href=\"${fileb}.png\"><img src=\"${fileb}.png\" width=\"95%%\"></a></td>\n"
  printf "      </tr>\n"
  printf "    </table>\n"
  printf "  </center>\n"
  printf "  <br/>\n"
  figs[${#figs[@]}]="${filea}.png"
  figs[${#figs[@]}]="${fileb}.png"
}

function compplots() {
  # Shows a component pattern and its trace side by side.
  filea="$1"; shift     # Name of the first file, minus the ".png"
  widtha="$1"; shift  # Width as percentage of widow width.
  fileb="$1"; shift     # Name of the first file, minus the ".png"
  widthb="$1"; shift  # Width as percentage of widow width.
  printf "  <br/>\n"
  printf "  <center>\n"
  printf "    <table cellpadding=\"2px\" border=\"0px\" cellborder=\"0px\">\n"
  printf "      <tr>\n"
  printf "        <td align=center><small><b>${filea##*/}</b></small></td>\n"
  printf "        <td>&nbsp;</td>\n"
  printf "        <td>&nbsp;</td>\n"
  printf "      </tr>\n"
  printf "      <tr>\n"
  if [[ "${filea}" != "NONE" ]]; then
    printf "        <td width=\"${widtha}%%\" align=center><a href=\"${filea}.png\"><img src=\"${filea}.png\" width=\"95%%\"></a></td>\n"
  else
    printf "        <td width=\"${widtha}%%\">&nbsp;</td>\n"
  fi
  printf "        <td width=\"10px\">&nbsp;</td>\n"
  if [[ "${fileb}" != "NONE" ]]; then
    printf "        <td width=\"${widthb}%%\" align=center><a href=\"${fileb}.png\"><img src=\"${fileb}.png\" width=\"95%%\"></a></td>\n"
  else
    printf "        <td width=\"${widthb}%%\">&nbsp;</td>\n"
  fi
  printf "      </tr>\n"
  printf "    </table>\n"
  printf "  </center>\n"
  printf "  <br/>\n"
  figs[${#figs[@]}]="${filea}.png"
  figs[${#figs[@]}]="${fileb}.png"
}

cat <<EOF
<!doctype html public "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Neuromat - Jorge Stolfi - Report 2013-11-15</title>
</head>
<body bgcolor="#fffff7">
<font face="bookman,arial">

<hr>

<h1>Project Neuromat<br/>Jorge Stolfi Report 2013-11-15</h1>

<p>Hi all, this is a short report on what I have been doing 
in the last few months (up to dec/2013).</p>

<p>I have been looking at the 128-electrode datasets that Claudia uploaded
to <b>~/Dropbox/eeg_sinal_ghislain/</b> a while ago (<b>S13.raw</b> and <b>S14.raw</b>). 
I have extracted the runs as separate files, filtered and plotted them.</p>  

<p>I have some observations and questions about the data.</p>

<h2>On the file format:</h2>

<ul>
  <li><p>The trigger pulses (in channels HB, HS, QB, QS, and fix1) last only
  one frame, correct?  (I ask because in the 20-electrode datasets each trigger
  pulse spanned several frames.)</p></li>

  <li><p>The CZ channel is always exactly zero, correct?</p></li>
</ul>
  
<h2>On the experimental setup:</h2>

<ul>
  <li><p>I understand that the first 128 data channels are the potential differences
  (in microvolts) between the 128 numbered electrodes and the reference
  electrode, correct?</p></li>

  <li><p>The reference electrode is the one labeled VREF in the electrode
  diagram (surrounded by C7 C106 C80 C55 C31), correct? It is not the
  unlabeled white disk a little further back (surrounded by C55 C79 C78
  C62 C61 C54)?</p></li>
</ul>
 
<h2>Extracting the runs</h2>

<p>For each experimental run, I extracted a segment from the original
dataset (<b>S13.raw</b> or <b>S14.raw</b>), exactly 7 seconds long,
spanning a fixation phase and the following stimulus phase, plus some
extra frames at both ends. The length of the two phases varies
somewhat, but the extracted files have the fixation-to-stimulus
transition always at the same moment, exactly 3.5 seconds after the
start of the file.</p>

<h3>Removing the electrode offsets</h3>

<p>In the original files, the potential of each electrode includes a
very large and seemingly arbitrary DC offset (up to 20 mV = 20.000
µV), mostly constant but different for each electrode. This offset
seems to vary (gradually or abruptly?) along the session, and from
session to session.</p>

<p>Therefore, when extracting the individual runs I had to compute some
'mean' potential of each electrode in each run and subtract it from
its data values, just to be able to plot them.  Apart from this mean shift,
no other processing was done on the raw runs.</p>

<h3>Examples of extracted runs</h3>

<p>The figures below show three typical extracted runs, with the
constant offsets subtracted fromeach electrode. The notation
<b>s013_r00209</b> means subject 13, block 2, run 9, etc.</p>

<p>For each run, the leftmost plot shows all 128 channels as a function of time (seconds) since the
start of the file.  Next to it are two plots of the power spectra of 
those channels, one from 0 to 35 Hz, the other from 0 ro 250 Hz
(the Nyquist frequency limit).  Note that the vertical scale is logarithmic.<br/>
EOF

biplot raw-runs/s013_r00209 45
biplot raw-runs/s013_r00805 45
biplot raw-runs/s014_r00203 45

cat <<EOF    
These files are available also in <tt>~/Dropbox/eeg_sinal_ghislain/2013-11-15-stolfi/</tt>.</p>

<h3>Observations on the raw runs</h3>

<ul>

  <li><p>What is the physical explanation of those large constant offsets,
  and their drifts within each session? Can they be eliminated at the source?</p>

  <p>Note that 1% of 5.000 µV is 50 µV. Thus, even relatively small oscillations
  in these offsets, say 1% or less and lasting less than a second, 
  will be confused with significant EEG signals.</p></li>
    
  <li><p>Besides these large offsets, there is an enourmous amount of
  60 Hz power line noise and its harmonics  (over ±200 µV amplitude in some channels, over ±50 µV in 
  several of them).<br/>
   
  The power line noise can and will be be removed by software filtering, which is 
  supposed to discard everything above 40 Hz (see below). However, I am
  worried that this noise may still contaminate the filtered data.</p>

  <p>If you recall, in the 20-electrode sets we obsered a significant 30
  Hz component that we conjectured to be a sub-harmonic of the 60 Hz
  noise (or interference from a computer fan motor running 1800 rpm).
  Any lower sub-harmonics of the power line noise (say 20, 15, or 10 Hz)
  would fall into the range of frequencies that are to be preserved by
  the software filtering step.</p>

  <p>Since data above 40 Hz is going to be discarded anyway, could it be
  possible to apply a 40 Hz hardware lowpass filter to the signals
  before sampling and A/D conversion? (I understood that the
  20-electrode equipment had a notch filter that removed the 60 Hz noise
  specifically, but passed the 30 and 90 Hz harmonics.)</p>
  
  <p>Hardware pre-filtering would allow the use of lower sampling rates
  (say, 200 or 150 Hz instead of 500 Hz); and that in turn may improve
  the accuracy of the sampled values.</p>
  
  <p>Another way to reduce the power line noise would be to place the
  subject inside a shielding cage, e.g. of chickenwire mesh. Perhaps the
  display's power source (or its power cable) is a source of the 60 Hz
  noise? </p></li>
  
  <li><p>In many runs there is also a sharp peak in the spectrum around
  80-85 Hz. Could this be due to the "microtremors" of the eyes?
  According to some papers I found, they are small involutary rotations
  of the eyeball (by about 1 degree) that allow the eye-brain system to
  compensate for the blind spots caused by blood vessels over the
  retina. According to those papers, the frequency of these microtremors
  is fairly constant from person to person, about 84 Hz.</p></li>
</ul>
  
<h2>Filtering</h2>

<p>After extracting the runs, I passed them through a Fourier-based bandpass filter.</p>

<h3>Filter choice</h3>

<p>For the low-pass and band-pass stages, I tried the Butterworth
filters used in the 20-electrode tests, but I found that they produced
substantial "ringing" whenever the input had a spike or a sharp step.</p>

<p>I therefore used Gaussian filters instead. Their transitions from
"pass" to "kill" are more gradual but they are free of ringing.</p>

<p>The following plots compare the effects of both filters. The top figure
shows some synthetic signals (an impulse, some bell-shaped pulses, a
square pulse and a chirp). The next two figures show the output of the
Gaussian and Butterworth filters, respectively, on those signals.<p/>
EOF

monoplot filter-tests/synth_p      80
monoplot filter-tests/synth_p_G    80
monoplot filter-tests/synth_p_BUR8 80

cat <<EOF    

<h3>Removing long-period drift</h3>

<p>Fourier-based filters assume that the input signal is periodic. This
is not a viable assumption when the input includes substantial
variations whose period is longer than the signal sample, such as random
drift. For the Fourier filter, those long-period variations create a
discontinuity in the signal at the end of each period, which gives rise
to spurious artifacts near both ends when it is smoothed out by the
filter.</p>

<p>Unfortunately, such long-period drifting is conspicuous in many raw
runs, as noted above. To reduce the artifacts, I fitted a cubic
polynomial (by a robust variant of least squares) to each electrode
signal in each run, and subtracted it from the signal, before applying
the Gaussian filter.</p>

<h3>Examples of filtered runs</h3>

<p>Here are some samples of filtered runs, and their power spectra: </p>
EOF

biplot flt-runs-B/s013_r00121  45
biplot flt-runs-B/s013_r00209  45
biplot flt-runs-B/s013_r00229  45 
biplot flt-runs-B/s013_r00805  45
biplot flt-runs-B/s014_r00203  45
biplot flt-runs-B/s014_r00425  45

cat <<EOF 
<p>These plots show that the filtering succeeded in removing
most of the drift and power-line noise, leaving a set of fairly cohrent
signals.</p>

<h3>General observations on filtered runs</h3>

<ul>
  
  <li><p>In almost every run there are a couple of electrodes that seem to
  be drifting randomly, by 50 µV or more, quite independently of their
  neighbors. Since such independence is not physically possible, those
  channels are probably garbage. I suppose that they should be removed
  from the data, but I have not done so. </p></li>
  
  <li><p>I am assuming that the large pulses seen in these plots (usually peaking at 50 to 200
  µV, and lasting from 0.3 to 0.5 seconds) are neuro-muscular signals
  due to the subject blinking. These are discussed in more detail
  below.</p></li>

  <li><p>In all runs that I have checked, there is a noticeable bump in the
  spectrum around 10 or 11 Hz. This is discussed further down, too.</p></li>
  
  <li><p>In a few runs there were very large oscillations of the 
  electrode signals, apparently random and independent from electrode
  to electrode, as in the folowing example:</p>
EOF

monoplot flt-runs-B/s013_r00401 60
  
cat <<EOF
  <p>Such "crazy" runs often occur as the first run of a new block.  I presume
  that they are due to the subject shifting the head to focus on the 
  fixation cross after a "rest" period, is that so?</p></li>

</ul>

<h2>Blinks</h2>

<p>Bad news: almost every extracted run contains one or more blink
pulses, and most of them may have to be discarded. Good news: the blink
pulses have a fairly simple, single-component model. Bad news: there may
be significant "sub-blink" muscular signals even when there seem to be
no blink pulses:</p>

<h2>Few blink-free runs</h2>

<p>Presumably blinks are not a problem unless they occur in the "important"
part of the run.  I arbitrarily assumed the "important" part to be the last 1 second
of the fixation phase and the entire 3 seconds of the stimulus phase (4
seconds in total).  Even so, I found that most runs would have to be discarded: 
only 91 runs of subject 013 (36%) and 16 runs of subject 14 (6%) were free of blinks
or other accidents in the "important" interval.</p>

<h2>Distribution of blinks</h2>

<p>Perhaps not surprisingly, I found that blinks are not uniformly
distributed in time. The following histograms shows the distribution of
the blink's position as a function of the time since the start of the
extracted run file, for the two subjects:</p>
EOF

twoplots blinks/s013_blinks_hist             blinks/s014_blinks_hist 45

cat <<EOF

<p>Recall that the fixation-to-stimulus transition occurs at precisely at <i>t</i>=3.5 seconds 
after the start of each run file.  The fixation phase begins around <i>t</i>=0.5 seconds
(sometimes a bit earlier) and the stimulus phase ends at <i>t</i>=6.5, usually with the 
start of another fixation phase.</p>

<p>From these plots, it seems that both subjects are much more likely to blink around <i>t</i>=1.0,
that is, about 0.5 seconds after the start of the fixation phase.  (The timing of those blinks may be 
even more regular than it seems in the plot, since the peak is somewhat 
broadened by the variation in the starting time of the fixation phase.)</p>

<p>Conversely, blinking seems to be suppressed during the first 0.5
seconds of the stimulus phase.</p>

<p>Within the stimulus phase, subject 014 is more likely to blink about 1 second
into it, whereas subject 013 shows no preference after the initial suppression period.</p>

<h2>Blink pulse modeling</h2>

<p>The blink pulses vary substantially from subject to subject (or
session to session), presumably due to changes in the anatomy, to
different "blinking styles" (which muscles are activated in the blink),
or simply to different placements of the electrodes.</p>

<p>On the other hand, blink pulses are remarkably similar within the
same subject and session. While there is some variation in the duration
and amplitude of the blinks, all electrode potentials rise and fall
together, in fixed proportions, throughout the blink pulse. In other
words, there is a single voltage distribution over the skull that
changes only by a common time-varying factor.</p>

<p>To find that pattern I extracted all blink pulses from each session,
and ran a principal component analysis on them.  The dominant component
(the one with largest intensity), for each subject, is shown graphically below:</p> 

EOF

twoplots flt-runs-B/s013_blinks_P000_eig_b2_f000000 flt-runs-B/s014_blinks_P000_eig_b2_f000000 45

cat <<EOF

<p>In these plots, as in my previous animations, lighter and warmer
tones are supposed to indicate positive voltages, darker and bluer tones
are negative. However, the two patterns above had their polarity
accidentally reversed by the PCA algorithm. Thus, during a blink pulse
the frontal region becomes positive while the rest of the scalp becomes
negative. The latter includes the temporal(?) electrodes (C125 and C128)
and the maxilar(?) ones (C126 and C127).</p>

<p>These patterns have surprising bilateral symmetry, and their similarity
too is surprsing considering the apparent difference between the 
plotted pulses of the two subjects.</p>

<h2>The 10 Hz component</h2>

<p>Another conspicuous feature in the time-base plots of the filtered runs is an irregular
oscillation with about 10 cycles per second, affecting almost all channels in synchrony.
This oascillation clearly matches the 10 Hz bump in the power spectra, whose width indicates
that the frequency varies somewhat along a run.</p>

<p>This 10 Hz oscillation too appears to be due to a single voltage pattern on the
skull. That is, all electrode potentials change together, in fixed
proportions, by a time-varying factor.</p>

<p>To identify this pattern, I performed a PCA of the blink-free "important" segments
of all runs, for each subject. Namely, I extracted from each run that had no "crazy" behavior
the last 1 second of the fixation phase and the 3 seconds of the stimuls phase,
and discarded those that included any blink pulses (as idenfied previously by visual 
inspectio, see above).  The concatenation of all those segments was then subjected to PCA.</p>

<p>The 10 Hz voltage pattern showed up as the first principal component in both subjects, shown below:</p>

EOF

twoplots flt-runs-B/s013_nonblinks_P000_eig_b2_f000000 flt-runs-B/s014_nonblinks_P000_eig_b2_f000000 45

cat <<EOF

<p>These diagrams show that the 10 Hz oscillation increases as one moves away from the reference electrode,
rather uniformly in every direction.  It is as if the source of that pulsation was not
inside the skull, nor somewhere on the scalp or face, but in the neck or lower.<p>

<p>The pattern of subject 13 is stronger on the back of the head, suggesting that neck muscles
are involved.</p>

<h2>The neck component</h2>

<h2>Separating the two components</h2>

<p>I tried to separate the filtered runs into a combination of the two components identified above --- the blink pattern (BL0) and
the general 10 Hz oscillation pattern (H10) --- and a residue (RES) that is orthogonal to both patterns. See the figures below.</p>
 
EOF

compplots flt-runs-B/s013_r00229     75 NONE                                          20
compplots flt-runs-B/s013_r00229_BL0 75 flt-runs-B/s013_blinks_P000_eig_b2_f000000    20
compplots flt-runs-B/s013_r00229_H10 75 flt-runs-B/s013_nonblinks_P000_eig_b2_f000000 20
compplots flt-runs-B/s013_r00229_BLH 75 NONE                                          20
compplots flt-runs-B/s013_r00229_RES 75 NONE                                          20
                                                                                        
compplots flt-runs-B/s014_r00425     75 NONE                                          20
compplots flt-runs-B/s014_r00425_BL0 75 flt-runs-B/s014_blinks_P000_eig_b2_f000000    20
compplots flt-runs-B/s014_r00425_H10 75 flt-runs-B/s014_nonblinks_P000_eig_b2_f000000 20
compplots flt-runs-B/s014_r00425_BLH 75 NONE                                          20
compplots flt-runs-B/s014_r00425_RES 75 NONE                                          20

cat <<EOF

<p>The negative parts of the extracted blink signal (such as in <b>s013_r00229_BL0</b> between <i>t</i>=2.0 and <i>t</i>=3.0) are not sigificant.  The principal component analysis is formulated in such a way that every extracted component has necessarily zero mean value in every electrode.  Therefore, the "positive" pulses that correspond to blinks must be compensated by a spurious "negative" signal between blinks.   I will try to reformulate the analysis to avoid these artifacts.</p>

<p>Note that the scale of the residual plots (<b>s013_r00229_RES</b>, <b>s014_r00425_RES</b>) is different from the other plots. For most electrodes, the amplitude of the residual signal is about 10 µV.</p>

<p>In the residual plots one can still see events that affect many electrodes together simultaneously.  For example, in <b>s014_r00425_RES</b> these events are visible around <i>t</i>=0.5,<i>t</i>=2.0, <i>t</i>=4.0, and several other places.  These events presumably are the next significant PCA elements; to be checked.</p>
 
</font>
<hr>
<p><small>
Last edited on 2013-12-07 16:14:35 by stolfilocal
</small></p>

</body>
</html>
EOF

# Ship files to man
echo "${figs[@]}"| tr ' ' '\012' | sort | uniq > .report-figs.dir
