AutoHeadFix package

Submodules

AutoHeadFix.AHF_CageSet module

class AutoHeadFix.AHF_CageSet.AHF_CageSet[source]

Bases: object

Manages settings for hardware GPIO pin-outs and some other cage-specific settings for the raspberry Pi used for Auto Head Fix

The class AHF_CageSet defines the following settings:
cageID:str - whatver name you have for this cage
pistonsPin:int - connected to solenoids that drive pistons for head fixing
rewardPin:int - connected to solenoid for delivering water reward
tirPin:int - tag in-range pin for the ID tag reader
contactPin:int - connected to the head contacts
ledPin:int - output pin for the Blue LED that illuminates the brain
serialPort:str - “/dev/ttyUSB0” for USB with sparkFun breakout or “/dev/ttyAMA0” for built-in
dataPath:str - path to base folder, possibly on removable media, where data will be saved in created subfolders

The settings are saved between program runs in a json-styled text config file, AHFconfig.jsn, in a human readable and editable key=value form.

__init__()[source]

Makes a new AHF_CageSet object by loading from AHFconfig.jsn or by querying the user

Either reads a dictionary from a config file, AHFconfig.jsn, in the same directory in which the program is run, or if the file is not found, it querries the user for settings and then writes a new file.

edit()[source]

Allows the user to edit and save the cage settings

save()[source]

Saves current configuration stored in this AHF_CageSet object into the file ./AHFconfig.jsn

Call this function after modifying the contents of the AHF_CageSet to save your changes

param:none
returns:nothing
show()[source]

Prints the current configuration stored in this AHF_CageSet to the console, nicely formatted

param:none
returns:nothing

AutoHeadFix.AHF_Camera module

class AutoHeadFix.AHF_Camera.AHF_Camera(paramDict)[source]

Bases: picamera.camera.PiCamera

AHF_Camera is subclassed from PiCamera to hold a few extra settings and to initialize the camera for constant exposure.

__init__(paramDict)[source]

Initializes an AHF_Camera object from a dictonary and sets the gain as appropriate

Parameters:
  • paramDict.format – video format for recording, default=’.h264’
  • paramDict.quality – different video formats interpret quality paramater differently, default = 10
  • paramDict.resolution – two-tuple of horizontal pixel number and vertical pixel number default= (640, 480)
  • paramDict.framerate – rate,1 in Hz, at which to record video, default = 30
  • paramDict.shutter_speed – camera exposure time, in microseconds, inverse must be less than frame rate default = 30
  • paramDict.iso – used to set gain of camera directly, or use 0 to have camera calculate gain automatically
  • paramDict.whiteBalance – set to True if you want camera to auto white balance, set to False to set all color gains to 1, default = False
  • paramDict.previewWin – set the size of the preview window, in pixels a tuple of (left, top, right, bottom) coordinates. default = (0,0,640,480)
Raises:

PiCameraError – error raised by superclass PiCamera if camera is not found, or can’t be initialized

adjust_config_from_user()[source]

Lets the user change the settings for the camera :returns: a dictionary containing the new, modified version fo the settings

static dict_from_user(paramDict)[source]

static method that leys user make or edit a dictionary object that holds camera setttings

configure gets info from user with the input function, which returns strings

get_configDict()[source]

Loads camera settings into a dictionary with same keys as used in __init__ and returns that dictionary

Note that we use float () on framerate becuase it is a Fraction, i,e, 30 is represented as Fraction (30, 1) and it doen’t serialize for storing as a JSON dict

set_gain()[source]

Sets the gain and white balance of the camera based on a 2 second preview - so set illumination as you like before calling

If ISO for the camera is set to non-zero value, gain is not settable. If pWhiteBalance was set to False, white balancing is not done, and gains for red and green are set to 1. :raises PiCameraError: error raised by superclass PiCamera from preview

set_params(paramDict)[source]

modifies paramaters for an AHF_Camera object from a dictonary

Parameters:paramDict – dictionary of setings to change, same format as for __init__()
show_config()[source]

prints the settings for the camera

start_recording(video_name_path)[source]

Starts a video recording using the saved settings for format, quality, gain, etc.

A preview of the recording is always shown

Parameters:video_name_path – a full path to the file where the video will be stored. Always save to a file, not a PIL, for, example
stop_recording()[source]

Stops a video recording previously started with start_recording.

timed_recording(video_name_path, recTime)[source]

Does a timed video recording using the PiCamera wait_recording function.

A preview of the recording is always shown

Control does not pass back to the calling function until the recording is finished :param video_name_path: a full path to the file where the video will be stored. :param recTime: duration of the recorded video, in seconds

AutoHeadFix.AHF_HardwareTester module

AutoHeadFix.AHF_HardwareTester.hardwareTester(cageSet, tagReader)[source]

Hardware Tester for Auto Head Fixing, allows you to verify the various hardware bits are working

AutoHeadFix.AHF_HardwareTester.htloop(cageSet, tagReader)[source]

Presents a menu asking user to choose a bit of hardware to test, and runs the tests

If a test fails, a dialog is presented asking user to change the pin setup. The modified pinout can be saved, overwriting the configuration in ./AHF_Config.jsn Commands are: t= tagReader: trys to read a tag and, if successful, monitors Tag in Range Pin until tag goes away r = reward solenoid: Opens the reward solenoid for a 1 second duration, then closes it c = contact check: Monitors the head contact pin until contact, and then while contact is maintained p = pistons solenoid: Energizes the pistons for a 2 second duration, and then de-energizes them l = LED: Turns on the brain illumination LED for a 2 second duration, then off h = sHow config settings: Prints out the current pinout in the AHF_CageSet object v = saVe modified config file: Saves the the AHF_CageSet object to the file ./AHF_Config.jsn q = quit: quits the program

AutoHeadFix.AHF_Mouse module

class AutoHeadFix.AHF_Mouse.Mice[source]

The mice class simply contains an array of mouse objects

__init__()[source]

Initializes the array of mice with an empty array

addMiceFromFile(statsfp)[source]

Adds mouse objects to the mice array, initialzing tagID and initial values for rewards from quickstats file

If there is a problem with the quickstats file structure, the file is scrubbed and started over with 0 mice :param statsfp: file pointer to the quickstats file returns:nothing

addMouse(aMouse, statsfp)[source]

Appends a mouse object to the array and updates quickstats file with new mouse :param aMouse: the mouse object to append :param statsfp: file pointer to the quickstats file so it can be updated

clear()[source]

Clears the info for each mouse in the array by calling mouse.clear

getMouseFromTag(tag)[source]

Finds the mouse with the given tag number from the array of mice

Parameters:tag – the tag ID of the mouse to find
Returns:the mouse object with the given tag
getMousePos(tag)[source]

Finds the positon in the array of the mouse with the given tag number :param tag: the tag ID of the mouse to remove :returns: the position with the array

nMice()[source]

gets the number of mice in the mouse array :returns: the number of mice in the array

removeMouseByTag(tag)[source]

Removes the mouse with the given tag number from the array of mice :param tag: the tag ID of the mouse to remove

show()[source]

Prints the info for each mouse in the array by calling mouse.show

class AutoHeadFix.AHF_Mouse.Mouse(tag, entries, entranceRewards, headFixes, headFixRewards)[source]

Class to hold information about each mouse, each mouse gets its own object

__init__(tag, entries, entranceRewards, headFixes, headFixRewards)[source]

Makes a new mouse object, initializing with RFID tag and entrance and reward info

entrance and reward info can be loaded from quickStats file if program is restarted, else each mouse will probably be initialized with 1 entry, all reward 0 first time mouse enters chamber :param tag: RFID tag of this mouse :param entries: number of entries mouse has made :param entranceRewards: number of entrance rewards mouse has been given :param headFixes: number of head fixes for this mouse :param headFixRewards: number of head fix rewards mouse has earned

clear()[source]

Clears the stats for entries and rewards for this mouse, done at the start of every day Also clears any StimResults dict entries that the stimulator has made

reward(rewarder, rewardName)[source]

Gives a reward to the mouse and increments the reward count for task or entries :param:rewarder: Rewarder object used to ive rewards for all the mice :param rewardName: either entrance or task for the two types of rewards logged

show()[source]

Prints all the data for this mouse, including any stimResults info

AutoHeadFix.AHF_Notifier module

class AutoHeadFix.AHF_Notifier.AHF_Notifier(cageID_p, phoneList_p)[source]

Sends a text message using a web service, textbelt.com

AHF_Notifier needs requests module, which is not installed by default. The best way to install python modules is with pip. Assuming you are using Python 3: sudo apt-get install python3-pip sudo pip-3.2 install requests

__init__(cageID_p, phoneList_p)[source]

Makes a new AHF_Notifier object

The notifier will send text messages to a tuple of phone numbers using a web service, textbelt.com As it uses http requests to send the message to the web service, you need to be online for notifier to work. :param cageID_p: identifier for cage, sent in message :param durationSecs_p: duration that mouse has been in tube, sent in message :param phoneList_p: tuple of telephone numbers to which the message will be sent return: nothing

notify(tag, durationSecs, isStuck)[source]

Sends a text message with the given information.

Two types of message can be sent, depending if isStuck is True or False No timing is done by the AHF_Notifier class, the durations are only for building the text mssg :param tag: RFID tag of the mouse :param durationSecs: how long the mouse has been inside the chamber :param isStuck: boolean signifying if the mouse has been inside the chamber for too long, or has just left the chamber :return: nothing

AutoHeadFix.AHF_Rewarder module

class AutoHeadFix.AHF_Rewarder.AHF_Rewarder(defaultTimeVal, rewardPin)[source]

A class to use a solenoid to deliver water rewards of various sizes and keep track of rewards delivered.

A dictionary is used to store different opening durations with user-defined names. A separate dictionary with the same keys is used to store the total number of rewards of each type that have been delivered. The Rewarder class is inited with a default duration to be used if a non-existent key is later requested, and the pin number of the GPIO pin used to control the solenoid. Be sure to run GPIO.setmode and GPIO.setup before using the rewarder TODO:1)include a measure of flow rate and record/return values in litres delivered, not seconds open.2)make doReward threaded, so main program does not have to stop for long reards

__init__(defaultTimeVal, rewardPin)[source]

Makes a new Rewarder object with a GPIO pin and default opening time

Parameters:
  • defaultTimeVal – opening suration to be used if requested reward Type is not in dictionary
  • rewardPin – GPIO pin number connected to the solenoid
Returns:

returns nothing

addToDict(rewardName, rewardSize)[source]

Adds a new reward type with defined size to the dictionary of reward sizes

param: rewardName: name of new reward type to add param:rewardSize: opening duration of solenoid, in seconds

getNumOfType(rewardName)[source]

Returns the number of times rewards of a particular reward type have been disbursed

param:rewardName: the type of the reward queried, should already be in the dictionary, or exception wil be raised

getTotalDur()[source]

Returns the total duration in seconds of solenoid openings, of all reward types

giveReward(rewardName)[source]

Gives a reward of the requested type, if the requested reward type is found in the dictionary

If the requested reward type is not found, the default reward size is used param:rewardName: the tyoe of the reward to be given, should already be in dictionary

setNumOfType(rewardName, rewardNum)[source]

Sets number of rewards of a particular type, if, for example, a rewarder is associated with an existing mouse

totalsToStr()[source]

Returns a formatted string of total rewards given

zeroTotals()[source]

Zeros the count of number of rewards given, for all reward types.

You might want to do this if keeping track of how many rewards have been delivered per day

AutoHeadFix.AHF_Settings module

class AutoHeadFix.AHF_Settings.AHF_Settings(fileName)[source]

Bases: object

AHF_Settings is a class that reads, edits, and saves settings for the AutoheadFix program

__init__(fileName)[source]

Makes a new settings object, loading from a given file, letting user choose from existing files, or making new settings from user

Will try to load a file if file name is passed in,

config_from_user()[source]

Queries the user for settings. This function may run before a camera or stimulator has been configured

We need to run static function for stimulator configuration and camera configuration

edit_from_user()[source]

Allows user to edit experiment settings, including stimulator settings, but not camera settings

user can either change the stimulaotr, or reconfigure it, but not both :returns: code for mods - bit 0 = 1 is set if stimulator config is changed, bit 1 =2 is set if stimulator is changed

load(file)[source]
save()[source]

Saves current settings to a dictionary and then sends dictionary to a json dictionary file

show()[source]

Prints the current configuration stored in this AHF_Settings to the console, nicely formatted

param:none
returns:nothing

AutoHeadFix.AHF_Stimulator module

class AutoHeadFix.AHF_Stimulator.AHF_Stimulator(configDict, rewarder, textfp)[source]

Bases: object

Stimulator does all stimulation and reward during a head fix task

All events and their timings in a head fix, including rewards, are controlled by a Stimulator.

__init__(configDict, rewarder, textfp)[source]

The Stimulator class is inited with: a config dictionary of settings; the same rewarder object used to give entry rewards; and a file pointer to the log file

change_config(changesDict)[source]

Edits the configuration dictionary, adding or replacing with key/value pairs from changesDict paramater

configStim(mouse)[source]

Called before running each head fix trial, stimulator decides what to do and configures itself

You may wish to different things for different mice, and to store data about stim presentations in the mouse object returns: a short string representing stim configuration, used to generate movie file name :param mouse: the object representing the mouse that is currently head-fixed

config_from_user()[source]

makes or edits the dictionary object that holds settings for this stimulator

Gets info from user with the input function, which returns strings so your sublass methods will need to use int() or float() to convert values as appropriate

static dict_from_user(stimDict)[source]

static method that makes or edits a dictionary object that holds settings for a stimulator

configure gets info from user with the input function, which returns strings so your sublass methods will need to use int() or float() to convert values as appropriate

static get_class(fileName)[source]

Imports a module from a fileName (stripped of the .py) and returns the class

Assumes the class is named the same as the module

static get_stimulator_from_user()[source]

Static method that trawls through current folder looking for stimulator class python files

Allows user to choose from the list of files found. Files are recognized by names starting with ‘AHF_Stimulator_‘ and ending with ‘.py’ Raises: FileNotFoundError if no stimulator class files found

logFile()[source]
Called after each head fix, prints more detailed text to the log file, perhaps a line for each event

You may wish to use the same format as writeToLogFile function in __main__.py

Or you may wish to override with pass and log from the run method

nextDay(newFP)[source]

Called when the next day starts. The stimulator is given the new log file pointer. Can do other things as needed :param newFP: the file pointer for the new day’s log file

quitting()[source]

Called before AutoHeadFix exits. Gives stimulator chance to do any needed cleanup

A stimulator may, e.g., open files and wish to close them before exiting, or use hardware that needs to be cleaned up

run()[source]

Called at start of each head fix. Gives a reward, increments mouse’s reward count, then waits 10 seconds

setup()[source]

AutoHeadFix.AHF_Stimulator_LEDs module

class AutoHeadFix.AHF_Stimulator_LEDs.AHF_Stimulator_LEDs(configDict, rewarder, textfp)[source]

Bases: AutoHeadFix.AHF_Stimulator_Rewards.AHF_Stimulator_Rewards

__init__(configDict, rewarder, textfp)[source]
change_config(changesDict)[source]
configStim(mouse)[source]
config_from_user()[source]
static dict_from_user(stimDict)[source]
logfile()[source]
run()[source]
setup()[source]
AutoHeadFix.AHF_Stimulator_LEDs.random() → x in the interval [0, 1).

AutoHeadFix.AHF_Stimulator_Rewards module

class AutoHeadFix.AHF_Stimulator_Rewards.AHF_Stimulator_Rewards(configDict, rewarder, textfp)[source]

Bases: AutoHeadFix.AHF_Stimulator.AHF_Stimulator

__init__(configDict, rewarder, textfp)[source]
static dict_from_user(stimDict)[source]
logfile()[source]
run()[source]
setup()[source]

AutoHeadFix.AHF_TagReader module

class AutoHeadFix.AHF_TagReader.AHF_TagReader(serialPort, doChecksum=False)[source]

Class to read values from a Innovations RFID tag reader, such as ID-20LA

__init__(serialPort, doChecksum=False)[source]

Makes a new AHF_TagReader object :param serialPort: serial port tag reader is attached to, /dev/ttyUSB0 or /dev/ttyAMA0 for instance :param doCheckSum: set to calculate the checksum on each tag read

checkSum(tag, checkSum)[source]

Sequentially XOR-ing 2 byte chunks of the 10 byte tag value will give the 2-byte check sum

Parameters:
  • tag – the 10 bytes of tag value
  • checksum – the two butes of checksum value
Returns:

True if check sum calculated correctly, else False

clearBuffer()[source]

Clears the serial buffer for the serialport used by the tagReader

readTag()[source]

Reads a hexidecimal RFID tag from the serial port using a blocking read and returns the decimal equivalent

RFID Tag is 16 characters: STX(02h) DATA (10 ASCII) CHECK SUM (2 ASCII) CR LF ETX(03h) 1 char of junk, 10 of hexadecimal data, 2 of hexadecimal check sum, 3 of junk

:returns decimal value of RFID tag :raises IOError: if serialPort not read raises ValueError: if checksum or conversion from hex to decimal fails

AutoHeadFix.AHF_UDPTrig module

class AutoHeadFix.AHF_UDPTrig.AHF_UDPTrig(UDPlist_p)[source]

Sends/receives UDP signals as to another pi to start/stop recording

AHF_UDPTrig uses the socket module to do the UDP stuff, but it should be part of the default install

__init__(UDPlist_p)[source]

Makes a new AHF_UDPtrig object using passed in list of ip addresses.

stores UDPlist in the new object sets hasUDP to false if object creation fails because of network error, else True

doTrigger(message)[source]

Sends a UDP message to the stored list of ip addresses

getTrigger()[source]

Waits for a UDP message and returns a string contaiing the message

AutoHeadFix.AHF_ValveControl module

AutoHeadFix.AHF_ValveControl.runLoop(cageSet)[source]

main loop asks user to open or close solenoid; Opens on 1, closes on 0, quits on q

param:cageSet: an instance of AHF_CageSet describing which pin is used for water reward solenoid returns:nothing

AutoHeadFix.AHF_ValveControl.valveControl(cageSet)[source]

Opens and closes valve, as for testing, or draining the lines

when run as a module, valveControl assumes GPIO is setup as defined in cageSet and offers to open/close water delivery solenoid. ValveControl takes an instance of AHF_CageSet as a paramater and assumes that the GPIO pin connected to the water delivery solenoid us as defined in the cageSet, and that GPIO is already setup. param:cageSet: an instance of AHF_CageSet describing which pin is used for water reward solenoid returns:nothing

Module contents