Thursday, July 31, 2008

Fractions in HTML

So I finally found a way to put (mathematical) fractions inline in HTML. It's quite straightforward using the inline-block display style. It works in all major browsers, except for Firefox earlier than version 3. Here's the code
<style>
.fraction {
  display: inline-block; vertical-align: middle;
  font-size: 50%; text-align: center;
}
.fraction span { display: block; }
.fracdenom { padding-top: .05em; border-top: .125em white solid; }
</style>

<p>Compute 
3 <span class="fraction"> 
<span>1</span> 
  <span class="fracdenom">400</span> 
  </span>+ 
<span class="fraction">
  <span>399</span>
  <span class="fracdenom">400</span>
</span> without your pocket calculator!
</p>

And this is what it looks like:

Compute 3 1 400 + 399 400 without your pocket calculator!

Unfortunately, you have to tweak it for ever page to make it look good; and it displays differently on each and every browser (for one thing: Firefox handles the "inline-block" setting correctly only since version 3).

Saturday, September 29, 2007

Random draws from Gaussian, Logit and Exponential

I implemented some probability distributions in JavaScript. The attached file contains a set of functions for sampling from the standard normal, the logit and the exponential distribution, as well as their density and distribution function. Their quality relies entirely on the uniform distribution sampler of the browsers javascript engine (Math.random()).

The file defines the functions as methods of the Math object, but there is also a new, single instance, Stat object that you might one to use to distinguish the two. The Stat object is merely an alias for the Math object. I used the R/S-plus naming conventions for the functions: psomething codes the distribution function, dsomething the corresponding density, and rsomething generates samples from that distribution. The function rnorm() generates standard normals by rejection sampling (on average about 22 calls to random() for every 10 samples drawn) and are accurate if random() is accurately uniform (I tested it in IE6, Firefox 2, Safari 3, Opera 9: drew 50000 samples and tested for disparity from standard normal using a KS-test, and repeated that a couple of times). The function pnorm however is a crude (logit) approximation that will differ less than 0.01 from the true probability (maximum differences at ±0.574 and ±2.04; greates accuracy at 0, ±1.22, and beyond ±4).

An example of the use of rnorm is:

   <html>
   <head>
     <script type="text/javascript" src="Stat.js"></script>
   </head>
   <body>
     <pre>
     <script>
         for(var i=0; i < 100; i++) 
             document.write(Math.rnorm()+" ");
    </script>
    </pre>
   </body>  
   </html>
The result is

Stat.js

Friday, August 04, 2006

HTML Application tool for scoring videofragments in psychology and social science research.

There are impressive examples of what you can do with HTML applications. Here is the famous Word like editor application example of Microsoft. Guido needed an application that would make scoring the video fragements he recorded of emotional behavior in children easier and more acurate. Although commercially available packages exist, for example Observer, these are expensive and offer far more features than necessary. More importantly they are accompanied by a dongle and so only one installation can be used at a time and only at the university. This is not very convenient for Guido's students, who are doing much of the scoring. They would like to be able to do it on their own computer, and they don't want to set up a schedule for sharing with other students. So I started to build a HTA, because that saves me a bit of time compared to building a full blown application in C. Furthermore, it suffices generously. It is now in a state where I think it might be useful for others, at least as an example of what you can do with HTA. The interface is however fully in Dutch (could be translated if there is enough interest). You can find a screenshot here: 'filmpjes-scoren' screenshot. You can download the installer from this link.

Monday, April 24, 2006

Saving web form data to file

If you want to use webpages and DHTML to do experiments or fill out questionairs, the problem is saving the data to a file on the hard drive for statistical analysis. If your web-form is on a online webpage this not too difficult (e.g., using a mail-form—see this page). But if you want to collect data offline, you would like to able to save those data to a file on the hard drive. How to get access to the hard disk from within a webpage is explained here, but it is more convenient to have javascript code that works for any form on a webpage. To this end I created a Javascript object that gathers the data from a form, and—in Internet Explorer—can write it to the hard disk in the comma separated values (".cvs") format. Part of the code is based on code from this website. An example and a detailed explanation can be found here. A zip file containing the .js library file and the example and documentation can downloaded here.

Wednesday, December 21, 2005

Detecting the popup-blocker

It is often useful to be able to open a new window to present the page containing the intended content (e.g., a page containing the actual experiment as was done here) in a way that is not possible from the user openen browser window. For example, you may want to get rid of the menu and toolbar, and have the window span the entire screen. This is easily achieved using the window.open function. The problem is that most web surfers have a popup blocker activated. There's no way to circumvent this, but you would like to be able to detect wether the creation of the popup window succeeded. Then you can present a warning to the user, explain the problem, and instruct the user to click a link on the current page to try again (the popup blocker doesn't block popups that are the direct result of a click event by the user). In MSIE you can use the window.createPopup function to create a popup that won't be blocked (this type of popup is subject to the restriction that only one popup can be open at the same time), but this is not available in other browsers. Here's a simple example:
   <html>
   <head>
     <script>
       url = 'http://www.google.com'
       message  = "A popup-blocker was detected!"
       message += " Please click the link to try again."
       popupProp = "fullscreen=yes, toolbar=no"

       function openIt() {
           var w = window.open(url, '_blank', popupProp)
           if(!w) // popup was blocked
              alert(message)
       }
    </script>
   </head>
   <body onload="openIt()">
    <h1> 
      If the window doesn't open
      <a href=# onclick="openIt()">
        click here
      </a>
      to try again.
    </h1>
   </body>  
   </html>
If you move your mouse over the square below you can see the above script in action.
Move your mouse over this square. If the window doesn't open click here to try again.
It doesn't necessarily have to be a click event, it can also be a keydown event. For example if you first click the square below and press the 'a' key, a popup window will appear. This is achieved by setting onkeydown="if(event.keyCode==65) openIt()". (See this post for making this compatible with Firefox.)
If this square has focus and the 'a'-key is pressed, a popup will open without being blocked.

Saturday, November 26, 2005

Nonlinear minimization in javascript

For certain experiments in psychology, especially those with tasks in which parameters are changed in response to the behavior of the subject ('adaptive testing'), it is useful to be able to minimize a function. DHTML is very useful for implementing such tasks (and an extemely cheap alternative for expensive experimentation software such as E-Prime), and so it is useful to have a javascript algorithm for function minimization. I found a useful C algorithm that was straightforward enough to translate into JavaScript (click the title of this post to download). It is an implementation of the Hooke and Jeeves algorithm (with improvements; read this for a conceptual explanation and comparison to other algorithms). Good things of this algorithm are: light weight and simple code, reasonably robust, multidimensional minimization, no gradients required, and open source. This javascript implementation is easy to use as the example below demonstrates:
  <script type=text/javascript src="hooke.js"><script/>
  <script>
  function g(x, n) // x contains the parameters, n is the # of params
  {
      c = -Math.exp(-(4-x[0])*(4-x[0])) + (x[1]*x[1]); 
      return (c);
  } 

  var console = document.getElementById("console")
  var a = new Hooke(g);  // new minimizer object
  a.startpt = [5, 1.9];  // starting point
  a.setConsole(console); // give a div element for diagnostic output
  a.main();              // start searching
  var result = a.endpt;  // array containing the coordinates found
  <script>
  <div id=console></div>

console

The full documentation is provided in the source.

Sunday, November 20, 2005

The EZ-Diffusion Model

We—that is, Eric-Jan Wagenmakers, Han van der Maas and me—have recently submited a paper which introduces the "EZ diffusion model" for two-choice reaction times, based on the diffusion model by Ratcliff (1978). To make application of the model easier we made a simple JavaScript program. Here's a batch-processing version. You only have to paste a table with the means, variances and proportions correct, and click a button to compute the EZ-diffusion parameters. The values are nicely formatted in a table so that you can copy easily copy and paste them back into your data analysis program. The original program can be found on E-J's site.

Update: An updated version of the EZ diffusion model, EZ2, is now available which also estimates the starting point/bias parameter. See EZ2

Saturday, November 12, 2005

Simple Questionnaire Wizard (SQW): example 2

1. Als ik 's ochtends wakker wordt heb ik altijd moeite om meteen op te staan.
  helemaal waar 1 2 3 4 5          helemaal onwaar
2. Als ik 's ochtends wakker wordt heb ik altijd honger.
  helemaal waar 1 2 3 4 5          helemaal onwaar
3. Als ik 's ochtends wakker wordt ga ik meteen douchen.
  helemaal waar 1 2 3 4 5          helemaal onwaar
4. Als ik 's ochtends wakker wordt wil ik graag weten wat voor weer het is.
  helemaal waar 1 2 3 4 5          helemaal onwaar
5. Als ik 's ochtends wakker wordt kijk ik als eerste op de klok.
  helemaal waar 1 2 3 4 5          helemaal onwaar

Friday, November 11, 2005

Simple questionnaire Wizard (SQW) Example

Here's an example what the new Simple Questionnaire Wizard can generate:
1. Als ik 's ochtends wakker wordt heb ik altijd moeite om meteen op te staan.
When I wake up in the morning I always find it hard to get up immediately.
  helemaal oneens
completely disagree
1 2 3 4 5         helemaal eens
        completely agree
2. Als ik 's ochtends op sta dan behoren bij mijn ochtend ritueel:
When I get up in the morning, my morning ritual includes:
  douchen
ontbijten
koffie drinken
de krant lezen
scheren / opmaken / haren
thee drinken
ochtend
   gymnastiek
3. Als ik 's ochtends wakker wordt en het gordijn open schuif, dan erger ik me het sterkst als
When I wake up in the morning and open up the curtains, I get mostly irritated when
 

Simple questionnaire Wizard (SQW)

I'm in the process of making a very simple questionnaire wizard for generating web based questionnaire for my colleagues who do not wish to delve into HTML coding, but still want to be able to gather some data online. It is already usable, but it's capabilities are currently very limited. It only generates forms that can be used from a website hosted on a uva.nl domain server, but you can easily modify the resulting HTML-code to make it suitable for other server domains. It currently only generates questionnaires with 7-point Likert scales. (These can be reduced to fewer points by simply deleting points, but this cannot be reversed unless you click undo in the edit menu or press Ctrl-z.) I will soon extend the possibilities. I also will start making the interface more visually appealing very soon. You can find the wizard here.
update: The current version can do a lot more, but it has still limited capabilities. update: For offline collection of data using webpages and storing the collected data to file, read this.
There's an update here and an example of the new capabilities here.

Wednesday, September 21, 2005

Iowa Gambling Task

Eric-Jan and his undergraduate Mirre Stallen decided to collect responses from a biggg group of subjects on the Iowa Gambling task. Together with Eric-Jan I implemented an internet version of this task. It should work with both MSIE and Firefox (I didn't test other browsers). You can find it here. Although it is in Dutch I have added some approximate English translation when you mouseover the text. I would appreciate it if you would seriously do the task for me until the end, so that I can gather some data for comparisson with the subject pool. If you would like to hack the code for your own purposes, you can dowload this zip file which contains all the files used. The code is not the neatest possible, but sufficiently readable I think.

Added June 25th, 2006
Please read this post to learn how to save the data.

Added January 14th, 2007
The zip file now bundles both the task and the code to save data to file. Now there is a web version (.html file) and a desktop version (.hta file) which runs after unzipping the complete directory. Both are English versions. The saved data format is compatible with the included data extraction tool. Please see the Readme.txt file for instructions. The desktop version also has more graphical feedback (see screenshot below).

Added April 30th, 2007
Note that after you downloaded the zip file, you really must unzip the file! In Windows XP this is easiest if you double click the downloaded file, and click the 'Extract all files' at the top of the left panel. If you don't see images when you start the hta version, then you most likely have not unzipped the zip file.

Added April 13, 2010
Apparently still a lot of people want to use this tool. Now you can gather your own data in your own Google Spreadsheet without any hassle at all. Just follow this link and follow the 3-steps instructions to create your own customized version without the need to dive into the html or javascript and collect data in your own spreadsheet. It couldn't be easier!

Preventing a participant (or user) from accidentally leaving a page or closing a window prematurely

When using DHTML for behavioral experiments, one thing you certainly wish not to be possible, is that before the experiment is finished and the data were saved or submitted, your subjects can accidentally close the window (by clicking on the window close button, or pressing Ctrl-W, or even pressing Alt-F4), or unload the page in any other way (e.g., pressing the reload button or pressing F5). To prevent such accidents you can use an onbeforesubmit event handler. (Fortunately it is not possible to prevent such actions that are carried out deliberately.) The simplest is to copy and paste the code below and put it in your HTML page:
<script>
window.onbeforeunload = confirmExit;
function confirmExit()
{
   // you might consider conditionalizing 
   // this return statement
   return "You haven't finished yet!" +
          " Please press 'Cancel' to continue.";
}
</script>
This works in MSIE 5.1 and higher, and in Firefox 0.9 and higher.

Monday, September 19, 2005

Opening your HTML page in full screen mode

How to start your DHTML page in 'theatermode' (or 'channelmode' or 'full screen' mode, whatever...)

If you are using DHTML for psychological experiments, you would often like to get rid of the window border and have the entire display covered by a background. This was possible in MS Internet Explorer if you would open a popup window with one of the parameters set to channelmode (see the example here, which will open such a window if you click the button), or by resizing and repositioning the window such that the window borders would fall of the screen. For security reasons (phishing, and the like) this has changed in recent updates of MSIE. Now, you cannot get rid of the window if the document is loaded over an http connection. It is still possible to have the screen entirely occupied by you HTML-page if you load it from the hard disk (e.g., when you use MSIE as a substitute for behavioral research software and don't want to spend ridiculous amounts of public funding money on products such as E-prime). The secret is in the launch flags of MSIE that hardly anyone knows about: If you click Start &rightarrow; Run and type “iexplore.exe -k” followed by the full address of your file (i.e., 'iexplore.exe -k “c:\Documents and settings\John Doe\Desktop\myExperiment.html”') , then MSIE will launch in theater mode with the indicated file opened. You can close the window with Alt-F4.

This is probably not the most convenient way to start your experiment each time with a new participant is tested. Instead, you can place a shortcut on the desktop: First right click the HTML file that implements your experiment, choose 'Send to desktop (creates shortcut)'. Then, on the desktop right click the freshly created shortcut and choose 'Properties'. A tabbed window opens, choose the tab 'Shortcut'. In the target field, you'll find the name and path of you HTML file. Put the cursor in front of and type the full path and name of the internet explorer executable in quotes (something like '"C:\Program Files\Internet Explorer\iexplore.exe"', followed by '-k' and a whitespace (see the image below). Click 'OK'; you're done. You'll notice that the icon of your shortcut has changed spontaneously to the icon you'd expect for a shortcut to MSIE itself. If you double click the shortcut your experiment starts automatically in full screen mode.

Friday, August 12, 2005

Changing the appearance—or getting rid—of the mouse pointer

When using DHTML to do psychological experiments, you're likely to want to get rid of the mouse pointer as stimuli are presented. This is very easy fortunately. In principle you can have your mouse pointer look like anything that you can make a picture look like: First you create a bitmap (e.g., a blank one), and then you turn it into a .ico file. Then, on the body element (or any other element) of the HTML page you specify a cascading style sheet that includes the specification "cursor: url('mymouse.ico');" (of course 'mymouse' may be anything you like).

example: the George W. Bush fan DIV

<div style="cursor: url('gwbush.ico')">
Move your mouse over this text, you Georgey fan!
</div>

Here's the ico image that is used. You can make any bitmap in paint, for example, but that program won't save it as an .ico file. You can however copy and paste your design to IrfanView, from which you can save it as an .ico file.

Wednesday, July 27, 2005

Special Characters in HTML

This is not strict DHTML, but useful anyway. This page on webmonkey shows a listing of special characters, but it isn't complete. One would like to have a listing of all available symbols and the HTML &...; format, but that's an awful lot of work, so I made a page that helps you find them: character codes.

Sunday, July 24, 2005

Capturing the escape (Esc) key in JavaScript

One would often like to be able to interupt a process in the middle of it (e.g., a computation that takes a long time, a block of trials in an ψ experiment, or a project creation sequence by a wizard), with a single button press. A standard choice of key for allowing this, is to interupt the process as soon as the escape key on the keyboard is pressed. In MSIE, Javascript allows you to capture key presses of all but the function keys (function keys can be captured in Firefox). Key presses, are events, and like any other event, the Event object collects all available information about what the user was doing. The key that was pressed is encoded in the keyCode property of the event object. In MSIE there is a single global window.event object that is accessible by the event handler function, while in Firefox the event object is passed when the keypress handler is called. Here's a simple example page that captures the Esc key:

 <html>
 <head>
   <script>
   function keyPressHandler(e) {
      var kC  = (window.event) ?    // MSIE or Firefox?
                 event.keyCode : e.keyCode;
      var Esc = (window.event) ?   
                27 : e.DOM_VK_ESCAPE // MSIE : Firefox
      if(kC==Esc)
         alert("Esc pressed")
   }
   </script>
 </head>
 <body onkeypress="keyPressHandler(e)">
   <h1> Press the escape key </h1>
 </body>
 </html>
Other keys are captured in the same way. You can also detect if the Alt or Ctrl keys were held down during the key press. Booleans indicating this are stored in the altKey and ctrlKey properties of the event object. To see the key code your looking for, move your mouse over the rectangle and press the key.

double click to see the source of this textarea element

Monday, June 27, 2005

Exploiting JavaScript and DHTML Browser capabilities for Experimentation in Psychology

JavaScript+HTML = Dynamic HTML (DHTML) can be very useful and extremely powerful for implementing less conventional experimental paradigms in experimental and/or cognitive psychology and allied neurosciences. It is certainly worthwhile to consider DHTML for your next experiment.

Timing in DHTML can be very accurate. This is the case on Windows NT, Windows 2000, and Windows XP (both Professional and Home edition). This is not the case for Windows 95 and Windows 98. I haven't checked it for Windows ME. I also haven't tested this on other platforms. Currently, on the indicated platforms timing of visual stimuli presentation in HTML pages is very accurate: A light sensor attached to a conventional computer monitor connected to a oscilloscope indicated in time appearance of the stimulus in 99% of the presentations, when SOA's >= 33msec (result for MSIE6.0; not tested in other browsers). Response times registration seems to be very accurate as well: mouse button clicks seem to be captured at least every 10 msec in MSIE6.0. This is much better than the 30 msec of keyboard which are often used in some subfields of experimental psychology (notably developmental psychology). The accuracy is likely to depend on the hardware (i. e., mouse type/brand) however. I haven't actually rigorously evaluated this with measuring equipment - beware. However, we did reproduce results previously reported in the literature, with a visual selective attention paradigm. Auditory stimuli currently cannot be presented with reliable timing directly from DHTML as far as I've tested. The start of a .wav is inconsistent and has long delays. I haven't yet considered the SMIL aka HTML+TIME extension though).

I think it should be possible to develop COM objects to deploy other functionality (like trigger generation on a parallel port for synchronization with physiological recordings etc.), in the same way a COM object can be used to save recorded responses to file -- see the HTA link below.

With newer versions of MSIE new security 'enhancements' are implemented, which may present warning windows about code execution on the page. Some are solvable by modifying the settings in the internet options menu.

Below you find links to some of my files that can be useful for understanding what you can do with DHTML and how to do it. Some example experiments are given (subject/participant instructions are in Dutch), but the code is extremely opaque (I apologize). If I find the time I will make it better.

I presume you know about HTML and manipulation of the document elements using the Document Object Model and JavaScript. If not, tutor yourself with Thau's JavaScript tutorial and Advanced JavaScript tutorial (takes about 2 days for a programmer, a week for an R/SPLUS/OCTAVE/MATLAB programmer, and three weeks for a novice programmer).

Key to programming experiments is an event sequence in which each event in a trial is handled by an event specific handler (a JavaScript function). Each event handler elicits the next event. Timing is done using the setTimeout function of defined in the HTML Document Object Model. A simple example template is given below:

View template

Key to accurate timing is to have as little computations done as possible during time critical events. If computations are necessary (e.g., if the next trial depends on the response of the subject in the previous trial), put them at the end of the trial (the endTrial event handler), and use the time recorded in each trial to check the event timing. If any computations can be done on before hand, like for example generating randomized SOA's, ITI's and the like, it is certainly advisable to do so.

To avoid timing inaccuracy, it is advisable to close down all processes running in the background that are not essential system processes. This includes closing all unnecessary programs, and especially network communication dependent processes. Of course, this makes it less suitable for experimenting over the Internet, but that is the case with any experimentation software! Furthermore, not all experiments are time critical, or at least not with 10 msec accuracy.

Note that this type of programming is highly non-linear, and brings you back to the days of goto statements of BASIC, and so can become difficult to follow (spaghetti) and opaque. I haven't found another technique yet. But I think JavaScript does allow for more advanced object oriented techniques that will make your code more understandable and reusable. Some day, if I have more time, I might pursue that...

The links I promised:

  • HTA: HTML Applications - or making, saving and writing to text files from within webpages on a Windows platform.

  • Starting page that records subject characteristics and lets the experiment leader start different blocks of an experiment. All blocks started can be stopped by pressing the escape key ('Esc') on your keyboard. After stopping, a window will appear complaining about a broken link so to speak, this is not erroneous, as the programs were intended to run only locally and not over an IP-connection (I am to lazy to change it). The popup-window may cover you entire screen (which was intended, but due to security issues Microsoft changed this behavior in MSIE updates), if this is the case you may close the window by pressing Alt-F4.

  • Time estimation training block of a time estimation experiment: after an instruction alert box, it presents a square (blue or red) for a certain time (the 'example'), then another one (red or blue) and the subject is required to press the left mouse button after the same amount of time has elapsed as the duration of the example. The subject receives feedback ('way too early', 'too early', 'good', 'too late', 'way to late') after each trial. Three different example durations are practiced in increasing order. To start the block you first have to press the right mouse button.

  • Another time estimation training block of a time estimation experiment: same as above, except that the order of example durations is randomized.

  • The actual time estimation experiment No feedback, except at the end of the block (intended for the experiment leader). Instructions are in Dutch. If you press the escape key (Esc on your keyboard), the experiment will be stopped. The data recorded are written to the clipboard ==> if you open for example Notepad, and choose Paste in the Edit menu (or press Ctrl-V but do not accidentally press Ctrl-C), you will past the table of times that were recorded. This is not an ideal way to save your data. Other options are: sending it to a form-process cgi script on a server (but it is advisable to close down all internet connections during the experiment if timing is extremely critical), or using so called HTML applications (see the link above).

  • Posner-task exogenously directed visual selective attention implements a version of this famous task, including the presentation of feedback in terms of the RT in msec, or 'error' ('fout') if the subject responded when he shouldn't have, or vice versa. This is the version with which we could replicate a number of findings in Possamai, C. A. (1986). Relationship between inhibition and facilitation following a visual cue. Acta Psychologica, 61 243-258.

  • Another version of the same Posner-task Except for the differences in cue- and target-stimulus, I'm not sure what else is different.

  • MaestroMind: Just shows some cool effects, but is not really an experiment (although it can be used to track user thought pattern over the Internet). It ain't finished yet.

  • soccer: actually an assignment for a programming course for Cognitive Science master students. More AI related than psychology.

Documentation on the Document Object Model as it is implemented in MSIE can be found at msdn .

I definitely appreciate feedback, suggestions, links, and your experience! Please send it to rgrasman•{at}•uva•nl