Autopilot Logo
v0.4.4.post0

User Guide:

  • Overview
    • Program Structure
    • Tasks
    • Module Tour
  • Quickstart
    • Minimal Installation
    • Blink an LED
    • Capture Video
    • Communicate Between Computers
    • Realtime DeepLabCut
    • Put it Together - Close a Loop!
      • Pilot 1 - Image Capture
      • GPU Computer
      • Pilot 2 - LED
    • What Next?
  • Installation
    • Supported Systems
    • Pre-installation
      • On the Pilot device
      • On the Terminal device
      • Creating a Virtual Environment
    • Installing Autopilot
      • Method 1: Installation with pip
      • Method 2: Installation from source
      • Extra Dependencies
    • Configuration
      • Select agent
      • Select scripts
      • Configure Agent
      • Configure Hardware
    • Networking
      • IP Addresses
      • Ports
    • Testing the Installation
  • Training a Subject
    • Connecting the Pilot
    • Creating a Protocol
      • Using the Protocol Wizard
      • Manual Protocol Creation
    • Creating a Subject
    • Running the Task
    • Debugging a Task
  • Writing a Task
    • The Nafc Task
      • The Task class
      • Four Task Attributes
        • PARAMS
        • Data
        • PLOT
        • HARDWARE
      • Initialization
      • Stage Methods
        • Request
        • Discrim
        • Reinforcement
      • Additional Methods
    • Distributed Go/No-Go - Using Child Agents
      • Additional Prefs
      • Go/No-Go Parameterization
      • Initialization
      • The Child Task
      • A Very Smart Wheel
      • Go/No-Go Stage Methods
  • Writing a Hardware Class
    • GPIO with pigpio
  • Using Plugins
    • Plugins
    • Registries
    • The Wiki API
    • Plugins on the Wiki
  • Examples
    • Blink
      • Preamble
        • Params
        • TrialData
        • Hardware
      • Initialization
      • Stage Methods
      • Full Source

API Documentation:

  • Core Modules
    • gui
      • _MAPS
      • gui_event()
      • Control_Panel
        • Control_Panel.init_ui()
        • Control_Panel.add_pilot()
        • Control_Panel.create_subject()
        • Control_Panel.update_db()
        • Control_Panel.staticMetaObject
      • Subject_List
        • Subject_List.populate_list()
        • Subject_List.dropEvent()
        • Subject_List.staticMetaObject
      • Pilot_Panel
        • Pilot_Panel.init_ui()
        • Pilot_Panel.remove_subject()
        • Pilot_Panel.create_subject()
        • Pilot_Panel.staticMetaObject
      • Pilot_Button
        • Pilot_Button.toggle_start()
        • Pilot_Button.set_state()
        • Pilot_Button.staticMetaObject
      • New_Subject_Wizard
        • New_Subject_Wizard.Biography_Tab
        • New_Subject_Wizard.Task_Tab
        • New_Subject_Wizard.staticMetaObject
      • Protocol_Wizard
        • Protocol_Wizard.add_step()
        • Protocol_Wizard.rename_step()
        • Protocol_Wizard.remove_step()
        • Protocol_Wizard.populate_params()
        • Protocol_Wizard.clear_params()
        • Protocol_Wizard.reorder_steps()
        • Protocol_Wizard.set_param()
        • Protocol_Wizard.set_sounds()
        • Protocol_Wizard.set_graduation()
        • Protocol_Wizard.check_depends()
        • Protocol_Wizard.staticMetaObject
      • Graduation_Widget
        • Graduation_Widget.populate_params()
        • Graduation_Widget.clear_params()
        • Graduation_Widget.store_param()
        • Graduation_Widget.staticMetaObject
      • Drag_List
        • Drag_List.fileDropped
        • Drag_List.dragEnterEvent()
        • Drag_List.dragMoveEvent()
        • Drag_List.dropEvent()
        • Drag_List.staticMetaObject
      • Sound_Widget
        • Sound_Widget.pass_set_param_function()
        • Sound_Widget.add_sound()
        • Sound_Widget.remove_sound()
        • Sound_Widget.populate_lists()
        • Sound_Widget.files_dropped()
        • Sound_Widget.Add_Sound_Dialog
        • Sound_Widget.staticMetaObject
      • Bandwidth_Test
        • Bandwidth_Test.init_ui()
        • Bandwidth_Test.start()
        • Bandwidth_Test.send_test()
        • Bandwidth_Test.process_test()
        • Bandwidth_Test.save()
        • Bandwidth_Test.register_msg()
        • Bandwidth_Test.update_pbar()
        • Bandwidth_Test.validate_list()
        • Bandwidth_Test.staticMetaObject
      • Calibrate_Water
        • Calibrate_Water.init_ui()
        • Calibrate_Water.staticMetaObject
      • Pilot_Ports
        • Pilot_Ports.init_ui()
        • Pilot_Ports.update_volumes()
        • Pilot_Ports.start_calibration()
        • Pilot_Ports.l_progress()
        • Pilot_Ports.staticMetaObject
      • Reassign
        • Reassign.init_ui()
        • Reassign.populate_steps()
        • Reassign.set_protocol()
        • Reassign.set_step()
        • Reassign.staticMetaObject
      • Weights
        • Weights.init_ui()
        • Weights.set_weight()
        • Weights.staticMetaObject
      • Plugins
        • Plugins.init_ui()
        • Plugins.list_plugins()
        • Plugins.download_plugin()
        • Plugins.select_plugin_type()
        • Plugins.select_plugin()
        • Plugins.staticMetaObject
      • Psychometric
        • Psychometric.init_ui()
        • Psychometric.populate_steps()
        • Psychometric.populate_variables()
        • Psychometric.check_all()
        • Psychometric.plot_params
        • Psychometric.staticMetaObject
      • Stream_Video
        • Stream_Video.init_ui()
        • Stream_Video.current_pilot
        • Stream_Video.current_camera
        • Stream_Video.populate_cameras()
        • Stream_Video.camera_selected()
        • Stream_Video.toggle_start()
        • Stream_Video.write_video()
        • Stream_Video.l_frame()
        • Stream_Video.closeEvent()
        • Stream_Video.staticMetaObject
      • pop_dialog()
    • loggers
      • _LOGGERS
      • init_logger()
    • pilot
      • Pilot
        • Pilot.server
        • Pilot.logger
        • Pilot.running
        • Pilot.stage_block
        • Pilot.file_block
        • Pilot.quitting
        • Pilot.networking
        • Pilot.node
        • Pilot.get_ip()
        • Pilot.handshake()
        • Pilot.update_state()
        • Pilot.l_start()
        • Pilot.l_stop()
        • Pilot.l_param()
        • Pilot.l_cal_port()
        • Pilot.calibrate_port()
        • Pilot.l_cal_result()
        • Pilot.l_bandwidth()
        • Pilot.l_stream_video()
        • Pilot.calibration_curve()
        • Pilot.init_pigpio()
        • Pilot.init_audio()
        • Pilot.blank_LEDs()
        • Pilot.open_file()
        • Pilot.run_task()
    • plots
      • gui_event()
      • Plot_Widget
        • Plot_Widget.init_plots()
        • Plot_Widget.staticMetaObject
      • Plot
        • Plot.init_plots()
        • Plot.l_start()
        • Plot.l_data()
        • Plot.l_stop()
        • Plot.l_param()
        • Plot.l_state()
        • Plot.staticMetaObject
      • Point
        • Point.update()
        • Point.staticMetaObject
      • Line
        • Line.update()
        • Line.staticMetaObject
      • Segment
        • Segment.update()
        • Segment.staticMetaObject
      • Roll_Mean
        • Roll_Mean.update()
        • Roll_Mean.staticMetaObject
      • Shaded
        • Shaded.update()
        • Shaded.staticMetaObject
      • Timer
        • Timer.start_timer()
        • Timer.stop_timer()
        • Timer.update_time()
        • Timer.staticMetaObject
      • Video
        • Video.init_gui()
        • Video._update_frame()
        • Video.update_frame()
        • Video.release()
        • Video.staticMetaObject
      • HLine
        • HLine.staticMetaObject
      • ImageItem_TimedUpdate
        • ImageItem_TimedUpdate.setImage()
        • ImageItem_TimedUpdate.staticMetaObject
        • ImageItem_TimedUpdate.update_img()
      • PLOT_LIST
    • styles
    • subject
      • Subject
        • Subject.open_hdf()
        • Subject.close_hdf()
        • Subject.new_subject_file()
        • Subject.ensure_structure()
        • Subject.update_biography()
        • Subject.update_history()
        • Subject.assign_protocol()
        • Subject.flush_current()
        • Subject.stash_current()
        • Subject.prepare_run()
        • Subject.data_thread()
        • Subject.save_data()
        • Subject.stop_run()
        • Subject.to_csv()
        • Subject.get_trial_data()
        • Subject.apply_along()
        • Subject.get_step_history()
        • Subject.get_timestamp()
        • Subject.get_weight()
        • Subject.set_weight()
        • Subject.update_weights()
        • Subject.graduate()
        • Subject.History_Table
        • Subject.Weight_Table
        • Subject.Hash_Table
    • terminal
      • Terminal
        • Terminal.initUI()
        • Terminal.reset_ui()
        • Terminal.pilots
        • Terminal.protocols
        • Terminal.subject_protocols
        • Terminal.subject_list
        • Terminal.ping_pilot()
        • Terminal.heartbeat()
        • Terminal.toggle_start()
        • Terminal.l_data()
        • Terminal.l_ping()
        • Terminal.l_state()
        • Terminal.l_handshake()
        • Terminal.new_pilot()
        • Terminal.new_protocol()
        • Terminal.subject_weights()
        • Terminal.update_protocols()
        • Terminal.reassign_protocols()
        • Terminal.calibrate_ports()
        • Terminal.test_bandwidth()
        • Terminal.plot_psychometric()
        • Terminal.manage_plugins()
        • Terminal.staticMetaObject
        • Terminal.stream_video()
        • Terminal.closeEvent()
  • Hardware
    • BOARD_TO_BCM
    • BCM_TO_BOARD
    • Hardware
      • Hardware.is_trigger
      • Hardware.pin
      • Hardware.type
      • Hardware.input
      • Hardware.output
      • Hardware.release()
      • Hardware.assign_cb()
      • Hardware.get_name()
      • Hardware.init_networking()
      • Hardware.calibration
    • cameras
      • OPENCV_LAST_INIT_TIME
      • Camera
        • Camera.input
        • Camera.type
        • Camera.capture()
        • Camera._capture()
        • Camera._process()
        • Camera.stream()
        • Camera.l_start()
        • Camera.l_stop()
        • Camera.write()
        • Camera._write_frame()
        • Camera._write_deinit()
        • Camera.queue()
        • Camera.cam
        • Camera.output_filename
        • Camera._grab()
        • Camera._timestamp()
        • Camera.init_cam()
        • Camera.capture_init()
        • Camera.capture_deinit()
        • Camera.stop()
        • Camera.release()
      • PiCamera
        • PiCamera.sensor_mode
        • PiCamera.resolution
        • PiCamera.fps
        • PiCamera.rotation
        • PiCamera.init_cam()
        • PiCamera.capture_init()
        • PiCamera._grab()
        • PiCamera.capture_deinit()
        • PiCamera.release()
        • PiCamera.PiCamera_Writer
      • Camera_CV
        • Camera_CV.fps
        • Camera_CV.shape
        • Camera_CV._grab()
        • Camera_CV._timestamp()
        • Camera_CV.backend
        • Camera_CV.init_cam()
        • Camera_CV.release()
        • Camera_CV.v4l_info
      • Camera_Spinnaker
        • Camera_Spinnaker.type
        • Camera_Spinnaker.ATTR_TYPES
        • Camera_Spinnaker.ATTR_TYPE_NAMES
        • Camera_Spinnaker.RW_MODES
        • Camera_Spinnaker.init_cam()
        • Camera_Spinnaker.capture_init()
        • Camera_Spinnaker.capture_deinit()
        • Camera_Spinnaker._process()
        • Camera_Spinnaker._grab()
        • Camera_Spinnaker._timestamp()
        • Camera_Spinnaker.write()
        • Camera_Spinnaker._write_frame()
        • Camera_Spinnaker._write_deinit()
        • Camera_Spinnaker.bin
        • Camera_Spinnaker.exposure
        • Camera_Spinnaker.fps
        • Camera_Spinnaker.frame_trigger
        • Camera_Spinnaker.acquisition_mode
        • Camera_Spinnaker.readable_attributes
        • Camera_Spinnaker.writable_attributes
        • Camera_Spinnaker.get()
        • Camera_Spinnaker.set()
        • Camera_Spinnaker.list_options()
        • Camera_Spinnaker.device_info
        • Camera_Spinnaker.release()
      • Video_Writer
        • Video_Writer.run()
      • list_spinnaker_cameras()
    • gpio
      • TRIGGER_MAP
      • INVERSE_TRIGGER_MAP
      • PULL_MAP
      • INVERSE_PULL_MAP
      • ENABLED
      • clear_scripts()
      • GPIO
        • GPIO.init_pigpio()
        • GPIO.pin
        • GPIO.state
        • GPIO.pull
        • GPIO.polarity
        • GPIO.trigger
        • GPIO.release()
      • Digital_Out
        • Digital_Out.output
        • Digital_Out.type
        • Digital_Out.pigs_function
        • Digital_Out.set()
        • Digital_Out.turn()
        • Digital_Out.toggle()
        • Digital_Out.pulse()
        • Digital_Out._series_script()
        • Digital_Out.store_series()
        • Digital_Out.series()
        • Digital_Out.delete_script()
        • Digital_Out.delete_all_scripts()
        • Digital_Out.stop_script()
        • Digital_Out.release()
      • Digital_In
        • Digital_In.is_trigger
        • Digital_In.type
        • Digital_In.input
        • Digital_In.assign_cb()
        • Digital_In.clear_cb()
        • Digital_In.record_event()
        • Digital_In.release()
      • PWM
        • PWM.output
        • PWM.type
        • PWM.pigs_function
        • PWM.set()
        • PWM.range
        • PWM.polarity
        • PWM.release()
      • LED_RGB
        • LED_RGB.output
        • LED_RGB.type
        • LED_RGB.range
        • LED_RGB.set()
        • LED_RGB.toggle()
        • LED_RGB.pulse()
        • LED_RGB._series_script()
        • LED_RGB.flash()
        • LED_RGB.release()
        • LED_RGB.pin
        • LED_RGB.pin_bcm
        • LED_RGB.pull
      • Solenoid
        • Solenoid.output
        • Solenoid.type
        • Solenoid.DURATION_MIN
        • Solenoid.duration
        • Solenoid.dur_from_vol()
        • Solenoid.open()
    • i2c
      • I2C_9DOF
        • I2C_9DOF.ACCELRANGE_2G
        • I2C_9DOF.ACCELRANGE_16G
        • I2C_9DOF.ACCELRANGE_4G
        • I2C_9DOF.ACCELRANGE_8G
        • I2C_9DOF.MAGGAIN_4GAUSS
        • I2C_9DOF.MAGGAIN_8GAUSS
        • I2C_9DOF.MAGGAIN_12GAUSS
        • I2C_9DOF.MAGGAIN_16GAUSS
        • I2C_9DOF.GYROSCALE_245DPS
        • I2C_9DOF.GYROSCALE_500DPS
        • I2C_9DOF.GYROSCALE_2000DPS
        • I2C_9DOF.GYRO_HPF_CUTOFF
        • I2C_9DOF.accel_range
        • I2C_9DOF.mag_gain
        • I2C_9DOF.gyro_scale
        • I2C_9DOF.gyro_filter
        • I2C_9DOF.gyro_polarity
        • I2C_9DOF.acceleration
        • I2C_9DOF.magnetic
        • I2C_9DOF.gyro
        • I2C_9DOF.rotation
        • I2C_9DOF.temperature
        • I2C_9DOF.calibrate()
      • MLX90640
        • MLX90640.type
        • MLX90640.ALLOWED_FPS
        • MLX90640.SHAPE_SENSOR
        • MLX90640.fps
        • MLX90640.integrate_frames
        • MLX90640.interpolate
        • MLX90640.init_cam()
        • MLX90640.capture_init()
        • MLX90640._threaded_capture()
        • MLX90640._grab()
        • MLX90640._timestamp()
        • MLX90640.interpolate_frame()
        • MLX90640.release()
    • usb
      • Wheel
        • Wheel.input
        • Wheel.type
        • Wheel.trigger
        • Wheel.THRESH_TYPES
        • Wheel.MODES
        • Wheel.MOVE_DTYPE
        • Wheel.start()
        • Wheel.check_thresh()
        • Wheel.calc_move()
        • Wheel.thresh_trig()
        • Wheel.assign_cb()
        • Wheel.l_measure()
        • Wheel.l_clear()
        • Wheel.l_stop()
        • Wheel.release()
      • Scale
        • Scale.MODEL
  • Networking
    • serialize_array()
    • station
      • Station
        • Station.repeat_interval
        • Station.run()
        • Station.prepare_message()
        • Station.send()
        • Station.push()
        • Station.repeat()
        • Station.l_confirm()
        • Station.l_stream()
        • Station.handle_listen()
        • Station.get_ip()
        • Station.release()
        • Station._check_stop()
      • Terminal_Station
        • Terminal_Station.plot_timer
        • Terminal_Station.sent_plot
        • Terminal_Station.start_plot_timer()
        • Terminal_Station.l_ping()
        • Terminal_Station.l_init()
        • Terminal_Station.l_change()
        • Terminal_Station.l_stopall()
        • Terminal_Station.l_kill()
        • Terminal_Station.l_data()
        • Terminal_Station.l_continuous()
        • Terminal_Station.l_state()
        • Terminal_Station.l_handshake()
        • Terminal_Station.l_file()
      • Pilot_Station
        • Pilot_Station._pinger()
        • Pilot_Station.l_noop()
        • Pilot_Station.l_state()
        • Pilot_Station.l_cohere()
        • Pilot_Station.l_ping()
        • Pilot_Station.l_start()
        • Pilot_Station.l_stop()
        • Pilot_Station.l_change()
        • Pilot_Station.l_file()
        • Pilot_Station.l_continuous()
        • Pilot_Station.l_child()
        • Pilot_Station.l_forward()
    • node
      • Net_Node
        • Net_Node.repeat_interval
        • Net_Node.init_networking()
        • Net_Node.threaded_loop()
        • Net_Node.handle_listen()
        • Net_Node.send()
        • Net_Node.repeat()
        • Net_Node.l_confirm()
        • Net_Node.l_stream()
        • Net_Node.prepare_message()
        • Net_Node.get_stream()
        • Net_Node.ip
        • Net_Node.release()
    • Message
      • Message
        • Message.__getitem__()
        • Message.__setitem__()
        • Message._serialize_numpy()
        • Message.expand()
        • Message.__delitem__()
        • Message.__contains__()
        • Message.get_timestamp()
        • Message.validate()
        • Message.serialize()
  • Stimuli
    • managers
      • init_manager()
      • Stim_Manager
        • Stim_Manager.do_correction()
        • Stim_Manager.do_bias()
        • Stim_Manager.init_sounds()
        • Stim_Manager.set_triggers()
        • Stim_Manager.make_punishment()
        • Stim_Manager.play_punishment()
        • Stim_Manager.next_stim()
        • Stim_Manager.compute_correction()
        • Stim_Manager.update()
        • Stim_Manager.end()
      • Proportional
        • Proportional.init_sounds_grouped()
        • Proportional.init_sounds_individual()
        • Proportional.store_groups()
        • Proportional.set_triggers()
        • Proportional.next_stim()
      • Bias_Correction
        • Bias_Correction.next_bias()
        • Bias_Correction.thresholded_linear()
        • Bias_Correction.update()
    • sound
      • jackclient
        • SERVER
        • FS
        • BLOCKSIZE
        • QUEUE
        • PLAY
        • STOP
        • Q_LOCK
        • CONTINUOUS
        • CONTINUOUS_QUEUE
        • CONTINUOUS_LOOP
        • JackClient
      • pyoserver
        • pyo_server()
      • base - sound
        • Sound
        • Pyo_Sound
        • Jack_Sound
        • get_sound_class()
      • sounds
        • Tone
        • Noise
        • File
        • Gap
        • Gammatone
        • STRING_PARAMS
        • int_to_float()
  • Tasks
    • task
      • Task
        • Task.PARAMS
        • Task.HARDWARE
        • Task.STAGE_NAMES
        • Task.PLOT
        • Task.TrialData
        • Task.init_hardware()
        • Task.set_reward()
        • Task.handle_trigger()
        • Task.set_leds()
        • Task.flash_leds()
        • Task.end()
    • children
      • Child
      • Wheel_Child
        • Wheel_Child.STAGE_NAMES
        • Wheel_Child.PARAMS
        • Wheel_Child.HARDWARE
        • Wheel_Child.noop()
        • Wheel_Child.end()
      • Video_Child
        • Video_Child.PARAMS
        • Video_Child.start()
        • Video_Child.stop()
        • Video_Child.noop()
      • Transformer
        • Transformer.noop()
        • Transformer.l_process()
        • Transformer.forward()
    • free_water
      • Free_Water
        • Free_Water.STAGE_NAMES
        • Free_Water.PARAMS
        • Free_Water.DATA
        • Free_Water.TrialData
        • Free_Water.HARDWARE
        • Free_Water.PLOT
        • Free_Water.water()
        • Free_Water.response()
        • Free_Water.end()
    • graduation
      • Graduation
        • Graduation.PARAMS
        • Graduation.COLS
        • Graduation.update()
      • Accuracy
        • Accuracy.PARAMS
        • Accuracy.COLS
        • Accuracy.update()
      • NTrials
        • NTrials.PARAMS
        • NTrials.update()
    • nafc
      • Nafc
        • Nafc.STAGE_NAMES
        • Nafc.PARAMS
        • Nafc.PLOT
        • Nafc.TrialData
        • Nafc.HARDWARE
        • Nafc.request()
        • Nafc.discrim()
        • Nafc.reinforcement()
        • Nafc.punish()
        • Nafc.respond()
        • Nafc.stim_start()
        • Nafc.stim_end()
        • Nafc.flash_leds()
  • Transformations
    • make_transform()
    • TransformRhythm
      • TransformRhythm.FIFO
      • TransformRhythm.FILO
    • Transform
      • Transform.rhythm
      • Transform.format_in
      • Transform.format_out
      • Transform.parent
      • Transform.process()
      • Transform.reset()
      • Transform.check_compatible()
      • Transform.__add__()
    • Coercion
    • Geometry
      • Distance
        • Distance.format_in
        • Distance.format_out
        • Distance.process()
      • Angle
        • Angle.format_in
        • Angle.format_out
        • Angle.process()
      • IMU_Orientation
        • IMU_Orientation.process()
      • Rotate
        • Rotate.process()
      • Spheroid
        • Spheroid.fit()
        • Spheroid.process()
        • Spheroid.generate()
      • _ellipsoid_func()
      • Order_Points
        • Order_Points.process()
      • Linefit_Prasad
        • Linefit_Prasad.process()
    • Image
      • Image
        • Image.format_in
        • Image.format_out
        • Image.shape
      • DLC
        • DLC.process()
        • DLC.model
        • DLC.model_dir
        • DLC.dlc_paths
        • DLC.dlc_dir
        • DLC.list_modelzoo()
        • DLC.import_dlc()
        • DLC.create_modelzoo()
        • DLC.load_model()
        • DLC.export_model()
        • DLC.format_in
        • DLC.format_out
    • Logical
      • Condition
        • Condition.process()
        • Condition.minimum
        • Condition.maximum
        • Condition.format_in
        • Condition.format_out
      • Compare
        • Compare.process()
    • Selection
      • Slice
        • Slice.format_in
        • Slice.format_out
        • Slice.process()
      • DLCSlice
        • DLCSlice.format_in
        • DLCSlice.format_out
        • DLCSlice.check_slice()
        • DLCSlice.process()
    • Timeseries
      • Filter_IIR
        • Filter_IIR.process()
      • Gammatone
        • Gammatone.process()
      • Kalman
        • Kalman._init_arrays()
        • Kalman.predict()
        • Kalman.update()
        • Kalman._reshape_z()
        • Kalman.process()
        • Kalman.residual_of()
        • Kalman.measurement_of_state()
        • Kalman.alpha
      • Integrate
        • Integrate.process()
    • Units
      • Rescale
        • Rescale.format_in
        • Rescale.format_out
        • Rescale.process()
      • Colorspaces
        • Colorspaces.HSV
        • Colorspaces.RGB
        • Colorspaces.YIQ
        • Colorspaces.HLS
      • Color
        • Color.format_in
        • Color.format_out
        • Color.CONVERSIONS
        • Color.process()
  • Visualization Tools
    • trial_viewer
      • load_subject_data()
      • load_subject_dir()
      • step_viewer()
      • trial_viewer()
    • psychometric
      • calc_psychometric()
      • plot_psychometric()
  • Utilities
    • Common Utils
      • list_classes()
      • find_class()
      • recurse_subclasses()
      • ReturnThread
        • ReturnThread.run()
        • ReturnThread.join()
      • list_subjects()
      • load_pilotdb()
      • coerce_discrete()
      • find_key_recursive()
      • find_key_value()
      • NumpyEncoder
        • NumpyEncoder.default()
      • NumpyDecoder
        • NumpyDecoder.object_hook()
    • GUI Invoker
      • InvokeEvent
        • InvokeEvent.EVENT_TYPE
      • Invoker
        • Invoker.event()
        • Invoker.staticMetaObject
      • get_invoker()
    • Plugins
      • import_plugins()
      • unload_plugins()
      • list_wiki_plugins()
    • Registry
      • REGISTRIES
        • REGISTRIES.HARDWARE
        • REGISTRIES.TASK
        • REGISTRIES.GRADUATION
        • REGISTRIES.TRANSFORM
        • REGISTRIES.CHILDREN
        • REGISTRIES.SOUND
      • get()
      • get_names()
      • get_hardware()
      • get_task()
    • Wiki
      • ask()
      • browse()
      • make_ask_string()
      • make_browse_string()
  • Setup
    • make_dir()
    • make_alias()
    • parse_manual_prefs()
    • parse_args()
    • locate_user_dir()
    • run_form()
    • make_launch_script()
    • make_systemd()
    • results_string()
    • make_ectopic_dirnames()
    • main()
    • scripts
      • SCRIPTS
    • run_script
      • call_series()
      • run_script()
      • run_scripts()
      • list_scripts()
  • Prefs
    • Scopes
      • Scopes.COMMON
      • Scopes.TERMINAL
      • Scopes.PILOT
      • Scopes.DIRECTORY
      • Scopes.LINEAGE
      • Scopes.AUDIO
    • _PREF_MANAGER
    • _DEFAULTS
    • _WARNED
    • get()
    • set()
    • save_prefs()
    • init()
    • add()
    • git_version()
    • compute_calibration()
    • clear()
  • External

Meta:

  • Wiki
  • Discussion
  • Changelog
    • Version 0.4
      • v0.4.4 - Timing and Sound (February 2nd, 2022)
        • New
        • Improvements
        • Bugfixes
        • Docs
      • v0.4.3 (October 20th, 2021)
        • New Features
        • Minor Improvements
        • Bugfixes
      • v0.4.2 (August 24th)
        • Minor Improvements
        • Bugfixes
        • Documentation
      • v0.4.1 (August 17th)
        • Bugfixes
        • Docs
      • v0.4.0 - Become Multifarious (August 3rd, 2021)
        • New Features
        • Major Improvements
        • Minor Improvements
        • Bugfixes
        • Code Structure
        • Docs
        • Regressions
    • Version 0.3
      • v0.3.5 (February 22, 2021)
        • Bugfixes
      • v0.3.4 (December 13, 2020)
        • Improvements
        • Bugfixes
        • Docs
        • Logging
      • v0.3.3 (October 25, 2020)
        • Bugfixes
        • Improvements
        • Cleanup
      • v0.3.2 (September 28, 2020)
        • Bugfixes
        • Cleanup
      • v0.3.1 (August 4, 2020)
      • v0.3.0 (August 4, 2020)
        • Major Updates
        • Minor Updates
        • New Features
        • Bugfixes
        • Code Structure
        • External Libraries
        • Regressions
    • Version 0.2
      • v0.2.0 (October 26, 2019)
  • To-Do
    • Visions
      • Integrations
        • Open Ephys Integrationpriority: high | discuss>>
        • Multiphoton & High-performance Image Integrationpriority: high | discuss>>
        • Bonsai Integrationpriority: low | discuss>>
      • Closed-Loop Behavior & Processing Pipelines
    • Improvements
    • Bugs
    • Completed
    • Lowest Priority
  • References

Tests:

  • Tests
    • Networking
      • test_node()
      • test_node_to_node()
      • test_multihop()
    • Plugins
      • hardware_plugin()
      • test_hardware_plugin()
      • test_autoplugin()
    • Prefs
      • clean_prefs()
      • test_prefs_defaults()
      • test_prefs_warnings()
      • test_prefs_deprecation()
    • Registry
      • _EXPECTED_HARDWARE
      • logger_registry_get()
      • test_get_one()
      • test_get_all()
      • test_get_subtree()
      • test_get_hardware()
      • test_get_task()
      • test_get_equivalence()
      • test_except_on_failure()
    • Setup
      • test_make_alias()
      • test_quiet_mode()
    • Sounds
      • test_init_noise()
      • test_init_multichannel_noise()
      • test_unpadded_gap()
    • Terminal
    • Transforms
    • Utils
Autopilot
  • Docs »
  • Examples »
  • Blink
  • Edit on GitHub

Blink¶

A very simple task: Blink an LED

Written by @mikewehr in the mike branch: https://github.com/wehr-lab/autopilot/blob/mike/autopilot/tasks/blink.py

Demonstrates the basic structure of a task with one stage, described in the comments throughout the task.

This page is rendered in the docs here in order to provide links to the mentioned objects/classes/etc., but it was written as source code initially and translated to .rst, so the narrative flow is often inverted: text follows code as comments, rather than text introducing and narrating code.

Preamble¶

import itertools
import tables
import time
from datetime import datetime

from autopilot.hardware import gpio
from autopilot.tasks import Task
from collections import OrderedDict as odict

class Blink(Task):
    """
    Blink an LED.

    Args:
        pulse_duration (int, float): Duration the LED should be on, in ms
        pulse_interval (int, float): Duration the LED should be off, in ms

    """

Note that we subclass the Task class (Blink(Task)) to provide us with some methods useful for all Tasks, and to make it available to the task registry (see Plugins & The Wiki).

Tasks need to have a few class attributes defined to be integrated into the rest of the system See here for more about class vs. instance attributes https://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide

Params¶

STAGE_NAMES = ["pulse"] # type: list
"""
An (optional) list or tuple of names of methods that will be used as stages for the task.

See ``stages`` for more information
"""

PARAMS = odict()
PARAMS['pulse_duration'] = {'tag': 'LED Pulse Duration (ms)', 'type': 'int'}
PARAMS['pulse_interval'] = {'tag': 'LED Pulse Interval (ms)', 'type': 'int'}

PARAMS - A dictionary that specifies the parameters that control the operation of the task – each task presumably has some range of options that allow slight variations (eg. different stimuli, etc.) on a shared task structure. This dictionary specifies each PARAM as a human-readable tag and a type that is used by the gui to create an appropriate input object. For example:

PARAMS['pulse_duration'] = {'tag': 'LED Pulse Duration (ms)', 'type': 'int'}

When instantiated, these params are passed to the __init__ method.

A collections.OrderedDict is used so that parameters can be presented in a predictable way to users.

TrialData¶

class TrialData(tables.IsDescription):
    trial_num = tables.Int32Col()
    timestamp_on = tables.StringCol(26)
    timestamp_off = tables.StringCol(26)

TrialData declares the data that will be returned for each “trial” – or complete set of executed task stages. It is used by the Subject object to make a data table with the correct data types. Declare each piece of data using a pytables Column descriptor (see https://www.pytables.org/usersguide/libref/declarative_classes.html#col-sub-classes for available data types, and the pytables guide: https://www.pytables.org/usersguide/tutorials.html for more information)

For each trial, we’ll return two timestamps, the time we turned the LED on, the time we turned it off, and the trial number. Note that we use a 26-character tables.StringCol for the timestamps,

Hardware¶

HARDWARE = {
    'LEDS': {
        'dLED': gpio.Digital_Out
    }
}

Declare the hardware that will be used in the task. Each hardware object is specified with a group and an id as nested dictionaries. These descriptions require a set of hardware parameters in the autopilot prefs.json (typically generated by autopilot.setup.setup_autopilot ) with a matching group and id structure. For example, an LED declared like this in the HARDWARE attribute:

HARDWARE = {'LEDS': {'dLED': gpio.Digital_Out}}

requires an entry in prefs.json like this:

"HARDWARE": {"LEDS": {"dLED": {
    "pin": 1,
    "polarity": 1
}}}

that will be used to instantiate the hardware.gpio.Digital_Out object, which is then available for use in the task like:

self.hardware['LEDS']['dLED'].set(1)

Initialization¶

first we call the superclass (‘Task’)’s initialization method. All tasks should accept *args and **kwargs to pass parameters not explicitly specified by subclass up to the superclass.:

def __init__(self, stage_block=None, pulse_duration=100, pulse_interval=500, *args, **kwargs):
    super(Blink, self).__init__(*args, **kwargs)

    # store parameters given on instantiation as instance attributes
    self.pulse_duration = int(pulse_duration)
    self.pulse_interval = int(pulse_interval)
    self.stage_block = stage_block # type: "threading.Event"

    # This allows us to cycle through the task by just repeatedly calling self.stages.next()
    self.stages = itertools.cycle([self.pulse])

Some generator that returns the stage methods that define the operation of the task.

To run a task, the pilot.Pilot object will call each stage function, which can return some dictionary of data (see pulse() ) and wait until some flag (stage_block ) is set to compute the next stage. Since in this case we want to call the same method (pulse() ) over and over again, we use an itertools.cycle object (if we have more than one stage to call in a cycle, we could provide them like itertools.cycle([self.stage_method_1, self.stage_method_2]) . More complex tasks can define a custom generator for finer control over stage progression.:

self.trial_counter = itertools.count()
"""
Some counter to keep track of the trial number
"""

Hardware is initialized by the superclass’s Task.init_hardware() method, which creates all the hardware objects defined in HARDWARE according to their parameterization in prefs.json , and makes them available in the hardware dictionary.:

self.init_hardware()
self.logger.debug('Hardware initialized')

All task subclass objects have an logger – a logging.Logger that allows users to easily debug their tasks and see feedback about their operation. To prevent stdout from getting clogged, logging messages are printed and stored according to the LOGLEVEL pref – so this message would only appear if LOGLEVEL == "DEBUG":

self.stage_block.set()

We set the stage block and never clear it so that the Pilot doesn’t wait for a trigger to call the next stage – it just does it as soon as the previous one completes.

See run_task() for more detail on this loop.

Stage Methods¶

def pulse(self, *args, **kwargs):
    """
    Turn an LED on and off according to :attr:`~examples.tasks.Blink.pulse_duration` and :attr:`~examples.tasks.Blink.pulse_interval`

    Returns:
        dict: A dictionary containing the trial number and two timestamps.
    """
    # -------------
    # turn light on

    # use :meth:`.hardware.gpio.Digital_Out.set` method to turn the LED on
    self.hardware['LEDS']['dLED'].set(1)
    # store the timestamp
    timestamp_on = datetime.now().isoformat()
    # log status as a debug message
    self.logger.debug('light on')
    # sleep for the pulse_duration
    time.sleep(self.pulse_duration / 1000)

    # ------------
    # turn light off, same as turning it on.

    self.hardware['LEDS']['dLED'].set(0)
    timestamp_off = datetime.now().isoformat()
    self.logger.debug('light off')
    time.sleep(self.pulse_interval / 1000)

    # count and store the number of the current trial
    self.current_trial = next(self.trial_counter)


    data = {
        'trial_num': self.current_trial,
        'timestamp_on': timestamp_on,
        'timestamp_off': timestamp_off
    }
    return data

Create the data dictionary to be returned from the stage. Note that each of the keys in the dictionary must correspond to the names of the columns declared in the TrialData descriptor.

At the conclusion of running the task, we will be able to access the data from the run with Subject.get_trial_data(), which will be a pandas.DataFrame with a row for each trial, and a column for each of the fields here.

Full Source¶

  1"""
  2A very simple task: Blink an LED
  3
  4Written by @mikewehr in the ``mike`` branch: https://github.com/wehr-lab/autopilot/blob/mike/autopilot/tasks/blink.py
  5
  6Demonstrates the basic structure of a task with one stage,
  7described in the comments throughout the task.
  8
  9See the main tutorial for more detail: https://docs.auto-pi-lot.com/en/latest/guide.task.html#
 10
 11This page is rendered in the docs here in order to provide links to the mentioned objects/classes/etc., but
 12this example was intended to be read as source code, as some comments will only be visible there.
 13"""
 14import itertools
 15import tables
 16import time
 17from datetime import datetime
 18
 19from autopilot.hardware import gpio
 20from autopilot.tasks import Task
 21from collections import OrderedDict as odict
 22
 23class Blink(Task):
 24    """
 25    Blink an LED.
 26
 27    Note that we subclass the :class:`~autopilot.tasks.Task` class (``Blink(Task)``) to provide us with some methods
 28    useful for all Tasks.
 29
 30    Args:
 31        pulse_duration (int, float): Duration the LED should be on, in ms
 32        pulse_interval (int, float): Duration the LED should be off, in ms
 33
 34    """
 35    # Tasks need to have a few class attributes defined to be integrated into the rest of the system
 36    # See here for more about class vs. instance attributes https://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide
 37
 38    STAGE_NAMES = ["pulse"] # type: list
 39    """
 40    An (optional) list or tuple of names of methods that will be used as stages for the task. 
 41    
 42    See :attr:`~examples.tasks.Blink.stages` for more information
 43    """
 44
 45    PARAMS = odict()
 46    """
 47    A dictionary that specifies the parameters that control the operation of the task -- each task presumably has some
 48    range of options that allow slight variations (eg. different stimuli, etc.) on a shared task structure. This
 49    dictionary specifies each ``PARAM`` as a human-readable ``tag`` and a ``type`` that is used by the gui to 
 50    create an appropriate input object. For example::
 51    
 52        PARAMS['pulse_duration'] = {'tag': 'LED Pulse Duration (ms)', 'type': 'int'}
 53        
 54    When instantiated, these params are passed to the ``__init__`` method.
 55    
 56    A :class:`collections.OrderedDict` is used so that parameters can be presented in a predictable way to users.
 57    """
 58    PARAMS['pulse_duration'] = {'tag': 'LED Pulse Duration (ms)', 'type': 'int'}
 59    PARAMS['pulse_interval'] = {'tag': 'LED Pulse Interval (ms)', 'type': 'int'}
 60
 61    class TrialData(tables.IsDescription):
 62        """
 63        This class declares the data that will be returned for each "trial" -- or complete set of executed task
 64        stages. It is used by the :class:`~autopilot.core.subject.Subject` object to make a data table with the
 65        correct data types. Declare each piece of data using a pytables Column descriptor
 66        (see https://www.pytables.org/usersguide/libref/declarative_classes.html#col-sub-classes for available
 67        data types, and the pytables guide: https://www.pytables.org/usersguide/tutorials.html for more information)
 68
 69        For each trial, we'll return two timestamps, the time we turned the LED on, the time we turned it off,
 70        and the trial number. Note that we use a 26-character :class:`tables.StringCol` for the timestamps,
 71        which are given as an isoformatted string like ``'2021-02-16T18:11:35.752110'``
 72        """
 73        trial_num = tables.Int32Col()
 74        timestamp_on = tables.StringCol(26)
 75        timestamp_off = tables.StringCol(26)
 76
 77
 78    HARDWARE = {
 79        'LEDS': {
 80            'dLED': gpio.Digital_Out
 81        }
 82    }
 83    """
 84    Declare the hardware that will be used in the task. Each hardware object is specified with a ``group`` and 
 85    an ``id`` as nested dictionaries. These descriptions require a set of hardware parameters in the autopilot
 86    ``prefs.json`` (typically generated by :mod:`autopilot.setup.setup_autopilot` ) with a matching ``group`` and
 87    ``id`` structure. For example, an LED declared like this in the :attr:`~examples.tasks.Blink.HARDWARE` attribute::
 88    
 89        HARDWARE = {'LEDS': {'dLED': gpio.Digital_Out}}
 90        
 91    requires an entry in ``prefs.json`` like this::
 92    
 93        "HARDWARE": {"LEDS": {"dLED": {
 94            "pin": 1,
 95            "polarity": 1
 96        }}}
 97        
 98    that will be used to instantiate the :class:`.hardware.gpio.Digital_Out` object, which is then available for use
 99    in the task like::
100    
101        self.hardware['LEDS']['dLED'].set(1)
102    """
103
104    def __init__(self, stage_block=None, pulse_duration=100, pulse_interval=500, *args, **kwargs):
105        # first we call the superclass ('Task')'s initialization method. All tasks should accept ``*args``
106        # and ``**kwargs`` to pass parameters not explicitly specified by subclass up to the superclass.
107        super(Blink, self).__init__(*args, **kwargs)
108
109        # store parameters given on instantiation as instance attributes
110        self.pulse_duration = int(pulse_duration)
111        self.pulse_interval = int(pulse_interval)
112        self.stage_block = stage_block # type: "threading.Event"
113
114        # This allows us to cycle through the task by just repeatedly calling self.stages.next()
115        self.stages = itertools.cycle([self.pulse])
116        """
117        Some generator that returns the stage methods that define the operation of the task.
118        
119        To run a task, the :class:`.pilot.Pilot` object will call each stage function, which can return some dictionary
120        of data (see :meth:`~examples.tasks.Blink.pulse` ) and wait until some flag (:attr:`~examples.tasks.Blink.stage_block` ) is set to compute the
121        next stage. Since in this case we want to call the same method (:meth:`~examples.tasks.Blink.pulse` ) over and over again,
122        we use an :class:`itertools.cycle` object (if we have more than one stage to call in a cycle, we could provide
123        them like ``itertools.cycle([self.stage_method_1, self.stage_method_2])`` . More complex tasks can define a custom
124        generator for finer control over stage progression.
125        """
126
127        self.trial_counter = itertools.count()
128        """
129        Some counter to keep track of the trial number
130        """
131
132
133        self.init_hardware()
134
135        """
136        Hardware is initialized by the superclass's :meth:`.Task.init_hardware` method, which creates all the
137        hardware objects defined in :attr:`~examples.tasks.Blink.HARDWARE` according to their parameterization in 
138        ``prefs.json`` , and makes them available in the :attr:`~examples.tasks.Blink.hardware` dictionary.
139        """
140
141        self.logger.debug('Hardware initialized')
142
143        """
144        All task subclass objects have an :attr:`~autopilot.tasks.Task.logger` -- a :class:`logging.Logger` that allows
145        users to easily debug their tasks and see feedback about their operation. To prevent stdout from
146        getting clogged, logging messages are printed and stored according to the ``LOGLEVEL`` pref -- so this
147        message would only appear if ``LOGLEVEL == "DEBUG"``
148        """
149
150        self.stage_block.set()
151
152        """
153        We set the stage block and never clear it so that the :class:`.Pilot` doesn't wait for a trigger 
154        to call the next stage -- it just does it as soon as the previous one completes. 
155        
156        See :meth:`~autopilot.core.pilot.Pilot.run_task` for more detail on this loop.
157        """
158
159
160    ##################################################################################
161    # Stage Functions
162    ##################################################################################
163    def pulse(self, *args, **kwargs):
164        """
165        Turn an LED on and off according to :attr:`~examples.tasks.Blink.pulse_duration` and :attr:`~examples.tasks.Blink.pulse_interval`
166
167        Returns:
168            dict: A dictionary containing the trial number and two timestamps.
169        """
170        # -------------
171        # turn light on
172
173        # use :meth:`.hardware.gpio.Digital_Out.set` method to turn the LED on
174        self.hardware['LEDS']['dLED'].set(1)
175        # store the timestamp
176        timestamp_on = datetime.now().isoformat()
177        # log status as a debug message
178        self.logger.debug('light on')
179        # sleep for the pulse_duration
180        time.sleep(self.pulse_duration / 1000)
181
182        # ------------
183        # turn light off, same as turning it on.
184
185        self.hardware['LEDS']['dLED'].set(0)
186        timestamp_off = datetime.now().isoformat()
187        self.logger.debug('light off')
188        time.sleep(self.pulse_interval / 1000)
189
190        # count and store the number of the current trial
191        self.current_trial = next(self.trial_counter)
192
193
194        data = {
195            'trial_num': self.current_trial,
196            'timestamp_on': timestamp_on,
197            'timestamp_off': timestamp_off
198        }
199
200        """
201        Create the data dictionary to be returned from the stage. Note that each of the keys in the dictionary
202        must correspond to the names of the columns declared in the :attr:`~examples.tasks.Blink.TrialData` descriptor. 
203        
204        At the conclusion of running the task, we will be able to access the data from the run with 
205        :meth:`.Subject.get_trial_data`, which will be a :class:`pandas.DataFrame` with a row for each trial, and
206        a column for each of the fields here.
207        """
208
209        # return the data dictionary from the stage method  and yr done :)
210        return data
Next Previous

© Copyright 2019, Jonny Saunders Revision 99f411b8.

Built with Sphinx using a theme provided by Read the Docs.
Read the Docs v: v0.4.4.post0
Versions
latest
stable
v0.5.0
v0.4.5
v0.4.4.post0
v0.4.4
v0.4.3
v0.4.2
v0.4.1
v0.4.0
v0.3.5
v0.3.4
v0.3.3
v0.3.2
v0.3.1
v0.3.0
parallax
main
hotfix
gammatone
dev
detour-datamodel
Downloads
On Read the Docs
Project Home
Builds

Free document hosting provided by Read the Docs.