Cell Types Database

This notebook demonstrates most of the features of the AllenSDK that help manipulate data in the Cell Types Database. The main entry point will be through the CellTypesCache class.

CellTypesCache is responsible for downloading Cell Types Database data to a standard directory structure on your hard drive. If you use this class, you will not have to keep track of where your data lives, other than a root directory.

Download this file in .ipynb format here.

In [1]:
from allensdk.core.cell_types_cache import CellTypesCache

# Instantiate the CellTypesCache instance.  The manifest_file argument
# tells it where to store the manifest, which is a JSON file that tracks
# file paths.  If you supply a relative path (like this), it will go
# into your current working directory
ctc = CellTypesCache(manifest_file='cell_types/manifest.json')

# this saves the NWB file to 'cell_types/specimen_464212183/ephys.nwb'
data_set = ctc.get_ephys_data(464212183)

The data_set variable is an NwbDataSet instance, which has some methods we can use to access the injected current stimulus waveform and the voltage response waveform for all experimental sweeps. Let's pull one sweep out and plot it.

In [2]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

sweep_number = 30
sweep_data = data_set.get_sweep(sweep_number)

index_range = sweep_data["index_range"]
i = sweep_data["stimulus"][0:index_range[1]+1] # in A
v = sweep_data["response"][0:index_range[1]+1] # in V
i *= 1e12 # to pA
v *= 1e3 # to mV

sampling_rate = sweep_data["sampling_rate"] # in Hz
t = np.arange(0, len(v)) * (1.0 / sampling_rate)

plt.style.use('ggplot')
fig, axes = plt.subplots(2, 1, sharex=True)
axes[0].plot(t, v, color='black')
axes[1].plot(t, i, color='gray')
axes[0].set_ylabel("mV")
axes[1].set_ylabel("pA")
axes[1].set_xlabel("seconds")
plt.show()

Filtering Cells via Metadata

Cell records in the Cell Types Database come with a large amount of metadata. We have exposed the most commonly used of these are arguments to CellTypesCache.get_cells.

In [3]:
from allensdk.core.cell_types_cache import CellTypesCache
from allensdk.core.cell_types_cache import ReporterStatus as RS

# download all cells
cells = ctc.get_cells()
print "Total cells: ", len(cells)

# download metadata for all cells with morphology images
cells = ctc.get_cells(require_morphology = True)
print "Cells with morphology images: ", len(cells)

# cells with reconstructions
cells = ctc.get_cells(require_reconstruction = True)
print "Cells with reconstructions: ", len(cells)

# all cre positive cells
cells = ctc.get_cells(reporter_status = RS.POSITIVE)
print "Cre-positive cells: ", len(cells)

# cre negative cells with reconstructions
cells = ctc.get_cells(require_reconstruction = True, 
                      reporter_status = RS.NEGATIVE)
print "Cre-negative cells with reconstructions: ", len(cells)
Total cells:  978
Cells with morphology images:  575
Cells with reconstructions:  295
Cre-positive cells:  889
Cre-negative cells with reconstructions:  35

Cell Morphology Reconstructions

The Cell Types Database also contains 3D reconstructions of neuronal morphologies. The data are presented in the SWC format. We'll download a particular cell's reconstrution here.

The AllenSDK contains a module that makes it easier to work with the SWC files. We'll see how the data is contained in the file by looking at the first node.

In [4]:
import pprint

# download and open an SWC file
cell_id = 480114344
morphology = ctc.get_reconstruction(cell_id) 

# the compartment list has all of the nodes in the file
pprint.pprint(morphology.compartment_list[0])
{'children': [1,
              1763,
              2012,
              2089,
              2421,
              2604,
              2821,
              3147,
              3440,
              3491,
              3552,
              4015],
 'id': 0,
 'parent': -1,
 'radius': 7.6078,
 'tree_id': 0,
 'type': 1,
 'x': 444.3296,
 'y': 503.0168,
 'z': 31.92}

Note that the type field refers to the type of neuronal compartment. The values can be 1 for the soma, 2 for the axon, 3 for dendrites, and 4 for apical dendrites (if present).

Morphologies now also come with marker files, which contains points of interest in the reconstruction. The marker file contains locations where dendrites have been truncated due to slicing and when axons were not reconstructed. The name field indicates the type of marker (10 for dendrite truncation, 20 for no reconstruction).

In [5]:
# download and open a marker file
markers = ctc.get_reconstruction_markers(cell_id) 
print len(markers)
pprint.pprint(markers[0])
21
{'name': 10, 'x': 527.5029999999999, 'y': 496.4319, 'z': 12.4555}

We can use this data to draw lines between each node and all its children to get a drawing of the cell. We'll do it looking at it from the front and from the side.

In [6]:
from allensdk.core.swc import Marker
fig, axes = plt.subplots(1, 2, sharey=True, sharex=True)
axes[0].set_aspect('equal', 'box-forced')
axes[1].set_aspect('equal', 'box-forced')

# Make a line drawing of x-y and y-z views
for n in morphology.compartment_list:
    for c in morphology.children_of(n):
        axes[0].plot([n['x'], c['x']], [n['y'], c['y']], color='black')
        axes[1].plot([n['z'], c['z']], [n['y'], c['y']], color='black')

# cut dendrite markers
dm = [ m for m in markers if m['name'] == Marker.CUT_DENDRITE ]

axes[0].scatter([m['x'] for m in dm], [m['y'] for m in dm], color='#3333ff')
axes[1].scatter([m['z'] for m in dm], [m['y'] for m in dm], color='#3333ff')

# no reconstruction markers
nm = [ m for m in markers if m['name'] == Marker.NO_RECONSTRUCTION ]

axes[0].scatter([m['x'] for m in nm], [m['y'] for m in nm], color='#333333')
axes[1].scatter([m['z'] for m in nm], [m['y'] for m in nm], color='#333333')

axes[0].set_ylabel('y')
axes[0].set_xlabel('x')
axes[1].set_xlabel('z')
plt.show()

Electrophysiology Features

The Cell Types Database contains a set of features that have already been computed, which could serve as good starting points for analysis. We can query the database using the SDK to get these features.

In [7]:
import pprint
pp = pprint.PrettyPrinter(indent=2)

# download all electrophysiology features for all cells
ephys_features = ctc.get_ephys_features()

print("Ephys. features available for %d cells" % len(ephys_features))

# filter down to a specific cell
specimen_id = 464212183
cell_ephys_features = [f for f in ephys_features if f['specimen_id'] == specimen_id]

pp.pprint(cell_ephys_features)
Ephys. features available for 978 cells
[ { 'adaptation': 0.010660191695700002,
    'avg_isi': 50.9122222222,
    'electrode_0_pa': -73.0906168922,
    'f_i_curve_slope': 0.385990848293,
    'fast_trough_t_long_square': 1.243575,
    'fast_trough_t_ramp': 3.872615,
    'fast_trough_t_short_square': 1.0257983333299998,
    'fast_trough_v_long_square': -58.4062538147,
    'fast_trough_v_ramp': -56.364584604899996,
    'fast_trough_v_short_square': -61.026043574,
    'has_burst': False,
    'has_delay': False,
    'has_pause': False,
    'id': 464366365,
    'input_resistance_mohm': 129.36264,
    'latency': 0.030780000000000002,
    'peak_t_long_square': 1.24139,
    'peak_t_ramp': 3.87071,
    'peak_t_short_square': 1.02364916667,
    'peak_v_long_square': 10.71875,
    'peak_v_ramp': 26.4895833333,
    'peak_v_short_square': 16.0000006358,
    'rheobase_sweep_id': 464306919,
    'rheobase_sweep_number': 45,
    'ri': 223.43757748599998,
    'sag': 0.196279138327,
    'seal_gohm': 1.80903808,
    'slow_trough_t_long_square': nan,
    'slow_trough_t_ramp': nan,
    'slow_trough_t_short_square': 1.273295,
    'slow_trough_v_long_square': nan,
    'slow_trough_v_ramp': nan,
    'slow_trough_v_short_square': -65.72916793819999,
    'specimen_id': 464212183,
    'tau': 19.0825501891,
    'threshold_i_long_square': 70.0,
    'threshold_i_ramp': 71.25,
    'threshold_i_short_square': 380.0,
    'threshold_t_long_square': 1.240845,
    'threshold_t_ramp': 3.87010166667,
    'threshold_t_short_square': 1.02313833333,
    'threshold_v_long_square': -40.53125,
    'threshold_v_ramp': -39.395834604899996,
    'threshold_v_short_square': -40.3802083333,
    'thumbnail_sweep_id': 464306887,
    'trough_t_long_square': 1.243855,
    'trough_t_ramp': 3.8729699999999996,
    'trough_t_short_square': 1.273295,
    'trough_v_long_square': -58.59375,
    'trough_v_ramp': -56.6354192098,
    'trough_v_short_square': -65.72916793819999,
    'upstroke_downstroke_ratio_long_square': 1.91568368871,
    'upstroke_downstroke_ratio_ramp': 2.0455410248700003,
    'upstroke_downstroke_ratio_short_square': 1.8211783878099999,
    'vm_for_sag': -90.46875,
    'vrest': -65.7717132568}]

That's how to get all the ephys features for a given specimen - what if we want a particular feature for all cells?

In [8]:
updown = np.array([f['upstroke_downstroke_ratio_long_square'] for f in ephys_features], dtype=float)
fasttrough = np.array([f['fast_trough_v_long_square'] for f in ephys_features], dtype=float)

plt.figure()
plt.scatter(fasttrough, updown, color='#2ca25f')
plt.ylabel("upstroke-downstroke ratio")
plt.xlabel("fast trough depth (mV)")
plt.show()

Let's use numpy to fit a regression line to these data and plot it.

In [9]:
A = np.vstack([fasttrough, np.ones_like(updown)]).T
print "First 5 rows of A:"
print A[:5, :]

m, c = np.linalg.lstsq(A, updown)[0]
print "m", m, "c", c

plt.figure()
plt.scatter(fasttrough, updown, color='#2ca25f')
plt.plot(fasttrough, m * fasttrough + c, c='gray')
plt.ylabel("upstroke-downstroke ratio")
plt.xlabel("fast trough depth (mV)")
plt.show()
First 5 rows of A:
[[-42.00000381   1.        ]
 [-51.18750381   1.        ]
 [-44.96875      1.        ]
 [-45.15625      1.        ]
 [-65.09375      1.        ]]
m 0.105360900954 c 8.25646756432

It looks like there may be roughly two clusters in the data above. Maybe they relate to whether the cells are presumably excitatory (spiny) cells or inhibitory (aspiny) cells. Let's query the API and split up the two sets to see.

In [10]:
cells = ctc.get_cells()

cell_index = { c['id']: c for c in cells}

dendrite_types = ['spiny', 'aspiny']
data = {}

# group fast trough depth and upstroke downstroke ratio values by cell dendrite type
for dendrite_type in dendrite_types:
    type_features = [f for f in ephys_features if cell_index[f['specimen_id']]['dendrite_type'] == dendrite_type]
    data[dendrite_type] = {
        "fasttrough": [f['fast_trough_v_long_square'] for f in type_features],
        "updown": [f['upstroke_downstroke_ratio_short_square'] for f in type_features],
    }
    
plt.figure()
for a_type, color in zip(dendrite_types, ["#d95f02", "#7570b3"]):
    plt.scatter(data[a_type]['fasttrough'], data[a_type]['updown'], color=color, label=a_type)
plt.legend(loc='best')
plt.ylabel("upstroke-downstroke ratio")
plt.xlabel("fast trough depth (mV)")
plt.show()

Morphology Features

The Cell Types Database contains a set of precomputed morphological features for cells that have reconstructions. You can access morphology features by themselves, or combined with the electrophysiology features.

In [11]:
import pandas as pd

# download all morphology features for cells with reconstructions
morphology_features = ctc.get_morphology_features()

# or download both morphology and ephys features
all_features = ctc.get_all_features(require_reconstruction=True)

# convert to a pandas DataFrame
all_features = pd.DataFrame(all_features)
print("All features available for %d cells" % len(all_features))

all_features.head()
All features available for 295 cells
Out[11]:
adaptation average_bifurcation_angle_local average_bifurcation_angle_remote average_contraction average_diameter average_fragmentation average_parent_daughter_ratio avg_isi electrode_0_pa f_i_curve_slope ... trough_t_ramp trough_t_short_square trough_v_long_square trough_v_ramp trough_v_short_square upstroke_downstroke_ratio_long_square upstroke_downstroke_ratio_ramp upstroke_downstroke_ratio_short_square vm_for_sag vrest
0 0.046079 82.140925 NaN 0.919328 0.279353 41.273973 0.861677 97.000000 23.797500 0.124640 ... 6.046945 1.262538 -52.562500 -53.708337 -72.765629 3.119665 3.083533 3.068449 -85.968758 -72.388512
1 0.022854 67.779736 NaN 0.904721 0.221545 35.984848 0.824531 88.649000 23.465624 0.127967 ... 7.295498 1.422118 -53.968754 -53.333336 -78.925003 4.067833 4.053186 4.076769 -91.062500 -78.132263
2 0.017411 74.465327 NaN 0.892347 0.232456 48.306122 0.793683 59.770313 -36.128749 0.182813 ... 7.179703 1.074060 -53.781254 -54.614587 -69.197920 3.041565 2.863346 2.698525 -77.437508 -68.042091
3 0.048709 59.310821 NaN 0.926514 0.287638 44.450000 0.977300 118.397143 -90.575616 0.307589 ... 7.204045 1.233473 -46.156254 -49.218753 -66.318753 2.026000 1.827572 1.818158 -82.406250 -65.503044
4 0.044825 77.679949 NaN 0.895664 0.488865 48.027778 0.928510 91.322222 -46.761876 0.223864 ... 3.862007 1.806510 -50.875000 -50.989586 -76.791669 2.992793 2.817856 2.706951 -96.906250 -75.320374

5 rows × 83 columns

Computing Electrophysiology Features

The AllenSDK contains the code used to compute the electrophysiology features you accessed above. You can run it yourself like this.

In [12]:
from allensdk.ephys.ephys_extractor import EphysSweepFeatureExtractor

sweep_number = 35
sweep_data = data_set.get_sweep(sweep_number)

index_range = sweep_data["index_range"]
i = sweep_data["stimulus"][0:index_range[1]+1] # in A
v = sweep_data["response"][0:index_range[1]+1] # in V
i *= 1e12 # to pA
v *= 1e3 # to mV

sampling_rate = sweep_data["sampling_rate"] # in Hz
t = np.arange(0, len(v)) * (1.0 / sampling_rate)

sweep_ext = EphysSweepFeatureExtractor(t=t, v=v, i=i, start=1.02, end=2.02)
sweep_ext.process_spikes()

print "Avg spike threshold: {:.1f} mV".format(sweep_ext.spike_feature("threshold_v").mean())
print "Avg spike width: {:.2f} ms".format(1e3 * np.nanmean(sweep_ext.spike_feature("width")))
Avg spike threshold: -35.5 mV
Avg spike width: 0.94 ms

The method spike_feature() returns a NumPy array of features for each spike. You pass it the name of the feature that you want. Features that can't be calculated for a given spike are set to NaN. We can take a look at all the properties calculated for each spike by the extractor:

In [13]:
sweep_ext.spike_feature_keys()
Out[13]:
['threshold_index',
 'threshold_t',
 'threshold_v',
 'threshold_i',
 'peak_index',
 'peak_t',
 'peak_v',
 'peak_i',
 'trough_index',
 'trough_t',
 'trough_v',
 'trough_i',
 'downstroke_index',
 'downstroke',
 'downstroke_t',
 'downstroke_v',
 'upstroke_index',
 'upstroke',
 'upstroke_t',
 'upstroke_v',
 'isi_type',
 'fast_trough_index',
 'fast_trough_t',
 'fast_trough_v',
 'fast_trough_i',
 'slow_trough_index',
 'slow_trough_t',
 'slow_trough_v',
 'slow_trough_i',
 'adp_index',
 'adp_t',
 'adp_v',
 'adp_i',
 'width',
 'upstroke_downstroke_ratio']

We can look at when the spikes occur by looking at the threshold_t property (i.e., time of spike threshold).

In [14]:
spike_times = sweep_ext.spike_feature("threshold_t")

print(spike_times[:5])  # print just the first 5 spike times
[ 1.02811   1.040935  1.053675  1.068645  1.082835]

We can see that the first spikes happen just after the stimulus step begins at 1.02 sec. Let's plot the voltage trace and then put a dot at the time of each spike detected by the extractor.

In [15]:
fig = plt.figure()
p = plt.plot(t, v, color='black')

min_v = v.min()

v_level = min_v - 5

plt.scatter(spike_times, np.ones(len(spike_times)) * min_v, c='firebrick')
plt.xlim(0.9, 1.2)
Out[15]:
(0.9, 1.2)

We could also get the threshold voltages from the extractor and put dots where the extractor thinks the spikes begin (zooming in a little more to see better):

In [16]:
fig = plt.figure()
plt.plot(t, v, color='black')

threshold_v = sweep_ext.spike_feature("threshold_v")

# setting zorder puts the dots on top of the trace
plt.scatter(spike_times, threshold_v, s=50, c='firebrick', zorder=20)
plt.xlim(1.015, 1.08)
Out[16]:
(1.015, 1.08)