INTENSE Visualization
- driada.intense.visual.plot_pc_activity(exp, cell_ind, place_key=('x', 'y'), ds=5, ax=None, show_trajectory=False, show_spikes=True, cmap='plasma', marker_size=100, marker_style='*', marker_color='k', scatter_alpha=0.8, trajectory_alpha=0.3, trajectory_color='gray', figsize_base=6, title_format='Cell {cell_ind}, Rel MI={rel_mi:.4f}, pval={pval:.2e}', xlabel=None, ylabel=None, show_stats=True)[source]
Plot place cell activity overlaid on spatial trajectory.
- Parameters:
exp (Experiment) – Experiment object with spatial data and neurons.
cell_ind (int) – Index of the neuron to plot.
place_key (tuple or str, optional) – Feature key for spatial data. Default: (“x”, “y”). Can be tuple like (“x”, “y”) or string like “position”.
ds (int, optional) – Downsampling factor. Default: 5.
ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, creates new figure.
show_trajectory (bool, optional) – Whether to show trajectory line. Default: False.
show_spikes (bool, optional) – Whether to show spike markers. Default: True.
cmap (str, optional) – Colormap for activity. Default: “plasma”.
marker_size (int, optional) – Size of spike markers. Default: 100.
marker_style (str, optional) – Marker style for spikes. Default: “*”.
marker_color (str, optional) – Color for spike markers. Default: “k”.
scatter_alpha (float, optional) – Alpha for activity scatter. Default: 0.8.
trajectory_alpha (float, optional) – Alpha for trajectory line. Default: 0.3.
trajectory_color (str, optional) – Color for trajectory. Default: “gray”.
figsize_base (float, optional) – Base figure size (adjusted by aspect ratio). Default: 6.
title_format (str, optional) – Format string for title. Available keys: cell_ind, rel_mi, pval. Default: “Cell {cell_ind}, Rel MI={rel_mi:.4f}, pval={pval:.2e}”
xlabel (str, optional) – X-axis label. Default: first element of place_key or “x”.
ylabel (str, optional) – Y-axis label. Default: second element of place_key or “y”.
show_stats (bool, optional) – Whether to show statistics in title. Default: True.
- Returns:
ax – Axes with the plot.
- Return type:
- Raises:
KeyError – If cell_ind or place_key not found in stats_table
IndexError – If cell_ind >= number of neurons
ValueError – If place data is not 2D
AttributeError – If required attributes missing from experiment
Notes
Uses log-transformed calcium data for color mapping
Figure aspect ratio automatically adjusted based on spatial extent
Stats (MI and p-value) retrieved from experiment’s stats_table
Supports both tuple place keys like (“x”, “y”) and single feature names
Examples
>>> import matplotlib.pyplot as plt >>> from driada.experiment import load_demo_experiment >>> >>> # Basic place cell plot with position data >>> exp = load_demo_experiment(verbose=False) >>> # Use x_pos and y_pos which are available in demo data >>> # Note: Demo data doesn't have spike data, so we disable spike display >>> ax = plot_pc_activity(exp, cell_ind=5, place_key=("x_pos", "y_pos"), ... show_spikes=False, show_stats=False) >>> plt.close() # Suppress display >>> >>> # Using separate x,y features with custom styling >>> ax = plot_pc_activity(exp, cell_ind=10, place_key=("x_pos", "y_pos"), ... show_trajectory=True, cmap='viridis', ... marker_color='red', show_stats=False, ... show_spikes=False, ds=20) >>> plt.close() >>> >>> # Custom styling example >>> ax = plot_pc_activity(exp, cell_ind=3, place_key=("x_pos", "y_pos"), ... ds=10, show_stats=False, show_spikes=False) >>> plt.close()
- driada.intense.visual.plot_neuron_feature_density(exp, data_type, cell_id, featname, ind1=0, ind2=100000, ds=1, shift=None, ax=None, compute_wsd=False)[source]
Plot density distribution of neural activity conditioned on feature values.
- Parameters:
exp (Experiment) – Experiment object containing neurons and features.
data_type (str) – Type of neural data: ‘calcium’ or ‘spikes’.
cell_id (int) – Index of the neuron.
featname (str) – Name of the behavioral feature.
ind1 (int, optional) – Start frame index. Default: 0.
ind2 (int, optional) – End frame index. Default: 100000.
ds (int, optional) – Downsampling factor. Default: 1.
shift (int, optional) – Temporal shift in frames. Currently not implemented. Default: None.
ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, creates new figure.
compute_wsd (bool, optional) – Whether to compute Wasserstein distance for binary features. Default: False.
- Returns:
ax – Axes with the plot.
- Return type:
- Raises:
NotImplementedError – If data_type=’spikes’ with binary feature
IndexError – If cell_id >= number of neurons
AttributeError – If feature not found in experiment
Notes
Binary features: Uses KDE with bw_adjust=0.5, log10 transform
Continuous features: Adds 1e-8 noise, uses 100x100 grid
Uses .scdata attribute for scaled data access
shift parameter is accepted but not used
Examples
>>> import matplotlib.pyplot as plt >>> from driada.experiment import load_demo_experiment >>> >>> # Plot calcium vs feature density >>> exp = load_demo_experiment(verbose=False) >>> # Using 'speed' feature which is available in demo data >>> ax = plot_neuron_feature_density(exp, 'calcium', 5, 'speed') >>> plt.close() # Suppress display >>> >>> # For binary features (if available in your data) >>> # ax = plot_neuron_feature_density(exp, 'calcium', 10, 'licking', >>> # compute_wsd=True)
- driada.intense.visual.plot_shadowed_groups(ax, xvals, binary_series, color='gray', alpha=0.3, label='shadowed', ymin=0.0, ymax=1.0)[source]
Shade regions where binary series equals 1.
- Parameters:
ax (matplotlib.axes.Axes) – Axes to plot on.
xvals (array-like) – X-axis values corresponding to binary_series.
binary_series (array-like) – Binary array (0s and 1s) indicating regions to shade.
color (str, optional) – Color for shaded regions. Default: ‘gray’.
alpha (float, optional) – Transparency of shaded regions. Default: 0.3.
label (str, optional) – Label for legend. Default: ‘shadowed’.
ymin (float, optional) – Lower y extent in axes coordinates (0–1). Default: 0.0.
ymax (float, optional) – Upper y extent in axes coordinates (0–1). Default: 1.0.
- Returns:
ax – Modified axes object.
- Return type:
- driada.intense.visual.plot_neuron_feature_pair(exp, cell_id, featname, ind1=0, ind2=100000, ds=1, add_density_plot=True, ax=None, axs=None, style=None, panel_size=None, skip_tight_layout=False, title=None, bcolor='g', neuron_label=None, feature_label=None, non_feature_label=None)[source]
Plot neural activity alongside behavioral feature with density analysis.
- Parameters:
exp (Experiment) – Experiment object containing neurons and features.
cell_id (int) – Index of the neuron.
featname (str) – Name of the behavioral feature.
ind1 (int, optional) – Start frame index. Default: 0.
ind2 (int, optional) – End frame index. Default: 100000.
ds (int, optional) – Downsampling factor. Default: 1.
add_density_plot (bool, optional) – Whether to add density subplot. Default: True.
ax (matplotlib.axes.Axes, optional) – Single axis to plot on. Forces add_density_plot=False when provided.
axs (tuple of matplotlib.axes.Axes, optional) – Tuple of (ax_timeseries, ax_density) for external 2-panel layout. Enables density plot with external axes.
style (StylePreset, optional) – Style preset from publication framework. If None, uses StylePreset.from_make_beautiful() for backward compatibility.
panel_size (tuple of float, optional) – (width, height) in cm for style scaling. Default: (20, 6).
skip_tight_layout (bool, optional) – If True, skip plt.tight_layout() call. Useful for subfigure layouts. Default: False.
title (str, optional) – Custom title for the plot.
bcolor (str, optional) – Color for feature visualization. Default: ‘g’.
neuron_label (str, optional) – Custom label for neuron. Default: f’neuron {cell_id}’.
feature_label (str, optional) – Custom label for feature. Default: featname.
non_feature_label (str, optional) – Custom label for non-feature state. Default: f’non-{featname}’.
- Returns:
fig – Figure containing the plot(s).
- Return type:
- Raises:
IndexError – If cell_id >= number of neurons
AttributeError – If featname not found in experiment
Notes
Discrete features shown as shaded regions where active
Uses StylePreset for axis styling with legends below
Y-axis formatted to 1 decimal place
Dark gray for non-feature distribution in density plot
Calls plt.tight_layout() with bottom adjustment for legends (unless skip_tight_layout=True)
Examples
>>> import matplotlib.pyplot as plt >>> from driada.experiment import load_demo_experiment >>> >>> # Basic time series plot >>> exp = load_demo_experiment(verbose=False) >>> fig = plot_neuron_feature_pair(exp, 5, 'speed') >>> plt.close(fig) # Suppress display >>> >>> # With custom labels >>> fig = plot_neuron_feature_pair(exp, 10, 'object1', ... feature_label='Object Interaction', ... non_feature_label='No Object') >>> plt.close(fig)
- driada.intense.visual.plot_disentanglement_heatmap(disent_matrix, count_matrix, feat_names, title=None, figsize=(12, 10), dpi=100, cmap=None, vmin=0, vmax=100, cbar_label='Disentanglement score (%)', fontsize=14, title_fontsize=18, show_grid=True, grid_alpha=0.3)[source]
Plot disentanglement analysis results as a heatmap.
Creates a heatmap showing the relative disentanglement scores between feature pairs. Each cell (i,j) shows the percentage of neurons where feature i was primary when paired with feature j.
- Parameters:
disent_matrix (ndarray) – Disentanglement matrix from disentangle_all_selectivities.
count_matrix (ndarray) – Count matrix from disentangle_all_selectivities.
feat_names (list of str) – Feature names corresponding to matrix indices.
title (str, optional) – Plot title. Default: ‘Disentanglement Analysis’.
figsize (tuple, optional) – Figure size (width, height). Default: (12, 10).
dpi (int, optional) – Figure DPI. Default: 100.
cmap (str or Colormap, optional) – Colormap to use. Default: custom red-white-green gradient.
vmin (float, optional) – Minimum value for colormap. Default: 0.
vmax (float, optional) – Maximum value for colormap. Default: 100.
cbar_label (str, optional) – Colorbar label. Default: ‘Disentanglement score (%)’.
fontsize (int, optional) – Font size for tick labels. Default: 14.
title_fontsize (int, optional) – Font size for title. Default: 18.
show_grid (bool, optional) – Whether to show grid lines. Default: True.
grid_alpha (float, optional) – Grid transparency. Default: 0.3.
- Returns:
fig (matplotlib.figure.Figure) – Figure containing the heatmap.
ax (matplotlib.axes.Axes) – Axes containing the heatmap.
- Raises:
ImportError – If seaborn, pandas, or matplotlib.colors not available
ValueError – If matrix dimensions don’t match or feat_names length doesn’t match matrices
Notes
The heatmap uses a diverging colormap where: - Red indicates low disentanglement (feature is redundant) - Gray (0.7, 0.7, 0.7) indicates balanced contribution (~50%) - Green indicates high disentanglement (feature is primary)
Cells are masked (shown in white) where no data is available. Uses pandas DataFrame internally for seaborn compatibility. Calls plt.tight_layout() which affects figure state.
Examples
>>> import numpy as np >>> import matplotlib.pyplot as plt >>> >>> # Create synthetic data for demonstration >>> n_features = 4 >>> features = ['speed', 'position', 'direction', 'licking'] >>> >>> # Create synthetic matrices >>> # disent_matrix[i,j] = how many times feature i was primary vs j >>> disent_mat = np.array([ ... [0, 15, 8, 20], ... [5, 0, 12, 18], ... [12, 8, 0, 10], ... [10, 7, 15, 0] ... ]) >>> >>> # count_matrix[i,j] = total comparisons between features i and j >>> count_mat = np.array([ ... [0, 20, 20, 30], ... [20, 0, 20, 25], ... [20, 20, 0, 25], ... [30, 25, 25, 0] ... ]) >>> >>> # Basic heatmap >>> fig, ax = plot_disentanglement_heatmap(disent_mat, count_mat, features) >>> plt.close(fig) # Suppress display >>> >>> # Custom styling >>> fig, ax = plot_disentanglement_heatmap( ... disent_mat, count_mat, features, ... title="My Analysis", cmap='RdYlGn', ... figsize=(8, 6), dpi=150 ... ) >>> plt.close(fig)
- driada.intense.visual.plot_disentanglement_summary(disent_matrix, count_matrix, feat_names, experiments=None, title_prefix='', figsize=(14, 10), dpi=100)[source]
Plot comprehensive disentanglement analysis with multiple views.
Creates a figure with multiple subplots showing: 1. Disentanglement heatmap 2. Feature dominance scores 3. Pairwise interaction counts
- Parameters:
disent_matrix (ndarray or list of ndarray) – Disentanglement matrix(es). If list, matrices are summed.
count_matrix (ndarray or list of ndarray) – Count matrix(es). If list, matrices are summed.
feat_names (list of str) – Feature names corresponding to matrix indices.
experiments (list of str, optional) – Experiment names if multiple matrices provided. Currently not used.
title_prefix (str, optional) – Prefix for the main title.
figsize (tuple, optional) – Figure size. Default: (14, 10).
dpi (int, optional) – Figure DPI. Default: 100.
- Returns:
fig – Figure containing all subplots.
- Return type:
- Raises:
ImportError – If matplotlib.colors, seaborn, or pandas not available
ValueError – If matrix dimensions don’t match or feat_names length doesn’t match matrices
TypeError – If disent_matrix/count_matrix not ndarray or list of ndarrays
Notes
Creates 2x2 grid layout with custom ratios (3:1 for both dimensions)
Main heatmap uses red-white-green colormap (different from plot_disentanglement_heatmap)
Dominance scores show how often each feature is primary
Only displays feature pairs with non-zero counts
experiments parameter is accepted but not used in current implementation
Calls plt.tight_layout() which affects figure state
Examples
>>> import numpy as np >>> import matplotlib.pyplot as plt >>> >>> # Create synthetic data >>> features = ['speed', 'position', 'direction', 'licking'] >>> >>> # Synthetic matrices as before >>> disent_mat = np.array([ ... [0, 15, 8, 20], ... [5, 0, 12, 18], ... [12, 8, 0, 10], ... [10, 7, 15, 0] ... ]) >>> count_mat = np.array([ ... [0, 20, 20, 30], ... [20, 0, 20, 25], ... [20, 20, 0, 25], ... [30, 25, 25, 0] ... ]) >>> >>> # Single experiment summary >>> fig = plot_disentanglement_summary(disent_mat, count_mat, features) >>> plt.close(fig) # Suppress display >>> >>> # Multiple experiments (matrices will be summed) >>> disent2 = disent_mat * 0.8 # Second synthetic experiment >>> count2 = count_mat # Same comparison counts >>> fig = plot_disentanglement_summary( ... [disent_mat, disent2], [count_mat, count2], features, ... title_prefix="Combined: " ... ) >>> plt.close(fig)
- driada.intense.visual.plot_selectivity_heatmap(exp, significant_neurons, metric='mi', cmap='viridis', use_log_scale=False, vmin=None, vmax=None, figsize=(10, 8), significance_threshold=None, ax=None)[source]
Create a heatmap showing metric values for selective neuron-feature pairs.
- Parameters:
exp (Experiment) – The experiment object containing all data and results
significant_neurons (dict) – Dictionary mapping neuron IDs to lists of significant features
metric (str, optional) – Which metric to display (‘mi’ for mutual information, ‘corr’ for correlation) Default: ‘mi’
cmap (str, optional) – Colormap to use. Default: ‘viridis’
use_log_scale (bool, optional) – Whether to use log scale for metric values. Default: False
vmin (float, optional) – Minimum value for colormap. If None, auto-determined from data
vmax (float, optional) – Maximum value for colormap. If None, auto-determined from data
figsize (tuple, optional) – Figure size (ignored if ax provided). Default: (10, 8)
significance_threshold (float, optional) – If provided, only show pairs with p-value below this threshold
ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, creates new figure.
- Returns:
fig (matplotlib.figure.Figure) – Figure containing the heatmap
ax (matplotlib.axes.Axes) – Axes containing the heatmap
stats (dict) – Dictionary containing statistics about the data: - n_selective: number of selective neurons - n_pairs: total number of significant pairs - selectivity_rate: percentage of selective neurons - metric_values: list of all non-zero metric values - sparsity: percentage of zero entries in the matrix
- Raises:
AttributeError – If experiment missing required attributes (dynamic_features, n_cells, get_neuron_feature_pair_stats)
KeyError – If neuron or feature not found in experiment data
Notes
Only processes string-type features (tuple features are ignored)
Always uses mode=’calcium’ when retrieving stats
Calls plt.tight_layout() which affects figure state
Examples
>>> import matplotlib.pyplot as plt >>> from driada.experiment import load_demo_experiment >>> >>> # Load demo experiment and create synthetic selectivity data >>> exp = load_demo_experiment(verbose=False) >>> >>> # Create synthetic significant_neurons dict >>> # In real usage, this comes from INTENSE analysis >>> significant_neurons = { ... 5: ['speed', 'x_pos'], # Neuron 5 selective for speed and x_pos ... 10: ['speed'], # Neuron 10 selective for speed only ... 15: ['x_pos', 'y_pos'], # Neuron 15 selective for spatial features ... 20: ['speed', 'y_pos'], ... 25: ['x_pos'] ... } >>> >>> # Initialize stats_tables if not present >>> if not hasattr(exp, 'stats_tables'): ... exp.stats_tables = {} >>> if 'calcium' not in exp.stats_tables: ... exp.stats_tables['calcium'] = {} >>> >>> # Add minimal stats to experiment for the example >>> # Using features that exist in demo data >>> # Each stat entry needs data_hash and other required fields >>> import numpy as np >>> hash_val = 'demo_hash' >>> exp.stats_tables['calcium']['speed'] = { ... 5: {'me': 0.3, 'pval': 0.001, 'rval': 0.5, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.1, 'pre_rval': 0.3, ... 'rel_me_beh': 0.2, 'rel_me_ca': 0.15}, ... 10: {'me': 0.4, 'pval': 0.0001, 'rval': 0.6, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.05, 'pre_rval': 0.4, ... 'rel_me_beh': 0.3, 'rel_me_ca': 0.2}, ... 20: {'me': 0.25, 'pval': 0.005, 'rval': 0.4, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.2, 'pre_rval': 0.25, ... 'rel_me_beh': 0.15, 'rel_me_ca': 0.1} ... } >>> exp.stats_tables['calcium']['x_pos'] = { ... 5: {'me': 0.35, 'pval': 0.002, 'rval': 0.55, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.15, 'pre_rval': 0.35, ... 'rel_me_beh': 0.25, 'rel_me_ca': 0.2}, ... 15: {'me': 0.45, 'pval': 0.0001, 'rval': 0.7, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.08, 'pre_rval': 0.5, ... 'rel_me_beh': 0.35, 'rel_me_ca': 0.3}, ... 25: {'me': 0.3, 'pval': 0.003, 'rval': 0.5, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.18, 'pre_rval': 0.3, ... 'rel_me_beh': 0.2, 'rel_me_ca': 0.15} ... } >>> exp.stats_tables['calcium']['y_pos'] = { ... 15: {'me': 0.2, 'pval': 0.01, 'rval': 0.3, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.25, 'pre_rval': 0.15, ... 'rel_me_beh': 0.1, 'rel_me_ca': 0.08}, ... 20: {'me': 0.15, 'pval': 0.02, 'rval': 0.25, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.3, 'pre_rval': 0.12, ... 'rel_me_beh': 0.08, 'rel_me_ca': 0.05} ... } >>> >>> # Basic selectivity heatmap >>> fig, ax, stats = plot_selectivity_heatmap(exp, significant_neurons) >>> plt.close(fig) # Suppress display >>> >>> # With log scale and p-value filtering >>> fig, ax, stats = plot_selectivity_heatmap( ... exp, significant_neurons, ... use_log_scale=True, ... significance_threshold=0.01 ... ) >>> plt.close(fig) >>> >>> # Custom visualization >>> fig, ax, stats = plot_selectivity_heatmap( ... exp, significant_neurons, ... cmap='hot', vmin=0, vmax=0.5, ... figsize=(12, 10) ... ) >>> plt.close(fig)
Visualization tools for INTENSE analysis results.
Function Groups
- Activity Visualization
- driada.intense.visual.plot_pc_activity(exp, cell_ind, place_key=('x', 'y'), ds=5, ax=None, show_trajectory=False, show_spikes=True, cmap='plasma', marker_size=100, marker_style='*', marker_color='k', scatter_alpha=0.8, trajectory_alpha=0.3, trajectory_color='gray', figsize_base=6, title_format='Cell {cell_ind}, Rel MI={rel_mi:.4f}, pval={pval:.2e}', xlabel=None, ylabel=None, show_stats=True)[source]
Plot place cell activity overlaid on spatial trajectory.
- Parameters:
exp (Experiment) – Experiment object with spatial data and neurons.
cell_ind (int) – Index of the neuron to plot.
place_key (tuple or str, optional) – Feature key for spatial data. Default: (“x”, “y”). Can be tuple like (“x”, “y”) or string like “position”.
ds (int, optional) – Downsampling factor. Default: 5.
ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, creates new figure.
show_trajectory (bool, optional) – Whether to show trajectory line. Default: False.
show_spikes (bool, optional) – Whether to show spike markers. Default: True.
cmap (str, optional) – Colormap for activity. Default: “plasma”.
marker_size (int, optional) – Size of spike markers. Default: 100.
marker_style (str, optional) – Marker style for spikes. Default: “*”.
marker_color (str, optional) – Color for spike markers. Default: “k”.
scatter_alpha (float, optional) – Alpha for activity scatter. Default: 0.8.
trajectory_alpha (float, optional) – Alpha for trajectory line. Default: 0.3.
trajectory_color (str, optional) – Color for trajectory. Default: “gray”.
figsize_base (float, optional) – Base figure size (adjusted by aspect ratio). Default: 6.
title_format (str, optional) – Format string for title. Available keys: cell_ind, rel_mi, pval. Default: “Cell {cell_ind}, Rel MI={rel_mi:.4f}, pval={pval:.2e}”
xlabel (str, optional) – X-axis label. Default: first element of place_key or “x”.
ylabel (str, optional) – Y-axis label. Default: second element of place_key or “y”.
show_stats (bool, optional) – Whether to show statistics in title. Default: True.
- Returns:
ax – Axes with the plot.
- Return type:
- Raises:
KeyError – If cell_ind or place_key not found in stats_table
IndexError – If cell_ind >= number of neurons
ValueError – If place data is not 2D
AttributeError – If required attributes missing from experiment
Notes
Uses log-transformed calcium data for color mapping
Figure aspect ratio automatically adjusted based on spatial extent
Stats (MI and p-value) retrieved from experiment’s stats_table
Supports both tuple place keys like (“x”, “y”) and single feature names
Examples
>>> import matplotlib.pyplot as plt >>> from driada.experiment import load_demo_experiment >>> >>> # Basic place cell plot with position data >>> exp = load_demo_experiment(verbose=False) >>> # Use x_pos and y_pos which are available in demo data >>> # Note: Demo data doesn't have spike data, so we disable spike display >>> ax = plot_pc_activity(exp, cell_ind=5, place_key=("x_pos", "y_pos"), ... show_spikes=False, show_stats=False) >>> plt.close() # Suppress display >>> >>> # Using separate x,y features with custom styling >>> ax = plot_pc_activity(exp, cell_ind=10, place_key=("x_pos", "y_pos"), ... show_trajectory=True, cmap='viridis', ... marker_color='red', show_stats=False, ... show_spikes=False, ds=20) >>> plt.close() >>> >>> # Custom styling example >>> ax = plot_pc_activity(exp, cell_ind=3, place_key=("x_pos", "y_pos"), ... ds=10, show_stats=False, show_spikes=False) >>> plt.close()
- Feature Analysis Plots
- driada.intense.visual.plot_neuron_feature_density(exp, data_type, cell_id, featname, ind1=0, ind2=100000, ds=1, shift=None, ax=None, compute_wsd=False)[source]
Plot density distribution of neural activity conditioned on feature values.
- Parameters:
exp (Experiment) – Experiment object containing neurons and features.
data_type (str) – Type of neural data: ‘calcium’ or ‘spikes’.
cell_id (int) – Index of the neuron.
featname (str) – Name of the behavioral feature.
ind1 (int, optional) – Start frame index. Default: 0.
ind2 (int, optional) – End frame index. Default: 100000.
ds (int, optional) – Downsampling factor. Default: 1.
shift (int, optional) – Temporal shift in frames. Currently not implemented. Default: None.
ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, creates new figure.
compute_wsd (bool, optional) – Whether to compute Wasserstein distance for binary features. Default: False.
- Returns:
ax – Axes with the plot.
- Return type:
- Raises:
NotImplementedError – If data_type=’spikes’ with binary feature
IndexError – If cell_id >= number of neurons
AttributeError – If feature not found in experiment
Notes
Binary features: Uses KDE with bw_adjust=0.5, log10 transform
Continuous features: Adds 1e-8 noise, uses 100x100 grid
Uses .scdata attribute for scaled data access
shift parameter is accepted but not used
Examples
>>> import matplotlib.pyplot as plt >>> from driada.experiment import load_demo_experiment >>> >>> # Plot calcium vs feature density >>> exp = load_demo_experiment(verbose=False) >>> # Using 'speed' feature which is available in demo data >>> ax = plot_neuron_feature_density(exp, 'calcium', 5, 'speed') >>> plt.close() # Suppress display >>> >>> # For binary features (if available in your data) >>> # ax = plot_neuron_feature_density(exp, 'calcium', 10, 'licking', >>> # compute_wsd=True)
- driada.intense.visual.plot_neuron_feature_pair(exp, cell_id, featname, ind1=0, ind2=100000, ds=1, add_density_plot=True, ax=None, axs=None, style=None, panel_size=None, skip_tight_layout=False, title=None, bcolor='g', neuron_label=None, feature_label=None, non_feature_label=None)[source]
Plot neural activity alongside behavioral feature with density analysis.
- Parameters:
exp (Experiment) – Experiment object containing neurons and features.
cell_id (int) – Index of the neuron.
featname (str) – Name of the behavioral feature.
ind1 (int, optional) – Start frame index. Default: 0.
ind2 (int, optional) – End frame index. Default: 100000.
ds (int, optional) – Downsampling factor. Default: 1.
add_density_plot (bool, optional) – Whether to add density subplot. Default: True.
ax (matplotlib.axes.Axes, optional) – Single axis to plot on. Forces add_density_plot=False when provided.
axs (tuple of matplotlib.axes.Axes, optional) – Tuple of (ax_timeseries, ax_density) for external 2-panel layout. Enables density plot with external axes.
style (StylePreset, optional) – Style preset from publication framework. If None, uses StylePreset.from_make_beautiful() for backward compatibility.
panel_size (tuple of float, optional) – (width, height) in cm for style scaling. Default: (20, 6).
skip_tight_layout (bool, optional) – If True, skip plt.tight_layout() call. Useful for subfigure layouts. Default: False.
title (str, optional) – Custom title for the plot.
bcolor (str, optional) – Color for feature visualization. Default: ‘g’.
neuron_label (str, optional) – Custom label for neuron. Default: f’neuron {cell_id}’.
feature_label (str, optional) – Custom label for feature. Default: featname.
non_feature_label (str, optional) – Custom label for non-feature state. Default: f’non-{featname}’.
- Returns:
fig – Figure containing the plot(s).
- Return type:
- Raises:
IndexError – If cell_id >= number of neurons
AttributeError – If featname not found in experiment
Notes
Discrete features shown as shaded regions where active
Uses StylePreset for axis styling with legends below
Y-axis formatted to 1 decimal place
Dark gray for non-feature distribution in density plot
Calls plt.tight_layout() with bottom adjustment for legends (unless skip_tight_layout=True)
Examples
>>> import matplotlib.pyplot as plt >>> from driada.experiment import load_demo_experiment >>> >>> # Basic time series plot >>> exp = load_demo_experiment(verbose=False) >>> fig = plot_neuron_feature_pair(exp, 5, 'speed') >>> plt.close(fig) # Suppress display >>> >>> # With custom labels >>> fig = plot_neuron_feature_pair(exp, 10, 'object1', ... feature_label='Object Interaction', ... non_feature_label='No Object') >>> plt.close(fig)
- Heatmaps and Summaries
- driada.intense.visual.plot_selectivity_heatmap(exp, significant_neurons, metric='mi', cmap='viridis', use_log_scale=False, vmin=None, vmax=None, figsize=(10, 8), significance_threshold=None, ax=None)[source]
Create a heatmap showing metric values for selective neuron-feature pairs.
- Parameters:
exp (Experiment) – The experiment object containing all data and results
significant_neurons (dict) – Dictionary mapping neuron IDs to lists of significant features
metric (str, optional) – Which metric to display (‘mi’ for mutual information, ‘corr’ for correlation) Default: ‘mi’
cmap (str, optional) – Colormap to use. Default: ‘viridis’
use_log_scale (bool, optional) – Whether to use log scale for metric values. Default: False
vmin (float, optional) – Minimum value for colormap. If None, auto-determined from data
vmax (float, optional) – Maximum value for colormap. If None, auto-determined from data
figsize (tuple, optional) – Figure size (ignored if ax provided). Default: (10, 8)
significance_threshold (float, optional) – If provided, only show pairs with p-value below this threshold
ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, creates new figure.
- Returns:
fig (matplotlib.figure.Figure) – Figure containing the heatmap
ax (matplotlib.axes.Axes) – Axes containing the heatmap
stats (dict) – Dictionary containing statistics about the data: - n_selective: number of selective neurons - n_pairs: total number of significant pairs - selectivity_rate: percentage of selective neurons - metric_values: list of all non-zero metric values - sparsity: percentage of zero entries in the matrix
- Raises:
AttributeError – If experiment missing required attributes (dynamic_features, n_cells, get_neuron_feature_pair_stats)
KeyError – If neuron or feature not found in experiment data
Notes
Only processes string-type features (tuple features are ignored)
Always uses mode=’calcium’ when retrieving stats
Calls plt.tight_layout() which affects figure state
Examples
>>> import matplotlib.pyplot as plt >>> from driada.experiment import load_demo_experiment >>> >>> # Load demo experiment and create synthetic selectivity data >>> exp = load_demo_experiment(verbose=False) >>> >>> # Create synthetic significant_neurons dict >>> # In real usage, this comes from INTENSE analysis >>> significant_neurons = { ... 5: ['speed', 'x_pos'], # Neuron 5 selective for speed and x_pos ... 10: ['speed'], # Neuron 10 selective for speed only ... 15: ['x_pos', 'y_pos'], # Neuron 15 selective for spatial features ... 20: ['speed', 'y_pos'], ... 25: ['x_pos'] ... } >>> >>> # Initialize stats_tables if not present >>> if not hasattr(exp, 'stats_tables'): ... exp.stats_tables = {} >>> if 'calcium' not in exp.stats_tables: ... exp.stats_tables['calcium'] = {} >>> >>> # Add minimal stats to experiment for the example >>> # Using features that exist in demo data >>> # Each stat entry needs data_hash and other required fields >>> import numpy as np >>> hash_val = 'demo_hash' >>> exp.stats_tables['calcium']['speed'] = { ... 5: {'me': 0.3, 'pval': 0.001, 'rval': 0.5, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.1, 'pre_rval': 0.3, ... 'rel_me_beh': 0.2, 'rel_me_ca': 0.15}, ... 10: {'me': 0.4, 'pval': 0.0001, 'rval': 0.6, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.05, 'pre_rval': 0.4, ... 'rel_me_beh': 0.3, 'rel_me_ca': 0.2}, ... 20: {'me': 0.25, 'pval': 0.005, 'rval': 0.4, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.2, 'pre_rval': 0.25, ... 'rel_me_beh': 0.15, 'rel_me_ca': 0.1} ... } >>> exp.stats_tables['calcium']['x_pos'] = { ... 5: {'me': 0.35, 'pval': 0.002, 'rval': 0.55, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.15, 'pre_rval': 0.35, ... 'rel_me_beh': 0.25, 'rel_me_ca': 0.2}, ... 15: {'me': 0.45, 'pval': 0.0001, 'rval': 0.7, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.08, 'pre_rval': 0.5, ... 'rel_me_beh': 0.35, 'rel_me_ca': 0.3}, ... 25: {'me': 0.3, 'pval': 0.003, 'rval': 0.5, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.18, 'pre_rval': 0.3, ... 'rel_me_beh': 0.2, 'rel_me_ca': 0.15} ... } >>> exp.stats_tables['calcium']['y_pos'] = { ... 15: {'me': 0.2, 'pval': 0.01, 'rval': 0.3, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.25, 'pre_rval': 0.15, ... 'rel_me_beh': 0.1, 'rel_me_ca': 0.08}, ... 20: {'me': 0.15, 'pval': 0.02, 'rval': 0.25, 'data_hash': hash_val, ... 'opt_delay': 0, 'pre_pval': 0.3, 'pre_rval': 0.12, ... 'rel_me_beh': 0.08, 'rel_me_ca': 0.05} ... } >>> >>> # Basic selectivity heatmap >>> fig, ax, stats = plot_selectivity_heatmap(exp, significant_neurons) >>> plt.close(fig) # Suppress display >>> >>> # With log scale and p-value filtering >>> fig, ax, stats = plot_selectivity_heatmap( ... exp, significant_neurons, ... use_log_scale=True, ... significance_threshold=0.01 ... ) >>> plt.close(fig) >>> >>> # Custom visualization >>> fig, ax, stats = plot_selectivity_heatmap( ... exp, significant_neurons, ... cmap='hot', vmin=0, vmax=0.5, ... figsize=(12, 10) ... ) >>> plt.close(fig)
- driada.intense.visual.plot_disentanglement_heatmap(disent_matrix, count_matrix, feat_names, title=None, figsize=(12, 10), dpi=100, cmap=None, vmin=0, vmax=100, cbar_label='Disentanglement score (%)', fontsize=14, title_fontsize=18, show_grid=True, grid_alpha=0.3)[source]
Plot disentanglement analysis results as a heatmap.
Creates a heatmap showing the relative disentanglement scores between feature pairs. Each cell (i,j) shows the percentage of neurons where feature i was primary when paired with feature j.
- Parameters:
disent_matrix (ndarray) – Disentanglement matrix from disentangle_all_selectivities.
count_matrix (ndarray) – Count matrix from disentangle_all_selectivities.
feat_names (list of str) – Feature names corresponding to matrix indices.
title (str, optional) – Plot title. Default: ‘Disentanglement Analysis’.
figsize (tuple, optional) – Figure size (width, height). Default: (12, 10).
dpi (int, optional) – Figure DPI. Default: 100.
cmap (str or Colormap, optional) – Colormap to use. Default: custom red-white-green gradient.
vmin (float, optional) – Minimum value for colormap. Default: 0.
vmax (float, optional) – Maximum value for colormap. Default: 100.
cbar_label (str, optional) – Colorbar label. Default: ‘Disentanglement score (%)’.
fontsize (int, optional) – Font size for tick labels. Default: 14.
title_fontsize (int, optional) – Font size for title. Default: 18.
show_grid (bool, optional) – Whether to show grid lines. Default: True.
grid_alpha (float, optional) – Grid transparency. Default: 0.3.
- Returns:
fig (matplotlib.figure.Figure) – Figure containing the heatmap.
ax (matplotlib.axes.Axes) – Axes containing the heatmap.
- Raises:
ImportError – If seaborn, pandas, or matplotlib.colors not available
ValueError – If matrix dimensions don’t match or feat_names length doesn’t match matrices
Notes
The heatmap uses a diverging colormap where: - Red indicates low disentanglement (feature is redundant) - Gray (0.7, 0.7, 0.7) indicates balanced contribution (~50%) - Green indicates high disentanglement (feature is primary)
Cells are masked (shown in white) where no data is available. Uses pandas DataFrame internally for seaborn compatibility. Calls plt.tight_layout() which affects figure state.
Examples
>>> import numpy as np >>> import matplotlib.pyplot as plt >>> >>> # Create synthetic data for demonstration >>> n_features = 4 >>> features = ['speed', 'position', 'direction', 'licking'] >>> >>> # Create synthetic matrices >>> # disent_matrix[i,j] = how many times feature i was primary vs j >>> disent_mat = np.array([ ... [0, 15, 8, 20], ... [5, 0, 12, 18], ... [12, 8, 0, 10], ... [10, 7, 15, 0] ... ]) >>> >>> # count_matrix[i,j] = total comparisons between features i and j >>> count_mat = np.array([ ... [0, 20, 20, 30], ... [20, 0, 20, 25], ... [20, 20, 0, 25], ... [30, 25, 25, 0] ... ]) >>> >>> # Basic heatmap >>> fig, ax = plot_disentanglement_heatmap(disent_mat, count_mat, features) >>> plt.close(fig) # Suppress display >>> >>> # Custom styling >>> fig, ax = plot_disentanglement_heatmap( ... disent_mat, count_mat, features, ... title="My Analysis", cmap='RdYlGn', ... figsize=(8, 6), dpi=150 ... ) >>> plt.close(fig)
- driada.intense.visual.plot_disentanglement_summary(disent_matrix, count_matrix, feat_names, experiments=None, title_prefix='', figsize=(14, 10), dpi=100)[source]
Plot comprehensive disentanglement analysis with multiple views.
Creates a figure with multiple subplots showing: 1. Disentanglement heatmap 2. Feature dominance scores 3. Pairwise interaction counts
- Parameters:
disent_matrix (ndarray or list of ndarray) – Disentanglement matrix(es). If list, matrices are summed.
count_matrix (ndarray or list of ndarray) – Count matrix(es). If list, matrices are summed.
feat_names (list of str) – Feature names corresponding to matrix indices.
experiments (list of str, optional) – Experiment names if multiple matrices provided. Currently not used.
title_prefix (str, optional) – Prefix for the main title.
figsize (tuple, optional) – Figure size. Default: (14, 10).
dpi (int, optional) – Figure DPI. Default: 100.
- Returns:
fig – Figure containing all subplots.
- Return type:
- Raises:
ImportError – If matplotlib.colors, seaborn, or pandas not available
ValueError – If matrix dimensions don’t match or feat_names length doesn’t match matrices
TypeError – If disent_matrix/count_matrix not ndarray or list of ndarrays
Notes
Creates 2x2 grid layout with custom ratios (3:1 for both dimensions)
Main heatmap uses red-white-green colormap (different from plot_disentanglement_heatmap)
Dominance scores show how often each feature is primary
Only displays feature pairs with non-zero counts
experiments parameter is accepted but not used in current implementation
Calls plt.tight_layout() which affects figure state
Examples
>>> import numpy as np >>> import matplotlib.pyplot as plt >>> >>> # Create synthetic data >>> features = ['speed', 'position', 'direction', 'licking'] >>> >>> # Synthetic matrices as before >>> disent_mat = np.array([ ... [0, 15, 8, 20], ... [5, 0, 12, 18], ... [12, 8, 0, 10], ... [10, 7, 15, 0] ... ]) >>> count_mat = np.array([ ... [0, 20, 20, 30], ... [20, 0, 20, 25], ... [20, 20, 0, 25], ... [30, 25, 25, 0] ... ]) >>> >>> # Single experiment summary >>> fig = plot_disentanglement_summary(disent_mat, count_mat, features) >>> plt.close(fig) # Suppress display >>> >>> # Multiple experiments (matrices will be summed) >>> disent2 = disent_mat * 0.8 # Second synthetic experiment >>> count2 = count_mat # Same comparison counts >>> fig = plot_disentanglement_summary( ... [disent_mat, disent2], [count_mat, count2], features, ... title_prefix="Combined: " ... ) >>> plt.close(fig)