+ All Categories
Home > Documents > an operant chamber control system by Rudolf Cardinal...

an operant chamber control system by Rudolf Cardinal...

Date post: 22-Jul-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
94
Whisker an operant chamber control system by Rudolf Cardinal Copyright © 1999–2000 Rudolf Cardinal All rights reserved http://www.pobox.com/~rudolf/whisker User Guide 30 March 2000
Transcript
Page 1: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker

an operant chamber control systemby Rudolf Cardinal

Copyright © 1999–2000 Rudolf CardinalAll rights reserved

http://www.pobox.com/~rudolf/whisker

User Guide30 March 2000

Page 2: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide Contents 2

PART 1. INTRODUCTION 6

1.1 Synopsis 6

1.2 Description 6

1.3 Advantages 6

1.4 Disadvantages 7

1.5 Cost 8

PART 2. PURCHASE AND INSTALLATION 11

2.1 Shopping list 112.1.1 Computer 112.1.2 Digital I/O hardware 112.1.3 Other hardware 122.1.4 Software 132.1.5 Notes regarding large systems 13

2.2 Hardware installation 15

2.3 Software installation 182.3.1 Installing Windows NT 182.3.2 Installing Amplicon drivers 182.3.3 Installing Whisker 182.3.4 Installing programming languages 19

2.4 Uninstalling Whisker 19

2.5 DANGER – Critical devices 20

2.6 Wiring map for Amplicon boards 22

PART 3. THE WHISKER SUITE OF PROGRAMS 23

3.1 Overview of installed software 23

3.2 The WhiskerServer console 243.2.1 The left-hand tree 243.2.2 Views that pertain to the server as a whole 243.2.3 Views that pertain to a single client 273.2.4. The menus 293.2.5 The configuration dialogue boxes 323.2.6 Keyboard shortcuts 33

3.3 The WHISKERSTATUS status report program 34

3.4 The WHISKERCLIENT test client 35

3.5 The WHISKERRESET utility 36

3.6 Performance considerations 36The problem 36The way Whisker works 36If the computer is slow… 36Suggestions 38

Page 3: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide Contents 3

Other possible approaches 38Schematic of timer accuracy 40

PART 4. THE SECOND-ORDER SCHEDULE: A PROTOTYPICAL TASK 41

4.1 Introduction 41

4.2 Specifications 41

4.3 Before you begin: setting up a database 42Why? 42Copying the database that is supplied 42Configuring an ODBC data source 42Creating a personalized shortcut to SecondOrder 43

4.4 Running the task 43

4.5 Using the data 46

4.6 Inner workings of the program 47

PART 5. CLIENT–SERVER COMMUNICATIONS 49

5.1 Introduction 49

5.2 Programming tasks: design principles 49

5.3 Communication: design principles 50

5.4 Format of messages that pass between a client and the server 51

5.5 Events: the core of the system 51

5.6 Exploring the system with WhiskerTestClient 51

5.7 Two ways of communicating: a general-purpose and an immediate-response system 52

5.8 Ensuring network responsiveness 53

5.9 ‘So how on earth do I make a socket?’ 53

5.10 Key messages 54ClaimLine 54SetState 54ReadState 55RequestLineEvent 55RequestTimerEvent 55Event 56SetLineAlias 56SetSafetyTimer 57

5.11 Controlling groups of lines 58

5.12 Getting rid of events, timers and lines; shutting down cleanly 59KillEventByLine 59KillTimer 59KillEvent 59KillAllEvents 59KillAllTimers 60

Page 4: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide Contents 4

RelinquishAllLines 60ShutDown 60

5.13 The two-socket system 62ImmPort 62Code 62Link 62

5.14 Two-socket system: sequence of events 63

5.15 Status information and niceties 64WhiskerStatus 64ReportName 64ReportStatus 64TestNetLatency 64RequestTime 65

5.16 Other messages originating from the server 66Info 66SyntaxError 66RequestRefused 66Fault 66Warning 66Ping 67

5.17 A reminder about non-local machines 67

PART 6. WRITING CLIENTS (BEHAVIOURAL TASKS) 68

6.1 Choosing your programming language 68

6.2 Styles of programming for behavioural tasks 68Types of task and appropriate programming models 68

6.3 Programming benefits of Whisker’s design 70Keeping it simple 70Naming your events 70Events: a comparison to Arachnid 70

6.4 VBRatioClient: a Visual Basic example 72About VBRatioClient 72What to do if you want to develop this into a task of your own 72Simple networking with Visual Basic 72From simple networking to a behavioural task 74Comments on the suitability of Visual Basic 75

6.5 Networking in Perl 77Obtaining and installing Perl 77Writing code for Perl and running Perl programs 77A simple TCP client: implementing a status program in Perl 77Comments on the suitability of Perl 78

6.6 SimpleCPPClient: a C++ console-mode example 79About SimpleCPPClient 79Learning C++ 79Building programs in C++ 80An introduction to WhiskerClientLib 80Comments on the suitability of C++ 80

6.7 WhiskerClientLib – a library for writing C++ clients 81

Page 5: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide Contents 5

Classes to help you write clients 81Creating console-mode C++ applications for Whisker 84Creating Windows-based C++ applications for Whisker 84Creating a behavioural task using the library 84Debug and Release mode in Visual C++, and the Whisker client library 84

6.8 A few last suggestions 86

PART 7. DATA COLLECTION: PRINCIPLES AND PRACTICE 87Know the rules 87Databases 87Summary of database principles 88A concrete example: Microsoft Access 97 88Getting data out of a database 88Getting data into a database 89Recovering data from old applications 90

PART 8. LIBRARY OF BEHAVIOURAL TASKS 92

8.1 Second-order IV self-administration 92

PART 9. FUTURE IMPROVEMENTS, KNOWN PROBLEMS 93

9.1 Future additions: server-side 93

9.2 Future additions: client-side 93

9.3 Known bugs 93

PART 10. ACKNOWLEDGEMENTS AND BIBLIOGRAPHY 94

Page 6: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide I. Introduction 6

Part 1. Introduction

1.1 SynopsisWhisker is a software system designed for controlling digital input/output devices. Itsprincipal function is to control operant chambers for behavioural experiments. Whisker isbased on the client-server metaphor: a server program is responsible for dealing with thehardware, while many clients can communicate with this server simultaneously, each im-plementing a specific behavioural task.

Whisker was first used in the Behavioural and Cognitive Neuroscience Group of the De-partment of Experimental Psychology, University of Cambridge, UK. It was designed tobring a level of power and flexibility to operant chamber control that was previously un-available in this laboratory, while dramatically cutting the cost of such a system.

1.2 DescriptionThe system is based on standard PC-compatible computers running Microsoft WindowsNT. Standard digital input/output (I/O) control hardware from an electrical engineeringcompany is added. Proprietary hardware is avoided to minimize cost.

The Whisker server controls the digital I/O hardware directly, and treats each input andoutput line as a resource to be managed. Clients communicate with the server via theTCP/IP network protocol, and may request the use of a set of I/O lines, typically to con-trol one or more operant chambers. Each client then instructs the server to switch outputlines on or off, and asks to be informed whenever an input line goes on or off by means ofevents. With this information, each client can implement a behavioural task.

This system was adopted in order to enable independent and different tasks to be used si-multaneously without restricting the clients to a pre-specified programming language, asthis can only reduce the flexibility of the system.

The inner workings of the system are described in full to allow you to assess its meritsand failings, and so you can program with it if you choose.

The hardware and software for a typical system are illustrated on pages 9 and 10.

1.3 AdvantagesThe use of a TCP event-driven server brings the following advantages:

1. It enables client applications to be written in any programming language that can useTCP communications. Users are therefore not tied to a particular language, client ap-plications can be as sophisticated as you wish, and programming skills will transfer toother tasks. You can use a compiled language so that syntactic errors are picked upbefore you go live.

2. The server and clients can run on different computers if desired (though this relies ongood network performance for real-time control).

3. Applications that are already geared towards TCP communications will readily lendthemselves to further extensions. One such feature built into the system is the abilityto find out your subject’s progress from another computer.

Page 7: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide I. Introduction 7

4. The communications system is designed for easy, logical programming. Particularattention was paid to avoiding the potential for programming errors that are commonin some other operant control systems, such as conflicts between timers.

5. The system can run different client applications simultaneously, allowing differenttasks to be used in different boxes at the same time. While applications may be writ-ten to control (say) four boxes simultaneously, it is easier and more useful to write atask for a single box; the system will then run four copies of this task and so everytask written for the system allows boxes to be run asynchronously without specialprogramming. You can even use one chamber for writing and debugging a new taskwithout fear of disrupting the other chambers.

The computers are standard PC running Windows NT, so they can be used for other tasks(word-processing, data analysis) when not running behavioural tasks. Depending on yoursystem’s speed, you may even be able to use the PC for other things when it is runningbehavioural tasks. You can connect your operant control computers to your local areanetwork to move data around the network, print to remote printers, etc.

In addition to some simple examples of behavioural tasks, one relatively complex task(second-order schedules of reinforcement) is supplied, together with source code. Whilethe schedule itself is not complicated, the task illustrates some of the possibilities avail-able under the Whisker system. For example, complete and unabridged data can be storedautomatically in a relational database with no user intervention, while complex mathe-matical calculations can be performed on the data to extract useful summary measures ofperformance at the time of data collection.

1.4 DisadvantagesThere are two kinds of disadvantage with the present Whisker system:

Disadvantages inherent in the system

1. Typically, clients run on the same computer as the server; thus task responsivenessdepends on the speed with which TCP messages get sent from one program to an-other within the computer. Whisker provides facilities to monitor this performance,and we consistently achieve <10 ms time resolution. However, with any multitaskingsystem, very heavy processing loads can slow this down for brief periods; it is there-fore inadvisable to run other software at the same time as the operant control systemuntil you have checked the effect of this software on your system’s performance.

2. If the control computer is connected to a network, it is potentially vulnerable to de-nial-of-service attacks from other computers on that network. If that network is theInternet, the range of potential attackers is large. This problem applies to any net-worked computer, not just the Whisker system, but the data collected via Whisker islikely to be very important to you! Similarly, it is a matter of choice whether you al-low computers outside your network to connect to your Whisker servers. (By default,other computers are allowed to ask the server for status information, but not to gaincontrol of any digital I/O hardware.)

Disadvantages of the present system that need not remain

1. Only one manufacturer’s digital I/O hardware is presently supported.

2. Devices other than simple digital I/O lines – for example, serial communications oranalogue control – are not presently supported.

3. Clients must be written in a programming language, though the choice of such lan-guages is wide. (This was a deliberate design feature, to make the system as powerfulas possible.) At present, there is no ‘special’ client that would allow you to design

Page 8: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide I. Introduction 8

behavioural tasks in graphical form with no programming skills, for example, but onecould be written.

1.5 Cost

WhiskerHardware

The cost depends principally upon the number of digital I/O lines you wish to use,whether you can make do with 5V outputs or want to cope with higher voltages, and thebalance of inputs and outputs (because high-voltage-capable output cards cost more).Every time the number of lines increases beyond the next multiple of 72, there’s an extracost, namely another control card for the computer and associated wiring boards.

We spent £1377 on our first Whisker system (72 lines of which 24 were inputs and 48were outputs), based on a £500 computer with Windows NT. More details are given inthe next section.

We now spend about £1860 on a similar system to run 6 operant chambers, using 48 in-puts and 48 outputs and equipped with an uninterruptible power supply (UPS) for thecontrol computer.

(To equip a whole group with, say, 36 operant chambers, it would be possible to buy anindustrial PC to control up to 576 lines. However, we prefer to buy several smaller sys-tems. A hardware failure is less disastrous and you end up with more computers in thelab.)

Software

Again, the price depends on what you want to do. A minimum would be £41 for Win-dows NT Workstation, plus Whisker. The price of Whisker itself has yet to be set, but isexpected to be ~£500 per copy. For software development, you might want to add VisualC++ (£34) or Visual Basic (£34).

Alternative systemsArachnid

Arachnid (Cenes Cognition Ltd, Cambridge, UK) costs about £8000 for a 6-box system.Arachnid runs on Acorn Archimedes series computers and is an extension to BBC BA-SIC. At the time of writing it remains the main system in use in our lab. However, thecomputers are no longer being produced and are of little use for other tasks. The languageis simple but is interpreted, so errors are often discovered at run-time. Controlling multi-ple boxes simultaneously is fairly easy; controlling them asynchronously is hard, andrunning an arbitrary mix of behavioural tasks is not possible.

Med PC

Med PC (Med Associates, VT, USA) costs £5000–£6000 for a 6-box system. It interfacesvery easily to operant chambers from the same company. Tasks can be run independentlyof each other, and the computer can be used for other things. However, it doesn’t run un-der Windows NT at present (using Windows 95/98 instead) and we wouldn’t trust data toWindows 95. It uses a simple programming language, but this lacks some flexibility andexperienced gained with it cannot be used in other programming areas. It appears slightlydifficult to control boxes in groups.

Page 9: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

WhiskerServerhardware

Client:Second-order IVself-admin, box 0

Client:Second-order IVself-admin, box 1

Client:Yoked second-order IVself-admin, boxes 2+3

Client:Five-choice task,

box 4

Client:New task being

developed, box 5

Word processor

Web browserRelational database

Analysis software

Client:WhiskerStatus information

program

Client:WhiskerStatus information

program

experimenter's office computer

computer elsewhere in the world

lab computer equipped with digital I/O boardsand connected to operant chambers TCP/IP links

via a local-area networkTCP/IP linksvia a wide-area network

TCP/IP linkswithin one computer

Examples ofother active programs

Whisker: Software Design

Page 10: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

operantchamber

digital I/Ohigh voltage / optoisolation / relay

wiring panels

operantchamber

operantchamber

operantchamber

digital I/Olow voltage wiring / distribution board

digital I/OISA card (in computer)

cables connectingoperant chambers

to I/O cards

computer

uninterruptiblepower supply (UPS)

(recommended)

24-28 V DC power supplyfor operant chambers

and high-voltage panels

Whisker: Hardware Implementation

to mains

Page 11: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide II. Installation 11

Part 2. Purchase and installation

2.1 Shopping list

2.1.1 ComputerYou will need a PC-compatible computer with one free ISA slot for every 72 controllines. (Note: Popular modern motherboards frequently have no more than two such slots,limiting you to 144 lines; if you need more than 144 lines per computer, you will need tobuy a specialized motherboard, such as for an “industrial PC”.)

I used the following: an AMD K6-2/450 system with a Gigabyte GA-5AX motherboard,128 Mb RAM, 8 Gb hard disk, 8 Mb AGP video card, PCI Ethernet card, 48-speed CD-ROM and 15” monitor. This set us back about £510 (Insight UK Ltd; September 1999).

Since computers are getting faster and prices dropping like there’s no tomorrow at themoment, these prices will not be correct when you read this! Nevertheless, to give you anidea of what you might need, here’s what we first bought:

Item Component [with Insight product code] Price (Sep 1999).Insight UK Ltd

Motherboard Gigabyte GA-5AX ATX 100 MHz m/b [MBGI008] 48.99CPU AMD K6-2/450 [PRAM025] 57.99Heatsink/fan for CPU [HS60] 9.99RAM 128 Mb DRAM, 100 MHz compatible [DMS1281] 79.99Video card Diamond Speedstar A50, AGP 8 Mb [VIDI017] 29.99Network card DLink DE-528CT PCI Ethernet card [DLK5840517] 11.99Hard disk drive Maxtor DiamondMax 4320 8.4 Gb IDE HDD [HAMX020] 73.99Floppy disk drive 3.5” 1.44 Mb Sony floppy drive [FD5-S] 9.99Case Mediaforce 235W ATX case [CS17] 29.99Monitor ATI ProVista E44 15” monitor [MNAD003] 99.00Keyboard Cherry Win95 105-key PS/2 k/b [KECH002] 17.00Mouse Microsoft basic PS/2 mouse [MS803G637] 10.99CD-ROM drive Creative 48× CD-ROM IDE [BW48] 28.00

Uninterruptible powersupply (UPS)

APC Smart-UPS 700inet [APC2700221]Note. In Europe (230 V mains supply) this will supply twocomputers for ~40 min without their monitors, or ~15 minwith both monitors. If this isn’t sufficient, choose anotherUPS.

179.99

Insight UK Ltd are at http://www.insight.com/uk.

An uninterruptible power supply (UPS) is important to protect your system against mainspower failure, especially if you are using potentially dangerous devices such as intrave-nous infusion pumps; in this situation, we consider a UPS essential (see page 19). Usingan UPS is also good practice because it prevents data loss.

2.1.2 Digital I/O hardwareThe hardware comes from Amplicon Liveline Ltd (http://www.amplicon.co.uk/, tele-phone 0800–525–335, technical support 01273–608–331, next-day delivery is usuallyavailable).

For each 72 lines, you will need one ISA card and one distribution board. For high-voltage (>5V) devices, you will need up to three I/O panels, each with 24 lines. The vitalcomponents are

Page 12: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide II. Installation 12

Item Provides Ampliconpart no.

Price each(Sept 1999)

PC272E ISA digital I/O board Interfaces the computer to up to 72 in-put/output lines

909–562–33 £99

78-way cable Connects the computer to the distributionboard

909–663–49 £61

EX233 distribution board A bridge between the computer and thehigh-voltage input/output panels, or canaccept 5V inputs/outputs directly

909–663–33 £99

If your inputs and outputs all use TTL voltages (5 V), that’s all you need. If you wantother systems, as we do, you may connect up to three 24-line panels to each distributionboard. Amplicon supply a 24-way output panel, a 24-way input panel and a mixed 16 in-put/8 output panel, which you may install in any combination. They are:

Item Provides Ampliconpart no.

Price each(Sept 1999)

EX213 output panel 24 outputs of several kinds (see below). 909–663–63 £199EX230 input panel 24 inputs of several kinds (see below). 909–663–73 £129EX221 mixed panel A combination of the above, with 16

inputs and 8 outputs.909–663–83 £149

37-way ribbon cable Connects each input/output panel to theEX233 distribution board.

908–920–05 £20

Technicalnote

Input specificationsInputs operate in “low voltage” mode (–5V to +1.5V low, +4V to +12V high) or “high voltage” mode (–15V to +2V low, +10V to +30V high), with or without optoisolation, chosen for each input individually. Op-toisolation is recommended, and the voltages quoted are for the optoisolated mode.

Output specificationsThe output lines can operate in several modes. (1) “TTL” mode provides TTL voltages (approx. 0V low,+5V high) for low-power devices, such as transistors. If you need to switch high-power devices electroni-cally, you can use these lines to drive the transistor; this is what happens in the Cenes output panels. (2)“Source driver” mode does something slightly mysterious and will be ignored. (3) “High level logic output”mode provides +0.7V (off) or +23V (on) and will drive devices up to 100 mA directly. (4) “Isolated relaycontact output” mode switches a relay on the circuit board. When the output is switched on, the relay con-tact is closed. (There is a second relay contact that behaves oppositely.) This can obviously switch high-power devices which use their own power supply, and is the easy way to switch devices that need more than100 mA.

2.1.3 Other hardware

DC power supplies

• The Amplicon output panels need a 24 V DC power supply.• The distribution board and input panels can draw power from the computer, and this

is recommended.• Presumably, you will have a DC power supply for your operant chambers.

MountingThe Amplicon boards use DIN rail mounting, which is very cheap. The cards clip ontothe rails. Attach the rails to something convenient, like a wall.

Item Provides RS part no. Price each(Sept 1999)

Deep top hat DIN rail (35 mmwide, 15 mm deep), punched

Something to clip the Amplicon panelsto.

176-703 £3.88 permetre

RS Components are at http://rswww.com/

Page 13: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide II. Installation 13

2.1.4 Software

RequiredThe Amplicon cards come with driver software, which is needed. The only software youmust have is an operating system and Whisker. Whisker runs under Windows but has notbeen tested on Windows 95/98, which we consider too unreliable for the task. It waswritten for Windows NT 4.0, and has not yet been tested with Windows 2000 (though Ianticipate no problems).

Item Supplier Price each(Mar 2000)

Microsoft Windows NT 4.0 Workstation – media [CD] University of CambridgeComputing Service [3762]

£5

Microsoft Windows NT 4.0 Workstation – license University of CambridgeComputing Service [5316]

£36

Whisker – ?University of Cambridge Software Sales are at http://www.cam.ac.uk/CS/Support/software.html

They do not supply customers outside the University of Cambridge.

OptionalTo take full advantage of the Whisker system (i.e. to write your own tasks), you will needa programming language that supports TCP/IP communications. This is discussed ingreater detail later in this Guide, but Visual C++ and Visual Basic are two useful pro-gramming languages:

Item Supplier [code] Price each(Mar 2000)

Microsoft Visual C++ 6.0 Professional – media [CD] University of CambridgeComputing Service [4749]

£14

Microsoft Visual C++ 6.0 Professional – license University of CambridgeComputing Service [5114]

£30

Microsoft Visual Basic 6.0 Professional – media [CD] University of CambridgeComputing Service [4708]

£14

Microsoft Visual Basic 6.0 Professional – license University of CambridgeComputing Service [5112]

£30

Perl for Win32 ActiveState freeActiveState supply Perl at http://www.activestate.com/ActivePerl/

2.1.5 Notes regarding large systemsAt the moment, if you need more than two 72-line cards, you will need more than twoISA slots. Amplicon are, however, developing a PCI card (they estimate 4–6 months fromJanuary 2000); since modern motherboards have several PCI slots, this should alleviatethe problem.

In the meantime, you might consider an industrial computer. Amplicon’s design consistsof a chassis, a backplane (they sell one with up to 14 ISA slots) and a single-board com-puter which plugs into the backplane. At the time of writing (January 2000) you can getsingle-board computers up to dual Pentium-III 700 MHz, which should be enough.

If the number of ISA slots is no longer the limit, how many cards can use? Amplicon’sdriver software imposes a limit of 8 cards, giving you up to 8 × 72 = 576 lines.

Whether you can use up to the software limit of 8 cards depends on the other devices inthe computer. Each card will need a unique I/O base address, and very probably a uniqueinterrupt. Base addresses and interrupts are also used by things like serial ports, Ethernetcards and so on. But if you use a PS/2 mouse and keyboard, disable the serial (COM)ports, use a networked printer and disable the printer (LPT/PRN) port, use PCI or on-board video, a PCI network card, and as many as possible of your PCI devices share in-

Page 14: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide II. Installation 14

terrupts, you should certainly manage 5 or 6 cards in an industrial computer (360 or 432lines).

With low-voltage (5V TTL) devices, each card may be configurable in any input/outputmix, but with 24V devices, which we use, they are configured in blocks of 24. Each blockof 24 may be all inputs, all outputs, or 16 inputs and 8 outputs. So each 72-line card cantake the following input/output mixes: 72/0, 64/8, 56/16, 48/24, 40/32, 32/40, 24/48,16/56 (the only combination not possible is 8/64).

Our intravenous self-administration boxes have up to 6 inputs and 8 outputs each. So afull 8-card system should be able to run 41 of these boxes (with two spare input lines�)… and if you have fewer devices attached, you’ll get more boxes. So you can buildlarge systems.

Caveat. For a system this large, it would be a bit cheaper to get an ‘industrial’ computer(1 @ <£1,500?) than the necessary number of smaller-capacity PCs (4–5 @ £500 each).On the other hand, I generally prefer to have lots of cheap PCs scattered around runningsmaller systems – if one crashes, you lose less; also, you have more computers hangingaround to do other things with.

Page 15: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide II. Installation 15

2.2 Hardware installationTurn everything off first! (In particular, never try to add an expansion card to a com-puter that is on, or remove one.)

Please note that I may confuse +24V and +28V in this discussion – this is because theprecise voltage isn’t terribly important. As long as everything’s the same, you can useeither. (Note also that Med Associates persist in referring to +28V and –28V lines, givingthe impression that there’s a 56V potential in total. This is nonsense; what they refer to as–28V, or sometimes as “28V ground”, is 0V.)

1. Configure the PC272E card(s) and install them in the computer.There are two things to configure on the card: the I/O base address (default 0x300) andIRQ (default 5). See the electronic manual for details of how to set these(\manual\pc272e.pdf on the Amplicon CD-ROM).

These settings need to be chosen to avoid conflicts with other cards installed in the com-puter; if you use more than one Amplicon board you will certainly have to change thejumper settings for at least one board. In a plain PC system, a single-board installationwill probably work without changing anything.

We generally use two PC272E cards, and as IRQ 5 is normally used by a network card inour computers, we use the following settings:

First card: IRQ 10, base address 0x300

Second card: IRQ 11, base address 0x320

2. Connect the power supply to the EX233 distribution board and connect it to thePC272E card with the 78-way cable.

To simplify wiring, use the “shared bus” facility of the distribution board. Eight connec-tors on the EX233 board, collectively labelled SK3, are provided for your own use.Whatever you connect to these is connected via the ribbon cables to an equivalent blockof 8 connectors on any input/output panels that you connect to the distribution board(where they are labelled SK5 to confuse you).

We need to share out +28V and 0V to all the panels. So wire 0V (GROUND) from thepower supply to pins 1–4 of block SK3 on the EX233 board, and +28V from the powersupply to pins 5–8. (This is an arbitrary choice, but I will assume you’ve done this fromnow on.)

3. Configure the input panels.I will give examples for Med Associates inputs, which, when activated, short their controllines to ground. Here’s how we arrange things:

• To use 24 V inputs, disconnect jumpers J7–J30. Don’t lose the jumpers; attach themto one pin only.

• To use optoisolated inputs, ensure jumpers J31–54 are all set LEFT.• So the board takes power from the computer, ensure jumpers J1–J6 are all CON-

NECTED.• So the ground connectors are all independent, disconnect jumpers J55–75. (Again,

don’t lose the jumpers!)• So the +28V lines are all shared, connect A0–7, B0–7 and C0–7 together on the “SK7

I/P” block. Pieces of paperclip are great for this, or you could use a single piece ofwire. Then connect those lines to a +28V line (for example, pins 5–8 of SK5 shouldbe attached to +28V if you have wired up the EX233 board as I suggested). Don’tconnect up the pins marked “0V” or “5V” in this block! You’d be shorting 0V or5V to 28V, probably with some sparks.

Page 16: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide II. Installation 16

(This is not as neat as we’d like – there’s wire everywhere – but this is because the engi-neers at Amplicon expect people to share a ground wire and have separate +28V controllines, not the reverse. As optoisolators don’t work if you plug them in backwards, wehave to share the +28V lines by hand.)

You will then be able to connect the data lines from the Med Associates devices to A0–7,B0–7 and C0–7 on the SK8 0V block (one line per device). Ensure that the Med Associ-ates devices use the same ground as the rest of the system.

4. Configure the output panels.Med Associates devices are turned on by shorting their control lines to ground (0V).

• To use relay outputs, set J12–J35 to the RIGHT.• To supply ground to all the relay circuits, connect ground (e.g. SK5 pins 1–4) to “A

GND”, “B GND” and “C GND” on the block labelled SK6.• To provide power to operate the relays, connect +28V (e.g. SK5 pins 5–8) to “A

VCC”, “B VCC” and “C VCC” on SK6.

Relays can be thought of as follows. They have a common (COM) pin. When there is nopower applied to the relay, the COM pin is connected to the normally closed (N/C) pin,but not to the normally open (N/O) pin. When power is applied, this reverses (so N/O isconnected to COM and N/C is disconnected).

All the relays act independently and have separate COM lines, one per relay, but to sim-plify things for Med Associates devices, we want a shared ground:

• Connect all the COM pins together on the two long blocks (A0–7, B0–7 and C0–7).Then connect these lines to a ground line (e.g. pins 1–4 of SK5).

Make sure that your boxes use the same ground, too (i.e. that they run off the same powersupply).

Then you can connect your device control wires to the N/O pins. This will keep your ap-paratus off by default. If you want it on instead – for example, if your supplier has wired adipper so it’s up by default and you want it down – you can wire it to the N/C pin instead.

If you use the EX221 mixed input/output panels (which we haven’t, yet), note that thefirst 8 lines are outputs (relays), and the last 16 are inputs.

5. Connect each of the input/output panels to the EX233 distribution board with the 34-way cables.

The three columns on the EX233 board are labelled X, Y and Z; you may find it useful tolabel the cables going to the input/output panels accordingly. It helps when wiring thingsup later.

6. Connect your apparatus.

See above. Plan your wiring diagram before starting (see page 22). To remind you:

• Connect Med Associates inputs to A0–7, B0–7 and C0–7 on the SK8 0V block.• Connect each output control wires to either the N/O or the N/C pin of one of the re-

lays.• Ensure that output ground wires are (eventually) connected to the COM pin of the

same relay.

Page 17: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide II. Installation 17

7. Plug the computer into the uninterruptible power supply (UPS).

8. Ensure you do not place subjects in the operant chambers until you have installed thesystem, tested the hardware and read the discussion of life-threatening devices on page 19.

Tip If you don’t connect the ground wires to the operant boxes, you may experience the following symptoms:(1) levers and dippers may click slightly and not work – surprisingly, lights can be OK; (2) you will hererelays clicking spontaneously as they ‘float’; (3) when you turn the power supply on after it’s been off for awhile, ungrounded inputs may light up the optoisolator LEDs as stray capacitance discharges.

Technicalnote

The Amplicon EX230 input cardSK5 is a ‘user’ connector block with 6 connections on it. It is connected via the 37-way ribbon cables to theequivalent block on the EX233 card. This is handy for providing external power and data lines that areshared between all cards. SK6 provides power and ground to the board itself (and is usually not needed asthe 37-way connector provides power; see notes for J1–J6 below). SK7 is the I/P (input) connector block.Beware: there’s a stray 0V connector in the middle, and a 5V connector at one end. SK8 is the 0V (ground)connector block. J1–J6 connect power and ground lines from the 37-way D connector to the VCC/GNDconnectors that provide power for the board itself. J7–J30 select high or low voltage ranges for each of the24 inputs. J31–J54 select optoisolated or logic mode for each of the inputs. J55–J75 short the ground linestogether. They are in three blocks of 7, which connect the ground lines of the three blocks of 8 connectorstogether.

The optoisolators do not work if you reverse +28V and 0V.

Input voltage rangesIn the ‘high-voltage’ range, 10–30V is considered ‘on’ or ‘high’, and anything less is considered ‘off’ or‘low’. If you want to use 5V inputs instead (where the range 4–12V is considered ‘high’), connect the jump-ers.

Outputs on the EX213 panelThe alternative to relays is logic output. For blocks B and C, this is always high-voltage (0 off, 24V on). Forblock A only, you can choose high-voltage or TTL voltage (0 off, 5V on) using SK2. The text assumes youare using relays.

Technicalnote

Med Associates inputsActivating a device shorts its data lead to ground.

So the Amplicon board needs to be set to high-voltage, optoisolated mode. • Then all the +28V linesneed to be connected to +28V (it’s easy to do this by inserting paperclips into the SK7 I/P connectors!); •then the ground (SK7, 0V) connectors need to be disconnected from each other by removing J55–75; • thedata leads can then be wired to the ground connections (SK7). Thus when the device shorts its data lead toground, the circuit is completed and the optoisolator LED illuminates.

I can’t think of an alternative, but it may be worth asking Amplicon if they can redesign the card soshorting the I/P lines together is possible.

Page 18: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide II. Installation 18

2.3 Software installation

2.3.1 Installing Windows NTIf you don’t know how to install this, find an expert. You will want to install WindowsNT Service Pack 3 or greater (5 or greater for large hard disks).

Tip When you install Windows NT, it creates a user account called Administrator, and you set the password forthis account. Never lose this password. It is also a good idea to add a new user (e.g. “Rudolf”) and subse-quently do all your work in this user, so that you always have the Administrator account to fall back on. Youmay or may not want to give the new user the power and responsibility of an administrative account.Choose Start → Programs → Administrative Tools (Common) → User Manager to add users.

You should log in to Windows NT as an Administrator for the installation of the rest ofthe software – administrator authority is required to install TCP/IP, the Amplicon driversand ODBC (supplied with Whisker).

You must install and configure TCP/IP (found under Control Panel → Network → Pro-tocols), even if you have not installed a network card, because Whisker uses TCP tocommunicate.

Tips Whenever you make major changes to your computer’s configuration, update the Rescue Disk once you aresure the new changes worked and the system is stable. Run rdisk.exe and choose Update Repair Info,then Create Rescue Disk.

After installation, choose Control Panel → Regional Settings and configure your computer for the countryyou live in. It makes dates more consistent.

If you would like to be able to right-click a folder and bring up a command prompt already in that directory,run Windows NT Explorer and choose View → Options → File Types. Choose “Folder”, and click Edit →New. In the Action box, fill in “Command prompt here”. In the Application used to perform action box, fillin

C:\WINNT\system32\cmd.exe /k cd "%1"or a different directory if you have installed Windows NT elsewhere. Click OK.

2.3.2 Installing Amplicon driversInsert the Amplicon CD, which comes with the PC272E cards. It will auto-run.

Choose “Software drivers and manuals” from the main menu. Choose “32-bit drivers forthe PC272E card” from the matrix presented. The drivers will be installed. Note that themanuals for the card are also available in this matrix. To read them, install Adobe Acro-bat Reader from the CD. The drivers have their own, very detailed manual (amp-dio32manual.pdf).

Run Control Panel → Amplicon DIO and configure each of your cards. The first card iscalled DIO 0, the second DIO 1, etc. They will be PC272E cards, and you should set theinterrupt and base address settings to match those you physically configured the cards to.You will then need to reboot the computer.

2.3.3 Installing WhiskerInsert the Whisker CD (or floppies, or switch to theWhisker installation directory if you have a network in-stallation version).

Run setup.exe and follow the on-screen instructions.

Once installed, choose Start → Whisker → Whisker Server to run the server, and config-ure it for your particular mix of input/output panels. (This is on the menu underServer/Configure Hardware, and is described on p30.)

Page 19: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide II. Installation 19

2.3.4 Installing programming languagesFollow the instructions that accompany each product.

2.4 Uninstalling Whisker

If you ever want to uninstall Whisker, click Start → Settings → Control Panel →Add/Remove Programs, choose Whisker, and click Add/Remove.

Page 20: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide II. Installation 20

2.5 DANGER – Critical devicesWe have discovered one potentially life-threatening eventuality. This relates to theuse of devices which are potentially fatal if switched on inappropriately – particularly in-travenous infusion pumps.

At the core of the Whisker system is a set of digital I/O boards that control your devices,and a server program that controls the I/O lines. Whenever you start or stop the server, itmakes sure that all devices are off. While the server is running, it does its best to ensurethat devices are never left switched on by mistake, using a number of safety features.

So far, so good. But when the computer is first turned on (or hard-reset), output re-lays are switched ON (see the Technical Note overleaf for an explanation). As soon asyou run the Whisker server for the first time, everything is OK. But consider the situation:your tasks are running, there is a power cut; everything switches off. The power is re-stored; the computer powers up; all the devices are switched on, including i.v. pumps; be-fore the computer finishes booting the animals are dead of an overdose.

We’d thought this through, and our computers had ATX motherboards that did not switchon when power is applied; they need someone to press the ON button. We though wewere OK, but we had never tested the effects of very brief (<0.5 s) power cuts; this didcause the computer to reset, and all devices went on.

The solution we have adopted is twofold:

1. Install uninterruptible power supplies for the control computers. This preventsthe danger from power cuts.

2. Never turn on or hard-reset the control computer with subjects in the operantchambers and the operant chambers powered on. Run the server software at leastonce first. (You can turn the computer on if you switch the box power supply off untilthe server is loaded, or you can take the rats out until the server is loaded, or what-ever.)

There is a third option to increase safety, which is to wire the power to the critical devicesthrough a fail-safe mechanism (discussed overleaf and in the section on server configura-tion).

Whisker is a system designed for research purposes only, and should never be usedto control medical apparatus or other devices that could endanger human life.

Page 21: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide II. Installation 21

Technicalnote

Why does this problem occur?When the Amplicon PC272E cards power up, they reset their 82C55 controller chips. When the 82C55 chipresets, it places all its lines into input (high-impedance) mode. When a line is set to input mode, a set ofpull-up resistors on the PC272E card bring the voltage high, and if an output devices is connected to thisline, it will be turned on. These resistors are not configurable (unless you feel like resoldering the board),and the net result is that the outputs stay on until the software reconfigures the lines for output.

Sources: Peter Adams (Amplicon Technical Support, tel. 01273–601331) and the Appendices for the71055 and 8255 controller chips on the Amplicon CD-ROM.

These are not valid solutions:1. Swapping all outputs from the “normally open” to the “normally closed” relay pins. In this situation,

short power cuts are safe, but now long power cuts are dangerous (the box power supply comes on butthe computer stays off).

What are the possible solutions?1. Use different digital I/O cards. [Impractical for us.]2. Rewire the existing cards. [Difficult.]3. Use a motherboard that guarantees never to power on unsupervised. [Very hard to guarantee.]4. Plug the computer and/or DC power supply into a trip switch, so a mains power cut cuts power to eve-

rything until reset by a human. [Possible with an “industrial self-testing plug”, £48 each from RS, butnot the best solution.]

5. Wire the DC power supply for the critical devices through a fail-safe mechanism. Probably the best isto wire it through two relays such that one relay must be ON and the other must be OFF in order forpower to reach the devices. This is extremely unlikely to happen by chance (all the problems describedso far switch all the relays on or off together). The server software provides support for assigning somerelay outputs to this function. The only criterion that must be fulfilled is that the relays can take the cur-rent: the relays on the EX213 board can switch AC to 60VA and DC to 28W (i.e. 1A at 28V). [This is agood solution, and can be combined with #6.]

6. Install an UPS for the computer. This eradicates the problem and gives data protection. If you’re will-ing to spend money on a very powerful UPS, you could also guarantee DC power to the operant cham-bers, so your tasks would not even be interrupted by a power cut. [This is the best solution and can becombined with #5.]

Page 22: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

2.6

Wir

ing

map

for

Am

plic

on b

oard

sN

ote:

this

info

rmat

ion

is a

lso o

n th

e se

rver

’s li

ne d

ispla

ys (f

ar r

ight

).Th

e m

ap o

nly

show

s the

firs

t tw

o di

gita

l I/O

boa

rds.

Wiri

ng p

anel

Line

on

pane

lSo

ftwar

e lin

e#(fi

rst D

IO b

oard

)(b

oard

0)

Softw

are

line#

(sec

ond

DIO

boa

rd)

(boa

rd 1

)X

A0

072

A1

173

A2

274

A3

375

A4

476

A5

577

A6

678

A7

779

B0

880

B1

981

B2

1082

B3

1183

B4

1284

B5

1385

B6

1486

B7

1587

C0

1688

C1

1789

C2

1890

C3

1991

C4

2092

C5

2193

C6

2294

C7

2395

YA

024

96A

125

97A

226

98A

327

99A

428

100

A5

2910

1A

630

102

A7

3110

3B

032

104

B1

3310

5B

234

106

B3

3510

7

B4

3610

8B

537

109

B6

3811

0B

739

111

C0

4011

2C

141

113

C2

4211

4C

343

115

C4

4411

6C

545

117

C6

4611

8C

747

119

ZA

048

120

A1

4912

1A

250

122

A3

5112

3A

452

124

A5

5312

5A

654

126

A7

5512

7B

056

128

B1

5712

9B

258

130

B3

5913

1B

460

132

B5

6113

3B

662

134

B7

6313

5C

064

136

C1

6513

7C

266

138

C3

6713

9C

468

140

C5

6914

1C

670

142

C7

7114

3

Page 23: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 23

Part 3. The Whisker suite of programs

3.1 Overview of installed softwareWhen Whisker has been installed, it appears here:

The Whisker suite includes the following software:

• WhiskerServer, the server program.• On-line documentation, including this User Guide and a ReadMe file with reminders

on installation.• WhiskerStatus, a client used to find out the status of your subjects from another

computer. Source code is supplied for this program.• WhiskerReset, a small command-line utility to reset all your devices.

The following clients (behavioural tasks) are supplied, all with full source code:

• Second-order schedules of reinforcement. This package includes (1) the SecondOr-der task, written in C++; (2) a relational database for automated data storage, whichrequires Microsoft Access 97 (part of Microsoft Office 97 Professional); (3) a spread-sheet for displaying cumulative record graphs, which required Microsoft Excel 97.

• A simple command-line C++ client, as an example for you to extend.• A simple Visual Basic client, as an example.• A library for use in writing C++ clients.

The following third-party software is included:

• Adobe Acrobat Reader 4.05. Select the menu option to install Acrobat Reader. Thisis required to read the on-line version of the User Guide (this document).

• ODBC v3.5 (Open Database Connectivity). This is installed automatically, and isused by the SecondOrder program.

• Library files required to run Whisker software.

Page 24: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 24

3.2 The WhiskerServer consoleStart → Whisker → Whisker Server

The WhiskerServer program must be running at all times when you wish to use theoperant chambers. It is this program that actually communicates with the hardware.

However, you almost never need to interact with the server while it is running. It can pro-vide you with a great deal of information about what’s going on within your system, andcan be very helpful for wiring up the system, testing devices and debugging client pro-grams, but in day-to-day operation you can simply minimize it and forget it. (If you try toclose the server while tasks are running, thus aborting any ongoing tasks, it will complainvociferously so you don’t do it by accident.)

3.2.1 The left-hand treeThis picture shows the various views avail-able to the server. When you click on anitem on this tree, a view opens up on theright-hand side of the screen.

In addition to the ‘top’ view, there are fourviews giving a summary of the server’sstatus as a whole (‘Server status’, ‘Serverevent log’, ‘Line status’, ‘Clients’). Clickon the tree on the left to open each view inthe right-hand window.

Then, for each connected client, there aresix views giving information about just thatclient (‘Information/status’ through to ‘Ali-ases’).

3.2.2 Views that pertain to the server as a whole

The ‘top’ view

This view displays version information about the server, and that’s it.

The Server Status ViewDisplays information about the server’s network status, and how many clients are con-nected. Here’s an example:

Page 25: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 25

Since the server is accepting connections from clients, the network status shows as ‘run-ning’. The server is running on a machine named egret. The server’s IP address displays127.0.0.1 – this is the IP address which a computer can use to talk to itself with. EveryTCP/IP based program communicates using a ‘port number’ – for example, the HTTPprotocol that drives the Web runs on port 80 – and the two TCP ports that Whisker usesby default are 1333 and 1334.

Two clients are currently connected, and there is an arbitrary limit of 15. (There is no rea-son why this limit could not be increased.)

Whisker operates by asking the digital I/O boards very frequently whether anything haschanged since it last asked, a technique known as polling. The last section of this displayis updating itself every 1000 ms; in the last second, the longest time between successivepolls was 11 ms. The average inter-poll time can be calculated as 10 ms. The longest in-ter-poll time since the server was started has been 30 ms. The meaning of this informationis discussed in more detail later (§3.6 Performance considerations, page 36).

Technicalnote

Why use polling?Because the Amplicon boards cannot generate interrupts when an arbitrary input line changes state.

The Server Event LogLess than thrilling, this displays significant information pertaining to the whole server.For example, when clients connect and disconnect, and when the hardware is first initial-ized, status and error messages are recorded here. Here’s a screenshot:

Page 26: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 26

The Line Status View

Lists every digital I/O line available to the server. All boards and lines are numbered fromzero. The fields are as follows:

Field DescriptionLine# The line number.I/O Whether this is an input or an output line.State If the line is on, ‘***’ appears here. If it is off, nothing is displayed.Pegged Whether the line has been forced ON or OFF by you, the person operating the server console.

If nothing is displayed here, the line is free to be controlled by the client (for output lines) orthe physical device (for input lines).

Owner Name of the client that has claimed this lineFirst alias The name that the client first used to refer to this line. This might be something informative,

like ‘Houselight’.‘On’ event (For input lines.) The message, if any, that will be sent to the client whenever the line is

turned on.‘Off’ event (For input lines.) The message, if any, that will be sent to the client whenever the line is

turned off.Safety timer (For output lines.) For critical lines, like intravenous infusion pumps, the client can ask the

server to make sure that the line is switched on or off if the client hasn’t mentioned it for awhile. This display might say ‘OFF after 10000 ms’, for example; then if the client crashes,the server will ensure the line is not left on accidentally.

Reset state (For output lines.) When the client releases the line, the server can leave it in whatever state itwas in, ensure that it is off, or ensure that it is on. This display tells you what the client haschosen for this particular line.

Hardwaredescription

This is an aid to finding the physical connections associated with this line. If you have eightI/O boards, each with 72 lines, you might have difficulty finding line 524 – this display shouldtell you that line 524 is on board 7, channel X, line C4.

Tips Some of the field may not initially be visible. Use the scroll bars to move down or to the right.

You can resize all of the fields on any list-like display by dragging the edges of the field headings. In thismanner, you can bring the line number and the hardware description into view at the same time, which maybe very useful for wiring up a system.)

The Client Summary View

Page 27: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 27

Lists all connected clients, together with their name (supplied by the client), current status(supplied by the client), time since the client last communicated with the server, andwhether any network errors have occurred while trying to communicate with this client.

Note that clients are assigned numbers by the server (starting with 1, and ticking up for aslong as the server is running). These numbers usually bear no relationship to the boxnumber being used, or to anything else – they are merely a way of keeping clients sepa-rate. Good clients will provide a name to the server, giving more useful information:“Second-order IVSA, box 4”, for example. This replaces the “Unnamed-1”, “Unnamed-2”, etc, which the server assigns to clients before they have provided a proper name.

3.2.3 Views that pertain to a single client

The (Individual) Client Status View

Gives the client’s name (supplied by the client), status (supplied by the client), the IP ad-dress of the computer the client is running on, an arbitrary serial number, the time sincethe client last sent anything to the server, and whether any network errors have beennoted by the server while trying to communicate with the client.

The Client Event Log

This view shows significant events that pertain to this client (assuming its event log is en-abled). Not often a terribly useful view!

Page 28: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 28

The Client Communications Log

This is a display primarily for debugging, as it can accumulate huge numbers of mes-sages. It displays everything that has passed between client and server (assuming thecommunications log is on). Part of this display shows whether a ‘main’ or ‘immediate’socket was used (see discussion later); the source of the message is given as Server, Cli-ent, Server-IMM or Client-IMM.

The Timer View

Displays every timer currently in use by the client. You see the name of the timer (whichwill be sent to the client as an event when the timer expires), its overall duration, the timeleft before the timer expires, and the number of reloads left.

The Client Line Status View

The view is identical to the server line view, but only shows lines claimed by the currentclient.

Page 29: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 29

The Aliases View

The view normally lists aliases in the order they were defined. Click on the phrase “Linenumber” to sort by line number instead.

3.2.4. The menus

FileThe File menu is available all the time, but it isn’t very useful.

EditNor’s the Edit menu.

ViewRefresh all views simply starts the views from scratch, ensuringthat all the data they are displaying is up to date. You shouldn’tneed to use this, as all the views should be up to date all thetime! It’s just here in case I’ve made a programming error.

The Toolbar and Status Bar options enable you to turn on and off the toolbar (which normally lives justunder the menus) and the status bar (at the bottom of the window). The toolbar isn’t very useful, though it willat some point provide context-sensitive help. The status bar tells you the function of all the menu items (watchit as you move the mouse over the menu), which can be quite useful.

Full screen expands the server display until it fills the whole screen. Press Escape to return it to normal (oruse the menus, which are still accessible via ALT-key shortcuts). You may like to turn the status bar and tool-bar off to get even more space for the glorious displays offered by the server.

Page 30: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 30

Server

Configure hardware. This brings up a map of your digital I/Oboards, so you can inform the server how you have pluggedyours in. This is discussed below (§3.2.5 The configuration dia-logue boxes).

Configure failsafe outputs. This allows you to set up to 8 out-puts for use in controlling power supplies in a fail-safe manner,and is discussed below (§3.2.5 The configuration dialogueboxes).

Choose Stop accepting clients to prevent any more clients from connecting. This option does not affect cli-ents that are already connected. Once selected, the menu item changes to Start communications…, whichallows you to restart comms (specifying TCP port numbers in the process, but I recommend that you do notchange the port numbers unless you understand TCP/IP well – client software will not expect the change).

Log events toggles the recording of significant events relating to the server. A tick by the entry indicates thatlogging is active.

Reject all non-local connections is an option which prevents any other computer from connecting to theWhisker server. This is the highest security level, but is off by default, because it prevents you from findingout how your subjects are doing by using WhiskerStatus on your office computer. If you are concerned aboutthe prospect of people elsewhere in the world finding out about Whisker, finding out how it works, discover-ing the IP address of your lab computer and reading the status messages you intended for yourself, you caneither enable this facility, or install a firewall on your network to prevent access from outside.

Allow non-local machines to control lines also sets the behaviour of the server with respect to other comput-ers. Assuming you haven’t ticked “Reject all non-local connections”, the server allows other computers to askit for status information (e.g. using the WhiskerStatus program), but does not normally allow other computersto control hardware devices; it responds to any such attempt with an error message. If you want to let othercomputers have access to the hardware, tick this option. Bear in mind that if your computer is connected to theInternet in the absence of any firewalls, any computer in the world could try to influence your devices!

(Note: changing these two settings does not affect clients currently connected, only new clients.)

Clear event log removes all entries from the server’s event log.

Reset timing statistics resets all the timing measurements displayed in the Server Status view to zero. This isdiscussed further in §3.6 Performance considerations.

Ping all clients sends a ‘Ping’ message to all connected clients (see below, under the Client menu).

ClientThe client menu is only available when a client is selected (eitherin the tree view on the left, or in the client summary view).

Ping sends a ‘Ping’ message to the client in an attempt to get itto respond. It is good practice to write clients that do respond toPing messages (see discussion of client/server communicationsbelow).

Delete enables you to disconnect the currently selected client from the server. It will be removed from theserver’s list and all communication links to the client will be severed. You would normally use this only as alast resort to get rid of ‘dead’ (crashed) clients. If you are unsure whether a client is dead, check for networkerrors in the client status/summary view and see when the client last sent a message to the server. If the clientis programmed to respond to ‘Ping’ events, you may use the Ping command to try to provoke a reaction fromit.

Page 31: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 31

Log events toggles the recording of significant events relating to the client. A tick by the entry indicates thatlogging is active.

Log communications toggles the recording of communication messages sent to/from the client. A tick by theentry indicates that logging is active.

Communications and event logging are off by default, to save time and memory. When you turn the logs on,messages will start to be recorded for the client, and any new clients that connect will take the new settings astheir default. Therefore, if you want to monitor communications at the very start of a client’s session, turn oncommunications (using any other client) before the client of interest connects.

Clear event log removes all entries from the selected client’s event log.

Clear comm log removes all entries from the selected client’s communications log.

Send debugging message to client allows you to type a message which is sent to the client immediately.Prefix the message with “Event:” if you want to mimic an event message. Note that clients are allowed toassume a rigid pattern of messages from the server – they can be case-sensitive, if they want, as the servernormally guarantees them a predictable message – so it’s your job to get this right if you mimic the serveryourself.

LineThe line menu is only available when a line view is selected.

Peg line on/off is a debugging feature that allows you to force any line ON or OFF, or to Free it up again.The ‘pegged’ state overrides the true state (of input lines) or the commanded state (of output lines).In other words, pegging input lines allows you to manipulate what your client software sees (including thegeneration of events), independently of the state of the device responsible for the input; pegging output linesallows you to manipulate the devices without the client sending any instructions. This facility is thereforeuseful for testing client software and checking your apparatus is working. It is not intended to be used duringnormal operation.

When you free a line, input lines return to their ‘real-world’ state (the state of the device that is connected).Output lines remain in the state you set them, until the client sends a message to turn the device on or off. (Ifyou think that freeing an output line should return in to the state that the client had it in before you pegged it,let me know on [email protected] – I was ambivalent on this point.)

Note also that lines remain pegged when a client releases them. The Pegging Rule: if you pegged it, it’s yourjob to free it again.

HelpHelp Topics brings up the help system, which will at some pointbe very helpful. Not now, though.

About WhiskerServer displays version and copyright informa-tion, like this:

Page 32: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 32

3.2.5 The configuration dialogue boxes

Configure hardware

This configures the digital I/O cards, of which you can have up to 8 (a limit set by theAmplicon drivers). Each card has 3 chips: X, Y and Z. Each chip controls 24 lines, andcan be configured to have a 24-input card plugged into it, a 24-output card, or a ‘mixed’card with 16 inputs and 8 outputs (the EX221; the outputs are the first eight lines).

You should set the map up so it matches your hardware. (Remember, to configure the in-terrupts and port addresses for each card, use Control Panel → Amplicon DIO.)

Changes will not take effect until you restart the WhiskerServer program.

Technicalnote

Use of the registryWhiskerServer stores information in two places in the registry, that mysterious database at the heart of Win-dows. The first place is for storing information specific to each user of the system. That is in

\HKEY_CURRENT_USER\Software\Rudolf Cardinal\WhiskerServerThis isn’t actually used yet. The other place is for storing information that applies to all users of a computer,because it relates to the hardware. The configuration of the digital I/O boards is kept in this place, which is

\HKEY_CURRENT_CONFIG\Software\Rudolf Cardinal\WhiskerServer.

Configure failsafe outputs

On page 20 (§2.5 DANGER – Critical devices), we discussed the issue of wiring thepower supply to critical devices (such as intravenous infusion pumps) in a fail-safe man-ner. One way of doing this is to require one relay to be on, and one to be off, before the

Page 33: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 33

device gets power. Let’s suppose lines 142 and 143 are output lines using relays. Wecould wire a fail-safe power system as follows:

DC power supply (+24V) → common (COM) pin of the relay 142normally open (N/O) pin of relay 142 → COM pin of relay 143

normally closed (N/C) pin of relay 143 → operant chamber +24V wire

The ground wire would be wired normally, and no other wires should be connected toeither of these relays. In this situation, power would only reach the operant chamber whenrelay 142 was on (so the normally-open pin was in fact closed, i.e. connected to the com-mon pin) and relay 143 was off. This situation is extremely unlikely to happen by chanceor a power failure.

You can then configure the server to keep the relays in this state when it is running, but toswitch both of them off when it exits, as illustrated in the screenshot above. These twolines would then be unavailable for use by clients.

When the server exits, all other outputs are switched off.

3.2.6 Keyboard shortcutsPress DELETE to remove a client, when the desired client is selected (either in the left-hand view or in the client summary list).

Press INSERT to send a debugging message to a client. (You can press INSERT in a fewmore places than you can press DELETE, because it’s a lot safer!)

Press 1 to peg a line ON, when a line is selected.

Press 0 to peg a line OFF.

Press F to free up a line.

Page 34: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 34

3.3 The WHISKERSTATUS status report programThis program allows you to find out the status of your server(s). In conjunction with well-written clients (behavioural tasks), you will be able to find out the status of each of yourrats without leaving your desk.

Run the WhiskerStatus program (Start → Whisker → Whisker Status Client). When youstart it, and whenever you open a new window, it will ask you for the name and portnumber of the server you wish to connect to.

The name loopback may be used as a pseudonym for the machine you presently using,i.e. if the server is running on the same computer as the status program. If the server youare interested in is on a different computer, enter its IP name/address (e.g.homer.psychol.cam.ac.uk or 131.111.190.22).You should normally leave the port numberat its default value of 1333.

The status program will then attempt to open a connection to that server, and will displaymessages telling you how it’s doing. Once it’s connected, then you can click the lightningsymbol, or choose WhiskerStatus → Update server status to request a status display fromthe server.

The default status display lists all the clients (behavioural tasks) connected to the server,showing important information about who they are and what they are doing:

example 1 example 2client number Client number 4 Client number 5name Second-order IVSA (box 0) WhiskerStatus client (C++ version)status Box 0 (F6) – active 34, inactive 5, stim 3, reinf 0 – Task

startedOK

time of lastcommunication

0 min 3 sec ago 0 min 0 sec ago

You will always see the WhiskerStatus program itself in the display (as in example 2above). The status display may be improved in future versions!

The Name and Status fields are provided by the client. You can see how useful it is toprogram your clients so they tell the server what the rat is doing, because the server canthen pass this information on to the status program somewhere else on the network.

Remember that if a client closes the connection to the server, the server won’t knowabout it. If your client closes the connection when the task is finished, you will have tolearn to equate “absence of client on the status list” with “the client has finished”.

By clicking on the blank page icon, or choosing File → New, you can simultaneouslyopen connections to several servers, one per window. The title of each window shows theserver it is connected or attempting to connect to.

You can copy the status program, WhiskerStatus.exe, to another computer (its de-fault location is \Program Files\Rudolf Cardinal\Whisker\WhiskerStatus); it requires no extrasoftware to run (except that TCP/IP must be installed on the computer).

Page 35: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 35

3.4 The WHISKERCLIENT test clientYou can use this program to communicate with the server manually. It does incrediblylittle but is a handy programming tool nonetheless.

Connecting to the server. First, you need to choose a server and click Connect. The de-fault server address is ‘loopback’ (or 127.0.0.1), which is computer-speak for ‘this ma-chine’. To communicate with WhiskerServer when it is running on another machine, en-ter that machine’s IP address – the address that looks like ‘homer.psychol.cam.ac.uk’.The default port number is 1333; you probably won’t need to change this.

Sending commands. You can type into the box marked ‘Message’ and click Send (orpress Enter). Click the drop-down arrow to see a list of commands that the server shouldrecognize.

Have a play. Try claiming an input line, requesting an event on it, and playing with thesensor it’s connected to. Try claiming an output line and setting its state. (The commandsto perform these tasks are described fully later; see Part 5. Client–server communica-tions.) Explore the server console at the same time. Try enabling the communication logsfor client you are using. You’ll be able to find a log of everything that occurred, and beable to watch the lines and events fly back and forth.

Every message you send is shown in the window labelled ‘Sent’. Messages that comeback from the server, plus a few status messages from the program itself, are shown in thebox labelled ‘Received’. Any messages that come from the server and begin with ‘Event:’are shown in the ‘Events’ window, with the event prefix removed.

Click Clear event history to wipe the slates clean.

Technicalnotes

Using an immediate socket system (q.v., page 52) with this client requires that you fire up a second copy,using a different port number. This program hides almost nothing from you – useful for learning how thesystem is put together, if you like that sort of thing.

The client was written in Visual C++ as a dialogue-based application. It does not use the client library thatwas used to develop the behavioural tasks. It is a derivative of the first Windows socket-based program Iwrote.

Page 36: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 36

3.5 The WHISKERRESET utilityThis is a command-line utility that can be used to switch all the lines on or off when theserver is not running (or when Windows is not running).

Usage: WhiskerReset [ReverseOutputs | On | Off] ‘ReverseOutputs’ and ‘On’ both turn all lines ON. ‘Off’, the default, turns all lines OFF.

3.6 Performance considerations

The problemBecause Whisker runs in a multitasking environment, it is unavoidable that other applica-tions that consume processor time can slow down Whisker. Nevertheless, we find theability to run other applications incredibly useful and on the hardware we have used, itdoes not pose a performance problem. It is up to you whether you run other applicationsat the same time, and Whisker does its best to help you make your judgement by provid-ing performance information.

The way Whisker worksEssentially, the server asks Windows to send it a message every millisecond, or as closeto it as Windows can manage. When this message arrives, Whisker does two things.Firstly, it checks the state of the digital input lines, and if any lines have changed statesince the last time Whisker looked, the server flags the change; if any clients are usingthose lines and have asked to be notified of a change in their state, it sends the appropriatemessage to the clients. Secondly, Whisker runs through all the timers being used by theclients (see Part V); if any have timed out, it sends a message to the client.

If the computer is slow…From Whisker’s point of view, the computer can be slow either because it genuinely is aslow computer, or because it’s doing lots of other processor-intensive things at the sametime. Either way, there are two potential consequences.

1. The system’s ‘reaction times’ may deteriorate.

For example, suppose a client is running which switches on a light whenever a rat pressesa lever. The client will have requested to be informed whenever that lever is depressed.You could think of the system’s reaction time as the time it takes for Whisker to send thatmessage to the client, for the client to receive it, process it, and send a command back tothe server to switch on the light, and for the server to receive that command and act on it.If the computer is slowed, this sequence might take longer. (If you’re living dangerouslyand the client and server are on two different computers, then you’re relying on the per-formance of both computers, plus the network that links them!)

Monitoring round-trip performance

Frankly, I don’t expect this to be a problem. In an attempt to assess it, I added the Test-NetLatency command (see Part V). If you run WhiskerTestClient, connect to theserver, and type in TestNetLatency, the following sequence occurs:

client sends TestNetLatency to serverserver receives TestNetLatency, notes the time (Time 1) and responds with Ping

client receives the Ping and responds with PingAcknowledgedserver receives PingAcknowledged, notes the time (Time 2)

Page 37: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 37

server sends the difference between Time 1 and Time 2 in an Info message

The upshot is that you have timed a complete round trip, including processing times, andyou will receive a message like this:

Info: Network latency is 0 ms

It usually is 0 ms, too; sometimes it’s 10–11 ms, occasionally 20 ms. (Obviously the sys-tem time resolution isn’t good at such short times!) I’ve tried to load our machines quiteheavily, and have not managed to get these latencies much higher; basically, TCP/IPcommunication within a single computer is fast.

A delay of 10 ms might be unacceptable in an EEG experiment, but in behavioural con-trol I don’t think it’s a problem. For a start, it is significantly shorter than the time it takesfor a filament bulb lamp to reach a reasonable proportion of its final brightness, and cer-tainly an incredibly brief time compared to the times involved in activating lever retract-ing devices or infusion pumps. It is also extremely brief compared to reaction times intypical tasks. For behavioural purposes, this is a very responsive system.

2. The system may miss events.In the situations discussed above, the system might respond to events slowly, but it wouldstill notice every single one. The potential to miss events completely is a much more im-portant problem. It might arise like this:

detector device is initially OFFpoll #1: Whisker scans the hardware, finds the device off

device goes ONdevice goes OFF

poll #2: Whisker scans the hardware, finds the device off

In this situation, the server would never notice the change. Is this a real problem? Well, ifthe time between successive polls is 10 ms, probably not. There aren’t many actions a ratcan make that are completely over in a lot less than 10 ms! If you have a detector devicethat genuinely does generate pulses in the millisecond range, there is a real problem. Wedon’t.

However, if the inter-poll time is considerably prolonged, a problem might arise.

Monitoring inter-poll times

Part of the Server Status view is dedicated to performance monitoring. Here’s a snapshotof this view:

Every second, this display is updated (together with several other clock-related serverdisplays). This display is telling you since the display was last updated, there have been100 polls, so the average inter-poll time was 10 ms. All well and good. The worst singleinter-poll time in the last second was 11 ms; some indication of the distribution of inter-poll times is also given on the last line of the display.

However, the longest inter-poll time since the server was started has been 160 ms. Thismight have occurred when the server first started (it often does, and that’s nothing toworry about, because no clients are connected then). But it might also have occurred be-cause you just ran some very processor-intensive program.

By using the Server → Reset timing statistics command, you can assess the impact ofrunning a given program. When you have no clients running (or none that matter!), resetthe statistics, then run your program and see how bad the inter-poll time gets. If it exceeds

Page 38: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 38

your personal threshold for worrying, don’t run that program when you have an experi-ment going.

Bear in mind that you only have a problem if you run a processor-intensive program andit hogs the processor at the same instant that your subject makes a response. The serverdisplay gives you the worst-case scenario.

3. Timer accuracy

Timer accuracy is not affected by long inter-poll times occurring while the timer is run-ning (though potentially affected by a long inter-poll time occurring just at the momentwhen the timer expires). All Whisker does on every poll is to calculate the absolute timethat has elapsed since the timer was created, and if this time equals or exceeds the pro-grammed timer duration, it sends the timer message.

Technicalnotes

Repetitive timersSuppose a timer is set up to fire repetitively, once every 100 ms. What could cause this to be inaccurate?

Transmission delay. If a system delay slows message transmission down by 10 ms, one message willarrive late, and the subsequent message will ‘catch up’ and be on the originally scheduled time.

A late clock tick. If the server isn’t polled by Windows when the timer elapses, the message will be sentlate. In this situation, the server could do two things. (1) If it schedules the next occurrence 100 ms later, theclient will receive one late message, and the subsequent messages will be phase-shifted and all of them willbe late from the point of view of the original command, so the whole sequence will finish late. (2) Alterna-tively, the server could schedule the next occurrence so it is ‘on time’, in which case the client will see onelate message and one that ‘catches up’, just as with a transmission delay. The overall sequence will be of thedesired length.

Whisker adopts strategy (2).These scenarios are illustrated on page 40.

SuggestionsAll common sense, really; see the ability to use the testing computer for other tasks as aluxury and judge for yourself whether it would cause problems for your task.

• If you have really time-critical experiments running, don’t use the computer for any-thing else at the same time.

• Know what programs slow the system down and avoid them when you’re testing.(For example, we’ve found that Adobe Illustrator 8.0 is a particular CPU hog; we’veseen a maximum inter-poll time of 500 ms once. On the other hand, Microsoft Excelcauses few problems.)

• Don’t push it. If you buy a slow computer, set it up as a web server, dedicate 25% ofits CPU time to scanning for extraterrestrial intelligence, and defragment your disk inthe background while checking for viruses, running a complicated screensaver andredrawing your plans for a nuclear power station, your system may be a little over-loaded.

Other possible approachesUnless you’re interested in the technical aspects of Whisker, I’d skip this section.

Thread priority

Under Windows NT, it is possible to set the priority of a running program. It would there-fore be possible to increase the priority of the WhiskerServer thread. One problem, ofcourse is that this would detract from the CPU time available to Whisker’s clients. Onecould react to this by increasing their priority, or by decreasing the priority of other pro-grams… It’s not a particularly ‘clean’ solution – and since we don’t experience real per-formance problems anyway, I haven’t gone down this road.

Hardware interruptsWhisker uses polling to respond to two classes of event: changes in the state of the digitalinput lines, and timers. If the digital I/O cards were capable of generating interrupts, then

Page 39: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide III. Using the software suite 39

a different approach could be taken with the input lines: instead of checking them regu-larly, Whisker could sit back and wait to be informed via a high-priority interrupt signalwhen one changes. Of course, timers would still have to be serviced by regular polling,and I don’t know whether a whole flood of hardware interrupts would have adverse per-formance consequences, but it would be an additional mechanism of gaining perform-ance.

Page 40: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

late

> 100 ms < 100 ms

400 ms exactly

LATE CLOCK TICK, COMPENSATED FOR

late

> 100 ms 100 ms exactly

> 400 ms

UNCOMPENSATED CLOCK ERROR. This should not happen in Whisker.

Time (ms)0 400300200100

slow

> 100 ms < 100 ms

400 ms exactly

TRANSMISSION DELAY

server

client

Technical schematicTypes of timer inaccuracy that are possible, illustrated with a repetitive timerthat fires once every 100 ms.

Page 41: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide IV. The Second-Order Client 41

Part 4. The Second-Order schedule: aprototypical task

4.1 IntroductionIn a second-order schedule of reinforcement, the subject must complete a certain simpleschedule (fixed ratio, fixed interval, variable ratio, etc.) to obtain a stimulus. It works on ahigher (second-order) schedule for the actual reinforcer; for example, it might obtain astimulus+drug compound once it has earned five stimuli.

The SecondOrder client is designed to use a {left lever, right lever, nosepoke} response toearn stimuli on an {FR, FI, VR} schedule, and earn reinforcement from a {liquid dipper,infusion pump}on a second-order {FR, FI, VR} schedule. It records all responses, andalso records locomotor activity. The schedule, stimulus and reinforcement parameters areall configurable.

(IVSA; intravenous self-administration.)

SecondOrder is implemented as a dialogue-based Windows application that stores its dataon disk, but also directly into a database (also supplied).

4.2 Specifications

Program

• Finished on 14 Jan 2000, pending examination of a few other quirks of the printoutfrom the Paul Fray second-order program (i.e. do we need these features?).

• Implemented as a dialogue-based Windows program using the Whisker C++ client li-brary. Provides status information to the server to enable its progress to be monitoredfrom a different location (using the WhiskerStatus tool)

• Maintains rat configuration data files.• Produces a summary file containing the most useful information about the session,

and a response file in comma-delimited format containing a time-stamped record ofevery response made, with information about whether that response produced astimulus or a primary reinforcer.

• Stores a session’s complete data set directly in a database when the run is finished.This feature uses ODBC (Open Database Connectivity, a world standard for commu-nicating with databases). An appropriately-configured database in Microsoft Access97 format is supplied with SecondOrder.

Page 42: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide IV. The Second-Order Client 42

Schedules

• Supports FI/FR/VR for both unit and overall schedules. VR schedules are specifiedwith a flat probability distribution function (i.e. you specify the minimum and maxi-mum value, rather than the mean).

• For overall-FI schedules, calculates index of curvature and proportions of respondingin each quarter of the interval.

• Supports left/right lever and nosepoke manipulanda, with variable location CS.• Inactive lever can optionally cause both levers to retract for a timeout period.• Supports pump/dipper reinforcement, with configurable multi-dip reinforcement, and

timeout periods at reinforcement.• All stimulus and reinforcement timing parameters can be configured.• Records locomotor activity on up to three beams in bins of configurable size.• Session time and number of reinforcements can be capped.

Schedule and calculation details

Responding during a stimulus is counted towards totals and index-of-curvature plotting,but does not contribute towards the unit schedule in progress.

Responding during a reinforcement timeout (which is only possible for nosepokes andnon-retractable levers) is recorded in the response log, and contributes towards the re-sponse totals, but does not contribute to progress on the schedule or to index-of-curvaturedata, as these responses are considered ‘outside’ the overall FI (the overall FI is consid-ered to start at the end of this timeout period).

4.3 Before you begin: setting up a database

Why?The SecondOrder client can store its data in a relational database, which is a Very GoodIdea and can save you a great deal of time and effort. It needs a database containing tableswith particular names and layouts. Rather than describe this in exhaustive detail, I’vesupplied a sample database with Whisker, for use with Microsoft Access 97 or later. It’son the menu (shown earlier).

However, I strongly recommend you make a copy of this database and do not use theoriginal that I have supplied; firstly, because then you won’t lose any data if you uninstallWhisker (this procedure deletes the supplied database), and secondly, because you canmake multiple copies for different purposes (perhaps different experimenters).

Copying the database that is suppliedThe database lives in the Whisker’s SecondOrder directory (by default, this is \ProgramFiles\Rudolf Cardinal\Whisker\SecondOrder) and is called Second-order IVSA database (proto-type).mdb.

Copy this to some directory of your own and rename it.

Configuring an ODBC data sourceSecondOrder chooses and finds its database using the Open Database Connectivity(ODBC) system, which allows programs to talk to databases from a wide variety ofmanufacturer (i.e. not just Access). You must set up your copy of the database as a datasource.

ODBC must be installed on the computer. (The Whisker Setup program will ensure thatyou have ODBC version 3.5 or greater installed.)

Page 43: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide IV. The Second-Order Client 43

1. Configure a data source name (DSN) to point to the database(s) you want to use. RunStart → Settings → Control Panel → ODBC Data Sources.

2. You may add your data source as a “User DSN”, which will be visible only to theuser you configure it with, or a “System DSN”, which will be visible to all users ofthe system. (You could probably use a File DSN as well, but never mind that.)

3. Choose Add, then choose a database driver (e.g. “Microsoft Access Driver”).

4. Then define a data source name (DSN), which should have no spaces in it (e.g.Rudolf_SecondOrder).

5. Click Select to browse your directories and choose the database that this DSN willconnect to.

6. Click OK.

Good. Now when you run SecondOrder, this DSN will be among the list you can choosefrom when your session is complete.

Technicalnote

Record-lockingWhen several copies of SecondOrder are running, there is a chance that they both try to store their data inthe same database at (almost) the same time. This creates a problem: the first copy will lock the tables whileit stores new data, during which time the second copy can’t gain access. If this happens, the second clientwill report an error, and the user can (and is recommended to) click Retry to have another go.

Configuring MS Access database parametersHowever, we can reduce the likelihood of an error being reported by making the database system try forlonger itself. In any Access database that you wish to configure, choose Tools → Options → Advanced.You can then specify the Number of Update Retries (default 2, you want 10) and the ODBC Refresh Inter-val (default 250 ms, you want 1000 ms). This has already been done for the second-order database.

Creating a personalized shortcut to SecondOrderYou can create several shortcuts to the SecondOrder program, and have each shortcutstart in a different directory.

1. Find the SecondOrder.exe program and create a shortcut to it, or copy the shortcutthat is installed in the Start menu (by right-clicking the Windows Start button andchoosing Open All Users.

2. Once you have a copy of the shortcut, right-click it and choose Properties → Shortcut→ Start In, then type in a directory name.

This may be useful for keeping different people’s experimental data separate.

4.4 Running the taskWhen you run SecondOrder, you will see this dialogue box.

Page 44: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide IV. The Second-Order Client 44

First, connect to the server (which must be running!). Then, set the task parameters. Youwill be presented with this dialogue box:

I hope most of it is obvious. The only things that may not be are these:

• You should name your subject and assign it a session number. You can save thewhole configuration in a configuration file. When you load that configuration file thenext time, the program increments the session number by one (and auto-saves anychanges you make to the configuration). This makes it easy to take subjects through atraining programme – the configuration file remembers where they are at any givenmoment.

• When you load a configuration file, the program guesses suitable summary-output(human-readable) and per-response-output (database format) filenames. By default, itstores these files in the same directory as the configuration file. These filenamesmust be specified before the task will start. If you try to start two copies of the pro-gram using the same filenames, the task will not start.

• If you use a dipper, you can either have the dipper down at rest, and come up one orseveral times to deliver liquid so there’s no liquid available when it finishes, or youcan have the dipper up and dip down to collect liquid so the liquid remains availableuntil it’s collected. You can specify the timing of the dips: for example, you can havethe dipper be down at rest, come up for 2 s (dip time), go down for 0.5 s (inter-diptime) and then repeat this cycle a total of three times (#dips per reinforcement).

The example above (overall schedule FR10, unit schedule FR2) means that the subjectwill get a stimulus for every 2 responses, and reinforcement after every 10 stimuli.

Click OK when you’re done.

Choose the box you wish to use. Boxes are numbered from ZERO, not one.

Optionally, you may wish to set up yoked boxes, as follows:

Page 45: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide IV. The Second-Order Client 45

When you’ve done this, claim the box(es) from the server.

When the subject is in the chamber, click start. The display looks like this when the taskis running:

When the task finishes, it quietly stores its data in the files you specified. It also asks youfor a ODBC data source – that is, a database to store the data into. You should have setthis up before starting (see above), though you can do it now if you really want! Double-click on the database you’d like to use:

That’s it. The program returns to the main window and displays ‘FINISHED’ in its titlebar. You can close it.

Page 46: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide IV. The Second-Order Client 46

If the program reports an error, another client may be using the same database (see theTechnical Note a few pages back) or there may be a problem with the ODBC data source.If the former, then wait a few seconds and click Retry. Otherwise, reconfigure the ODBCsource – in an emergency, you can always create a new one on the spot using the Newbutton (visible in the screenshot).

Note that the moment at which the SecondOrder client stores data in a database is quiteCPU-intensive (see discussion of performance considerations on page 36).

Note that the program goes to considerable lengths to ensure you never lose data. When-ever you abort the program, it tries to store all the data it has collected in as many placesas possible (i.e. on disk; in a database). You should find it hard to abort it accidentally, asit complains loudly when you try.

4.5 Using the dataA full data set is stored in the database, including the configuration each session was rununder, the exact time of each response and locomotor activity data, together with usefulsummary information (total number of responses, indices of curvature and quarter-livesfor interval schedules).

You can design queries to extract the data in any conceivable way (see also Part VII).

For your convenience, there are queries built into the database that will extract data in asuitable form to be copied directly in to the cumulative record spreadsheet (in Excelformat) that is also supplied with Whisker. This gives you cumulative records and acti-grams.

The database looks like this:

Here’s one of the five tables, containing some data:

If you want to obtain a cumulative record graph, have a look at the Queries. One of themis named EXCEL cumulative record graph (ACTIVE) lever, and there’s another for theinactive lever. Open up the query. You’ll be asked for the date/time code of your sessionof interest (e.g. 3/4/00 2:01:24 PM), the name of the master rat and the box number of therat you’re interested in. (Note this well, if you’re using yoked rats: to get a record of theyoked rat, enter the name of the master rat and the box number of the yoked rat.)

Page 47: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide IV. The Second-Order Client 47

The query then runs and produces something like this.

Copy the whole thing (Ctrl-A to select the whole query, Ctrl-C to copy it).

Open up the supplied Excel spreadsheet. Put the cursor in the top-left cell of the ACTIVELEVER worksheet and press Ctrl-V to paste in your data.

Here’s part of the cumulative record worksheet that results:

Actigrams are also generated. If you want to add inactive lever responses to the actigram,just run the other Access query and paste the results into the INACTIVE LEVER work-sheet.

4.6 Inner workings of the programI think it would be fair to say that this is not a simple program by experimental psychol-ogy standards, though this is due more to the user interface and the communication withthe database than the complexity of the task. However, I tried to write it in as comprehen-sible a manner as I could. The source code is supplied, and I encourage you to explore it,though it may be easier to start with simpler clients (see Part VI). The central function,

Page 48: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide IV. The Second-Order Client 48

CSecondOrderTask::IncomingEvent(CString strEvent), in SecondOrderTask.cpp, does allthe work relating to the task, and it’s quite simple.

Page 49: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 49

Part 5. Client–server communications

Time to get to the heart of the system. This section deals with the information you need towrite powerful behavioural tasks. It is partly intended as a reference section.

5.1 IntroductionThe Whisker system is based on a client–server model. The server is a program thattalks directly to the hardware controlling the operant chambers. The clients are programsthat you can write that instruct the server how to control the chambers. A client imple-ments a behavioural task, such as an FR-5 schedule of responding on a lever for pellets,or a five-choice serial reaction time task.

Several clients can communicate with a single server, and they operate independently.Because of this, you need only program the task client to cope with a single operantchamber, and then run several copies of the client when you want to use several boxes atonce.

This brings several immediate advantages: (1) it simplifies the process of writing a task,because you only need to be concerned about one box; (2) it becomes almost impossiblefor a task to accidentally activate a device in the wrong box; (3) you can run any combi-nation of different tasks at the same time without special programming.

5.2 Programming tasks: design principlesThis seems like a good point to summarize the three main ways of designing a multi-chamber control system.

System Pros Cons1. General-purposelanguage with hard-ware-specific exten-sions. Example:Arachnid.

• Programming experience (in thecase of Arachnid, with BBC BA-SIC) applies to completely differentapplications

• Independent control of multipleboxes is hard to achieve (withdanger of programmer error)

• Very hard to run two differenttasks simultaneously, as only asingle user program runs at once

• Need to learn specific language

2. Custom languagedesigned for operantchamber control;software runs usertasks ‘inside’ theserver. Example: Med-PC®.

• Safe, independent control of multi-ple operant chambers

• Simple programming language (oreven graphical task design)

• Programming language has re-stricted capabilities

• Programming experience not use-ful for completely different appli-cations

3. Server and clientsare independent pro-grams. Example:Whisker.

• Safe, independent control of multi-ple operant chambers

• User free to choose programminglanguage for client task

• Programming experience general-izes to other applications

• Need to learn at least one pro-gramming language

• Need to communicate with server

Options 1 and 3 may entail a choice of programming language (though not in the caseof Arachnid). In this situation, there are three considerations: how easy the language is to

Page 50: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 50

learn, the merits of the language itself, (including whether it is interpreted or compiled),and how useful the language is applications outside operant chamber control.

One of the main dangers of using an interpreted language like BBC BASIC for operantchamber control is that typing and syntax errors may not be discovered until the taskcrashes with a rat in the box. Compiled languages find all those kinds of bugs before youever run the program. I strongly recommend the use of compiled languages for all but themost trivial programming tasks when it is very important that the program does not crash.

(My favourite is C++, the language the Whisker server was written in. C++ is one of themost popular languages world-wide, and for good reason. If you choose to learn and useC++, a fringe benefit is that you will become skilled in a general-purpose language, sowhen you decide that you want to become a computational neuroscientist you have a headstart!)

The principle ‘con’ of Whisker’s approach is that the user must develop some minimalprogramming ability in the chosen language. I have attempted to reduce the programmingburden by providing libraries of code for different programming languages, so writing atask becomes a more a matter of filling in blanks.

5.3 Communication: design principlesMessages are passed between the client and server through a ‘socket’, which is a linkbetween two programs through a network. The two programs can be on the same com-puter (I expect you will normally use this mode) or thousands of miles apart. The cli-ent/server computer(s) must have TCP/IP installed – the standard protocol for Internetcommunications. The client connects to the server by opening a connection with a stan-dard port number, which is 1333.

Each message constitutes a single string. This is a very general format, which is why Ichose it. Most modern computer languages have no difficulty understanding and ma-nipulating strings, and humans can understand string-based output. If the client or serverneeds to send a number, it is simply encoded in a string; thus 15 is sent as “1” (ASCII 49)followed immediately by “5” (ASCII 53).

For technical reasons, it is impossible to guarantee that two separate messages do not getconcatenated when sent over the network. Therefore, each string sent by the server endsin a linefeed (LF; ASCII code 10 decimal, 0A hex, also written as CTRL-J, ^J or \n).When you send commands to the server, you should also end them with a linefeed or car-riage return (CR), in case two of your commands become concatenated in transit. Youmay also use a semicolon to separate commands.

Technicalnotes

Wide-area networksThe more network is in between the client and server, however, the less rapid the system’s response be-comes (especially on a busy network). This is why I recommend keeping the client and server on the samecomputer. However, it is easy to find out the status of the operant chambers from a different computer; Iimagine this will be the main practical use of this feature. The design didn’t depend on this, though; ifyou’re going to separate the client and server, you need a communication protocol, and TCP/IP happens tocarry associated benefits.

TCP port numbersEvery type of program that communicates over the Internet (or similar TCP/IP networks) has a port number.For example, the Web uses the HTTP protocol, which runs on port 80. The Whisker main port, 1333, is notregistered with Internet authorities, but is not assigned for any other purpose at the time of writing (seeftp://ftp.isi.edu/in-notes/iana/assignments/port-numbers), as is the Whisker accessory port, 1334.

Network speed and concatenation of packetsFor those interested in such technical matters, the server disables the Nagle TCP algorithm to ensure that allpackets are sent immediately (this is achieved by instructing its sockets to set the parameterTCP_NODELAY). Nevertheless, if the server sends two packets in very quick succession, the TCP algo-rithm amalgamates them. This does make sense from a network performance point of view.

Page 51: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 51

5.4 Format of messages that pass between a client andthe server

The messages are described on the following pages. Strings to be quoted literally (incomputer-speak, ‘string literals’) are shown in monospaced type; parameters are shownin italic type.

Client commands do not use a colon and are not case-sensitive. The server will acceptmultiple commands in one packet if they are separated by a carriage return (CR, ^M,CTRL-M, ASCII 13, \r), a linefeed (LF, ^J, CTRL-J, ASCII 10, \n) or a semicolon (; orASCII 59).

Server responses use a colon, and will always give messages as they are described in thismanual – CapitalizedWords with no space between them, a colon, a space and the rest ofthe message. (Exceptions: a colon is not given for Ping and PingAcknowledged com-mands, which can be sent by either the client or the server.)

5.5 Events: the core of the systemEvents are the key to the Whisker system. What a typical client (behavioural task) pro-gram does is to say, in effect, ‘Say FISH to me when the rat depresses a lever; sayTIME_UP to me when 30 minutes elapse from now.’ It then sits quietly and waits for theserver to send it messages. When the appropriate lever is pressed (or the time elapses), theserver sends it a message containing the desired text; the client may then take action (suchas activating the pellet dispenser, or ending the session). The client may choose freely thetext used for these events.

Event messages are marked in a special way (they’re preceded by ‘Event:’) to distin-guish them from other types of message. The detailed list of messages given on subse-quent pages shows how this works.

5.6 Exploring the system with WhiskerTestClientOn page 35, we glanced at the WhiskerTestClient program. This might be a good time torun it, connect to the server, and try sending some messages. As a very simple example,try sending the following command:

RequestTimerEvent 5000 0 Your_Time_Is_Up

This is one of the commands detailed in the rest of this section. It requests the server toset up a timer event that elapses in 5000 ms (5 s), never reloads, and sends the event“Your_Time_Is_Up” when the timer elapses. You should see that the server respondsimmediately with

TimerCreated: duration 5000, reloadcount 0

and five seconds later, the server should sendEvent: Your_Time_Is_Up

This is a message that has the “Event:” prefix, and WhiskerTestClient is alert to these; inaddition to displaying the message from the server in its Received window, it also dis-plays

Your_Time_Is_Up

in its Events window. Events are the class of message that clients are most interested inresponding to; were this a real client, it might be programmed to terminate a schedule atthis point. Events are not restricted to timers; by using the RequestLineEvent mes-sage, you can ask the server to send you a message of your choosing when your subjectbreaks an infrared detector beam, or presses a lever.

Page 52: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 52

5.7 Two ways of communicating: a general-purpose and animmediate-response system

Caution: technical information!

The event-driven system and the separation of client and server is an enormously power-ful technique, but it involves one area of complexity. That concerns queries that requirean immediate and specific response.

For example, if (as the client) you wish to know whether an infra-red nosepoke detector ison or off, you may ask the server. But you do not wish to pause while waiting for the an-swer (you wish to know the device’s state now, and you do not want to hold up process-ing of other ongoing events).

Imagine that as you begin to ask this question of the server, the server has detected alever-press for which you have requested notification. It sends the event message at thesame instant you send the query about the nosepoke detector. We have a dilemma: youdon’t want a lever-press event in response to your nosepoke query, you don’t want toprocess the lever-press event until you know the nosepoke detector status (let’s say), andyou don’t want to have your “nosepoke query” routine handle lever-press events itself(that would be needlessly difficult to program in a task of realistic complexity!).

This is a problem whenever we have one channel of communication and when the servermay send event messages at unpredictable times. If the ‘client’ and ‘server’ were thesame program (as in every other operant control system currently on the market, to myknowledge) it would be easy to organize the program so the nosepoke detector requestcould take priority and hold up processing of the lever-press event. But this would defeatthe many advantages of client–server separation. So we must get around the problem.

The way I have chosen to do this is to use two communication channels between theclient and the server. Now, you don’t have to use two channels, but whenever this prob-lem crops up it is a good solution (and believe me, it crops up all the time). In the networksystem we are using, communication channels are known as sockets, so this is a two-socket system.

One socket is called the main socket. You may send commands to the server through thissocket, and the server will send all of its event notification messages (and other unsolic-ited information) down this socket. The other is a called the immediate socket. Theserver guarantees two things about communication down the immediate socket:

1. The server will send nothing to you through this socket, except in direct response tocommands that you send to it through this socket.

2. Every command you send will be responded to immediately, and that response willcomprise a single message, or one line of text.

As the client, you should implement the immediate socket as a ‘blocking’ socket (Iapologize for the networking terminology; this means that when you say to the socket‘give me the server’s reply’, it waits for that reply if necessary and then returns it to you;the socket never says ‘sorry, no information has come from the server yet’).

Don’t worry, you shouldn’t have to work with this system directly – all the technical de-tail is implemented for you in the handy function libraries for several popular languages(the support is particularly good in C++, because I like that language).

The message descriptions that follow describe the effect of giving each commandthrough the main socket and the immediate socket, under the headings ‘Response’ and‘Response (immediate socket)’. In general, responses to commands down the immediatesocket are much simpler and more sharply defined, and consequently easier to deal withfor the client task. Responses down the main socket give a good deal of ancillary infor-

Page 53: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 53

mation and are more useful to the watching human. Remember that every message will beterminated by a carriage return.

You cannot connect more than one immediate socket to a given client.

Technicalnote

Why two communications channels?The network administrators out there may be wondering why I didn’t use out-of-band transmission on themain socket: because not all client languages (and not even all TCP implementations) support it.

5.8 Ensuring network responsivenessOne final technical point: I strongly recommend that you disable the Nagle algorithm onyour client’s sockets (by instructing them to set the parameter TCP_NODELAY), for tworeasons:

1. It guarantees crisper network transmission and better latencies (albeit at the expenseof more traffic)

2. If you send a lot of information from the client as separate messages, they might beconcatenated, and then the resulting packet split randomly. Since the end of a packetis taken as a command terminator by the server, this results in a command being ig-nored – obviously undesirable. (Actually, I’ve only seen this once, and it went awayas soon as I disabled the Nagle algorithm.)

The C++ client library (WhiskerClientLib) performs this chore for you automatically.

5.9 ‘So how on earth do I make a socket?’Good question. Essentially, this depends on the language you are using. Be assured that iseasy. See Part VI, where concrete examples are given.

Page 54: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 54

5.10 Key messages

ClaimLineMessage ClaimLine linenumber input|output [ResetOn|ResetOff|Leave] [–

alias alias]

Originator Client

Details Claims hardware line linenumber for input or output. By default, or if “reset” is specified,output lines are turned off. If “leave” is specified, the line is left in its current state. Thisparameter also determines what happens if the client falls off the edge of the earth. Lines arenumbered from 0, so a typical single-board system has lines 0–71.

Input | output. Whether a line is an input or an output line is not determined by the in-put/output parameter, but by the configuration of the server (which you can set, on theserver, depending on how you wire up the apparatus). This parameter is merely a statementof your intent. You do not have to specify “input” or “output” when you claim the line.However, it is advisable. If you claim an input line and subsequently try to set its state, youwill get an error message. It is better to state when you claim the line that you think it is anoutput line; if you are wrong, then the error message comes immediately and you knowthings aren’t safe to proceed.

ResetOn | ResetOff | Leave. If you specify “ResetOn” or “ResetOff” and the line is an out-put line, it will be turned on/off now, and when the client gives up the line. Otherwise it willbe left in its current state, whatever that is. The default is “Leave”.

Response Either ofClaimAccepted: linenumberClaimRejected: linenumber reason

For example,ClaimRejected: 112 is a non-existent lineClaimRejected: 5 is already claimedClaimRejected: line 7 is not an input line

If you set an alias, you will also get messages concerning the success or failure of the aliascommand. You may also get a message of the form

ClaimAccepted: 5 (alias not set)if the claim succeeded but the alias was improperly formed.

Response(immediatesocket)

Either ofSuccessFailure

If you request an alias, you will only get Success if the alias command also succeeds.

SetStateMessage SetState linenumber|alias on|off

Originator Client

Response A successful call generates no response. Otherwise an error message will be generated:SyntaxError: reason for failureError: can’t set line lineNumber

Response(immediatesocket)

Either ofSuccessFailure

Details Turns output lines on/off.The SetState command supports grouping. That is, you can do this:

ClaimLine 4 –alias HouselightClaimLine 5 –alias LeftStimLight

Page 55: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 55

ClaimLine 6 –alias RightStimLightSetLineAlias LeftStimLight LIGHTGROUPSetLineAlias RightStimLight LIGHTGROUPSetState LIGHTGROUP on

–– This will turn lines 5 and 6 on.SetState LeftStimLight off; SetState RightStimLight off

–– Remember that multiple commands can be given in one line.

If a group is set, multiple error messages may be generated on the main socket, but only asingle value will return on the immediate socket – this value will be Success if all lineswere set correctly, and Failure if a single line could not be set.

ReadStateMessage ReadState linenumber|alias

Originator Client

Response State: linenumber on|offor an error message.

Response(immediatesocket)

One ofonofferror

Details Asks the server what the current status of the line is (on or off). Applies to input and outputlines.

Advanced point: if a group alias is given on the main socket, the server will respond with aState message for each applicable line. If a group alias is given on the immediate socket, theserver will only return the state of one line, chosen (effectively) at random. I would discour-age you from using group aliases with ReadState.

RequestLineEventMessage RequestLineEvent linenumber|alias on|off|both eventtext

Originator Client

Response LineEventCreated: linenumber on|off|bothLineEventRefused: reason for refusal

Response(immediatesocket)

Either ofSuccessFailure

Details You can have separate events for on and off. Probably should only allow one of each,though.

If a grouped alias is used, multiple messages may be generated on the main socket, but onlya single value will return on the immediate socket (Success if all lines were set correctly,and Failure if there was a problem with any one line). However, it is not recommendedthat you use grouped lines with this command.

RequestTimerEventMessage RequestTimerEvent duration reloadcount message

Originator Client

Response TimerCreated: duration duration reloadcount reloadcountTimerRefused: reason

Page 56: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 56

Response(immediatesocket)

Either ofSuccessFailure

Details You do not specify the duration with which the timer is reloaded, but the number of timesthat it is reloaded with its original duration. (For those of you used to Arachnid, this repre-sents a significant change in the way timers are used.) The value –1 has a special signifi-cance: it means that the timer should be reloaded for eternity (i.e. until you manually kill it).Use 0 for a one-off timer, 1 for a timer that is reloaded once (i.e. executes twice in total), andso on.

In fact, all negative numbers are treated the same way as –1.

EventMessage Event: text

Originator Server

Details A hardware or timer event has occurred.This is the main message that the client needs to set up and respond to.It is always sent to the main socket.

Examples Event: SEEKING_LEVER_PRESSED_BOX_3Event: ITI_expired

SetLineAliasMessage SetLineAlias line_number|existing_alias new_alias

Originator Client

Response No response (implies success) or an error message.

Response(immediatesocket)

Either ofSuccessFailure

Details You can define aliases for lines or timers (see RegisterTimeAlias). If you issue the command“RegisterLineAlias 5 leftlever”, you can then use “leftlever” in place of the line number insubsequent commands (meaning you can do “ClaimLine leftlever”, “RequestLineEvent left-lever on LEFT_LEVER_PRESSED”).

Restrictions: there can be no spaces in the alias. Aliases cannot begin with a number (todistinguish them from ordinary line numbers). It is not case-sensitive.

Aliases can be used with any command that takes a line number, except ClaimLine (forwhich you obviously have to know the actual line number!). Note: you can claim and alias aline in one step (see ClaimLine).

Aliases are designed to make programs independent of the box (chamber) number. Onceyou’ve defined your houselight (which might be line 5 in box 1, or line 28 in box 3) youshouldn’t need to know its actual number again. Aliases also help to simplify counterbal-ancing and task design. For example,

ClaimLine 8 –alias LeftLeverClaimLine 9 –alias RightLever...

L/R counterbalancing determined by client program at this point...SetLineAlias LeftLever ACTIVELEVERSetLineAlias RightLever INACTIVELEVERRequestLineEvent ACTIVELEVER on active_lever_pressedRequestLineEvent ACTIVELEVER off active_lever_releasedRequestLineEvent INACTIVELEVER on inactive_lever_pressedRequestLineEvent INACTIVELEVER off inac-

tive_lever_released

Page 57: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 57

Before you ask, there is no need to set aliases for timers, as timers have names anyway andyou define the names. Aliases for timers are not supported.

SetSafetyTimerMessage SetSafetyTimer linenumber|alias time on|off

Originator Client

Response Info: line 6 will be switched off after 5000 ms of inactivitySyntaxError: something wrong with SafetyTimer callError: invalid line linenumberError: you do not own line linenumberError: line linenumber is not an output line

Response(immediatesocket)

SuccessFailure

Example SafetyTimer PUMP 5000 off

This tells the server to ensure that PUMP is always switched off if its state has not been setby the client in the last 5 s.

(The timer continually compares the current time with a record of when the line last had itsstate set, or was claimed by a client.)

If the safety timer is triggered, a warning message will be sent to the client, as in the follow-ing example:

Warning: line 6 switched OFF after 5000 ms of inactivity

Group aliases may be used, though that seems to me like an odd thing to do.

Important note: this feature only operates while the server thinks the client is connected. Itprovides some protection against a mis-programmed client (including a client that crashesbut leaves the link to the server open) or a network failure. If the device is really critical, likean i.v. pump, you should also specify a reset state when you claim the line; for example,

ClaimLine 5 output ResetOff –alias PUMP

In this situation, when the client releases the line or client-server communication is lost, theline will be reset to the off state. Use both these commands for maximum safety.

Page 58: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 58

5.11 Controlling groups of lines

The SetLineAlias and SetState commands supports grouping. That is, two lines can begiven common (as well as distinct) aliases:

ClaimLine 4 –alias HouselightClaimLine 5SetLineAlias 5 LeftStimulusLight

–– This illustrates two ways to set an aliasClaimLine 6 –alias RightStimulusLightSetLineAlias LeftStimulusLight LIGHTGROUPSetLineAlias RightStimulusLight LIGHTGROUPSetState 4 onSetState LIGHTGROUP on

–– This will turn lines 5 and 6 on.SetState LeftStimulusLight off

–– This will turn line 5 off.SetLineAlias LIGHTGROUP ANOTHERALIASSetState ANOTHERALIAS off

–– You can add another alias for a whole group. This will turn lines 5 and 6 off.

The grouping function makes it very easy to implement yoking. For example, if your taskcurrently looks like this:

ClaimLine 4 –alias HouselightClaimLine 5 –alias LeftStimulusLightClaimLine 6 –alias RightStimulusLight

(*)SetState Houselight onSetState LeftStimulusLight on

and you want another box to be yoked to it (which has lines 15–17 for these same de-vices), you can add the following lines at or before the point marked (*):

ClaimLine 15 –alias HouselightClaimLine 16 –alias LeftStimulusLightClaimLine 17 –alias RightStimulusLight

and the main program will happily control the devices as before, except when it switchesthe houselight on in the main box, it will also switch it on in the yoked box.

Though you can use group aliases with RequestLineEvent, KillEventByLine (describedlater) and ReadState, I think this is unwise. In particular, this practice may lead to con-fusing results with ReadState: if you issue a ReadState command on the main socket, theserver will respond with the status of all applicable lines, but if you do the same thing onthe immediate socket – where a single instant response is the only reply you ever get – theserver will provide the status of just one of the applicable lines (chosen at random).

Page 59: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 59

5.12 Getting rid of events, timers and lines; shutting downcleanly

KillEventByLineMessage KillEventByLine linenumber|alias on|off|both|all

Originator Client

Response SyntaxError: something wrong with KillEventByLine callError: invalid line linenumberError: you do not own line linenumberInfo: killed all events on line linenumber

Response(immediatesocket)

SuccessFailure

Details Kills events on the specified line. The default is to kill all events, but you can selectively kill“on” or “off” events. “Both” and “all” do the same thing.

KillTimerMessage KillTimer timername

Originator Client

Response Info: killed all timers called eventnameError: no timers to kill called eventname

Response(immediatesocket)

SuccessFailure

Details I hope this is self-explanatory!

KillEventMessage KillEvent eventname

Response Info: killed all line events called eventnameError: no line events to kill called eventname

Response(immediatesocket)

SuccessFailure

Originator Client

Details Kills a line event, or events, by the message associated with them. May kill multiple events.Does not kill timers.

KillAllEventsMessage KillAllEvents

Originator Client

Response Info: All line events killed

Response Success

Page 60: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 60

(immediatesocket)

Details Kills all line events. Does not affect timers.

KillAllTimersMessage KillAllTimers

Originator Client

Response Info: All timers killed

Response(immediatesocket)

Success

Details Kills all timers. Does not affect line events.

RelinquishAllLinesMessage RelinquishAllLines

Originator Client

Response Info: All lines relinquished

Response(immediatesocket)

Success

Details Relinquishes control of all lines owned by the client.Also deletes all aliases.

ShutDownMessage ShutDown

Originator Client

Response No reply

Response(immediatesocket)

No reply

Details Kills all line events, kills all timers, releases all lines and closes the network connection(s).There may be a short delay (< 1 s) before the network connection is closed.

This command should be issued when the client has finished. It releases ownership of thelines under the client’s control, so another client can use them. If you close the network con-nection without this, the server will notice and clean up. However, if the client crashes,there may be a considerable delay before the server notices.

The problem of crashed clients:

Obviously, I could have programmed the system so the server regularly checked that its cli-ents were OK, and killed all links to unresponsive clients. However, I don’t agree with thisphilosophy; the client might be busy doing other things. The solution I went for is this: Theserver keeps track of the time of the last communication received from the client. The op-erator (you!) can also ask the server to ‘ping’ all its clients. The server sends a Ping messageto the client(s), and a well-written client will respond with an acknowledgement. As thisconstitutes communication, this will reset the “time since last communication” clock. Thisclock is displayed on the server’s console (it’s in the main client list). In addition, if theserver tries to send a message to the client and the network link actually fails (which oftenhappens with a dead client), the message “ERROR SENDING TO CLIENT” will be re-

Page 61: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 61

corded indelibly in that client’s status information.

So, if you think your client is dead, have a look at its clock. If it hasn’t responded for a while,you can ping it using the server’s console. If it responds, its clock will be reset to zero. If itdoesn’t respond, and you know the client is programmed to respond to Ping events, or if thenetwork error message has appeared, the client may well be dead. You can then delete itfrom the server’s list and free up its resources. However, it’s your job to decide whether thatclient is really dead, and not just too busy doing something else to respond to ping messages.

If you’re living life on the edge and the client is on a different computer to the server, youmust also bear in mind the possibility that the network is down (rather than the client).

Page 62: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 62

5.13 The two-socket system

ImmPortMessage ImmPort: port_number

Originator Server

Details The server sends this message when the client first connects to the main socket. It gives theport number to use for the immediate socket connection, should one be desired.

CodeMessage Code: code

Originator Server

Details The server sends this message when the client first connects to the main socket, after theImmPort message. It gives a code that the client needs to prove to the server that it is thegenuine owner of its immediate socket. As soon as the client receives the Code command, ithas all the information it needs to connect and link an immediate socket using the Linkcommand.

LinkMessage Link code

Originator Client

Response This command does not work through a normal socket.

Response(immediatesocket)

Either of:SuccessFailure

This command only works when the immediate socket is not yet connected to a client. If yousend it once the immediate socket has been connected, an error will be generated.

Details When an immediate socket has been connected, the server does not know which client itbelongs to. At this stage, the only command that the server will respond to on this socket isthe Link command. As the client, you should send a Link command with the code you re-ceived from the server (see Code above). Once the socket has been successfully linked to theclient, it is fully operational.

Page 63: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 63

5.14 Two-socket system: sequence of eventsThis table shows the sequence of events that occurs when a client connects to the serverand wishes to use two sockets (a ‘main’ socket for normal communication, and an ‘im-mediate’ socket for instant, well-defined replies).

The C++ client library (WhiskerClientLib) performs these tasks automatically when youask it to connect to the server.

· ← S

erve

r

no re

spon

se

Success

Clie

nt →

· ·

· ·

· ·

sock

et n

ot c

onne

cted

yet

conn

ects

a so

cket

on

port

1334

Link1_41

Imm

edia

te so

cket

· ·

· ·

· ·

· · ·

· ·

· ·

· ·

· ·

· ←

Ser

ver

Info:WhiskerServerv1.0,blahblah

Info:Youareclientnumberblahblah

ImmPort:1334

Code:1_41

Mai

n so

cket

Clie

nt →

· ·

·

conn

ects

a so

cket

on m

ain

port

the

two

sock

ets a

re n

ow li

nked

and

ope

rate

as a

func

tiona

l pai

r

time →

The main port is usually port 1333. The server will always inform the client of the imme-diate port number, but this is usually port 1334.

Page 64: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 64

5.15 Status information and niceties

WhiskerStatusMessage WhiskerStatus [lines] [clients] [events] [clientnumber(s)]

Originator Client

Details Causes the server to send a whole bunch of status info.Default: general server status report, with help info on syntax.Clients: describes registered clientsLines: reports status and ownership of all linesEvents: reports all pending line/timer eventsClientnumber: restricts reports to numbered client(s). If clientnumber is “*”, refers to thecalling client.

Thus a program interested in the status of all boxes on a system would issueWhiskerStatus clients

while a client wanting a report on its own lines might issueWhiskerStatus lines *

If you send this request down the immediate socket, the response Failure will be given.

This command is not fully implemented.At the moment, it always gives the same general status report.

ReportNameMessage ReportName text

Originator Client

Response No reply

Response(immediatesocket)

Success

Details Tells the server the client’s name.

Example ReportName: Pavlovian-to-instrumental transfer, v. 26-Aug-99

ReportStatusMessage ReportStatus text

Originator Client

Response No reply

Response(immediatesocket)

Success

Details Tells the server what the client’s up to. Text is the status report that will be reported on theserver screen and is available to programs like WhiskerStatus.

Example ReportStatus: rat 6 has made 15 responses

TestNetLatencyMessage TestNetLatency

Page 65: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 65

Originator Client

Details If the client sends TestNetLatency, the server will send Ping. The client should respond withPingAcknowledged as soon as possible. The server will calculate the time difference betweensending the Ping and receiving the PingAcknowledged and report it in the following manner:

Info: Network latency is 15 ms

Do not send multiple TestNetLatency messages very fast, as the server doesn’t keep track ofmultiple outstanding Pings. You will get an abnormally high value as the server matches thePingAcknowledged with a much earlier Ping, or something like that.

If the client wants to test the network latency itself, it can send a Ping; the server will re-spond immediately with a PingAcknowledged. The TestNetLatency command just saves theclient the effort of calculating the time difference.

The Whisker test client supports Ping/PingAcknowledged, as does the C++ client library.

Disabling status messages on the server window reduces network latencies (when debuggingmessages are being reported), from 10/20 ms to 0/10 ms. (Actually, hiding the server win-dow behind another has the same beneficial effect – it’s just that the screen update takes alittle while.)

These commands are supported on the immediate socket. That is to say, whichever socketyou send the command on, the following replies are received on the same socket:

TestNetLatency → PingPing →PingAcknowledgedPingAcknowledged → Info: Network latency is latency ms [on the imm. socket, just

latency].

Comments I suppose 10 ms is the system resolution using timeGetTime()… is this OK? (Have had some11 ms messages.)

RequestTimeMessage RequestTime

Originator Client

Response Time: time

Response(immediatesocket)

time

Details Asks for a Time message to be sent giving the system time (on the server) in milliseconds. Ifyou want to use this timing information (e.g. for latency calculation) and your client lan-guage can’t read the system time sufficiently accurately, you can use this feature of theserver.

Page 66: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 66

5.16 Other messages originating from the server

InfoMessage Info: text

Originator Server

Details Used for all user-oriented reports (such as the response to a WhiskerStatus call). Boxcontrol programs can safely ignore Info messages.

SyntaxErrorMessage SyntaxError: report

Originator Server

Details This will be generated in response to unrecognized and badly-formed commands.

Note that while most commands respond with Success or Failure on the immediatesocket when their parameters are improperly given, unrecognized commands generate theusual “SyntaxError: Unrecognized command” message. This allows failed com-mands to be distinguished from bad commands via the immediate socket.

Example SyntaxError: Unrecognized command.SyntaxError: “ClaimLine” must give a line number.

RequestRefusedMessage RequestRefused: report

Originator Server

Details

Example RequestRefused: ReadState attempted on a line you do not own.RequestRefused: SetState attempted on a line you do not own.RequestRefused: SetState attempted on an input line.RequestRefused: SetState attempted on a nonexistent line.

FaultMessage Fault: report

Originator Server

Details

Example Fault: interface broken

Note Not implemented yet

WarningMessage Warning: report

Originator Server

Details

Example Warning: new timer #15 shares a message with timer #4. Messageis ITI_EXPIRED

Page 67: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide V. Client–server communications 67

Note Not implemented yet

PingMessage Ping

Originator Server

Details The client should respond with PingAcknowledged. This is an optional facility, but if yourclient supports this it makes it much easier for the user to determine whether or not the clienthas crashed (by whether or not it responds to the Ping command).

5.17 A reminder about non-local machinesUnless Allow non-local machines to control lines is ticked on the Server menu, non-localmachines can only ping the server, test network latencies and request status information.All other commands generate an error message.

(If Reject all non-local connections is ticked, of course, non-local machines won’t evenbe able to connect.)

Page 68: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 68

Part 6. Writing clients (behavioural tasks)

I’m first going to discuss the choice of programming language, discuss the principles ofbehavioural task programming, and then walk you through some examples – a Visual Ba-sic client, a brief digression into Perl, and then some C++ clients together with the librarydesigned to simplify client programming in C++.

6.1 Choosing your programming languageThe only requirement of a client language is that it can communicate using TCP/IP sock-ets. This does rule out some languages.

Beginners are probably best off with Microsoft Visual Basic.

Intermediate programmers might like to consider Visual Basic or C++.

C++ is harder to learn but gives you full control over the system; it’s also enormouslypowerful. The programming skills you develop will be useful in many different situa-tions. C++ is the closest to the world standard for ‘real’ programming; knowing C++ andWindows programming will make you sought after. I quite like Microsoft’s C++ devel-opment environment, but it is something of a mixed blessing; you can do a lot veryquickly, but it does hide some of the details from you (which, depending on your per-spective, is a convenient or a confusing thing). It’s also cheap, with an academic licensingsystem.

One other possibility is Perl, a language originally designed for scripting and text proc-essing. It looks pretty obscure at first glance, but half an hour with a book like LearningPerl (Schwartz & Christiansen) should give you all you need to write effective programs.The Perl compiler/interpreter for Windows is free.

Expert programmers don’t need to be told. For your information, the server and test cli-ent were written using Microsoft Visual C++ 6.0 using Winsock. The server runs off asingle timer that polls at 1 ms (or as close to that as the system can manage); when theserver receives this message, it polls its digital I/O boards and checks if any timer eventsneed servicing. All other events are triggered through the Windows or sockets communi-cations system.

6.2 Styles of programming for behavioural tasksThe technique you adopt can make task programming easy or difficult. Think throughyour task carefully before beginning.

Types of task and appropriate programming modelsMost behavioural tasks that I’ve come across use one or more of the following styles ofprogramming.

Free-operant tasksSimple reinforcement schedules fall into this category. Take the example of a ratioschedule: whenever a lever is pressed, a counter is advanced, and whenever the counterreaches a certain number (the ratio requirement), reinforcement is delivered and thecounter is reset.

Page 69: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 69

In Whisker, where everything is driven by events, this is phenomenally easy to code.First, you ask the server to send you a message when a lever is pressed – perhaps Battle-shipPotemkin. Part of your program will receive messages coming from the server. If amessage begins with Event:, the rest of the message should be checked. If you had re-ceived Event: BattleshipPotemkin, then the rat has pressed a lever. Increment your countervariable and if appropriate, send commands to deliver reinforcement.

State modelsAn extension of this model is a state-based system. To be frank, every behavioural taskcan be programmed using this model, but it’s worth considering explicitly. The programmaintains a representation of what state the task is in. When it receives information aboutthe subject’s actions, its response is based on (1) what the subject did, but also (2) whatstate the task is in.

As a very simple example, and an extension of the ratio schedule, suppose you want toignore lever-presses while reinforcement is being delivered. You would implicitly havedefined two possible States of the Box: hanging around waiting and delivering rein-forcement. When the lever-press message comes in and the box is in the delivering rein-forcement state, nothing is done about it; if the box is in the hanging around state instead,the schedule counter is incremented. In this example, you would also set up timers to in-form you when enough reinforcer had been delivered, and this would trigger the state tochange from delivering reinforcement to hanging around. (The transition in the oppositedirection obviously occurs when the rat fulfils the ratio.)

I have found that many novice programmers use state-based programming techniqueswithout really realizing it. I think it is well worth representing the state of the box explic-itly in your code. (There are often more states than you think!)

State models in complex tasks

Sometimes, of course, your task may be too complicated to represent with a single statechain. Perhaps you are training animals to respond under a discriminative stimulus. Dif-ferent stimuli are presented and lever-pressing is measured during each stimulus. Thestimuli are controlled on one progression (e.g. interstimulus interval → S1 → ISI →S2…), and you want to ignore lever-presses while your pump is running, so you imple-ment waiting and delivering reinforcement states as well. It would be easiest to representthese states in two variables (maybe called StimulusSequenceState and LeverState). Thatway the transition from one state to the other is clearly defined for each variable (if a sin-gle variable was used for both, you’d have to work out which stimulus state to go backinto when the reinforcer has been delivered, and so on). The response to a lever-presswould then depend on the conjoint state of both variables – reinforcement would be de-livered when the discriminative S+ was on and the pump was off.

Furthermore, states may be controlled on the basis of time (and therefore, in Whisker,timers). A random interval schedule sets up a ‘ticker’; every second, reinforcement is oris not ‘set up’. When the rat presses a lever, reinforcement is only delivered if it has beenset up by the timer-based schedule. This is another example easily implemented if youthink about the states involved.

Most complicated tasks are very easily represented using state models. For example, thenotorious five-choice serial reaction time task has various states: when a stimulus is pre-sented, for example (the Stimulus On state?), several things can happen: the rat can re-spond correctly or incorrectly, or it can fail to respond within a time limit. There are threestates that the system can move into: a timer will move it into the Omission Timeout state,but before this occurs, a response from the rat can move the system into a Delivering Re-ward or a Incorrect Response Timeout state. (Maybe in this example the two timeouts donot need to be distinguished.)

Page 70: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 70

6.3 Programming benefits of Whisker’s design

Keeping it simpleThe main operant control system used by our lab at the moment is Arachnid (Paul FrayLtd / Cenes, Cambridge). This is an extension of BBC BASIC. In designing Whisker, Iwas particularly keen to avoid the sources of programming error that were common inArachnid programs. Among the most common problems are typing errors, misunder-standings (often due to illegible code), inappropriate use of global variables, failure to de-sign tasks carefully, and cross-talk between boxes.

Some of these problems are due to the choice of language. Replacing an interpreted lan-guage like BBC BASIC with a compiled, strongly type-checked language like C++ vastlyreduces the number of typing errors that find their way into programs – the compilerpicks them up, so you can guarantee that a program that compiles successfully is at leastsyntactically correct. Logical errors can still occur, but C++ encourages you to writesmall, easily testable chunks of code that hide information from each other, so many logi-cal problems (including over-reliance on global variables) disappear.

On the other hand, some programming problems we experienced with Arachnid were dueto weaknesses in the design of the system. When a program must control six operantboxes, the potential for errors increases; it is the programmer’s responsibility to makesure that every switch and timer event is tagged to the correct box, to create a systemwhereby different boxes can run asynchronously, and so on.

Whisker follows the Unix philosophy instead: rather than one huge program, create lotsof small ones. If one program only controls one box, errors of cross-talk are simply notpossible.

Most of the programming examples I have supplied only control a single box. The excep-tion is the SecondOrder task, which can control other boxes for the purpose of yoking. Inthis case, all the potential for cross-talk exists. The program calls its events things likeYoke_4_Active_Lever, and passes the Active_Lever part of this message on to a datastructure representing the fourth yoked box. (SecondOrder follows the C++ principle ofrepresenting each operant chamber as an independent object which stores its own data.)Theoretically, it would have been possible to implement yoking by running two kinds ofclients simultaneously, one controlling all the boxes using Whisker’s line-grouping facil-ity (discussed earlier, in Part V) and the other reading inputs from the yoked boxes, butthen there’s a problem of synchronizing the two programs; it would really have been im-practical.

Naming your eventsYou could name your events after Russian films, but that would be silly. More usefulwould be to define events like NOSEPOKE_ON, which is what I tend to do. But there’sno reason why you can’t change the event name during the task to make it simpler to pro-cess events – for example, you could set things up so that the nosepoke detector generatesINITIATE_TRIAL sometimes and REWARD_COLLECTED at others.

Events: a comparison to ArachnidFor those of you that are familiar with Arachnid, a direct comparison may be helpful. InArachnid, you execute PROCpipe_switch() and PROCpipe_timer() calls,passing the name of a BASIC function of your own. When the event occurs, Arachnidcalls your function.

Whisker gives you control at one level higher up. You can receive all the messages com-ing from the server, and decide what to do with them – which might involve calling other

Page 71: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 71

functions, just as Arachnid would have handled it, but it doesn’t have to. It’s a more pow-erful system and it makes for simpler code in some situations.

Technicalnote

Of course, it is nice at times to be able to set up a complex sequence of events and have it happen withoutfurther interference; the Whisker C++ client library provides this kind of functionality. One can, for exam-ple, ask for a message to be sent to the server after a specified delay, and the library can do this for you.(Internally, it asks the server for a timer of its own, whose name begins with _sys, and it remembers whatyou wanted done when that timer elapses. The point is that this detail is hidden from you.) Visual Basicprovides similar functionality by supporting re-entrant functions via the DoEvents command.

Page 72: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 72

6.4 VBRatioClient: a Visual Basic example

About VBRatioClientVBRatioClient is an extremely simple Visual Basic client that implements a ratio sched-ule. You can set the ratio requirement. It also implements a 1-minute timer; when thistimer expires, the program ends and stores its data in a comma-delimited text file.

I hope it will be easy for you to develop into a task of your own, should you decide thatVisual Basic is the language you want to use.

What to do if you want to develop this into a task of your ownI suggest you make a copy of the whole project and explore the code – it’s quite short.You’ll probably find it useful to keep those parts of the code that communicate with theserver (including cmdConnect_Click, tcpClient_DataArrival, Send and Parse), but you’llwant to change the functions that deal with the task itself (particularly LineNumber,ClaimLines, StartRatioSchedule, WhiskerEvent, StopTask and TaskFinished). The otherfunctions are largely cosmetic.

Simple networking with Visual BasicThe code in this section is for a minimal Visual Basic (VB) client that talks using thenetwork. That was the starting point for this behavioural task.

This section assumes you own VB and have installed it.

Page 73: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 73

Technicalnote

SourceThis example used Visual Basic 5.0 Professional, and the code is lifted from the “ActiveX Winsock control”documentation. Windows Sockets support comes built-in with VB version 5 and above. You need this. (Ifyou have VB 4, you can get a third-party add-on, or upgrade.)

• Create a new project of type Standard EXE. Change the caption of Form1 to ‘MyTCP client’ or something you prefer.

• Add a Winsock control to your form (click on the Winsock control button on thetoolbar, then drag on your form). If you can’t see the control on the toolbar, use Proj-ect → Components, tick Microsoft Winsock Control 6.0 and click OK. This will addthe control to the toolbar so you can use it. Change the name of the Winsock controlfrom “Winsock1” to “tcpClient” (or something).

• Add two TextBox controls to the form. Name them txtSend and txtOutput.• Add a CommandButton control and name it cmdConnect. Change its caption to

‘Connect’.• Add another CommandButton called cmdSend, with the caption ‘Send’.• Choose View → Code to see the form’s code. Add the following code to the form

(just paste it in; you don’t have to type the comments, which are lines beginning withan apostrophe):

Private Sub Form_Load()' The name of the Winsock control is tcpClient.' Note: to specify a remote host, you can use' either the IP address (ex: "121.111.1.1") or' the computer's "friendly" name, as shown here.tcpClient.RemoteHost = "loopback"tcpClient.RemotePort = 1333

End Sub

Private Sub cmdConnect_Click()' Invoke the Connect method to initiate a' connection.tcpClient.Connect

End Sub

Private Sub cmdSend_Click()tcpClient.SendData txtSend.Text' When you click the "Send" command button, this sends' the contents of the "txtSend" text box to the "tcpClient"' Winsock control.

End Sub

Private Sub tcpClient_DataArrival _(ByVal bytesTotal As Long)

' please note, that _ at the end of the line and starting a new' line for "(ByVal..." is deliberate.Dim strData As StringtcpClient.GetData strDatatxtOutput.Text = strData

End Sub

• You may want to change the parts in bold to reflect the IP name/address and portnumber of your Whisker server. Use “loopback” if the server is running on the samemachine as the client. Port 1333 is the default.

• Save the project.• Start the server and run the project (click the ► button). You should be able to con-

nect, see messages coming from the server, and issue commands.• When you want to compile your project to an executable (.EXE) file, choose File →

Make Project1.exe (this may show a different name if you have renamed the project).Choose a filename and click OK.

Page 74: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 74

Technicalnote

ExecutableThe resultant executable file will run directly on any computer with VB installed, or the necessary subcom-ponents – in this case, a VB library and the Winsock component, MSWINSCK.OCX

• You might like to experiment with changing the txtOutput text box to a list box, soyou can see several recent messages from the server. But that’s just cosmetic.

From simple networking to a behavioural taskWe already have code that talks to the server, which took me about 3 minutes to createthe second time round. From there, it’s a short step to a fully-fledged task. We add somesophistication to the message receiver (so if messages from the server get concatenated,we can disentangle things), and then we design the task itself and the front end.

Here’s some code from VBRatioClient.

This is part of the code handling communications with the server.Private Sub tcpClient_DataArrival _(ByVal bytesTotal As Long)

Dim strData As StringtcpClient.GetData strData

Dim semipos, crpos, lfpos, pos As IntegerDim truncate As BooleanDo

truncate = Falsepos = Len(strData)semipos = InStr(strData, ";")If semipos > 0 Then truncate = True: pos = semiposcrpos = InStr(strData, Chr(13))If crpos > 0 Then truncate = True: If crpos < pos Then pos = crposlfpos = InStr(strData, Chr(10))If lfpos > 0 Then truncate = True: If lfpos < pos Then pos = lfposIf truncate Then

Parse (Left(strData, pos - 1))strData = Right(strData, Len(strData) - pos)

End IfLoop While truncate = TrueIf Len(strData) > 0 Then Parse (strData)

End Sub

Sub Send(message)tcpClient.SendData message + ";"If chkLogComms.Value = 1 Then

txtSent.Text = txtSent.Text + message + Chr(13) + Chr(10)End If

End Sub

Sub Parse(message)' Display the text, just for funIf chkLogComms.Value = 1 Then

txtReceived.Text = txtReceived.Text + message + Chr(13) + Chr(10)End If' You need both CR+LF. Took me a while to work that out!' Also, text box needs to be multiline.

' Do something relevant.If message = "Ping" Then Send ("PingAcknowledged")

' We'll use a somewhat ugly method of seeing if our claims worked' (since VB doesn't appear to support non-blocking sockets)If Left(message, 15) = "ClaimRejected: " Then

claimed = Falserunning = False ' Not really necessary!UpdateButtonStatesSend ("RelinquishAllLines")

End If

Page 75: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 75

' Deal with all Event messagesIf Left(message, 7) = "Event: " Then WhiskerEvent (Right(message, Len(message)

- 7))End Sub

With that kind of code done, we can forget about the underlying communications systemand get down to business. This is part of the code dealing with the behavioural task, and italso updates the display to reflect the number of lever-presses.Sub StartRatioSchedule()

' Get and check the parameters of the task.ratioRequirement = Val(txtRatioRequirement.Text)If ratioRequirement <= 0 Then MsgBox ("Invalid ratio requirement!"): Exit Sub

pressesThisRatio = 0pressesTotal = 0reinforcements = 0Dim sessionduration_ms As Longsessionduration_ms = 60000 ' one minute session

Send ("SetState Houselight on")Send ("SetState LeftLeverControl on")Send ("RequestLineEvent LeftLever On LeverPressed")Send ("RequestTimerEvent " + Str(sessionduration_ms) + " 0 SessionFinished")' remember, it's "RequestTimerEvent duration reloadcount message"

running = TrueUpdateButtonStates

End Sub

Sub WhiskerEvent(eventmessage)' This is where most of the task-specific code lives

If eventmessage = "SessionFinished" ThenTaskFinishedExit Sub ' no point staying here

End If

If eventmessage = "LeverPressed" ThenpressesTotal = pressesTotal + 1pressesThisRatio = pressesThisRatio + 1labelLeverPresses.Caption = Str(pressesTotal)

If pressesThisRatio >= ratioRequirement Thenreinforcements = reinforcements + 1pressesThisRatio = 0labelReinforcements.Caption = Str(reinforcements)

Dim start, pausetimestart = Timerpausetime = 1 ' in seconds

Send ("SetState PelletDispenser on")Do While Timer < start + pausetime

DoEvents ' Yield to other processes.LoopSend ("SetState PelletDispenser off")

End If

End IfEnd Sub

Comments on the suitability of Visual Basic

Benefits

VB is a very easy language to use, and it makes it very easy to interface to a Windowsdisplay (when you change a variable, the display on the screen is updated automatically).

VB has a lovely function called DoEvents, which enables the program to wait for a cer-tain time, but to have other events being processed at the same time (using re-entrant

Page 76: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 76

functions). This completely removes the need for a great many timer events. There’s anexample shown above; while one part of the program is waiting for the pellet dispenser,the same program can also respond to lever-presses. You do have to be a little carefulwith re-entrant functions (in particular, not to fiddle with global variables in certain ways,and not to allow too many re-entrant calls; these issues are discussed in the VB on-linemanual).

DeficitsI’m not sure how accurately VB can read the system time. I suspect that its functions fordoing this (Timer, Time) are only accurate to 1 s. If you need to get the time more accu-rately, you can always ask the server using the RequestTime call.

I don’t think VB supports blocking (immediate) sockets, which could cause some prob-lems.

Page 77: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 77

6.5 Networking in PerlI have not written a full behavioural task in Perl, because I don’t think it’s very suitable.However, code is given below as an example of using network communications in Perl;the example is a Perl version of the WhiskerStatus program.

Obtaining and installing PerlPerl for Win32 is available free, from http:/ /www.ActiveState.com/. Follow the installationinstructions that accompany the software.

Writing code for Perl and running Perl programsEssentially, you use a text editor to create a Perl script, usually called something.pl.Then you can simply type something.pl from the command line, passing it furtherarguments as necessary.

A simple TCP client: implementing a status program in PerlHere’s an example of network communications using Perl. You can run it as

whiskerstat.pl somewhere.psychol.cam.ac.uk

#!/usr/bin/perl –w# PIT.pl# --------------------------- Call this file "WhiskerStat.pl".# Note that Perl comments are preceded by a hash (#)require 5.002;use Socket;

# --------------------------- Say hello

print "\n\nWhiskerStat.pl\n\n";

&LogIn(@ARGV);

&Send("ReportName WhiskerStat status program");&Send("ReportStatus Absolutely fine.");&Send("WhiskerStatus");&Send("TestNetLatency");

while ($line = <SOCK>) {# The server has sent us a message. Deal with it.if ($line =~ /Ping/) { &Send("PingAcknowledged"); }print $line;

}

&LogOut();print "All done.\n";exit;

# -----------------------------------------------------------# --------------------------- Networking routines.# -----------------------------------------------------------

sub LogIn {# Get parameters from the command line, or acceptable defaults

my ($remote,$port, $iaddr, $paddr, $proto, $line);$remote = shift || 'localhost';$port = shift || 1333; # default portif ($port =~ /\D/) { $port = getservbyname($port, 'tcp') }die "No port" unless $port;

# Connect to the server

$iaddr = inet_aton($remote) || die "no host: $remote";$paddr = sockaddr_in($port, $iaddr);$proto = getprotobyname('tcp');socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "can't make socket: $!";

Page 78: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 78

connect(SOCK, $paddr) || die "can't connect: $!";print "Connected to " . inet_ntoa($iaddr) . "\n\n";

select(SOCK); $| = 1;# This is vital to ensure that output to the socket# gets sent immediately. Otherwise it hangs around for ever# (literally) in some circumstances.

select(STDOUT);# Output goes to the local console once more.

}

sub LogOut{

close (SOCK) || die "close: $!";}

sub Send {# This sends something to the server, with a trailing newline.# Use it like Send("Hello ","I am " . " a ", "fish");print SOCK @_;print SOCK "\n";

}

Comments on the suitability of PerlI haven’t written anything more complex by way of a behavioural task in Perl. Though Ifeel it’s a great script language, I don’t think it’s very well suited to moment-by-momentreal-time control. Maybe I’m wrong, but if you want to do this, you’re on your own.

Page 79: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 79

6.6 SimpleCPPClient: a C++ console-mode example

About SimpleCPPClientThis is a task so simple as to be useless behaviourally – it extends a lever, records up toten lever-presses, times out after a minute and stores the response times. Nevertheless, itillustrates communication with the server, controlling outputs, responding to timers andinput devices, and data output in a comma-delimited format suitable for importing di-rectly into a database. Furthermore, it is one of the easiest kinds of client to write in C++,because it doesn’t really any Windows graphical user interface programming. You canrun the task from the Start menu:

When running, it looks like this:

The source code is provided in the SimpleCPPClient directory. If you want to open proj-ects (‘workspaces’) in Visual C++, double-click on the *.dsw files (in this case, Sim-pleCPPClient.dsw). The process of writing such an application is documented in the fol-lowing files:

• Building this program – quickly!.txt• Building this program – from scratch, in detail.txt

It would be easy to copy this application and modify it to perform a more useful task. Asthis is meant to be a programming exercise, I’ll leave the rest to you.

Learning C++If you would like to learn C++, I suggest you get a good compiler. The compiler is theprogram that converts the source code (in textual format) into an executable program,finding your typing mistakes along the way. There are some pretty good free C++ com-

Page 80: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 80

pilers; one is DJGPP, available at http:/ /www.delorie.com/djgpp/. Mind you, if you’re in anacademic environment you can get a very cheap version of Microsoft Visual C++ 6.0Professional, which is what I use.

In addition, you’ll want a book or an electronic tutorial. Bear in mind that most books onlearning Visual C++ (Microsoft’s product) are concerned more with Windows program-ming than on the language itself, but you should start with a plain C++ tutorial. I’m notsure what the best one for beginners currently is. The definitive reference is Stroustrup(1997), The C++ Programming Language (3rd Edition), though the book is oriented to-wards programmers with some experience. Stroustrup created C++ (see alsohttp:/ /www.research.att.com/~bs/). There are additional literature references at the end of thisGuide.

Building programs in C++The actual process depends on the compiler. If you have loaded a workspace into VisualC++, you can press F7 to compile the application, and Ctrl-F5 to run it.

An introduction to WhiskerClientLibSeveral of the C++ clients supplied with Whisker (including SimpleCPPClient, Whisker-Status and SecondOrder) use the WhiskerClientLib library. A library is a collection ofcode to perform certain functions; its purpose is to save you reinventing the wheel. In thecase of WhiskerClientLib, the library contains a set of routines that automate connectingto and communicating with the server and also assist in the creation of behavioural tasks.More detail is given on page 81.

If you want to change and rebuild SimpleCPPClient, see also the notice regarding Debugand Release modes on page 84.

Comments on the suitability of C++C++ is a general-purpose programming language; as such, you can do pretty much any-thing in it. If it’s not obvious from the rest of this guide, it’s my favourite programminglanguage.

Page 81: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 81

6.7 WhiskerClientLib – a library for writing C++ clientsTo simplify the process of writing tasks in C++, I have written a library of routines thatsimplify the process of communicating with the server and provide some useful behav-ioural functions.

Full source code is supplied in the WhiskerClientLib directory (by default, \ProgramFiles\Rudolf Cardinal\Whisker\WhiskerClientLib). The compiled libraries are to be found inthe Debug and Release subdirectories. (Which of these two versions you will use will de-pend on your compilation settings, discussed below.)

Classes to help you write clientsOne of the key concepts in C++ is that of code re-usability. Since I’ve written all the codeneeded to create a client task, you shouldn’t have to. All you need to do is to use theclasses that I created. A class represents an object in a very general sense; in this case, abehavioural task. The main class designed to help you is called CWhiskerTask, and hereare the functions that it offers you:

Extract from WhiskerTask.h

class CWhiskerTask{

typedef void (CWhiskerTask::*WhiskerFuncPtr)(const CString&); // the type of acallback function

public:

// The client is expected to override some or all of these

virtual void ServerConnected(); // main connection has just been madevirtual void ServerFullyConnected(); // main and immediate sockets are both con-

nectedvirtual void ServerDisconnected(); // Called when communication is lostvirtual bool PollPipedEvents(const CString& msg); // override to 'pipe' your own

events: return true to prevent them from getting to IncomingEvent()virtual void StatusMessage(const CString& msg); // Override to handle status

messages from this libraryvirtual void IncomingInfo(CString msg); // an Info message has arrivedvirtual void IncomingError(CString strError); // an Error message has arrivedvirtual void IncomingEvent(CString strEvent); // an Event message has arrivedvirtual void IncomingOther(CString strMessage); // some other kind of message

has arrived

// These are just example functions - can override if you want

virtual bool ClaimLines(int iBox); // override to claim lines for this boxvirtual bool StartTask();virtual void EndTask();virtual void AbortTask();virtual bool IsClaimed(); // has a successful call to ClaimLines been made?virtual bool IsRunning(); // is the task running?

// The client is expected to call these to talk to the network

bool ConnectToServer(const CString& strServerName, int iPort);void Send(const CString &msg); // sends msg to servervoid ImmediateSend(const CString &msg); // sends msg to immediate socketbool ImmediateBoolean(const CString& question); // sends question on immsocket,

returns success/failurebool ImmediateSocketQuery(const CString& out, CString& in); // sends "out" on

immsocket, puts reply in "in"CString ImmediateSocketQuery(const CString& question); // sends "question" on

immsocket, returns reply

// Extra network functions - icing on the cake

CString ThisComputerName(); // returns the IP name of this host

Page 82: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 82

// Useful operant control functions

void RequestTimerEvent(const CString& strEvent, unsigned long timeInMs, int iRe-petitions = 0); // request a timer event from the server

int LineNumber_BoxGroupings(int Box, int LineWithinBox, int MaxLines); // calcu-late line number in "all box 1, all box 2..." system

int LineNumber_DeviceGroupings(int Box, int LineWithinBox, int MaxBoxes); //calculate line number in "all houselights, all traylights..." system

void SendAfterDelay(const CString& strMsg, DWORD delay, const CString& strEven-tLabel = ""); // send a message after a given delay

void GivePellets(const CString& strLine, int numPellets, DWORD interpellet_time= 500); // dispenses pellets

void SwitchOn(const CString& strLine); // switch a line onvoid SwitchOff(const CString& strLine); // switch a line offvoid FlashLineNumber(const CString& strLine, int iCount, DWORD on_time, DWORD

off_time, bool bOnAtRest = false); // flashes the line iCount timesvoid FlashLineTime(const CString& strLine, DWORD duration, DWORD on_time, DWORD

off_time, bool bOnAtRest = false); // flashes the line for "duration" msCString StartFlashLine(const CString& strLine, DWORD on_time, DWORD off_time,

bool bOnAtRest = false); // starts the line going; returns its event labelvoid StopFlashLine(const CString& strLine, const CString& strEventLabel, bool

bOnAtRest = false); // stops the flashing

// Calculation functions

DWORD Minutes_ms(int minutes) {return minutes*60*1000;}; // converts minutes toms

DWORD Seconds_ms(int seconds) {return seconds*1000;}; // converts seconds to msfloat FoodMass_g(int pellets) {return pellets*0.045;}; // pellet is 45 mgfloat LiquidVolume_ml(int dips) {return dips*0.05;}; // dipper is 0.05 ml

// Useful string manipulation functions

bool GetPrefix(const CString& msg, CString& prefix, CString& remainder); // IN:msg from server. OUT: message prefix and remainder

int GetIntegerParam(CString &strSentence); // chops first word out of sentenceand converts it to a number

void GetNextWord(CString &strWord, CString &strSentence); // chops first wordout of strSentence, stores in in strWord

// Other handy stuff

CString UniqueString(); // returns a unique stringfloat RandomProbability(); // returns random float, 0-1int RandomInt(int max); // returns a random integer, 0-maxint RandomInt(int min, int max); // returns a random integer, min-maxbool Chance(float p); // returns true with probability pvoid SeedRandomNumberGenerator(); // seeds random number generator with system

clockDWORD CurrentTime(); // return system time (ms)

// Discrete probability distributions.

double PoissonRV(int lambda); // returns a random variable from the Pois-son distribution

double PoissonCDF(int x, int lambda); // the Poisson cumulative distributionfunction

double PoissonPDF(int x, int lambda); // the Poisson probability distributionfunction

double LinearInterpolation(double x_query, double x1, double x2, double y1, dou-ble y2); // Linear interpolation. If x1->y1 and x2->y2, x_query->???

long double Factorial(int x);int Round(double x); // Rounds the number (>=.5 up, <.5 down).

// The client is unlikely to need these, but may override some

virtual void ShutDown(); // releases timers/events/lines and closesvoid DisconnectFromServer(); // closes all socketsvirtual void IncomingMessage(CString strRecvd); // handles raw incoming data

from socketvirtual void Parse(CString& msg); // handles CR/semicolon-stripped messages;

also deals with immsocket connection and pingingbool ConnectImmediateSocket();bool IsConnected();bool IsImmediateConnected();CWhiskerTask();virtual ~CWhiskerTask();void SocketConnect();

Page 83: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 83

void SocketSend();void SocketConnectError();void SocketClose();void ImmSocketClose();

// ...

}

I’m not going to go through all of these functions in detail. You have the library sourcecode, which is commented, and you have several examples of clients that use the library(SimpleCPPClient, WhiskerStatus, and a fully-fledged task, SecondOrder). If you knowC++, that should be enough to get you going. Remember, the virtual functions are theones you might override; the others are functions you call actively.

Note that CWhiskerTask provides a whole host of useful functions. Try looking therebefore you write a routine yourself.

Technicalnote

Several of the library functions use callback functions. If I was writing ‘pure’ code, I’d probably have madethem of type CObject* (since the library is written using MFC) and use run-time type information (RTTI) toestablish what parameters were actually coming into a particular callback function. This would allow apointer to any CObject-derived class to be passed.

Instead, I made the parameter of type const CString& (that is, a reference to a constant [immutable]CString). This necessitates using CString::Format to pack parameters into a string, and there are some cus-tom routines in the library to extract them.

It’s not as neat; why do it? Basically, I felt it was too optimistic to expect users to manage explicit castsand RTTI checking, even though it makes for poorer code. Everyone understands strings.

Technicalnote

Implementing callback functions for your own classesFor technical reasons, you have to do a little bit of work as the client here. These instructions assume yourclient task (CMyTask) is derived from CWhiskerTask.

You should include this snippet in your class definition:

class CMyTask : public CWhiskerTask{// ...CPipedEventList<CMyTask> m_PipedEvents;bool PollPipedEvents(CString msg) { return m_PipedEvents.Poll(); }// ...

}

Then, to use the code, your callback function must take a single const CString& parameter, and returnvoid. Then you can do this (the example is to deliver a single pellet):

void CMyTask::PelletOn(){Send(“SetState PELLET on”);Send(“RequestTimerEvent 40 0 _pellet_dispensed”);m_PipedEvents.AddEvent(“_pellet_dispensed”,

this,&CMyTask::PelletOff,“hey there”,PIPED_EVENT_NUMBER,1);

}

void CMyTask::PelletOff(const CString& message){// message will contain “hey there”,// but it could contain something useful!Send(“SetState PELLET off”);

}

This code is unnecessary as you could just have used SendAfterDelay(“SetState PELLET off”, 40), but it illus-trates the principles.

Page 84: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 84

Well, on to the practicalities.

Creating console-mode C++ applications for WhiskerThe discussion of SimpleCPPClient (page 79) covers this. In particular, the text fileBuilding this program – from scratch, in detail.txt gives you step-by-step instructions.

Creating Windows-based C++ applications for WhiskerIn Visual C++, to create the skeleton of a Windows simple application you just followthese steps:

1. File → New → Project → MFC AppWizard (exe) → give it a name and a directory2. Choose type (SDI, MDI, dialogue). I’m going to use dialogues for a while because

they’re easier.3. Include support for Windows Sockets.4. Accept all the other defaults.

Creating a behavioural task using the library

Include the library files in the projectRegardless of the type of application you create, you will next want to include theWhiskerClientLib library in your project. Choose Project → Add To Project → Files,look for files of type Library files (*.lib) and choose either

WhiskerClientLib\Debug\WhiskerClientLib_Debug.lib

or

WhiskerClientLib\Release\WhiskerClientLib_Release.lib

Choose the version of the library that matches your compilation settings; see below.

Derive your task’s class from CWhiskerTaskThe core of the behavioural task is a class derived from CWhiskerTask.

Insert a new class (Insert → New Class) and name it (within the SecondOrder program, itwas called CSecondOrderTask). Make it a generic class, and tell the compiler that it’s de-rived from CWhiskerTask with public inheritance.

Include the library header fileFinally, so your code knows what’s in the library, add the following line to your newclass’s header file:

#include “../WhiskerClientLib/WhiskerTask.h”

Depending on the directory you are developing your project in, you’ll need to edit thepath in that statement so that it does actually reach WhiskerTask.h!

Debug and Release mode in Visual C++, and the Whisker client libraryOne important thing. Visual C++ applications can be compiled in two modes, Debug andRelease. Compiling a project in Debug mode builds information into the resulting pro-gram that can be used for debugging; if the application crashes, you can step through thesource code to find out where, and so on. Release mode is used for finished products: theresulting file is smaller, but it doesn’t contain debug information. You can also let the

Page 85: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 85

compiler optimize the code for speed or size when you use Release mode (though I haveavoided this since I found some bugs in the VC++ 6.0 optimizer, i.e. it screws the code upsometimes).

Given a choice, I would have distributed SimpleCPPClient in Debug mode – after all, it’sa programming example and not a useful behavioural task. However, I’m not allowed todistribute the libraries that you need to run Debug mode applications.

If you own Visual C++ and want to switch SimpleCPPClient back into Debug mode,open its project by double-clicking on SimpleCPPClient.dsw and choose Build → Set ActiveConfiguration. Change the setting to Win32 Debug. When you next build the project (justpress F7) it will be in debug mode.

I’m afraid there’s one other thing to do first. You can’t mix debug and release libraries, soI’ve had to create two versions of the WhiskerClientLib library which this applicationuses. Rather than hide it away, I’ve tried to make it very obvious: if you switch the left-hand view to FileView, you should see WhiskerClientLib_Release.lib in the file list. Youshould delete this, then choose Project → Add To Project → Files, look at files of typeLibrary Files (*.lib) and double-click on WhiskerClientLib_Debug.lib which lives in theWhiskerClientLib\Debug directory.

This applies to every application built using WhiskerClientLib; if you want to com-pile in Debug mode, use the debug version of the library; for release builds, switch to therelease library.

Warning. If you mix debug and release-mode libraries (i.e. by building your program indebug mode and linking in the release mode of WhiskerClientLib, or vice versa), you willget a few warnings as you build the program. The compiler will let you run the code, butit may CRASH at some unpredictable moment. Don't ignore the warnings! Use the properlibrary. The errors you get look like this:LINK : warning LNK4098: defaultlib "mfc42.lib" conflicts with use of other libs;use /NODEFAULTLIB:library

Page 86: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VI. Writing clients 86

6.8 A few last suggestions

DebuggingThe Server Is Your Friend. Use its debugging facilities and monitor what your program isdoing.

Front endsA text-based (console mode) front-end offers little opportunity for the user to wreak mis-chief. However, Windows-based front ends typically offer a host of buttons to press ormenu items to choose; you must ensure that the user can’t do anything inappropriate (likedisconnect from the server without saving the data, or trying to connect twice). The usualway of achieving this in Windows is to grey out the relevant buttons so they can’t be se-lected. Both VBRatioClient and SecondOrder demonstrate this technique.

Controlling multiple boxesThink twice before doing this. One of the strengths of Whisker is that you often don’tneed to; you can run a second copy of a simple one-box program. If you do need to con-trol several boxes from the same program, remember the following:

• For yoking, you can always give two output lines the same name and they’ll be con-trolled as one.

• You must name your inputs so you can distinguish them (e.g. Box_1_LeftLever,Box_2_LeftLever).

• Be extremely careful not to introduce ‘cross-talk’ errors, when you misdirect data orcommands to or from the wrong box.

The SecondOrder client gives several examples of these techniques.

Page 87: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VII. Principles of data collection 87

Part 7. Data collection: principles and prac-tice

Know the rulesMy philosophy of data collection can be summarized in three rules:

1. Never type in data;

2. Collect all the data you could possibly want, from the word go, in a structured format;

3. Worry about what to do with it later.

DatabasesI have found the most useful way to store data is in a relational database, often called arelational database management system (RDBMS). A relational database stores data intables, which are made up of fields and records:

A table five fields:Date Rat NumResponses NumStimuli NumReinforcements

one record: 17/2/00 12:29:00 M4 56 5 1another: 17/2/00 14:37:06 M5 437 43 8

… and so on 17/2/00 12:54:00 M4 263 26 5

The driving principle behind a relational database is this: never duplicate data. Let’s sayour rats came from two groups, Sham and Lesion. If we wanted to record this in the data-base, so we could analyse data by group, we could store it like this:

Table BigDataDate Rat Group NumResponses NumStimuli NumReinforcements17/2/00 12:29:00 M4 sham 56 5 117/2/00 14:37:06 M5 lesion 437 43 817/2/00 12:54:00 M4 sham 263 26 5

However, this introduces two problems. Firstly, it generates very large tables. Secondly,and more importantly, it is unclear what to do if the data is inconsistent – let’s say the un-derlined ‘sham’ was changed to ‘lesion’ by mistake. The database would then not knowwhether rat M4 was in the Sham or Lesion group – there would be entries for both. Thesolution to both problems is to create two tables, linked on the smallest possible unit ofinformation (in this example, the rat name):

Table ResponsesDate Rat NumResponses NumStimuli NumReinforcements17/2/00 12:29:00 M4 56 5 117/2/00 14:37:06 M5 437 43 817/2/00 12:54:00 M4 263 26 5

Table GroupsRat GroupM4 shamM5 lesion

Page 88: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VII. Principles of data collection 88

By using the rat name as a key (also known as a foreign key), the database can link thetwo tables together whenever we want to know how many responses the two groups madeon average.

When we want to find out that sort of information, we query the database, specifyinghow we want to see the data. We could, for example, obtain the following (ignoring vari-ous scientific flaws!):

Query AverageByGroupsGroup NumberOfRats MeanNumResponses MeanNumStimuli MeanNumReinforcementssham 2 159.5 15.5 3lesion 1 437 43 8

Summary of database principlesSo relational databases split up the data (which should be entered in well-designed tableswithout any duplication of information) from queries that look at the data in an infinitevariety of ways.

A concrete example: Microsoft Access 97Microsoft Access 97 is a commonly-used relational database for PCs. It isn’t perfect, by along shot, but I’ve found it good enough. It supports structured query language (SQL)for designing queries; this is a powerful quasi-English language. For example, the queryshown above would be written in SQL like this:

SELECT group,count(*) as NumberOfRats,avg(NumResponses) as MeanNumResponses,avg(NumStimuli) as MeanNumStimuli,avg(NumReinforcements) as MeanNumReinforcements

FROM responses, groupsWHERE responses.rat = groups.ratGROUP BY group;

If you find all this a bit cryptic, Access also provides a graphical interface for designingqueries.

Getting data out of a databaseGiven a well-designed database, you should be able to get the data out in any conceivableway. The size of this manual doesn’t permit a detailed look at relational database designor queries, but there are abundant sources. If you use Microsoft Access, there’s the helpsystem, but I also recommend Viescas JL (1997), Running Microsoft Access 97, Micro-soft Press. Beyond that there is a whole field of database design.

Tip I operate on the principle that any view of the data is achievable. If the graphical query design can’t do it,you can use SQL. If SQL can’t do it alone, you can use Visual Basic to augment it. If all that fails (and ithasn’t failed me yet) you can always re-export the data and use a general-purpose programming languageto analyse it. If the data’s there, you can get at it.

One thing is worth noting: modern statistical packages (e.g. SPSS, http:/ /www.spss.com/)are starting to support the ODBC standard for exchanging information with databases.You can set up database queries to create views of the data that your stats packages canuse, then set up sequences of ODBC capture, analysis and graphical presentation in yourstats package. Then whenever you import new data, you can run the entire analysis in amatter of seconds. If you handle large volumes of data, it easily repays the initial effort.

Page 89: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VII. Principles of data collection 89

Getting data into a database

The direct methodIt is possible for behavioural tasks to store data in a database directly. The SecondOrderclient (discussed earlier) does exactly this. It asks you which database you’d like to use,and then stores data in five tables in the correct format. It’s very easy to use! It’s not thathard to program, either, if you use Visual C++ (which can set up classes for you to exportdata to a given database).

The indirect method

A method which needs less programming skill, and can apply to a great variety of lan-guages and computers, is to export your data in an ASCII text file. The trick is to save thedata in a format which is easily importable into a database. Regrettably, there is no easyway to save data destined for multiple database tables into a single text file. Therefore Iadvocate the procedure of saving one text file per table. They should be saved in comma-delimited format, with the field names on the first row. Our example data might havecome from two files looking like this:response-Feb2000.txtDate,Rat,NumResponses,NumStimuli,NumReinforcements2/17/2000 12:29:00,M4,56,5,12/17/2000 14:37:06,M5,437,43,83/17/2000 12:54:00,M4,263,26,5

groups.txtRat,GroupM4,shamM5,lesion

It is very easy to import data in this format into Access (choose File → Get External Data→ Import, choose your text file, ensure that you choose Delimited format and that FirstRow Contains Field Names is selected; then simply choose the table to put the data in).

Amalgamating multiple files

A problem I had with this method is that it did take a long time to import every singlefile. So I wrote a small utility called amalgam.pl (written in the language Perl) to amal-gamate lots of similar files that were all destined for the same database table, in such away that the header row (with the field names) only appeared once.

This tool is supplied with Whisker, in the Amalgam subdirectory (by default, in \ProgramFiles\Rudolf Cardinal\Whisker\Amalgam). To use it, you will need to obtain Perl (fromhttp:/ /www.ActiveState.com/) and install it. (I’m afraid that their distribution terms preventme from supplying you with a copy together with Whisker.)

You can either copy amalgam.pl to a directory that is on your path, or you can add thedirectory containing amalgam.pl to the path. To do the latter, choose Control Panel →System → Environment. Click on the Path variable and edit the Value field to append thedirectory that Amalgam is in, using semicolons to separate consecutive path entries (e.g.;d:\program files\rudolf cardinal\whisker\amalgam;). Then click Set and OK. If you change theSystem path, you’ll affect all users of the system; if you change the User path, only yourown user. Only administrators can change the system path.

Once you have that set up, simply fire up a command prompt and change to the directorycontaining your data. Let’s say you have a whole host of response data files, called re-sponse-Jan2000.txt, response-Feb2000.txt, response-Mar2000.txt,and so on. You can issue this command:

amalgam.pl big-response-file.txt response*.txt

Page 90: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VII. Principles of data collection 90

and it will create a single file, big-response-file.txt, that you can import intoAccess in one step. If you want to import into five tables, you are aiming to generate fivefiles. (Amalgam will not let you merge files that have different headers.)

A note on dates

Access’s text import facility will only recognize dates as such if they are in a very par-ticular format. For the UK, it is this:

17/03/2000 15:30:05

and this depends on telling Windows that you are in the UK in Control Panel → RegionalSettings. (Specifically, Access recognises the “short date” and “short time” pictures set upin Control Panel.) It is so useful to have date/time-stamping of your data (and so awkwardto configure the Access’s import facility differently) that I strongly suggest you configureyour regional settings and write your behavioural tasks to save data to disk in this format.

Recovering data from old applications

Data in ASCII format

Of course, you may not have the luxury of redesigning your task to store data in a ma-chine-friendly format. If you’re lucky enough to have electronic output in ASCII form, itmay not be in neat comma-delimited files but look more like this:d62-990519.txtBox 6: 62 - ; Wed,19 May 1999.12:41:50, 200 min sessionRIGHT Lever active: Overall FR 1, FR 1 for CSReinforcements per spell: 1CS duration (csec): 100Reinforcement delay (csec): 100Lever retraction time (csec): 2000Reinforcement duration (csec): 728

Active: 59 Inactive: 13 Stimuli: 44 Reinforcements: 44

...

All great for a human to read, but a pain for a computer. (In fact, the SecondOrder pro-gram does store some output a format like this! My excuse is that it stores the data di-rectly into a database anyway, so you might as well make the ‘backup’ copy easy forpeople to read.)

My usual solution to this problem is to write a mini-program in Perl, a language espe-cially designed for searching for patterns in text files and extracting data from them. Forthe example above, I have a Perl script that scans through, extracts the data and creates aset of comma-delimited files which can be amalgamated and imported into a database.(Perl is free and quite easy to learn; see the bibliography at the end of this guide for de-tails.) In fact, the SecondOrder summary file looks like this:m4-03Mar2000-1020-summary.txtSECOND-ORDER I.V. SELF-ADMINISTRATION -- SUMMARY FILE...Rat: m4Session: 24Date/time code: 03-Mar-2000(1019)...Session time limit (min): 120Locomotor time bin size (min): 20...Reinforcement device: PUMPMax #reinforcements: 10Pump infusion duration (s): 5.83...

Page 91: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VII. Principles of data collection 91

Number of stimuli: 41Number of reinforcements: 4Finished at: Fri 03-Mar-2000, 12:39Active lever responses: 454Inactive lever responses: 87f

which is one of the easiest formats to read into Perl if you needed to (each file followsexactly the same format; there’s one piece of information per line; there are a few sec-tions with comma-delimited output that can be copied directly into a file for database im-port).

Data not in ASCII formatIf the numbers that make up your data set are stored in some obscure format, it’s still pos-sible to extract such data, but you may end up having to write a program in a general-purpose language like C or C++ to extract them. This is beyond the scope of this guide.

Page 92: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide VII. Principles of data collection 92

Part 8. Library of behavioural tasks

Some tasks that we develop will be available free on the WWW at

http:/ /www.pobox.com/~rudolf/whisker

8.1 Second-order IV self-administrationThis is described in full on page 41.

Page 93: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide IX. Future developments 93

Part 9. Future improvements, knownproblems

9.1 Future additions: server-sideLive testing began in January 2000, with the release build.

At the time of writing, the following additions are planned:

• Context menus (from a right mouse click) for clients and lines, so you can ping/deleteclients, etc., and ‘peg’ lines without using the main menu. A relatively trivial issue.

After that, further major server features might include:

• Support for digital I/O boards from other manufacturers• Support for serial communications, to support touchscreen programming. (However,

this raises a design issue: as the operating system ensures multiple applications cannotuse a serial port simultaneously, why should the clients not deal with the problemthemselves? The Whisker architecture is designed to manage a central resource forwhich clients compete. Also, full touchscreen support requires multiple video screenoutput. This is a complex area.)

• Support for analogue-to-digital (A-D) inputs, as used for example in electrochemistry(voltammetry).

Minor updates may include

• Writing a proper context-dependent help file• Further optimization of display code (this is a trivial issue).

9.2 Future additions: client-side• At the moment, the line numbers are hard-coded into the clients (that is, the fact that

the pump for box 5 is line 61, or whatever). This is not a practical problem for our IVresearchers (the current guinea pigs!), because we wire all our systems in the sameway – and of course, the source code is there to be modified. However, one systemworth considering is to implement a box definition file (stored on disk or in the reg-istry) which would facilitate re-wiring.

• One attractive feature of some operant control systems is the ability to program a be-havioural task by writing a script (in a dedicated script language) or drawing the taskin graphical form. I have shied away from this deliberately, as I believe it inevitablyrestricts the capabilities of the tasks. However, there is no reason why, in the Whiskerarchitecture, a client could not be written that interprets a script language (and passesthe script’s instructions on to the server).

9.3 Known bugsNone known at present.

Page 94: an operant chamber control system by Rudolf Cardinal ...egret.psychol.cam.ac.uk/whisker/Whisker_v1_documentation/Whiske… · The use of a TCP event-driven server brings the following

Whisker User Guide X. Acknowledgements 94

Part 10. Acknowledgements andbibliography

Thanks to the following people:

Rob Milner sparked the whole thing off by telling me how cheap the hardware was.The IVSA group told me what was needed – particularly Maria Pilla, Simon Howes, Dan

Hutcheson and Barry Everitt. Maria also served patiently as the guinea pig for the first system.Mike Aitken provided useful discussion and came up with the idea of the safety timer for i.v.

pumps.Barry Everitt approved the project and provided encouragement throughout.

The following books were useful during this project:

Stevens WR (1998). UNIX Network Programming, Volume 1. Networking APIs: Sockets andXTI. Prentice Hall.Kain E (1998). The MFC Answer Book: Solutions for Effective Visual C++ Applications.Addison Wesley.Prosise J (1999). Programming Windows with MFC, second edition. Microsoft Press.Cline MP & Lomow GA (1994). C++ FAQs: Frequently Asked Questions. Addison Wesley.Musser DR & Saini A (1996). STL Tutorial and Reference Guide. Addison Wesley.Chapman D (1998). Teach Yourself Visual C++ 6 in 21 Days. Sams / Macmillan.Schwartz RL & Christansen T (1997). Learning Perl, second edition. O’Reilly.Wall L, Christiansen T & Schwartz RL (1996). Programming Perl, second edition. O’Reilly.

The following software was used:

Microsoft Visual C++ 6.0 Professional (http:/ /msdn.microsoft.com/visualc)with InstallShield for Microsoft Visual C++ 6 (http:/ /www.installshield.com/)

Microsoft Word 97 (http:/ /www.microsoft.com/office)Adobe Acrobat 4.0 (http:/ /www.adobe.com/)TextPad 3.2.5 (http:/ /www.textpad.com/)WinZip 7.0 (http:/ /www.winzip.com/)

with WinZip Self-Extractor 2.1Perl 5 for Win32 (http:/ /www.ActiveState.com/)Microsoft Visual Basic 5.0 and 6.0 Professional (http:/ /msdn.microsoft.com/vbasic)Paint Shop Pro 6.02 (http:/ /www.jasc.com/)


Recommended