Beauchamp: BuffyElectrodeNotes

From OpenWetWare
Jump to navigationJump to search
Brain picture
Beauchamp Lab




To search for things on the wiki, use Google's site search feature. For instance, to find an Experiment Sheet, type

 site:openwetware.org/wiki/Beauchamp ExperimentSheet

What is iELVis?

iELVis stands for Intracranial Electrode Visualizer. We use the iELVis software package to visualize electrode locations in our research patients along with a number of other programs. iELVis is not a self-contained program but runs in a combination of BASH script, BioImage Suite, and MATLAB and can be downloaded from GitHub at:

https://github.com/iELVis/iELVis 

Setting up iELVis

General Notes

Setting up and using iELVis requires a little bit of knowledge about general programming in a UNIX-type system and in an advanced language like MATLAB. For iELVis to work properly, multiple programs need to be able to access each other and work in harmony which may require a little bit of troubleshooting depending on the setup of your individual system. This document contains the information needed to run iELVis on a BCM beauchamplab computer, but another system may require different commands or even different programs. Currently, iELVis is only developed for MacOS. While it may be able to run on Linux, it is not developed for Windows systems. Sections marked in brackets are variable by computer, like the installation folders of certain programs or patient codes. The correct input will depend on your system and the process you're trying to run.

Prerequisites

FreeSurfer and FSL

FreeSurfer is a software package for analyzing and visualizing neuroimaging data. Install the program according to instructions at the FreeSurfer wiki:

http://freesurfer.net/fswiki/DownloadAndInstall 

Installing FreeSurfer should also set up FSL, its viewing program, but if it doesn't install automatically, FSL can be downloaded and installed separately at:

https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FslInstallation

BioImage Suite

BioImage Suite is a software package for visualization of bioimaging data, mainly developed for abdominal/cardiac imaging and neuroimaging. Currently, the version we use is BioImage Suite 35; a web version is available but is set up differently from our preferred version. The required version of this software is stored in the BCM ECoG server and can be installed using terminal commands:

cd /Volumes/ecog/Foster_Lab/CODE/Toolboxes/Bioimagesuite_35
sudo sh ./bioimagesuite-35_0b1_06_Apr_2017-MacOS-c++-x86_64.sh -prefix= ~/

MATLAB

MATLAB is a statistical analysis program that requires a license to use. BCM has campus-wide licenses for students and faculty that provides access to the latest versions of MATLAB though iELVis can be run on any a/b version from 2016 or later. Downloads and licensing information can be found at:

https://www.mathworks.com/products/matlab.html

Dcm2niix in MRIcroGL

Dcm2niix is a file converter program that converts CT and MRI data stored in .dcm files to NIfTI (read: nifty) .nii format which is readable by FreeSurfer and other viewing programs. MRIcroGL is a neuroimaging viewing program that contains the latest version of dcm2niix as well as a number of image editing options for CT and MRI data. There are other programs contain the updated dcm2niix and can be used instead, but MRIcroGL not only provides the file converter but a useful platform for viewing 3D reconstructions. Avoid the older version dcm2nii; it is no longer supported. Download and install MRIcroGL according to the instructions here:

https://www.nitrc.org/plugins/mwiki/index.php/dcm2nii:MainPage

BASH

BASH commands are UNIX-type commands used in the MacOS terminal window. BASH uses profiles which can be saved with file pathways and setup commands that will run upon opening that profile. We generally recommend .bashrc, .profile, or .bash profiles and this document will refer to first as the default. While .tcsh can be used, be aware that the syntax it uses is slightly different. To access a profile, enter the terminal and enter:

nano ~/.bashrc 

You may need to use sudo nano ~/.bashrc if admin permission is required, in which case you will need a password. iELVis requires that all necessary files be on the same pathway and that that pathway can be accessed by BASH, MATLAB, and BioImage Suite alike. Entering these lines in .bashrc will allow these programs to setup the correct pathway. These lines should be marked by a comment line (to write a comment in BASH, enter an octothorpe (#) followed by your text) to denote what pathways they're setting up.

#SETUP iELVis Freesurfer
export FREESURFER_HOME=/[location of freesurfer folder]
source $FREESURFER_HOME/SetUpFreeSurfer.sh
#SETUP iELVis BASH
export PATH=$ PATH: [location of iELVis folder]/iELVis_master/iELVis_MAIN/iELVis_BASH/
export PATH=$PATH: [location of iELVis folder]/iELVis_master/iELVis_MAIN/iELVis_MATLAB/

Starting Electrode Localization

Surface Reconstruction (aka The Long Step)

The first step of electrode localization is to reconstruct a 3D image of the patient's brain from their pre-operative MRI. This step will create a number of files in whatever location you've selected as the target that will be used not just by the next steps but all parts of iELVis. Be aware that this step takes a long time--as long as 24 hours on a slow computer, even longer if there are errors!--though the CT alignment (see next section) can be run in the early stages of this process, once the T1.mgz file has been created in the subject's "surf" folder. Open terminal and enter the target folder to begin.

cd /[target folder]/
export SUBJECTS_DIR=/[target folder]/
recon-all -s [subject ID] -i [subject's MRI].nii -all -localGI

CT alignment

Converting .dcm to .nii

Before visualizations can start, the CT and MRI scans need to be in .nii or .nii.gz format. Most CT and MRI scans are developed as .dcm (read: DICOM) images, one for each slice, and need to be compiled by a conversion program like dcm2niix.

In our lab, we work with patients receiving care at St. Luke's Episcopal; the hospital stores patient scans on disc in the Film Library on floor B1. To get the scans you'll need the patient's full name, the name of the primary surgeon, and your ID badge. It can take a day or so for the Film Library to get the scans, so be prepared by calling ahead at *** and asking for the pre-operative MRI and the most recent post-operative CT scan. If you have the disc, be sure to copy the files into a designated folder in the subject's name on the beauchamplab and/or ecog servers.

If using MRIcroGL, open the software, select "Import" from top right menu, and select "Convert DICOM to NIFTI". This will open a new window. In this window, select "Edit" from the top right menu. In the popup window, find the folder containing the MRI or CT .dcm files and select "Open." Dcm2niix should automatically convert the files into a .nii.gz file which can be unzipped to get the .nii file. It will also create a .json file of the scan. The program may make multiple .nii.gz files for each set of .dcm files. Generally, only one of them is the complete MRI/CT and the others are partial sections or single slices. These will not be used by iELVis, so be sure to rename the complete MRI/CT  to something recognizable or delete the unneeded files (for more information, see Troubleshooting).

Coregistering the CT and MRI

iELVis uses a function called ct2mri.sh to coregister the CT and MRI that is based on FreeSurfer's flirt command. To run iELVis's coregistration, enter the commands below:

cd /[folder_location]/
export SUBJECTS_DIR=/[target_folder]/
ct2mri.sh [target folder name] subID_CT.nii 

This step can be done while the recon-all step is still running as long as the T1.mgz file has been created (found in the subject's "surf" folder). The file will be saved as ct2ti.nii.gz in the target folder and two .gif files will pop up showing the coregistration. Check the alignment of the CT and MRI in these files. If they're misaligned, the ctINti.nii.gz is also misaligned and the file won't be useful the next steps.

The ct2mri.sh command will also create the elec_recon folder in the subject's folder that iELVis will use to store a number of files with the patient's electrode localization info, including electrode coordinates and labels, and later steps will use this folder as both storage and an access point for those information files. However, if you'd like to perform a coregistration of two .nii images without setting up the elec_recon folder, you can run FreeSurfer's flirt command on its own as follows:

flirt -in [subID_CT].nii -ref [subID_t1].nii -out [output file name].nii -omat ct2t1.mat -interp trilinear -cost mutualinfo -dof 6 -searchcost mutualinfo -searchrx -180 180 -searchry -180 180 -searchrz -180 180 

These are the parameters used by ct2mri.sh during its call to flirt but they can be adjusted as needed; the general flirt command can also be used to coregister multiple MRIs or CTs based on the input and reference file. Similarly, the degrees of freedom can be adjusted from 6 and the angle range from -180 to 180 as desired. A less strict coregistration for problematic alignments can be done by increasing the degrees of freedom to 12 and decreasing the angle range from -90 to 90.

Electrode Localization

Patient Files and iELVis Naming

Before you begin the actual localization process, you'll some information about the patient to correctly identify the electrodes in their scans. At a minimum you'll need the patient's montage file listing the inserted electrodes and the aligned CT to MRI from the previous step. If surgical files, implant drawings, electrode diagrams, intra-operative photographs, or any other information is available it should be gathered and used for the next steps to ensure the localization is correct.

At BCM, we keep patient files with the surgical diagrams, CT/MRI discs, clinical and research montages, and other data in folders under lock in room S 104 F. Contact Dr. Brett Foster and/or Dr. Bill Boskings for access. Much of the information in these folders is also available on the beauchamplab and ecog servers with identifying information removed. We use both AdTech and PMT brand electrodes for our electrocorticography experiments. Diagrams of the electrodes these companies produce are available at their websites:

AdTech: https://adtechmedical.com/
PMT: http://www.pmtcorp.com/index.html

iELVis refers to all electrodes, be they grid, strip, or depth, as "grids" and each individual electrode channel as a "contact"; the rest of this section will do the same. iELVis uses a naming system that gives each grid a unique name as well as a tag identifying its location on the left or right hemisphere and whether the model grid is a grid, strip, or depth electrode. This is written as an "L" or "R" for left/right, a "G", "S", or "D" for grid/strip/depth, an underscore, and the electrode name from the patient's montage (e.g., LG_Grid, RS_PTO, LD_LIns). Each grid must have a unique name not including the LS/RD tag-- i.e., if there are two grids with the same name on each hemisphere, their names should include the left/right designation, not just the tag (e.g., for two amygdalal probes, use LS_LAMY and RS_RAMY, not LS_AMY and RS_AMY)-- two grids with the same name will cause errors later in MATLAB when trying to plot these electrodes.

BioImageSuite Settings

The actual localization process is done in BioImage Suite. The version we use is launched through the terminal with the command:

start_bioimagesuite

The BioImage Suite menu should appear with a left-hand column of menus and options within each appearing in the larger right column. Electrode identification and placement is done through the Electrode Editor, accessed from the "Editors" menu to the left, and launches in two windows called the Electrode Editor and the Electrode Control windows. The Electrode Editor window will display the subject's aligned ct2t1.nii.gz and the right will be used to create the patient's .mgrid file containing the names and locations of the electrodes.

First, load the subject's ctINt1.nii.gz into the Electrode Editor window. Go to "File" then "Load" and use the directory to select the correct file. There are a number of views in which BioImage Suite can display this 3D image, accessible from the right-hand menu "General View" and the options menus below it. To view a rotatable, black-and-white 3D image of the skull and electrodes, set the "General View" to "3D only" and the "View Options" below it to "Volume." You can remove the green orientation box around the image by selecting "Orientation Options" and setting that menu to "None." This will display the electrode contacts as small white dots in the thin grey-white skull as well as the white teeth and any wires in the CT scan as grey-white lines. Click and drag the image to rotate it and click "Reset" at the bottom of the left menu to return the image to its original orientation. Hitting "Reset" will only reset the image's position; it will not erase any electrode data.

In some cases, especially with depth electrodes, it may be more useful to view the electrodes in sagittal, coronal, and axial views aligned side-by-side; to do this, set the "General View" to "Simple Mode" and the "View Options" to "3-Slice Mode." The background will be displayed in cyan and electrodes and bones in bright red. To navigate this 2D image, click and drag the crossbar through one view to adjust the displayed slices in the others.

For any view, the image will need to be processed to adjust the contrast and make the electrodes more visible. Using the top menu, select "Image Processing" and then "Threshold" to open the Image Threshold window. Most patients in 3D view have a high threshold of about 3000 and a low threshold of about -1000 though these numbers, especially the former, can vary greatly by scan. Adjusting the low threshold to about 1000 will reveal the electrodes and the surrounding skull; adjusting it to about 2000 will show only the electrodes, wires, and teeth. It's worth playing with these settings a little when first loading a patient into BioImage Suite to get the clearest view possible. You can adjust these settings at any time from the Image Threshold window to make individual contacts more visible.

Settings must also be adjusted in the Electrode Control window. At the top menu, select "Edit" and then "Full Edit Mode" to remove the Read-Only restriction. Only one electrode strip/grid will be shown at a time in the Electrode Editor window unless "Display All" is selected from the "Display" menu. If loading a patient with a pre-existing .mgrid file, load that file by selecting "File" then "Load" from the upper left menu and using the directory. This window has two tabs, Patient Info and Electrode Info. The first will display a list of electrode strips, grids, or depth electrodes by name; the second allows you to edit the information and contact placement of the selected electrode.

Electrode Selection

To begin electrode selection, select a grid from the Grid Information box of the Patient Info tab or click "Add New Grid" to the right to add another grid to the list. With the grid selected, enter the Electrode Info tab. This tab is divided into three boxes, "Grid Properties" to the upper left, "Electrode Arrangement" to the lower left, and "Electrode Properties" to the right. In the Grid Properties box, enter a name for the grid that matches the patient's montage and includes the LS/RD tag. Below that, enter the dimensions of the grid with the smaller number first (i.e., 4x8, not 8x4) and click "Update Grid." A dialog box may pop up warning that changing the grid dimensions will erase all placement information and asking to confirm this choice; all this means is that changing the grid dimensions will remove any placed contacts. Hit "yes" to save the changes. You can also change the color of the grid in the "Grid" menu at the top by dragging the arrows beneath the Red, Green, and Blue sliders or entering a value between 0 and 255 into the boxes for each bar. This is useful for creating contrast between multiple grids and between grids and a colored brain image.

Now you can align the model grid with the electrodes on the patient's scan. Under Electrode Properties there is a small box labeled "Editing" and a checkbox labeled "Button Pick." Check this box and then select a contact from the grid in the Electrode Arrangement box. Notice that, once a contact is selected, the upper section of the Electrode Properties menu will fill in with the number of that contact out of the total number of contacts on the grid, coordinates of that contact, and its distance to its neighbors in the grid. With that contact selected, Shift+click the corresponding contact in the Electrode Editor window. The grid contact should snap to the center of the shape. If it snaps incorrectly, click away from and back to the contact in the Electrode Arrangement box and Shift+click the desired place again, or adjust the Image Threshold settings and try again. You can also manually adjust the coordinates of the contact by altering the X, Y, and Z coordinates in the Electrode Properties box. Click the next contact in the Electrode Arrangement grid and repeat until the entire grid has been placed. Do this with all the grids listed in the patient's montage.

When localization is complete, save the .mgrid file in the target folder from the Electrode Control window and name the file [subID].mgrid so that it can be found later by MATLAB scripts expecting this name. Remember that saving the ctINt1.nii.gz will NOT save the information in the Electrode Control window; the .mgrid file needs to be saved separately.

Electrode Projection and Visualization

The iELVis projection and visualization steps are run in MATLAB. While the basic projection steps only require single commands, for more advanced analysis and plotting some scripting may be required.

Basic Projection

Open MATLAB and globalize the subject's iELVis folder to set the patient's directory:

globalFsDir = '/Location of iELVis localization folder/'
global globalFsDir 

The next script creates eight files--seven will be named [subID] with the extensions: .electrodeNames, .INF, .LEPTO, .LEPTOVOX, .PIAL, .PIALVOX, .POSTIMPLANT and the last will be [subID]PostimpLoc.txt--based on the BioImage Suite localization .mgrid file. If the .mgrid file has been edited since the last projection, this step will need to be run again to overwrite these files with the updated information. All of these files can be found in the subject's elec_recon folder.

makeIniLocTxtFile('subject ID')

Projection and Brainshift Methods

There are two methods of electrode projection built into iELVis, the Dykstra et al. method and the Yang, Wang et al. method, that correct for brain shift. Both will project the post-operative electrode locations to the pre-operative brain surface. To launch the Dykstra et al. method, enter:

dykstraElecPjct('subject ID')

The Dykstra et al. method projects each electrode to a smoothed pial surface (functionally a dural surface) before projecting to the regular pial surface to maintain the original distance between each contact and its nearest neighbors. When running this command, a figure will appear showing the optimization process of the function followed by the shift distribution of the electrodes on the subject's brain. To launch the Yang, Wang et al. method, enter:

yangWangElecPjct('subject ID') 

If there is an electrode tagged as a grid, the command window will prompt for its dimensions and orientation. Enter the smaller dimension first (i.e., 4x8, not 8x4) and enter the order of the grid's corners as specified. If there are multiple grids, the function will require the dimensions and orientations of each. This method projects strips to the nearest point on the dural surface and projects grids to the dural surface by inverse gnomic projection. This should produce two figures. The first will have on the right a plot of Euclidean differences between each grid contact and its neighbors and on the left the standard deviation of contact distances. This function includes a number of tested parameters to produce the lowest difference in known distance between contacts and the lowest standard deviation of those differences. If none of those parameters work (which may indicate an error in electrode placement or grid orientation), it will prompt the user to elect the best parameter by selecting the contact from its displayed list with the lowest standard deviation. The second and figures it will produce are the shift distribution maps.

After running either projection function, display-ready images of the electrodes on the subject's brain can be generated by running:

plotMgridOnPial('subject ID', 1)

Advanced Projection

Converting Coordinates between iELVis and AFNI/SUMA

iELVis does not display brains in the same orientation space as AFNI/SUMA, so to view brains in the latter (or in any program that uses the same orientation) the coordinates must be converted into that space. In addition, the iELVis outputs, especially for grids, may not be in the same order as the patient's montage; in particular, iELVis will list grid contacts by column, not numerical order. To counter this we use the function afni2elvis.m, found on both the beauchamplab and ecog servers.

[output_coords] = afni2elvis(input_coords, subject, varagin)

There is a reverse option as well to convert AFNI/SUMA coordinates into iELVis space.

Mapping Electrodes to Average Brains

The iELVis wiki has detailed instructions on plotting electrodes on an average brain in MATLAB here:

http://ielvis.pbworks.com/w/page/117733770/Mapping%20Electrode%20Locations%20to%20Average%20Brains

Built into iELVis is the command sub2AvgBrain (see above for details) that will take the electrode names and coordinates stored in a patient's [subID].PIAL file and plot them on the fsaverage brain. We have a slight variation on this command named sub2SubBrain that will also output a patient's coordinates in their original (untransformed) space instead of the fsaverage space and can plot them on their own brain.

Troubleshooting

General Troubleshooting

Missing Files/Commands

This is perhaps the most common problem in setting up and running iELVis. The required files may exist in multiple places, on a local machine, on one or both servers, or as part of a program; it can be difficult to get all the required components of iELVis to work harmoniously. First, search for the file name in your computer and the servers. If it appears, check that the folder it's in has been added to the pathways in BASH and MATLAB. If it doesn't, check the name of the file itself to make sure that it's been named correctly (this often occurs when iELVis is searching for a file with a specific name format, such as subID.mgrid, and the file has not been named according to its expected structure). Sometimes commands and files are missing when a program isn't installed correctly; if this is the case, download and re-install the program.

CT/MRI Alignment Errors

No MRI or CT DICOM files

If the individual .dcm images are not available for a subject, it may be possible to recreate them using .BRIK and .HEAD files if the subject has previously been processed in AFNI/SUMA. Check the beauchamplab server for the FreeSurfer folder (generally labeled "fs") in the subject's directory. If there is a SUMA folder therein, check to see if it has .BRIK and .HEAD files. Open terminal and enter:

cd /location of .BRIK and .HEAD files/
3dAFNItoNIFTI [file_name]+orig.HEAD -prefix [subID CT/MRI].nii

Open the resulting file in your viewing program of choice to check quality.

Permission Denied

If you forget to enter the SUBJECTS_DIR=[target folder] line, you might get this error.

No Brainmask

If an error appears that the ct2mri.sh command cannot find the subject's brainmask.nii.gz, it's likely that you're trying to run the command a little too early into the recon-all process (or, if recon-all has completed, that there was an error). The command will still work as long as the T1.mgz file has been created; the ct2mri.sh command only copies the brainmask.nii.gz into the elec_recon folder. That being said, check to see that the brainmask was, in fact, created by the recon-all step and is saved in the patient's ** folder. If not, recon-all may need to be rerun.

Image Exception #63/22

Generally, this means that the ct2mri.sh command can't find the T1.mgz file created by recon-all. The T1.mgz can be found in the subject's freesurfer "fs" folder, in the "mri" subfolder. If the file does not exist, recon-all may have encountered an error and should be run again. If you don't want to overwrite the information, enter a new name for the target folder or move/delete the folder from the original recon-all. If still encountering this error, take the T1.nii.gz file and copy it to the elec_recon folder. Make sure to use the most updated form of dcm2niix to create this and be sure that the T1 is in .nii.gz format, not just .nii.

Misalignment

Misalignment is usually very visible in the .gif files created by ct2mri.sh. One of the easiest ways to tell if the coregistration is correct is to look at the eyes and nose of the patient in the .gif files. If they're crooked, incomplete, or not in the same orientation, the ctINt1.nii.gz is also misaligned. Check the CT and MRI .nii files for errors first and make sure they're in the correct format, then check the MRI to be sure it's a T1 weighted scan. A T1 will be high resolution with lighter white matter than gray matter. While other MRI scan types may align properly with the CT, it will cause problems later in BioImageSuite and MATLAB that depend on the contrast found in a T1-type scan. If the pre-op MRI is not a T1 scan, one can be made from the .BRIK and .HEAD files (see above). Re-run the alignment with less strict parameters. This will require stepping out from the ct2mri.sh command and using the flirt command directly, then adding the resulting alignment to the elec_recon folder. See the alignment section above for the full flirt command and its parameters.

Electrode Placement

Can't Find Electrodes/Images Do Not Match Surgical File

First check that you've loaded the correct ct2ti.nii.gz and .mgrid file. We recommend naming both files with the subject's identifier and making sure that they match each time you open a new file or switch patients in BioImage Suite. Also check that you have the correct patient's files for reference (surgical files, etc.) and that the scans used to create the ctINt1.nii.gz file were the most up-to-date. If using intra-op images for reference, be sure to know the orientation of the patient's head in relation to the camera to avoid rotation errors.

Sometimes the surgical files include a diagram of the electrodes used. Often subdural electrode grids will have a platinum marker on them that will show up in a CT scan and in BioImage Suite that can be used to ensure the orientation of the grid. The electrode producer's website should have information about each product including a diagram with numbered contacts, marker locations, and wire placement.

Electrodes shift after placement; some electrodes may slide along the surface of the brain or move within the tissue. This can cause electrodes to end up a few millimeters from their original implant location and to a limited extent should be expected. The electrode projection methods described above correct for this type of brainshift.

In the case of depth electrodes, improper tightening of the anchor bolt that holds the electrode in place can cause the entire electrode to shift outward from the brain, sometimes leaving contacts in the anchor bolt itself. Often if it seems a depth electrode is missing a contact, it may have slid outward slightly.

If there is a major issue with any element of the patient's setup--a detached wire, a broken anchor bolt, multiple missing contacts, etc.--contact the patient's surgical team immediately. Provide evidence of the issue's nature and location so it can be quickly identified. This issue is extremely rare but should never be dismissed lightly; if there seems to be a problem, report it or check it out just to be safe.

MATLAB Projection

Errors in makeIniLocTxtFile

Check that the globalFsDir was indeed globalized. This step is dependent on the directory entered as globalFsDir; it cannot find any files not on that path. Check that the file or folder for which it's searching is correct.

Errors in yangWangElecPjct

Sometimes the Yang, Wang et al. projection method will display a warped grid with high standard deviations. If this is the case, re-run the function with slightly different parameters. All grids need to be entered with the smaller dimension first. Accept the default orientation of the grid's corners; it should only affect the labeling of the grid in future images.

If the error "String X# not found in cell array" appears, it means that MATLAB can't find electrode # of grid X. Check labeling first as the issue may be as simple as mixing up the names of the grids. Then check BioImageSuite grid placement that all electrodes have been placed correctly and that the names of the grids are correct.

Sometimes the function will fail to produce the shift distribution maps. Generally, when this occurs it is because the grids were not given unique names or were improperly tagged. If this is the case, rename the electrodes in BioImageSuite and rerun makeIniLocTxtFile to update the files created with the new names.

Errors in plotMgridOnPial

An odd error reading "Error using *" may appear if you try to run this step after the Yang, Wang et al. function does not produce the shift distribution maps. See above for the correction.

If the brain looks lopsided, jagged, or not like a normal brain should, it may be that the CT/MRI alignment was not completely aligned or not done with a T1 weighted scan. Check the original .nii files used in ct2mri.sh and if necessary re-run the alignment.