> Agents can also search and read this documentation through its [MCP server](https://zapit.swcmicroscopy.com/~gitbook/mcp).

# Zapit Optostim: Introduction

[Zapit](https://github.com/Zapit-Optostim) is a general purpose package for coordinating galvo-based optostimulation *in vivo*.

<div align="center"><figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FIph9XyGTIeCiBo6yeA9X%2Fzapit_example_image.jpg?alt=media&amp;token=d4f7d6f3-fc27-4170-ab50-35bc1c8ecd19" alt=""><figcaption><p>Zapit GUI showing the "Calibrate Sample" stage</p></figcaption></figure></div>

### What is it?

Zapit is point-based (scanner-based) optostimulator system for head-fixed mouse behavioral tasks. The software will run on a variety of hardware designs and experimental paradigms. A user-friendly MATLAB GUI handles creation of stimulus sets, scanner calibration, and alignment of stereotaxic coordinates to the sample. The experiment itself is run via a MATLAB API: using a small number of simple commands the user can initiate and stop optostimulation, and handle trial logging to disk. There is a Python wrapper for the MATLAB API and support for presenting stimuli in other programming languages.&#x20;

### How does it work?

A pair of scan mirrors deflect an incoming laser beam, which is focused onto the exposed skull of a head-fixed animal with a lens. This lens is also used to image the sample onto a camera in order to visualise where the beam is pointing. Zapit registers the scanners to the camera, allowing the user to place the beam in any desired location by clicking on a live image feed. Zapit maps stereotaxic coordinates into the camera space, allowing the user to point the beam to coordinates defined with respect to bregma. A graphical tool builds experiment coordinate files using a top-down view of the Allen Atlas. Two stimulation regimes are currently possible:

1. The beam is parked at a single location and gated with a fixed duty cycle (typically 40 Hz) until a command is issued to end the trial.
2. The beam is cycled between two or more coordinates at a fixed duty cycle.

Within any single experiment, coordinates are chosen from a pre-defined list. Stimulation begins either immediately after an API command is issued or after a hardware trigger is received by the DAQ. Stimulation ends on receipt of an API command and laser intensity is decreased gradually over a period of about 250 ms to avoid the significant rebound artefacts which would occur in the absence of the ramp. &#x20;

{% hint style="danger" %}
Zapit is being used in production experiments at the Sainsbury Wellcome Centre but it remains under development. New users should check the live Issues on GitHub, in particular the known obvious ones at: <https://github.com/Zapit-Optostim/zapit/labels/Known%20obvious%20issue>
{% endhint %}


# Feature List

Why use Zapit?

#### Features

* Open source [hardware](https://github.com/Zapit-Optostim/zapit_CAD) and [software](https://github.com/Zapit-Optostim/zapit).&#x20;
* [One-click automatic calibration of the scanners to camera using a grid of points.](https://zapit.swcmicroscopy.com/using-the-gui/scanner-calibration#conducting-the-calibration)
* [Easy manual calibration of sterotaxic space to the live image feed. ](https://zapit.swcmicroscopy.com/using-the-gui/sample-calibration)
* [GUI for building stimulus sets.](https://zapit.swcmicroscopy.com/using-the-gui/stimconfig-editor)
* On a single trial one or more locations are stimulated in series. The maximum number of points is limited by laser power and the kinetics of the opsin.
* Interactive tools for [checking calibrations](https://zapit.swcmicroscopy.com/using-the-gui/scanner-calibration#checking-the-calibration) and stimulus positions.
* [An easy to use API](https://zapit.swcmicroscopy.com/running-experiments/matlab/basic-api-usage-in-matlab) for integrating photostimulation into experiment code in MATLAB and [Python](https://zapit.swcmicroscopy.com/running-experiments/python/basic-zapit-api-use-in-python).&#x20;
* Automatic logging of stimuli during an experiment.&#x20;
* Power is conveniently displayed to the user in mW following a simple calibration procedure.
* Stimuli are sent to the DAQ at the trial start then hardware triggered for precise onset.&#x20;
* Stimuli may be presented for a fixed duration or terminated after an arbitrary time.&#x20;
* Installation and updates via MATLAB's add-on manager. User notified of new versions in the GUI.&#x20;

#### The Geeky Bit

* It's been neatly version controlled with [releases](https://github.com/Zapit-Optostim/zapit/releases) and [Issues are logged](https://github.com/Zapit-Optostim/zapit/issues?q=).&#x20;
* The code is [idiomatically written with extensive comments](https://github1s.com/Zapit-Optostim/zapit/blob/main/zapit/+zapit/@pointer/sendSamples.m), making it easy to modify and fix.([Here is how that last link works](https://www.stefanjudis.com/notes/github1s-open-any-github-repository-in-vs-code-in-your-browser/). Add MATLAB syntax highlighting via the Extensions icon on the left.)
* Everything is [structured neatly in packages](https://github.com/Zapit-Optostim/zapit/tree/main/zapit/%2Bzapit). For example, try typing `help zapit.settings`.
* The GUIs and underlying logic are [separated in a model/view/controller architecture](https://github.com/Zapit-Optostim/zapit/blob/main/zapit/%2Bzapit/%2Bgui/README_GUIs.md).&#x20;
* There are [tests](https://github.com/Zapit-Optostim/zapit/tree/main/tests) and [examples](https://github.com/Zapit-Optostim/zapit/tree/main/examples).


# FAQ

* **Can I use a laser that has no analog control and only TTL?** Sort of. Zapit has a TTL signal signal on AO3 that is used to drive an optional masking LED. You could connect this to your laser and it will drive it. *However* you get no rapid power control, so you have to use the same number of points in every trial and you can not ramp down power at the end of the stimulus. The latter is a problem, because it will generate rebound artifacts when the stimulation ends. &#x20;
* **Which wavelengths does the system work with?** Any, but if you are using far red [please see this preprint](https://www.biorxiv.org/content/10.1101/2024.08.14.607152v1).

<br>


# Hardware setup

Building the system

## LASER SAFETY

Zapit is an optostimulation device that uses Class 3B laser. A Class 3B laser has sufficient power to instantly blind. The system should be assembled only by qualified individuals. You assume all the risk in setting up the System: the designers of the system are not liable for injury or damage.&#x20;

In normal use, Zapit produces a 10 cm open beam as this is the working distance of the objective lens. This open beam is unavoidable. When set to a 2 mW time-averaged power stimulating 1 or 2 points per trial the system is delivering 4 mW of power, which is roughly at the threshold for what is safe should you be transiently hit in the eye. When set to >2 mW time averaged power or when using more than points per trial the system will yield unsafe power levels. To use Zapit safely, you should conduct alignment operations at 1 mW or less and use the system in a light-tight enclosure. &#x20;

&#x20;

## Building the system

We have a parts list and CAD files for a custom enclosure available on our [Zapit CAD repository](https://github.com/Zapit-Optostim/zapit_CAD). Detailed construction instructions are pending. Zapit can also be constructed from the off-the-shelf ThorLabs parts, although we do not have an example design available at present. We are keen to help others build the system, so if you feel you lack information please make contact via GitHub and we will get you up and running.&#x20;

## Obis Setup

#### Starting the Obis for the first time

Connect up the Obis as described in its manual. Install the Coherent Connection Software. Connect the Obis to your PC via USB. Confirm that yuo can start the laser and change the output power using the slider in the "Operating Power" tab. You can confirm the reported output power in mW matches the actual power with a power meter.

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FzN3irGpjXrpkitLar8N5%2Fimage.png?alt=media&amp;token=f3112d98-f812-49df-87e9-b38785252ea4" alt=""><figcaption><p>Testing laser output</p></figcaption></figure>

#### Enabling analog mode

In the "Remote" tab set the input impedance to 2000 Ohms. We have found that leaving it at 50 Ohms does not allow a 5V control signal from an NI DAQ to elicit the maximum power.&#x20;

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2F7AJCRiIXNxXwtrn9gOA5%2Fimage.png?alt=media&amp;token=5fbd8643-452a-4623-8f00-f8cadfec6013" alt=""><figcaption><p>Input impedence</p></figcaption></figure>

Go to the "Advanced" tab. Stop the laser if it is running. Set operating mode to "Analog:Power" and start laser again.&#x20;

&#x20;

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FAwK30savIByCjDZtj77A%2Fimage.png?alt=media&amp;token=e5a62572-3d39-4492-9bf4-43960fbf821f" alt=""><figcaption><p>Set laser to analog power</p></figcaption></figure>

#### Enable Auto-Start

Remove the sticker on the Coherent Obis box and enable auto-start. This way the laser will turn on when you switch it on. Otherwise you have to connect it to the PC via USB and turn it on that way each time.&#x20;

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FrrLjgkDAQ6Scfaz0xVFT%2Fobis_auto_start.jpg?alt=media&amp;token=53756520-0515-4805-be40-25c5fda739f7" alt=""><figcaption><p>Obis Auto-Start</p></figcaption></figure>

{% hint style="info" %}
The Obis laser responds linearly to the control signal but it does have a non-zero minimum laser power. You should check you setup so you know how it behaves. Likely will find that that the laser can not produce power values below about 0.25 to 0.5 mW. In practice this should make no difference: the only time you may notice it is when examining the rampdown following a low-power photostimulation. The last pair of pulses may not play out as they could be below threshold.&#x20;
{% endhint %}

### Masking light

It is probably a good idea to add an LED masking light, unless you can otherwise control for the presence of the laser photostimulation light. Analog output 3 on the DAQ will produces a 0/5V (TTL) waveform that can be used to gate an LED driver. Hook up AO3 to the gate input on your LED driver. The LED will flash in sync with the laser during stimulation trials. During control trials, the laser will be off but the scanners will move and the LED masking light will be on.&#x20;

### Scanner Setup

If your scanners did not come with a PSU, you will need to set up two unipolar DC PSUs to form a bipolar PSU ([see parts list](https://github.com/Zapit-Optostim/zapit_CAD/blob/main/Parts_List.md)). Supply A will provides +V and supply B provides -V. In addition, -V on supply A is connected to +V on supply B *and this is ground for the scanner controller*. If you have never set up something like this, either get advice from someone who has or do some reading first to make certain you wire up everything correctly.&#x20;

If you are using ScannerMax galvos and want to swap the short control cable for a longer one, [please see this video](https://www.youtube.com/watch?v=ZcLodfoWSN4\&ab_channel=ScannerMAX). You will need to contact the manufacturer to be given the magic command for accessing the advanced settings for the scanner control card.&#x20;

### Wiring the NI DAQ

The DAQ should be wired as follows:&#x20;

* AO0 to the X galvo controller analog input.
* AO1 to the Y galvo controller analog input.
* AO2 to the laser control analog input.&#x20;
* AO3 to the optional masking light TTL in. Building and setup of this light source is left to the user.&#x20;
* Connect PFI0 to your trigger source. &#x20;

&#x20;


# Software setup

These instructions assume you have already assembled the hardware, wired the DAQ, aligned the laser, etc. &#x20;

#### MATLAB

Zapit has been tested on MATLAB R2022a and R2022b and it should work on more recent versions also. It may work on earlier versions but this has not been tested. The latest version of MATLAB is recommended. You will need a PC with at least 16 GB of RAM.&#x20;

#### MATLAB Toolboxes

You will need the following MATLAB ToolBoxes.&#x20;

* [Image Processing Toolbox](https://www.mathworks.com/help/images/index.html)
* [Image Acquisition Toolbox](https://www.mathworks.com/products/image-acquisition.html)
* [Curve Fitting Toolbox](https://www.mathworks.com/help/curvefit/) (used for calibrating power on non-linear lasers. Not needed for Obis)
* [Instrument Control Toolbox](https://uk.mathworks.com/products/instrument.html) (optional: use for TCP/IP comms)

#### DAQ Drivers

* Install NI [DAQmx](https://www.ni.com/en-gb/support/downloads/drivers/download.ni-daqmx.html) and ensure you have checked to install **with .NET support enabled**. Ideally install one of our tested versions: 19.0 to 21.8.

#### Camera Drivers

Zapit currently supports only Basler cameras (although in principle this can be extended to other cameras). You will need to:

* If not done already, install [Basler's Pylon](https://www.baslerweb.com/en/downloads/software-downloads/#os=windows;version=all;type=pylonsoftware;language=all) [Camera Software Suite Windows](https://www.baslerweb.com/en/downloads/software-downloads/software-pylon-7-2-1-windows/). Choose the Developer option during installation and your connection type (probably USB). Plug in your camera into a USB3 port and confirm it is detected and runs using the software.&#x20;
* Install the [Image Acquisition Toolbox Support Package for GenICam Interface](https://uk.mathworks.com/matlabcentral/fileexchange/45180-image-acquisition-toolbox-support-package-for-genicam-interface). Either from that link or, better yet, via the[ Add-On Manager](https://uk.mathworks.com/help/matlab/matlab_env/get-add-ons.html) accessible via **Home** > **Add-Ons** on the MATLAB ribbon.&#x20;

You will need to restart MATLAB after the camera driver has been installed. If you later encounter problems connecting to the camera in MATLAB, see [Basler's instructions for the GenICam interface](https://www.baslerweb.com/en/downloads/document-downloads/using-pylon-gentl-producers-for-basler-cameras-with-matlab/).<br>

#### Installing Zapit

Gather and install the above requirements then install Zapit in one of the following ways:

* *Via MATLAB*: Go to the **Apps** ribbon in MATLAB and click on **Get More Apps**. Search for Zapit and add it to MATLAB. This is recommended.
* *Via your browser*: Navigate to the [Zapit File Exchange page](https://uk.mathworks.com/matlabcentral/fileexchange/122142-zapit). Download. Unpack in a reasonable place. Add the  `zapit` directory (i.e. that which contains `start_zapit.m`) to your path. You need add only this directory, not it and all sub-directories.
* *Via Git*: Clone [the repo](https://github.com/Zapit-Optostim/zapit) in your favourite Git client. Add the  `zapit` directory (i.e. that which contains `start_zapit.m`) to your path. You need add only this directory, not it and all sub-directories.

You will need to configure Zapit before it can be started.&#x20;


# Configuring Zapit

## Starting for the first time <a href="#setting-up" id="setting-up"></a>

Run the following command to make the settings file:

```
>> zapit.settings.readSettings;
```

You will be prompted to choose the location where the settings file is created. Make the choice and press return. Then navigate to the location where you asked for the settings file to be created. This will contain a file called `zapitSystemSettings.yml` that contains device configuration information and also caches the GUI state.&#x20;

{% hint style="info" %}
If you already have a known working settings file, you can simply replace the default `zapitSystemSettings.yml` with your file and skip the rest of the configuration instructions. If you are using a file given to you by someone else, confirm that the NI device ID setting is correct for your system. You can check the ID of your NI device via the NI MAX application. You should also be familiar with the the [Laser Power Calibration instructions](https://zapit.swcmicroscopy.com/installation-and-setup/configuring-zapit/laser-power-calibration), as you might need to do that from time to time.&#x20;
{% endhint %}

You will need to edit the YML file in a text editor of your choice. The contents of the file will be something like this:

```yaml
general: {maxSettingsBackUpFiles: 50.0, openPythonBridgeOnStartup: 0.0}
NI: {device_ID: Dev2, samplesPerSecond: 100000.0, triggerChannel: PFI0, wrapper: dotnet}
scanners: {voltsPerPixel: 0.0022, invertXscanner: 0.0, invertYscanner: 0.0}
laser:
  name: obis
  laserMinMaxControlVolts: [0.0, 5.0]
  laserMinMax_mW: [0.0, 44.6]
  maxValueInGUI: 30.0
camera: {connectionIndex: 1.0, default_exposure: 800.0, micronsPerPixel: 11.72, flipImageUD: 1.0,
  flipImageLR: 1.0}
calibrateScanners: {areaThreshold: 500.0, calibration_power_mW: 5.2, beam_calib_exposure: 900.0,
  bufferMM: 2.0, pointSpacingInMM: 2.0}
calibrateSample: {refAP: 3.0}
experiment: {defaultLaserModulationFrequencyHz: 40.0, defaultLaserPowerMW: 5.0, offRampDownDuration_ms: 250.0,
  blankingTime_ms: 0.6, blankOnsetShift_ms: -0.12, blankOffsetShift_ms: 0.25}
tcpServer: {IP: localhost, port: 1488.0, enable: false}
cache:
  ROI: []
  previouslyLoadedFiles:
  - []
```

Some settings you will need to change. Other settings are either cached GUI values, and can be left alone, or are there only for developers or super-users. Proceed through the next steps in order.


# General settings

#### `general`

* `maxSettingsBackUpFiles` is the number of backup settings files the software stores. You can leave this alone or change it if you wish.
* `openPythonBridgeOnStartup`should be set to `1` if you want to control Zapit from Python. Otherwise leave at `0`.


# NI DAQ settings

#### `NI`

* `device_ID` **must** be set to the name of the DAQ you will use to run Zapit. Open [NI MAX](https://www.ni.com/en-gb/support/documentation/supplemental/21/what-is-ni-measurement---automation-explorer--ni-max--.html) and find the name of your DAQ. Likely it will be called `Dev1`, `Dev2` or similar. If you wish, you can change the name to something more meaningful, such as "`zapit`". Either way, find the name and enter this as the value of `device_ID`.
* `wrapper` determines the method used by MATLAB to communicate with [NI DAQmx](https://www.ni.com/docs/en-US/bundle/ni-daqmx/page/daqhelp/nidaqoverview.html). It should stay as `dotnet`
* `samplesPerSecond` It's probably a bad idea to edit this.
* `triggerChannel` defines the channel on which Zapit looks for a trigger before initiating stimulation during an experiment.&#x20;


# Experiment settings

#### `experiment`

The values in this section are used as defaults when a new stimulus configuration file is created. You can change the exact value in the stimulus configuration GUI, so here you need to only choose the most common values you expect to use. Likely you can leave all of these as they are.

* `defaultDutyCycleHz` is the default duty cycle (the frequency) at which the laser will stimulate each point. A value of 40 Hz or 50 Hz is commonly used in the field.&#x20;
* `defaultLaserPowerMW`defines the *time-averaged* power in mW at the sample surface used for stimulation. In other words, if two points are being stimulated in a single trial and requested power is 2 mW then the laser would deliver 4 mW at the sample. A power meter receiving light from just one of those points would report an average power of 2 mW.&#x20;
* `offRampDownDuration_ms` defines the time course over which the laser will decay from the chosen stimulation power in mW to zero mW. About 250 ms has been shown to be a good choice.
* `blankingTime_ms` defines the number of ms during which the beam is switched off and the scanners move from one point to the next. The default value is suitable for faster scanners, like those from ScannerMax or CamTech.  You don't need to change this now
* `blankOnsetShift_ms` and `blankOffsetShift_ms` are used to control the relative time of the laser blanking. You should probably verify these settings, but you can not do it yet. &#x20;

Once you have finished editing these, you can save the settings file.&#x20;


# Scanner & Camera settings

The remaining settings will mostly need to be set interactively once Zapit has started. Let's start the software:

```
>> start_zapit
Available interfaces:
1  -  videoinput('gentl', 1, 'Mono12')
2  -  videoinput('gentl', 1, 'Mono8')

Connecting to number 1
Connecting to DAQ
Connecting to NI hardware via .NET DAQmx.
No laser fit file found. Laser is uncalibrated
Zapit is installed at C:\UsersMatlab_Scripts\zapit\
Building GUI
Zapit has started
Zapit is up to date.
Zapit version 0.10.2  --  2023/2/1
```

You should see some messages at the command line then after a short delay the GUI will appear. The image is a live camera feed. Place an object in the field of view and focus. Now you will set the scanner and camera settings. &#x20;

#### Setting the image orientation

{% hint style="warning" %}
**You should confirm that the image itself is not inverted!** If it is, there is a chance that the beam will go the Left hemisphere when you asked for the Right. This will not be obvious unless you look at the sample itself!
{% endhint %}

Make some target with a clear left/right/up/down directions. If the on-screen image does not look as expected, alter the `flipImageUD` or `flipImageLR` parameters under `camera` until it does. True `1` and false is `0`. For a 180 degree flip, set both of these to 1. After editing the YML you will need to restart Zapit for your changes to take effect.

#### Setting the scanner orientation

Start the laser and Zapit. Press "Point Mode" in the GUI and click on a location in the image feed. Adjust "Exposure" if needed. The desired position is shown by the red circle. The beam will not go to the desired position because the calibration has not yet been performed. However it is a good idea for the beam to go in the same *direction* as the mouse cursor. You can verify this by clicking "Cat & Mouse" and moving the mouse cursor over the field of view. If the beam motion seems inverted in its behavior, it can be corrected with `scanners.invertXscanner` or `scanners.invertYscanner`. Close Zapit and alter the appropriate settings to `1` (true) or 0 (false) as needed. Restart Zapit and verify. Once done you should have the beam going in the correct direction when you point but with an offset. There is an automatic scanner calibration which will take care of this later.&#x20;

#### Exposure settings

You will see a `camera.default_exposure` and a `calibrateScanners.beam_calib_exposure`. These are both changed via the GUI and you can ignore them.&#x20;

#### Scale settings

`camera.micronsPerPixel` is the number of microns per pixel at the sensor. To obtain this, find the pixel size in your camera spec sheet  (for example, the [Basler ACA1920-40um](https://www.baslerweb.com/en/products/cameras/area-scan-cameras/ace/aca1920-40um/#specs), has a pixel size of 5.86 microns) then divide that by the magnification of your optical system. Our suggest setup for mouse brains, for example, has an f=100 mm objective and an f=50 mm tube lens. This yields a magnification of 0.5 and a pixel size of 11.72 microns. &#x20;

`scanners.voltsPerPixel` is used to map scanner control voltage to a pixel location on the screen. A reasonable default value for this assuming an f=100 mm objective and ThorLabs Basic Scanners is `0.022`.  This value does **not** depend on the number of microns per pixel the system is set to. Having a reasonably accurate value is necessary for the the "Point Spacing" and "Border Buffer" settings used during scanner calibration to be accurate. However, so long as the system can calibrate itself, an accurate voltsPerPixel value is not important. To set this value, start Zapit and wipe any existing scanner calibration there may be (`hZP.wipeScannerCalib`).  Set the system to "Cat and Mouse" mode. Place the red circle near the middle of the field of view (0/0) and align final fold mirror until the beam points at the circle. Now move the circle and ensure the beam remains near the circle throughout. If the gain of the laser spot if obviously larger or smaller, edit the value of `hZP.settings.scanners.voltsPerPixel` at the command line until the mismatch has gone. e.g.

```matlab
hZP.settings.scanners.voltsPerPixel = 0.002
```

You don't have to be spot on: just ensure there is no obvious gain difference. The scanner calibration procedure should get rid of any residual mismatches.&#x20;

{% hint style="info" %}
Assigning values to settings at the command line as shown above **will change the values in the user settings file**. So when you quit and re-start Zapit, these settings will persist. Do not assume you can revert settings applied this way by restarting Zapit.
{% endhint %}


# Laser Power Calibration

These settings are used for analog input control to the laser.&#x20;

#### `laser`

* `laserMinMaxControlVolts` should be the maximum and minimum analog input values that your laser will accept. Set to 5V max for the Obis.&#x20;
* `laserMinMax_mW` is the maximum and minimum power your laser will produce. We will change these in the next section. Leave them alone for now.&#x20;
* `name` is just for information purposes at the moment. Change it to the model name of your laser.
* `maxValueInGUI` is the maximum control value accessible in the GUI. You will be photoactivating in the range of about 1 to 10 mW but you might want more power for the scanner calibration stage. The default maximum power that can be set in the GUI is 30 mW but you can alter it by changing this setting. &#x20;

*Save the settings file and restart Zapit before carrying on*.&#x20;

#### Calibrating the laser

The Zapit GUI allows the user to specify power in mW at the sample. In order to achieve this, the laser must be calibrated using a power meter. A suitable power sensor and meter would be a ThorLabs [S121C](https://www.thorlabs.com/thorproduct.cfm?partnumber=S121C) and [PM100D](https://www.thorlabs.com/thorproduct.cfm?partnumber=PM100D). You can also buy the [PM103A](https://www.thorlabs.com/thorproduct.cfm?partnumber=PM103A) if you want a cheaper unit with the disadvantage that it requires a PC (this unit has an analog output, which you may need so **do not** buy the cheaper [PM100USB](https://www.thorlabs.com/thorproduct.cfm?partnumber=PM100USB)).&#x20;

For lasers such as the Obis, where output power is linear as a function of the control signal only the following linear calibration procedure is necessary. For systems using an EOM or AOM, where power output is non-linear as a function of control voltage, an additional step is needed. This is described below and require Zapit version 1.0.4 or later.&#x20;

* Start Zapit.
* Turn on the laser and wait half an hour for it to warm up and settle.&#x20;
* Place the power sensor where the sample will be and turn on the beam with the "Off/On" control located in the "Laser power (mW)" section of the GUI. <img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2F4NitBO7VTpQNlwcRosYT%2Fimage.png?alt=media&amp;token=01859aa1-b04b-499a-aacc-5c1cc958ba7e" alt="" data-size="original">
* Set your power meter to the wavelength of your laser and set the scale to the 100s of milliwatts so it does not change range automatically during the process.  Point the beam at the sensor. Make sure you can obtain a reading.&#x20;
* Set the laser to maximum power using the command line. For the Obis this is 5V so we issue at the CLI:\
  `>> hZP.setLaserPowerControlVoltage(5)`
* Read off the value on the power meter. Let's say you read 41.1 mW.&#x20;
* You can now tell Zapit what this maximum value is in mW by entering at the command line: `>> hZP.settings.laser.laserMinMax_mW=[0,41.1];` \
  This updates the YAML settings file so you do *not* need to edit it. This step is for both linear and non-linear laser.

#### Finalising linear power calibrations

* For linear system, such as most small diode lasers like the Obis, test the calibration by asking for a laser power in mW `>> hZP.setLaserInMW(10)` You will likely find it accurate to within about about 0.1 or 0.2 mW.&#x20;
* Try a few different values. If your lower power values in particular are off by more than about 0.2 mW, you can probably improve the things by adding a small offset to the low mW value. e.g. `hZP.settings.laser.laserMinMax_mW(1)=0.04;` Do that by trial and error and things should improve.

#### Nonlinear power calibrations

If you have a laser with a **nonlinear** power/control curve (a sigmoid or one that can be fitted by a third order polynomial) you will need to measure this using a photodiode, such as a [ThorLabs PDA100A2](https://www.thorlabs.com/item/PDA100A2), or a power meter with an analog output. Then:

* Connect the NI DAQ AI0 terminal to the analog output of the sensor.
* Turn on the photodiode or power meter and point the beam at it.
* Run `hZP.generateLaserCalibrationCurve` This will record a calibration curve, fit it, and plot the results. A sigmoid and 3rd order polynomial are fitted with the best fit automatically used.&#x20;
* The measured curve is now active. An interactive CLI prompt will appear asking if you want to save the curve for future use.&#x20;
* The `hZP.loadLaserFit` method will re-load a previously saved calibration (only one can be saved). `hZP.saveLaserFit` will save the currently active calibration.&#x20;
* Try setting the laser power to a range of values to verify the reported and true laser power match.&#x20;

**NOTE** this measurement step measures the *shape* of the calibration curve. The scale (max/min values) were set previously where you assigned values to `hZP.settings.laser.laserMinMax_mW`&#x20;

Please [file an Issue](https://github.com/Zapit-Optostim/zapit/issues/new/choose) if you have problems with this process or it does not work.<br>

#### Checking power day to day

Put the power meter under the objective and set up as before. Set the power in the GUI or at the command line (e.g. `hZP.setLaserInMW(10)`) and confirm the reading with a power meter. If it is off, repeat the above steps.&#x20;


# Blanking settings

## What are the blanking settings?

Zapit blanks the beam when moving between points. The defaults in the settings file work with 5 mm ScannerMax galvos. For other galvos you may need to tweak them. You should verify these settings before starting experiments. The settings we are interested in are:

* `experiment.blankingTime_ms` defines the number of ms during which the beam is switched off and the scanners move from one point to the next.
* `experiment.blankOnsetShift_ms` and `experiment.blankOffsetShift_ms` are used to control the relative start and end time of the laser blanking with respect to the motion time period of the beam. These settings take into account the lag between the scanner command signal and the scanner motion.

## Setting up the system for testing

Start Zapit and run the following to do a fake calibration:

```
hZP.applyUnityStereotaxicCalib
hZP.scannersCalibrated=true;
```

Connect:

1. AO0 to channel 1 of your osciloscope and also to the X scanner control input using a T.&#x20;
2. Connect the X scanner feedback signal to channel 2 of your oscilloscope.&#x20;
3. &#x20;Connect AO2 to channel 3 of your osciloscope.&#x20;

Load the stimulus config file called `uniAndBilateral_5_conditions.yml` You will find that in the examples folder. In the second tab in the GUI, select condition 2 and present it. You should see waveforms appearing on the scope. A system that is well set up should look as follows:

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FC59N3gF6O4xe4fgQlOHC%2Fblanking_calib_traces.jpg?alt=media&amp;token=22254e6a-ba83-4172-ac5c-ec880a6d2521" alt=""><figcaption><p>Waveforms used to check blanking parameters. Yellow: X scanner control signal. Blue: X scanner feedback signal. Magenta: laser analog control signal. Note laser is off (low) during the time the mirror is moving.  </p></figcaption></figure>

Should your traces indicate that the blanking time is not correctly synchronised to the motion time, you can alter the relative start and stop of the laser blanking by altering `experiment.blankOnsetShift_ms` and `experiment.blankOffsetShift_ms` To do this, simply stop the stimulation in the GUI and do, say, `hZP.settings.experiment.blankOnsetShift_ms=-0.2` Then try the stimulation again. The settings are automatically saved to the YML file. **i.e. If you start and stop Zapit, the new blanking setting will persist**.&#x20;


# Staying up to date

Upgrading Zapit

## Upgrade Notifications

The Zapit main window will print a notification in the title bar when a new version is available. If you installed via the MATLAB Add On Manager then you can return there to update the software. Note: At the time of writing the MATLAB Add On Manager has a bug that may cause the update  to fail. If you receive an error, you can update by simply uninstalling and re-installing via the Add On Manager.&#x20;

## Is it safe to upgrade?

You are encouraged to keep the software up to date and the way new versions are handled is designed to provide confidence that a new release will not break anything. New versions will appear as [GitHub releases](https://github.com/Zapit-Optostim/zapit/releases) and on the [MATLAB File Exchange](https://uk.mathworks.com/matlabcentral/fileexchange/122142-zapit?s_tid=prof_contriblnk\&requestedDomain=). All changes will be detailed in the [changelog](https://github.com/Zapit-Optostim/zapit/blob/main/CHANGELOG.md)[ ](https://github.com/Zapit-Optostim/zapit/blob/main/CHANGELOG.md)and new releases will generally alter just a small number of things. The version number will be the clearest indication of how major the changes are.

Zapit uses a system similar to [semantic versioning](http://semver.org), meaning it has a version number denoted as `MAJOR.MINOR.PATCH`Briefly, increments to the `MINOR` and `PATCH` version numbers will not be associated with potentially breaking changes. Only increments to the `MAJOR` version number will be. &#x20;

* The `MAJOR` version is incremented when there are incompatible API changes, or changes in functionality which might carry important caveats. You should review the nature of a MAJOR version change before upgrading a production system. An example of a MAJOR change might be that the API commands running the experiments change.
* The `MINOR` version is incremented when functionality is added in a backwards compatible manner. This might mean significant new features that do not break existing functionality, or it might mean existing features are significantly improved. For example, addition of a rat atlas, or improvements in the way stimulus conditions are overlaid in the main GUI.
* The `PATCH` version is incremented when there are backwards compatible bug fixes. It may also be incremented by the addition of new example code snippets, or by code changes which result in no functionality change.

#### TL/DR

If your current version differs from the latest version in only the `MINOR` or `PATCH` version numbers then it is almost certainly safe to upgrade, even on a production system in the middle of a series of experiments. As always, see the [changelog](https://github.com/Zapit-Optostim/zapit/blob/main/CHANGELOG.md)[ ](https://github.com/Zapit-Optostim/zapit/blob/main/CHANGELOG.md)first. Increments of the `MAJOR` version number should be treated with more caution. Breaking changes will be flagged as such in the changelog.&#x20;

####


# Introduction: Using the GUI

The GUI is used to calibrate the scanners, calibrate the sample, and set up stimuation coordinates.&#x20;

Start the sofware.

```
start_zapit
```

A window will open after a short delay.&#x20;

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FgTLalzHcg8GnwviUBrIi%2Fzapit_first_start.jpg?alt=media&amp;token=168b31c4-16ca-4983-add9-f3ed2dbe31b4" alt=""><figcaption><p>Zapit GUI</p></figcaption></figure>

A live image of the sample is displayed. Coordinates are in mm with 0 mm being the image centre. There are two tabs. "Calibrate Scanners" allows you to align the scanners with respect to the camera. "Calibrate Sample" is used to project stereotaxic coordinates onto the image space. The status bar along the bottom has indicators to show whether these two steps have been achieved.

Stimuli are defined using "stimulus configuration files". These can be loaded and created via menu options under "File". The name of the loaded stimulus config file is displayed in the status bar area.&#x20;


# Scanner Calibration

Calibrating the scanners to the camera view

This section describes how to calibrate the scanners so that they are in register with the image.

#### Before beginning

The first time you start Zapit you will see the full field of view of the camera. Since we only care about the area around the skull, we press "ROI" to draw a box and zoom in. This ROI is remembered when you next start the software. You can zoom back out again with the "Reset" button. Ensure the exposed of the skull is sharply in focus.&#x20;

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FpwnexH5l3Q8Z9fY3ll8n%2Fzapit_beforeafter_ROI_confirm.jpg?alt=media&amp;token=b67f36cf-ac7c-4345-b6f9-e7abb0b4b732" alt=""><figcaption><p>Zooming using the "ROI" button. Left: full field of view. Right: after cropping.</p></figcaption></figure>

#### Pointing the beam

Press `Point Mode` and click on the image. Zapit will attempt to place the beam at the clicked position. Likely it will be off (see image below) because the scanners have yet to be calibrated: the "Scanners Calibrated" indicator will be red. After clicking the beam remains on. You can alter laser power used for interactive calibration operations with the slider (the laser power used during stimulation for experiments is set elsewhere). You can turn off the beam with the laser On/Off switch next to the slider but the system will remain in Point Mode. Clicking `Point Mode` again will turn off the beam and exit point mode. You can enter a different mode (e.g. Cat & Mouse) directly without first un-clicking `Point Mode`. &#x20;

<div align="center"><figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2F7hsGcK6JlJLnUFZaHXpM%2Fpoint_mode_not_calib.jpg?alt=media&amp;token=de6683a6-7ef3-451f-bd7a-e1d787ffad65" alt=""><figcaption><p>With scanners uncalibrated the beam (bright spot)<br>does not point to the desired location (red spot). </p></figcaption></figure></div>

{% hint style="info" %}
If you see a lot of reflections surrounding the beam rather than a clean point, as above, then confirm that the bandpass filter is not tilted.&#x20;
{% endhint %}

#### Conducting the calibration&#x20;

Press `Run Calibration` to present a grid of points and conduct the calibration. Green circles are drawn at locations where the beam position was detected. You can use the `Point Spacing` spinner box to alter the density of points: 2 or 3 mm is usually OK. You can use the `Border Buffer` spinner box to avoid placing the laser near the edges of the field of view. e.g. setting this to `2` will mean that no laser points will be placed within 2 mm of the image border. A good calibration can be achieved with as few as four or five points. Adding more points will likely have a minimal impact, as the transformation being calculated is rigid (scale, rotation, and translation).&#x20;

{% hint style="info" %}
The exact spacing values will depend upon having a reasonably accurate value for scanners.voltsPerPixel in your settings file. See the "Scanner & Cameras settings" section under "Configuring Zapit".
{% endhint %}

#### Checking the calibration

Press the `Check Calibration` button and the beam will cycle over all detected beam positions (image below). You can also enter `Point Mode` or `Cat & Mouse` to confirm the laser goes to the clicked location (image below). You might want to turn down laser power to get a clearer image of the spot. At higher powers the spot size appears larger as the camera picks up more scattered light.&#x20;

<div><figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FAsHzasGE72Rmd9PGmVxI%2Fcheck_scanner_calib.jpg?alt=media&amp;token=aac67896-bdff-40cc-a9a0-c7738cfa9def" alt=""><figcaption><p>Checking the scanner calibration</p></figcaption></figure> <figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2F4j02gomky0aWJfuOEOrE%2Fpoint_mode_after_calib.jpg?alt=media&amp;token=0991e9a8-8f5c-4134-a5ba-cf48a07b2165" alt=""><figcaption><p>Point the beam after calibration<br>results in the beam going to the<br>desired position (red circle).</p></figcaption></figure></div>

&#x20;

#### Troubleshooting

* **What if too few points are found?** Try changing the laser intensity, the camera exposure, check the laser spot is in focus (use the `Point` button and turn down the power). If you still have an insufficient number of points, look at the messages that appear on the command window during calibration. When finding the laser,  Zapit looks for a small bright spot with a total size (the number of pixels) no greater than the value in `Size Thresh`. Reports to the command line will indicate if a point was excluded due to this. You can try increasing `Size Thresh`. &#x20;
* **What if problematic points on a headbar or similar are being detected?** Try increasing the "Border Buffer" setting in the GUI, causing a greater region around the ROI edge to not be sampled. You can also try reducing altering the "Size Thresh" setting in the GUI. If something is out of focus it yields a larger laser spot size and a smaller threshold should cause this to be ignored.


# Sample Calibration

Registering the sample to stereotaxic coordinate space

#### Registering the sample to stereotaxic space

The sample is registered interactively to stereotaxic space by placing an outline of the brain over the exposed skull. The outline is positioned using two reference points. The first point is always bregma. The second point can be user-selected via the `Ref AP` dropdown. Before initiating the calibration procedure, select a value you are happy with from this drop-down.&#x20;

{% hint style="warning" %}
To ensure accuracy it is necessary to use a stereotaxic frame to make a small mark on the skull corresponding to the location you have chosen for the Ref AP position. This way you have a second landmark in addition to bregma for performing the Sample Calibration step.&#x20;
{% endhint %}

Press `Calibrate Sample` and move the mouse over the image: a cyan outline of the brain will surround the mouse cursor. Click on bregma in the image to lock it to bregma of the outline. You will scale and orient the outline in the next step.

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FKziqSNH9YIH5FryAEqG3%2Fstarting_sample_calibrate.jpg?alt=media&amp;token=1bf1bb65-3ae1-467a-8fd4-f4ab5e7419b1" alt=""><figcaption><p>Pressing "Calibrate Sample" brings up a cyan brain border that follows the mouse cursor. Click on bregma in the image to lock it to bregma of the outline. You will scale and orient the outline in the next step.</p></figcaption></figure>

A red marker will appear over bregma once the outline is placed. The outline will now rotate and scale as the mouse cursor moves. If you are not happy with your choice of bregma, you can shift-click anywhere over the image to remove it. Click on the second point (defined by Ref AP) and a confirmation dialog appears: clicking `Yes` will commit the border and the outline turns green; clicking `No` will remove the outline. You have now completed the sample calibration procedure. To redo it simply click `Calibrate Sample` again. The `Paint brain border` button can be used when you are bored or are trying to impress visitors to the lab.&#x20;

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2F0qrifoO7z2KEObQXummg%2Frotate_and_scale_calilb.jpg?alt=media&amp;token=c16dce12-bbbb-455a-a06e-db3e372bcf08" alt=""><figcaption><p>The brain outline is freely rotated and scaled by moving the mouse cursor once bregma has been placed. </p></figcaption></figure>

#### Loading a stimulus config file

You will now load a stimulus configuration file. For the purpose of this example we will load the file `uniAndBilateral_5_conditions.yml` located in the `examples/example_stimulus_config_files` folder where Zapit is installed. If you don't know the install location, you can find it by typing the following command into the MATLAB command prompt. Load the file with `File` > `Load stim config` from the Zapit menu.

Previously loaded files appear in the `File` > `Load recent` menu for easier access.

```matlab
>> zapit.updater.getInstallPath

ans =

    '/Users/bob/Dropbox/MATLAB/ZapitOptostim/zapit/'
```

The stimulus config file that you loaded is a plain text file that defines inactivation locations for each condition, laser power, stimulus frequency, and the duration of the offset ramp at stimulus conclusion. You can open the files in a text editor but in the next section you will see how to create and edit them via Zapit's StimConfig Editor.&#x20;

#### Verifying the stimulus locations

The `Overlay stim sites` button will plot the locations of all stimulus sites as red circles. `Zap all coords` will cycle the beam rapidly between all stimulus locations. `Plot stim coords` button brings up a new window (e.g. as shown below) with the locations of each condition clearly described.

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FkFiYyKHCEOvQYrZbkSlz%2Fstim_map_example.jpg?alt=media&amp;token=3bc7de97-d1a8-4654-b2e7-3117f18145af" alt=""><figcaption><p>Stimulus coordinates in stereotaxic space.<br>The brain area borders are extracted from the<br>Allen Atlas.</p></figcaption></figure>

You can use the `Zap Site` button and associated drop-down menu to present a single stimulus condition at the laser power and repetition rate defined by the config file. Pressing `Zap Site` a second time will ramp down the stimulus and cease presentation. The `Paint area` button will use the laser to draw borders around the brain area(s) being stimulated in the selected trial. Use this option if bored or are trying to impress visitors to the lab.

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FlscRnpIbYOb8Pv9Hvbn5%2Fzap_sites_example.jpg?alt=media&amp;token=595a2461-a601-4f2c-8b2e-c5f2e1be76bb" alt=""><figcaption><p>"Zap Site" asks Zapit to start presenting the stimulus<br>indicated by the drop-down. Here the first site, which is<br>primary somatosensory cortex. The beam locations can<br>be made out in the image.</p></figcaption></figure>

The remaining buttons in the Calibrate Sample tab will be discussed in the[ ](broken://pages/zy9xdG5LYL0PmuG3yJY3)[Running Experiments](https://zapit.swcmicroscopy.com/running-experiments/introduction-running-experiments) section.


# StimConfig Editor

Constructing Stimulus Sets

The Stimulus Config Editor is a convenient way to create new configuration files for Zapit. You can start it by going to `File` > `New stim config` in the Zapit menu. If you are not at the rig, you can install Zapit and start editor standalone with the command `zapit.stimConfigEditor`

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FTTmAcagT0YgAq5h3N7sN%2Finitial_view_stimCOnfig_editor.jpg?alt=media&amp;token=b113b609-605b-431a-8ccc-a0f5eb98fa64" alt=""><figcaption><p>The stimulus configuration editor.</p></figcaption></figure>

Once started, you can use the `Load` button to open a previously created file or just start work on a fresh one. The `New` button will issue a confirmation dialog then wipe all points and start over. The `Save` buttons opens an interactive UI for saving the file; it does not simply over-write a file that is already loaded.

#### Adding points

Moving the mouse cursor over the atlas image will highlight the brain area under the cursor and report its identity in the figure title. A plot symbol follows the cursor. In `Bilateral` mode, there are two points over homologous positions on the left and right sides. In `Unilateral` mode there is only one symbol: that under the cursor.&#x20;

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FEHzSfc1c7MT9TEppmd11%2Fbilateral_point_add.jpg?alt=media&amp;token=fbf9871d-2cbd-4d66-b3ed-6764cc487ed0" alt=""><figcaption><p>Bilateral point mode adds symmertical locations on the right and left sides.</p></figcaption></figure>

Clicking on the atlas image will place the point and symbol under the mouse cursor will change, indicating that the GUI is ready to place the next stimulus condition. Try placing a few bilateral points. Each pair of differently colored symbols represents a different stimulus condition. There is no limit on the number of conditions you add.&#x20;

Now try `Unilateral` mode: clicking will place a single point under the mouse cursor. The number of points per stimulus condition is limited to two, so in `bilateral` mode you can not add further points to a stimulus condition. However, in `unilateral` mode a point can be appended to a condition. To do this, after placing the first point press the `shift` key: the symbol under the cursor will now match that of the last added point. Click again and a second point is added to the condition ([there is a known bug that makes this process fail sometimes](https://github.com/Zapit-Optostim/zapit/issues/58); just try again if that happens). By default you are blocked from adding more than two points. You can relieve this restriction by editing the `experiment.maxStimPointsPerCondition` setting in the config file. Zapit will handle presentation of multiple points in a trial up to limits imposed by laser power and scanner motion time. **You are responsible for ensuring that you have sufficient power to handle your stimulus set: see below**.

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FHg2jSESBq2w26rmZjmzI%2Fbilateral_and_unilateral.jpg?alt=media&amp;token=4611e621-9498-401a-b9ce-5e059f544580" alt=""><figcaption><p>Two bilateral have been added (triangles and circles) and one "Unilateral" condition (squares). </p></figcaption></figure>

You can only append points to the current stimulus condition. If you wish to append a point to a condition you added previously, you will need to delete that condition first (see below) then add it back, then append.

{% hint style="danger" %}
Stimuli composed of more than 2 points are a new feature to Zapit and not well tested. In particular, adding more points will reduce pulse duration and this can readily become shorter than the generally accepted minimum stimulation time for ChR2. For over about 3 or 4 points it is suggested you consider using a faster opsin, such as ChRmine.&#x20;
{% endhint %}

#### Removing points

Hold down the `ctrl` key and the symbol under the mouse cursor turns into a red cross. The stimulus condition points nearest the cursor will enlarge slightly. Clicking will remove these points. If there are two positions in the stimulus condition, both are removed.&#x20;

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2Fy1t3H6HEQHeaMQ4HOhAN%2Fdeleting_points.jpg?alt=media&amp;token=98361bc7-3d8a-4f66-9b2f-d88a89174d2a" alt=""><figcaption><p>Points are deleting by holding down "ctrl". The points nearest the cursor are enlarged. <br>Clicking will delete these highlighted points. </p></figcaption></figure>

#### Stimulus parameters

The parameters with which stimuli will be presented are set by the `Rampdown`, `Laser Power`, and `Stim. Freq.` spin boxes.&#x20;

* The `Rampdown` is the number of ms over which the laser power is gradually stepped down once the stop stimulus command is issued. Previous work indicates that about 250 ms is a safe and reasonable minimum value.
* The `Laser Power` setting defines the *time-averaged* power in mW at the sample surface used for stimulation. In other words, if two points are being stimulated in a single trial and requested power is 2 mW then the laser would deliver 4 mW at the sample. A power meter receiving light from just one of those points would report an average power of 2 mW.&#x20;
* The `Stim. Freq.` setting defines the on/off modulation rate of the laser. For a condition with one position, the laser is modulated at this rate using a square waveform. For two locations, the  beam is moved back and forth between the positions at this rate. The scanners take 1 ms to move from position to position regardless of the distance between points. The beam is blanked during this period.  &#x20;

#### &#x20;Saving the file

Once you are happy click the configuration you save it to disk with the `Save` button. If you launched the editor from Zapit, the saved file will appear immediately in Zapit's `File` > `Load recent` menu for quick access.

### Confirming Stimulus Power Point is Working

When presenting stimuli with large number of points, it is your responsibility to ensure that you have enough power for your stimuli to work. You can test this using the included example parameter file `power_check_multipoint.yml`. This file has 21 conditions. In condition 1 there is just one point over unilateral V1. In condition 2 there is the same point over 1 and a second point far anterior to it. In condition 3 there are two anterior points and the V1 point. And so on. Place a power meter such that the V1 point hits the meter but none of the others do. Block with an iris if needed. Measure power of the one point as you increase the point number. Faster sensors and power meters will begin to under-estimate power as the number of points goes up! With the ThorLabs meter and a photodiode sensor, this can be counteracted by setting the scale range to `180 mW`. Alternatively, you might get around the issue by using a slower sensor. You should find a reasonably flat line up to the point at which Zapit starts to complain at the CLI that the requested laser power is unattainable. For example:

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FbKkUzX4lKPRpRX7rGyfP%2Fimage.png?alt=media&amp;token=e1686ec2-bf57-4a27-8cd0-f2a072e8b144" alt=""><figcaption><p>Laser power per point drops off at 20 and 21 points, but these are the values at which we have run out of power. Nonetheless power stays within 0.1 mW of the requested 2.0 mW for all stimuli.</p></figcaption></figure>


# Generating stimulus patterns at the CLI

How to generate complicated stimulus patterns at the command line

There is a command line tool called `zapit.utils.stimConfigPatternGenerator` for generating patterns of stimuli, like grids or crosses, at the command line. You can access doc text for the tool at the command line:

```
help zapit.utils.stimConfigPatternGenerator
```

This page show with plots how it works.&#x20;

#### Grid of points over V1 stimulating bilaterally

```matlab
zapit.utils.stimConfigPatternGenerator('myV1', [-2.75,-3.8], ...
                                       'num', [3,5], ...
                                       'patterns', [1,1.5], ...
                                       'bilateral',true)
```

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FtW0hrL9WRDei7ncNjimY%2Fimage.png?alt=media&amp;token=f32ef86e-929d-4a7d-b5a3-5c932615c669" alt=""><figcaption><p>Bilateral non-square grid over V1. In a single trial corresponding points on the two sides<br>will be stimulated. e.g. both points labelled "5" will be stimulated in one trial.</p></figcaption></figure>

The grids above are bilateral stimulation points. In other words, they constitute 15 different trials. All 15 points are not stimulated in a single trial. &#x20;

#### Square grid over V1 with independent stimulus conditions on the two sides

To create grids that are independent you need to generate the patterns in two steps. Note that second has `'overwrite', false` to allow the new points to be appended to the file created by the first step.&#x20;

```matlab
zapit.utils.stimConfigPatternGenerator('myV1', [-2.75,-3.8], ...
                                       'num',3, 'patterns', 1, ...
                                       'overwrite', true)
zapit.utils.stimConfigPatternGenerator('myV1', [2.75,-3.8], ...
                                       'num', 3, 'patterns', 1, ...
                                       'overwrite',false)
```

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2F2ekCCjvM5dKwJewyP3Bq%2Fimage.png?alt=media&amp;token=1e5c2592-fc7d-434f-8047-78660b24f6c5" alt=""><figcaption><p>Bilateral square grids over V1. In a single trial only one location is stimulated, unlike the bilateral<br>example above. e.g. Point "3" on the left is stimulated alone in one trial.</p></figcaption></figure>

#### Generate a variety of patterns

```matlab
zapit.utils.stimConfigPatternGenerator('myPattern', [3.55,-1.3], ...
                           'pattern','cross', 'num',3, 'patternsize',0.8, ...
                           'overwrite',true)

zapit.utils.stimConfigPatternGenerator('myPattern', [0.55,-2.5], ...
                           'pattern', 'APline', 'num',7, 'patternsize',2, ...
                           'overwrite',false, 'bilateral',true)

zapit.utils.stimConfigPatternGenerator('myPattern', [1.55,2.75], ...
                           'pattern', 'MLline', 'num',5, 'patternsize',1.5, ...
                           'overwrite',false, 'bilateral',true)

zapit.utils.stimConfigPatternGenerator('myPattern', [-3.5,0], ...
                            'pattern','cross', 'num',[3,5], 'patternsize', [0.75,1.5], ...
                            'overwrite',false)

```

<figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FCIBplOt0gDXhNqpe3vOL%2Fimage.png?alt=media&amp;token=68e249b7-3cde-4373-ae6c-0506e215c919" alt=""><figcaption><p>The two crosses are independent. The AP and ML lines each contain points that are stimulated bilaterally.</p></figcaption></figure>

#### Generating plots of the stimulus locations

You can generate plots of the stimulus locations in one of two ways.

```matlab
zapit.utils.plotStimuli('myPattern.yml')
```

Or with the `'makePlot', true` parameter/value pair as an argumnent to the stimConfigPatternGenerator. These files can also be loaded into the stim editor GUI and modified.&#x20;


# Advanced Usage

#### Handy API Commands

* Once you have calibrated the sample, you can plot the waveforms sent to scanners for, say, the 3rd stimulus: `hZP.stimConfig.plotChanSamples(3)`

#### Stimulus Config

The stimulus config editor makes YAML files with tem following layout:

```
stimLocations01:
  ML: [3.56, -3.56]
  AP: [-1.24, -1.24]
  Class: stimulate
  Type: bilateral_points
  Attributes: {laserPowerInMW: 5.0, stimDutyCycleHz: 40.0, offRampDownDuration_ms: 250.0}
stimLocations02:
  ML: [3.95, -3.95]
  AP: [-0.08, -0.08]
  Class: stimulate
  Type: bilateral_points
  Attributes: {laserPowerInMW: 5.0, stimDutyCycleHz: 40.0, offRampDownDuration_ms: 250.0}
stimLocations03:
  ML: 0.71
  AP: 0.8
  Class: stimulate
  Type: unilateral_point 
  Attributes: {laserPowerInMW: 5.0, stimDutyCycleHz: 40.0, offRampDownDuration_ms: 250.0}
```

Each `stimulusLocationsXX` section corresponds to one stimulus. The coordinates under `ML` and `AP` define the position of the beam at the one or two stimulus locations that are allowed. The `Class` field always has the value `stimulate`. This is field may be used in future for different purposes. The field `Type` currently distinguishes beetween whether the beam will cycle between two locations or stay fixed at one location but me modulated at the user-defined duty cycle.&#x20;

The `Attributes` field of each stimulus location defines how the stimuli will be presented. In the GUI it is currently possible to define only one laser power, duty cycle, and rampdown duration. The laser power and rampdown can, however, be defined on a per stimulus basis by editing the file. At present altering the duty cycle across stimulus locations is not supported.

#### Check fixed duration waveforms in simulated mode

```
>> start_zapit('simulated',true)
% * Calibrate and open a stim config *

>> hZP.sendSamples('cond',1,'stimDuration',0.25)
>> plot(hZP.DAQ.lastWaveform(:,3)) %plot the laser waveform
```

#### Hidden settings

There are some "hidden" settings that are not yet fully tested. They are not available via the GUI but can entered by editing the YML file. These are parameters that can be entered in the stimulus `Attributes` section. All are optional and can just be left out if not needed.

* `ephysWaveform` If present and set to `1` the laser waveform is filtered such that onsets and offsets are more gradual and so less likely to cause artifacts with an electrode. **This has not yet been tested in practice**!


# Introduction: Running Experiments

Integrating photostimulation into your experiments

Once you have calibrated the scanners and the sample, and loaded a set of stimulus coordinates, you are ready to present the stimuli in an experiment. At this point the GUI plays little role, as the key task is to integrate photostimulation commands into the code that runs your experiment. The Zapit ecosystem provides APIs for [MATLAB](https://zapit.swcmicroscopy.com/running-experiments/matlab) and [Python](https://zapit.swcmicroscopy.com/running-experiments/python), or you can [PControl Zapit via TCP/IP from any PC or language](https://zapit.swcmicroscopy.com/running-experiments/remote-control-and-other-programming-languages).&#x20;

#### Common Basic Concepts

No matter how you control Zapit, the overall approach will be the same. Zapit can present stimuli of either a precise fixed duration or continuously until terminated with a software command. Laser power is ramped down gently over a user-defined period on stimulus offset. Stimuli can be started either immediately on receipt of a software command or queued until a hardware trigger is received. Optionally, stimulus onset can be delayed with respect to the TTL trigger. These triggering options allow opto-stim to be delivered precisely with respect to other stimuli.

Let's assume you want the photostimulation waveforms triggered by an external hardware trigger and to continue until some event has ceased. Your pseudo-code event sequence will then be something along these lines:

```
<Trial is initiated>
<Photo-stimulus condition is selected and queued to the DAQ buffer>
...
Misc. stuff happens in the trial
...
An external device or software entity sends a 5V trigger pulse to the Zapit DAQ
<Photo-stimulus begins>
...
Some event of unknown duration occurs
...
<Photo-stimulus is stopped by a software command>
...
Trial ends 
```

The two key commands needed to achieve these goals are `sendSamples` (`send_samples` in Python) and `stopOptoStim` (`stop_opto_stim` in Python). The following sections will discuss how these commands are used in practice and discuss other relevant commands.  Please read the MATLAB docs even if you won't use MATLAB to control experiements: most of the information there is relevant to Python and TCP/IP.

#### Knowing what happens in each stimulus condition

Should you need to know what will happen in each stimulus condition you can type `hZP.stimConfig.print` into the command line to see a text summary.&#x20;

```
>> hZP.stimConfig.print

1. ML = +3.56 / AP = -1.24  <-->  ML = -3.56 / AP = -1.24  1' somatosensory barrel field
2. ML = +3.95 / AP = -0.08  <-->  ML = -3.95 / AP = -0.08  1' somatosensory nose
3. ML = +0.01 / AP = -0.91  Retrosplenial dorsal part
4. ML = +2.73 / AP = +1.66  <-->  ML = +1.88 / AP = +0.94  1' motor 
5. ML = -2.73 / AP = -2.98  <-->  ML = -2.73 / AP = -4.09  1' visual 
```

Alternatively, you can press "Plot stim coords" in the "Calibrate Sample" tab to see a plot of the same information.&#x20;

<div align="center"><figure><img src="https://3364750977-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJMuT1cmeXVpDEtDZ7qKd%2Fuploads%2FHBM1Y1z6adlktUzLWX4F%2Fplot_stim_coords_example.png?alt=media&amp;token=a857add0-3dce-48b1-901a-98f642ae5c92" alt=""><figcaption></figcaption></figure></div>

This plot is generated by a function called `zapit.utils.plotStimuli` and you can you can generate the same plot at the MATLAB command line as follows:

```
>> zapit.utils.plotStimuli(hZP.stimConfig)
```

This command also accepts file names of stimulus config files, so you can run it on any saved file on disk to visualise its contents (see `help zapit.utils.plotStimuli`).&#x20;


# MATLAB


# Basic API Usage in MATLAB

Intro running experiments in a local MATLAB session

When you start Zapit with `start_zapit` the MATLAB workspace will contain a variable called `hZP`. This serves as an API (Application Programming Interface) that allows controlling of almost all functions via the command line. For example, you can query which stimuli are loaded and whether Zapit is ready to deliver stimuli:

```matlab
% Reports "true" and is ready to present stimuli
>> hZP.isReadyToStim

ans =
  logical
   1

% The stimulus config is located here 
>> hZP.stimConfig

ans = 
  stimConfig with properties:

            configFileName: 'C:\stim_configs\uniAndBilateral_5_conditions.yml'
            laserPowerInMW: 5
      stimModulationFreqHz: 40
             stimLocations: [1×5 struct]
    offRampDownDuration_ms: 250
               chanSamples: [2500×4×5 double]
      maxStimPulseDuration: 12.2000
           blankingTime_ms: 0.3000

% The stimulus config can be queried to return the number of conditions
>> hZP.stimConfig.numConditions

ans =
     5
```

#### Presenting a stimulus

The two main commands you will need for running experiments are `sendSamples` and `stopOptoStim`. `sendSamples` is so called because it transfers stimulus waveforms to the DAQ. The following code  will send samples to the DAQ to stimulate one condition (e.g. one brain area bilaterally). It will start immediately because `hardwareTriggered` is set to `false`

```matlab
hZP.sendSamples('conditionNum', 1, 'hardwareTriggered', false);
```

Stimulation begins and continues until `stopOptoStim` is run.

```matlab
hZP.stopOptoStim
```

The `stopOptoStim` command will ramp down the laser power over a period defined in the stimulus config file. You can get help via the MATLAB command line e.g. `help hZP.sendSamples`

#### Presenting a randomly chosen stimulus

If you call `sendSamples` with the `conditionNum` undefined then a random stimulus is presented. The same stimulus will not be selected on two consecutive trials. The identity of the stimulus is returned as the first output argument of `sendSamples`

```matlab
>> stim=hZP.sendSamples('hardwareTriggered', false)

stim =
     5

>> stim=hZP.sendSamples('hardwareTriggered', false)

stim =
     3
```

A simply toy scenario sees us present a small number of stimuli at random with each having a random duration:

```matlab
numAreasToStim = length(hZP.stimConfig.stimLocations);

for ii=1:numAreasToStim
    % No stimulus condition defined so a random one chosen
    hZP.sendSamples('hardwareTriggered', false, 'verbose', true)
    pause(rand*2)
    hZP.stopOptoStim
    pause(0.3) % Because of https://github.com/Zapit-Optostim/zapit/issues/102
end
```

#### Presenting a control trial with the laser off

You can use the `laserOn` parameter to present a trial where the scanners move but the laser off:

```matlab
hZP.sendSamples('laserOn',0)
```

If the value of `laserOn` is empty then a random laser on/off state is chose. The second output argument of `sendSamples` reports this state:

```
>> [S,L]=hZP.sendSamples('laserOn',0,'hardwareTriggered', false); disp([S,L])
     3     0

>> [S,L]=hZP.sendSamples('laserOn',0,'hardwareTriggered', false); disp([S,L])
     4     0

>> [S,L]=hZP.sendSamples('laserOn',0,'hardwareTriggered', false); disp([S,L])
     2     1
```

#### Logging stimuli

In a real experiment you will want to know which stimuli were presented when. To achieve this, set an "experiment path" in Zapit, the identity of presented stimuli will be logged to a file, along with all additional relevant information such as the laser on/off state. You can either set the experiment path in the GUI or at the command line  by assigning a path to the `hZP.experimentPath` variable. If the variable is empty no logging takes place. If you run `sendSamples`with `logging` set to `false` then also no logging takes place.&#x20;

#### Precise control of stimulus timing

In the above examples stimuli started immediately because `hardwareTriggered` was always set to `false` and were terminated by `stopOptoStim`. The timing of events is therefore coarse. To present stimuli more accurately you can trigger them using a TTL line. By default you will connect port PFI0 on the Zapit NI DAQ to your trigger source. Stimulus presentation then begins when a TTL pulse is received.  The following example uses code in the `zapit\examples\externalTrigger` folder and assumes you have a second DAQ called `Dev2` with its port0/line0 connected to the Zapit PFI0 terminal

```matlab
>> auxDAQ = connectAuxDaq('Dev2'); % replace by your DAQ ID name
>> makeTTLpulse(D) % sends a TTL pulse
>> hZP.sendSamples('conditionNum', 1);

%% Nothing happens until a TTL pulse is sent

>> makeTTLpulse(D) % send a TTL pulse to start the stimulation

%% Wait a while then stop the stimulation at the command line

>> hZP.stopOptoStim
```

In the above example we tie stimulus onset to a TTL trigger. Following on from this, we can also define a fixed stimulus duration thus:

<pre class="language-matlab"><code class="lang-matlab"><strong>>> hZP.sendSamples('conditionNum', 1, 'stimDurationSeconds', 2.25);
</strong>
%% Nothing happens until a TTL pulse is sent

>> makeTTLpulse(D) % send a TTL pulse to start the stimulatio

%% A 2.25 second stimulus is presented followed by a rampdown
</code></pre>

You can also define a delay between the onset of the stimulus and the trigger:

```matlab
% Note in the following line we use abbreviated versions of the parameter 
% names and this still works.
>> hZP.sendSamples('cond', 1, 'stimDur', 2.25, 'startDelay', 0.5);

%% Nothing happens until a TTL pulse is sent

>> makeTTLpulse(D) % send a TTL pulse to start the stimulatio

%% 0.5 second delay then condition 1 is presented for  2.25 seconds then a rampdown
```

{% hint style="info" %}
If stimulus duration is known in advance, it is preferable to use the `stimDurationSeconds` input argument to the `sendSamples`method rather than a `pause` statement. The former is more accurate and has fewer failure points.&#x20;
{% endhint %}


# Running an Experiment in MATLAB

Using the Zapit API in MATLAB

The following example function presents 20 random stimuli using software timing.

```matlab
function myStimPresenter
    
    % Get the API object from the base workspace
    hZP = zapit.utils.getObject;
    if isempty(hZP)
        return
    end

    if hZP.isReadyToStim == false
        fprintf('Zapit is not ready to stimulate.\n')
        return
    end

    % Present 20 random stimuli without waiting for a hardware trigger
    for ii = 1:20
        hZP.sendSamples('hardwareTriggered',false) % Starts right away
        pause(1) % Wait approx 1s 
        hZP.stopOptoStim
        pause(0.3) % Because of https://github.com/Zapit-Optostim/zapit/issues/102
    end

end
```

The following function presents 20 random stimuli using an external hardware trigger:

```matlab
function myStimPresenter
    
    % Get the API object from the base workspace
    hZP = zapit.utils.getObject;
    if isempty(hZP)
        return
    end

    if hZP.isReadyToStim == false
        fprintf('Zapit is not ready to stimulate.\n')
        return
    end

    % Present 20 random 1 second stimuli without waiting for a hardware trigger
    for ii = 1:20
        hZP.sendSamples('hardwareTriggered',true,'stimDurationSeconds',1)
    end
end
```

{% hint style="warning" %}
Note the 0.3 seconds pause after the `stopOptoStim in the first example`. [This is to take into account ](https://github.com/Zapit-Optostim/zapit/issues/102)the laser power ramp-down time which is triggered by stopOptoStim. The system will **not** respond to an external trigger during this period in hardware triggered mode. The pause is almost certainly only needed during demo code. In reality it is unlikely one trial will follow the previous one with a latency of <300 ms. Add a timeout to your behavior code to avoid this should it be a possibility.&#x20;
{% endhint %}


# Python


# Connecting Python to Zapit

Installation and basic use of the Zapit Python bridge

Zapit's [Python Bridge](https://github.com/Zapit-Optostim/zapit-Python-Bridge) uses the [MATLAB Engine](https://uk.mathworks.com/help/matlab/matlab-engine-for-python.html) to call Zapit from Python.  The MATLAB GUI is used for calibrating the scanners and the sample. After this point all subsequent operations for which you might have used the MATLAB API can be done in Python. Zapit must remain running in MATLAB throughout. &#x20;

#### Setting up

1. Close Zapit if open.&#x20;
2. Edit your `zapitSystemSettings.yml` file, setting `general.openPythonBridgeOnStart` to `1`.
3. Restart Zapit. You should see the message "Opened Python Bridge" at the command line.

Now install the Python Bridge:

```
pip install zapit-Python-Bridge
```

#### Test the bridge

Open a stim config file in Zapit and open an ipython session. Test the connection by querying the number of stimulus conditions in the loaded stimulus config file.

<pre class="language-python"><code class="lang-python"><strong>import zapit_python_bridge.bridge as zpb
</strong>hZP = zpb.bridge()
hZP.num_stim_cond()
</code></pre>

&#x20;


# Basic Zapit API Use in Python

Make sure you are first familiar with [Basic API Usage in MATLAB](https://zapit.swcmicroscopy.com/running-experiments/matlab/basic-api-usage-in-matlab).

The following code presents 10 random trials using Zapit's Python bridge.

```python
import zapit_python_bridge.bridge as zpb
from time import sleep

# Create an instance of the bridge object
hZP = zpb.bridge()
num_cond = hZP.num_stim_cond()

numTrials = 10
currentTrial = 1

while currentTrial <= numTrials:
    # Send stimuli and do not log because this an example.
    # In a real experiment you likely want to enable both logging
    # and hardware triggering.
    print("Presenting stimulus %d/%d" % (currentTrial, numTrials))
    hZP.send_samples(conditionNum=-1, hardwareTriggered=False, logging=False)

    sleep(1)

    hZP.stop_opto_stim()
    currentTrial += 1

hZP.release_matlab()

```


# Remote Control and Other Programming Languages

Running Zapit stimuli in other programming languages or from a different PC

You can control Zapit from a different PC on the same network or from any programming language of your choice using the TCP/IP server. Make sure you are first familiar with [Basic API Usage in MATLAB](https://zapit.swcmicroscopy.com/running-experiments/matlab/basic-api-usage-in-matlab).

### Controlling Zapit via TCP/IP

The easiest way to control Zapit externally is to use its built-in TCP/IP server. With this approach you can control a running Zapit instance from a different MATLAB instance on the same PC, a different programming language on the same PC, or from a different PC on the same network. You simply need to install  the [Zapit TCP Bridge](https://github.com/Zapit-Optostim/zapit-tcp-bridge) on the client machine and correctly configure the Zapit YML settings file.&#x20;

#### Configuring the YML file

Open the YML settings file and ensure `tcpServer` `enable` setting in the `yml` file set to `true`. If you will be controlling Zapit from an external PC, you must also set the `IP` value in the settings file to the IP address on the PC which runs Zapit.&#x20;

* Find the IP address of the Zapit (server) PC with `zapit.interfaces.getIPaddress`
* Enter this into the TCP server `IP` variable in the `yml` settings file.

Now save the YML file and re-start Zapit.&#x20;

#### Connecting to Zapit using the TCP/IP client

Clone the [Zapit TCP Bridge](https://github.com/Zapit-Optostim/zapit-tcp-bridge) repo on your client PC. Go over the main README. At the time of writing the MATLAB client is the most mature, but there are also functional clients for Python and Bonsai. Read the examples for your desired client to get started. A brief example MATLAB session is shown below to give a flavour of what is possible.&#x20;

```matlab
% Start the client on a remote PC, specifying the IP address of the Zapit server
client = zapit_tcp_bridge.TCPclient('ip','122.14.143.200');
client.connect;
 
% present the last stimulus condition for a short period using software timing
nCond = client.getNumConditions;
client.sendSamples('conditionNumber',nCond, 'hardwareTriggered', false);
pause(3)
client.stopOptoStim;
 
% Disconnect
delete(client)
```

#### Precise timing over TCP/IP

Precise stimulus timing is the same over TCP/IP as it is for local control of Zapit. The client PC will have DAQ that has a TTL line connected to PFI0 on the server (Zapit) PC. The following can then be used to present a randomly chosen 1 second stimulus that is triggered by the TTL line.

```matlab
client.sendSamples('stimDur',1)
```

The stimulus rampdown begins after one second. If you set up an experiment path on the server, then stimulus identities are logged.&#x20;

### Rolling your own stimulus presentation code

The most low-level way to present stimuli in a language of your choice is to use the Zapit GUI for calibration but present the waveforms it produces using hardware and a language of your choice. It seems unlikely this option would be necessary, but the procedure for achieving it is outlined briefly below. &#x20;

The Zapit GUI is used to make stimulus configurations and then calibrate the hardware so these can be presented in stereotaxic coordinates. All that is finally needed for this to happen is a small body of waveforms corresponding to each stimulus condition. The Zapit MATLAB API presents these waveforms and can be integrated into MATLAB code (or Python code [via a wrapper](https://zapit.swcmicroscopy.com/running-experiments/python/connecting-python-to-zapit)). Not much work is needed to present these same waveforms in a different language. The example class in [minimalWaveformPresentation](https://github.com/Zapit-Optostim/zapit/tree/main/examples/minimalWaveformPresentation) demonstrates how to use the waveforms and stripped-down MATLAB code achieve this. There is substantial documentation. To use this above code:

* Start Zapit and calibrate as normal. Load your desired stimulus set.&#x20;
* Then export the waveforms using the Export Waveforms button in the Sample Calibration tab, or at the CLI with the method `zapit.stimConfig.writeWaveformsToDisk`. See `help zapit.stimConfig.writeWaveformsToDisk`. You can run the command with `hZP.stimConfig.writeWaveformsToDisk`.

The above should be enough information to get you started. But briefly, all you need to implement is code to:

* Present the waveforms continuously using DAQmx at the correct sample rate.
* Stop the waveforms with the gentle ramp-down. The ramp-down is generated in code and is not saved with the waveforms.&#x20;
* Log the identity of the presented stimuli.&#x20;


# Project Structure

This page describes how the code is laid out and also provides links to concepts as needed.&#x20;

### Overall Layout

* Code is laid out in [packages ](https://uk.mathworks.com/help/matlab/matlab_oop/scoping-classes-with-packages.html)(the directories starting with a `+` denote a package in MATLAB).
* The bulk of the code is in [classes](https://uk.mathworks.com/help/matlab/matlab_oop/create-a-simple-class.html): it is [object-oriented](https://uk.mathworks.com/products/matlab/object-oriented-programming.html).
* [start\_zapit ](https://github.com/Zapit-Optostim/zapit/blob/main/zapit/start_zapit.m)is used to neatly start up the GUI in a user-friendly way.&#x20;
* The main gui is structured in a similar way to a [model/view/controller](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) layout:
  * The "model", [zapit.pointer](https://github.com/Zapit-Optostim/zapit/tree/main/zapit/%2Bzapit/%40pointer), handles the underlying logic and is independent of the GUI as possible. This class is sometimes referred to at the [API ](https://en.wikipedia.org/wiki/API)in the documentation, is it is the interface used to integrate the photostimulation into custom behavior code.&#x20;
  * The "view", [zapit.gui.main.view](https://github.com/Zapit-Optostim/zapit/blob/main/zapit/%2Bzapit/%2Bgui/%2Bmain/view.m), builds the UI elements of the GUI itself and contains no logic. It was built using [AppDesigner ](https://uk.mathworks.com/products/matlab/app-designer.html)and must never be edited by hand.&#x20;
  * The "controller", [zapit.gui.main.controller](https://github.com/Zapit-Optostim/zapit/tree/main/zapit/%2Bzapit/%2Bgui/%2Bmain/%40controller), is a class that [inherits ](https://uk.mathworks.com/help/simscape/lang/subclassing-and-inheritance.html)`zapit.gui.main.view` and so when it is instantiated (i.e. created at the command line or in `start_zapit`) the GUI appears. The `controller` class is what provides the logic to make the GUI run: it defines [callback functions](https://uk.mathworks.com/help/matlab/creating_plots/create-callbacks-for-graphics-objects.html), [listeners](https://uk.mathworks.com/help/matlab/matlab_oop/learning-to-use-events-and-listeners.html), etc. The `controller` is a composite class, since it has a `model` [property](https://uk.mathworks.com/help/matlab/properties-storing-data-and-state.html) that contains an instance of `zapit.pointer` this enables the `controller` to interact with the model. For example, to initiate the galvo calibration routine or to present stimuli.
* The class[ zapit.pointer](https://github.com/Zapit-Optostim/zapit/tree/main/zapit/%2Bzapit/%40pointer) implements the bulk of the logic and does the heavy lifting.&#x20;

### Concepts

* In most classes contain some[ observable properties](https://uk.mathworks.com/help/matlab/matlab_oop/class-to-observe-property-changes.html), meaning that changes to the values of those properties will drive a [callback function](https://uk.mathworks.com/help/matlab/creating_plots/create-callbacks-for-graphics-objects.html) to run via a [listener](https://uk.mathworks.com/help/matlab/matlab_oop/learning-to-use-events-and-listeners.html). For example, the `experimentPath` property in [zapit.pointer](https://github.com/Zapit-Optostim/zapit/tree/main/zapit/%2Bzapit/%40pointer) is observable. The [buildListeners ](https://github.com/Zapit-Optostim/zapit/blob/main/zapit/%2Bzapit/%2Bgui/%2Bmain/%40controller/buildListeners.m)method in [zapit.gui.main.controller](https://github.com/Zapit-Optostim/zapit/tree/main/zapit/%2Bzapit/%2Bgui/%2Bmain/%40controller) creates a listener that watches for changes the experiment path property. These can be made via the GUI or at the command line (`hZP.experimentPath='\some\path'`). When changes are made, the `updateExperimentPathTextArea` method of `zapit.gui.main.controller` is run to update the text of the path in a text area box found in the GUI Calibrate Scanners tab.&#x20;


# Conventions

#### Function/method code layout

Functions and methods should be laid out as follows

```matlab
function chanString = functionName(arguments)
    % What it does summarized in one line
    %
    % function zapit.DAQ.functionName(arguments)
    %
    % Purpose
    % What it does in more detail
    %   
    % Inputs
    % input1 - what it is.
    %
    % Outputs
    % output1- what it is 
    %
    % Examples
    % [This section is optional. If the function or method is likely to be
    %  used by an end-user then it is recommended to include some examples]
    %
    % 
    
end % functionName
```

#### Style Conventions

* Two spaces between methods in a class file.
* Comment block endings if they are large. e.g. `end % methods` at the end of methods blocks in a class file, as you typically can not see the `methods` at the start of the block at the same time as the `end`.&#x20;
* Try to keep class files below about 500 lines.&#x20;
* Short methods can remain in the main class file.&#x20;
* Longer methods should be in their own files.
* For consistency it is preferred to use a `@className` folder for all concrete classes even if there is only one `.m` file in it. Short abstract classes can be left bare if desired to distinguish them from concrete classes.
* Unless there is an exceptional reason, all functions should be in a module sub-directory for neatness.
* Max line length is 100 characters but you can break this rule occasionally if that makes sense. It is better to sometimes have an exceptionally long line than to break up that line in an ugly and hard to read way.&#x20;
* Where possible follow the [mlinter ](https://uk.mathworks.com/help/matlab/ref/mlint.html)suggestions, but if doing so will make things ugly then feel free to ignore them.&#x20;

#### Format Guidelines

* Save files with Unix line endings. Sometimes these get switched to Windows endings by git. You can tell this has occurred because the Git client will show that all lines in a file are modified. Please do not commit these files: convert back to Unix line endings and commit. There is a Linux shell script in the project root folder that does this for the whole project, or use a text editor like [Sublime Text](https://www.sublimetext.com/), which [makes it easy to change the line endings](https://superuser.com/questions/1217622/how-can-i-remove-the-m-from-my-file-in-sublime-text-3#:~:text=To%20change%20it%20through%20the,Select%20desired%20line%20ending%20type.). The best solution is to [set up Git to not mess with your line endings](https://troyready.com/blog/git-windows-dont-convert-line-endings.html).
* Ident size should be 4 spaces (i.e. two indents should be 8 spaces). Do not use tabs. These are the settings used by default in the MATLAB editor.


# Hints and Tips

#### Simulated mode

There is a simulated mode for working on the project with no camera or DAQ hardware. On a Windows PC start it with:

```
start_zapit('simulated',true)
```

On Mac or Linux you can omit the argument and `start_zapit` will open the GUI in simulated mode.&#x20;

Simulated mode does just enough to make many development tasks possible but it does not simulate everything. For example, the scanner calibration is not simulated and is simply indicated as being calibrated. The sample calibration procedure works. You can also run `hZP.applyUnityStereotaxicCalib` if you wish to apply a 1:1 calibration without going through the operations in the GUI.&#x20;

#### Running with a simulated DAQ

You can also run Zapit with a simulated NI DAQ but a real camera. To do this, [create a suitable simulated DAQ in NI MAX](https://knowledge.ni.com/KnowledgeArticleDetails?id=kA03q000000x0PxCAI\&l=en-US) such as a USB-6363. Then edit the settings YAML to use this as the device ID. Connect your camera and start Zapit. You should now define the "scanners" as being calibrated with `hZP.scannersCalibrated=true;` You may either run `hZP.applyUnityStereotaxicCalib` to do the stereotaxic calibration or run through the actualy procedure. You can now load stimulus sets and run experiments. Of course, nothing is actually generated but you can do more testing than with the regular simulated mode described above.&#x20;

#### Waveform Debugging

With a calibrated system and loaded stim config you can plot the waveforms which will be sent to the DAQ using:&#x20;

```matlab
hZP.stimConfig.plotChanSamples %plot first stimulus
hZP.stimConfig.plotChanSamples(1) %plot first stimulus
hZP.stimConfig.plotChanSamples(4) %plot fourth stimulus
```

You can see what is being presented with `hZP.stimConfig.print` e.g.

```
>> hZP.stimConfig.print

1. ML = +3.56 / AP = -1.24  <-->  ML = -3.56 / AP = -1.24  1' somatosensory barrel field
2. ML = +3.95 / AP = -0.08  <-->  ML = -3.95 / AP = -0.08  1' somatosensory nose
3. ML = +0.71 / AP = +0.80  2' motor 
4. ML = +2.73 / AP = +1.66  <-->  ML = +1.88 / AP = +0.94  1' motor 
5. ML = -2.73 / AP = -2.98  <-->  ML = -2.73 / AP = -4.09  1' visual 
```

The full stimulus data are in the `stimLocations` property:

```
>> hZP.stimConfig.stimLocations

ans = 

  1×5 struct array with fields:

    ML
    AP
    Class
    Type
    Attributes
```


