For close loop optogenetics, a computer running a Bonsai script captured and recorded wireless sensor motion data and video information as described above in grey-walled open-field experiment. Here, data is also streamed to a customMATLAB code which analyzes action composition changes over the course of action reinforcement, we used the EMD metric to label individual 300 ms motion histograms with an actionID. For each arriving 300-ms segment we calculate the EMD distance
between each cluster exemplar (or representative) of the ground truth cluster library from the grey open field behavior recording. The motion features histogram is assigned to the action for which comparison with the exemplar gave the lowest EMD score (most similar to target) among stall comparisons. Decision making for stimulation has a range of 35-55 ms time gap between action performance and sent decision for stimulation. To trigger optogenetics, a Multi-Pulse WidthModulation (PWM) generator (Harp Multi-PWM Generator hardware v1.1, Assembly v1, Harp v1.4, Firmware v1.1; Harp Multi-PWMGenerator software v2.1.0; Champalimaud Scientific Platform) converts each decision to trigger laser into electrical signals for 15 light pulses of 10 ms pulse duration at 25 Hz, with each train of pulses occurring over 600 ms and at 25% duty
cycle. The multi-PWM signal is passed through a 12 V, 7.2 W amplifier (Champalimaud Scientific Platform) and fixed frequency driver(Opto-electronic, MODA110-D4-30 (2001.320220)) to control the activities of a 473 nm, blue low noise laser (ShanghaiDream Lasers Technology, Co, Ltd. SDL-473-200T), which was sent through an acousto-optic modulator(Opto-electronic, MTS110-A3-V1S (1001 / 330433)).The laser component that is modulated is then reflected by a mirror and funneled to a mono fiberoptic patchcord, which is then coupled to a commutator. The output laser is then passed through a dual-optic fiber patchcord and connected to the implant cannula. Power adjustment out of the tip of patchcord was made so that ~5mW was emitted from each end of the dual optic fiber cannula. To ensure common time stamps from different channels, a clock synchronization device (HarpClock Sync v1.0;Champalimaud Scientific Platform) was performed between the basestation and multi-PWM device.