Compare commits

..

No commits in common. "master" and "origin" have entirely different histories.

225 changed files with 6748 additions and 1201362 deletions

385
.gitignore vendored
View File

@ -1,385 +0,0 @@
*~
# ---> TeX
## Core latex/pdflatex auxiliary files:
*.aux
*.lof
*.log
*.lot
*.fls
*.out
*.toc
*.fmt
*.fot
*.cb
*.cb2
.*.lb
## Intermediate documents:
*.dvi
*.xdv
*-converted-to.*
# these rules might exclude image files for figures etc.
# *.ps
# *.eps
## Generated if empty string is given at "Please type another file name for output:"
.pdf
## Bibliography auxiliary files (bibtex/biblatex/biber):
*.bbl
*.bcf
*.blg
*-blx.aux
*-blx.bib
*.run.xml
## Build tool auxiliary files:
*.fdb_latexmk
*.synctex
*.synctex(busy)
*.synctex.gz
*.synctex.gz(busy)
*.pdfsync
## Build tool directories for auxiliary files
# latexrun
latex.out/
## Auxiliary and intermediate files from other packages:
# algorithms
*.alg
*.loa
# achemso
acs-*.bib
# amsthm
*.thm
# beamer
*.nav
*.pre
*.snm
*.vrb
# changes
*.soc
# comment
*.cut
# cprotect
*.cpt
# elsarticle (documentclass of Elsevier journals)
*.spl
# endnotes
*.ent
# fixme
*.lox
# feynmf/feynmp
*.mf
*.mp
*.t[1-9]
*.t[1-9][0-9]
*.tfm
#(r)(e)ledmac/(r)(e)ledpar
*.end
*.?end
*.[1-9]
*.[1-9][0-9]
*.[1-9][0-9][0-9]
*.[1-9]R
*.[1-9][0-9]R
*.[1-9][0-9][0-9]R
*.eledsec[1-9]
*.eledsec[1-9]R
*.eledsec[1-9][0-9]
*.eledsec[1-9][0-9]R
*.eledsec[1-9][0-9][0-9]
*.eledsec[1-9][0-9][0-9]R
# glossaries
*.acn
*.acr
*.glg
*.glo
*.gls
*.glsdefs
*.lzo
*.lzs
# uncomment this for glossaries-extra (will ignore makeindex's style files!)
# *.ist
# gnuplottex
*-gnuplottex-*
# gregoriotex
*.gaux
*.gtex
# htlatex
*.4ct
*.4tc
*.idv
*.lg
*.trc
*.xref
# hyperref
*.brf
# knitr
*-concordance.tex
# TODO Comment the next line if you want to keep your tikz graphics files
*.tikz
*-tikzDictionary
# listings
*.lol
# luatexja-ruby
*.ltjruby
# makeidx
*.idx
*.ilg
*.ind
# minitoc
*.maf
*.mlf
*.mlt
*.mtc[0-9]*
*.slf[0-9]*
*.slt[0-9]*
*.stc[0-9]*
# minted
_minted*
*.pyg
# morewrites
*.mw
# nomencl
*.nlg
*.nlo
*.nls
# pax
*.pax
# pdfpcnotes
*.pdfpc
# sagetex
*.sagetex.sage
*.sagetex.py
*.sagetex.scmd
# scrwfile
*.wrt
# sympy
*.sout
*.sympy
sympy-plots-for-*.tex/
# pdfcomment
*.upa
*.upb
# python
*.pyc
__pycache__/
# pythontex
*.pytxcode
pythontex-files-*/
# tcolorbox
*.listing
# thmtools
*.loe
# TikZ & PGF
*.dpth
*.md5
*.auxlock
# todonotes
*.tdo
# vhistory
*.hst
*.ver
# easy-todo
*.lod
# xcolor
*.xcp
# xmpincl
*.xmpi
# xindy
*.xdy
# xypic precompiled matrices and outlines
*.xyc
*.xyd
# endfloat
*.ttt
*.fff
# Latexian
TSWLatexianTemp*
## Editors:
# WinEdt
*.bak
*.sav
# Texpad
.texpadtmp
# LyX
*.lyx~
# Kile
*.backup
# gummi
.*.swp
# KBibTeX
*~[0-9]*
# TeXnicCenter
*.tps
# auto folder when using emacs and auctex
./auto/*
*.el
# expex forward references with \gathertags
*-tags.tex
# standalone packages
*.sta
# Makeindex log files
*.lpz
beat_results_smoothed.npy
beat_results_smoothed.pkl
data_baseline.npy
data_baseline.pkl
data_beat.npy
data_beat.pkl
exlude_beats.npy
beat_results_smoothed.csv
.pdf.png
compare.png
2019-09-10-ab-invivo-1/2019-09-10-ab-invivo-1.nix
2019-09-10-ab-invivo-1/chirpallspikess1.dat
2019-09-10-ab-invivo-1/chirprates1.dat
2019-09-10-ab-invivo-1/chirps-events.dat
2019-09-10-ab-invivo-1/chirpss.dat
2019-09-10-ab-invivo-1/chirpspikess1.dat
2019-09-10-ab-invivo-1/chirptracess.dat
2019-09-10-ab-invivo-1/chirpeodampls.dat
meansquare2.csv
highbeats.pdf
highbeats.pdf
differentcells_trans.png
MPFmodulation_tob.png
singlecellexample5.png
highbeats.pdf
beats.npy
*.png
*.svg
highbeats_backup/
highbeats_Review/
1. Introduction.pdf
abstract (2).pdf
abstract.pdf
abstract_illustrator-3.pdf
abstract_illustrator.pdf
ActivationFunction_SAM.pdf
amexamples.pdf
ammethodspowerspectra.pdf
beatmethodspowerspectra.pdf
beatspectra.pdf
beatspectra_orig.pdf
beatspectra_power.pdf
beatspectra_rectify.pdf
dampinghopkins.pdf
doc/1pseperateaug.pdf
doc/1psingleauthorgroup.pdf
doc/elsdoc.pdf
doc/elstest-1p.pdf
doc/elstest-1pdoubleblind.pdf
doc/elstest-3p.pdf
doc/elstest-3pd.pdf
doc/elstest-5p.pdf
doc/jfigs.pdf
efishsketch.pdf
EIF.pdf
EIF_appendix.pdf
EIF_original.pdf
elsarticle-template-num-names.pdf
elsarticle/doc/1pseperateaug.pdf
elsarticle/doc/1psingleauthorgroup.pdf
elsarticle/doc/elsdoc.pdf
elsarticle/doc/elstest-1p.pdf
elsarticle/doc/elstest-1pdoubleblind.pdf
elsarticle/doc/elstest-3p.pdf
elsarticle/doc/elstest-3pd.pdf
elsarticle/doc/elstest-5p.pdf
elsarticle/doc/jfigs.pdf
EODwaveform.pdf
EODwaveform_otherfish.pdf
graphic_abstract-2.pdf
highbeats_bef2_rev.pdf
highbeats_elsarticle.pdf
JAR.pdf
lockingspectra_adapt.pdf
lowpass.pdf
modulation_div_fr.pdf
MSE.pdf
MSE_modulation_error.pdf
numerical_compar_both.pdf
nyquist.pdf
Phase.pdf
population.pdf
population_orig.pdf
power.pdf
problem.pdf
quit.pdf
rebuttal1.pdf
rebuttal2.pdf
rebuttal3.pdf
rectify.pdf
resonance.pdf
RezeptorSkizze.pdf
SAM.pdf
samspectra.pdf
Skizze2.pdf
Spikes.pdf
toblerone.pdf
toblerone_animation.pdf
CurrentBiology_Guidlines.PDF

View File

@ -1,971 +0,0 @@
# -*- coding: utf-8 -*-
"""
Functions for Cb Stellate model
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import h5py
import gc
import scipy
import json
import copy
import os
import numpy as np
from numba import types, njit
from numba.typed import Dict
from scipy import signal
from Code.Functions.Utility_fxns import stimulus_init, NumpyEncoder
@njit
def Cb_stellate(V, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, ind_dict):
""" Simulate current and Vm for Cb stellate cell model from Alexander et al 2019 (https://dx.doi.org/10.1523%2FENEURO.0126-19.2019)
for I_in
Parameters
----------
V : float
Initial membrane potentia
g : dict
maximal conductance for currents
E : dict
Reversal potentials for currents
I_in : array
Current stimulus input to model
dt : float
fixed time step
currents_included : dict
Boolean to include current in simulation or not
stim_time :
length of stimulus ()
stim_num : int
number of different stimulus currents
C : float
membrane capacitance
shift : dict
for each gating parameter
scale : dict
for each gating parameter
b_param : dict
Boltzmann parameter values for each gating parameter
slope_shift : dict
for each gating parameter
gating : array
array of gating values over time
current : array
array of current values over time
ind_dict: dict
Dictionary of indices in arrays for gating variables
Returns
-------
V_m : array
Simulated membrane potential in response to I_in
"""
V_m = np.zeros((stim_num, stim_time))
# initialize gating
# Na activation
m_inf = (1 / (1 + np.exp((V - shift["m"] - slope_shift["m"] - b_param["m"][0]) / b_param["m"][1]))) ** \
b_param["m"][2]
gating[ind_dict['m'], :] = np.ones((stim_num)) * m_inf
# Na inactivation
h_inf = ((1 - b_param["h"][3]) / (1 + np.exp((V - shift["h"] - slope_shift["h"] - b_param["h"][0])
/ b_param["h"][1])) + b_param["h"][3]) ** b_param["h"][2]
gating[ind_dict['h'], :] = np.ones((stim_num)) * h_inf
# K activation
n_inf = (1 / (1 + np.exp((V - shift["n"] - slope_shift["n"] - b_param["n"][0]) / b_param["n"][1]))) ** \
b_param["n"][2]
gating[ind_dict['n'], :] = np.ones((stim_num)) * n_inf
# A-type K activation
n_A_inf = (1 / (1 + np.exp((V - shift["n_A"] - slope_shift["n_A"] - b_param["n_A"][0]) / b_param["n_A"][1]))) ** \
b_param["n_A"][2]
gating[ind_dict['n_A'], :] = np.ones((stim_num)) * n_A_inf
# A-type K inactivation
h_A_inf = (1 / (1 + np.exp((V - shift["h_A"] - slope_shift["h_A"] - b_param["h_A"][0]) / b_param["h_A"][1]))) ** \
b_param["h_A"][2]
gating[ind_dict['h_A'], :] = np.ones((stim_num)) * h_A_inf
# mutant A-type K activation
n_A_mut_inf = (1 / (1 + np.exp((V - shift["n_A_mut"] - slope_shift["n_A_mut"] - b_param["n_A_mut"][0]) / b_param["n_A_mut"][1]))) ** \
b_param["n_A_mut"][2]
gating[ind_dict['n_A_mut'], :] = np.ones((stim_num)) * n_A_mut_inf
# mutant A-type K inactivation
h_A_mut_inf = (1 / (1 + np.exp((V - shift["h_A_mut"] - slope_shift["h_A_mut"] - b_param["h_A_mut"][0]) / b_param["h_A_mut"][1]))) ** \
b_param["h_A_mut"][2]
gating[ind_dict['h_A_mut'], :] = np.ones((stim_num)) * h_A_mut_inf
# T-type Ca activation
m_T_inf = (1 / (1 + np.exp((V - shift["m_T"] - slope_shift["m_T"] - b_param["m_T"][0]) / b_param["m_T"][1]))) ** \
b_param["m_T"][2]
gating[ind_dict['m_T'], :] = np.ones((stim_num)) * m_T_inf
# T-type Ca inactivation
h_T_inf = (1 / (1 + np.exp((V - shift["h_T"] - slope_shift["h_T"] - b_param["h_T"][0]) / b_param["h_T"][1]))) ** \
b_param["h_T"][2]
gating[ind_dict['h_T'], :] = np.ones((stim_num)) * h_T_inf
# initialize currents and Vm
current[ind_dict['Na'], :] = np.zeros((stim_num))
current[ind_dict['Kd'], :] = np.zeros((stim_num))
current[ind_dict['Leak'], :] = np.zeros((stim_num))
current[ind_dict['A'], :] = np.zeros((stim_num))
current[ind_dict['A_mut'], :] = np.zeros((stim_num))
current[ind_dict['T'], :] = np.zeros((stim_num))
V_m[:, 0] = V
t = 1
while t < stim_time:
# Na activation
m_inf = (1 / (1 + np.exp((V_m[:, t - 1] - shift["m"] - slope_shift["m"] - b_param["m"][0]) / b_param["m"][1]))) ** \
b_param["m"][2]
gating[ind_dict['m'], :] = m_inf
gating[ind_dict['m'], :][gating[ind_dict['m'], :] > 1.] = 1.
gating[ind_dict['m'], :][gating[ind_dict['m'], :] < 0.] = 0.
# Na inactivation
h_inf = ((1 - b_param["h"][3]) / (1 + np.exp((V_m[:, t - 1] - shift["h"] - slope_shift["h"] - b_param["h"][0])
/ b_param["h"][1])) + b_param["h"][3]) ** b_param["h"][2]
tau_h = 0.1 + (2 * 322 * 46) / (4 * np.pi * (V_m[:, t - 1] - shift["h"] - -74) ** 2 + (46 ** 2))
h_dot = (h_inf - gating[ind_dict['h'], :]) * (1 / (tau_h * scale["h"]))
gating[ind_dict['h'], :] = gating[ind_dict['h'], :] + h_dot * dt
gating[ind_dict['h'], :][gating[ind_dict['h'], :] > 1.] = 1.
gating[ind_dict['h'], :][gating[ind_dict['h'], :] < 0.] = 0.
# K activation
n_inf = (1 / (1 + np.exp((V_m[:, t - 1] - shift["n"] - slope_shift["n"] - b_param["n"][0]) / b_param["n"][1]))) ** \
b_param["n"][2]
tau_n = 6 / (1 + np.exp((V_m[:, t - 1] - shift["n"] + 23) / 15))
n_dot = (n_inf - gating[ind_dict['n'], :]) * (1 / (tau_n * scale["n"]))
gating[ind_dict['n'], :] = gating[ind_dict['n'], :] + n_dot * dt
gating[ind_dict['n'], :][gating[ind_dict['n'], :] > 1.] = 1.
gating[ind_dict['n'], :][gating[ind_dict['n'], :] < 0.] = 0.
# A-type K activation
n_A_inf = (1 / (1 + np.exp((V_m[:, t - 1] - shift["n_A"] - slope_shift["n_A"] - b_param["n_A"][0]) / b_param["n_A"][1]))) ** \
b_param["n_A"][2]
tau_n_A = 5
n_A_dot = (n_A_inf - gating[ind_dict['n_A'], :]) * (1 / (tau_n_A * scale["n_A"]))
gating[ind_dict['n_A'], :] = gating[ind_dict['n_A'], :] + n_A_dot * dt
gating[ind_dict['n_A'], :][gating[ind_dict['n_A'], :] > 1.] = 1.
gating[ind_dict['n_A'], :][gating[ind_dict['n_A'], :] < 0.] = 0.
# A-type K inactivation
h_A_inf = (1 / (1 + np.exp(
(V_m[:, t - 1] - shift["h_A"] - slope_shift["h_A"] - b_param["h_A"][0]) / b_param["h_A"][1]))) ** \
b_param["h_A"][2]
tau_h_A = 10
h_A_dot = (h_A_inf - gating[ind_dict['h_A'], :]) * (1 / (tau_h_A * scale["h_A"]))
gating[ind_dict['h_A'], :] = gating[ind_dict['h_A'], :] + h_A_dot * dt
gating[ind_dict['h_A'], :][gating[ind_dict['h_A'], :] > 1.] = 1.
gating[ind_dict['h_A'], :][gating[ind_dict['h_A'], :] < 0.] = 0.
# mutant A-type K activation
n_A_mut_inf = (1 / (1 + np.exp((V_m[:, t - 1] - shift["n_A_mut"] - slope_shift["n_A_mut"] - b_param["n_A_mut"][0]) / b_param["n_A_mut"][1]))) ** \
b_param["n_A_mut"][2]
tau_n_A_mut = 5
n_A_mut_dot = (n_A_mut_inf - gating[ind_dict['n_A_mut'], :]) * (1 / (tau_n_A_mut * scale["n_A_mut"]))
gating[ind_dict['n_A_mut'], :] = gating[ind_dict['n_A_mut'], :] + n_A_mut_dot * dt
gating[ind_dict['n_A_mut'], :][gating[ind_dict['n_A_mut'], :] > 1.] = 1.
gating[ind_dict['n_A_mut'], :][gating[ind_dict['n_A_mut'], :] < 0.] = 0.
# mutant A-type K inactivation
h_A_mut_inf = (1 / (1 + np.exp((V_m[:, t - 1] - shift["h_A_mut"] - slope_shift["h_A_mut"] - b_param["h_A_mut"][0]) / b_param["h_A_mut"][1]))) ** \
b_param["h_A_mut"][2]
tau_h_A_mut = 10
h_A_mut_dot = (h_A_mut_inf - gating[ind_dict['h_A_mut'], :]) * (1 / (tau_h_A_mut * scale["h_A_mut"]))
gating[ind_dict['h_A_mut'], :] = gating[ind_dict['h_A_mut'], :] + h_A_mut_dot * dt
gating[ind_dict['h_A_mut'], :][gating[ind_dict['h_A_mut'], :] > 1.] = 1.
gating[ind_dict['h_A_mut'], :][gating[ind_dict['h_A_mut'], :] < 0.] = 0.
# T-type Ca activation
m_T_inf = (1 / (1 + np.exp((V_m[:, t - 1] - shift["m_T"] - slope_shift["m_T"] - b_param["m_T"][0]) / b_param["m_T"][1]))) ** \
b_param["m_T"][2]
gating[ind_dict['m_T'], :] = m_T_inf
gating[ind_dict['m_T'], :][gating[ind_dict['m_T'], :] > 1.] = 1.
gating[ind_dict['m_T'], :][gating[ind_dict['m_T'], :] < 0.] = 0.
# T-type Ca inactivation
h_T_inf = (1 / (1 + np.exp((V_m[:, t - 1] - shift["h_T"] - slope_shift["h_T"] - b_param["h_T"][0]) / b_param["h_T"][1]))) ** \
b_param["h_T"][2]
tau_h_T = 15
h_T_dot = (h_T_inf - gating[ind_dict['h_T'], :]) * (1 / (tau_h_T * scale["h_T"]))
gating[ind_dict['h_T'], :] = gating[ind_dict['h_T'], :] + h_T_dot * dt
gating[ind_dict['h_T'], :][gating[ind_dict['h_T'], :] > 1.] = 1.
gating[ind_dict['h_T'], :][gating[ind_dict['h_T'], :] < 0.] = 0.
# update currents
current[ind_dict['Leak'], :] = g["Leak"] * (V_m[:, t - 1] - E["Leak"]) * currents_included["Leak"]
current[ind_dict['Na'], :] = g["Na"] * (gating[ind_dict['m'], :] ** 3) * gating[ind_dict['h'], :] * \
(V_m[:, t - 1] - E["Na"]) * currents_included["Na"]
current[ind_dict['Kd'], :] = g["Kd"] * (gating[ind_dict['n'], :] ** 4) * (V_m[:, t - 1] - E["K"]) * \
currents_included["Kd"]
current[ind_dict['A'], :] = g["A"] * gating[ind_dict['n_A'], :] * gating[ind_dict['h_A'], :] * (
V_m[:, t - 1] - E["K"]) * currents_included["A"]
current[ind_dict['A_mut'], :] = g["A_mut"] * gating[ind_dict['n_A_mut'], :] * gating[ind_dict['h_A_mut'], :] * (
V_m[:, t - 1] - E["K"]) * currents_included["A_mut"]
current[ind_dict['T'], :] = g["T"] * gating[ind_dict['m_T'], :] * gating[ind_dict['h_T'], :] * (
V_m[:, t - 1] - E["Ca"]) * currents_included["T"]
# update dV/dt
V_dot = (1 / C) * (I_in[t, :] - (current[ind_dict['Leak'], :] + current[ind_dict['Na'], :] +
current[ind_dict['Kd'], :] + current[ind_dict['A'], :] +
current[ind_dict['A_mut'], :] + current[ind_dict['T'], :]))
# update V_m
V_m[:, t] = V_m[:, t - 1] + V_dot * dt
t += 1
return V_m
def Cb_stellate_mut(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low, number_steps,
initial_period, sec):
""" Simulate mutations for Cb Stellate model
Parameters
----------
V_init : float
Initial membrane potential
g : dict
maximal conductance for currents
E : dict
Reversal potentials for currents
I_in : array
Current stimulus input to model
dt : float
fixed time step
currents_included : dict
Boolean to include current in simulation or not
stim_time :
length of stimulus ()
stim_num : int
number of different stimulus currents
C : float
membrane capacitance
shift : dict
for each gating parameter
scale : dict
for each gating parameter
b_param : dict
Boltzmann parameter values for each gating parameter
slope_shift : dict
for each gating parameter
gating : array
array of gating values over time
current : array
array of current values over time
prominence : float
required spike prominence
desired_AUC_width : float
width of AUC from rheobase to rheobase+desired_AUC_width
mutations : dict
dictionary of mutation effects
mut : str
mutation
folder : str
folder to save hdf5 file in
high : float
upper current step magnitude
low : float
lowest current step magnitude
number_steps : int
number of current steps between low and high
initial_period : float
length of I = 0 before current step
sec:
length of current step in seconds
Returns
-------
saves mut.hdf5 file to folder
"""
# setup for simulation
g_multi = copy.deepcopy(g)
E_multi = copy.deepcopy(E)
b_param_multi = copy.deepcopy(b_param)
shift_multi = copy.deepcopy(shift)
scale_multi = copy.deepcopy(scale)
slope_shift_multi = copy.deepcopy(slope_shift)
currents_included_multi = copy.deepcopy(currents_included)
gating2 = copy.deepcopy(gating)
current2 = copy.deepcopy(current)
g_effect = Dict.empty(key_type=types.unicode_type, value_type=types.float64, )
for k, v in g_multi.items():
g_effect[k] = v
b_param_effect = Dict.empty(key_type=types.unicode_type, value_type=types.float64[:], )
for k, v in b_param_multi.items():
b_param_effect[k] = np.array(v)
shift2 = Dict.empty(key_type=types.unicode_type, value_type=types.float64, )
for k, v in shift_multi.items():
shift2[k] = v
scale2 = Dict.empty(key_type=types.unicode_type, value_type=types.float64, )
for k, v in scale_multi.items():
scale2[k] = v
slope_shift2 = Dict.empty(key_type=types.unicode_type, value_type=types.float64, )
for k, v in slope_shift_multi.items():
slope_shift2[k] = v
E2 = Dict.empty(key_type=types.unicode_type, value_type=types.float64, )
for k, v in E_multi.items():
E2[k] = v
currents_included2 = Dict.empty(key_type=types.unicode_type, value_type=types.boolean, )
for k, v in currents_included_multi.items():
currents_included2[k] = v
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'n_A', 'h_A', 'n_A_mut', 'h_A_mut', 'm_T', 'h_T']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'A', 'A_mut', 'T', 'Leak']):
ind_dict[var] = i
i += 1
# effect of mutation
g_effect['A_mut'] = g['A_mut'] * mutations[mut]['g_ratio']
b_param_effect['n_A_mut'][0] = b_param_effect['n_A_mut'][0] + mutations[mut]['activation_Vhalf_diff']
b_param_effect['n_A_mut'][1] = b_param_effect['n_A_mut'][1] * mutations[mut]['activation_k_ratio']
# initial simulation for current range from low to high
V_m = Cb_stellate(V_init * np.ones((stim_num)), g_effect, E2, I_in, dt, currents_included2, stim_time, stim_num, C,
shift2, scale2, b_param_effect, slope_shift2, gating2, current2, ind_dict)
stim_start = np.int(initial_period * 1 / dt)
min_spike_height = V_m[0, stim_start] + prominence ##########################################################
# create hdf5 file for the mutation and save data and metadata
fname = os.path.join(folder, "{}.hdf5".format(mut.replace(" ", "_")))
with h5py.File(fname, "a") as f:
data = f.create_group("data")
data.create_dataset('V_m', data=V_m, dtype='float64', compression="gzip", compression_opts=9)
metadata = {'I_high': high, 'I_low': low, 'stim_num': number_steps, 'stim_time': stim_time, 'sec': sec, 'dt': dt,
'initial_period': initial_period, 'g': json.dumps(dict(g_effect)), 'E': json.dumps(dict(E2)), 'C': C,
'V_init': V_init, 'ind_dict': json.dumps(dict(ind_dict)),
'b_param': json.dumps(dict(b_param_effect), cls=NumpyEncoder), 'currents': json.dumps(dict(currents_included2)),
'shift': json.dumps(dict(shift2)), 'scale': json.dumps(dict(scale2)), 'slope_shift': json.dumps(dict(slope_shift2)),
'prominence': prominence, 'desired_AUC_width': desired_AUC_width, 'mut': str(mut),
'min_spike_height': min_spike_height, }
data.attrs.update(metadata)
# firing frequency analysis and rheobase
with h5py.File(fname, "r+") as f:
I_mag = np.arange(low, high, (high - low) / stim_num)
analysis = f.create_group("analysis")
dtyp = h5py.special_dtype(vlen=np.dtype('float64'))
for i in np.array(['spike_times', 'spike_times_rheo', 'ISI', 'Freq', 'amplitude']):
analysis.create_dataset(i, (I_mag.shape[0],), dtype=dtyp, compression="gzip", compression_opts=9)
analysis.create_dataset('F_inf', (I_mag.shape[0],), dtype='float64')
analysis.create_dataset('F_null', (I_mag.shape[0],), dtype='float64')
analysis.create_dataset('AP', (I_mag.shape[0],), dtype='bool', compression="gzip", compression_opts=9)
analysis.create_dataset('AP_rheo', (I_mag.shape[0],), dtype='bool', compression="gzip", compression_opts=9)
analysis.create_dataset('rheobase', (1,), dtype='float64', compression="gzip", compression_opts=9)
for stim in range(I_mag.shape[0]):
# spike detection
ap_all, ap_prop = scipy.signal.find_peaks(V_m[stim, stim_start:], min_spike_height,
prominence=prominence, distance=1 * 1 / dt)
analysis['spike_times'][stim] = ap_all * dt
if analysis['spike_times'][stim].size == 0:
analysis['AP'][stim] = False
else:
analysis['AP'][stim] = True
analysis['amplitude'][stim] = np.array(ap_prop["peak_heights"])
analysis['ISI'][stim] = np.array([x - analysis['spike_times'][stim][i - 1] if i else None for i, x in
enumerate(analysis['spike_times'][stim])][1:]) # msec
analysis['Freq'][stim] = 1 / (analysis['ISI'][stim] / 1000)
if analysis['Freq'][stim].size != 0:
analysis['F_null'][stim] = analysis['Freq'][stim][0]
last_second_spikes = analysis['spike_times'][stim] > np.int(
f['data'].attrs['stim_time'] * dt - (500 + initial_period))
if np.any(last_second_spikes == True):
last_second_spikes_1 = np.delete(last_second_spikes,0) # remove first spike because it has no ISI/freq
analysis['F_inf'][stim] = np.mean(analysis['Freq'][stim][last_second_spikes_1])
else: # if no ISI detected
analysis['F_null'][stim] = 0
analysis['F_inf'][stim] = 0
# rheobase
# find where the first AP occurs
if np.any(analysis['AP'][:] == True):
# setup current range to be between the current step before and with first AP
I_first_spike = I_mag[np.argwhere(analysis['AP'][:] == True)[0][0]]
I_before_spike = I_mag[np.argwhere(analysis['AP'][:] == True)[0][0] - 1]
analysis.create_dataset('I_first_spike', data=I_first_spike, dtype='float64')
analysis.create_dataset('I_before_spike', data=I_before_spike, dtype='float64')
number_steps_rheo = 100
stim_time, I_in_rheo, stim_num_rheo, V_m_rheo = stimulus_init(I_before_spike, I_first_spike,
number_steps_rheo,
initial_period, dt, sec)
# simulate response to this current range and save
V_m_rheo = Cb_stellate(V_init * np.ones((stim_num_rheo)), g_effect, E2, I_in_rheo, dt, currents_included2,
stim_time, stim_num_rheo, C, shift2, scale2, b_param_effect, slope_shift2,
np.zeros((len(b_param), stim_num_rheo)),
np.zeros((len(currents_included), stim_num_rheo)), ind_dict)
f['data'].create_dataset('V_m_rheo', data=V_m_rheo, dtype='float64', compression="gzip", compression_opts=9)
# run AP detection
stim_start = np.int(initial_period * 1 / dt)
for stim in range(I_in_rheo.shape[1]):
ap_all, ap_prop = scipy.signal.find_peaks(V_m_rheo[stim, stim_start:], min_spike_height,
prominence=prominence, distance=1 * 1 / dt)
analysis['spike_times_rheo'][stim] = ap_all * dt
if analysis['spike_times_rheo'][stim].size == 0:
analysis['AP_rheo'][stim] = False
else:
analysis['AP_rheo'][stim] = True
# find rheobase as smallest current step to elicit AP and save
analysis['rheobase'][:] = I_in_rheo[-1, np.argwhere(analysis['AP_rheo'][:] == True)[0][0]] * 1000
# AUC
# find rheobase of steady state firing (F_inf)
with h5py.File(fname, "a") as f:
F_inf = f['analysis']['F_inf'][:]
try:
# setup current range to be in current step between no and start of steady state firing
F_inf_start_ind = np.argwhere(F_inf != 0)[0][0]
dI = (high - low) / stim_num
I_start = I_mag[F_inf_start_ind - 1]
I_end = I_mag[F_inf_start_ind]
I_rel = np.arange(I_start, I_end + (I_end - I_start) / 100, (I_end - I_start) / 100)
I_rel = np.reshape(I_rel, (1, I_rel.shape[0]))
I_in = np.zeros((stim_time + np.int(initial_period * 1 / dt), 1)) @ I_rel
I_in[np.int(initial_period * 1 / dt):, :] = np.ones((stim_time, 1)) @ I_rel
stim_num = I_in.shape[1]
# simulate response to this current step range
V_m_inf_rheo = Cb_stellate(V_init * np.ones(stim_num), g_effect, E2, I_in, dt, currents_included2,
stim_time, stim_num, C, shift2, scale2, b_param_effect, slope_shift2,
np.zeros((len(b_param), stim_num)), np.zeros((len(currents_included), stim_num)),
ind_dict)
# save response, analyse and save
for i in np.array(['spike_times_Finf', 'ISI_Finf', 'Freq_Finf']):
f['analysis'].require_dataset(i, shape=(I_rel.shape[1],), dtype=dtyp, compression="gzip",
compression_opts=9)
f['analysis'].require_dataset('F_inf_Finf', shape=(I_rel.shape[1],), dtype='float64')
f['analysis'].require_dataset('F_null_Finf', shape=(I_rel.shape[1],), dtype='float64')
for stim in range(I_rel.shape[1]):
# spike peak detection
ap_all, ap_prop = scipy.signal.find_peaks(V_m_inf_rheo[stim, stim_start:], min_spike_height,
prominence=prominence, distance=1 * 1 / dt)
f['analysis']['spike_times_Finf'][stim] = ap_all * dt
f['analysis']['ISI_Finf'][stim] = np.array(
[x - f['analysis']['spike_times_Finf'][stim][i - 1] if i else None for i, x in
enumerate(f['analysis']['spike_times_Finf'][stim])][1:]) # msec
f['analysis']['Freq_Finf'][stim] = 1 / (f['analysis']['ISI_Finf'][stim] / 1000)
if f['analysis']['Freq_Finf'][stim].size != 0:
last_second_spikes = f['analysis']['spike_times_Finf'][stim] > np.int(
f['data'].attrs['stim_time'] * dt - (500 + f['data'].attrs['initial_period']))
if np.any(last_second_spikes == True):
last_second_spikes_1 = np.delete(last_second_spikes, 0) # remove first spike because it has no ISI/freq
f['analysis']['F_inf_Finf'][stim] = np.mean(
f['analysis']['Freq_Finf'][stim][last_second_spikes_1])
else:
f['analysis']['F_null_Finf'][stim] = 0
f['analysis']['F_inf_Finf'][stim] = 0
# find AUC relative to F_inf rheobase
# setup current inputs with current range around F_inf rheobase
I_first_inf = I_rel[0, np.argwhere(f['analysis']['F_inf_Finf'][:] != 0)[0][0]]
I_start = I_first_inf - 0.00005
I_end = I_first_inf + desired_AUC_width * high
I_rel2 = np.arange(I_start, I_end + (I_end - I_start) / 200, (I_end - I_start) / 200)
I_rel2 = np.reshape(I_rel2, (1, I_rel2.shape[0]))
I_in2 = np.zeros((stim_time + np.int(initial_period * 1 / dt), 1)) @ I_rel2
I_in2[np.int(initial_period * 1 / dt):, :] = np.ones((stim_time, 1)) @ I_rel2
stim_num = I_in2.shape[1]
# simulate response to this current step range
V_m_AUC = Cb_stellate(V_init * np.ones(stim_num), g_effect, E2, I_in2, dt, currents_included2, stim_time,
stim_num, C, shift2, scale2, b_param_effect, slope_shift2,
np.zeros((len(b_param), stim_num)), np.zeros((len(currents_included), stim_num)),
ind_dict)
# save data and analysis for this current step range including AUC
f['data'].require_dataset('V_m_AUC', shape=V_m_AUC.shape, dtype='float64')
f['data']['V_m_AUC'][:] = V_m_AUC
dtyp = h5py.special_dtype(vlen=np.dtype('float64'))
for i in np.array(['spike_times_Finf_AUC', 'ISI_Finf_AUC', 'Freq_Finf_AUC']): # analysis_names:
f['analysis'].require_dataset(i, shape=(I_rel2.shape[1],), dtype=dtyp, compression="gzip",
compression_opts=9)
f['analysis'].require_dataset('F_inf_Finf_AUC', shape=(I_rel2.shape[1],), dtype='float64')
f['analysis'].require_dataset('F_null_Finf_AUC', shape=(I_rel2.shape[1],), dtype='float64')
for stim in range(I_rel2.shape[1]):
# spike peak detection
ap_all, ap_prop = scipy.signal.find_peaks(V_m_AUC[stim, stim_start:], min_spike_height,
prominence=prominence, distance=1 * 1 / dt)
f['analysis']['spike_times_Finf_AUC'][stim] = ap_all * dt
f['analysis']['ISI_Finf_AUC'][stim] = np.array(
[x - f['analysis']['spike_times_Finf_AUC'][stim][i - 1] if i else None for i, x in
enumerate(f['analysis']['spike_times_Finf_AUC'][stim])][1:]) # msec
f['analysis']['Freq_Finf_AUC'][stim] = 1 / (f['analysis']['ISI_Finf_AUC'][stim] / 1000)
if f['analysis']['Freq_Finf_AUC'][stim].size != 0:
last_second_spikes = f['analysis']['spike_times_Finf_AUC'][stim] > np.int(
f['data'].attrs['stim_time'] * dt - (500 + f['data'].attrs['initial_period']))
if np.any(last_second_spikes == True):
last_second_spikes_1 = np.delete(last_second_spikes, 0) # remove first spike because it has no ISI/freq
f['analysis']['F_inf_Finf_AUC'][stim] = np.mean(
f['analysis']['Freq_Finf_AUC'][stim][last_second_spikes_1])
else:
f['analysis']['F_null_Finf_AUC'][stim] = 0
f['analysis']['F_inf_Finf_AUC'][stim] = 0
f['analysis'].require_dataset('AUC_rel_acc', shape=(1,), dtype='float64', compression="gzip",
compression_opts=9)
f['analysis']['AUC_rel_acc'][:] = np.trapz(f['analysis']['F_inf_Finf_AUC'][:],
I_rel2[:] * 1000, dI * 1000) # AUC
except:
f['analysis'].require_dataset('AUC_rel_acc', shape=(1,), dtype='float64', compression="gzip",
compression_opts=9)
f['analysis']['AUC_rel_acc'][:] = 0 # AUC
print('exception', f['analysis']['AUC_rel_acc'][()])
# ramp protocol #####################
# setup ramp current
sec = 4
ramp_len = np.int(sec *1000 *1/dt)
stim_time = ramp_len *2
I_amp = np.array([0, -0.000001])
I_amp = np.reshape(I_amp, (1,I_amp.shape[0]))
I_step = np.zeros((stim_time + np.int(initial_period * 1 / dt), 1))@ I_amp
I_step[np.int(initial_period * 1 / dt):, :] = np.ones((stim_time, 1)) @ I_amp
stim_num_step = I_step.shape[1]
start = np.int(initial_period * 1 / dt)
I_step[start:np.int(start+ramp_len),0] = np.linspace(0, high, ramp_len)
I_step[np.int(start + ramp_len):np.int(start + ramp_len*2),0] = np.linspace(high, 0, ramp_len)
stim_time_step = I_step.shape[0]
# simulate response to ramp
V_m_step = Cb_stellate(-70 * np.ones(stim_num_step), g_effect, E2, I_step, dt, currents_included2, stim_time_step,
stim_num_step, C, shift2, scale2, b_param_effect, slope_shift2,
np.zeros((len(b_param), stim_num_step)), np.zeros((len(currents_included), stim_num_step)),
ind_dict)
# spike peak detection
ap_all, ap_prop = scipy.signal.find_peaks(V_m_step[0, stim_start:], min_spike_height,
prominence=prominence, distance=1 * 1 / dt)
# save ramp firing properties
with h5py.File(fname, "a") as f:
f['data'].create_dataset('V_m_ramp', data=V_m_step, dtype='float64', compression="gzip", compression_opts=9)
if ap_all.shape[0] != 0:
if ap_all[0] < stim_start + ramp_len:
f['analysis'].create_dataset('ramp_I_up', data =I_step[stim_start+ap_all[0], 0] *1000, dtype='float64')
else:
f['analysis'].create_dataset('ramp_I_up', data =np.NaN, dtype='float64')
if ap_all[-1] > stim_start + ramp_len:
f['analysis'].create_dataset('ramp_I_down', data =I_step[stim_start+ap_all[-1], 0]*1000, dtype='float64')
else:
f['analysis'].create_dataset('ramp_I_down', data =np.NaN, dtype='float64')
f['analysis'].create_dataset('hysteresis', data =f['analysis']['ramp_I_down'][()] - f['analysis']['ramp_I_up'][()], dtype='float64')
else: # if no spikes in response to ramp
f['analysis'].create_dataset('ramp_I_up', data =np.NaN, dtype='float64')
f['analysis'].create_dataset('ramp_I_down', data =np.NaN, dtype='float64')
f['analysis'].create_dataset('hysteresis', data =np.NaN, dtype='float64')
#########################################
if f.__bool__():
f.close()
gc.collect()
def SA_Cb_stellate(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, folder, high, low, number_steps, initial_period,
sec, lin_array, log_array, alt_types, alt_ind, alt):
""" Sensitivity analysis for Cb Stellate model
Parameters
----------
V_init : float
Initial membrane potential
g : dict
maximal conductance for currents
E : dict
Reversal potentials for currents
I_in : array
Current stimulus input to model
dt : float
fixed time step
currents_included : dict
Boolean to include current in simulation or not
stim_time :
length of stimulus ()
stim_num : int
number of different stimulus currents
C : float
membrane capacitance
shift : dict
for each gating parameter
scale : dict
for each gating parameter
b_param : dict
Boltzmann parameter values for each gating parameter
slope_shift : dict
for each gating parameter
gating : array
array of gating values over time
current : array
array of current values over time
prominence: float
required spike prominence
desired_AUC_width: float
width of AUC from rheobase to rheobase + desired_AUC_width
folder : str
folder to save hdf5 in
high : float
upper current step magnitude
low : float
lowest current step magnitude
number_steps : int
number of current steps between low and high
initial_period: float
length of I = 0 before current step
sec : float
length of current step in seconds
lin_array : array
array of linear shifts from -10 tp 10
log_array : array
array of log2 values from -1 to 1
alt_types : array
array of arrays of strings of [variable, alteration type]
alt_ind : int
index for alt_type
alt :
index for lin_array of log_array
Returns
-------
saves hdf5 file to folder
"""
# setup for simulation
g_multi = copy.deepcopy(g)
E_multi = copy.deepcopy(E)
b_param_multi = copy.deepcopy(b_param)
shift_multi = copy.deepcopy(shift)
scale_multi = copy.deepcopy(scale)
slope_shift_multi = copy.deepcopy(slope_shift)
currents_included_multi = copy.deepcopy(currents_included)
gating2 = copy.deepcopy(gating)
current2 = copy.deepcopy(current)
g2 = Dict.empty(key_type=types.unicode_type, value_type=types.float64, )
for k, v in g_multi.items():
g2[k] = v
b_param2 = Dict.empty(key_type=types.unicode_type, value_type=types.float64[:], )
for k, v in b_param_multi.items():
b_param2[k] = np.array(v)
shift2 = Dict.empty(key_type=types.unicode_type, value_type=types.float64, )
for k, v in shift_multi.items():
shift2[k] = v
scale2 = Dict.empty(key_type=types.unicode_type, value_type=types.float64, )
for k, v in scale_multi.items():
scale2[k] = v
slope_shift2 = Dict.empty(key_type=types.unicode_type, value_type=types.float64, )
for k, v in slope_shift_multi.items():
slope_shift2[k] = v
E2 = Dict.empty(key_type=types.unicode_type, value_type=types.float64, )
for k, v in E_multi.items():
E2[k] = v
currents_included2 = Dict.empty(key_type=types.unicode_type, value_type=types.boolean, )
for k, v in currents_included_multi.items():
currents_included2[k] = v
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'n_A', 'h_A', 'n_A_mut', 'h_A_mut', 'm_T', 'h_T']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'A', 'A_mut', 'T', 'Leak']):
ind_dict[var] = i
i += 1
# alteration to gating ##########################################################################
if alt_types[alt_ind, 1] == 'shift':
shift2[alt_types[alt_ind, 0]] = lin_array[alt]
fname = os.path.join(folder,
"{}_{}_{}.hdf5".format(alt_types[alt_ind, 1], alt_types[alt_ind, 0], lin_array[alt]))
elif alt_types[alt_ind, 1] == 'slope':
b_param2[alt_types[alt_ind, 0]][1] = b_param2[alt_types[alt_ind, 0]][1] * log_array[alt]
fname = os.path.join(folder,
"{}_{}_{}.hdf5".format(alt_types[alt_ind, 1], alt_types[alt_ind, 0],
np.int(np.around(log_array[alt], 2) * 100)))
if b_param2[alt_types[alt_ind, 0]][2] != 1:
# adjust slope_shift to account for slope not changing (rotating) around 0.5
V_test = np.arange(-150, 100, 0.001)
if b_param2[alt_types[alt_ind, 0]].shape[0] == 4:
steady_state = ((1 - b_param2[alt_types[alt_ind, 0]][3]) / (
1 + np.exp(
(V_test - b_param2[alt_types[alt_ind, 0]][0]) / b_param2[alt_types[alt_ind, 0]][1])) +
b_param2[alt_types[alt_ind, 0]][3]) ** b_param2[alt_types[alt_ind, 0]][2]
orig = ((1 - b_param[alt_types[alt_ind, 0]][3]) / (
1 + np.exp((V_test - b_param[alt_types[alt_ind, 0]][0]) / b_param[alt_types[alt_ind, 0]][1])) +
b_param[alt_types[alt_ind, 0]][3]) ** b_param[alt_types[alt_ind, 0]][2]
else:
steady_state = (1 / (1 + np.exp(
(V_test - b_param2[alt_types[alt_ind, 0]][0]) / b_param2[alt_types[alt_ind, 0]][1]))) ** \
b_param2[alt_types[alt_ind, 0]][2]
orig = (1 / (1 + np.exp(
(V_test - b_param[alt_types[alt_ind, 0]][0]) / b_param[alt_types[alt_ind, 0]][1]))) ** \
b_param[alt_types[alt_ind, 0]][2]
orig_V_half = V_test[(np.abs(orig - 0.5)).argmin()]
V_half_new = V_test[(np.abs(steady_state - 0.5)).argmin()]
slope_shift2[alt_types[alt_ind, 0]] = orig_V_half - V_half_new
elif alt_types[alt_ind, 1] == 'g':
g2[alt_types[alt_ind, 0]] = g2[alt_types[alt_ind, 0]] * log_array[alt]
fname = os.path.join(folder, "{}_{}_{}.hdf5".format(alt_types[alt_ind, 1], alt_types[alt_ind, 0],
np.int(np.around(log_array[alt], 2) * 100)))
###########################################################################
# initial simulation for current range from low to high
V_m = Cb_stellate(V_init * np.ones((stim_num)), g2, E2, I_in, dt, currents_included2, stim_time, stim_num, C,
shift2, scale2, b_param2, slope_shift2, gating2, current2, ind_dict)
stim_start = np.int(initial_period * 1 /dt)
min_spike_height = V_m[0, stim_start] + prominence
# create hdf5 file and save data and metadata
with h5py.File(fname, "a") as f:
data = f.create_group("data")
data.create_dataset('V_m', data=V_m, dtype='float64', compression="gzip", compression_opts=9)
metadata = {'I_high': high, 'I_low': low, 'stim_num': number_steps, 'stim_time': stim_time, 'sec': sec, 'dt': dt,
'initial_period': initial_period, 'g': json.dumps(dict(g2)), 'E': json.dumps(dict(E2)), 'C': C,
'V_init': V_init, 'ind_dict': json.dumps(dict(ind_dict)),
'b_param': json.dumps(dict(b_param2), cls=NumpyEncoder),
'currents': json.dumps(dict(currents_included2)), 'shift': json.dumps(dict(shift2)),
'var_change': str(alt_types[alt_ind, 1]), 'var': str(alt_types[alt_ind, 0]),
'scale': json.dumps(dict(scale2)), 'slope_shift': json.dumps(dict(slope_shift2)),
'prominence': prominence, 'desired_AUC_width': desired_AUC_width,
'alteration_info': str(alt_types[alt_ind, :]), 'alt_index': str(alt),
'min_spike_height': min_spike_height, }
data.attrs.update(metadata)
if alt_types[alt_ind, 1] == 'shift':
meta2 = {'alteration': lin_array[alt]}
else:
meta2 = {'alteration': log_array[alt]}
data.attrs.update(meta2)
# firing frequency analysis and rheobase
with h5py.File(fname, "r+") as f:
I_mag = np.arange(low, high, (high - low) / stim_num)
analysis = f.create_group("analysis")
dtyp = h5py.special_dtype(vlen=np.dtype('float64'))
for i in np.array(['spike_times', 'spike_times_rheo', 'ISI', 'Freq']):
analysis.create_dataset(i, (I_mag.shape[0],), dtype=dtyp, compression="gzip", compression_opts=9)
analysis.create_dataset('F_inf', (I_mag.shape[0],), dtype='float64')
analysis.create_dataset('F_null', (I_mag.shape[0],), dtype='float64')
analysis.create_dataset('AP', (I_mag.shape[0],), dtype='bool', compression="gzip", compression_opts=9)
analysis.create_dataset('AP_rheo', (I_mag.shape[0],), dtype='bool', compression="gzip", compression_opts=9)
for i in np.array(['rheobase']):
analysis.create_dataset(i, (1,), dtype='float64', compression="gzip", compression_opts=9)
try:
for stim in range(I_mag.shape[0]):
# spike detection
ap_all, ap_prop = scipy.signal.find_peaks(V_m[stim, stim_start:], min_spike_height,
prominence=prominence, distance=1 * 1 / dt)
analysis['spike_times'][stim] = ap_all * dt
if analysis['spike_times'][stim].size == 0:
analysis['AP'][stim] = False
else:
analysis['AP'][stim] = True
analysis['ISI'][stim] = np.array([x - analysis['spike_times'][stim][i - 1] if i else None for i, x in
enumerate(analysis['spike_times'][stim])][1:]) # msec
analysis['Freq'][stim] = 1 / (analysis['ISI'][stim] / 1000)
if analysis['Freq'][stim].size != 0:
#####################################################################################################################################################
analysis['F_null'][stim] = analysis['Freq'][stim][0]
if np.argwhere(ap_all >= 1000 * 1 / dt).shape[0] != 0: # if first spike is after 1 ms
half_second_spikes = np.logical_and(analysis['spike_times'][stim] < np.int(
ap_all[np.argwhere(ap_all >= 1000 * 1 / dt)[0][0]] * dt + 500),
analysis['spike_times'][stim] > np.int(
ap_all[np.argwhere(ap_all >= 1000 * 1 / dt)[0][
0]] * dt)) # spikes in half second window
if np.sum(half_second_spikes == True) > 1:
half_second_spikes_1 = np.delete(half_second_spikes,
np.argwhere(half_second_spikes == True)[0][0])
analysis['F_inf'][stim] = np.mean(analysis['Freq'][stim][half_second_spikes_1])
else:
analysis['F_inf'][stim] = 0
else:
analysis['F_inf'][stim] = 0
else: # if no ISI detected
analysis['F_null'][stim] = 0
analysis['F_inf'][stim] = 0
except:
print(alt_types[alt_ind, 0], alt_types[alt_ind, 1], alt, 'Freq analysis unsuccessful')
# rheobase
# find where the first AP occurs
if np.any(analysis['AP'][:] == True):
# setup current range to be between the current step before and with first AP
I_first_spike = I_mag[np.argwhere(analysis['AP'][:] == True)[0][0]]
I_before_spike = I_mag[np.argwhere(analysis['AP'][:] == True)[0][0] - 1]
analysis.create_dataset('I_first_spike', data=I_first_spike, dtype='float64')
analysis.create_dataset('I_before_spike', data=I_before_spike, dtype='float64')
number_steps_rheo = 100
stim_time, I_in_rheo, stim_num_rheo, V_m_rheo = stimulus_init(I_before_spike, I_first_spike,
number_steps_rheo, initial_period,
dt, sec)
# simulate response to this current range and save
V_m_rheo = Cb_stellate(V_init * np.ones((stim_num_rheo)), g2, E2, I_in_rheo, dt, currents_included2,
stim_time, stim_num_rheo, C, shift2, scale2, b_param2, slope_shift2,
np.zeros((len(b_param), stim_num_rheo)),
np.zeros((len(currents_included), stim_num_rheo)), ind_dict)
# run AP detection
try:
# stim_start = np.int(initial_period * 1 / dt)
for stim in range(I_in_rheo.shape[1]): # range(stim_num):
ap_all, ap_prop = scipy.signal.find_peaks(V_m_rheo[stim, stim_start:], min_spike_height,
prominence=prominence, distance=1 * 1 / dt)
analysis['spike_times_rheo'][stim] = ap_all * dt
if analysis['spike_times_rheo'][stim].size == 0:
analysis['AP_rheo'][stim] = False
else:
analysis['AP_rheo'][stim] = True
except:
print(alt_types[alt_ind, 0], alt_types[alt_ind, 1], alt, 'RHEOBASE NO AP')
# find rheobase as smallest current step to elicit AP and save
analysis['rheobase'][:] = I_in_rheo[-1, np.argwhere(analysis['AP_rheo'][:] == True)[0][0]] * 1000
# AUC
# find rheobase of steady state firing (F_inf)
with h5py.File(fname, "a") as f:
F_inf = f['analysis']['F_inf'][:]
try:
# setup current range to be in current step between no and start of steady state firing
F_inf_start_ind = np.argwhere(F_inf != 0)[0][0]
dI = (high - low) / stim_num
I_start = I_mag[F_inf_start_ind - 1]
I_end = I_mag[F_inf_start_ind]
I_rel = np.arange(I_start, I_end + (I_end - I_start) / 100, (I_end - I_start) / 100)
I_rel = np.reshape(I_rel, (1, I_rel.shape[0]))
I_in = np.zeros((stim_time + np.int(initial_period * 1 / dt), 1)) @ I_rel
I_in[np.int(initial_period * 1 / dt):, :] = np.ones((stim_time, 1)) @ I_rel
stim_num = I_in.shape[1]
# simulate response to this current step range
V_m_inf_rheo = Cb_stellate(V_init * np.ones(stim_num), g2, E2, I_in, dt, currents_included2, stim_time,
stim_num, C, shift2, scale2, b_param2, slope_shift2,
np.zeros((len(b_param), stim_num)), np.zeros((len(currents_included), stim_num)),
ind_dict)
# save response, analyse and save
for i in np.array(['spike_times_Finf', 'ISI_Finf', 'Freq_Finf']):
f['analysis'].require_dataset(i, shape=(I_rel.shape[1],), dtype=dtyp, compression="gzip",
compression_opts=9)
f['analysis'].require_dataset('F_inf_Finf', shape=(I_rel.shape[1],), dtype='float64')
f['analysis'].require_dataset('F_null_Finf', shape=(I_rel.shape[1],), dtype='float64')
for stim in range(I_rel.shape[1]):
# spike peak detection
ap_all, ap_prop = scipy.signal.find_peaks(V_m_inf_rheo[stim, stim_start:], min_spike_height,
prominence=prominence, distance=1 * 1 / dt)
f['analysis']['spike_times_Finf'][stim] = ap_all * dt
f['analysis']['ISI_Finf'][stim] = np.array(
[x - f['analysis']['spike_times_Finf'][stim][i - 1] if i else None for i, x in
enumerate(f['analysis']['spike_times_Finf'][stim])][1:]) # msec
f['analysis']['Freq_Finf'][stim] = 1 / (f['analysis']['ISI_Finf'][stim] / 1000)
if f['analysis']['Freq_Finf'][stim].size != 0:
if np.argwhere(ap_all >= 1000 * 1 / dt).shape[0] != 0: # if first spike is after 1 ms
half_second_spikes = np.logical_and(f['analysis']['spike_times_Finf'][stim] < np.int(
ap_all[np.argwhere(ap_all >= 1000 * 1 / dt)[0][0]] * dt + 500),
f['analysis']['spike_times_Finf'][stim] > np.int(
ap_all[np.argwhere(ap_all >= 1000 * 1 / dt)[0][0]] * dt)) # spikes in half second window
if np.sum(half_second_spikes == True) > 1:
half_second_spikes_1 = np.delete(half_second_spikes,
np.argwhere(half_second_spikes == True)[0][0]) # remove first spike because it has no ISI/freq
f['analysis']['F_inf_Finf'][stim] = np.mean(
f['analysis']['Freq_Finf'][stim][half_second_spikes_1])
else:
f['analysis']['F_inf_Finf'][stim] = 0
else:
f['analysis']['F_null_Finf'][stim] = 0
f['analysis']['F_inf_Finf'][stim] = 0
else:
f['analysis']['F_null_Finf'][stim] = 0
f['analysis']['F_inf_Finf'][stim] = 0
# find AUC relative to F_inf rheobase
# setup current inputs with current range around F_inf rheobase
I_first_inf = I_rel[0, np.argwhere(f['analysis']['F_inf_Finf'][:] != 0)[0][0]]
I_start = I_first_inf - 0.00005
I_end = I_first_inf + 0.2 * high
I_rel2 = np.arange(I_start, I_end + (I_end - I_start) / 100, (I_end - I_start) / 100)
I_rel2 = np.reshape(I_rel2, (1, I_rel2.shape[0]))
I_in2 = np.zeros((stim_time + np.int(initial_period * 1 / dt), 1)) @ I_rel2
I_in2[np.int(initial_period * 1 / dt):, :] = np.ones((stim_time, 1)) @ I_rel2
stim_num = I_in2.shape[1]
# simulate response to this current step range
V_m_AUC = Cb_stellate(V_init * np.ones(stim_num), g2, E2, I_in2, dt, currents_included2, stim_time,
stim_num, C, shift2, scale2, b_param2, slope_shift2,
np.zeros((len(b_param), stim_num)), np.zeros((len(currents_included), stim_num)),
ind_dict)
# save data and analysis for this current step range including AUC
f['data'].require_dataset('V_m_AUC', shape=V_m_AUC.shape, dtype='float64')
f['data']['V_m_AUC'][:] = V_m_AUC
dtyp = h5py.special_dtype(vlen=np.dtype('float64'))
for i in np.array(['spike_times_Finf_AUC', 'ISI_Finf_AUC', 'Freq_Finf_AUC']): # analysis_names:
f['analysis'].require_dataset(i, shape=(I_rel2.shape[1],), dtype=dtyp, compression="gzip",
compression_opts=9)
f['analysis'].require_dataset('F_inf_Finf_AUC', shape=(I_rel2.shape[1],), dtype='float64')
f['analysis'].require_dataset('F_null_Finf_AUC', shape=(I_rel2.shape[1],), dtype='float64')
for stim in range(I_rel2.shape[1]):
# spike peak detection
ap_all, ap_prop = scipy.signal.find_peaks(V_m_AUC[stim, stim_start:], min_spike_height,
prominence=prominence, distance=1 * 1 / dt)
f['analysis']['spike_times_Finf_AUC'][stim] = ap_all * dt
f['analysis']['ISI_Finf_AUC'][stim] = np.array(
[x - f['analysis']['spike_times_Finf_AUC'][stim][i - 1] if i else None for i, x in
enumerate(f['analysis']['spike_times_Finf_AUC'][stim])][1:]) # msec
f['analysis']['Freq_Finf_AUC'][stim] = 1 / (f['analysis']['ISI_Finf_AUC'][stim] / 1000)
if f['analysis']['Freq_Finf_AUC'][stim].size != 0:
if np.argwhere(ap_all >= 1000 * 1 / dt).shape[0] != 0: # if first spike is after 1 ms
half_second_spikes = np.logical_and(f['analysis']['spike_times_Finf_AUC'][stim] < np.int(
ap_all[np.argwhere(ap_all >= 1000 * 1 / dt)[0][0]] * dt + 500),
f['analysis']['spike_times_Finf_AUC'][stim] > np.int(
ap_all[np.argwhere(ap_all >= 1000 * 1 / dt)[0][
0]] * dt)) # spikes in half second window
if np.sum(half_second_spikes == True) > 1:
half_second_spikes_1 = np.delete(half_second_spikes,
np.argwhere(half_second_spikes == True)[0][0]) # remove first spike because it has no ISI/freq
f['analysis']['F_inf_Finf_AUC'][stim] = np.mean(
f['analysis']['Freq_Finf_AUC'][stim][half_second_spikes_1])
else:
f['analysis']['F_inf_Finf_AUC'][stim] = 0
else:
f['analysis']['F_null_Finf_AUC'][stim] = 0
f['analysis']['F_inf_Finf_AUC'][stim] = 0
else:
f['analysis']['F_null_Finf_AUC'][stim] = 0
f['analysis']['F_inf_Finf_AUC'][stim] = 0
f['analysis'].require_dataset('AUC', shape=(1,), dtype='float64', compression="gzip",
compression_opts=9)
f['analysis']['AUCc'][:] = np.trapz(f['analysis']['F_inf_Finf_AUC'][:],
I_rel2[:] * 1000, dI * 1000)
except:
f['analysis'].require_dataset('AUC', shape=(1,), dtype='float64', compression="gzip",
compression_opts=9)
f['analysis']['AUC'][:] = 0
if f.__bool__():
f.close()
gc.collect()

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,144 +0,0 @@
"""
General functions used throughout simulation scripts
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import json
import numpy as np
from numba import njit
@njit
def sqrt_log(x, *p):
""" Function of sum of square root and logarithmic function to fit to fI curves
Parameters
----------
x : array
input x value
*p : array
parameters for function
Returns
-------
p[0] * np.sqrt(x + p[1]) + p[2] * np.log(x + (p[1] + 1)) + p[3]
"""
return p[0] * np.sqrt(x + p[1]) + p[2] * np.log(x + (p[1] + 1)) + p[3]
@njit
def capacitance(diam, C_m):
""" calculate the capacitance of a cell's membrane give the diameter
Parameters
----------
diam: float
diameter of spherical cell body
C_m: float
specific membrane capacitance of cell
Returns
-------
capacitance: float
capacitance of cell
surf_area: flaot
surface area of cell
"""
r = diam * 1E-4 / 2 # cm
l = r
surf_area = 2 * np.pi * r ** 2 + 2 * np.pi * r * l # cm^2
C = C_m * surf_area # uF
return (C, surf_area)
@njit
def stimulus_init(low, high, number_steps, initial_period, dt, sec):
""" initiation of stimulus pulse from stimulus magnitudes I_in_mag
Parameters
----------
low : float
lowest current step magnitude
high : float
upper current step magnitude
number_steps : int
number of current steps between low and high
initial_period : float
length of I=0 before current step
dt : float
time step
sec:
length of current step in seconds
Returns
-------
stim_time: float
length of I_in in samples
I_in: array
I input array
stim_num: int
number of current steps
V_m: array
membrane potential array initialization of shape:(stim_num, stim_time)
"""
stim_time = np.int(1000 * 1 / dt * sec) # 1000 msec/sec * 1/dt
I_in_mag = np.arange(low, high, (high - low) / number_steps)
I_in_mag = np.reshape(I_in_mag, (1, I_in_mag.shape[0]))
I_in = np.zeros((stim_time + np.int(initial_period * 1 / dt), 1)) @ I_in_mag
I_in[np.int(initial_period * 1 / dt):, :] = np.ones((stim_time, 1)) @ I_in_mag
stim_num = I_in.shape[1] # number of different currents injected
stim_time = stim_time + np.int(initial_period * 1 / dt)
V_m = np.zeros((stim_num, stim_time))
return stim_time, I_in, stim_num, V_m
class NumpyEncoder(json.JSONEncoder):
""" Special json encoder for numpy types """
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
def init_dict(variable):
""" Initialize dictionaries for simulations
Parameters
----------
variable : array
array of variable name strings to put in dicts
Returns
-------
shift : dict
with every variable name in variable = 0.
scale : dict
with every variable name in variable = 1.
slope_shift : dict
with every variable name in variable = 0.
E : dict
empty dictionary
currents_included : dict
empty dictionary
b_param : dict
with every variable name in variable = np.array of 2 zeros
g : dict
empty dictionary
"""
shift = {}
scale = {}
slope_shift = {}
b_param ={}
g = {}
E ={}
currents_included = {}
for var in variable:
shift[var] = 0.
scale[var] = 1.0
slope_shift[var] = 0.
b_param[var] = np.zeros(3, dtype=np.dtype('float64'))
return shift, scale, slope_shift, E, currents_included, b_param, g

View File

@ -1,114 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to simulate all KCNA1 mutations in Cb Stellate model
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import numpy as np
from joblib import Parallel, delayed
import json
import os
from numba import types
from numba.typed import Dict
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Cb_stellate_fxns import Cb_stellate_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.0015
number_steps = 200
initial_period = 1000
num_gating = 9
num_current = 6
C, surf_area = capacitance(61.4, 1.50148)
variable = np.array(['m', 'h', 'n', 'n_A', 'h_A', 'n_A_mut', 'h_A_mut', 'm_T', 'h_T'])
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'n_A', 'h_A','n_A_mut', 'h_A_mut', 'm_T', 'h_T']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-37., -3, 1])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-40., 4., 1., 0])
b_param['n'][:] = np.array([-23, -5, 1])
b_param['n_A'][:] = np.array([-27, -13.2, 1.])
b_param['h_A'][:] = np.array([-80., 6.5, 1.])
b_param['n_A_mut'][:] = np.array([-27, -13.2, 1.])
b_param['h_A_mut'][:] = np.array([-80., 6.5, 1.])
b_param['m_T'][:] = np.array([-50., -3, 1.])
b_param['h_T'][:] = np.array([-68., 3.75, 1.])
mut_act_Vhalf_wt = -30.01851851851851
mut_act_k_wt = -7.7333333333333325
s_diff_Vhalf = mut_act_Vhalf_wt - b_param['s'][0]
s_diff_k = mut_act_k_wt - b_param['s'][1]
b_param['s'][1] = b_param['s'][1] + s_diff_k
b_param['u'][1] = b_param['u'][1] + s_diff_k
b_param['s'][0] = b_param['s'][0] + s_diff_Vhalf
b_param['u'][0] = b_param['u'][0] + s_diff_Vhalf
b_param['s_mut'][1] = b_param['s_mut'][1] + s_diff_k
b_param['u_mut'][1] = b_param['u_mut'][1] + s_diff_k
b_param['s_mut'][0] = b_param['s_mut'][0] + s_diff_Vhalf
b_param['u_mut'][0] = b_param['u_mut'][0] + s_diff_Vhalf
# reversal potentials
E["Na"] = 55.
E["K"] = -80.
E["Ca"] = 22.
E["Leak"] = -70. # as per Molineux et al 2005 and NOT the -38 in Alexander et al 2019
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["A_mut"] = True
currents_included["A"] = True
currents_included["T"] = True
currents_included["Leak"] = True
# model conductances
g["Na"] = 3.4 * surf_area
g["Kd"] = 9.0556 * surf_area
g["A_mut"] = 15.0159 * surf_area * 0.5
g["A"] = 15.0159 * surf_area* 0.5
g["T"] = 0.45045 * surf_area
g["Leak"] = 0.07407 * surf_area
# save folder
folder = './KCNA1_mutations/Cb_stellate'
if not os.path.isdir(folder):
os.makedirs(folder)
#
# mutation properties
mutations = json.load(open("./KCNA1_mutations/mutations_effects_dict.json"))
# %%
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(Cb_stellate_mut)(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low, number_steps,
initial_period, sec) for mut in list(mutations.keys()))

View File

@ -1,123 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to simulate all KCNA1 mutations in Cb Stellate \Delta Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import numpy as np
from joblib import Parallel, delayed
import json
import os
from numba import types
from numba.typed import Dict
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Cb_stellate_fxns_Kv import Cb_stellate_Kv_mut
#%%
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.0015
number_steps = 200
initial_period = 1000
num_gating = 11
num_current = 7
C, surf_area = capacitance(61.4, 1.50148)
variable = np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut'])
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-37., -3, 1])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-40., 4., 1., 0])
b_param['n'][:] = np.array([-23, -5, 1])
b_param['n_A'][:] = np.array([-27, -13.2, 1.])
b_param['h_A'][:] = np.array([-80., 6.5, 1.])
b_param['m_T'][:] = np.array([-50., -3, 1.])
b_param['h_T'][:] = np.array([-68., 3.75, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
mut_act_Vhalf_wt = -30.01851851851851
mut_act_k_wt = -7.7333333333333325
s_diff_Vhalf = mut_act_Vhalf_wt - b_param['s'][0]
s_diff_k = mut_act_k_wt - b_param['s'][1]
b_param['s'][1] = b_param['s'][1] + s_diff_k
b_param['u'][1] = b_param['u'][1] + s_diff_k
b_param['s'][0] = b_param['s'][0] + s_diff_Vhalf
b_param['u'][0] = b_param['u'][0] + s_diff_Vhalf
b_param['s_mut'][1] = b_param['s_mut'][1] + s_diff_k
b_param['u_mut'][1] = b_param['u_mut'][1] + s_diff_k
b_param['s_mut'][0] = b_param['s_mut'][0] + s_diff_Vhalf
b_param['u_mut'][0] = b_param['u_mut'][0] + s_diff_Vhalf
# reversal potentials
E["Na"] = 55.
E["K"] = -80.
E["Ca"] = 22.
E["Leak"] = -70. # as per Molineux et al 2005 and NOT the -38 in Alexander et al 2019
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["A"] = False
currents_included["T"] = True
currents_included["Leak"] = True
# model conductances
g["Na"] = 34 * surf_area
g["Kd"] = 9.0556 * surf_area
if currents_included["Kv_mut"] == True:
g["Kv"] = 1.50159 / 2 * surf_area
else:
g["Kv"] = 1.50159 / 2 * surf_area * 2
g["Kv_mut"] = 1.50159 / 2 * surf_area
g["A"] = 0 * surf_area
g["T"] = 0.45045 * surf_area
g["Leak"] = 0.07407 * surf_area
# save folder
folder = './KCNA1_mutations/Cb_stellate_Delta_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
#
# mutation properties
mutations = json.load(open("./KCNA1_mutations/mutations_effects_dict.json"))
# %%
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(Cb_stellate_Kv_mut)(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale,
b_param, slope_shift, gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low,
number_steps, initial_period, sec) for mut in list(mutations.keys()))

View File

@ -1,122 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to simulate all KCNA1 mutations in Cb Stellate +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import numpy as np
from joblib import Parallel, delayed
import json
import os
from numba import types
from numba.typed import Dict
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Cb_stellate_fxns_Kv import Cb_stellate_Kv_mut
#%%
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.0015
number_steps = 200
initial_period = 1000
num_gating = 11
num_current = 7
C, surf_area = capacitance(61.4, 1.50148)
variable = np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut'])
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-37., -3, 1])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-40., 4., 1., 0])
b_param['n'][:] = np.array([-23, -5, 1])
b_param['n_A'][:] = np.array([-27, -13.2, 1.])
b_param['h_A'][:] = np.array([-80., 6.5, 1.])
b_param['m_T'][:] = np.array([-50., -3, 1.])
b_param['h_T'][:] = np.array([-68., 3.75, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
mut_act_Vhalf_wt = -30.01851851851851
mut_act_k_wt = -7.7333333333333325
s_diff_Vhalf = mut_act_Vhalf_wt - b_param['s'][0]
s_diff_k = mut_act_k_wt - b_param['s'][1]
b_param['s'][1] = b_param['s'][1] + s_diff_k
b_param['u'][1] = b_param['u'][1] + s_diff_k
b_param['s'][0] = b_param['s'][0] + s_diff_Vhalf
b_param['u'][0] = b_param['u'][0] + s_diff_Vhalf
b_param['s_mut'][1] = b_param['s_mut'][1] + s_diff_k
b_param['u_mut'][1] = b_param['u_mut'][1] + s_diff_k
b_param['s_mut'][0] = b_param['s_mut'][0] + s_diff_Vhalf
b_param['u_mut'][0] = b_param['u_mut'][0] + s_diff_Vhalf
# reversal potentials
E["Na"] = 55.
E["K"] = -80.
E["Ca"] = 22.
E["Leak"] = -70. # as per Molineux et al 2005 and NOT the -38 in Alexander et al 2019
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["A"] = True
currents_included["T"] = True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 3.4 * surf_area
g["Kd"] = 9.0556 * (1-Kv_ratio) * surf_area
g["Kv"] = 6. * Kv_ratio/2 * surf_area * (2 * int(currents_included["Kv_mut"] == False))
g["Kv_mut"] = 6. * Kv_ratio/2 * surf_area
g["A"] = 15.0159 * surf_area
g["T"] = 0.45045 * surf_area
g["Leak"] = 0.07407 * surf_area
# save folder
folder = './KCNA1_mutations/Cb_stellate_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
#
# mutation properties
mutations = json.load(open("./KCNA1_mutations/mutations_effects_dict.json"))
# %%
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(Cb_stellate_Kv_mut)(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low, number_steps,
initial_period, sec) for mut in list(mutations.keys()))

View File

@ -1,122 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to simulate all KCNA1 mutations in FS +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import numpy as np
import os
import json
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict, NumpyEncoder
from Code.Functions.Pospischil_fxns import Pospischil_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(56.9, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
tau_max_p = 502
V_init = -70
V_T = -57.9
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param = {}
b_param['m'] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.array([-34.51951036, 4.04059373, 1., 0.])
b_param['n'] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'] = np.array([-57.37, 20.98, 1.])
b_param['p'] = np.array([-45., -9.9998807337, 1.])
b_param['s'] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.array([-31., 5.256, 1., 0.245])
mut_act_Vhalf_wt = -30.01851851851851
mut_act_k_wt = -7.7333333333333325
s_diff_Vhalf = mut_act_Vhalf_wt - b_param['s'][0]
s_diff_k = mut_act_k_wt - b_param['s'][1]
b_param['s'][1] = b_param['s'][1] + s_diff_k
b_param['u'][1] = b_param['u'][1] + s_diff_k
b_param['s'][0] = b_param['s'][0] + s_diff_Vhalf
b_param['u'][0] = b_param['u'][0] + s_diff_Vhalf
b_param['s_mut'][1] = b_param['s_mut'][1] + s_diff_k
b_param['u_mut'][1] = b_param['u_mut'][1] + s_diff_k
b_param['s_mut'][0] = b_param['s_mut'][0] + s_diff_Vhalf
b_param['u_mut'][0] = b_param['u_mut'][0] + s_diff_Vhalf
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -70.4
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 58. * surf_area
g["Kd"] = 3.9 * (1 - Kv_ratio) * surf_area
g["M"] = 0.075 * surf_area
if currents_included["Kv_mut"] == True:
g["Kv"] = 3.9 * Kv_ratio / 2 * surf_area
else:
g["Kv"] = 3.9 * Kv_ratio / 2 * surf_area * 2
g["Kv_mut"] = 3.9 * Kv_ratio / 2 * surf_area
g["L"] = 0. * surf_area
g["Leak"] = 0.038 * surf_area
# save folder
folder = './KCNA1_mutations/FS_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
# mutation properties
mutations = json.load(open("./KCNA1_mutations/mutations_effects_dict.json"))
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(Pospischil_mut)(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift, scale,
b_param, slope_shift, gating, current, prominence, desired_AUC_width, mutations, mut, folder,
high, low, number_steps, initial_period, sec)
for mut in list(mutations.keys()))

View File

@ -1,129 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to simulate all KCNA1 mutations in RS Inhibitory +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import numpy as np
from joblib import Parallel, delayed
import os
import h5py
import json
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Pospischil_fxns import Pospischil_mut
# model parameters
tau_max_p = 608
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(61.8, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
tau_max_p = 934
V_init = -70
V_T = -67.9
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param = {}
b_param['m'] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.array([-34.51951036, 4.04059373, 1., 0.05])
b_param['n'] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'] = np.array([-57.37, 20.98, 1.0])
b_param['p'] = np.array([-45., -9.9998807337, 1.])
b_param['s'] = np.array([-14.16, -10.15, 1.0])
b_param['u'] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.array([-31., 5.256, 1., 0.245])
mut_act_Vhalf_wt = -30.01851851851851
mut_act_k_wt = -7.7333333333333325
s_diff_Vhalf = mut_act_Vhalf_wt - b_param['s'][0]
s_diff_k = mut_act_k_wt - b_param['s'][1]
b_param['s'][1] = b_param['s'][1] + s_diff_k
b_param['u'][1] = b_param['u'][1] + s_diff_k
b_param['s'][0] = b_param['s'][0] + s_diff_Vhalf
b_param['u'][0] = b_param['u'][0] + s_diff_Vhalf
b_param['s_mut'][1] = b_param['s_mut'][1] + s_diff_k
b_param['u_mut'][1] = b_param['u_mut'][1] + s_diff_k
b_param['s_mut'][0] = b_param['s_mut'][0] + s_diff_Vhalf
b_param['u_mut'][0] = b_param['u_mut'][0] + s_diff_Vhalf
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -56.2
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 10. * surf_area
g["Kd"] = 2.1 * (1 - Kv_ratio) * surf_area
g["M"] = 0.0098 * surf_area
if currents_included["Kv_mut"] == True:
g["Kv"] = 2.1 * Kv_ratio / 2 * surf_area
else:
g["Kv"] = 2.1 * Kv_ratio / 2 * surf_area * 2
g["Kv_mut"] = 2.1 * Kv_ratio / 2 * surf_area
g["L"] = 0. * surf_area
g["Leak"] = 0.0205 * surf_area
# save folder
folder = './KCNA1_mutations/RS_inhib_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
# mutation properties
mutations = json.load(open("./KCNA1_mutations/mutations_effects_dict.json"))
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(Pospischil_mut)(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift,
scale, b_param, slope_shift, gating, current, prominence, desired_AUC_width, mutations, mut,
folder, high, low, number_steps, initial_period, sec)
for mut in list(mutations.keys()))

View File

@ -1,123 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to simulate all KCNA1 mutations in RS Pyramidal +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import numpy as np
import os
import json
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Pospischil_fxns import Pospischil_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(61.4, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
tau_max_p = 608
V_init = -70
V_T = -56.2
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param = {}
b_param['m'] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.array([-34.51951036, 4.04059373, 1., 0.05])
b_param['n'] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'] = np.array([-57.37, 20.98, 1.0])
b_param['p'] = np.array([-45., -9.9998807337, 1.])
b_param['s'] = np.array([-14.16, -10.15, 1.0])
b_param['u'] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.array([-31., 5.256, 1., 0.245])
mut_act_Vhalf_wt = -30.01851851851851
mut_act_k_wt = -7.7333333333333325
s_diff_Vhalf = mut_act_Vhalf_wt - b_param['s'][0]
s_diff_k = mut_act_k_wt - b_param['s'][1]
b_param['s'][1] = b_param['s'][1] + s_diff_k
b_param['u'][1] = b_param['u'][1] + s_diff_k
b_param['s'][0] = b_param['s'][0] + s_diff_Vhalf
b_param['u'][0] = b_param['u'][0] + s_diff_Vhalf
b_param['s_mut'][1] = b_param['s_mut'][1] + s_diff_k
b_param['u_mut'][1] = b_param['u_mut'][1] + s_diff_k
b_param['s_mut'][0] = b_param['s_mut'][0] + s_diff_Vhalf
b_param['u_mut'][0] = b_param['u_mut'][0] + s_diff_Vhalf
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -70.3
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 56. * surf_area
g["Kd"] = 6. * (1 - Kv_ratio) * surf_area
g["M"] = 0.075 * surf_area
if currents_included["Kv_mut"] == True:
g["Kv"] = 6. * Kv_ratio / 2 * surf_area
else:
g["Kv"] = 6. * Kv_ratio / 2 * surf_area * 2
g["Kv_mut"] = 6. * Kv_ratio / 2 * surf_area
g["L"] = 0. * surf_area
g["Leak"] = 0.0205 * surf_area
# save folder
folder = './KCNA1_mutations/RS_pyramidal_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
# mutation properties
mutations = json.load(open("./KCNA1_mutations/mutations_effects_dict.json"))
# # %%
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(Pospischil_mut)(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift,
scale, b_param, slope_shift, gating, current, prominence, desired_AUC_width, mutations, mut,
folder, high, low, number_steps, initial_period, sec)
for mut in list(mutations.keys()))

View File

@ -1,110 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to simulate all KCNA1 mutations in STN model
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import numpy as np
from joblib import Parallel, delayed
import json
import os
from numba import types
from numba.typed import Dict
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.STN_fxns import STN_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.005
number_steps = 100
initial_period = 1000
num_gating = 15
num_current = 8
d = 61.4
r = d/2 * 10**-6 # radius in meters
vol = np.pi * r**3 # volume in liters
C, surf_area = capacitance(d, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'a', 'b', 'a_mut', 'b_mut', 'c', 'd1', 'd2', 'p', 'q', 'r', 'Ca_conc', 'E_Ca']))
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'] = np.array([-40., -1. , 1.])
b_param['h'] = np.zeros(4)
b_param['h'] = np.array([-45.5, 1. , 1., 0.05])
b_param['n'] = np.array([-41., -1., 1.])
b_param['p'] = np.array([-56., -1., 1.])
b_param['q'] = np.array([-85., 1., 1.])
b_param['r'] = np.array([0.17, -0.08, 1.])
b_param['a'] = np.array([-45., -14.7, 1.])
b_param['b'] = np.array([-90., 7.5, 1.])
b_param['a_mut'] = np.array([-45., -14.7, 1.])
b_param['b_mut'] = np.array([-90., 7.5, 1.])
b_param['c'] = np.array([-30.6, -5., 1.])
b_param['d1'] = np.array([-60, 7.5, 1.])
b_param['d2'] = np.array([0.1, 0.02, 1.])
# reversal potentials
E["Na"] = 60.
E["K"] = -90.
E["Leak"] = -60.
# model currents
currents_included["Na"] = True
currents_included["Kd"] =True
currents_included["L"] = True
currents_included["T"] = True
currents_included["Ca_K"] = True
currents_included["A"] =True
currents_included["A_mut"] =True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 49. * surf_area
g["Kd"] = 27. * (1-Kv_ratio)* surf_area
g["A"] = 5. * surf_area *0.5
g["A_mut"] = 5. * surf_area *0.5
g["L"] = 5. * surf_area
g["T"] = 5. * surf_area
g["Ca_K"] = 1 * surf_area
g["Leak"] = 0.035 * surf_area
V_init = -70
# save folder
folder = './KCNA1_mutations/STN'
if not os.path.isdir(folder):
os.makedirs(folder)
#
# mutation properties
mutations = json.load(open("./KCNA1_mutations/mutations_effects_dict.json"))
prominence = 50
desired_AUC_width = high/5
#%%
Parallel(n_jobs=8, verbose=9)(
delayed(STN_mut)(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low, number_steps,
initial_period, sec, vol) for mut in list(mutations.keys()))

View File

@ -1,132 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to simulate all KCNA1 mutations in STN \Delta Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import numpy as np
from joblib import Parallel, delayed
import json
import os
from numba import types
from numba.typed import Dict
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.STN_fxns_Kv import STN_Kv_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.005
number_steps = 100
initial_period = 1000
num_gating = 17
num_current = 9
d = 61.4
r = d/2 * 10**-6 # radius in meters
vol = np.pi * r**3 # volume in liters
C, surf_area = capacitance(d, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'a', 'b', 'c', 'd1', 'd2', 'p', 'q', 'r', 's', 'u', 's_mut', 'u_mut','Ca_conc', 'E_Ca']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'] = np.array([-40., -1. , 1.])
b_param['h'] = np.zeros(4)
b_param['h'] = np.array([-45.5, 1. , 1., 0.05])
b_param['n'] = np.array([-41., -1., 1.])
b_param['p'] = np.array([-56., -1., 1.])
b_param['q'] = np.array([-85., 1., 1.])
b_param['r'] = np.array([0.17, -0.08, 1.])
b_param['a'] = np.array([-45., -14.7, 1.])
b_param['b'] = np.array([-90., 7.5, 1.])
b_param['c'] = np.array([-30.6, -5., 1.])
b_param['d1'] = np.array([-60, 7.5, 1.])
b_param['d2'] = np.array([0.1, 0.02, 1.])
b_param['s'] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'] = np.array([-31., 5.256, 1., 0.245])
mut_act_Vhalf_wt = -30.01851851851851
mut_act_k_wt = -7.7333333333333325
s_diff_Vhalf = mut_act_Vhalf_wt - b_param['s'][0]
s_diff_k = mut_act_k_wt - b_param['s'][1]
b_param['s'][1] = b_param['s'][1] + s_diff_k
b_param['u'][1] = b_param['u'][1] + s_diff_k
b_param['s'][0] = b_param['s'][0] + s_diff_Vhalf
b_param['u'][0] = b_param['u'][0] + s_diff_Vhalf
b_param['s_mut'][1] = b_param['s_mut'][1] + s_diff_k
b_param['u_mut'][1] = b_param['u_mut'][1] + s_diff_k
b_param['s_mut'][0] = b_param['s_mut'][0] + s_diff_Vhalf
b_param['u_mut'][0] = b_param['u_mut'][0] + s_diff_Vhalf
# reversal potentials
E["Na"] = 60.
E["K"] = -90.
E["Leak"] = -60.
# model currents
currents_included["Na"] = True
currents_included["Kd"] =True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["L"] = True
currents_included["T"] = True
currents_included["Ca_K"] = True
currents_included["A"] =True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 49. * surf_area
g["Kd"] = 27. * (1-Kv_ratio)* surf_area
if currents_included["Kv_mut"]==True:
g["Kv"] = 27. * Kv_ratio/2 * surf_area
else:
g["Kv"] = 27. * Kv_ratio/2 * surf_area * 2
g["Kv_mut"] = 27. * Kv_ratio/2 * surf_area
g["A"] = 5. * surf_area
g["L"] = 5. * surf_area
g["T"] = 5. * surf_area
g["Ca_K"] = 1 * surf_area
g["Leak"] = 0.035 * surf_area
# save folder
folder = './KCNA1_mutations/STN_Delta_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
#
# mutation properties
mutations = json.load(open("./KCNA1_mutations/mutations_effects_dict.json"))
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(STN_Kv_mut)(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param,
slope_shift, gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low,
number_steps, initial_period, sec, vol) for mut in list(mutations.keys()))

View File

@ -1,132 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to simulate all KCNA1 mutations in STN +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import numpy as np
from joblib import Parallel, delayed
import json
import os
from numba import types
from numba.typed import Dict
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.STN_fxns_Kv import STN_Kv_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.005
number_steps = 100
initial_period = 1000
num_gating = 17
num_current = 9
d = 61.4
r = d/2 * 10**-6 # radius in meters
vol = np.pi * r**3 # volume in liters
C, surf_area = capacitance(d, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'a', 'b', 'c', 'd1', 'd2', 'p', 'q', 'r', 's', 'u', 's_mut', 'u_mut','Ca_conc', 'E_Ca']))
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'] = np.array([-40., -1. , 1.])
b_param['h'] = np.zeros(4)
b_param['h'] = np.array([-45.5, 1. , 1., 0.05])
b_param['n'] = np.array([-41., -1., 1.])
b_param['p'] = np.array([-56., -1., 1.])
b_param['q'] = np.array([-85., 1., 1.])
b_param['r'] = np.array([0.17, -0.08, 1.])
b_param['a'] = np.array([-45., -14.7, 1.])
b_param['b'] = np.array([-90., 7.5, 1.])
b_param['c'] = np.array([-30.6, -5., 1.])
b_param['d1'] = np.array([-60, 7.5, 1.])
b_param['d2'] = np.array([0.1, 0.02, 1.])
b_param['s'] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'] = np.array([-31., 5.256, 1., 0.245])
mut_act_Vhalf_wt = -30.01851851851851
mut_act_k_wt = -7.7333333333333325
s_diff_Vhalf = mut_act_Vhalf_wt - b_param['s'][0]
s_diff_k = mut_act_k_wt - b_param['s'][1]
b_param['s'][1] = b_param['s'][1] + s_diff_k
b_param['u'][1] = b_param['u'][1] + s_diff_k
b_param['s'][0] = b_param['s'][0] + s_diff_Vhalf
b_param['u'][0] = b_param['u'][0] + s_diff_Vhalf
b_param['s_mut'][1] = b_param['s_mut'][1] + s_diff_k
b_param['u_mut'][1] = b_param['u_mut'][1] + s_diff_k
b_param['s_mut'][0] = b_param['s_mut'][0] + s_diff_Vhalf
b_param['u_mut'][0] = b_param['u_mut'][0] + s_diff_Vhalf
# reversal potentials
E["Na"] = 60.
E["K"] = -90.
E["Leak"] = -60.
# model currents
currents_included["Na"] = True
currents_included["Kd"] =True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["L"] = True
currents_included["T"] = True
currents_included["Ca_K"] = True
currents_included["A"] =True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 49. * surf_area
g["Kd"] = 27. * (1-Kv_ratio)* surf_area
if currents_included["Kv_mut"]==True:
g["Kv"] = 27. * Kv_ratio/2 * surf_area
else:
g["Kv"] = 27. * Kv_ratio/2 * surf_area * 2
g["Kv_mut"] = 27. * Kv_ratio/2 * surf_area
g["A"] = 5. * surf_area
g["L"] = 5. * surf_area
g["T"] = 5. * surf_area
g["Ca_K"] = 1 * surf_area
g["Leak"] = 0.035 * surf_area
V_init = -70
# save folder
folder = './KCNA1_mutations/STN_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
#
# mutation properties
mutations = json.load(open("./KCNA1_mutations/mutations_effects_dict.json"))
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(STN_Kv_mut)(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param,
slope_shift, gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low, number_steps,
initial_period, sec, vol) for mut in list(mutations.keys()))

View File

@ -1 +0,0 @@
{"I407M": {"activation_Vhalf_diff": 44.2, "activation_k_ratio": 1.0, "g_ratio": 0.43523316100000004}, "G311D": {"activation_Vhalf_diff": 0.0, "activation_k_ratio": 1.0, "g_ratio": 0.333333333}, "V408A 1": {"activation_Vhalf_diff": 1.0, "activation_k_ratio": 1.0, "g_ratio": 0.658536585}, "V404I": {"activation_Vhalf_diff": 11.3, "activation_k_ratio": 1.25, "g_ratio": 1.0}, "V408A 3": {"activation_Vhalf_diff": 0.9, "activation_k_ratio": 1.228915663, "g_ratio": 1.0}, "F249C": {"activation_Vhalf_diff": 0.0, "activation_k_ratio": 1.0, "g_ratio": 0.001}, "F414S": {"activation_Vhalf_diff": 14.9, "activation_k_ratio": 1.0, "g_ratio": 0.079493088}, "F184C 2": {"activation_Vhalf_diff": 25.9, "activation_k_ratio": 0.87654321, "g_ratio": 0.151}, "E325D 1": {"activation_Vhalf_diff": 60.4, "activation_k_ratio": 2.160493827, "g_ratio": 0.038}, "G311S": {"activation_Vhalf_diff": 31.7, "activation_k_ratio": 1.654320988, "g_ratio": 0.22899999999999998}, "V408A 2": {"activation_Vhalf_diff": 0.4, "activation_k_ratio": 0.9259259259999999, "g_ratio": 0.498}, "E325D 2": {"activation_Vhalf_diff": 21.8, "activation_k_ratio": 1.518072289, "g_ratio": 1.0}, "C185W 1": {"activation_Vhalf_diff": 4.4, "activation_k_ratio": 1.0, "g_ratio": 0.298791019}, "A242P": {"activation_Vhalf_diff": -4.8, "activation_k_ratio": 0.947368421, "g_ratio": 0.1}, "T226R": {"activation_Vhalf_diff": 0.0, "activation_k_ratio": 1.0, "g_ratio": 1.0}, "R307C": {"activation_Vhalf_diff": 11.4, "activation_k_ratio": 1.0, "g_ratio": 0.254608295}, "T226M": {"activation_Vhalf_diff": 14.8, "activation_k_ratio": 1.0, "g_ratio": 0.039}, "V408L": {"activation_Vhalf_diff": 0.0, "activation_k_ratio": 1.0, "g_ratio": 1.0}, "R167M": {"activation_Vhalf_diff": 10.0, "activation_k_ratio": 1.0, "g_ratio": 0.283246978}, "wt": {"activation_Vhalf_diff": 0.0, "activation_k_ratio": 1.0, "g_ratio": 1.0}, "F249I": {"activation_Vhalf_diff": -0.6, "activation_k_ratio": 0.7654320990000001, "g_ratio": 0.01}, "N255D": {"activation_Vhalf_diff": 31.0, "activation_k_ratio": 1.0, "g_ratio": 0.180904523}, "E283K": {"activation_Vhalf_diff": 9.3, "activation_k_ratio": 1.054054054, "g_ratio": 0.666666667}, "F414C": {"activation_Vhalf_diff": 2.2, "activation_k_ratio": 1.216666667, "g_ratio": 1.0}, "R324T": {"activation_Vhalf_diff": 0.0, "activation_k_ratio": 1.0, "g_ratio": 1.0}, "R239S": {"activation_Vhalf_diff": 0.0, "activation_k_ratio": 1.0, "g_ratio": 1.0}, "F303V": {"activation_Vhalf_diff": 36.0, "activation_k_ratio": 1.333333333, "g_ratio": 0.035714286}, "C185W 2": {"activation_Vhalf_diff": 0.8, "activation_k_ratio": 0.739130435, "g_ratio": 1.0}, "F184C 1": {"activation_Vhalf_diff": 28.0, "activation_k_ratio": 1.0, "g_ratio": 0.39024390200000003}, "I262M": {"activation_Vhalf_diff": 0.0, "activation_k_ratio": 1.0, "g_ratio": 0.075268817}, "R417Stop": {"activation_Vhalf_diff": 8.5, "activation_k_ratio": 1.684210526, "g_ratio": 0.02}, "V174F": {"activation_Vhalf_diff": 35.1, "activation_k_ratio": 0.75308642, "g_ratio": 0.076}, "I262T": {"activation_Vhalf_diff": 33.6, "activation_k_ratio": 2.136363636, "g_ratio": 0.3}, "I177N": {"activation_Vhalf_diff": -2.8, "activation_k_ratio": 1.226666667, "g_ratio": 1.0}, "T226A": {"activation_Vhalf_diff": 14.3, "activation_k_ratio": 0.740740741, "g_ratio": 0.024}}

View File

@ -1,90 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run Cb Stellate \Delta Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Cb_stellate_fxns_Kv import Cb_stellate_Kv_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.0015
number_steps = 200
initial_period = 1000
num_gating = 11
num_current = 7
C, surf_area = capacitance(61.4, 1.50148)
variable = np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut'])
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# gating parameters
b_param['m'][:] = np.array([-37., -3, 1])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-40., 4., 1., 0])
b_param['n'][:] = np.array([-23, -5, 1])
b_param['n_A'][:] = np.array([-27, -13.2, 1.])
b_param['h_A'][:] = np.array([-80., 6.5, 1.])
b_param['m_T'][:] = np.array([-50., -3, 1.])
b_param['h_T'][:] = np.array([-68., 3.75, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 55.
E["K"] = -80.
E["Ca"] = 22.
E["Leak"] = -70. # as per Molineux et al 2005 and NOT the -38 in Alexander et al 2019
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["A"] = False
currents_included["T"] = True
currents_included["Leak"] = True
# model conductances
g["Na"] = 34 * surf_area
g["Kd"] = 9.0556 * surf_area
if currents_included["Kv_mut"] == True:
g["Kv"] = 1.50159 / 2 * surf_area
else:
g["Kv"] = 1.50159 / 2 * surf_area * 2
g["Kv_mut"] = 1.50159 / 2 * surf_area
g["A"] = 0 * surf_area
g["T"] = 0.45045 * surf_area
g["Leak"] = 0.07407 * surf_area
prominence = 50
min_spike_height = 0
desired_AUC_width = high/5
folder = '../Neuron_models'
mut = 'Cb_stellate_Delta_Kv'
mutations = {mut:{'g_ratio': 1, 'activation_Vhalf_diff': 0, 'activation_k_ratio':0}}
if not os.path.isdir(folder):
os.makedirs(folder)
Cb_stellate_Kv_mut(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low, number_steps,
initial_period, sec)

View File

@ -1,89 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run Cb Stellate +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Cb_stellate_fxns_Kv import Cb_stellate_Kv_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.0015
number_steps = 200
initial_period = 1000
num_gating = 11
num_current = 7
C, surf_area = capacitance(61.4, 1.50148)
variable = np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut'])
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# gating parameters
b_param['m'][:] = np.array([-37., -3, 1])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-40., 4., 1., 0])
b_param['n'][:] = np.array([-23, -5, 1])
b_param['n_A'][:] = np.array([-27, -13.2, 1.])
b_param['h_A'][:] = np.array([-80., 6.5, 1.])
b_param['m_T'][:] = np.array([-50., -3, 1.])
b_param['h_T'][:] = np.array([-68., 3.75, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 55.
E["K"] = -80.
E["Ca"] = 22.
E["Leak"] = -70. # as per Molineux et al 2005 and NOT the -38 in Alexander et al 2019
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["A"] = True
currents_included["T"] = True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 3.4 * surf_area
g["Kd"] = 9.0556 * (1-Kv_ratio) * surf_area
g["Kv"] = 6. * Kv_ratio/2 * surf_area * (2 * int(currents_included["Kv_mut"] == False))
g["Kv_mut"] = 6. * Kv_ratio/2 * surf_area
g["A"] = 15.0159 * surf_area
g["T"] = 0.45045 * surf_area
g["Leak"] = 0.07407 * surf_area
prominence = 50
min_spike_height = 0
desired_AUC_width = high/5
folder = '../Neuron_models'
mut = 'Cb_stellate_Kv'
mutations = {mut:{'g_ratio': 1, 'activation_Vhalf_diff': 0, 'activation_k_ratio':0}}
if not os.path.isdir(folder):
os.makedirs(folder)
Cb_stellate_Kv_mut(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low, number_steps,
initial_period, sec)

View File

@ -1,82 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run Cb Stellate model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Cb_stellate_fxns import Cb_stellate_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.0015
number_steps = 200
initial_period = 1000
num_gating = 9
num_current = 6
C, surf_area = capacitance(61.4, 1.50148)
variable = np.array(['m', 'h', 'n', 'n_A', 'h_A', 'n_A_mut', 'h_A_mut', 'm_T', 'h_T'])
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'n_A', 'h_A','n_A_mut', 'h_A_mut', 'm_T', 'h_T']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# gating parameters
b_param['m'][:] = np.array([-37., -3, 1])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-40., 4., 1., 0])
b_param['n'][:] = np.array([-23, -5, 1])
b_param['n_A'][:] = np.array([-27, -13.2, 1.])
b_param['h_A'][:] = np.array([-80., 6.5, 1.])
b_param['n_A_mut'][:] = np.array([-27, -13.2, 1.])
b_param['h_A_mut'][:] = np.array([-80., 6.5, 1.])
b_param['m_T'][:] = np.array([-50., -3, 1.])
b_param['h_T'][:] = np.array([-68., 3.75, 1.])
# reversal potentials
E["Na"] = 55.
E["K"] = -80.
E["Ca"] = 22.
E["Leak"] = -70. # as per Molineux et al 2005 and NOT the -38 in Alexander et al 2019
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["A_mut"] = True
currents_included["A"] = True
currents_included["T"] = True
currents_included["Leak"] = True
# model conductances
g["Na"] = 3.4 * surf_area
g["Kd"] = 9.0556 * surf_area
g["A_mut"] = 15.0159 * surf_area * 0.5
g["A"] = 15.0159 * surf_area* 0.5
g["T"] = 0.45045 * surf_area
g["Leak"] = 0.07407 * surf_area
prominence = 50
min_spike_height = 0
desired_AUC_width = high/5
folder = '../Neuron_models'
mut = 'Cb_stellate'
mutations = {mut:{'g_ratio': 1, 'activation_Vhalf_diff': 0, 'activation_k_ratio':0}}
if not os.path.isdir(folder):
os.makedirs(folder)
Cb_stellate_mut(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low, number_steps,
initial_period, sec)

View File

@ -1,102 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run FS +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Pospischil_fxns import Pospischil_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(56.9, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-34.51951036, 4.04059373, 1., 0.])
b_param['n'][:] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'][:] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'][:] = np.array([-57.37, 20.98, 1.])
b_param['p'][:] = np.array([-45., -9.9998807337, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -70.4
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
Kv_ratio = 0.10
g["Na"] = 58. * surf_area
g["Kd"] = 3.9 * (1 - Kv_ratio) * surf_area
g["M"] = 0.075 * surf_area
if currents_included["Kv_mut"] == True:
g["Kv"] = 3.9 * Kv_ratio / 2 * surf_area
else:
g["Kv"] = 3.9 * Kv_ratio / 2 * surf_area * 2
g["Kv_mut"] = 3.9 * Kv_ratio / 2 * surf_area
g["L"] = 0. * surf_area
g["Leak"] = 0.038 * surf_area
tau_max_p = 502
V_init = -70
V_T = -57.9
prominence = 50
min_spike_height = 0
desired_AUC_width = high/5
folder = '../Neuron_models'
if not os.path.isdir(folder):
os.makedirs(folder)
mut = 'FS_Kv'
mutations = {mut:{'g_ratio': 1, 'activation_Vhalf_diff': 0, 'activation_k_ratio':0}}
Pospischil_mut(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift, scale,
b_param, slope_shift, gating, current, prominence, desired_AUC_width, mutations, mut, folder,
high, low, number_steps, initial_period, sec)

View File

@ -1,100 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run FS model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Pospischil_fxns import Pospischil_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(56.9, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-34.51951036, 4.04059373, 1., 0.])
b_param['n'][:] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'][:] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'][:] = np.array([-57.37, 20.98, 1.])
b_param['p'][:] = np.array([-45., -9.9998807337, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -70.4
# currents in model
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = False
currents_included["Kv_mut"] = False
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
# model conductances
g["Na"] = 58. * surf_area
g["Kd"] = 3.9 * surf_area
g["M"] = 0.075 * surf_area
g["Kv"] = 0.
g["Kv_mut"] = 0.
g["L"] = 0.
g["Leak"] = 0.038 * surf_area
tau_max_p = 502
V_init = -70
V_T = -57.9
prominence = 50
min_spike_height = 0
desired_AUC_width = high/5
folder = '../Neuron_models'
if not os.path.isdir(folder):
os.makedirs(folder)
mut = 'FS'
mutations = {mut:{'g_ratio': 1, 'activation_Vhalf_diff': 0, 'activation_k_ratio':0}}
Pospischil_mut(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift, scale,
b_param, slope_shift, gating, current, prominence, desired_AUC_width, mutations, mut, folder,
high, low, number_steps, initial_period, sec)

View File

@ -1,116 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run RS Inhibitory +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Pospischil_fxns import Pospischil_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.00035
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(61.8, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
tau_max_p = 934
V_init = -70
V_T = -67.9
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-34.51951036, 4.04059373, 1., 0.05])
b_param['n'][:] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'][:] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'][:] = np.array([-57.37, 20.98, 1.])
b_param['p'][:] = np.array([-45., -9.9998807337, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
mut_act_Vhalf_wt = -30.01851851851851
mut_act_k_wt = -7.7333333333333325
s_diff_Vhalf = mut_act_Vhalf_wt - b_param['s'][0]
s_diff_k = mut_act_k_wt - b_param['s'][1]
b_param['s'][1] = b_param['s'][1] + s_diff_k
b_param['u'][1] = b_param['u'][1] + s_diff_k
b_param['s'][0] = b_param['s'][0] + s_diff_Vhalf
b_param['u'][0] = b_param['u'][0] + s_diff_Vhalf
b_param['s_mut'][1] = b_param['s_mut'][1] + s_diff_k
b_param['u_mut'][1] = b_param['u_mut'][1] + s_diff_k
b_param['s_mut'][0] = b_param['s_mut'][0] + s_diff_Vhalf
b_param['u_mut'][0] = b_param['u_mut'][0] + s_diff_Vhalf
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -56.2
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 10. * surf_area
g["Kd"] = 2.1 * (1 - Kv_ratio) * surf_area
g["M"] = 0.0098 * surf_area
if currents_included["Kv_mut"] == True:
g["Kv"] = 2.1 * Kv_ratio / 2 * surf_area
else:
g["Kv"] = 2.1 * Kv_ratio / 2 * surf_area * 2
g["Kv_mut"] = 2.1 * Kv_ratio / 2 * surf_area
g["L"] = 0. * surf_area
g["Leak"] = 0.0205 * surf_area
prominence = 50
min_spike_height = 0
desired_AUC_width = high/5 #0.0005
folder = '../Neuron_models'
if not os.path.isdir(folder):
os.makedirs(folder)
mut = 'RS_inhib_Kv'
mutations = {mut:{'g_ratio': 1, 'activation_Vhalf_diff': 0, 'activation_k_ratio':0}}
Pospischil_mut(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift, scale,
b_param, slope_shift, gating, current, prominence, desired_AUC_width, mutations, mut, folder,
high, low, number_steps, initial_period, sec)

View File

@ -1,102 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run RS Inhibitory model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Pospischil_fxns import Pospischil_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.00035
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(61.8, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
tau_max_p = 934
V_init = -70
V_T = -67.9
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-34.51951036, 4.04059373, 1., 0.05])
b_param['n'][:] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'][:] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'][:] = np.array([-57.37, 20.98, 1.])
b_param['p'][:] = np.array([-45., -9.9998807337, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potential
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -56.2
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = False
currents_included["Kv_mut"] = False
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
g["Na"] = 10. * surf_area
g["Kd"] = 2.1 * surf_area
g["M"] = 0.0098 * surf_area
g["Kv"] = 0.
g["Kv_mut"] = 0.
g["L"] = 0.
g["Leak"] = 0.0205 * surf_area
prominence = 50
min_spike_height = 0
desired_AUC_width = high/5
folder = '../Neuron_models'
if not os.path.isdir(folder):
os.makedirs(folder)
mut = 'RS_inhib'
mutations = {mut:{'g_ratio': 1, 'activation_Vhalf_diff': 0, 'activation_k_ratio':0}}
Pospischil_mut(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift, scale,
b_param, slope_shift, gating, current, prominence, desired_AUC_width, mutations, mut, folder,
high, low, number_steps, initial_period, sec)

View File

@ -1,119 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run RS Pyramidal +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Pospischil_fxns import Pospischil_mut
# model parameters
tau_max_p = 608
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(61.4, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
V_init = -70
V_T = -56.2
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-34.51951036, 4.04059373, 1., 0.05])
b_param['n'][:] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'][:] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'][:] = np.array([-57.37, 20.98, 1.])
b_param['p'][:] = np.array([-45., -9.9998807337, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
mut_act_Vhalf_wt = -30.01851851851851
mut_act_k_wt = -7.7333333333333325
s_diff_Vhalf = mut_act_Vhalf_wt - b_param['s'][0]
s_diff_k = mut_act_k_wt - b_param['s'][1]
b_param['s'][1] = b_param['s'][1] + s_diff_k
b_param['u'][1] = b_param['u'][1] + s_diff_k
b_param['s'][0] = b_param['s'][0] + s_diff_Vhalf
b_param['u'][0] = b_param['u'][0] + s_diff_Vhalf
b_param['s_mut'][1] = b_param['s_mut'][1] + s_diff_k
b_param['u_mut'][1] = b_param['u_mut'][1] + s_diff_k
b_param['s_mut'][0] = b_param['s_mut'][0] + s_diff_Vhalf
b_param['u_mut'][0] = b_param['u_mut'][0] + s_diff_Vhalf
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -70.3
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = False
currents_included["L"] = False
currents_included["M"] = False
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 56. * surf_area
g["Kd"] = 6. * (1 - Kv_ratio) * surf_area
g["M"] = 0.075 * surf_area
if currents_included["Kv_mut"] == True:
g["Kv"] = 6. * Kv_ratio / 2 * surf_area
else:
g["Kv"] = 6. * Kv_ratio / 2 * surf_area * 2
g["Kv_mut"] = 6. * Kv_ratio / 2 * surf_area
g["L"] = 0. * surf_area
g["Leak"] = 0.0205 * surf_area
prominence = 50
min_spike_height = 0
desired_AUC_width = high/5
folder = '../Neuron_models'
if not os.path.isdir(folder):
os.makedirs(folder)
mut = 'RS_pyramidal_Kv'
mutations = {mut:{'g_ratio': 1, 'activation_Vhalf_diff': 0, 'activation_k_ratio':0}}
Pospischil_mut(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift, scale,
b_param, slope_shift, gating, current, prominence, desired_AUC_width, mutations, mut, folder,
high, low, number_steps, initial_period, sec)

View File

@ -1,101 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run RS Pyramidal model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Pospischil_fxns import Pospischil_mut
# model parameters
tau_max_p = 608
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(61.4, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
V_init = -70
V_T = -56.2
# initialize parameters
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-34.51951036, 4.04059373, 1., 0.05])
b_param['n'][:] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'][:] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'][:] = np.array([-57.37, 20.98, 1.])
b_param['p'][:] = np.array(
[-45., -9.9998807337, 1.]) # -45 with 10 mV shift so that it contributes to resting potential
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -70.3
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = False
currents_included["Kv_mut"] = False
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
# model conductances
g["Na"] = 56. * surf_area
g["Kd"] = 6. * surf_area
g["M"] = 0.075 * surf_area
g["Kv"] = 0.
g["Kv_mut"] = 0.
g["L"] = 0.
g["Leak"] = 0.0205 * surf_area
prominence = 50
min_spike_height = 0
desired_AUC_width = high / 5
folder = '../Neuron_models'
if not os.path.isdir(folder):
os.makedirs(folder)
mut = 'RS_pyramidal'
mutations = {mut:{'g_ratio': 1, 'activation_Vhalf_diff': 0, 'activation_k_ratio':0}}
Pospischil_mut(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift, scale,
b_param, slope_shift, gating, current, prominence, desired_AUC_width, mutations, mut, folder,
high, low, number_steps, initial_period, sec)

View File

@ -1,114 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run STN \Delta Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.STN_fxns_Kv import STN_Kv_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.005
number_steps = 100
initial_period = 1000
num_gating = 17
num_current = 9
d = 61.4
r = d/2 * 10**-6 # radius in meters
vol = np.pi * r**3 # volume in liters
C, surf_area = capacitance(d, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'a', 'b', 'c', 'd1', 'd2', 'p', 'q', 'r', 's', 'u', 's_mut', 'u_mut','Ca_conc', 'E_Ca']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = {}
i = 0
for var in np.array(['m', 'h', 'n', 'a', 'b', 'c', 'd1', 'd2', 'p', 'q', 'r', 's', 'u', 's_mut', 'u_mut', 'Ca_conc','E_Ca']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'A', 'L', 'Kv', 'Kv_mut', 'T', 'Leak', 'Ca_K']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'] = np.array([-40., -1. , 1.])
b_param['h'] = np.zeros(4)
b_param['h'] = np.array([-45.5, 1. , 1., 0.05])
b_param['n'] = np.array([-41., -1., 1.])
b_param['p'] = np.array([-56., -1., 1.])
b_param['q'] = np.array([-85., 1., 1.])
b_param['r'] = np.array([0.17, -0.08, 1.])
b_param['a'] = np.array([-45., -14.7, 1.])
b_param['b'] = np.array([-90., 7.5, 1.])
b_param['c'] = np.array([-30.6, -5., 1.])
b_param['d1'] = np.array([-60, 7.5, 1.])
b_param['d2'] = np.array([0.1, 0.02, 1.])
b_param['s'] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 60.
E["K"] = -90.
E["Leak"] = -60.
# model currents
currents_included["Na"] = True
currents_included["Kd"] =True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["L"] = True
currents_included["T"] = True
currents_included["Ca_K"] = True
currents_included["A"] =True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 49. * surf_area
g["Kd"] = 27. * (1-Kv_ratio)* surf_area
if currents_included["Kv_mut"]==True:
g["Kv"] = 27. * Kv_ratio/2 * surf_area
else:
g["Kv"] = 27. * Kv_ratio/2 * surf_area * 2
g["Kv_mut"] = 27. * Kv_ratio/2 * surf_area
g["A"] = 5. * surf_area
g["L"] = 5. * surf_area
g["T"] = 5. * surf_area
g["Ca_K"] = 1 * surf_area
g["Leak"] = 0.035 * surf_area
prominence = 50
min_spike_height = 0
desired_AUC_width = high/5
folder = '../Neuron_models'
mut = 'STN_Delta_Kv'
mutations = {mut:{'g_ratio': 1, 'activation_Vhalf_diff': 0, 'activation_k_ratio':0}}
if not os.path.isdir(folder):
os.makedirs(folder)
STN_Kv_mut(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low, number_steps,
initial_period, sec, vol)

View File

@ -1,114 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run STN +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.STN_fxns_Kv import STN_Kv_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.005
number_steps = 100
initial_period = 1000
num_gating = 17
num_current = 9
d = 61.4
r = d/2 * 10**-6 # radius in meters
vol = np.pi * r**3 # volume in liters
C, surf_area = capacitance(d, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'a', 'b', 'c', 'd1', 'd2', 'p', 'q', 'r', 's', 'u', 's_mut', 'u_mut','Ca_conc', 'E_Ca']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = {}
i = 0
for var in np.array(['m', 'h', 'n', 'a', 'b', 'c', 'd1', 'd2', 'p', 'q', 'r', 's', 'u', 's_mut', 'u_mut', 'Ca_conc','E_Ca']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'A', 'L', 'Kv', 'Kv_mut', 'T', 'Leak', 'Ca_K']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'] = np.array([-40., -1., 1.])
b_param['h'] = np.zeros(4)
b_param['h'] = np.array([-45.5, 1., 1., 0.05])
b_param['n'] = np.array([-41., -1., 1.])
b_param['p'] = np.array([-56., -1., 1.])
b_param['q'] = np.array([-85., 1., 1.])
b_param['r'] = np.array([0.17, -0.08, 1.])
b_param['a'] = np.array([-45., -14.7, 1.])
b_param['b'] = np.array([-90., 7.5, 1.])
b_param['c'] = np.array([-30.6, -5., 1.])
b_param['d1'] = np.array([-60, 7.5, 1.])
b_param['d2'] = np.array([0.1, 0.02, 1.])
b_param['s'] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 60.
E["K"] = -90.
E["Leak"] = -60.
# model currents
currents_included["Na"] = True
currents_included["Kd"] =True
currents_included["Kv"] = True
currents_included["Kv_mut"] = True
currents_included["L"] = True
currents_included["T"] = True
currents_included["Ca_K"] = True
currents_included["A"] =True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 49. * surf_area
g["Kd"] = 27. * (1-Kv_ratio)* surf_area
if currents_included["Kv_mut"]==True:
g["Kv"] = 27. * Kv_ratio/2 * surf_area
else:
g["Kv"] = 27. * Kv_ratio/2 * surf_area * 2
g["Kv_mut"] = 27. * Kv_ratio/2 * surf_area
g["A"] = 5. * surf_area
g["L"] = 5. * surf_area
g["T"] = 5. * surf_area
g["Ca_K"] = 1 * surf_area
g["Leak"] = 0.035 * surf_area
prominence = 50
min_spike_height = 0
desired_AUC_width = high/5
folder = '../Neuron_models'
mut = 'STN_Kv'
mutations = {mut:{'g_ratio': 1, 'activation_Vhalf_diff': 0, 'activation_k_ratio':0}}
if not os.path.isdir(folder):
os.makedirs(folder)
STN_Kv_mut(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low, number_steps,
initial_period, sec, vol)

View File

@ -1,103 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run STN model
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import numpy as np
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.STN_fxns import STN_mut
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.005
number_steps = 100
initial_period = 1000
num_gating = 15
num_current = 8
d = 61.4
r = d/2 * 10**-6 # radius in meters
vol = np.pi * r**3 # volume in liters
C, surf_area = capacitance(d, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'a', 'b', 'a_mut', 'b_mut', 'c', 'd1', 'd2', 'p', 'q', 'r', 'Ca_conc', 'E_Ca']))
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = {}
i = 0
for var in np.array(['m', 'h', 'n', 'a', 'b', 'a_mut', 'b_mut', 'c', 'd1', 'd2', 'p', 'q', 'r', 'Ca_conc','E_Ca']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'A', 'L', 'A_mut', 'T', 'Leak', 'Ca_K']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'] = np.array([-40., -1. , 1.])
b_param['h'] = np.zeros(4)
b_param['h'] = np.array([-45.5, 1. , 1., 0.05])
b_param['n'] = np.array([-41., -1., 1.])
b_param['p'] = np.array([-56., -1., 1.])
b_param['q'] = np.array([-85., 1., 1.])
b_param['r'] = np.array([0.17, -0.08, 1.])
b_param['a'] = np.array([-45., -14.7, 1.])
b_param['b'] = np.array([-90., 7.5, 1.])
b_param['a_mut'] = np.array([-45., -14.7, 1.])
b_param['b_mut'] = np.array([-90., 7.5, 1.])
b_param['c'] = np.array([-30.6, -5., 1.])
b_param['d1'] = np.array([-60, 7.5, 1.])
b_param['d2'] = np.array([0.1, 0.02, 1.])
# reversal potentials
E["Na"] = 60.
E["K"] = -90.
E["Leak"] = -60.
# model currents
currents_included["Na"] = True
currents_included["Kd"] =True
currents_included["L"] = True
currents_included["T"] = True
currents_included["Ca_K"] = True
currents_included["A"] =True
currents_included["A_mut"] =True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 49. * surf_area
g["Kd"] = 27. * (1-Kv_ratio)* surf_area
g["A"] = 5. * surf_area *0.5
g["A_mut"] = 5. * surf_area *0.5
g["L"] = 5. * surf_area
g["T"] = 5. * surf_area
g["Ca_K"] = 1 * surf_area
g["Leak"] = 0.035 * surf_area
V_init = -70
prominence = 50
min_spike_height = 0
desired_AUC_width = high/5
folder = '../Neuron_models'
mut = 'STN'
mutations = {mut:{'g_ratio': 1, 'activation_Vhalf_diff': 0, 'activation_k_ratio':0}}
if not os.path.isdir(folder):
os.makedirs(folder)
STN_mut(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, mutations, mut, folder, high, low, number_steps,
initial_period, sec, vol)

View File

@ -1,112 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run sensitivity analysis for Cb Stellate model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Cb_stellate_fxns import SA_Cb_stellate
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 9
num_current = 6
C, surf_area = capacitance(61.4, 1.50148)
variable = np.array(['m', 'h', 'n', 'n_A', 'h_A', 'n_A_mut', 'h_A_mut', 'm_T', 'h_T'])
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'n_A', 'h_A', 'n_A_mut', 'h_A_mut', 'm_T', 'h_T']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'n_A', 'h_A', 'n_A_mut', 'h_A_mut', 'm_T', 'h_T']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'A', 'A_mut', 'T', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-37., -3, 1])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-40., 4., 1., 0])
b_param['n'][:] = np.array([-23, -5, 1])
b_param['n_A'][:] = np.array([-27, -13.2, 1.])
b_param['h_A'][:] = np.array([-80., 6.5, 1.])
b_param['n_A_mut'][:] = np.array([-27, -13.2, 1.])
b_param['h_A_mut'][:] = np.array([-80., 6.5, 1.])
b_param['m_T'][:] = np.array([-50., -3, 1.])
b_param['h_T'][:] = np.array([-68., 3.75, 1.])
# reversal potentials
E["Na"] = 55.
E["K"] = -80.
E["Ca"] = 22.
E["Leak"] = -70. # as per Molineux et al 2005 and NOT the -38 in Alexander et al 2019
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["A_mut"] = False
currents_included["A"] = True
currents_included["T"] = True
currents_included["Leak"] = True
# model conductances
g["Na"] = 3.4 * surf_area
g["Kd"] = 9.0556 * surf_area
g["A_mut"] = 0.
g["A"] = 15.0159 * surf_area
g["T"] = 0.45045 * surf_area
g["Leak"] = 0.07407 * surf_area
# save folder
folder = '../Sensitivity_Analysis/Data/Cb_stellate'
if not os.path.isdir(folder):
os.makedirs(folder)
#%% setup for one-factor-at-a-time SA
var = np.array(['m', 'h', 'n', 'n_A', 'h_A'])
type_names = np.append(np.array(['shift' for i in range(var.shape[0])]),
np.array(['slope' for i in range(var.shape[0])]))
cur = np.array(['Na', 'Kd', 'A', 'Leak'])
type_names = np.append(type_names, np.array(['g' for i in range(cur.shape[0])]))
var = np.append(var, var)
var = np.append(var, cur)
alt_types = np.c_[var, type_names]
lin_array = np.arange(-10, 11, 1)
log_array = np.logspace(-1,1,21, base=2)
# %% multiprocessing
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(SA_Cb_stellate)(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param,
slope_shift,gating, current, prominence, desired_AUC_width, folder, high, low, number_steps,
initial_period, sec, lin_array, log_array, alt_types, alt_ind, alt)
for alt_ind in range(alt_types.shape[0]) for alt in range(21))

View File

@ -1,118 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run sensitivity analysis for Cb Stellate \Delta Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Cb_stellate_fxns_Kv import SA_Cb_stellate_Kv
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 11
num_current = 7
C, surf_area = capacitance(61.4, 1.50148)
variable = np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut'])
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'A', 'Kv', 'Kv_mut', 'T', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-37., -3, 1])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-40., 4., 1., 0])
b_param['n'][:] = np.array([-23, -5, 1])
b_param['n_A'][:] = np.array([-27, -13.2, 1.])
b_param['h_A'][:] = np.array([-80., 6.5, 1.])
b_param['m_T'][:] = np.array([-50., -3, 1.])
b_param['h_T'][:] = np.array([-68., 3.75, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 55.
E["K"] = -80.
E["Ca"] = 22.
E["Leak"] = -70. # as per Molineux et al 2005 and NOT the -38 in Alexander et al 2019
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = False
currents_included["A"] = False
currents_included["T"] = True
currents_included["Leak"] = True
# model conductances
g["Na"] = 34 * surf_area
g["Kd"] = 9.0556 * surf_area
if currents_included["Kv_mut"] == True:
g["Kv"] = 1.50159 / 2 * surf_area
else:
g["Kv"] = 1.50159 / 2 * surf_area * 2
g["Kv_mut"] = 1.50159 / 2 * surf_area
g["A"] = 0 * surf_area
g["T"] = 0.45045 * surf_area
g["Leak"] = 0.07407 * surf_area
# save folder
folder = './Sensitivity_Analysis/Data/Cb_stellate_Delta_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
#%% setup for one-factor-at-a-time SA
var = np.array(['m', 'h', 'n', 's', 'u'])
type_names = np.append(np.array(['shift' for i in range(var.shape[0])]),
np.array(['slope' for i in range(var.shape[0])]))
cur = np.array(['Na', 'Kd', 'Kv', 'Leak'])
type_names = np.append(type_names, np.array(['g' for i in range(cur.shape[0])]))
var = np.append(var, var)
var = np.append(var, cur)
alt_types = np.c_[var, type_names]
lin_array = np.arange(-10, 11, 1)
log_array = np.logspace(-1,1,21, base=2)
# %% multiprocessing
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(SA_Cb_stellate_Kv)(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param,
slope_shift,gating, current, prominence, desired_AUC_width, folder, high, low, number_steps,
initial_period, sec, lin_array, log_array, alt_types, alt_ind, alt)
for alt_ind in range(alt_types.shape[0]) for alt in range(21))

View File

@ -1,116 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run sensitivity analysis for Cb Stellate +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.Cb_stellate_fxns_Kv import SA_Cb_stellate_Kv
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 11
num_current = 7
C, surf_area = capacitance(61.4, 1.50148)
variable = np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut'])
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'n_A', 'h_A', 'm_T', 'h_T', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'A', 'Kv', 'Kv_mut', 'T', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-37., -3, 1])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-40., 4., 1., 0])
b_param['n'][:] = np.array([-23, -5, 1])
b_param['n_A'][:] = np.array([-27, -13.2, 1.])
b_param['h_A'][:] = np.array([-80., 6.5, 1.])
b_param['m_T'][:] = np.array([-50., -3, 1.])
b_param['h_T'][:] = np.array([-68., 3.75, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 55.
E["K"] = -80.
E["Ca"] = 22.
E["Leak"] = -70. # as per Molineux et al 2005 and NOT the -38 in Alexander et al 2019
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = False
currents_included["A"] = True
currents_included["T"] = True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 3.4 * surf_area
g["Kd"] = 9.0556 * (1-Kv_ratio) * surf_area
g["Kv"] = 9.0556 * Kv_ratio * surf_area
g["Kv_mut"] = 0.
g["A"] = 15.0159 * surf_area
g["T"] = 0.45045 * surf_area
g["Leak"] = 0.07407 * surf_area
# save folder
folder = './Sensitivity_Analysis/Data/Cb_stellate_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
#%% setup for one-factor-at-a-time SA
var = np.array(['m', 'h', 'n', 'n_A', 'h_A', 's', 'u'])
type_names = np.append(np.array(['shift' for i in range(var.shape[0])]),
np.array(['slope' for i in range(var.shape[0])]))
cur = np.array(['Na', 'Kd', 'A', 'Kv', 'Leak'])
type_names = np.append(type_names, np.array(['g' for i in range(cur.shape[0])]))
var = np.append(var, var)
var = np.append(var, cur)
alt_types = np.c_[var, type_names]
lin_array = np.arange(-10, 11, 1)
log_array = np.logspace(-1,1,21, base=2)
# %% multiprocessing
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(SA_Cb_stellate_Kv)(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param,
slope_shift,gating, current, prominence, desired_AUC_width, folder, high, low, number_steps,
initial_period, sec, lin_array, log_array, alt_types, alt_ind, alt)
for alt_ind in range(alt_types.shape[0]) for alt in range(21))

View File

@ -1,120 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run sensitivity analysis for FS model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict, NumpyEncoder
from Code.Functions.Pospischil_fxns import SA_Pospischil
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(56.9, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
tau_max_p = 502
V_init = -70
V_T = -57.9 # Threshold
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# create dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-34.51951036, 4.04059373, 1., 0.])
b_param['n'][:] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'][:] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'][:] = np.array([-57.37, 20.98, 1.])
b_param['p'][:] = np.array([-45., -9.9998807337, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -70.4
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = False
currents_included["Kv_mut"] = False
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
# model conductances
g["Na"] = 58. * surf_area
g["Kd"] = 3.9 * surf_area
g["M"] = 0.075 * surf_area
g["Kv"] = 0.
g["Kv_mut"] = 0.
g["L"] = 0.
g["Leak"] = 0.038 * surf_area
# folder to save to
folder = '../Sensitivity_Analysis/Data/FS'
if not os.path.isdir(folder):
os.makedirs(folder)
#%% setup for one-factor-at-a-time SA
var = np.array(['m', 'h', 'n'])
type_names = np.append(np.array(['shift' for i in range(var.shape[0])]),
np.array(['slope' for i in range(var.shape[0])]))
cur = np.array(['Na', 'Kd', 'Leak'])
type_names = np.append(type_names, np.array(['g' for i in range(cur.shape[0])]))
var = np.append(var, var)
var = np.append(var, cur)
alt_types = np.c_[var, type_names]
lin_array = np.arange(-10, 11, 1)
log_array = np.logspace(-1,1,21, base=2)
# %% multiprocessing
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(SA_Pospischil)(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift, scale,
b_param, slope_shift, gating, current, prominence, desired_AUC_width, folder, high, low,
number_steps, initial_period, sec, lin_array, log_array, alt_types, alt_ind, alt)
for alt_ind in range(alt_types.shape[0]) for alt in range(21))

View File

@ -1,117 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run sensitivity analysis for FS +Kv model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict, NumpyEncoder
from Code.Functions.Pospischil_fxns import SA_Pospischil
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(56.9, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
tau_max_p = 502
V_init = -70
V_T = -57.9
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-34.51951036, 4.04059373, 1., 0.])
b_param['n'][:] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'][:] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'][:] = np.array([-57.37, 20.98, 1.])
b_param['p'][:] = np.array([-45., -9.9998807337, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -70.4
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = False
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.10
g["Na"] = 58. * surf_area
g["Kd"] = 3.9 * (1 - Kv_ratio) * surf_area
g["M"] = 0.075 * surf_area
g["Kv"] = 3.9 * Kv_ratio * surf_area
g["Kv_mut"] = 0.
g["L"] = 0. * surf_area
g["Leak"] = 0.038 * surf_area
# save folder
folder = '../Sensitivity_Analysis/Data/FS_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
#%% setup for one-factor-at-a-time SA
var = np.array(['m', 'h', 'n', 's', 'u'])
type_names = np.append(np.array(['shift' for i in range(var.shape[0])]),
np.array(['slope' for i in range(var.shape[0])]))
cur = np.array(['Na', 'Kd', 'Kv', 'Leak'])
type_names = np.append(type_names, np.array(['g' for i in range(cur.shape[0])]))
var = np.append(var, var)
var = np.append(var, cur)
alt_types = np.c_[var, type_names]
lin_array = np.arange(-10, 11, 1)
log_array = np.logspace(-1,1,20, base=2)
log_array = np.append(log_array,1)
# %% multiprocessing
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(SA_Pospischil)(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift,
scale, b_param, slope_shift, gating, current, prominence, desired_AUC_width, folder, high,
low, number_steps, initial_period, sec, lin_array, log_array, alt_types, alt_ind, alt)
for alt_ind in range(alt_types.shape[0]) for alt in range(21))

View File

@ -1,120 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run sensitivity analysis for RS Inhibitory model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict, NumpyEncoder
from Code.Functions.Pospischil_fxns import SA_Pospischil
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.00035
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(61.8, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
tau_max_p = 934
V_init = -70
V_T = -67.9
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-34.51951036, 4.04059373, 1., 0.05])
b_param['n'][:] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'][:] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'][:] = np.array([-57.37, 20.98, 1.])
b_param['p'][:] = np.array([-45., -9.9998807337, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -56.2
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = False
currents_included["Kv_mut"] = False
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
# model conductances
g["Na"] = 10. * surf_area
g["Kd"] = 2.1 * surf_area
g["M"] = 0.0098 * surf_area
g["Kv"] = 0.
g["Kv_mut"] = 0.
g["L"] = 0.
g["Leak"] = 0.0205 * surf_area
# save folder
folder = '../Sensitivity_Analysis/Data/RS_inhib'
if not os.path.isdir(folder):
os.makedirs(folder)
#%% setup for one-factor-at-a-time SA
var = np.array(['m', 'h', 'n'])
type_names = np.append(np.array(['shift' for i in range(var.shape[0])]),
np.array(['slope' for i in range(var.shape[0])]))
cur = np.array(['Na', 'Kd', 'Leak'])
type_names = np.append(type_names, np.array(['g' for i in range(cur.shape[0])]))
var = np.append(var, var)
var = np.append(var, cur)
alt_types = np.c_[var, type_names]
lin_array = np.arange(-10, 11, 1)
log_array = np.logspace(-1,1,21, base=2)
# %% multiprocessing
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(SA_Pospischil)(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift,
scale,
b_param, slope_shift, gating, current, prominence, desired_AUC_width, folder, high, low,
number_steps, initial_period, sec, lin_array, log_array, alt_types, alt_ind, alt)
for alt_ind in range(alt_types.shape[0]) for alt in range(21))

View File

@ -1,118 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run sensitivity analysis for RS Inhibitory +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict, NumpyEncoder
from Code.Functions.Pospischil_fxns import SA_Pospischil
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.00035
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(61.8, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
tau_max_p = 934
V_init = -70
V_T = -67.9
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-34.51951036, 4.04059373, 1., 0.05])
b_param['n'][:] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'][:] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'][:] = np.array([-57.37, 20.98, 1.])
b_param['p'][:] = np.array([-45., -9.9998807337, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -56.2
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = False
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 10. * surf_area
g["Kd"] = 2.1 * (1 - Kv_ratio) * surf_area
g["M"] = 0.0098 * surf_area
g["Kv"] = 2.1 * Kv_ratio * surf_area
g["Kv_mut"] = 0.
g["L"] = 0. * surf_area
g["Leak"] = 0.0205 * surf_area
# save folder
folder = '../Sensitivity_Analysis/Data/RS_inhib_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
#%% setup for one-factor-at-a-time SA
var = np.array(['m', 'h', 'n', 's', 'u'])
type_names = np.append(np.array(['shift' for i in range(var.shape[0])]),
np.array(['slope' for i in range(var.shape[0])]))
cur = np.array(['Na', 'Kd', 'Kv', 'Leak'])
type_names = np.append(type_names, np.array(['g' for i in range(cur.shape[0])]))
var = np.append(var, var)
var = np.append(var, cur)
alt_types = np.c_[var, type_names]
lin_array = np.arange(-10, 11, 1)
log_array = np.logspace(-1,1,21, base=2)
# %% multiprocessing
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(SA_Pospischil)(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift,
scale, b_param, slope_shift, gating, current, prominence, desired_AUC_width, folder, high,
low, number_steps, initial_period, sec, lin_array, log_array, alt_types, alt_ind, alt)
for alt_ind in range(alt_types.shape[0]) for alt in range(21))

View File

@ -1,102 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run sensitivity analysis for RS Pyramidal model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from joblib import Parallel, delayed
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict, NumpyEncoder
from Code.Functions.Pospischil_fxns import SA_Pospischil
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(61.4, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
tau_max_p = 608
V_init = -70
V_T = -56.2
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# gating parameters
b_param = {}
b_param['m'] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.array([-34.51951036, 4.04059373, 1., 0.05])
b_param['n'] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'] = np.array([-57.37, 20.98, 1.0])
b_param['p'] = np.array([-45., -9.9998807337, 1.])
b_param['s'] = np.array([-14.16, -10.15, 1.0])
b_param['u'] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.array([-31., 5.256, 1., 0.245])
# reversal potential
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -70.3
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = False
currents_included["Kv_mut"] = False
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
# model conductances
g["Na"] = 56. * surf_area
g["Kd"] = 6. * surf_area
g["M"] = 0.075 * surf_area
g["Kv"] = 0.
g["Kv_mut"] = 0.
g["L"] = 0.
g["Leak"] = 0.0205 * surf_area
folder = '../Sensitivity_Analysis/Data/RS_pyramidal'
if not os.path.isdir(folder):
os.makedirs(folder)
#%% setup for one-factor-at-a-time SA
var = np.array(['m', 'h', 'n'])
type_names = np.append(np.array(['shift' for i in range(var.shape[0])]),
np.array(['slope' for i in range(var.shape[0])]))
cur = np.array(['Na', 'Kd', 'Leak'])
type_names = np.append(type_names, np.array(['g' for i in range(cur.shape[0])]))
var = np.append(var, var)
var = np.append(var, cur)
alt_types = np.c_[var, type_names]
lin_array = np.arange(-10, 11, 1)
log_array = np.logspace(-1,1,21, base=2)
# %% multiprocessing
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(SA_Pospischil)(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift,
scale,
b_param, slope_shift, gating, current, prominence, desired_AUC_width, folder, high, low,
number_steps, initial_period, sec, lin_array, log_array, alt_types, alt_ind, alt)
for alt_ind in range(alt_types.shape[0]) for alt in range(21))

View File

@ -1,117 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run sensitivity analysis for RS Pyramidal +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict, NumpyEncoder
from Code.Functions.Pospischil_fxns import SA_Pospischil
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 10
num_current = 7
C, surf_area = capacitance(61.4, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(
np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']))
tau_max_p = 608
V_init = -70
V_T = -56.2
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# create dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'q', 'r', 'p', 's', 'u', 's_mut', 'u_mut']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'M', 'Kv', 'Kv_mut', 'L', 'Leak']):
ind_dict[var] = i
i += 1
# gating parameters
b_param = {}
b_param['m'] = np.array([-34.33054521, -8.21450277, 1.42295686])
b_param['h'] = np.array([-34.51951036, 4.04059373, 1., 0.05])
b_param['n'] = np.array([-63.76096946, -13.83488194, 7.35347425])
b_param['q'] = np.array([-39.03684525, -5.57756176, 2.25190197])
b_param['r'] = np.array([-57.37, 20.98, 1.0])
b_param['p'] = np.array([-45., -9.9998807337, 1.])
b_param['s'] = np.array([-14.16, -10.15, 1.0])
b_param['u'] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 50.
E["K"] = -90.
E["Ca"] = 120.
E["Leak"] = -70.3
# model currents
currents_included["Na"] = True
currents_included["Kd"] = True
currents_included["Kv"] = True
currents_included["Kv_mut"] = False
currents_included["L"] = False
currents_included["M"] = True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.1
g["Na"] = 56. * surf_area
g["Kd"] = 6. * (1 - Kv_ratio) * surf_area
g["M"] = 0.075 * surf_area
g["Kv"] = 6. * Kv_ratio * surf_area
g["Kv_mut"] = 0.
g["L"] = 0. * surf_area
g["Leak"] = 0.0205 * surf_area
# save folder
folder = '../Sensitivity_Analysis/Data/RS_pyramidal_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
#%% setup for one-factor-at-a-time SA
var = np.array(['m', 'h', 'n', 's', 'u'])
type_names = np.append(np.array(['shift' for i in range(var.shape[0])]),
np.array(['slope' for i in range(var.shape[0])]))
cur = np.array(['Na', 'Kd', 'Kv', 'Leak'])
type_names = np.append(type_names, np.array(['g' for i in range(cur.shape[0])]))
var = np.append(var, var)
var = np.append(var, cur)
alt_types = np.c_[var, type_names]
lin_array = np.arange(-10, 11, 1)
log_array = np.logspace(-1,1,21, base=2)
# %% multiprocessing
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(SA_Pospischil)(V_init, V_T, g, E, I_in, dt, currents_included, stim_time, stim_num, C, tau_max_p, shift,
scale, b_param, slope_shift, gating, current, prominence, desired_AUC_width, folder, high,
low, number_steps, initial_period, sec, lin_array, log_array, alt_types, alt_ind, alt)
for alt_ind in range(alt_types.shape[0]) for alt in range(21))

View File

@ -1,116 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run sensitivity analysis for STN model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.STN_fxns import SA_STN
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 15
num_current = 8
d = 61.4
r = d/2 * 10**-6 # radius in meters
vol = np.pi * r**3 # volume in liters
C, surf_area = capacitance(d, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'a', 'b', 'a_mut', 'b_mut', 'c', 'd1', 'd2', 'p', 'q', 'r', 'Ca_conc', 'E_Ca']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'a', 'b', 'a_mut', 'b_mut', 'c', 'd1', 'd2', 'p', 'q', 'r','Ca_conc','E_Ca']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'A', 'L', 'A_mut', 'T', 'Leak', 'Ca_K']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-40., -1., 1.])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-45.5, 1., 1., 0.05])
b_param['n'][:] = np.array([-41., -1., 1.])
b_param['p'][:] = np.array([-56., -1., 1.])
b_param['q'][:] = np.array([-85., 1., 1.])
b_param['r'][:] = np.array([0.17, -0.08, 1.])
b_param['a'][:] = np.array([-45., -14.7, 1.])
b_param['b'][:] = np.array([-90., 7.5, 1.])
b_param['a_mut'][:] = np.array([-45., -14.7, 1.])
b_param['b_mut'][:] = np.array([-90., 7.5, 1.])
b_param['c'][:] = np.array([-30.6, -5., 1.])
b_param['d1'][:] = np.array([-60, 7.5, 1.])
b_param['d2'][:] = np.array([0.1, 0.02, 1.])
# reversal potentials
E["Na"] = 60.
E["K"] = -90.
E["Leak"] = -60.
# model currents
currents_included["Na"] = True
currents_included["Kd"] =True
currents_included["L"] = True
currents_included["T"] = True
currents_included["Ca_K"] = True
currents_included["A"] =True
currents_included["A_mut"] =False
currents_included["Leak"] = True
# model conductances
g["Na"] = 49. * surf_area
g["Kd"] = 57. * surf_area
g["A"] = 5. * surf_area
g["A_mut"] = 0.
g["L"] = 5. * surf_area
g["T"] = 5. * surf_area
g["Ca_K"] = 1 * surf_area
g["Leak"] = 0.035 * surf_area
# save folder
folder = '../Sensitivity_Analysis/Data/STN'
if not os.path.isdir(folder):
os.makedirs(folder)
#%% setup for one-factor-at-a-time SA
var = np.array(['m', 'h', 'n', 'a', 'b'])
type_names = np.append(np.array(['shift' for i in range(var.shape[0])]),
np.array(['slope' for i in range(var.shape[0])]))
cur = np.array(['Na', 'Kd', 'A', 'Leak'])
type_names = np.append(type_names, np.array(['g' for i in range(cur.shape[0])]))
var = np.append(var, var)
var = np.append(var, cur)
alt_types = np.c_[var, type_names]
lin_array = np.arange(-10, 11, 1)
log_array = np.logspace(-1,1,21, base=2)
# %% run SA with multiprocessing
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(SA_STN)(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, folder, high, low, number_steps, initial_period, sec, vol,
lin_array, log_array, alt_types, alt_ind, alt)
for alt_ind in range(alt_types.shape[0]) for alt in range(21))

View File

@ -1,131 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run sensitivity analysis for STN \Delta Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.STN_fxns_Kv import SA_Kv_STN
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 17
num_current = 9
d = 61.4
r = d/2 * 10**-6 # radius in meters
vol = np.pi * r**3 # volume in liters
C, surf_area = capacitance(d, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'a', 'b', 'c', 'd1', 'd2', 'p', 'q', 'r', 's', 'u', 's_mut', 'u_mut','Ca_conc', 'E_Ca']))
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'a', 'b', 'c', 'd1', 'd2', 'p', 'q', 'r', 's', 'u', 's_mut', 'u_mut', 'Ca_conc','E_Ca']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'A', 'L', 'Kv', 'Kv_mut', 'T', 'Leak', 'Ca_K']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-40., -1. , 1.])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-45.5, 1. , 1., 0.05])
b_param['n'][:] = np.array([-41., -1., 1.])
b_param['p'][:] = np.array([-56., -1., 1.])
b_param['q'][:] = np.array([-85., 1., 1.])
b_param['r'][:] = np.array([0.17, -0.08, 1.])
b_param['a'][:] = np.array([-45., -14.7, 1.])
b_param['b'][:] = np.array([-90., 7.5, 1.])
b_param['c'][:] = np.array([-30.6, -5., 1.])
b_param['d1'][:] = np.array([-60, 7.5, 1.])
b_param['d2'][:] = np.array([0.1, 0.02, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 60.
E["K"] = -90.
E["Leak"] = -60.
# model currents
currents_included["Na"] = True
currents_included["Kd"] =True
currents_included["Kv"] = True
currents_included["Kv_mut"] = False
currents_included["L"] = True
currents_included["T"] = True
currents_included["Ca_K"] = True
currents_included["A"] =True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.01
g["Na"] = 49. * surf_area
g["Kd"] = 57. * surf_area
g["Kv"] = 0.5 * surf_area
g["Kv_mut"] = 0
g["A"] = 0. * surf_area
g["L"] = 5. * surf_area
g["T"] = 5. * surf_area
g["Ca_K"] = 1 * surf_area
g["Leak"] = 0.035 * surf_area
V_init = -70
# save folder
folder = '../Sensitivity_Analysis/Data/STN_Delta_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
#%% setup for one-factor-at-a-time SA
var = np.array(['m', 'h', 'n', 's','u'])
type_names = np.append(np.array(['shift' for i in range(var.shape[0])]),
np.array(['slope' for i in range(var.shape[0])]))
cur = np.array(['Na', 'Kd', 'Kv', 'Leak'])
type_names = np.append(type_names, np.array(['g' for i in range(cur.shape[0])]))
var = np.append(var, var)
var = np.append(var, cur)
alt_types = np.c_[var, type_names]
lin_array = np.arange(-10, 11, 1)
log_array = np.logspace(-1,1,21, base=2)
# %% run SA with multiprocessing
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(SA_Kv_STN)(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param,
slope_shift, gating, current, prominence, desired_AUC_width, folder, high, low, number_steps, initial_period,
sec, vol, lin_array, log_array, alt_types, alt_ind, alt)
for alt_ind in range(alt_types.shape[0]) for alt in range(21))

View File

@ -1,127 +0,0 @@
# -*- coding: utf-8 -*-
"""
Script to run sensitivity analysis for STN +Kv1.1 model
"""
__author__ = "Nils A. Koch"
__copyright__ = "Copyright 2022, Nils A. Koch"
__license__ = "MIT"
import numpy as np
from numba import types
from numba.typed import Dict
from joblib import Parallel, delayed
import os
from Code.Functions.Utility_fxns import capacitance, stimulus_init, init_dict
from Code.Functions.STN_fxns_Kv import SA_Kv_STN
# model parameters
dt = 0.01
sec = 2
low = 0
high = 0.001
number_steps = 200
initial_period = 1000
num_gating = 17
num_current = 9
d = 61.4
r = d/2 * 10**-6 # radius in meters
vol = np.pi * r**3 # volume in liters
C, surf_area = capacitance(d, 1)
stim_time, I_in, stim_num, V_m = stimulus_init(low, high, number_steps, initial_period, dt, sec)
shift, scale, slope_shift, E, currents_included, b_param, g = init_dict(np.array(['m', 'h', 'n', 'a', 'b', 'c', 'd1', 'd2', 'p', 'q', 'r', 's', 'u', 's_mut', 'u_mut','Ca_conc', 'E_Ca']))
V_init = -70
# initialize arrays
current = np.zeros((num_current, stim_num))
gating = np.zeros((num_gating, stim_num))
# initialize dictionary
ind_dict = Dict.empty(key_type=types.unicode_type, value_type=types.int64, )
i = 0
for var in np.array(['m', 'h', 'n', 'a', 'b', 'c', 'd1', 'd2', 'p', 'q', 'r', 's', 'u', 's_mut', 'u_mut', 'Ca_conc','E_Ca']):
ind_dict[var] = i
i += 1
i = 0
for var in np.array(['Na', 'Kd', 'A', 'L', 'Kv', 'Kv_mut', 'T', 'Leak', 'Ca_K']):
ind_dict[var] = i
i += 1
# gating parameters
b_param['m'][:] = np.array([-40., -1. , 1.])
b_param['h'] = np.zeros(4)
b_param['h'][:] = np.array([-45.5, 1. , 1., 0.05])
b_param['n'][:] = np.array([-41., -1., 1.])
b_param['p'][:] = np.array([-56., -1., 1.])
b_param['q'][:] = np.array([-85., 1., 1.])
b_param['r'][:] = np.array([0.17, -0.08, 1.])
b_param['a'][:] = np.array([-45., -14.7, 1.])
b_param['b'][:] = np.array([-90., 7.5, 1.])
b_param['c'][:] = np.array([-30.6, -5., 1.])
b_param['d1'][:] = np.array([-60, 7.5, 1.])
b_param['d2'][:] = np.array([0.1, 0.02, 1.])
b_param['s'][:] = np.array([-14.16, -10.15, 1.])
b_param['u'] = np.zeros(4)
b_param['u'][:] = np.array([-31., 5.256, 1., 0.245])
b_param['s_mut'][:] = np.array([-14.16, -10.15, 1.])
b_param['u_mut'] = np.zeros(4)
b_param['u_mut'][:] = np.array([-31., 5.256, 1., 0.245])
# reversal potentials
E["Na"] = 60.
E["K"] = -90.
E["Leak"] = -60.
# model currents
currents_included["Na"] = True
currents_included["Kd"] =True
currents_included["Kv"] = True
currents_included["Kv_mut"] = False
currents_included["L"] = True
currents_included["T"] = True
currents_included["Ca_K"] = True
currents_included["A"] =True
currents_included["Leak"] = True
# model conductances
Kv_ratio = 0.01
g["Na"] = 49. * surf_area
g["Kd"] = 57. * (1-Kv_ratio)* surf_area
g["Kv"] = 57. * Kv_ratio * surf_area
g["Kv_mut"] = 0
g["A"] = 5. * surf_area
g["L"] = 5. * surf_area
g["T"] = 5. * surf_area
g["Ca_K"] = 1 * surf_area
g["Leak"] = 0.035 * surf_area
# save folder
folder = '../Sensitivity_Analysis/Data/STN_Kv'
if not os.path.isdir(folder):
os.makedirs(folder)
#%% setup for one-factor-at-a-time SA
var = np.array(['m', 'h', 'n', 'a', 'b', 's','u'])
type_names = np.append(np.array(['shift' for i in range(var.shape[0])]),
np.array(['slope' for i in range(var.shape[0])]))
cur = np.array(['Na', 'Kd', 'A','Kv', 'Leak'])
type_names = np.append(type_names, np.array(['g' for i in range(cur.shape[0])]))
var = np.append(var, var)
var = np.append(var, cur)
alt_types = np.c_[var, type_names]
lin_array = np.arange(-10, 11, 1)
log_array = np.logspace(-1,1,21, base=2)
# %% run SA with multiprocessing
prominence = 50
desired_AUC_width = high/5
Parallel(n_jobs=8, verbose=9)(
delayed(SA_Kv_STN)(V_init, g, E, I_in, dt, currents_included, stim_time, stim_num, C, shift, scale, b_param, slope_shift,
gating, current, prominence, desired_AUC_width, folder, high, low, number_steps, initial_period, sec,
vol, lin_array, log_array, alt_types, alt_ind, alt)
for alt_ind in range(alt_types.shape[0]) for alt in range(21))

View File

@ -1,333 +0,0 @@
"""
Script to analyse and collect data from simulations
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import pandas as pd
import h5py
import json
import os
import numpy as np
from ast import literal_eval
import string
import matplotlib.cm as cm
# %% rheo_{}_ex.csv, AUC_{}_ex.csv #####################################################################################
# Collect examples of effects of a shift, a slope change and a change in g on AUC and rheobase
## AUC ###################
AUC_shift = pd.DataFrame(columns=['alteration', 'RS Pyramidal', 'RS Inhibitory', 'FS', 'IB',
'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$','Cb stellate',
'Cb stellate +$K_V1.1$', 'Cb stellate $\Delta$$K_V1.1$', 'STN', 'STN +$K_V1.1$',
'STN $\Delta$$K_V1.1$'])
AUC_slope = pd.DataFrame(columns=['alteration', 'RS Pyramidal', 'RS Inhibitory', 'FS', 'IB',
'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$','Cb stellate',
'Cb stellate +$K_V1.1$', 'Cb stellate $\Delta$$K_V1.1$', 'STN', 'STN +$K_V1.1$',
'STN $\Delta$$K_V1.1$'])
AUC_g = pd.DataFrame(columns=['alteration', 'RS Pyramidal', 'RS Inhibitory', 'FS', 'IB',
'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$','Cb stellate',
'Cb stellate +$K_V1.1$', 'Cb stellate $\Delta$$K_V1.1$', 'STN', 'STN +$K_V1.1$',
'STN $\Delta$$K_V1.1$'])
script_dir = os.path.dirname(os.path.realpath("__file__"))
fname = os.path.join(script_dir, )
models = ['RS_pyramidal', 'RS_inhib', 'FS','RS_pyramidal_Kv', 'RS_inhib_Kv', 'FS_Kv', 'Cb_stellate','Cb_stellate_Kv',
'Cb_stellate_Kv_only','STN','STN_Kv', 'STN_Kv_only']
model_labels = ['RS Pyramidal','RS Inhibitory', 'FS','RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$',
'FS +$K_V1.1$','Cb stellate','Cb stellate +$K_V1.1$',
'Cb stellate $\Delta$$K_V1.1$','STN','STN +$K_V1.1$', 'STN $\Delta$$K_V1.1$']
shift_interest = 'n'
for i in range(len(models)):
with open('../Sensitivity_Analysis/Data/SA_summary_df/{}_shift_AUC.json'.format(models[i])) as json_file:
data = pd.read_json(json_file, convert_dates=False, convert_axes=False)
data.replace(0., np.NaN, inplace=True)
data = (data - data.loc['0', :])/ data.loc['0', :] # normalize AUC
data.sort_index(inplace=True)
AUC_shift[model_labels[i]] =data[shift_interest]
AUC_shift['alteration'] = AUC_shift.index
slope_interest = 's'
for i in range(len(models)):
with open('../Sensitivity_Analysis/Data/SA_summary_df/{}_slope_AUC.json'.format(models[i])) as json_file:
data = pd.read_json(json_file, convert_dates=False, convert_axes=False)
data.replace(0., np.NaN, inplace=True)
data = (data - data.loc['1.0', :])/ data.loc['1.0', :] # normalize AUC
data.sort_index(inplace=True)
try:
AUC_slope[model_labels[i]] = data[slope_interest]
except:
pass
AUC_slope['alteration'] = AUC_slope.index
g_interest = 'Kd'
for i in range(len(models)):
with open('../Sensitivity_Analysis/Data/SA_summary_df/{}_g_AUC.json'.format(models[i])) as json_file:
data = pd.read_json(json_file, convert_dates=False, convert_axes=False)
data.replace(0., np.NaN, inplace=True)
data = (data - data.loc['1.0', :])/ data.loc['1.0', :] # normalize AUC
data.sort_index(inplace=True)
AUC_g[model_labels[i]] =data[g_interest]
AUC_g['alteration'] = AUC_g.index
AUC_shift.to_csv('AUC_shift_ex.csv')
AUC_slope.to_csv('AUC_slope_ex.csv')
AUC_g.to_csv('AUC_g_ex.csv')
## rheobase ###################
rheo_shift = pd.DataFrame(columns=['alteration', 'RS Pyramidal', 'RS Inhibitory', 'FS', 'IB',
'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$','Cb stellate',
'Cb stellate +$K_V1.1$', 'Cb stellate $\Delta$$K_V1.1$', 'STN', 'STN +$K_V1.1$',
'STN $\Delta$$K_V1.1$'])
rheo_slope = pd.DataFrame(columns=['alteration', 'RS Pyramidal', 'RS Inhibitory', 'FS', 'RS Pyramidal +$K_V1.1$',
'RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$', 'Cb stellate', 'Cb stellate +$K_V1.1$',
'Cb stellate $\Delta$$K_V1.1$', 'STN', 'STN +$K_V1.1$','STN $\Delta$$K_V1.1$'])
rheo_g = pd.DataFrame(columns=['alteration', 'RS Pyramidal', 'RS Inhibitory', 'FS', 'IB',
'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$','Cb stellate',
'Cb stellate +$K_V1.1$', 'Cb stellate $\Delta$$K_V1.1$', 'STN', 'STN +$K_V1.1$',
'STN $\Delta$$K_V1.1$'])
script_dir = os.path.dirname(os.path.realpath("__file__"))
fname = os.path.join(script_dir, )
models = ['RS_pyramidal', 'RS_inhib', 'FS', 'RS_pyramidal_Kv', 'RS_inhib_Kv', 'FS_Kv', 'Cb_stellate', 'Cb_stellate_Kv', 'Cb_stellate_Kv_only', 'STN',
'STN_Kv',
'STN_Kv_only']
model_labels = ['RS Pyramidal','RS Inhibitory', 'FS','RS Pyramidal +$K_V1.1$', 'RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$',
'Cb stellate', 'Cb stellate +$K_V1.1$', 'Cb stellate $\Delta$$K_V1.1$', 'STN', 'STN +$K_V1.1$',
'STN $\Delta$$K_V1.1$']
shift_interest = 's'
for i in range(len(models)):
with open('../Sensitivity_Analysis/Data/SA_summary_df/{}_shift_rheo.json'.format(models[i])) as json_file:
data = pd.read_json(json_file, convert_dates=False, convert_axes=False)
data.replace(0., np.NaN, inplace=True)
data = (data - data.loc['0', :]) #/ data.loc['0', :] # normalize AUC
data.sort_index(inplace=True)
try:
rheo_shift[model_labels[i]] = data[shift_interest]
except:
pass
rheo_shift['alteration'] = rheo_shift.index
slope_interest = 'u'
for i in range(len(models)):
with open('../Sensitivity_Analysis/Data/SA_summary_df/{}_slope_rheo.json'.format(models[i])) as json_file:
data = pd.read_json(json_file, convert_dates=False, convert_axes=False)
data.replace(0., np.NaN, inplace=True)
data = (data - data.loc['1.0', :]) #/ data.loc['1.0', :] # normalize AUC
data.sort_index(inplace=True)
try:
rheo_slope[model_labels[i]] = data[slope_interest]
except:
pass
rheo_slope['alteration'] = rheo_slope.index
g_interest = 'Leak'
for i in range(len(models)):
with open('../Sensitivity_Analysis/Data/SA_summary_df/{}_g_rheo.json'.format(models[i])) as json_file:
data = pd.read_json(json_file, convert_dates=False, convert_axes=False)
data.replace(0., np.NaN, inplace=True)
data = (data - data.loc['1.0', :]) #/ data.loc['1.0', :] # normalize AUC
data.sort_index(inplace=True)
rheo_g[model_labels[i]] = data[g_interest]
rheo_g['alteration'] = rheo_g.index
rheo_shift.to_csv('rheo_shift_ex.csv')
rheo_slope.to_csv('rheo_slope_ex.csv')
rheo_g.to_csv('rheo_g_ex.csv')
# %% Model fI ##########################################################################################################
# for each model generate summary csv of sensitivity analysis results on AUC and rheobase
# | (index) | mag | alt | type | F | I |
# | 0 | -10 | m | shift | array | array |
models = ['RS Pyramidal', 'RS Inhibitory', 'FS', 'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate', 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN',
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']
model_save_name = {'RS Pyramidal': 'RS_pyr_posp', 'RS Inhibitory': 'RS_inhib_posp', 'FS': 'FS_posp',
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'RS_pyr_Kv',
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'RS_inhib_Kv',
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'FS_Kv',
'Cb stellate': 'Cb_stellate',
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'Cb_stellate_Kv',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'Cb_stellate_Kv_only',
'STN': 'STN',
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'STN_Kv',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'STN_Kv_only'}
top_file_dir = '../Sensitivity_Analysis/Data'
data_dir = {'RS Pyramidal': os.path.join(top_file_dir, 'RS_pyramidal_{}_fI.json'),
'RS Inhibitory': os.path.join(top_file_dir, 'RS_inhib_{}_fI.json'),
'FS': os.path.join(top_file_dir, 'FS_{}_fI.json'),
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'RS_pyramidal_{}_fI.json'),
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'RS_inhib_{}_fI.json'),
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'FS_{}_fI.json'),
'Cb stellate': os.path.join(top_file_dir, 'Cb_stellate_{}_fI.json'),
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'Cb_stellate_Kv_{}_fI.json'),
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'Cb_stellate_Kv_only_{}_fI.json'),
'STN': os.path.join(top_file_dir, 'STN_{}_fI.json'),
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'STN_Kv_{}_fI.json'),
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'STN_Kv_only_{}_fI.json')}
I_dir = {'RS Pyramidal': os.path.join(top_file_dir, 'RS_pyramidal_{}_I_mag.json'),
'RS Inhibitory': os.path.join(top_file_dir, 'RS_pyramidal_{}_I_mag.json'),
'FS': os.path.join(top_file_dir, 'RS_pyramidal_{}_I_mag.json'),
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'RS_pyramidal_{}_I_mag.json'),
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'RS_inhib_{}_I_mag.json'),
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'FS_{}_I_mag.json'),
'Cb stellate': os.path.join(top_file_dir, 'Cb_stellate_{}_I_mag.json'),
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'Cb_stellate_Kv_{}_I_mag.json'),
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'Cb_stellate_Kv_only_{}_I_mag.json'),
'STN': os.path.join(top_file_dir, 'STN_{}_I_mag.json'),
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'STN_Kv_{}_I_mag.json'),
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': os.path.join(top_file_dir, 'STN_Kv_only_{}_I_mag.json')}
def concat_dfs(df, data_dir, I_dir, type='shift'):
with open(data_dir.format(type)) as json_file:
data = pd.read_json(json_file, convert_axes=False)
with open(I_dir.format(type)) as json_file:
I = pd.read_json(json_file, convert_axes=False)
for c in data.columns:
# print(c)
df = df.append(pd.DataFrame(data=(np.array([data.index,['{}'.format(c) for i in range(0, len(data[c]))],
[type for i in range(0, len(data[c]))], data[c], I[c]]).T),
columns=['mag','alt', 'type', 'F', 'I']))
return df
summary_df = pd.DataFrame(columns=['mag','alt', 'type', 'F', 'I'])
for m in models:
print(m)
df = pd.DataFrame(columns=['mag','alt', 'type', 'F', 'I'])
df = concat_dfs(df, data_dir[m], I_dir[m], type='shift')
df = concat_dfs(df, data_dir[m], I_dir[m], type='slope')
df = concat_dfs(df, data_dir[m], I_dir[m], type='g')
folder = os.path.join(os.path.dirname(os.path.realpath("__file__")), 'Model_fI')
if not os.path.isdir(folder):
os.makedirs(folder)
df.to_csv(os.path.join(folder, '{}_fI.csv'.format(model_save_name[m])))
# %% firing_values.csv, model_spiking.csv, model_F_inf.csv #############################################################
# generate firing_values.csv with values for hysteresis from ramp current input
# generate model_spiking.csv with example model response to step current
# generate model_F_inf.csv with model fI curve data
import numpy as np
import pandas as pd
models = ['RS_pyramidal', 'RS_inhib', 'FS', 'RS_pyramidal_Kv', 'RS_inhib_Kv', 'FS_Kv', 'Cb_stellate', 'Cb_stellate_Kv',
'Cb_stellate_Kv_only', 'STN', 'STN_Kv', 'STN_Kv_only']
model_names = ['RS pyramidal', 'RS inhibitory', 'FS', 'RS pyramidal +Kv1.1', 'RS inhibitory +Kv1.1', 'FS +Kv1.1',
'Cb stellate', 'Cb stellate +Kv1.1', 'Cb stellate $\Delta$Kv1.1', 'STN', 'STN +Kv1.1',
'STN $\Delta$Kv1.1']
firing_values = pd.DataFrame(columns=models, index=['spike_ind', 'ramp_up', 'ramp_down'])
models = ['RS_pyr', 'RS_pyr_Kv', 'RS_inhib', 'RS_inhib_Kv', 'FS', 'FS_Kv',
'Cb_stellate', 'Cb_stellate_Kv', 'Cb_stellate_Delta_Kv',
'STN', 'STN_Kv', 'STN_Delta_Kv']
col_names = ['I', 'I_inhib']
for mod in models: col_names.append(mod)
model_F_inf = pd.DataFrame(columns=col_names)
col_names = ['t']
for mod in models: col_names.append(mod)
spiking = pd.DataFrame(columns=col_names)
# index for example trace
spike_ind = {'RS_pyramidal': 60, 'RS_inhib':25, 'FS':50, 'RS_pyramidal_Kv':60,
'RS_inhib_Kv':50, 'FS_Kv':50, 'Cb_stellate':60, 'Cb_stellate_Kv':130,
'Cb_stellate_Kv_only':75, 'STN': 25, 'STN_Kv':95, 'STN_Kv_only':80}
for model_name in models:
folder = '../Neuron_models/{}'.format(model_name)
fname = os.path.join(folder, "{}.hdf5".format(model_name)) # RS_inhib
with h5py.File(fname, "r+") as f:
I_mag = np.arange(f['data'].attrs['I_low'], f['data'].attrs['I_high'],
(f['data'].attrs['I_high'] - f['data'].attrs['I_low']) / f['data'].attrs['stim_num']) * 1000
start = np.int(f['data'].attrs['initial_period'] * 1 / f['data'].attrs['dt'])
stim_len = np.int((f['data'].attrs['stim_time'] - start) * f['data'].attrs['dt'])
time = np.arange(0, stim_len, f['data'].attrs['dt'])
spiking[model_name] = f['data']['V_m'][spike_ind[model_name]][start:]
model_F_inf[model_name] = f['analysis']['F_inf'][:]
firing_values.loc['spike_ind', model_name] = I_mag[spike_ind[model_name]]
firing_values.loc['ramp_down', model_name] = f['analysis']['ramp_I_down'][()]
firing_values.loc['ramp_up', model_name] = f['analysis']['ramp_I_up'][()]
firing_values.to_csv('firing_values.csv')
spiking.to_csv('model_spiking.csv')
model_F_inf.to_csv('model_F_inf.csv')
# %% model_ramp.csv ####################################################################################################
# generate model_ramp.csv with model responses to ramp input
# | (index) | t | models ....
import numpy as np
import pandas as pd
models = ['RS_pyramidal_Kv', 'RS_inhib_Kv', 'FS_Kv', 'Cb_stellate', 'Cb_stellate_Kv', 'Cb_stellate_Kv_only', 'STN',
'STN_Kv', 'STN_Kv_only']
model_names = ['RS pyramidal', 'RS inhibitory', 'FS', 'Cb stellate', 'Cb stellate +Kv1.1', 'Cb stellate $\Delta$Kv1.1',
'STN', 'STN +Kv1.1', 'STN $\Delta$Kv1.1']
col_names = ['t']
for mod in models: col_names.append(mod)
model_ramp = pd.DataFrame(columns=col_names)
sec = 4
dt = 0.01
ramp_len = int(sec * 1000 * 1 / dt)
t_ramp = np.arange(0, ramp_len) * dt
model_ramp.loc[:, 't'] = t_ramp
for model_name in models:
folder = '../Neuron_models/{}'.format(model_name)
fname = os.path.join(folder, "{}.hdf5".format(model_name)) # RS_inhib
with h5py.File(fname, "r+") as f:
model_ramp.loc[:, model_name] = f['analysis']['V_m_ramp'][()]
model_ramp.to_csv('model_ramp.csv')
#%% sim_mut_AUC.csv, sim_mut_rheo.csv ##################################################################################
# generate mutation plot data in sim_mut_AUC.csv and sim_mut_rheo.csv for the AUC and rheobase effects respectively for
# each mutation in each model
mutations = json.load(open("../KCNA1_mutations/mutations_effects_dict.json"))
keys_to_remove = ['V408L', 'T226R', 'R239S', 'R324T']
for key in keys_to_remove:
del mutations[key]
mutations_f = []
mutations_n = []
for mut in mutations:
mutations_n.append(mut)
mutations_f.append(mut.replace(" ", "_"))
models = ['RS_pyramidal_Kv', 'RS_inhib_Kv', 'FS_Kv', 'Cb_stellate', 'Cb_stellate_Kv', 'Cb_stellate_Kv_only', 'STN',
'STN_Kv', 'STN_Kv_only']
model_names = ['RS pyramidal', 'RS inhibitory', 'FS', 'Cb stellate', 'Cb stellate +Kv1.1', 'Cb stellate $\Delta$Kv1.1',
'STN', 'STN +Kv1.1', 'STN $\Delta$Kv1.1']
AUC = pd.DataFrame(columns=mutations_n)
rheobase = pd.DataFrame(columns=mutations_n)
save_folder = '../KCNA1_mutations'
if not os.path.isdir(save_folder):
os.makedirs(save_folder)
for model_name in models:
folder = '../KCNA1_mutations/{}'.format(model_name)
for mut in list(mutations_n):
fname = os.path.join(folder, "{}.hdf5".format(mut.replace(" ", "_")))
with h5py.File(fname, "r+") as f:
rheobase.loc[mut.replace(" ", "_"), model_name] = f['analysis']['rheobase'][()]
AUC.loc[mut.replace(" ", "_"), model_name] = f['analysis']['AUC'][()]
AUC.replace(0., np.NaN, inplace=True)
rheobase.replace(0., np.NaN, inplace=True)
rheobase = (rheobase - rheobase.loc['WT', :]) /rheobase.loc['WT', :]
AUC = (AUC - AUC.loc['WT', :]) /AUC.loc['WT', :]
AUC.to_csv(os.path.join(save_folder, 'sim_mut_AUC.csv'))
rheobase.to_csv(os.path.join(save_folder, 'sim_mut_rheobase.csv'))

View File

@ -1,311 +0,0 @@
"""
Script to analyse and collect data from sensitivity analysis simulations
"""
__author__ = "Nils A. Koch"
__copyright__ = 'Copyright 2022, Nils A. Koch'
__license__ = "MIT"
import numpy as np
import h5py
import pandas as pd
import os
from ast import literal_eval
import json
import scipy.stats as stats
# folder
top_dir = '../Sensitivity_Analysis/Data'
#%% create JSON files for each alt type for each model in '../Sensitivity_Analysis/Data/SA_summary_df/file.json'
for dir_name in next(os.walk(top_dir))[1]: # for each folder in top_file_dir (each model)
folder = os.path.join(top_dir, dir_name)
print(folder)
# for each alt_type create pandas dataframe
shift_AUC = pd.DataFrame()
shift_rheo = pd.DataFrame()
shift_fI = pd.DataFrame(dtype=object)
shift_I_mag = pd.DataFrame(dtype=object)
slope_AUC = pd.DataFrame()
slope_rheo = pd.DataFrame()
slope_fI = pd.DataFrame(dtype=object)
slope_I_mag = pd.DataFrame(dtype=object)
g_AUC = pd.DataFrame()
g_rheo = pd.DataFrame()
g_fI = pd.DataFrame(dtype=object)
g_I_mag = pd.DataFrame(dtype=object)
for root, dirs, files in os.walk(folder):
for file in files:
if file.endswith('.hdf5'):
with h5py.File(os.path.join(folder, file), "r+") as f:
alt = f['data'].attrs['alteration']
test = f['data'].attrs['alteration_info'].replace(' ', ',')
alt_info = literal_eval(test)
var = alt_info[0]
alt_type = alt_info[1]
if alt_type == 'shift':
shift_AUC.loc[alt, var] = f['analysis']['AUC'][()]
try:
shift_rheo.loc[alt, var] = f['analysis']['rheobase'][()]
except:
print('shift', var, alt)
shift_fI.loc[alt, var] = 0
shift_fI = shift_fI.astype(object)
shift_fI.at[alt, var] = f['analysis']['F_inf'][:].tolist()
shift_I_mag.loc[alt, var] = 0
shift_I_mag = shift_I_mag.astype(object)
shift_I_mag.at[alt, var] = ((np.arange(f['data'].attrs['I_low'], f['data'].attrs['I_high'],
(f['data'].attrs['I_high'] - f['data'].attrs['I_low']) /
f['data'].attrs['stim_num'])) * 1000).tolist() #nA
elif alt_type == 'slope':
slope_AUC.loc[alt, var] = f['analysis']['AUC'][()]
try:
slope_rheo.loc[alt, var] = f['analysis']['rheobase'][()]
except:
print('slope', var, alt)
slope_fI.loc[alt, var] = 0
slope_fI = slope_fI.astype(object)
slope_fI.at[alt, var] = f['analysis']['F_inf'][:].tolist()
slope_I_mag.loc[alt, var] = 0
slope_I_mag = slope_I_mag.astype(object)
slope_I_mag.at[alt, var] = ((np.arange(f['data'].attrs['I_low'], f['data'].attrs['I_high'],
(f['data'].attrs['I_high'] - f['data'].attrs['I_low']) /
f['data'].attrs['stim_num'])) * 1000).tolist()
elif alt_type == 'g':
g_AUC.loc[alt, var] = f['analysis']['AUC'][()]
try:
g_rheo.loc[alt, var] = f['analysis']['rheobase'][()]
except:
print('g', var, alt)
g_fI.loc[alt, var] = 0
g_fI = g_fI.astype(object)
g_fI.at[alt, var] = f['analysis']['F_inf'][:].tolist()
g_I_mag.loc[alt, var] = 0
g_I_mag = g_I_mag.astype(object)
g_I_mag.at[alt, var] = ((np.arange(f['data'].attrs['I_low'], f['data'].attrs['I_high'],
(f['data'].attrs['I_high'] - f['data'].attrs['I_low']) /
f['data'].attrs['stim_num'])) * 1000).tolist()
else:
print(file, 'Unknown alteration type')
#save df with folder+alt_type
save_folder = os.path.join(top_dir, 'SA_summary_df')
if not os.path.isdir(save_folder):
os.makedirs(save_folder)
shift_AUC.to_json(os.path.join(save_folder, '{}_shift_AUC.json'.format(dir_name)))
shift_rheo.to_json(os.path.join(save_folder, '{}_shift_rheo.json'.format(dir_name)))
shift_fI.to_json(os.path.join(save_folder, '{}_shift_fI.json'.format(dir_name)))
shift_I_mag.to_json(os.path.join(save_folder, '{}_shift_I_mag.json'.format(dir_name)))
slope_AUC.to_json(os.path.join(save_folder, '{}_slope_AUC.json'.format(dir_name)))
slope_rheo.to_json(os.path.join(save_folder, '{}_slope_rheo.json'.format(dir_name)))
slope_fI.to_json(os.path.join(save_folder, '{}_slope_fI.json'.format(dir_name)))
slope_I_mag.to_json(os.path.join(save_folder, '{}_slope_I_mag.json'.format(dir_name)))
g_AUC.to_json(os.path.join(save_folder, '{}_g_AUC.json'.format(dir_name)))
g_rheo.to_json(os.path.join(save_folder, '{}_g_rheo.json'.format(dir_name)))
g_fI.to_json(os.path.join(save_folder, '{}_g_fI.json'.format(dir_name)))
g_I_mag.to_json(os.path.join(save_folder, '{}_g_I_mag.json'.format(dir_name)))
#%% AUC Correlation analysis
alt_dict = {}
alt_dict['m'] = 'Na activation'
alt_dict['h'] = 'Na inactivation'
alt_dict['n'] = 'K activation'
alt_dict['s'] = '$K_V1.1$ activation'
alt_dict['u'] = '$K_V1.1$inactivation'
alt_dict['a'] = 'A activation'
alt_dict['b'] = 'A inactivation'
alt_dict['n_A'] = 'A activation'
alt_dict['h_A'] = 'A inactivation'
alt_dict['Na'] = 'Na'
alt_dict['Kd'] = 'K'
alt_dict['Kv'] = '$K_V1.1$'
alt_dict['A'] = 'A'
alt_dict['Leak'] = 'Leak'
# models = directory names in top_file_dir and what json files are named
models = ['RS_pyramidal', 'RS_inhib', 'FS', 'RS_pyramidal_Kv', 'RS_inhib_Kv', 'FS_Kv', 'Cb_stellate', 'Cb_stellate_Kv',
'Cb_stellate_Kv_only', 'STN', 'STN_Kv', 'STN_Kv_only']
# model_names = names of models for json files and ultimately csv files for plotting
model_names = ['RS Pyramidal','RS Inhibitory','FS', 'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$',
'Cb stellate','Cb stellate +$K_V1.1$', 'Cb stellate $\Delta$$K_V1.1$','STN','STN +$K_V1.1$', 'STN $\Delta$$K_V1.1$']
shift_df = pd.DataFrame(columns=['model', 'corr', 'p_value', 'local corr', 'local p_value', 'ratio', '$\Delta V_{1/2}$', 'color']) # for boxplots
for mod in range(len(models)):
with open('../Sensitivity_Analysis/Data/SA_summary_df/{}_shift_AUC.json'.format(models[mod])) as json_file:
df = pd.read_json(json_file)
df.sort_index(inplace=True)
df.replace(0., np.NaN, inplace=True)
df = (df - df.loc[0, :]) / df.loc[0, :]
zero_ind = np.argwhere(df.index == 0)[0][0]
ind = [df.index[zero_ind - 1], df.index[zero_ind], df.index[zero_ind + 1]]
df2 = df.loc[ind, :]
for c in df.keys():
tau, p = stats.kendalltau(df.index, df[c], nan_policy='omit')
tau_l, p_l = stats.kendalltau(df2.index, df2[c], nan_policy='omit')
ratio_tau = tau_l / tau
shift_df = shift_df.append(pd.Series([model_names[mod], tau, p,tau_l, p_l, ratio_tau, alt_dict[c],clr_dict[models[mod]]], index=shift_df.columns), ignore_index=True)
# models = directory names in top_file_dir and what json files are named
models = ['RS_pyramidal', 'RS_inhib', 'FS', 'RS_pyramidal_Kv', 'RS_inhib_Kv', 'FS_Kv', 'Cb_stellate', 'Cb_stellate_Kv',
'Cb_stellate_Kv_only', 'STN', 'STN_Kv', 'STN_Kv_only']
# model_names = names of models for json files and ultimately csv files for plotting
model_names = ['RS Pyramidal','RS Inhibitory','FS', 'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$',
'Cb stellate','Cb stellate +$K_V1.1$', 'Cb stellate $\Delta$$K_V1.1$','STN','STN +$K_V1.1$', 'STN $\Delta$$K_V1.1$']
slope_df = pd.DataFrame(columns=['model', 'corr', 'p_value','local corr', 'local p_value', 'ratio', 'Slope (k)', 'color']) # for boxplots
for mod in range(len(models)):
with open('../Sensitivity_Analysis/Data/SA_summary_df//{}_slope_AUC.json'.format(models[mod])) as json_file:
df = pd.read_json(json_file, convert_dates=False, convert_axes=False)
df.index = df.index.map(float)
df.sort_index(inplace=True)
df.replace(0., np.NaN, inplace=True)
df = (df - df.loc[1.0, :]) / df.loc[1.0, :]
zero_ind = np.argwhere(df.index == 1)[0][0]
ind = [df.index[zero_ind - 1], df.index[zero_ind], df.index[zero_ind + 1]]
df2 = df.loc[ind, :]
for c in df.keys():
tau, p = stats.kendalltau(df.index, df[c], nan_policy='omit')
tau_l, p_l = stats.kendalltau(df2.index, df2[c], nan_policy='omit')
ratio_tau = tau_l/tau
slope_df = slope_df.append(pd.Series([model_names[mod], tau, p, tau_l, p_l, ratio_tau, alt_dict[c],clr_dict[models[mod]]], index=slope_df.columns), ignore_index=True)
# models = directory names in top_file_dir and what json files are named
models = ['RS_pyramidal', 'RS_inhib', 'FS', 'RS_pyramidal_Kv', 'RS_inhib_Kv', 'FS_Kv', 'Cb_stellate', 'Cb_stellate_Kv',
'Cb_stellate_Kv_only', 'STN', 'STN_Kv', 'STN_Kv_only']
# model_names = names of models for json files and ultimately csv files for plotting
model_names = ['RS Pyramidal','RS Inhibitory','FS', 'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$',
'Cb stellate','Cb stellate +$K_V1.1$', 'Cb stellate $\Delta$$K_V1.1$','STN','STN +$K_V1.1$', 'STN $\Delta$$K_V1.1$']
g_df = pd.DataFrame(columns=['model', 'corr', 'p_value', 'local corr', 'local p_value', 'ratio', 'g', 'color']) # for boxplots
for mod in range(len(models)):
with open('../Sensitivity_Analysis/Data/SA_summary_df//{}_g_AUC.json'.format(models[mod])) as json_file:
df = pd.read_json(json_file, convert_dates=False, convert_axes=False)
df.index = df.index.map(float)
df.sort_index(inplace=True)
df.replace(0., np.NaN, inplace=True)
df = (df - df.loc[1.0, :]) / df.loc[1.0, :]
zero_ind = np.argwhere(df.index == 1)[0][0]
ind = [df.index[zero_ind - 1], df.index[zero_ind], df.index[zero_ind + 1]]
df2 = df.loc[ind, :]
for c in df.keys():
tau, p = stats.kendalltau(df.index, df[c], nan_policy='omit')
tau_l, p_l = stats.kendalltau(df2.index, df2[c], nan_policy='omit')
ratio_tau = tau_l / tau
g_df = g_df.append(pd.Series([model_names[mod], tau, p,tau_l, p_l, ratio_tau, alt_dict[c],clr_dict[models[mod]]], index=g_df.columns), ignore_index=True)
shift_df.to_json('./Sensitivity_analysis/shift_box_kendall_corr.json')
slope_df.to_json('./Sensitivity_analysis/slope_box_kendall_corr.json')
g_df.to_json('./Sensitivity_analysis/g_kendall_corr.json')
#%% rheobase correlation analysis
# models = directory names in top_file_dir and what json files are named
models = ['RS_pyramidal', 'RS_inhib', 'FS', 'RS_pyramidal_Kv', 'RS_inhib_Kv', 'FS_Kv', 'Cb_stellate', 'Cb_stellate_Kv',
'Cb_stellate_Kv_only', 'STN', 'STN_Kv', 'STN_Kv_only']
# model_names = names of models for json files and ultimately csv files for plotting
model_names = ['RS Pyramidal','RS Inhibitory','FS', 'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$',
'Cb stellate','Cb stellate +$K_V1.1$', 'Cb stellate $\Delta$$K_V1.1$','STN','STN +$K_V1.1$', 'STN $\Delta$$K_V1.1$']
shift_df = pd.DataFrame(columns=['model', 'corr', 'p_value', 'local corr', 'local p_value', 'ratio', '$\Delta V_{1/2}$', 'color']) # for boxplots
for mod in range(len(models)):
with open('../Sensitivity_Analysis/Data/SA_summary_df//{}_shift_rheo.json'.format(models[mod])) as json_file:
df = pd.read_json(json_file)
df.sort_index(inplace=True)
df.replace(0., np.NaN, inplace=True)
df = (df - df.loc[0, :]) / df.loc[0, :]
zero_ind = np.argwhere(df.index == 0)[0][0]
ind = [df.index[zero_ind - 1], df.index[zero_ind], df.index[zero_ind + 1]]
df2 = df.loc[ind, :]
for c in df.keys():
tau, p = stats.kendalltau(df.index, df[c], nan_policy='omit')
tau_l, p_l = stats.kendalltau(df2.index, df2[c], nan_policy='omit')
ratio_tau = tau_l / tau
shift_df = shift_df.append(pd.Series([model_names[mod], tau, p,tau_l, p_l, ratio_tau, alt_dict[c],clr_dict[models[mod]]], index=shift_df.columns), ignore_index=True)
# models = directory names in top_file_dir and what json files are named
models = ['RS_pyramidal', 'RS_inhib', 'FS', 'RS_pyramidal_Kv', 'RS_inhib_Kv', 'FS_Kv', 'Cb_stellate', 'Cb_stellate_Kv',
'Cb_stellate_Kv_only', 'STN', 'STN_Kv', 'STN_Kv_only']
# model_names = names of models for json files and ultimately csv files for plotting
model_names = ['RS Pyramidal','RS Inhibitory','FS', 'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$',
'Cb stellate','Cb stellate +$K_V1.1$', 'Cb stellate $\Delta$$K_V1.1$','STN','STN +$K_V1.1$', 'STN $\Delta$$K_V1.1$']
slope_df = pd.DataFrame(columns=['model', 'corr', 'p_value','local corr', 'local p_value', 'ratio', 'Slope (k)', 'color']) # for boxplots
for mod in range(len(models)):
with open('../Sensitivity_Analysis/Data/SA_summary_df//{}_slope_rheo.json'.format(models[mod])) as json_file:
df = pd.read_json(json_file, convert_dates=False, convert_axes=False)
df.index = df.index.map(float)
df.sort_index(inplace=True)
df.replace(0., np.NaN, inplace=True)
df = (df - df.loc[1.0, :]) / df.loc[1.0, :]
zero_ind = np.argwhere(df.index == 1)[0][0]
ind = [df.index[zero_ind - 1], df.index[zero_ind], df.index[zero_ind + 1]]
df2 = df.loc[ind, :]
for c in df.keys():
tau, p = stats.kendalltau(df.index, df[c], nan_policy='omit')
tau_l, p_l = stats.kendalltau(df2.index, df2[c], nan_policy='omit')
ratio_tau = tau_l/tau
slope_df = slope_df.append(pd.Series([model_names[mod], tau, p, tau_l, p_l, ratio_tau, alt_dict[c],clr_dict[models[mod]]], index=slope_df.columns), ignore_index=True)
# models = directory names in top_file_dir and what json files are named
models = ['RS_pyramidal', 'RS_inhib', 'FS', 'RS_pyramidal_Kv', 'RS_inhib_Kv', 'FS_Kv', 'Cb_stellate', 'Cb_stellate_Kv',
'Cb_stellate_Kv_only', 'STN', 'STN_Kv', 'STN_Kv_only']
# model_names = names of models for json files and ultimately csv files for plotting
model_names = ['RS Pyramidal','RS Inhibitory','FS', 'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$', 'FS +$K_V1.1$',
'Cb stellate','Cb stellate +$K_V1.1$', 'Cb stellate $\Delta$$K_V1.1$','STN','STN +$K_V1.1$', 'STN $\Delta$$K_V1.1$']
g_df = pd.DataFrame(columns=['model', 'corr', 'p_value', 'local corr', 'local p_value', 'ratio', 'g', 'color']) # for boxplots
for mod in range(len(models)):
with open('../Sensitivity_Analysis/Data/SA_summary_df//{}_g_rheo.json'.format(models[mod])) as json_file:
df = pd.read_json(json_file, convert_dates=False, convert_axes=False)
df.index = df.index.map(float)
df.sort_index(inplace=True)
df.replace(0., np.NaN, inplace=True)
df = (df - df.loc[1.0, :]) / df.loc[1.0, :]
zero_ind = np.argwhere(df.index == 1)[0][0]
ind = [df.index[zero_ind - 1], df.index[zero_ind], df.index[zero_ind + 1]]
df2 = df.loc[ind, :]
for c in df.keys():
tau, p = stats.kendalltau(df.index, df[c], nan_policy='omit')
tau_l, p_l = stats.kendalltau(df2.index, df2[c], nan_policy='omit')
ratio_tau = tau_l / tau
g_df = g_df.append(pd.Series([model_names[mod], tau, p,tau_l, p_l, ratio_tau, alt_dict[c],clr_dict[models[mod]]], index=g_df.columns), ignore_index=True)
shift_df.to_json('./Sensitivity_analysis/rheo_shift_box_kendall_corr.json')
slope_df.to_json('./Sensitivity_analysis/rheo_slope_box_kendall_corr.json')
g_df.to_json('./Sensitivity_analysis/rheo_g_kendall_corr.json')
#%% create csv files for plotting
# | (index) | model | corr | p_value | g | color
#% AUC
AUC_shift_json = pd.read_json('./Sensitivity_analysis/shift_kendall_corr_rel.json', orient='records')
AUC_slope_json = pd.read_json('./Sensitivity_analysis/slope_kendall_corr_rel.json', orient='records') #, lines=True)
AUC_g_json = pd.read_json('./Sensitivity_analysis/g_kendall_corr_rel.json', orient='records')
AUC_shift_df = AUC_shift_json[['model', 'corr', 'p_value', 'g', 'color']]
AUC_slope_df = AUC_slope_json[['model', 'corr', 'p_value', 'g', 'color']]
AUC_g_df = AUC_g_json[['model', 'corr', 'p_value', 'g', 'color']]
AUC_shift_df.to_csv('AUC_shift_corr.csv')
AUC_slope_df.to_csv('AUC_scale_corr.csv')
AUC_g_df.to_csv('AUC_g_corr.csv')
#% rheo
rheo_shift_json = pd.read_json('./Sensitivity_analysis/rheo_shift_kendall_corr.json', orient='records')
rheo_slope_json = pd.read_json('./Sensitivity_analysis/rheo_slope_kendall_corr.json', orient='records') #, lines=True)
rheo_g_json = pd.read_json('./Sensitivity_analysis/rheo_g_kendall_corr.json', orient='records')
rheo_shift_df = rheo_shift_json[['model', 'corr', 'p_value', 'g', 'color']]
rheo_slope_df = rheo_slope_json[['model', 'corr', 'p_value', 'g', 'color']]
rheo_g_df = rheo_g_json[['model', 'corr', 'p_value', 'g', 'color']]
rheo_shift_df.to_csv('rheo_shift_corr.csv')
rheo_slope_df.to_csv('rheo_scale_corr.csv')
rheo_g_df.to_csv('rheo_g_corr.csv')

View File

@ -1,47 +0,0 @@
# Bash shell script to run all simulations and analysis
# Individual Neuronal models
python ./Neuron_models/RS_pyramidal_model.py
python ./Neuron_models/RS_pyramidal_Kv_model.py
python ./Neuron_models/RS_inhib_model.py
python ./Neuron_models/RS_inhib_Kv_model.py
python ./Neuron_models/FS_model.py
python ./Neuron_models/FS_Kv_model.py
python ./Neuron_models/STN_model.py
python ./Neuron_models/STN_Kv_model.py
python ./Neuron_models/STN_Delta_Kv_model.py
python ./Neuron_models/Cb_stellate_model.py
python ./Neuron_models/Cb_stellate_Kv_model.py
python ./Neuron_models/Cb_stellate_Delta_Kv_model.py
# Sensitivity Analysis
python ./Sensitivity_Analysis/SA_RS_pyramidal.py
python ./Sensitivity_Analysis/SA_RS_pyramidal_Kv.py
python ./Sensitivity_Analysis/SA_RS_inhib.py
python ./Sensitivity_Analysis/SA_RS_inhib_Kv.py
python ./Sensitivity_Analysis/SA_FS.py
python ./Sensitivity_Analysis/SA_FS_Kv.py
python ./Sensitivity_Analysis/SA_STN.py
python ./Sensitivity_Analysis/SA_STN_Kv.py
python ./Sensitivity_Analysis/SA_STN_Delta_Kv.py
python ./Sensitivity_Analysis/SA_Cb_stellate.py
python ./Sensitivity_Analysis/SA_Cb_stellate_Kv.py
python ./Sensitivity_Analysis/SA_Cb_stellate_Delta_Kv.py
# KCNA1 mutations in models
python ./KCNA1_mutatoins/mut_RS_pyramidal_Kv.py
python ./KCNA1_mutatoins/mut_RS_inhib_Kv.py
python ./KCNA1_mutatoins/mut_FS_Kv.py
python ./KCNA1_mutatoins/mut_STN.py
python ./KCNA1_mutatoins/mut_STN_Kv.py
python ./KCNA1_mutatoins/mut_STN_Delta_Kv.py
python ./KCNA1_mutatoins/mut_Cb_stellate.py
python ./KCNA1_mutatoins/mut_Cb_stellate_Kv.py
python ./KCNA1_mutatoins/mut_Cb_stellate_Delta_Kv.py
# Data collection and csv generation
python SA_collection.py
python Plotting_data_collection.py

View File

@ -0,0 +1,292 @@
# Instructions for org mode export
# - to get export options: ctrl-c ctrl-e
# - to export as latex pdf: ctrl-c ctrl-e l p
#+OPTIONS: ':nil *:nil -:t ::t <:t H:3 \n:nil ^:t arch:headline
#+OPTIONS: author:nil broken-links:nil c:nil creator:nil
#+OPTIONS: d:(not "LOGBOOK") date:nil e:t email:nil f:t inline:t num:nil
#+OPTIONS: p:nil pri:nil prop:nil stat:t tags:t tasks:t tex:t
#+OPTIONS: timestamp:t title:nil toc:nil todo:nil |:t
#+TITLE: Nils Koch
#+DATE: <2021-08-16 Mon>
#+EMAIL: nils.koch@mail.mcgill.ca
#+TAGS: noexport(n)
#+LATEX_CLASS: article
#+LATEX_CLASS_OPTIONS: [letterpaper,10pt]
#+LATEX_HEADER: \usepackage[margin=0.6in]{geometry}
#+LATEX_HEADER: \usepackage{fontawesome}
#+LATEX_HEADER: \usepackage{titling}
#+LATEX_HEADER: \usepackage{titlesec}
#+LATEX_HEADER: \usepackage{fancyhdr}
#+LATEX_HEADER: \usepackage{setspace}
#+LATEX_HEADER: \usepackage{xcolor}
#+LATEX_HEADER: \usepackage{tabularx,xspace}
#+LATEX_HEADER: \usepackage{url}
#+LATEX_HEADER: \usepackage{academicons}
#+LATEX_HEADER: \usepackage{float}
#+LATEX_HEADER: \usepackage{hyperref}
#+LATEX_HEADER: \parindent=0in
#+LATEX_HEADER: \def\refname{\large References}
#+LATEX_HEADER: \newcommand{\eg}{e.g.\ }
#+LATEX_HEADER: \newcommand{\ie}{i.e.,\xspace }
#+LATEX_HEADER: \newcommand{\Aref}[1]{[A\ref{it:#1}]}
#+LATEX_HEADER: \newcommand{\Cref}[1]{[C\ref{it:#1}]}
#+LATEX_HEADER: \newcommand{\Pref}[1]{[P\ref{it:#1}]}
#+LATEX_HEADER: \usepackage{academicons}
#+LATEX_HEADER: \usepackage[breaklinks=true]{hyperref}
#+LATEX_HEADER: \usepackage{graphicx}
#+LATEX_HEADER: \usepackage{graphbox}
#+LATEX_HEADER: \usepackage{matlab-prettifier}
#+LATEX_HEADER: \usepackage[scaled]{helvet} \renewcommand\familydefault{\sfdefault}
#+LATEX_HEADER: \graphicspath{{./Figures/}}
#+LATEX_HEADER_EXTRA:
# For citation colors
#+LATEX_HEADER_EXTRA: \hypersetup{
#+LATEX_HEADER_EXTRA: colorlinks,
#+LATEX_HEADER_EXTRA: linkcolor={red!50!black},
#+LATEX_HEADER_EXTRA: citecolor={blue!50!black},
#+LATEX_HEADER_EXTRA: urlcolor={black!70}
#+LATEX_HEADER_EXTRA: }
#+DESCRIPTION:
#+KEYWORDS:
#+subtitle:
#+LATEX_COMPILER: pdflatex
#+BEGIN_EXPORT latex
\renewcommand{\maketitle}
\maketitle{
\begin{center}
\Huge \textbf{Update on Figures}}}\\
\end{center}
}
%\thispagestyle{empty} %remove header on first page
\titleformat{\section}{\Large\bfseries}{\thesection}{0pt}{}
\titleformat{\subsection}{\large\bfseries}{\thesection}{0pt}{}
\titlespacing*{\section}{0pt}{0ex}{0ex}
\titlespacing*{\subsection}{0pt}{0ex}{0ex}
\titlespacing*{\itemsep}{0pt}{0ex}{0ex}
\pagestyle{fancy}
\fancyhf{}
\renewcommand{\headrulewidth}{0pt} % remove lines as well
\renewcommand{\footrulewidth}{0pt} % remove lines as well
%\lfoot{\textcolor{black!50}{\footnotesize \today}}
%\cfoot{\textcolor{black!50}{\footnotesize Nils Koch }}
\rfoot{\textcolor{black!50}{\thepage}}
%\lhead{}
\chead{\today}
%\rhead{}
\newcommand{\squishlist}{
\begin{list}{$\bullet$}
{ \setlength{\itemsep}{0pt} \setlength{\parsep}{3pt} \setlength{\topsep}{3pt} \setlength{\partopsep}{0pt}
\setlength{\leftmargin}{1.5em} \setlength{\labelwidth}{1em} \setlength{\labelsep}{0.5em} } }
\newcommand{\squishend}{\end{list} }
#+END_EXPORT
* Firing Characterization:
** Question figure addresses:
Firing is a complicated phenomenon. How can it be simply characterized to compare the
effects of changes in current properties?
** Method by which data is generated:
Schematic diagram that does not contain underlying data - contains different square
root functions.
** Conclusion from Figure:
Firing can be characterized by the rheobase and the AUC (proprotional to the increase in
firing after the rheobase). The rheobase and firing in a small range above it (AUC) are
likely important for determining network excitability (I think this makes sense,
would need references to support this).
#+BEGIN_EXPORT latex
\begin{figure}[H]
\includegraphics[align=c,width=10cm]{firing_characterization.pdf}
\caption{A. Demonstrates AUC in cyan. B. Demonstrates what combinations of increased and
decreased rheobase and AUC look like in terms of fI curves.}
\label{fig:firing_charact}
\end{figure}
#+END_EXPORT
* Diversity in Model Firing:
We have used a number of neuronal models that do not burst to look at the effects
of changes in current properties in firing given different cell types/current
environments
** Question figure addresses:
Which model is used?
** Rationale:
The effect of a change in a current property cannot be assessed in only one cell
type to understand the general effects of this change and to assess whether differences
occur across cell types.
** Method by which data is generated:
Models from different sources are used and an example spike train is shown for each model
along with a fI curve. The black dot on the fI curve indicates where the spike train is
taken from and the green and red dots indicate the current at which the first and last
spike occurs from an increasing and decreasing current ramp respectively. (These ramps
can be seen in the ramp figure at the end).
** Conclusion from Figure:
The models use are diverse and display a variety of spike shapes, firing behaviours, and
fI curve shapes.
#+BEGIN_EXPORT latex
\begin{figure}[H]
\includegraphics[align=c,width=18cm]{diversity_in_firing.pdf}
\caption{Spike trains and corresponding fI curves from: A. Cb stellate, B. RS Inhibitory,
C. FS, D. RS Pyramidal, E. RS Inhibitory +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
F. Cb stellate +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
G. FS +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
H. RS Pyramidal +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\), I. STN +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
J.Cb stellate \(\Delta\)\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\) , K. STN \(\Delta\)\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\), L. STN,
where +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\) indicates the addition of Kv1.1 to the model
and \(\Delta\)\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\) indicates the exchange of the A type K+ current for Kv1.1. The black
dot on the fI curve indicates where the spike train is taken from and the green and red
dots indicate the current at which the first and last spike occurs from an increasing and
decreasing current ramp respectively.}
\label{fig:div_firing}
\end{figure}
#+END_EXPORT
* IB model issue: :noexport:
** Issue Background:
IB (intrinsicially bursting) model from Pospischil et al. 2008 uses a leak conductance
of 0.1. This results in bursting like firing initially (see bottom right of Figure
\ref{fig:IB}) and requires large currents to be injected (> 0.75 nA). When the Kv1.1
current is added to this model (bottom right Figure \ref{fig:IB}) the bursting
behaviour is diminished but the currents needed to get firing are still high. As a
result I decreased the leak conductance by a factor of 10 to 0.01 as seen in the
upper right of Figure \ref{fig:IB}. This is the model that I used for the sensitivity
analysis and modelling of Kv1.1 mutations. However, when the original IB model has a
reduced leak current (of 0.01) it bursts and only for a small current range (see upper
left of Figure \ref{fig:IB}).
** Issue:
Which model to use? To use the model with reduced leak that has nice properties with
Kv1.1 added, the bursting and weird fI curve of the model without Kv1.1 needs to be
addressed (bursting is not well captured by the analysis methods). To use the model with
the large leak current (the original model), the large input currents is concerning and
the sensitivity analysis and Kv1.1 mutation modelling would need to be re-done for this
model with and without Kv1.1 (with 20/24 cores on the Kraken this would take 2-3 days
I think). Alternatively, as neither option really sits well with me, we could remove this
model from all figure and discussion and focus on the other models that in their
original states (and with Kv1.1 added) have repetitive firing without bursting.
#+BEGIN_EXPORT latex
\begin{figure}[H]
\includegraphics[align=c,width=15cm]{IB_issue_plot.pdf}
\caption{The fI curves and exampling spike trains from the IB model with different
Leak conductances without and with (+Kv1.1) Kv1.1 conductance.}
\label{fig:IB}
\end{figure}
#+END_EXPORT
* Rheobase Sensitivity Analysis:
I am not yet happy with this figure's layout
** Question figure addresses:
How is rheobase affected by changes in current properties across models? Is the change
in rheobase always in the same direction across models?
** Method by which data is generated:
A one factor at a time (OFAT) sensitivity analysis was performed on the currents common
to all or most models, where one current property was changed systematically at a time,
the firing responses simulated and the fI curves computed. From this fI curve the
largest injected current at which no firing occurs and the smallest injected
current at which firing occurs were obtained. This current interval was then simulated
to obtain the rheobase at greater resolution.
** Conclusion from Figure:
Generally the effect on rheobase is similar across all models/current environments
#+BEGIN_EXPORT latex
\begin{figure}[H]
\includegraphics[align=c,width=18cm]{rheobase_correlation.pdf}
\caption{}
\label{fig:rheo}
\end{figure}
#+END_EXPORT
* AUC Sensitivity Analysis:
I prefer the first layout
** Question figure addresses:
How is AUC affected by changes in current properties across models? Is the change
in AUC rheobase always in the same direction across models?
** Method by which data is generated:
A one factor at a time (OFAT) sensitivity analysis was performed on the currents common
to all or most models, where one current property was changed systematically at a time,
the firing responses simulated and the steady-state fI curves computed. From this fI
curve the largest injected current at which no firing occurs was obtained and the
integral from this current using the composite trapezoidal rule for 1/5 of the current
range.
** Conclusion from Figure:
A given current property change does not necessarily cause the same
change in rheobase and as such the outcome of a given change is dependent on the
current environment or cell type.
#+BEGIN_EXPORT latex
\begin{figure}[H]
\includegraphics[align=c,width=18cm]{AUC_correlation.pdf}
\caption{}
\label{fig:AUC}
\end{figure}
#+END_EXPORT
* Kv1.1 mutation simulation:
** Question figure addresses:
Do mutations of Kv1.1 cause similar effects on firing across cell types or is the effect
cell type (and thus neuronal network) dependent?
** Method by which data is generated:
Published Kv1.1 mutations (Lauxmann et al 2021) are simulated in all models containing
Kv1.1 or an inactivating K^+ current by altering the current properties according to
those experimentally measured for each mutation. The firing of each model for each
mutation are then simulated and the rheobase and AUC are computed.
** Conclusion from Figure:
The effects of Kv1.1 mutations on rheobase are highly correlated across models indicating
that these mutations affect the rheobase in a similar fashion. However, the effect of
Kv1.1 mutations vary across models as seen by the different correlation magnitudes
between models. Thus although these mutations affect rheobase in a similar manner, the
effect on AUC cannot easily be generalized and depends on cell type.
Furthermore, this Figure demonstrates why characterization of mutations in terms of
LOF or GOF in relation to firing overlooks potentially important characteristics of
the changes in firing seen in different cell types. Thus, the characterization LOF
and GOF is useful at a channel level to characterize the effects of a mutation on
the current, but cannot and should not be blindly extended to characterize the
effects of the mutation on firing as LOF and GOF, not only because the current
environment in which this mutation occurs is a key determinant of the firing outcome,
but also that firing is complex and not easily characterized as LOF or GOF.
#+BEGIN_EXPORT latex
\begin{figure}[H]
\includegraphics[align=c,width=18cm]{simulation_model_comparison.pdf}
\caption{}
\label{fig:kv11}
\end{figure}
#+END_EXPORT
* Ramp Firing - For Supplements?:
** Question figure addresses:
How does the firing of the models look like with a ramp protocol?
** Method by which data is generated:
A 4 second ramp with the same current range as the step currents used to obtain fI
plots is used and the firing of all models is simulated. The resulting spike trains
are plotted.
** Conclusion from Figure:
The diversity of firing seen with step currents is also seen with current ramps. The
ramps highlight the hysteresis in models.
#+BEGIN_EXPORT latex
\begin{figure}[H]
\includegraphics[align=c,width=20cm]{ramp_firing.pdf}
\caption{A. Cb stellate, B. RS Inhibitory,
C. FS, D. RS Pyramidal, E. RS Inhibitory +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
F. Cb stellate +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
G. FS +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
H. RS Pyramidal +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\), I. STN +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
J.Cb stellate \(\Delta\)\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\) , K. STN \(\Delta\)\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\), L. STN,
where +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\) indicates the addition of Kv1.1 to the model
and \(\Delta\)\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\) indicates the exchange of the A type K+
current for Kv1.1.}
\label{fig:ramp}
\end{figure}
#+END_EXPORT

View File

@ -0,0 +1,278 @@
% Created 2022-02-16 Wed 15:41
% Intended LaTeX compiler: pdflatex
\documentclass[letterpaper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{grffile}
\usepackage{longtable}
\usepackage{wrapfig}
\usepackage{rotating}
\usepackage[normalem]{ulem}
\usepackage{amsmath}
\usepackage{textcomp}
\usepackage{amssymb}
\usepackage{capt-of}
\usepackage{hyperref}
\usepackage[margin=0.6in]{geometry}
\usepackage{fontawesome}
\usepackage{titling}
\usepackage{titlesec}
\usepackage{fancyhdr}
\usepackage{setspace}
\usepackage{xcolor}
\usepackage{tabularx,xspace}
\usepackage{url}
\usepackage{academicons}
\usepackage{float}
\usepackage{hyperref}
\parindent=0in
\def\refname{\large References}
\newcommand{\eg}{e.g.\ }
\newcommand{\ie}{i.e.,\xspace }
\newcommand{\Aref}[1]{[A\ref{it:#1}]}
\newcommand{\Cref}[1]{[C\ref{it:#1}]}
\newcommand{\Pref}[1]{[P\ref{it:#1}]}
\usepackage{academicons}
\usepackage[breaklinks=true]{hyperref}
\usepackage{graphicx}
\usepackage{graphbox}
\usepackage{matlab-prettifier}
\usepackage[scaled]{helvet} \renewcommand\familydefault{\sfdefault}
\graphicspath{{./Figures/}}
\hypersetup{
colorlinks,
linkcolor={red!50!black},
citecolor={blue!50!black},
urlcolor={black!70}
}
\date{}
\title{Nils Koch}
\hypersetup{
pdfauthor={},
pdftitle={Nils Koch},
pdfkeywords={},
pdfsubject={},
pdfcreator={Emacs 27.2 (Org mode 9.4.4)},
pdflang={English}}
\begin{document}
\renewcommand{\maketitle}
\maketitle{
\begin{center}
\Huge \textbf{Update on Figures}}}\\
\end{center}
}
%\thispagestyle{empty} %remove header on first page
\titleformat{\section}{\Large\bfseries}{\thesection}{0pt}{}
\titleformat{\subsection}{\large\bfseries}{\thesection}{0pt}{}
\titlespacing*{\section}{0pt}{0ex}{0ex}
\titlespacing*{\subsection}{0pt}{0ex}{0ex}
\titlespacing*{\itemsep}{0pt}{0ex}{0ex}
\pagestyle{fancy}
\fancyhf{}
\renewcommand{\headrulewidth}{0pt} % remove lines as well
\renewcommand{\footrulewidth}{0pt} % remove lines as well
%\lfoot{\textcolor{black!50}{\footnotesize \today}}
%\cfoot{\textcolor{black!50}{\footnotesize Nils Koch }}
\rfoot{\textcolor{black!50}{\thepage}}
%\lhead{}
\chead{\today}
%\rhead{}
\newcommand{\squishlist}{
\begin{list}{$\bullet$}
{ \setlength{\itemsep}{0pt} \setlength{\parsep}{3pt} \setlength{\topsep}{3pt} \setlength{\partopsep}{0pt}
\setlength{\leftmargin}{1.5em} \setlength{\labelwidth}{1em} \setlength{\labelsep}{0.5em} } }
\newcommand{\squishend}{\end{list} }
\section*{Firing Characterization:}
\label{sec:org2ff19f9}
\subsection*{Question figure addresses:}
\label{sec:org39e44a3}
Firing is a complicated phenomenon. How can it be simply characterized to compare the
effects of changes in current properties?
\subsection*{Method by which data is generated:}
\label{sec:org8f27edf}
Schematic diagram that does not contain underlying data - contains different square
root functions.
\subsection*{Conclusion from Figure:}
\label{sec:org219d22f}
Firing can be characterized by the rheobase and the AUC (proprotional to the increase in
firing after the rheobase). The rheobase and firing in a small range above it (AUC) are
likely important for determining network excitability (I think this makes sense,
would need references to support this).
\begin{figure}[H]
\includegraphics[align=c,width=10cm]{firing_characterization.pdf}
\caption{A. Demonstrates AUC in cyan. B. Demonstrates what combinations of increased and
decreased rheobase and AUC look like in terms of fI curves.}
\label{fig:firing_charact}
\end{figure}
\section*{Diversity in Model Firing:}
\label{sec:org2d2ab53}
We have used a number of neuronal models that do not burst to look at the effects
of changes in current properties in firing given different cell types/current
environments
\subsection*{Question figure addresses:}
\label{sec:org2a68d8a}
Which model is used?
\subsection*{Rationale:}
\label{sec:org574a416}
The effect of a change in a current property cannot be assessed in only one cell
type to understand the general effects of this change and to assess whether differences
occur across cell types.
\subsection*{Method by which data is generated:}
\label{sec:orgf4eccc9}
Models from different sources are used and an example spike train is shown for each model
along with a fI curve. The black dot on the fI curve indicates where the spike train is
taken from and the green and red dots indicate the current at which the first and last
spike occurs from an increasing and decreasing current ramp respectively. (These ramps
can be seen in the ramp figure at the end).
\subsection*{Conclusion from Figure:}
\label{sec:org2b1b0e7}
The models use are diverse and display a variety of spike shapes, firing behaviours, and
fI curve shapes.
\begin{figure}[H]
\includegraphics[align=c,width=18cm]{diversity_in_firing.pdf}
\caption{Spike trains and corresponding fI curves from: A. Cb stellate, B. RS Inhibitory,
C. FS, D. RS Pyramidal, E. RS Inhibitory +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
F. Cb stellate +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
G. FS +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
H. RS Pyramidal +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\), I. STN +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
J.Cb stellate \(\Delta\)\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\) , K. STN \(\Delta\)\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\), L. STN,
where +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\) indicates the addition of Kv1.1 to the model
and \(\Delta\)\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\) indicates the exchange of the A type K+ current for Kv1.1. The black
dot on the fI curve indicates where the spike train is taken from and the green and red
dots indicate the current at which the first and last spike occurs from an increasing and
decreasing current ramp respectively.}
\label{fig:div_firing}
\end{figure}
\section*{Rheobase Sensitivity Analysis:}
\label{sec:org482a6cf}
I am not yet happy with this figure's layout
\subsection*{Question figure addresses:}
\label{sec:org8d09846}
How is rheobase affected by changes in current properties across models? Is the change
in rheobase always in the same direction across models?
\subsection*{Method by which data is generated:}
\label{sec:org679728a}
A one factor at a time (OFAT) sensitivity analysis was performed on the currents common
to all or most models, where one current property was changed systematically at a time,
the firing responses simulated and the fI curves computed. From this fI curve the
largest injected current at which no firing occurs and the smallest injected
current at which firing occurs were obtained. This current interval was then simulated
to obtain the rheobase at greater resolution.
\subsection*{Conclusion from Figure:}
\label{sec:orgab5a050}
Generally the effect on rheobase is similar across all models/current environments
\begin{figure}[H]
\includegraphics[align=c,width=18cm]{rheobase_correlation.pdf}
\caption{}
\label{fig:rheo}
\end{figure}
\section*{AUC Sensitivity Analysis:}
\label{sec:org84023d3}
I prefer the first layout
\subsection*{Question figure addresses:}
\label{sec:org2aedc23}
How is AUC affected by changes in current properties across models? Is the change
in AUC rheobase always in the same direction across models?
\subsection*{Method by which data is generated:}
\label{sec:org7f21d20}
A one factor at a time (OFAT) sensitivity analysis was performed on the currents common
to all or most models, where one current property was changed systematically at a time,
the firing responses simulated and the steady-state fI curves computed. From this fI
curve the largest injected current at which no firing occurs was obtained and the
integral from this current using the composite trapezoidal rule for 1/5 of the current
range.
\subsection*{Conclusion from Figure:}
\label{sec:org2c7ad14}
A given current property change does not necessarily cause the same
change in rheobase and as such the outcome of a given change is dependent on the
current environment or cell type.
\begin{figure}[H]
\includegraphics[align=c,width=18cm]{AUC_correlation.pdf}
\caption{}
\label{fig:AUC}
\end{figure}
\section*{Kv1.1 mutation simulation:}
\label{sec:org747834c}
\subsection*{Question figure addresses:}
\label{sec:orgcae797a}
Do mutations of Kv1.1 cause similar effects on firing across cell types or is the effect
cell type (and thus neuronal network) dependent?
\subsection*{Method by which data is generated:}
\label{sec:org58691da}
Published Kv1.1 mutations (Lauxmann et al 2021) are simulated in all models containing
Kv1.1 or an inactivating K\^{}+ current by altering the current properties according to
those experimentally measured for each mutation. The firing of each model for each
mutation are then simulated and the rheobase and AUC are computed.
\subsection*{Conclusion from Figure:}
\label{sec:org4808be0}
The effects of Kv1.1 mutations on rheobase are highly correlated across models indicating
that these mutations affect the rheobase in a similar fashion. However, the effect of
Kv1.1 mutations vary across models as seen by the different correlation magnitudes
between models. Thus although these mutations affect rheobase in a similar manner, the
effect on AUC cannot easily be generalized and depends on cell type.
Furthermore, this Figure demonstrates why characterization of mutations in terms of
LOF or GOF in relation to firing overlooks potentially important characteristics of
the changes in firing seen in different cell types. Thus, the characterization LOF
and GOF is useful at a channel level to characterize the effects of a mutation on
the current, but cannot and should not be blindly extended to characterize the
effects of the mutation on firing as LOF and GOF, not only because the current
environment in which this mutation occurs is a key determinant of the firing outcome,
but also that firing is complex and not easily characterized as LOF or GOF.
\begin{figure}[H]
\includegraphics[align=c,width=18cm]{simulation_model_comparison.pdf}
\caption{}
\label{fig:kv11}
\end{figure}
\section*{Ramp Firing - For Supplements?:}
\label{sec:orgde070fe}
\subsection*{Question figure addresses:}
\label{sec:org86a05b7}
How does the firing of the models look like with a ramp protocol?
\subsection*{Method by which data is generated:}
\label{sec:org4560e37}
A 4 second ramp with the same current range as the step currents used to obtain fI
plots is used and the firing of all models is simulated. The resulting spike trains
are plotted.
\subsection*{Conclusion from Figure:}
\label{sec:orgdda18ae}
The diversity of firing seen with step currents is also seen with current ramps. The
ramps highlight the hysteresis in models.
\begin{figure}[H]
\includegraphics[align=c,width=20cm]{ramp_firing.pdf}
\caption{A. Cb stellate, B. RS Inhibitory,
C. FS, D. RS Pyramidal, E. RS Inhibitory +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
F. Cb stellate +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
G. FS +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
H. RS Pyramidal +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\), I. STN +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\),
J.Cb stellate \(\Delta\)\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\) , K. STN \(\Delta\)\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\), L. STN,
where +\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\) indicates the addition of Kv1.1 to the model
and \(\Delta\)\(\mathrm{K}_{\mathrm{V}}\mathrm{1.1}\) indicates the exchange of the A type K+
current for Kv1.1.}
\label{fig:ramp}
\end{figure}
\end{document}

View File

@ -0,0 +1,159 @@
% Created 2022-02-16 Wed 15:40
% Intended LaTeX compiler: pdflatex
\documentclass[presentation]{beamer}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{grffile}
\usepackage{longtable}
\usepackage{wrapfig}
\usepackage{rotating}
\usepackage[normalem]{ulem}
\usepackage{amsmath}
\usepackage{textcomp}
\usepackage{amssymb}
\usepackage{capt-of}
\usepackage{hyperref}
\usepackage[backend=bibtex,sorting=none, style=numeric-comp, citestyle=numeric-comp]{biblatex}
\usepackage{endnotes}
\bibliography{H2v01.bib} %% point at your bib file
\usepackage{tikz,bm}
\usepackage{epstopdf}
\graphicspath{{./Figures/}}
\definecolor{mcgillred}{RGB}{237, 27, 47}
\definecolor{darkred}{RGB}{158,9,24}
\definecolor{palegray}{RGB}{244,244,244}
\definecolor{grayt}{RGB}{180,180,180}
\definecolor{grayb}{RGB}{228,228,228}
\definecolor{black}{RGB}{0,0,0}
\setbeamercolor{palette primary}{bg=mcgillred,fg=white}
\setbeamercolor{palette secondary}{bg=mcgillred,fg=white}
\setbeamercolor{palette tertiary}{bg=mcgillred,fg=white}
\setbeamercolor{palette tertiary}{bg=mcgillred,fg=white}
\setbeamercolor{structure}{fg=mcgillred}
\setbeamercolor{title}{fg=mcgillred}
\setbeamercolor{frametitle}{fg=mcgillred}
\setbeamercolor{block body}{bg=palegray,fg=black}
\setbeamercolor{block title}{bg=mcgillred,fg=white}
\setbeamerfont{title}{size=\Large, series=\bfseries}
\setbeamercolor{alerted text}{fg=black}
\setbeamerfont{alerted text}{series=\bfseries}
\setbeamercolor{block title alerted}{bg=red,fg=black}
\setbeamerfont{block title alerted}{series=\mdseries}
\newcommand{\nox}{\(\mathrm{NO_{x}}\)}
\newlength\figH
\newlength\figW
\setbeamertemplate{caption}{\raggedright\insertcaption\par}
\setbeamerfont{caption}{size=\tiny}
\setlength\abovecaptionskip{-5pt}
\renewcommand{\footnote}{\endnote}
\usepackage{animate}
\usetheme{Boadilla}
\author{Nils Koch}
\date{}
\title{Figure update}
\subtitle{}
\hypersetup{
pdfauthor={Nils Koch},
pdftitle={Figure update},
pdfkeywords={},
pdfsubject={},
pdfcreator={Emacs 27.2 (Org mode 9.4.4)},
pdflang={English}}
\begin{document}
\maketitle
\section{Introduction}
\label{sec:org79d6537}
\begin{frame}[label={sec:orgb1bc930}]{Intro to org to Beamer}
\begin{itemize}
\item This is not that visually appealling, but I haven't taken the time to set the colors and style to my liking in the Latex header
\item I have tried to include as many examples of things I find useful as possible
\begin{itemize}
\item sometimes this makes the slide not make much sense, but the example of how to do things is hopefully useful
\end{itemize}
\item The only slight pain with using org for both Beamer and normal Latex pdf is:
\begin{itemize}
\item you cannot have the pdf open in some pdf viewers and export to it (eg adobe)
\item I use Sumatra (\url{https://www.sumatrapdfreader.org/free-pdf-reader})
\begin{itemize}
\item can have your pdf open in sumatra, export to it and it will update the pdf to the new exported file while open
\end{itemize}
\end{itemize}
\end{itemize}
\end{frame}
\section{Figure update}
\label{sec:org5e0c8fa}
\begin{frame}[label={sec:org9c64cb6}]{Firing Characterization}
\vspace{-0.5cm}
\begin{columns}
\begin{column}[t]{0.65\columnwidth}
\begin{itemize}
\item Firing is a complicated phenomenon
\item How to best characterize it?
\begin{itemize}
\item rheobase
\item AUC
\end{itemize}
\end{itemize}
\end{column}
\begin{column}[t]{0.35\columnwidth}
\begin{center}
\includegraphics[width=0.95\textwidth]{firing_characterization.pdf}
\end{center}
\end{column}
\end{columns}
\end{frame}
\begin{frame}[label={sec:orgca6ec9d}]{Diversity in Firing Properties of the Models}
\begin{center}
\includegraphics[width=0.55\textwidth]{diversity_in_firing.pdf}
\end{center}
\end{frame}
\begin{frame}[label={sec:org47d8006}]{Sensitivy analysis: OFAT}
\vspace{-2cm}
\begin{itemize}
\item[{$\square$}] one factor at a time sensitivity analysis
\item simulate firing responses
\begin{itemize}
\item compute fI curves
\begin{itemize}
\item get rheobase
\item compute AUC
\end{itemize}
\end{itemize}
\end{itemize}
\end{frame}
\begin{frame}[label={sec:org7ee95f9}]{Rheobase sensitivity Analysis}
\begin{center}
\includegraphics[width=0.85\textwidth]{rheobase_correlation.pdf}
\end{center}
\tiny Koch et al. 2022
\end{frame}
\begin{frame}[label={sec:org43a0268}]{AUC Sensitivity Analysis}
\begin{itemize}
\item AUC = area under the curve
\end{itemize}
\begin{center}
\includegraphics[width=0.75\textwidth]{AUC_correlation.pdf}
\end{center}
\begin{itemize}
\item AUC over the initial non-zero fI curve is a proxy for slope
\end{itemize}
\end{frame}
\begin{frame}[label={sec:orgba8be96}]{\(K_V1.1\) Mutations}
\begin{center}
\includegraphics[width=0.95\textwidth]{simulation_model_comparison.pdf}
\end{center}
\end{frame}
\begin{frame}[label={sec:orgbe7a060}]{Ramp Firing}
\begin{center}
\includegraphics[width=0.95\textwidth]{ramp_firing.pdf}
\end{center}
\end{frame}
\end{document}

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 441 KiB

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 273 KiB

View File

@ -13,14 +13,7 @@ import matplotlib
import matplotlib.lines as mlines
from matplotlib import ticker
from matplotlib.ticker import NullFormatter
from Figures.plotstyle import boxplot_style
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
#%% ##################### From https://stackoverflow.com/questions/52878845/swarmplot-with-hue-affecting-marker-beyond-color ##
# to change marker types in seaborn swarmplot
@ -51,7 +44,7 @@ def GetColor2Marker(markers):
mkcolors = [(palette[i]) for i in range(len(markers))]
return dict(zip(mkcolors,markers))
def fixlegend(ax,markers,markersize=3,**kwargs):
def fixlegend(ax,markers,markersize=8,**kwargs):
# Fix Legend
legtitle = ax.get_legend().get_title().get_text()
_,l = ax.get_legend_handles_labels()
@ -93,27 +86,13 @@ def new_scatter(self, *args, **kwargs):
return FinalCollection
Axes.scatter = new_scatter
############## End hack. ##############
########################################################################################################################
#%% add gradient arrows
import matplotlib.pyplot as plt
import matplotlib.transforms
import matplotlib.path
from matplotlib.collections import LineCollection
def gradientaxis(ax, start, end, cmap, n=100,lw=1):
# Arrow shaft: LineCollection
x = np.linspace(start[0],end[0],n)
y = np.linspace(start[1],end[1],n)
points = np.array([x,y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)
lc = LineCollection(segments, cmap=cmap, linewidth=lw,zorder=15)
lc.set_array(np.linspace(0,1,n))
ax.add_collection(lc)
return ax
#%%
#%%
def boxplot_with_markers(ax,max_width, alteration='shift', msize=3):
hlinewidth = 0.5
def boxplot_with_markers(ax,max_width, alteration='shift'):
# size =4
# ax.tick_params(axis='x', rotation=90)
model_names = ['RS pyramidal','RS inhibitory','FS',
'RS pyramidal +$K_V1.1$','RS inhibitory +$K_V1.1$',
'FS +$K_V1.1$','Cb stellate','Cb stellate +$K_V1.1$',
@ -134,9 +113,23 @@ def boxplot_with_markers(ax,max_width, alteration='shift', msize=3):
'#873770', # magenta
]
# colorslist = ['#40A787', # cyan'#
# '#F0D730', # yellow
# 'C02717', # red
# '#007030', # dark green
# '#AAB71B', # lightgreen
# '#008797', # light blue
# '#F78017', # orange
# '#478010', # green
# '#53379B', # purple
# '#2060A7', # blue
# '#873770', # magenta
# '#D03050' # pink
# ]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
colors = [matplotlib.colors.to_rgb(c) for c in colorslist] # sns.color_palette("hls", 14, desat=0.75)#[cm.tab20(i) for i in range(20)]
clr_dict = {}
for m in range(len(model_names)):
clr_dict[model_names[m]] = colors[m]
@ -146,60 +139,72 @@ def boxplot_with_markers(ax,max_width, alteration='shift', msize=3):
ax.axvspan(i - 0.4, i + 0.4, fill=False, edgecolor = 'k')
df = pd.read_csv('./Figures/Data/AUC_shift_corr.csv')
sns.swarmplot(y="corr", x="$\Delta V_{1/2}$", hue="model", data=df,
palette=clr_dict, linewidth=0, orient='v', ax=ax, size=msize,
palette=clr_dict, linewidth=0, orient='v', ax=ax,
order=['Na activation', 'Na inactivation', 'K activation', '$K_V1.1$ activation',
'$K_V1.1$ inactivation', 'A activation', 'A inactivation'],
hue_order=model_names, co2mk=Markers)
lim = ax.get_xlim()
ax.plot([lim[0], lim[1]], [0, 0], ':r',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [1, 1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [-1, -1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [0, 0], ':r')
ax.plot([lim[0], lim[1]], [1, 1], ':k')
ax.plot([lim[0], lim[1]], [-1, -1], ':k')
# ax.get_legend().remove()
# sns.despine(trim=True, bottom=True, ax=ax)
# ax.set(xlabel=None, ylabel=r'Kendall $\it{\tau}$')
ax.set_title("Shift ($\Delta V_{1/2}$)", y=1.05)
ax.set_xticklabels(['Na \nactivation', 'Na \ninactivation', 'K \nactivation', '$K_V1.1$ \nactivation',
'$K_V1.1$ \ninactivation', 'A \nactivation', 'A \ninactivation'])
elif alteration=='slope':
i = 3 # Kv1.1 act
ax.axvspan(i - 0.4, i + 0.4, fill=False, edgecolor='k')
df = pd.read_csv('./Figures/Data/AUC_scale_corr.csv')
# Add in points to show each observation
sns.swarmplot(y="corr", x="Slope (k)", hue="model", data=df,
palette=clr_dict, linewidth=0, orient='v', ax=ax, size=msize,
sns.swarmplot(y="corr", x="Slope (k)", hue="model", data=df, #dodge=True,
palette=clr_dict, linewidth=0, orient='v', ax=ax,
order=['Na activation', 'Na inactivation', 'K activation', '$K_V1.1$ activation',
'$K_V1.1$ inactivation', 'A activation', 'A inactivation'],
hue_order=model_names, co2mk=Markers)
lim = ax.get_xlim()
ax.plot([lim[0], lim[1]], [0, 0], ':r',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [1, 1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [-1, -1], ':k',linewidth=hlinewidth)
# ax.plot([lim[0], lim[1]], [0,0], ':k')
ax.plot([lim[0], lim[1]], [0, 0], ':r')
ax.plot([lim[0], lim[1]], [1, 1], ':k')
ax.plot([lim[0], lim[1]], [-1, -1], ':k')
# Markers = ["o","s","v","^","<",">","p","h","P","X","D","*","8","o"]
# ax=fixlegend(ax, Markers)
# Tweak the visual presentation
# ax.get_legend().remove()
# ax.xaxis.grid(False)
# ax.set_xticklabels(textwrap.fill(x.get_text(), max_width) for x in ax.get_xticklabels())
# ax.set(xlabel=None, ylabel=r'Kendall $\it{\tau}$')
ax.set_title("Slope (k)", y=1.05)
ax.set_xticklabels(['Na \nactivation', 'Na \ninactivation', 'K \nactivation', '$K_V1.1$ \nactivation',
'$K_V1.1$ \ninactivation', 'A \nactivation', 'A \ninactivation'])
# sns.despine(trim=True, bottom=True, ax=ax)
elif alteration=='g':
i = 1 # Kd
ax.axvspan(i - 0.4, i + 0.4, fill=False, edgecolor='k')
df = pd.read_csv('./Figures/Data/AUC_g_corr.csv')
# Add in points to show each observation
sns.swarmplot(y="corr", x="g", hue="model", data=df,
palette=clr_dict, linewidth=0, orient='v', ax=ax, size=msize,
sns.swarmplot(y="corr", x="g", hue="model", data=df, #dodge=True,
palette=clr_dict, linewidth=0, orient='v', ax=ax,
order=['Na', 'K', '$K_V1.1$', 'A', 'Leak'],
hue_order=model_names, co2mk=Markers)
lim = ax.get_xlim()
# ax.plot([lim[0], lim[1]], [0,0], ':k')
ax.plot([lim[0], lim[1]], [0, 0], ':r',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [1, 1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [-1, -1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [0, 0], ':r')
ax.plot([lim[0], lim[1]], [1, 1], ':k')
ax.plot([lim[0], lim[1]], [-1, -1], ':k')
# Tweak the visual presentation
# ax.xaxis.grid(False)
# sns.despine(trim=True, bottom=True, ax=ax)
# ax.set(xlabel=None, ylabel=r'Kendall $\it{\tau}$')
ax.set_title("Conductance (g)", y=1.05)
ax.set_xticklabels(textwrap.fill(x.get_text(), max_width) for x in ax.get_xticklabels())
# ax.set_xticklabels(textwrap.fill(x.get_text(), max_width) for x in ax.get_xticklabels())
else:
print('Please chose "shift", "slope" or "g"')
ax.get_legend().remove()
ax.xaxis.grid(False)
sns.despine(trim=True, bottom=True, ax=ax)
ax.set(xlabel=None, ylabel=r'Kendall $\it{\tau}$')
ax.set_xticklabels(textwrap.fill(x.get_text(), max_width) for x in ax.get_xticklabels())
# fixlegend(ax, Markers)
def model_legend(ax, marker_s_leg, pos, ncol):
colorslist = [ '#40A787', # cyan'#
@ -216,13 +221,15 @@ def model_legend(ax, marker_s_leg, pos, ncol):
'#D03050' # pink
]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
colors = [matplotlib.colors.to_rgb(c) for c in colorslist] #sns.color_palette("hls", 14, desat=0.75) #[cm.tab20(i) for i in range(20)]
model_pos = {'Cb stellate':0, 'RS Inhibitory':1, 'FS':2, 'RS Pyramidal':3,
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':4,
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':5, 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':6,
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':7, 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':8,
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':9,
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':10, 'STN':11}
Markers = ["o", "o", "o", "^", "^", "^", "D", "D", "D", "s", "s", "s"]
RS_p = mlines.Line2D([], [], color=colors[model_pos['RS Pyramidal']], marker=Markers[model_pos['RS Pyramidal']], markersize=marker_s_leg, linestyle='None',
label='RS pyramidal')
@ -284,7 +291,8 @@ def plot_AUC_alt(ax, model='FS', color1='red', color2='dodgerblue', alteration='
]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
colors = [matplotlib.colors.to_rgb(c) for c in
colorslist] #sns.color_palette("hls", 14, desat=0.75)#[cm.tab20(i) for i in range(20)]
clr_dict = {}
for m in range(len(model_names)):
clr_dict[model_names[m]] = colors[m]
@ -298,42 +306,24 @@ def plot_AUC_alt(ax, model='FS', color1='red', color2='dodgerblue', alteration='
ax.set_xticks([0.5, 1, 2])
ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
ax.xaxis.set_minor_formatter(NullFormatter())
ax.set_xlabel('$k$/$k_{WT}$')
ax.set_xlabel('Slope factor k')
elif alteration=='g':
df = pd.read_csv('./Figures/Data/AUC_g_ex.csv')
ax.set_xscale("log")
ax.set_xticks([0.5, 1, 2])
ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
ax.xaxis.set_minor_formatter(NullFormatter())
ax.set_xlabel('$g$/$g_{WT}$')
ax.set_xlabel('g')
for mod in model_names:
if mod == model_name_dict[model]:
ax.plot(df['alteration'], df[mod], color=clr_dict[mod], alpha=1, zorder=10, linewidth=2)
else:
ax.plot(df['alteration'], df[mod], color=clr_dict[mod],alpha=0.5, zorder=1, linewidth=1)
if alteration=='shift':
ax.set_ylabel('Normalized $\Delta$AUC', labelpad=4)
else:
ax.set_ylabel('Normalized $\Delta$AUC', labelpad=0)
ax.plot(df['alteration'], df[mod], color=clr_dict[mod],alpha=1, zorder=1, linewidth=1)
ax.set_ylabel('Normalized AUC')
x = df['alteration']
y = df[model_name_dict[model]]
ax.set_xlim(x.min(), x.max())
ax.set_ylim(df[model_names].min().min(), df[model_names].max().max())
# x axis color gradient
cvals = [-2., 2]
colors = ['lightgrey', 'k']
norm = plt.Normalize(min(cvals), max(cvals))
tuples = list(zip(map(norm, cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
(xstart, xend) = ax.get_xlim()
(ystart, yend) = ax.get_ylim()
print(ystart, yend)
start = (xstart, ystart * 1.0)
end = (xend, ystart * 1.0)
ax = gradientaxis(ax, start, end, cmap, n=200, lw=4)
ax.spines['bottom'].set_visible(False)
return ax
def plot_fI(ax, model='RS Pyramidal', type='shift', alt='m', color1='red', color2='dodgerblue'):
@ -366,7 +356,7 @@ def plot_fI(ax, model='RS Pyramidal', type='shift', alt='m', color1='red', color
c += 1
ax.set_ylabel('Frequency [Hz]')
ax.set_xlabel('Current [nA]')
ax.set_title(model, x=0.2, y=1.0)
ax.set_title(model)
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
L = ax.get_ylim()
@ -375,7 +365,6 @@ def plot_fI(ax, model='RS Pyramidal', type='shift', alt='m', color1='red', color
#%%
boxplot_style()
color_dict = {'Cb stellate': '#40A787', # cyan'#
'RS Inhibitory': '#F0D730', # yellow
'FS': '#C02717', # red
@ -389,67 +378,58 @@ color_dict = {'Cb stellate': '#40A787', # cyan'#
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#873770', # magenta
'STN': '#D03050' # pink
}
model_letter = {
'Cb stellate': 'A',
'RS Inhibitory': 'B',
'FS': 'C',
'RS Pyramidal': 'D',
'RS Inhibitory': 'E',
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'F',
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'G',
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'H',
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'I',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'J',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'K',
'STN':'L',
}
# plot setup
marker_s_leg = 2
max_width = 20
pad_x = 0.85
pad_y= 0.4
pad_w = 1.1
pad_h = 0.7
fig = plt.figure()
gs = fig.add_gridspec(3, 7, wspace=1.2, hspace=1.)
ax0 = fig.add_subplot(gs[0,2:7])
marker_s_leg = 8
max_width = 10
pad_x = 0.6
pad_y= 0.3
pad_w = 0.8
pad_h = 0.5
fig = plt.figure(figsize=(18,10))
gs = fig.add_gridspec(3, 6, wspace=0.9)
plt.subplots_adjust(hspace=0.8) #, wspace=0.6
ax0 = fig.add_subplot(gs[0,2:6])
ax0_ex = fig.add_subplot(gs[0,1])
ax0_fI = fig.add_subplot(gs[0,0])
ax1 = fig.add_subplot(gs[1,2:7])
ax1 = fig.add_subplot(gs[1,2:6])
ax1_ex = fig.add_subplot(gs[1,1])
ax1_fI = fig.add_subplot(gs[1,0])
ax2 = fig.add_subplot(gs[2,2:7])
ax2 = fig.add_subplot(gs[2,2:6])
ax2_ex = fig.add_subplot(gs[2,1])
ax2_fI = fig.add_subplot(gs[2,0])
line_width = 1
# plot fI examples
ax0_fI = plot_fI(ax0_fI, model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='shift', alt='s', color1='lightgrey', color2='k')
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=line_width,transform=ax0_fI.transAxes, color=color_dict['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=2,transform=ax0_fI.transAxes, color=color_dict['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = ax0_fI.add_patch(rec)
rec.set_clip_on(False)
ax1_fI = plot_fI(ax1_fI, model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='slope', alt='u', color1='lightgrey', color2='k')
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=line_width,transform=ax1_fI.transAxes, color=color_dict['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=2,transform=ax1_fI.transAxes, color=color_dict['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = ax1_fI.add_patch(rec)
rec.set_clip_on(False)
ax2_fI = plot_fI(ax2_fI, model='STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='g', alt='Leak', color1='lightgrey', color2='k')
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=line_width,transform=ax2_fI.transAxes, color=color_dict['STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=2,transform=ax2_fI.transAxes, color=color_dict['STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = ax2_fI.add_patch(rec)
rec.set_clip_on(False)
# label subplots with letters
ax0_fI.text(-0.6, 1.28, string.ascii_uppercase[0], transform=ax0_fI.transAxes, size=16, weight='bold') #-0.09
ax1_fI.text(-0.6, 1.28, string.ascii_uppercase[1], transform=ax1_fI.transAxes,size=16, weight='bold')
ax2_fI.text(-0.6, 1.28, string.ascii_uppercase[2], transform=ax2_fI.transAxes,size=16, weight='bold')
# plot boxplots
boxplot_with_markers(ax0,max_width, alteration='shift')
boxplot_with_markers(ax1,max_width, alteration='slope')
boxplot_with_markers(ax2,max_width, alteration='g')
# plot legend
pos = (0.225, -0.9)
ncol = 5
pos = (0.25, -0.6)
ncol = 6
model_legend(ax2, marker_s_leg, pos, ncol)
# plot examples
@ -457,21 +437,76 @@ plot_AUC_alt(ax0_ex,model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='l
plot_AUC_alt(ax1_ex,model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k',alteration='slope')
plot_AUC_alt(ax2_ex, model='STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k', alteration='g')
# label subplots with letters
ax0_fI.text(-0.875, 1.35, string.ascii_uppercase[0], transform=ax0_fI.transAxes, size=10, weight='bold')
ax0_ex.text(-0.8, 1.35, string.ascii_uppercase[1], transform=ax0_ex.transAxes, size=10, weight='bold')
ax0.text(-0.075, 1.35, string.ascii_uppercase[2], transform=ax0.transAxes, size=10, weight='bold')
ax1_fI.text(-0.875, 1.35, string.ascii_uppercase[3], transform=ax1_fI.transAxes,size=10, weight='bold')
ax1_ex.text(-0.8, 1.35, string.ascii_uppercase[4], transform=ax1_ex.transAxes, size=10, weight='bold')
ax1.text(-0.075, 1.35, string.ascii_uppercase[5], transform=ax1.transAxes, size=10, weight='bold')
ax2_fI.text(-0.875, 1.35, string.ascii_uppercase[6], transform=ax2_fI.transAxes,size=10, weight='bold')
ax2_ex.text(-0.8, 1.35, string.ascii_uppercase[7], transform=ax2_ex.transAxes, size=10, weight='bold')
ax2.text(-0.075, 1.35, string.ascii_uppercase[8], transform=ax2.transAxes, size=10, weight='bold')
#save
fig.set_size_inches(cm2inch(20.75,12))
fig.savefig('./Figures/AUC_correlation.pdf', dpi=fig.dpi) #pdf #eps
# fig.savefig('./Figures/AUC_correlation.png', dpi=fig.dpi) #pdf #eps
fig.savefig('./Figures/AUC_correlation.pdf', bbox_inches='tight', dpi=fig.dpi)
plt.show()
# #%% alternative layout
# # boxplot_style()
# marker_s_leg = 8
# max_width = 10
# pad_x = 0.2
# pad_y= 0.4
# pad_w = 0.22
# pad_h = 0.6
#
# fig = plt.figure(figsize=(12,20))
# gs = fig.add_gridspec(3, 1, hspace=0.4, wspace=0.4)
# gs0 = gs[0].subgridspec(2, 4, wspace=0.6, hspace=1.)
# gs1 = gs[1].subgridspec(2, 4, wspace=0.6, hspace=1.)
# gs2 = gs[2].subgridspec(2, 4, wspace=0.6, hspace=1.)
# ax0 = fig.add_subplot(gs0[1,:])
# ax0_ex = fig.add_subplot(gs0[0,2:])
# ax0_fI = fig.add_subplot(gs0[0,:2])
# ax1 = fig.add_subplot(gs1[1,:])
# ax1_ex = fig.add_subplot(gs1[0,2:])
# ax1_fI = fig.add_subplot(gs1[0,:2])
# ax2 = fig.add_subplot(gs2[1,:])
# ax2_ex = fig.add_subplot(gs2[0,2:])
# ax2_fI = fig.add_subplot(gs2[0,:2])
#
#
# ax0_fI = plot_fI(ax0_fI, model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='shift', alt='s', color1='lightgrey', color2='k')
# rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=2,transform=ax0_fI.transAxes, color=color_dict['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
# rec = ax0_fI.add_patch(rec)
# rec.set_clip_on(False)
#
# ax1_fI = plot_fI(ax1_fI, model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='slope', alt='u', color1='lightgrey', color2='k')
# rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=2,transform=ax1_fI.transAxes, color=color_dict['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
# rec = ax1_fI.add_patch(rec)
# rec.set_clip_on(False)
#
# ax2_fI = plot_fI(ax2_fI, model='STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='g', alt='Leak', color1='lightgrey', color2='k')
# rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=2,transform=ax2_fI.transAxes, color=color_dict['STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
# rec = ax2_fI.add_patch(rec)
# rec.set_clip_on(False)
#
# # label subplots with letters
# ax0_fI.text(-0.2, 1.38, string.ascii_uppercase[0], transform=ax0_fI.transAxes, size=16, weight='bold') #-0.09
# ax1_fI.text(-0.2, 1.38, string.ascii_uppercase[1], transform=ax1_fI.transAxes,size=16, weight='bold')
# ax2_fI.text(-0.2, 1.38, string.ascii_uppercase[2], transform=ax2_fI.transAxes,size=16, weight='bold')
#
# # plot boxplots
# boxplot_with_markers(ax0,max_width, alteration='shift')
# boxplot_with_markers(ax1,max_width, alteration='slope')
# boxplot_with_markers(ax2,max_width, alteration='g')
# # plot legend
# pos = (0.5, -1.)
# ncol = 6
# model_legend(ax2, marker_s_leg, pos, ncol)
#
# # # plot rheo across model for example alteration
# # plot_rheo_alt(ax0_ex,model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='red', color2='maroon', alteration='shift')
# # plot_rheo_alt(ax1_ex,model='Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='orchid', color2='purple',alteration='slope')
# # plot_rheo_alt(ax2_ex, model='Cb stellate', color1='darkviolet', color2='indigo', alteration='g')
# # plot_rheo_alt(ax0_ex,model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k', alteration='shift')
# # plot_rheo_alt(ax1_ex,model='Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k',alteration='slope')
# # plot_rheo_alt(ax2_ex, model='Cb stellate', color1='lightgrey', color2='k', alteration='g')
#
# # plot examples
# plot_AUC_alt(ax0_ex,model='FS', color1='lightgrey', color2='k', alteration='shift')
# plot_AUC_alt(ax1_ex,model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k',alteration='slope')
# plot_AUC_alt(ax2_ex, model='STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k', alteration='g')
# fig.savefig('AUC_correlation_2.pdf', bbox_inches='tight') #
# # plt.saveas(fig, 'AUC_correlation_2.png')
# plt.show()

View File

@ -1,543 +0,0 @@
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 3 19:52:04 2021
@author: nils
"""
import pandas as pd
import numpy as np
import string
import textwrap
import json
import matplotlib
import matplotlib.lines as mlines
from matplotlib import ticker
from matplotlib.ticker import NullFormatter
from Figures.plotstyle import boxplot_style
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
#%% ##################### From https://stackoverflow.com/questions/52878845/swarmplot-with-hue-affecting-marker-beyond-color ##
# to change marker types in seaborn swarmplot
import seaborn as sns
import matplotlib.pyplot as plt
############## Begin hack ##############
from matplotlib.axes._axes import Axes
from matplotlib.markers import MarkerStyle
from numpy import ndarray
def GetColor2Marker(markers):
colorslist = ['#40A787', # cyan'#
'#F0D730', # yellow
'#C02717', # red
'#007030', # dark green
'#AAB71B', # lightgreen
'#008797', # light blue
'#F78017', # orange
'#478010', # green
'#53379B', # purple
'#2060A7', # blue
'#873770', # magenta
'#D03050' # pink
]
import matplotlib.colors
palette = [matplotlib.colors.to_rgb(c) for c in colorslist]
mkcolors = [(palette[i]) for i in range(len(markers))]
return dict(zip(mkcolors,markers))
def fixlegend(ax,markers,markersize=3,**kwargs):
# Fix Legend
legtitle = ax.get_legend().get_title().get_text()
_,l = ax.get_legend_handles_labels()
colorslist = ['#40A787', # cyan'#
'#F0D730', # yellow
'#C02717', # red
'#007030', # dark green
'#AAB71B', # lightgreen
'#008797', # light blue
'#F78017', # orange
'#478010', # green
'#53379B', # purple
'#2060A7', # blue
'#873770', # magenta
'#D03050' # pink
]
import matplotlib.colors
palette = [matplotlib.colors.to_rgb(c) for c in colorslist]
mkcolors = [(palette[i]) for i in range(len(markers))]
newHandles = [plt.Line2D([0],[0], ls="none", marker=m, color=c, mec="none", markersize=markersize,**kwargs) \
for m,c in zip(markers, mkcolors)]
ax.legend(newHandles,l)
leg = ax.get_legend()
leg.set_title(legtitle)
old_scatter = Axes.scatter
def new_scatter(self, *args, **kwargs):
colors = kwargs.get("c", None)
co2mk = kwargs.pop("co2mk",None)
FinalCollection = old_scatter(self, *args, **kwargs)
if co2mk is not None and isinstance(colors, ndarray):
Color2Marker = GetColor2Marker(co2mk)
paths=[]
for col in colors:
mk=Color2Marker[tuple(col)]
marker_obj = MarkerStyle(mk)
paths.append(marker_obj.get_path().transformed(marker_obj.get_transform()))
FinalCollection.set_paths(paths)
return FinalCollection
Axes.scatter = new_scatter
############## End hack. ##############
########################################################################################################################
#%% add gradient arrows
import matplotlib.pyplot as plt
import matplotlib.transforms
import matplotlib.path
from matplotlib.collections import LineCollection
def gradientaxis(ax, start, end, cmap, n=100,lw=1):
# Arrow shaft: LineCollection
x = np.linspace(start[0],end[0],n)
y = np.linspace(start[1],end[1],n)
points = np.array([x,y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)
lc = LineCollection(segments, cmap=cmap, linewidth=lw,zorder=15)
lc.set_array(np.linspace(0,1,n))
ax.add_collection(lc)
return ax
#%%
#%%
def boxplot_with_markers(ax,max_width, alteration='shift', msize=3):
hlinewidth = 0.5
model_names = ['RS pyramidal','RS inhibitory','FS',
'RS pyramidal +$K_V1.1$','RS inhibitory +$K_V1.1$',
'FS +$K_V1.1$','Cb stellate','Cb stellate +$K_V1.1$',
'Cb stellate $\Delta$$K_V1.1$','STN','STN +$K_V1.1$',
'STN $\Delta$$K_V1.1$']
colorslist = ['#007030', # dark green
'#F0D730', # yellow
'#C02717', # red
'#478010', # green
'#AAB71B', # lightgreen
'#F78017', # orange
'#40A787', # cyan'#
'#008797', # light blue
'#2060A7', # blue
'#D03050', # pink
'#53379B', # purple
'#873770', # magenta
]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
clr_dict = {}
for m in range(len(model_names)):
clr_dict[model_names[m]] = colors[m]
print(colors)
print(clr_dict)
Markers = ["o", "o", "o", "^", "^", "^", "D", "D", "D", "s", "s", "s"]
if alteration=='shift':
i = 2 # Kd act
ax.axvspan(i - 0.4, i + 0.4, fill=False, edgecolor = 'k')
df = pd.read_csv('./Figures/Data/AUC_shift_corr.csv')
sns.swarmplot(y="corr", x="$\Delta V_{1/2}$", hue="model", data=df,
palette=clr_dict, linewidth=0, orient='v', ax=ax, size=msize,
order=['Na activation', 'Na inactivation', 'K activation', '$K_V1.1$ activation',
'$K_V1.1$ inactivation', 'A activation', 'A inactivation'],
hue_order=model_names, co2mk=Markers)
lim = ax.get_xlim()
ax.plot([lim[0], lim[1]], [0, 0], ':r',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [1, 1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [-1, -1], ':k',linewidth=hlinewidth)
ax.set_title("Shift ($\Delta V_{1/2}$)", y=1.05)
ax.set_xticklabels(['Na \nactivation', 'Na \ninactivation', 'K \nactivation', '$K_V1.1$ \nactivation',
'$K_V1.1$ \ninactivation', 'A \nactivation', 'A \ninactivation'])
elif alteration=='slope':
i = 3 # Kv1.1 act
ax.axvspan(i - 0.4, i + 0.4, fill=False, edgecolor='k')
df = pd.read_csv('./Figures/Data/AUC_scale_corr.csv')
# Add in points to show each observation
sns.swarmplot(y="corr", x="Slope (k)", hue="model", data=df,
palette=clr_dict, linewidth=0, orient='v', ax=ax, size=msize,
order=['Na activation', 'Na inactivation', 'K activation', '$K_V1.1$ activation',
'$K_V1.1$ inactivation', 'A activation', 'A inactivation'],
hue_order=model_names, co2mk=Markers)
lim = ax.get_xlim()
ax.plot([lim[0], lim[1]], [0, 0], ':r',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [1, 1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [-1, -1], ':k',linewidth=hlinewidth)
ax.set_title("Slope (k)", y=1.05)
ax.set_xticklabels(['Na \nactivation', 'Na \ninactivation', 'K \nactivation', '$K_V1.1$ \nactivation',
'$K_V1.1$ \ninactivation', 'A \nactivation', 'A \ninactivation'])
elif alteration=='g':
i = 1 # Kd
ax.axvspan(i - 0.4, i + 0.4, fill=False, edgecolor='k')
df = pd.read_csv('./Figures/Data/AUC_g_corr.csv')
# Add in points to show each observation
sns.swarmplot(y="corr", x="g", hue="model", data=df,
palette=clr_dict, linewidth=0, orient='v', ax=ax, size=msize,
order=['Na', 'K', '$K_V1.1$', 'A', 'Leak'],
hue_order=model_names, co2mk=Markers)
lim = ax.get_xlim()
# ax.plot([lim[0], lim[1]], [0,0], ':k')
ax.plot([lim[0], lim[1]], [0, 0], ':r',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [1, 1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [-1, -1], ':k',linewidth=hlinewidth)
# Tweak the visual presentation
ax.set_title("Conductance (g)", y=1.05)
ax.set_xticklabels(textwrap.fill(x.get_text(), max_width) for x in ax.get_xticklabels())
else:
print('Please chose "shift", "slope" or "g"')
ax.get_legend().remove()
ax.xaxis.grid(False)
sns.despine(trim=True, bottom=True, ax=ax)
ax.set(xlabel=None, ylabel=r'Kendall $\it{\tau}$')
def model_legend(ax, marker_s_leg, pos, ncol):
# colorslist = [ '#40A787', # cyan'#
# '#F0D730', # yellow
# '#C02717', # red
# '#007030', # dark green
# '#AAB71B', # lightgreen
# '#008797', # light blue
# '#F78017', # orange
# '#478010', # green
# '#53379B', # purple
# '#2060A7', # blue
# '#873770', # magenta
# '#D03050' # pink
# ]
colorslist = ['#007030', # dark green
'#F0D730', # yellow
'#C02717', # red
'#478010', # green
'#AAB71B', # lightgreen
'#F78017', # orange
'#40A787', # cyan'#
'#008797', # light blue
'#2060A7', # blue
'#D03050', # pink
'#53379B', # purple
'#873770', # magenta
]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
model_pos = {'Cb stellate':0, 'RS Inhibitory':1, 'FS':2, 'RS Pyramidal':3,
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':4,
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':5, 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':6,
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':7, 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':8,
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':9,
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':10, 'STN':11}
Markers = ["o", "o", "o", "^", "^", "^", "D", "D", "D", "s", "s", "s"]
# RS_p = mlines.Line2D([], [], color=colors[model_pos['RS Pyramidal']], marker=Markers[model_pos['RS Pyramidal']], markersize=marker_s_leg, linestyle='None',
# label='Model D')
# RS_i = mlines.Line2D([], [], color=colors[model_pos['RS Inhibitory']], marker=Markers[model_pos['RS Inhibitory']], markersize=marker_s_leg, linestyle='None',
# label='Model B')
# FS = mlines.Line2D([], [], color=colors[model_pos['FS']], marker=Markers[model_pos['FS']], markersize=marker_s_leg, linestyle='None', label='Model C')
# RS_p_Kv = mlines.Line2D([], [], color=colors[model_pos['RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], marker=Markers[model_pos['RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], markersize=marker_s_leg, linestyle='None',
# label='Model H')
# RS_i_Kv = mlines.Line2D([], [], color=colors[model_pos['RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], marker=Markers[model_pos['RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], markersize=marker_s_leg, linestyle='None',
# label='Model E')
# FS_Kv = mlines.Line2D([], [], color=colors[model_pos['Cb stellate']], marker=Markers[model_pos['Cb stellate']], markersize=marker_s_leg, linestyle='None', label='Model G')
# Cb = mlines.Line2D([], [], color=colors[8], marker=Markers[8], markersize=marker_s_leg, linestyle='None',
# label='Model A')
# Cb_pl = mlines.Line2D([], [], color=colors[model_pos['Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], marker=Markers[model_pos['Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], markersize=marker_s_leg, linestyle='None',
# label='Model F')
# Cb_sw = mlines.Line2D([], [], color=colors[model_pos['Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], marker=Markers[model_pos['Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], markersize=marker_s_leg, linestyle='None',
# label='Model J')
# STN = mlines.Line2D([], [], color=colors[model_pos['STN']], marker=Markers[model_pos['STN']], markersize=marker_s_leg, linestyle='None', label='Model L')
# STN_pl = mlines.Line2D([], [], color=colors[model_pos['STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], marker=Markers[model_pos['STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], markersize=marker_s_leg, linestyle='None',
# label='Model I')
# STN_sw = mlines.Line2D([], [], color=colors[model_pos['STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], marker=Markers[model_pos['STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], markersize=marker_s_leg, linestyle='None',
# label='Model K')
RS_p = mlines.Line2D([], [], color='#007030', marker="^",
markersize=marker_s_leg, linestyle='None',
label='Model D')
RS_i = mlines.Line2D([], [], color='#F0D730', marker="o",
markersize=marker_s_leg, linestyle='None',
label='Model B')
FS = mlines.Line2D([], [], color='#C02717', marker="o", markersize=marker_s_leg,
linestyle='None', label='Model C')
RS_p_Kv = mlines.Line2D([], [], color='#478010',
marker="D",
markersize=marker_s_leg, linestyle='None',
label='Model H')
RS_i_Kv = mlines.Line2D([], [], color='#AAB71B',
marker="^",
markersize=marker_s_leg, linestyle='None',
label='Model E')
FS_Kv = mlines.Line2D([], [], color='#F78017',
marker="D", markersize=marker_s_leg,
linestyle='None', label='Model G')
Cb = mlines.Line2D([], [], color='#40A787', marker="o",
markersize=marker_s_leg, linestyle='None',
label='Model A')
Cb_pl = mlines.Line2D([], [], color='#008797',
marker="^",
markersize=marker_s_leg, linestyle='None',
label='Model F')
Cb_sw = mlines.Line2D([], [], color='#2060A7',
marker="s",
markersize=marker_s_leg, linestyle='None',
label='Model J')
STN = mlines.Line2D([], [], color='#D03050', marker="s", markersize=marker_s_leg,
linestyle='None', label='Model L')
STN_pl = mlines.Line2D([], [], color='#53379B',
marker="D",
markersize=marker_s_leg, linestyle='None',
label='Model I')
STN_sw = mlines.Line2D([], [], color='#873770',
marker="s",
markersize=marker_s_leg, linestyle='None',
label='Model K')
# ax.legend(handles=[RS_p, RS_i, FS, RS_p_Kv, RS_i_Kv, FS_Kv, Cb, Cb_pl, Cb_sw, STN, STN_pl, STN_sw], loc='center',
# bbox_to_anchor=pos, ncol=ncol, frameon=False)
ax.legend(handles=[Cb, RS_i, FS, RS_p, RS_i_Kv, Cb_pl, FS_Kv, RS_p_Kv, STN_pl, Cb_sw, STN_sw, STN], loc='center',
bbox_to_anchor=pos, ncol=ncol, frameon=False)
def plot_AUC_alt(ax, model='FS', color1='red', color2='dodgerblue', alteration='shift'):
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
model_names = ['RS Pyramidal','RS Inhibitory','FS',
'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$',
'FS +$K_V1.1$','Cb stellate','Cb stellate +$K_V1.1$',
'Cb stellate $\Delta$$K_V1.1$','STN','STN +$K_V1.1$',
'STN $\Delta$$K_V1.1$']
model_name_dict = {'RS Pyramidal': 'RS Pyramidal',
'RS Inhibitory': 'RS Inhibitory',
'FS': 'FS',
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'RS Pyramidal +$K_V1.1$',
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'RS Inhibitory +$K_V1.1$',
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'FS +$K_V1.1$',
'Cb stellate': 'Cb stellate',
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'Cb stellate +$K_V1.1$',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'Cb stellate $\Delta$$K_V1.1$',
'STN': 'STN',
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'STN +$K_V1.1$',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'STN $\Delta$$K_V1.1$'}
colorslist = ['#007030', # dark green
'#F0D730', # yellow
'#C02717', # red
'#478010', # green
'#AAB71B', # lightgreen
'#F78017', # orange
'#40A787', # cyan'#
'#008797', # light blue
'#2060A7', # blue
'#D03050', # pink
'#53379B', # purple
'#873770', # magenta
]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
clr_dict = {}
for m in range(len(model_names)):
clr_dict[model_names[m]] = colors[m]
if alteration=='shift':
df = pd.read_csv('./Figures/Data/AUC_shift_ex.csv')
df = df.sort_values('alteration')
ax.set_xlabel('$\Delta$$V_{1/2}$')
elif alteration=='slope':
df = pd.read_csv('./Figures/Data/AUC_slope_ex.csv')
ax.set_xscale("log")
ax.set_xticks([0.5, 1, 2])
ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
ax.xaxis.set_minor_formatter(NullFormatter())
ax.set_xlabel('$k$/$k_{WT}$')
elif alteration=='g':
df = pd.read_csv('./Figures/Data/AUC_g_ex.csv')
ax.set_xscale("log")
ax.set_xticks([0.5, 1, 2])
ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
ax.xaxis.set_minor_formatter(NullFormatter())
ax.set_xlabel('$g$/$g_{WT}$')
for mod in model_names:
if mod == model_name_dict[model]:
ax.plot(df['alteration'], df[mod], color=clr_dict[mod], alpha=1, zorder=10, linewidth=2)
else:
ax.plot(df['alteration'], df[mod], color=clr_dict[mod],alpha=0.5, zorder=1, linewidth=1)
if alteration=='shift':
ax.set_ylabel('Normalized $\Delta$AUC', labelpad=4)
else:
ax.set_ylabel('Normalized $\Delta$AUC', labelpad=0)
x = df['alteration']
y = df[model_name_dict[model]]
ax.set_xlim(x.min(), x.max())
ax.set_ylim(df[model_names].min().min(), df[model_names].max().max())
# x axis color gradient
cvals = [-2., 2]
colors = ['lightgrey', 'k']
norm = plt.Normalize(min(cvals), max(cvals))
tuples = list(zip(map(norm, cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
(xstart, xend) = ax.get_xlim()
(ystart, yend) = ax.get_ylim()
print(ystart, yend)
start = (xstart, ystart * 1.0)
end = (xend, ystart * 1.0)
ax = gradientaxis(ax, start, end, cmap, n=200, lw=4)
ax.spines['bottom'].set_visible(False)
return ax
def plot_fI(ax, model='RS Pyramidal', type='shift', alt='m', color1='red', color2='dodgerblue'):
model_save_name = {'RS Pyramidal': 'RS_pyr_posp',
'RS Inhibitory': 'RS_inhib_posp',
'FS': 'FS_posp',
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'RS_pyr_Kv',
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'RS_inhib_Kv',
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'FS_Kv',
'Cb stellate': 'Cb_stellate',
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'Cb_stellate_Kv',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'Cb_stellate_Kv_only',
'STN': 'STN',
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'STN_Kv',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'STN_Kv_only'}
cvals = [-2., 2]
colors = [color1, color2]
norm = plt.Normalize(min(cvals), max(cvals))
tuples = list(zip(map(norm, cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
colors = cmap(np.linspace(0, 1, 22))
df = pd.read_csv('./Figures/Data/Model_fI/{}_fI.csv'.format(model_save_name[model]))
df.drop(['Unnamed: 0'], axis=1)
newdf = df.loc[df.index[(df['alt'] == alt) & (df['type'] == type)], :]
newdf['mag'] = newdf['mag'].astype('float')
newdf = newdf.sort_values('mag').reset_index()
c = 0
for i in newdf.index:
ax.plot(json.loads(newdf.loc[i, 'I']), json.loads(newdf.loc[i, 'F']), color=colors[c])
c += 1
ax.set_ylabel('Frequency [Hz]')
ax.set_xlabel('Current [nA]')
if model == 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':
ax.set_title("Model G", x=0.2, y=1.0)
elif model == 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':
ax.set_title("Model I", x=0.2, y=1.0)
else:
ax.set_title("", x=0.2, y=1.0)
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
L = ax.get_ylim()
ax.set_ylim([0, L[1]])
return ax
#%%
boxplot_style()
color_dict = {'Cb stellate': '#40A787', # cyan'#
'RS Inhibitory': '#F0D730', # yellow
'FS': '#C02717', # red
'RS Pyramidal': '#007030', # dark green
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#AAB71B', # lightgreen
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#008797', # light blue
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#F78017', # orange
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#478010', # green
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#53379B', # purple
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#2060A7', # blue
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#873770', # magenta
'STN': '#D03050' # pink
}
model_letter = {
'Cb stellate': 'A',
'RS Inhibitory': 'B',
'FS': 'C',
'RS Pyramidal': 'D',
'RS Inhibitory': 'E',
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'F',
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'G',
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'H',
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'I',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'J',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':'K',
'STN':'L',
}
# plot setup
marker_s_leg = 2
max_width = 20
pad_x = 0.85
pad_y= 0.4
pad_w = 1.1
pad_h = 0.7
fig = plt.figure()
gs = fig.add_gridspec(3, 7, wspace=1.2, hspace=1.)
ax0 = fig.add_subplot(gs[0,2:7])
ax0_ex = fig.add_subplot(gs[0,1])
ax0_fI = fig.add_subplot(gs[0,0])
ax1 = fig.add_subplot(gs[1,2:7])
ax1_ex = fig.add_subplot(gs[1,1])
ax1_fI = fig.add_subplot(gs[1,0])
ax2 = fig.add_subplot(gs[2,2:7])
ax2_ex = fig.add_subplot(gs[2,1])
ax2_fI = fig.add_subplot(gs[2,0])
line_width = 1
# plot fI examples
ax0_fI = plot_fI(ax0_fI, model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='shift', alt='s', color1='lightgrey', color2='k')
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=line_width,transform=ax0_fI.transAxes, color=color_dict['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = ax0_fI.add_patch(rec)
rec.set_clip_on(False)
ax1_fI = plot_fI(ax1_fI, model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='slope', alt='u', color1='lightgrey', color2='k')
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=line_width,transform=ax1_fI.transAxes, color=color_dict['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = ax1_fI.add_patch(rec)
rec.set_clip_on(False)
ax2_fI = plot_fI(ax2_fI, model='STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='g', alt='Leak', color1='lightgrey', color2='k')
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=line_width,transform=ax2_fI.transAxes, color=color_dict['STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = ax2_fI.add_patch(rec)
rec.set_clip_on(False)
# plot boxplots
boxplot_with_markers(ax0,max_width, alteration='shift')
boxplot_with_markers(ax1,max_width, alteration='slope')
boxplot_with_markers(ax2,max_width, alteration='g')
# plot legend
pos = (0.225, -0.9)
ncol = 6
model_legend(ax2, marker_s_leg, pos, ncol)
# plot examples
plot_AUC_alt(ax0_ex,model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k', alteration='shift')
plot_AUC_alt(ax1_ex,model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k',alteration='slope')
plot_AUC_alt(ax2_ex, model='STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k', alteration='g')
# label subplots with letters
ax0_fI.text(-0.875, 1.35, string.ascii_uppercase[0], transform=ax0_fI.transAxes, size=10, weight='bold')
ax0_ex.text(-0.8, 1.35, string.ascii_uppercase[1], transform=ax0_ex.transAxes, size=10, weight='bold')
ax0.text(-0.075, 1.35, string.ascii_uppercase[2], transform=ax0.transAxes, size=10, weight='bold')
ax1_fI.text(-0.875, 1.35, string.ascii_uppercase[3], transform=ax1_fI.transAxes,size=10, weight='bold')
ax1_ex.text(-0.8, 1.35, string.ascii_uppercase[4], transform=ax1_ex.transAxes, size=10, weight='bold')
ax1.text(-0.075, 1.35, string.ascii_uppercase[5], transform=ax1.transAxes, size=10, weight='bold')
ax2_fI.text(-0.875, 1.35, string.ascii_uppercase[6], transform=ax2_fI.transAxes,size=10, weight='bold')
ax2_ex.text(-0.8, 1.35, string.ascii_uppercase[7], transform=ax2_ex.transAxes, size=10, weight='bold')
ax2.text(-0.075, 1.35, string.ascii_uppercase[8], transform=ax2.transAxes, size=10, weight='bold')
#save
fig.set_size_inches(cm2inch(20.75,12))
# fig.savefig('./Figures/AUC_correlation.pdf', dpi=fig.dpi) #pdf #eps
fig.savefig('./Figures/AUC_correlation.jpg', dpi=fig.dpi) #pdf #eps
plt.show()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

View File

@ -4,16 +4,7 @@ import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.transforms import Bbox
import string
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
plt.rcParams['xtick.labelsize'] = 6
plt.rcParams['ytick.labelsize'] = 6
# from plotstyle import plot_style
#### from https://gist.github.com/dmeliza/3251476 #####################################################################
from matplotlib.offsetbox import AnchoredOffsetbox
@ -50,7 +41,7 @@ class AnchoredScaleBar(AnchoredOffsetbox):
AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
child=bars, prop=prop, frameon=False, **kwargs)
plt.rcParams.update({'font.size': 6})
def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, **kwargs):
""" Add scalebars to axes
Adds a set of scale bars to *ax*, matching the size to the ticks of the plot
@ -86,21 +77,13 @@ def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, **kwargs)
def plot_spike_train(ax, model='RS Pyramidal', stop=750):
model_spiking = pd.read_csv('./Figures/Data/model_spiking.csv')
stop_ind = int(np.argmin(np.abs(model_spiking['t'] - stop)))
# ax.plot(model_spiking['t'][0:stop_ind], model_spiking[model][0:stop_ind], 'k', linewidth=0.5)
if model == 'STN':
ax.plot(model_spiking['t'][0:stop_ind], model_spiking[model][0:stop_ind], 'k', linewidth=0.25)
else:
ax.plot(model_spiking['t'][0:stop_ind], model_spiking[model][0:stop_ind], 'k', linewidth=0.5) #1.5
# if model == 'STN':
# ax.plot(model_spiking['t'][0:stop_ind], model_spiking[model][0:stop_ind], 'k', linewidth=0.625)
# else:
# ax.plot(model_spiking['t'][0:stop_ind], model_spiking[model][0:stop_ind], 'k', linewidth=1.) #1.5
stop_ind = np.int(np.argmin(np.abs(model_spiking['t'] - stop)))
ax.plot(model_spiking['t'][0:stop_ind], model_spiking[model][0:stop_ind], 'k', linewidth=1.5)
ax.set_ylabel('V')
ax.set_xlabel('Time [s]')
ax.set_ylim(-85, 60)
ax.set_ylim(-80, 60)
ax.axis('off')
ax.set_title(model, fontsize=7, y=1.1)
ax.set_title(model)
def plot_fI(ax, model='RS Pyramidal'):
@ -108,115 +91,68 @@ def plot_fI(ax, model='RS Pyramidal'):
model_F_inf = pd.read_csv('./Figures/Data/model_F_inf.csv')
if model=='RS Inhibitory':
ax.plot(model_F_inf['I_inhib'], model_F_inf[model], color='grey')
ax.plot(firing_values.loc['spike_ind', model], model_F_inf[model][int(np.argmin(np.abs(model_F_inf['I_inhib'] - firing_values.loc['spike_ind', model])))],
ax.plot(firing_values.loc['spike_ind', model], model_F_inf[model][np.int(np.argmin(np.abs(model_F_inf['I_inhib'] - firing_values.loc['spike_ind', model])))],
'.', color='k', markersize=3)
ax.plot(firing_values.loc['ramp_up', model],
model_F_inf[model][int(np.argmin(np.abs(model_F_inf['I_inhib'] - firing_values.loc['ramp_up', model])))],
model_F_inf[model][np.int(np.argmin(np.abs(model_F_inf['I_inhib'] - firing_values.loc['ramp_up', model])))],
'.', color='g', markersize=3)
ax.plot(firing_values.loc['ramp_down', model],
model_F_inf[model][int(np.argmin(np.abs(model_F_inf['I_inhib'] - firing_values.loc['ramp_down', model])))],
model_F_inf[model][np.int(np.argmin(np.abs(model_F_inf['I_inhib'] - firing_values.loc['ramp_down', model])))],
'.', color='r', markersize=3)
else:
ax.plot(model_F_inf['I'], model_F_inf[model], color='grey')
ax.plot(firing_values.loc['spike_ind', model],
model_F_inf[model][int(np.argmin(np.abs(model_F_inf['I'] - firing_values.loc['spike_ind', model])))],
model_F_inf[model][np.int(np.argmin(np.abs(model_F_inf['I'] - firing_values.loc['spike_ind', model])))],
'.', color='k', markersize=3)
ax.plot(firing_values.loc['ramp_up', model],
model_F_inf[model][int(np.argmin(np.abs(model_F_inf['I'] - firing_values.loc['ramp_up', model])))],
model_F_inf[model][np.int(np.argmin(np.abs(model_F_inf['I'] - firing_values.loc['ramp_up', model])))],
'.', color='g', markersize=3)
ax.plot(firing_values.loc['ramp_down', model],
model_F_inf[model][int(np.argmin(np.abs(model_F_inf['I'] - firing_values.loc['ramp_down', model])))],
model_F_inf[model][np.int(np.argmin(np.abs(model_F_inf['I'] - firing_values.loc['ramp_down', model])))],
'.', color='r', markersize=3)
f = 6
f = 8
ax.set_ylabel('Frequency [Hz]', fontsize=f)
ax.set_xlabel('Current [nA]', fontsize=f)
ax.set_xlabel('Current [pA]', fontsize=f)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.tick_params(axis='y', labelrotation=90)
#%%
# plot layout
fig = plt.figure()
gs0 = fig.add_gridspec(3, 3, wspace=0.4, hspace=0.2)
# gs00 = gs0[:,0].subgridspec(5, 3, wspace=1.8, hspace=1.5)
# gs01 = gs0[:,1].subgridspec(5, 3, wspace=1.8, hspace=1.5)
# gs02 = gs0[:,2].subgridspec(5, 3, wspace=1.8, hspace=1.5)
gs00 = gs0[:,0].subgridspec(5, 2, wspace=0.8, hspace=1.5)
gs01 = gs0[:,1].subgridspec(5, 2, wspace=0.8, hspace=1.5)
gs02 = gs0[:,2].subgridspec(5, 2, wspace=0.8, hspace=1.5)
ax_diag = fig.add_subplot(gs02[2:, :])
import matplotlib.image as mpimg
img = mpimg.imread('./Figures/model_diagram2.png')
ax_diag.imshow(img)
ax_diag.spines['top'].set_visible(False)
ax_diag.spines['bottom'].set_visible(False)
ax_diag.spines['left'].set_visible(False)
ax_diag.spines['right'].set_visible(False)
ax_diag.set_yticks([])
ax_diag.set_xticks([])
# ax_diag.text(-0.12, 1.075, string.ascii_uppercase[12], transform=ax_diag.transAxes, size=10, weight='bold')
ax_diag.text(-0.22, 1.075, string.ascii_uppercase[12], transform=ax_diag.transAxes, size=10, weight='bold')
ax1_spikes = fig.add_subplot(gs00[0,0])
ax1_fI = fig.add_subplot(gs00[0, 1])
ax2_spikes = fig.add_subplot(gs01[0,0])
ax2_fI = fig.add_subplot(gs01[0, 1])
ax3_spikes = fig.add_subplot(gs02[0,0])
ax3_fI = fig.add_subplot(gs02[0, 1])
ax4_spikes = fig.add_subplot(gs00[1,0])
ax4_fI = fig.add_subplot(gs00[1, 1])
ax5_spikes = fig.add_subplot(gs01[1, 0])
ax5_fI = fig.add_subplot(gs01[1, 1])
ax6_spikes = fig.add_subplot(gs02[1,0])
ax6_fI = fig.add_subplot(gs02[1, 1])
ax7_spikes = fig.add_subplot(gs00[2,0])
ax7_fI = fig.add_subplot(gs00[2, 1])
ax8_spikes = fig.add_subplot(gs01[2,0])
ax8_fI = fig.add_subplot(gs01[2, 1])
ax9_spikes = fig.add_subplot(gs00[3,0])
ax9_fI = fig.add_subplot(gs00[3, 1])
ax10_spikes = fig.add_subplot(gs01[3,0])
ax10_fI = fig.add_subplot(gs01[3, 1])
ax11_spikes = fig.add_subplot(gs00[4,0])
ax11_fI = fig.add_subplot(gs00[4, 1])
ax12_spikes = fig.add_subplot(gs01[4, 0])
ax12_fI = fig.add_subplot(gs01[4, 1])
# ax1_spikes = fig.add_subplot(gs00[0,0:2])
# ax1_fI = fig.add_subplot(gs00[0, 2])
# ax2_spikes = fig.add_subplot(gs01[0,0:2])
# ax2_fI = fig.add_subplot(gs01[0, 2])
# ax3_spikes = fig.add_subplot(gs02[0,0:2])
# ax3_fI = fig.add_subplot(gs02[0, 2])
# ax4_spikes = fig.add_subplot(gs00[1,0:2])
# ax4_fI = fig.add_subplot(gs00[1, 2])
# ax5_spikes = fig.add_subplot(gs01[1, 0:2])
# ax5_fI = fig.add_subplot(gs01[1, 2])
# ax6_spikes = fig.add_subplot(gs02[1,0:2])
# ax6_fI = fig.add_subplot(gs02[1, 2])
# ax7_spikes = fig.add_subplot(gs00[2,0:2])
# ax7_fI = fig.add_subplot(gs00[2, 2])
# ax8_spikes = fig.add_subplot(gs01[2,0:2])
# ax8_fI = fig.add_subplot(gs01[2, 2])
# ax9_spikes = fig.add_subplot(gs00[3,0:2])
# ax9_fI = fig.add_subplot(gs00[3, 2])
# ax10_spikes = fig.add_subplot(gs01[3,0:2])
# ax10_fI = fig.add_subplot(gs01[3, 2])
# ax11_spikes = fig.add_subplot(gs00[4,0:2])
# ax11_fI = fig.add_subplot(gs00[4, 2])
# ax12_spikes = fig.add_subplot(gs01[4, 0:2])
# ax12_fI = fig.add_subplot(gs01[4, 2])
fig = plt.figure(figsize=(10,10))
gs0 = fig.add_gridspec(3, 2, wspace=0.3)
gs00 = gs0[:,0].subgridspec(6, 3, wspace=0.7, hspace=1)
gs01 = gs0[:,1].subgridspec(6, 3, wspace=0.7, hspace=1)
ax1_spikes = fig.add_subplot(gs00[0,0:2])
ax1_fI = fig.add_subplot(gs00[0, 2])
ax2_spikes = fig.add_subplot(gs01[0,0:2])
ax2_fI = fig.add_subplot(gs01[0, 2])
ax3_spikes = fig.add_subplot(gs00[1,0:2])
ax3_fI = fig.add_subplot(gs00[1, 2])
ax4_spikes = fig.add_subplot(gs01[1,0:2])
ax4_fI = fig.add_subplot(gs01[1, 2])
ax5_spikes = fig.add_subplot(gs00[2, 0:2])
ax5_fI = fig.add_subplot(gs00[2, 2])
ax6_spikes = fig.add_subplot(gs01[2, 0:2])
ax6_fI = fig.add_subplot(gs01[2, 2])
ax7_spikes = fig.add_subplot(gs00[3,0:2])
ax7_fI = fig.add_subplot(gs00[3, 2])
ax8_spikes = fig.add_subplot(gs01[3,0:2])
ax8_fI = fig.add_subplot(gs01[3, 2])
ax9_spikes = fig.add_subplot(gs00[4,0:2])
ax9_fI = fig.add_subplot(gs00[4, 2])
ax10_spikes = fig.add_subplot(gs01[4,0:2])
ax10_fI = fig.add_subplot(gs01[4, 2])
ax11_spikes = fig.add_subplot(gs00[5,0:2])
ax11_fI = fig.add_subplot(gs00[5, 2])
ax12_spikes = fig.add_subplot(gs01[5,0:2])
ax12_fI = fig.add_subplot(gs01[5, 2])
spike_axs = [ax1_spikes, ax2_spikes, ax3_spikes, ax4_spikes, ax5_spikes,ax6_spikes, ax7_spikes, ax8_spikes,
ax11_spikes,ax9_spikes,ax10_spikes, ax12_spikes]#, ax13_spikes, ax14_spikes]
fI_axs = [ax1_fI, ax2_fI, ax3_fI, ax4_fI, ax5_fI,ax6_fI, ax7_fI, ax8_fI, ax11_fI, ax9_fI, ax10_fI,
ax12_fI] #, ax13_fI, ax14_fI]
ax9_spikes, ax10_spikes, ax11_spikes, ax12_spikes]#, ax13_spikes, ax14_spikes]
fI_axs = [ax1_fI, ax2_fI, ax3_fI, ax4_fI, ax5_fI,ax6_fI, ax7_fI, ax8_fI, ax9_fI, ax10_fI,
ax11_fI, ax12_fI] #, ax13_fI, ax14_fI]
# model order
models = ['Cb stellate','RS Inhibitory','FS', 'RS Pyramidal','RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
@ -231,102 +167,18 @@ for i in range(len(models)):
plot_fI(fI_axs[i], model=models[i])
# add scalebars
# add_scalebar(ax6_spikes, matchx=False, matchy=False, hidex=True, hidey=True, sizex=100, sizey=50, labelx='100\u2009ms',
# labely='50\u2009mV', loc=3, pad=-0.5, borderpad=-1.0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.275, -0.05, 1, 1),
# bbox_transform=ax6_spikes.transAxes)
# add_scalebar(ax11_spikes, matchx=False, matchy=False, hidex=True, hidey=True, sizex=100, sizey=50, labelx='100\u2009ms',
# labely='50\u2009mV', loc=3, pad=-0.5, borderpad=-1.0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.275, -0.05, 1, 1),
# bbox_transform=ax11_spikes.transAxes)
# add_scalebar(ax12_spikes, matchx=False, matchy=False, hidex=True, hidey=True, sizex=100, sizey=50, labelx='100\u2009ms',
# labely='50\u2009mV', loc=3, pad=-0.5, borderpad=-1.0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.275, -0.05, 1, 1),
# bbox_transform=ax12_spikes.transAxes)
add_scalebar(ax6_spikes, matchx=False, matchy=False, hidex=True, hidey=True, sizex=100, sizey=50, labelx='100\u2009ms',
labely='50\u2009mV', loc=3, pad=-0.5, borderpad=-1.0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.475, -0.05, 1, 1),
bbox_transform=ax6_spikes.transAxes)
add_scalebar(ax11_spikes, matchx=False, matchy=False, hidex=True, hidey=True, sizex=100, sizey=50, labelx='100\u2009ms',
labely='50\u2009mV', loc=3, pad=-0.5, borderpad=-1.0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.475, -0.05, 1, 1),
add_scalebar(ax11_spikes, matchx=False, matchy=False, hidex=True, hidey=True, sizex=100, sizey=50, labelx='100 ms',
labely='50 mV', loc=3, pad=-0.5, borderpad=-1.0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.2, -0.05, 1, 1),
bbox_transform=ax11_spikes.transAxes)
add_scalebar(ax12_spikes, matchx=False, matchy=False, hidex=True, hidey=True, sizex=100, sizey=50, labelx='100\u2009ms',
labely='50\u2009mV', loc=3, pad=-0.5, borderpad=-1.0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.475, -0.05, 1, 1),
add_scalebar(ax12_spikes, matchx=False, matchy=False, hidex=True, hidey=True, sizex=100, sizey=50, labelx='100 ms',
labely='50 mV', loc=3, pad=-0.5, borderpad=-1.0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.2, -0.05, 1, 1),
bbox_transform=ax12_spikes.transAxes)
# add subplot labels
for i in range(0,len(models)):
# spike_axs[i].text(-0.18, 1.08, string.ascii_uppercase[i], transform=spike_axs[i].transAxes, size=10, weight='bold')
spike_axs[i].text(-0.572, 1.3, string.ascii_uppercase[i], transform=spike_axs[i].transAxes, size=10, weight='bold')
spike_axs[i].text(-0.18, 1.08, string.ascii_uppercase[i], transform=spike_axs[i].transAxes, size=16, weight='bold')
# save
fig.set_size_inches(cm2inch(21,15))
fig.savefig('./Figures/diversity_in_firing_diagram.jpg', dpi=300, bbox_inches='tight') #pdf # eps
fig.savefig('./Figures/diversity_in_firing.pdf', bbox_inches='tight')
plt.show()
# #%%
#
# # plot layout
# fig = plt.figure()
# gs0 = fig.add_gridspec(3, 2, wspace=0.3, hspace=0)
# gs00 = gs0[:,0].subgridspec(6, 3, wspace=1.5, hspace=1.5)
# gs01 = gs0[:,1].subgridspec(6, 3, wspace=1.2, hspace=1.3)
#
# ax1_spikes = fig.add_subplot(gs00[0,0:2])
# ax1_fI = fig.add_subplot(gs00[0, 2])
# ax2_spikes = fig.add_subplot(gs01[0,0:2])
# ax2_fI = fig.add_subplot(gs01[0, 2])
# ax3_spikes = fig.add_subplot(gs00[1,0:2])
# ax3_fI = fig.add_subplot(gs00[1, 2])
# ax4_spikes = fig.add_subplot(gs01[1,0:2])
# ax4_fI = fig.add_subplot(gs01[1, 2])
# ax5_spikes = fig.add_subplot(gs00[2, 0:2])
# ax5_fI = fig.add_subplot(gs00[2, 2])
# ax6_spikes = fig.add_subplot(gs01[2, 0:2])
# ax6_fI = fig.add_subplot(gs01[2, 2])
# ax7_spikes = fig.add_subplot(gs00[3,0:2])
# ax7_fI = fig.add_subplot(gs00[3, 2])
# ax8_spikes = fig.add_subplot(gs01[3,0:2])
# ax8_fI = fig.add_subplot(gs01[3, 2])
# ax9_spikes = fig.add_subplot(gs00[4,0:2])
# ax9_fI = fig.add_subplot(gs00[4, 2])
# ax10_spikes = fig.add_subplot(gs01[4,0:2])
# ax10_fI = fig.add_subplot(gs01[4, 2])
# ax11_spikes = fig.add_subplot(gs00[5,0:2])
# ax11_fI = fig.add_subplot(gs00[5, 2])
# ax12_spikes = fig.add_subplot(gs01[5,0:2])
# ax12_fI = fig.add_subplot(gs01[5, 2])
#
# spike_axs = [ax1_spikes, ax2_spikes, ax3_spikes, ax4_spikes, ax5_spikes,ax6_spikes, ax7_spikes, ax8_spikes,
# ax9_spikes, ax10_spikes, ax11_spikes, ax12_spikes]#, ax13_spikes, ax14_spikes]
# fI_axs = [ax1_fI, ax2_fI, ax3_fI, ax4_fI, ax5_fI,ax6_fI, ax7_fI, ax8_fI, ax9_fI, ax10_fI,
# ax11_fI, ax12_fI] #, ax13_fI, ax14_fI]
#
# # model order
# models = ['Cb stellate','RS Inhibitory','FS', 'RS Pyramidal','RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN']
#
# # plot spike train and fI for each model
# for i in range(len(models)):
# plot_spike_train(spike_axs[i], model=models[i])
# plot_fI(fI_axs[i], model=models[i])
#
# # add scalebars
# add_scalebar(ax11_spikes, matchx=False, matchy=False, hidex=True, hidey=True, sizex=100, sizey=50, labelx='100\u2009ms',
# labely='50\u2009mV', loc=3, pad=-0.5, borderpad=-1.0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.2, -0.05, 1, 1),
# bbox_transform=ax11_spikes.transAxes)
# add_scalebar(ax12_spikes, matchx=False, matchy=False, hidex=True, hidey=True, sizex=100, sizey=50, labelx='100\u2009ms',
# labely='50\u2009mV', loc=3, pad=-0.5, borderpad=-1.0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.2, -0.05, 1, 1),
# bbox_transform=ax12_spikes.transAxes)
# # add subplot labels
# for i in range(0,len(models)):
# # spike_axs[i].text(-0.18, 1.08, string.ascii_uppercase[i], transform=spike_axs[i].transAxes, size=10, weight='bold')
# spike_axs[i].text(-0.18, 1.2, string.ascii_uppercase[i], transform=spike_axs[i].transAxes, size=10, weight='bold')
# # save
# fig.set_size_inches(cm2inch(17.6,20))
# fig.savefig('./Figures/diversity_in_firing.jpg', dpi=fig.dpi) #pdf # eps
# # fig.savefig('./Figures/diversity_in_firing.png', dpi=fig.dpi) #pdf # eps
# plt.show()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 425 KiB

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

View File

@ -1,191 +1,8 @@
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.ticker as ticker
from matplotlib.colors import colorConverter as cc
from matplotlib.colors import to_hex
import string
from plotstyle import scheme_style
colorslist = ['#40A787', # cyan'#
'#F0D730', # yellow
'#C02717', # red
'#007030', # dark green
'#AAB71B', # lightgreen
'#008797', # light blue
'#F78017', # orange
'#478010', # green
'#53379B', # purple
'#2060A7', # blue
'#873770', # magenta
'#D03050' # pink
]
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
def show_spines(ax, spines='lrtb'):
""" Show and hide spines.
From github.com/janscience/plottools.git spines.py
Parameters
----------
ax: matplotlib figure, matplotlib axis, or list of matplotlib axes
Axis on which spine and ticks visibility is manipulated.
If figure, then apply manipulations on all axes of the figure.
If list of axes, apply manipulations on each of the given axes.
spines: string
Specify which spines and ticks should be shown.
All other ones or hidden.
'l' is the left spine, 'r' the right spine,
't' the top one and 'b' the bottom one.
E.g. 'lb' shows the left and bottom spine, and hides the top
and and right spines, as well as their tick marks and labels.
'' shows no spines at all.
'lrtb' shows all spines and tick marks.
Examples
--------
```py
import matplotlib.pyplot as plt
import plottools.spines
fig, (ax0, ax1, ax2) = plt.subplots(1, 3)
ax0.show_spines('lb')
ax1.show_spines('bt')
ax2.show_spines('tr')
```
![show](figures/spines-show.png)
"""
# collect spine visibility:
xspines = []
if 't' in spines:
xspines.append('top')
if 'b' in spines:
xspines.append('bottom')
yspines = []
if 'l' in spines:
yspines.append('left')
if 'r' in spines:
yspines.append('right')
# collect axes:
if isinstance(ax, (list, tuple, np.ndarray)):
axs = ax
elif hasattr(ax, 'get_axes'):
# ax is figure:
axs = ax.get_axes()
else:
axs = [ax]
if not isinstance(axs, (list, tuple)):
axs = [axs]
for ax in axs:
# hide spines:
ax.spines['top'].set_visible('top' in xspines)
ax.spines['bottom'].set_visible('bottom' in xspines)
ax.spines['left'].set_visible('left' in yspines)
ax.spines['right'].set_visible('right' in yspines)
# ticks:
if len(xspines) == 0:
ax.xaxis.set_ticks_position('none')
ax.xaxis.label.set_visible(False)
ax.xaxis._orig_major_locator = ax.xaxis.get_major_locator()
ax.xaxis.set_major_locator(ticker.NullLocator())
else:
if hasattr(ax.xaxis, '_orig_major_locator'):
ax.xaxis.set_major_locator(ax.xaxis._orig_major_locator)
delattr(ax.xaxis, '_orig_major_locator')
elif isinstance(ax.xaxis.get_major_locator(), ticker.NullLocator):
ax.xaxis.set_major_locator(ticker.AutoLocator())
if len(xspines) == 1:
ax.xaxis.set_ticks_position(xspines[0])
ax.xaxis.set_label_position(xspines[0])
else:
ax.xaxis.set_ticks_position('both')
ax.xaxis.set_label_position('bottom')
if len(yspines) == 0:
ax.yaxis.set_ticks_position('none')
ax.yaxis.label.set_visible(False)
ax.yaxis._orig_major_locator = ax.yaxis.get_major_locator()
ax.yaxis.set_major_locator(ticker.NullLocator())
else:
if hasattr(ax.yaxis, '_orig_major_locator'):
ax.yaxis.set_major_locator(ax.yaxis._orig_major_locator)
delattr(ax.yaxis, '_orig_major_locator')
elif isinstance(ax.yaxis.get_major_locator(), ticker.NullLocator):
ax.yaxis.set_major_locator(ticker.AutoLocator())
if len(yspines) == 1:
ax.yaxis.set_ticks_position(yspines[0])
ax.yaxis.set_label_position(yspines[0])
else:
ax.yaxis.set_ticks_position('both')
ax.yaxis.set_label_position('left')
def lighter(color, lightness):
""" Make a color lighter.
From github.com/janscience/plottools.git colors.py
![lighter](figures/colors-lighter.png)
Parameters
----------
color: dict or matplotlib color spec
A matplotlib color (hex string, name color string, rgb tuple)
or a dictionary with an 'color' or 'facecolor' key.
lightness: float
The smaller the lightness, the lighter the returned color.
A lightness of 0 returns white.
A lightness of 1 leaves the color untouched.
A lightness of 2 returns black.
Returns
-------
color: string or dict
The lighter color as a hexadecimal RGB string (e.g. '#rrggbb').
If `color` is a dictionary, a copy of the dictionary is returned
with the value of 'color' or 'facecolor' set to the lighter color.
Examples
--------
For 40% lightness of blue do
```py
import plottools.colors as c
colors = c.palettes['muted']
lightblue = c.lighter(colors['blue'], 0.4)
```
"""
try:
c = color['color']
cd = dict(**color)
cd['color'] = lighter(c, lightness)
return cd
except (KeyError, TypeError):
try:
c = color['facecolor']
cd = dict(**color)
cd['facecolor'] = lighter(c, lightness)
return cd
except (KeyError, TypeError):
if lightness > 2:
lightness = 2
if lightness > 1:
return darker(color, 2.0-lightness)
if lightness < 0:
lightness = 0
r, g, b = cc.to_rgb(color)
rl = r + (1.0-lightness)*(1.0 - r)
gl = g + (1.0-lightness)*(1.0 - g)
bl = b + (1.0-lightness)*(1.0 - b)
return to_hex((rl, gl, bl)).upper()
from plotstyle import plot_style
def plot_sqrt(ax, a=1, b=0.2, c=100, d=0):
x = np.linspace(0, 1, 10000)
@ -196,174 +13,156 @@ def plot_sqrt(ax, a=1, b=0.2, c=100, d=0):
ax.set_xlim(0,1)
ax.set_ylim(0, ax.get_ylim()[1])
def plot_AUC(ax, a=1, b=0.2, c=180, d=0, width=0.2):
x = np.linspace(0, 1, 1000)
def plot_AUC(ax, a=1, b=0.2, c=100, d=0, width=0.2):
x = np.linspace(0, 1, 10000)
y = c*np.sqrt(a*(x - b)) + d
ax.plot(x, y, colorslist[9])
ax.plot(x, y, 'k')
ax.set_xlabel('Current [nA]')
ax.set_ylabel('Frequency [Hz]')
ax.fill_between(x, y, where=(x<=b+width), color=lighter(colorslist[9], 0.3))
ax.text(0.3, 15, 'AUC', ha='center')
ax.annotate('', (0.2, 10), (0, 10), arrowprops=dict(arrowstyle="<->"))
ax.text(0.1, 20, 'rheobase', ha='center')
ax.set_xlim(0, 0.5)
ax.set_ylim(0, 100)
ax.yaxis.set_major_locator(ticker.MultipleLocator(50))
ax.fill_between(x,y, where=(x<=b+width), color='c')
ax.set_xlim(0,1)
ax.set_ylim(0, ax.get_ylim()[1])
def plot_diff_sqrt(ax, a=1, b=0.2, c=100, d=0, a2=1, b2=0.2, c2=100, d2=0):
show_spines(ax, 'lb')
x = np.linspace(0, 1, 10000)
y = c*np.sqrt(a*(x - b)) + d
y2 = c2 * np.sqrt(a2 * (x - b2)) + d2
ax.plot(x, y, colorslist[9])
ax.plot(x, y2, colorslist[2])
ax.plot(x, y, 'k')
ax.plot(x, y2, 'b')
ax.set_xlim(0,1)
ax.set_ylim(0, ax.get_ylim()[1])
ax.set_xticks([])
ax.set_yticks([])
def plot_quadrant(ax):
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.text(1.2, -0.15, '$\\Delta$ rheobase', ha='right')
ax.text(-0.03, 0.7, '$\\Delta$ AUC', ha='right', rotation=90)
ax.tick_params(length=0)
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.annotate('', (1, 0), (-1, 0), arrowprops=dict(arrowstyle="->"))
ax.annotate('', (0, 1), (0, -1), arrowprops=dict(arrowstyle="->"))
ax.set_xticks([-0.5, 0.5])
ax.plot(ax.get_xlim(),[0,0], '--k', linewidth=1.25)
ax.plot([0,0],ax.get_ylim(), '--k', linewidth=1.25)
ax.tick_params(axis=u'both', which=u'both', length=0)
ax.set_xticks([-0.55, 0, 0.55])
a = ax.get_xticks().tolist()
a[0] = '\u2212'
a[1] = '+'
a[1] = 0
a[2] = '+'
ax.set_xticklabels(a)
ax.set_yticks([-0.5, 0.5])
ax.set_yticks([-0.55, 0, 0.55])
b = ax.get_xticks().tolist()
b[0] = '\u2212'
b[1] = '+'
b[1] = 0
b[2] = '+'
ax.set_yticklabels(b)
ax.tick_params(labelsize=16)
# ax.set_yticks([0])
# ax.axis('off')
plot_style()
# scheme_style()
#%% with legend
fig = plt.figure(figsize=cm2inch(7, 12))
gs = gridspec.GridSpec(3,6, top=0.95, bottom=0.1, left=0.15, right = 0.95, hspace=0.8, wspace=0.6)
ax1 = fig.add_subplot(gs[0,1:])
show_spines(ax1, 'lb')
fig = plt.figure(figsize=(4, 6))
gs = gridspec.GridSpec(3,2, top=0.95, bottom=0.1, left=0.15, right = 0.95, hspace=0.8, wspace=0.6)
ax1 = fig.add_subplot(gs[0,:])
plot_AUC(ax1, width=0.2)
ax3 = fig.add_subplot(gs[1:, :])
# add panel letter labels
ax1.text(-0.4, 1.2, string.ascii_uppercase[0], transform=ax1.transAxes, size=16, weight='bold')
ax3.text(-0.15, 1.05, string.ascii_uppercase[1], transform=ax3.transAxes, size=16, weight='bold')
show_spines(ax3, '')
ax_list = fig.axes
i =0
for a in ax_list:
a.text(-0.18, 1.08, string.ascii_uppercase[i], transform=a.transAxes,size=16, weight='bold')
i += 1
ax3.set_ylabel('$\Delta$ AUC')
ax3.set_xlabel('$\Delta$ rheobase')
ax3.set_xlim(-1, 1)
ax3.set_ylim(-1, 1)
plot_quadrant(ax3) # plot delineation into quadrants
inset_ylim = (0, 100)
# top left
lfsize = 8
ax3.text(x=-0.9, y=0.7, s='$\\uparrow$ AUC\n$\\downarrow$ rheobase', fontsize=lfsize)
ax3.text(-0.95, 0.35, 'GOF', ha='right')
ax3_TL = ax3.inset_axes([0.07, 0.6, 0.3, 0.2])
ax3.text(x=-0.75, y=0.25, s=r'''$\uparrow$ AUC
$\downarrow$ rheobase''')
ax3_TL = ax3.inset_axes([0, 0.8, 0.3, 0.2])
plot_diff_sqrt(ax3_TL, b2=0.1, c2=200)
ax3_TL.set_ylim(inset_ylim)
# top right
ax3.text(x=0.22, y=0.7, s='$\\uparrow$ AUC\n$\\uparrow$ rheobase', fontsize=lfsize)
ax3.text(0.95, 0.35, 'LOF/\nGOF?')
ax3_TR = ax3.inset_axes([0.63, 0.6, 0.3, 0.2])
ax3.text(x=0.25, y=0.25, s=r'''$\uparrow$ AUC
$\uparrow$ rheobase''')
ax3_TR = ax3.inset_axes([0.7, 0.8, 0.3, 0.2])
plot_diff_sqrt(ax3_TR, b2=0.4, c2=200)
ax3_TR.set_ylim(inset_ylim)
# bottom left
ax3.text(x=-0.9, y=-0.95, s='$\\downarrow$ AUC\n$\downarrow$ rheobase', fontsize=lfsize)
ax3.text(-0.95, -0.55, 'GOF/\nLOF?', ha='right')
ax3_BL = ax3.inset_axes([0.07, 0.15, 0.3, 0.2])
plot_diff_sqrt(ax3_BL, b2=0.07, c2=65)
ax3.text(x=-0.75, y=-0.35, s=r'''$\downarrow$ AUC
$\downarrow$ rheobase''')
ax3_BL = ax3.inset_axes([0, 0, 0.3, 0.2])
plot_diff_sqrt(ax3_BL, b2=0.1, c2=75)
ax3_BL.set_ylim(inset_ylim)
# bottom right
ax3.text(x=0.22, y=-0.95, s='$\\downarrow$ AUC\n$\\uparrow$ rheobase', fontsize=lfsize)
ax3.text(0.95, -0.55, 'LOF')
ax3_BR = ax3.inset_axes([0.63, 0.15, 0.3, 0.2])
plot_diff_sqrt(ax3_BR, b2=0.4, c2=60)
ax3.text(x=0.25, y=-0.35, s=r'''$\downarrow$ AUC
$\uparrow$ rheobase''')
ax3_BR = ax3.inset_axes([0.7, 0, 0.3, 0.2])
plot_diff_sqrt(ax3_BR, b2=0.4, c2=75)
ax3_BR.set_ylim(inset_ylim)
import matplotlib.lines as mlines
wt = mlines.Line2D([], [], color=colorslist[9], linestyle='-',label='WT')
mut = mlines.Line2D([], [], color=colorslist[2], linestyle='-',label='Altered')
pos = (0.575, 0.05)
ncol = 2
fig.legend(handles=[wt, mut], loc='center', bbox_to_anchor=pos, ncol=ncol, frameon=False, fontsize=8)
fig.set_size_inches(cm2inch(8.5,12))
fig.savefig('./Figures/firing_characterization.png', dpi=fig.dpi) #pdf #eps
fig.savefig('./Figures/firing_characterization.pdf', bbox_inches='tight')
plt.show()
#%% with arrows
fig = plt.figure(figsize=cm2inch(7, 12))
# gs = gridspec.GridSpec(3,6, top=0.95, bottom=0.1, left=0.15, right = 0.95, hspace=0.8, wspace=0.6)
gs = gridspec.GridSpec(3,6, top=0.9, bottom=0.05, left=0.15, right = 0.9, hspace=0.8, wspace=0.6)
ax1 = fig.add_subplot(gs[0,1:])
show_spines(ax1, 'lb')
plot_AUC(ax1, width=0.2)
ax3 = fig.add_subplot(gs[1:, :])
# add panel letter labels
ax1.text(-0.4, 1.2, string.ascii_uppercase[0], transform=ax1.transAxes, size=16, weight='bold')
ax3.text(-0.15, 1.05, string.ascii_uppercase[1], transform=ax3.transAxes, size=16, weight='bold')
show_spines(ax3, '')
plot_quadrant(ax3) # plot delineation into quadrants
inset_ylim = (0, 100)
# top left
lfsize = 8
ax3.text(x=-0.9, y=0.7, s='$\\uparrow$ AUC\n$\\downarrow$ rheobase', fontsize=lfsize)
ax3.text(-0.95, 0.35, 'GOF', ha='right')
ax3_TL = ax3.inset_axes([0.07, 0.6, 0.3, 0.2])
plot_diff_sqrt(ax3_TL, b2=0.09, c2=200)
ax3_TL.set_ylim(inset_ylim)
ax3_TL.annotate('', (0.25, 7), (0.085, 7), arrowprops=dict(arrowstyle="<|-", color=colorslist[2],lw=0.5, mutation_scale=5), zorder=-10) #
ax3_TL.annotate('', (0.55, 55), (0.3, 90), arrowprops=dict(arrowstyle="<|-", color=colorslist[2],lw=0.5, mutation_scale=5), zorder=-10) #
# top right
ax3.text(x=0.22, y=0.7, s='$\\uparrow$ AUC\n$\\uparrow$ rheobase', fontsize=lfsize)
ax3.text(0.95, 0.35, 'LOF/\nGOF?')
ax3_TR = ax3.inset_axes([0.63, 0.6, 0.3, 0.2])
plot_diff_sqrt(ax3_TR, b2=0.4, c2=200)
ax3_TR.set_ylim(inset_ylim)
ax3_TR.annotate('', (0.17, 7), (0.41, 7), arrowprops=dict(arrowstyle="<|-", color=colorslist[2],lw=0.5, mutation_scale=5), zorder=-10) #
ax3_TR.annotate('', (0.8, 70), (0.6, 90), arrowprops=dict(arrowstyle="<|-", color=colorslist[2],lw=0.5, mutation_scale=5), zorder=-10) #
# bottom left
ax3.text(x=-0.9, y=-0.95, s='$\\downarrow$ AUC\n$\downarrow$ rheobase', fontsize=lfsize)
ax3.text(-0.95, -0.55, 'GOF/\nLOF?', ha='right')
ax3_BL = ax3.inset_axes([0.07, 0.15, 0.3, 0.2])
plot_diff_sqrt(ax3_BL, b2=0.06, c2=65)
ax3_BL.set_ylim(inset_ylim)
ax3_BL.annotate('', (0.25, 7), (0.07, 7), arrowprops=dict(arrowstyle="<|-", color=colorslist[2],lw=0.5, mutation_scale=5), zorder=-10) #
ax3_BL.annotate('', (0.8, 80), (0.85, 55), arrowprops=dict(arrowstyle="<|-", color=colorslist[2],lw=0.5, mutation_scale=5), zorder=-10) #
# bottom right
ax3.text(x=0.22, y=-0.95, s='$\\downarrow$ AUC\n$\\uparrow$ rheobase', fontsize=lfsize)
ax3.text(0.95, -0.55, 'LOF')
ax3_BR = ax3.inset_axes([0.63, 0.15, 0.3, 0.2])
plot_diff_sqrt(ax3_BR, b2=0.4, c2=60)
ax3_BR.set_ylim(inset_ylim)
ax3_BR.annotate('', (0.18, 7), (0.42, 7), arrowprops=dict(arrowstyle="<|-", color=colorslist[2],lw=0.5, mutation_scale=5), zorder=-10) #
ax3_BR.annotate('', (0.7, 75), (0.8, 37.5), arrowprops=dict(arrowstyle="<|-", color=colorslist[2],lw=0.5, mutation_scale=5), zorder=-10) #
fig.set_size_inches(cm2inch(8.3,12))
fig.savefig('./Figures/firing_characterization_arrows.pdf', dpi=300, bbox_inches='tight') #, dpi=fig.dpi #pdf #eps
plt.show()
#%% OLD
# fig = plt.figure()
# # fig, axs = plt.subplots(2, 3, figsize=(6, 4))
# # fig.subplots_adjust(top=0.95, bottom=0.1, left=0.1, right=0.95, hspace=0.6, wspace=0.6)
# gs = gridspec.GridSpec(2,3, top=0.95, bottom=0.1, left=0.1, right = 0.95, hspace=0.6, wspace=0.6)
# ax1 = fig.add_subplot(gs[0,0])
# plot_AUC(ax1, width=0.2)
# ax2 = fig.add_subplot(gs[1, 0])
# ax3 = fig.add_subplot(gs[:, 1:])
# # ax_list = fig.axes
# # import string
# # i =0
# # for a in ax_list:
# # a.text(-0.13, 1.05, string.ascii_uppercase[i], transform=a.transAxes,size=12, weight='bold')
# # i += 1
# ax3.set_ylabel('$\Delta$ AUC')
# ax3.set_xlabel('$\Delta$ rheobase')
# ax3.set_xlim(-1,1)
# ax3.set_ylim(-1,1)
# plot_quadrant(ax3)
#
# # top left
# ax3.text(x=-0.75, y=0.25, s=r'''$\uparrow$ AUC
# $\downarrow$ rheobase''')
# ax3_TL = ax3.inset_axes([0,0.8,0.3,0.2])
# plot_diff_sqrt(ax3_TL, b2=0.1, c2=200)
#
# # top right
# ax3.text(x=0.25, y=0.25, s=r'''$\uparrow$ AUC
# $\uparrow$ rheobase''')
# ax3_TR = ax3.inset_axes([0.7, 0.8, 0.3, 0.2])
# plot_diff_sqrt(ax3_TR, b2=0.4, c2=200)
#
# # bottom left
# ax3.text(x=-0.75, y=-0.35, s=r'''$\downarrow$ AUC
# $\downarrow$ rheobase''')
# ax3_BL = ax3.inset_axes([0, 0, 0.3, 0.2])
# plot_diff_sqrt(ax3_BL, b2=0.1, c2=75)
#
# # bottom right
# ax3.text(x=0.25, y=-0.35, s=r'''$\downarrow$ AUC
# $\uparrow$ rheobase''')
# ax3_BR = ax3.inset_axes([0.7, 0, 0.3, 0.2])
# plot_diff_sqrt(ax3_BR, b2=0.4, c2=75)
#
# # ax3_TL.sharey(ax3_TR)
#
# # ax3_TL.get_shared_x_axes().join(ax3_TL, ax3_TR, ax3_BL, ax3_BR)
# # ax3_TL.get_shared_y_axes().join(ax3_TL, ax3_TR, ax3_BL, ax3_BR)
# ax_list = [ax3_TL, ax3_TR, ax3_BL, ax3_BR] #< your axes objects
# ax_list[0].get_shared_x_axes().join(*ax_list)
# plt.show()
#
# # plot_sqrt(axs[0,0])
# # plot_temperature(axs[0,1])
# # plot_signal_n_power(axs[1,0], axs[1,1])
# # fig.savefig('coolresult.pdf')
#

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

View File

@ -1,182 +0,0 @@
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import string
# from plotstyle import plot_style
from plotstyle import scheme_style
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
def plot_sqrt(ax, a=1, b=0.2, c=100, d=0):
x = np.linspace(0, 1, 10000)
y = c*np.sqrt(a*(x - b)) + d
ax.plot(x, y)
ax.set_xlabel('Current [nA]')
ax.set_ylabel('Frequency [Hz]')
ax.set_xlim(0,1)
ax.set_ylim(0, ax.get_ylim()[1])
def plot_AUC(ax, a=1, b=0.2, c=100, d=0, width=0.2):
x = np.linspace(0, 1, 10000)
y = c*np.sqrt(a*(x - b)) + d
ax.plot(x, y, 'k')
ax.set_xlabel('Current [nA]')
ax.set_ylabel('Frequency [Hz]')
ax.fill_between(x,y, where=(x<=b+width), color='c')
ax.set_xlim(0,1)
ax.set_ylim(0, 100)
ax.yaxis.set_major_locator(ticker.MultipleLocator(50))
def plot_diff_sqrt(ax, a=1, b=0.2, c=100, d=0, a2=1, b2=0.2, c2=100, d2=0):
x = np.linspace(0, 1, 10000)
y = c*np.sqrt(a*(x - b)) + d
y2 = c2 * np.sqrt(a2 * (x - b2)) + d2
ax.plot(x, y, 'k')
ax.plot(x, y2, 'b')
ax.set_xlim(0,1)
ax.set_ylim(0, ax.get_ylim()[1])
ax.set_xticks([])
ax.set_yticks([])
def plot_quadrant(ax):
ax.plot(ax.get_xlim(),[0,0], '--k', linewidth=1.25)
ax.plot([0,0],ax.get_ylim(), '--k', linewidth=1.25)
ax.tick_params(axis=u'both', which=u'both', length=0)
ax.set_xticks([-0.55, 0, 0.55])
a = ax.get_xticks().tolist()
a[0] = '\u2212'
a[1] = 0
a[2] = '+'
ax.set_xticklabels(a)
ax.set_yticks([-0.55, 0, 0.55])
b = ax.get_xticks().tolist()
b[0] = '\u2212'
b[1] = 0
b[2] = '+'
ax.set_yticklabels(b)
# ax.tick_params(labelsize=16)
# ax.set_yticks([0])
# ax.axis('off')
# plot_style()
scheme_style()
fig = plt.figure(figsize=cm2inch(7, 12))
gs = gridspec.GridSpec(3,2, top=0.95, bottom=0.1, left=0.15, right = 0.95, hspace=0.8, wspace=0.6)
ax1 = fig.add_subplot(gs[0,:])
plot_AUC(ax1, width=0.2)
ax3 = fig.add_subplot(gs[1:, :])
# add panel letter labels
ax_list = fig.axes
i =0
for a in ax_list:
a.text(-0.18, 1.08, string.ascii_uppercase[i], transform=a.transAxes,size=16, weight='bold')
i += 1
ax3.set_ylabel('$\Delta$ AUC')
ax3.set_xlabel('$\Delta$ rheobase')
ax3.set_xlim(-1, 1)
ax3.set_ylim(-1, 1)
plot_quadrant(ax3) # plot delineation into quadrants
inset_ylim = (0, 100)
# top left
lfsize = 8
ax3.text(x=-0.75, y=0.25, s=r'''$\uparrow$ AUC
$\downarrow$ rheobase''', fontsize=lfsize)
ax3_TL = ax3.inset_axes([0, 0.8, 0.3, 0.2])
plot_diff_sqrt(ax3_TL, b2=0.1, c2=200)
ax3_TL.set_ylim(inset_ylim)
# top right
ax3.text(x=0.25, y=0.25, s=r'''$\uparrow$ AUC
$\uparrow$ rheobase''', fontsize=lfsize)
ax3_TR = ax3.inset_axes([0.7, 0.8, 0.3, 0.2])
plot_diff_sqrt(ax3_TR, b2=0.4, c2=200)
ax3_TR.set_ylim(inset_ylim)
# bottom left
ax3.text(x=-0.75, y=-0.35, s=r'''$\downarrow$ AUC
$\downarrow$ rheobase''', fontsize=lfsize)
ax3_BL = ax3.inset_axes([0, 0, 0.3, 0.2])
plot_diff_sqrt(ax3_BL, b2=0.1, c2=75)
ax3_BL.set_ylim(inset_ylim)
# bottom right
ax3.text(x=0.25, y=-0.35, s=r'''$\downarrow$ AUC
$\uparrow$ rheobase''', fontsize=lfsize)
ax3_BR = ax3.inset_axes([0.7, 0, 0.3, 0.2])
plot_diff_sqrt(ax3_BR, b2=0.4, c2=75)
ax3_BR.set_ylim(inset_ylim)
# fig.savefig('./Figures/firing_characterization.pdf', bbox_inches='tight')
print(fig.dpi)
fig.set_size_inches(cm2inch(8.17,15))
fig.savefig('./Figures/firing_characterization_old.pdf', dpi=fig.dpi) #bbox_inches='tight', dpi=fig.dpi
plt.show()
#%% OLD
# fig = plt.figure()
# # fig, axs = plt.subplots(2, 3, figsize=(6, 4))
# # fig.subplots_adjust(top=0.95, bottom=0.1, left=0.1, right=0.95, hspace=0.6, wspace=0.6)
# gs = gridspec.GridSpec(2,3, top=0.95, bottom=0.1, left=0.1, right = 0.95, hspace=0.6, wspace=0.6)
# ax1 = fig.add_subplot(gs[0,0])
# plot_AUC(ax1, width=0.2)
# ax2 = fig.add_subplot(gs[1, 0])
# ax3 = fig.add_subplot(gs[:, 1:])
# # ax_list = fig.axes
# # import string
# # i =0
# # for a in ax_list:
# # a.text(-0.13, 1.05, string.ascii_uppercase[i], transform=a.transAxes,size=12, weight='bold')
# # i += 1
# ax3.set_ylabel('$\Delta$ AUC')
# ax3.set_xlabel('$\Delta$ rheobase')
# ax3.set_xlim(-1,1)
# ax3.set_ylim(-1,1)
# plot_quadrant(ax3)
#
# # top left
# ax3.text(x=-0.75, y=0.25, s=r'''$\uparrow$ AUC
# $\downarrow$ rheobase''')
# ax3_TL = ax3.inset_axes([0,0.8,0.3,0.2])
# plot_diff_sqrt(ax3_TL, b2=0.1, c2=200)
#
# # top right
# ax3.text(x=0.25, y=0.25, s=r'''$\uparrow$ AUC
# $\uparrow$ rheobase''')
# ax3_TR = ax3.inset_axes([0.7, 0.8, 0.3, 0.2])
# plot_diff_sqrt(ax3_TR, b2=0.4, c2=200)
#
# # bottom left
# ax3.text(x=-0.75, y=-0.35, s=r'''$\downarrow$ AUC
# $\downarrow$ rheobase''')
# ax3_BL = ax3.inset_axes([0, 0, 0.3, 0.2])
# plot_diff_sqrt(ax3_BL, b2=0.1, c2=75)
#
# # bottom right
# ax3.text(x=0.25, y=-0.35, s=r'''$\downarrow$ AUC
# $\uparrow$ rheobase''')
# ax3_BR = ax3.inset_axes([0.7, 0, 0.3, 0.2])
# plot_diff_sqrt(ax3_BR, b2=0.4, c2=75)
#
# # ax3_TL.sharey(ax3_TR)
#
# # ax3_TL.get_shared_x_axes().join(ax3_TL, ax3_TR, ax3_BL, ax3_BR)
# # ax3_TL.get_shared_y_axes().join(ax3_TL, ax3_TR, ax3_BL, ax3_BR)
# ax_list = [ax3_TL, ax3_TR, ax3_BL, ax3_BR] #< your axes objects
# ax_list[0].get_shared_x_axes().join(*ax_list)
# plt.show()
#
# # plot_sqrt(axs[0,0])
# # plot_temperature(axs[0,1])
# # plot_signal_n_power(axs[1,0], axs[1,1])
# # fig.savefig('coolresult.pdf')
#

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 532 KiB

Binary file not shown.

View File

@ -1,197 +0,0 @@
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import string
from plotstyle import scheme_style
import pandas as pd
from matplotlib import cm
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i / inch for i in tupl[0])
else:
return tuple(i / inch for i in tupl)
def show_spines(ax, spines='lrtb'):
""" Show and hide spines.
From github.com/janscience/plottools.git spines.py
Parameters
----------
ax: matplotlib figure, matplotlib axis, or list of matplotlib axes
Axis on which spine and ticks visibility is manipulated.
If figure, then apply manipulations on all axes of the figure.
If list of axes, apply manipulations on each of the given axes.
spines: string
Specify which spines and ticks should be shown.
All other ones or hidden.
'l' is the left spine, 'r' the right spine,
't' the top one and 'b' the bottom one.
E.g. 'lb' shows the left and bottom spine, and hides the top
and and right spines, as well as their tick marks and labels.
'' shows no spines at all.
'lrtb' shows all spines and tick marks.
Examples
--------
```py
import matplotlib.pyplot as plt
import plottools.spines
fig, (ax0, ax1, ax2) = plt.subplots(1, 3)
ax0.show_spines('lb')
ax1.show_spines('bt')
ax2.show_spines('tr')
```
![show](figures/spines-show.png)
"""
# collect spine visibility:
xspines = []
if 't' in spines:
xspines.append('top')
if 'b' in spines:
xspines.append('bottom')
yspines = []
if 'l' in spines:
yspines.append('left')
if 'r' in spines:
yspines.append('right')
# collect axes:
if isinstance(ax, (list, tuple, np.ndarray)):
axs = ax
elif hasattr(ax, 'get_axes'):
# ax is figure:
axs = ax.get_axes()
else:
axs = [ax]
if not isinstance(axs, (list, tuple)):
axs = [axs]
for ax in axs:
# hide spines:
ax.spines['top'].set_visible('top' in xspines)
ax.spines['bottom'].set_visible('bottom' in xspines)
ax.spines['left'].set_visible('left' in yspines)
ax.spines['right'].set_visible('right' in yspines)
# ticks:
if len(xspines) == 0:
ax.xaxis.set_ticks_position('none')
ax.xaxis.label.set_visible(False)
ax.xaxis._orig_major_locator = ax.xaxis.get_major_locator()
ax.xaxis.set_major_locator(ticker.NullLocator())
else:
if hasattr(ax.xaxis, '_orig_major_locator'):
ax.xaxis.set_major_locator(ax.xaxis._orig_major_locator)
delattr(ax.xaxis, '_orig_major_locator')
elif isinstance(ax.xaxis.get_major_locator(), ticker.NullLocator):
ax.xaxis.set_major_locator(ticker.AutoLocator())
if len(xspines) == 1:
ax.xaxis.set_ticks_position(xspines[0])
ax.xaxis.set_label_position(xspines[0])
else:
ax.xaxis.set_ticks_position('both')
ax.xaxis.set_label_position('bottom')
if len(yspines) == 0:
ax.yaxis.set_ticks_position('none')
ax.yaxis.label.set_visible(False)
ax.yaxis._orig_major_locator = ax.yaxis.get_major_locator()
ax.yaxis.set_major_locator(ticker.NullLocator())
else:
if hasattr(ax.yaxis, '_orig_major_locator'):
ax.yaxis.set_major_locator(ax.yaxis._orig_major_locator)
delattr(ax.yaxis, '_orig_major_locator')
elif isinstance(ax.yaxis.get_major_locator(), ticker.NullLocator):
ax.yaxis.set_major_locator(ticker.AutoLocator())
if len(yspines) == 1:
ax.yaxis.set_ticks_position(yspines[0])
ax.yaxis.set_label_position(yspines[0])
else:
ax.yaxis.set_ticks_position('both')
ax.yaxis.set_label_position('left')
def plot_g(ax, df, models, i, let_x, let_y, titlesize=10, letsize=12):
# c = [cm.plasma(x) for x in np.linspace(0., 1., 9)]
# c = [cm.turbo(x) for x in np.linspace(0., 1., 9)]
c = [cm.gray(x) for x in np.linspace(0., 0.75, 9)]
myorder = [0, 4, 1, 6, 2,7, 3,8]
colors = [c[i] for i in myorder]
ax.set_ylim(0.01, 60)
df.plot.bar(y=models[i], rot=90, ax=ax, legend=False,
ylabel='$\mathrm{g}_{\mathrm{max}}$ [$\mathrm{mS}/ \mathrm{cm}^2$]',
color=colors)
ax.set_title(models[i], fontsize=titlesize)
show_spines(ax, spines='lb')
ax.text(let_x, let_y, string.ascii_uppercase[i], transform=ax.transAxes, size=letsize, weight='bold')
ax.set_yscale('log')
ax.set_xlim(-0.5, 9)
# ymin, ymax = ax.get_ylim()
# ax.set_ylim(0.001, 60)
from matplotlib.ticker import ScalarFormatter
for axis in [ax.yaxis]:
axis.set_major_formatter(ScalarFormatter())
# if i == 1 or i == 4:
# print(i)
ax.set_yticks([0.1,1.0, 10])
# ax.yaxis.set_major_formatter(ScalarFormatter())
# ax.set_yticklabels([0.1,1.0, 10])
# ax.set_yscale('log')
import matplotlib.ticker
# # ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
locmin = matplotlib.ticker.LogLocator(base=10.0, subs=(0.1, 0.2, 0.4, 0.6, 0.8, 1, 2, 4, 6, 8, 10), numticks=100)
ax.yaxis.set_minor_locator(locmin)
ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
ax.yaxis.set_tick_params(labelleft= True)
return ax
index = ['$\mathrm{g}_{\mathrm{Na}}$', '$\mathrm{g}_{\mathrm{Kd}}$', '$\mathrm{g}_{\mathrm{K_V1.1}}$',
'$\mathrm{g}_{\mathrm{A}}$', '$\mathrm{g}_{\mathrm{M}}$', '$\mathrm{g}_{\mathrm{L}}$',
'$\mathrm{g}_{\mathrm{T}}$', ' $\mathrm{g}_{\mathrm{Ca,K}}$', ' $\mathrm{g}_{\mathrm{Leak}}$']
df = pd.DataFrame({'RS Pyramidal': [56, 6, 0, 0, 0.075, 0, 0, 0, 0.0205],
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': [56, 5.4, 0.6, 0, 0.075, 0, 0, 0, 0.0205],
'RS Inhibitory': [10, 2.1, 0, 0, 0.0098, 0, 0, 0, 0.0205],
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': [10, 1.89, 0.21, 0, 0.0098, 0, 0, 0, 0.0205],
'FS': [58, 3.9, 0, 0, 0.075, 0, 0, 0, 0.038],
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': [58, 3.51, 0.39, 0, 0.075, 0, 0, 0, 0.038],
'Cb stellate': [3.4, 9.0556, 0, 15.0159, 0, 0, 0.4545, 0, 0.07407],
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': [3.4, 8.15, 0.90556, 15.0159, 0, 0, 0.4545, 0, 0.07407],
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': [3.4, 9.0556, 1.50159, 0, 0, 0, 0.4545, 0, 0.07407],
'STN': [49, 57, 0, 5, 0, 5, 5, 1, 0.035],
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': [49, 56.43, 0.57, 5, 0, 5, 5, 1, 0.035],
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': [49, 57, 0.5, 0, 0, 5, 5, 1, 0.035]},
index=index)
#% with legend
scheme_style()
models = ['Cb stellate', 'RS Inhibitory', 'FS', 'RS Pyramidal', 'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN']
fig, axs = plt.subplots(4, 3, figsize=cm2inch(20, 20))#, sharey=True)
plt.subplots_adjust(hspace=1.5, wspace=1.0)
let_x = -0.6
let_y = 1.2
titlesize = 9
letsize = 10
axs[0, 0] = plot_g(axs[0, 0], df, models, 0, let_x, let_y, titlesize=titlesize, letsize=letsize)
axs[0, 1] = plot_g(axs[0, 1], df, models, 1, let_x, let_y, titlesize=titlesize, letsize=letsize)
axs[0, 2] = plot_g(axs[0, 2], df, models, 2, let_x, let_y, titlesize=titlesize, letsize=letsize)
axs[1, 0] = plot_g(axs[1, 0], df, models, 3, let_x, let_y, titlesize=titlesize, letsize=letsize)
axs[1, 1] = plot_g(axs[1, 1], df, models, 4, let_x, let_y, titlesize=titlesize, letsize=letsize)
axs[1, 2] = plot_g(axs[1, 2], df, models, 5, let_x, let_y, titlesize=titlesize, letsize=letsize)
axs[2, 0] = plot_g(axs[2, 0], df, models, 6, let_x, let_y, titlesize=titlesize, letsize=letsize)
axs[2, 1] = plot_g(axs[2, 1], df, models, 7, let_x, let_y, titlesize=titlesize, letsize=letsize)
axs[2, 2] = plot_g(axs[2, 2], df, models, 8, let_x, let_y, titlesize=titlesize, letsize=letsize)
axs[3, 0] = plot_g(axs[3, 0], df, models, 9, let_x, let_y, titlesize=titlesize, letsize=letsize)
axs[3, 1] = plot_g(axs[3, 1], df, models, 10, let_x, let_y, titlesize=titlesize, letsize=letsize)
axs[3, 2] = plot_g(axs[3, 2], df, models, 11, let_x, let_y, titlesize=titlesize, letsize=letsize)
# save
# fig.set_size_inches(cm2inch(21,20))
fig.savefig('./Figures/model_g.jpg', dpi=300, bbox_inches='tight') # pdf # eps
plt.show()

View File

@ -1,59 +0,0 @@
import matplotlib.pyplot as plt
def scheme_style():
plt.rcParams['xtick.direction'] = 'out'
plt.rcParams['ytick.direction'] = 'out'
plt.rcParams['axes.titlesize'] = 20
plt.rcParams['axes.labelsize'] = 8
plt.rcParams['lines.linewidth'] = 2
plt.rcParams['lines.markersize'] = 10
plt.rcParams['xtick.labelsize'] = 10
plt.rcParams['ytick.labelsize'] = 10
plt.rcParams['savefig.bbox'] = 'tight'
# plt.rcParams['figure.figsize'] = [8.0, 8.0]
plt.rcParams['figure.dpi'] = 300
def plot_style():
plt.rcParams['xtick.direction'] = 'out'
plt.rcParams['ytick.direction'] = 'out'
plt.rcParams['axes.titlesize'] = 20
plt.rcParams['axes.labelsize'] = 12
plt.rcParams['lines.linewidth'] = 2
plt.rcParams['lines.markersize'] = 10
plt.rcParams['xtick.labelsize'] = 10
plt.rcParams['ytick.labelsize'] = 10
plt.rcParams['savefig.bbox'] = 'tight'
plt.rcParams['figure.dpi'] = 300
def boxplot_style():
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
plt.rcParams['lines.linewidth'] = 1
plt.rcParams['lines.markersize'] = 0.5
plt.rcParams['xtick.labelsize'] = 7
plt.rcParams['ytick.labelsize'] = 7
plt.rcParams['savefig.bbox'] = 'tight'
plt.rcParams['axes.titlesize'] = 7
plt.rcParams['axes.labelsize'] = 7
plt.rcParams['legend.fontsize']= 6
plt.rcParams['xtick.labelsize'] = 6
plt.rcParams['ytick.labelsize']= 6
plt.rcParams['mathtext.default'] = 'regular'
plt.rcParams['figure.dpi'] = 300
def sim_style():
plt.rcParams['xtick.direction'] = 'out'
plt.rcParams['ytick.direction'] = 'out'
plt.rcParams['axes.titlesize'] = 6
plt.rcParams['axes.labelsize'] = 8
plt.rcParams['lines.linewidth'] = 1
plt.rcParams['lines.markersize'] = 4
plt.rcParams['xtick.labelsize'] = 6
plt.rcParams['ytick.labelsize'] = 6
plt.rcParams['savefig.bbox'] = 'tight'
plt.rcParams.update({'font.size': 6})
plt.rcParams['figure.dpi'] = 300

135
Figures/ramp_examples.py Normal file
View File

@ -0,0 +1,135 @@
# plot ramp protocol and responses of each model to ramp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.transforms import Bbox
import string
#### from https://gist.github.com/dmeliza/3251476 #####################################################################
from matplotlib.offsetbox import AnchoredOffsetbox
class AnchoredScaleBar(AnchoredOffsetbox):
def __init__(self, transform, sizex=0, sizey=0, labelx=None, labely=None, loc=4,
pad=0.1, borderpad=0.1, sep=2, prop=None, barcolor="black", barwidth=None,
**kwargs):
"""
Draw a horizontal and/or vertical bar with the size in data coordinate
of the give axes. A label will be drawn underneath (center-aligned).
- transform : the coordinate frame (typically axes.transData)
- sizex,sizey : width of x,y bar, in data units. 0 to omit
- labelx,labely : labels for x,y bars; None to omit
- loc : position in containing axes
- pad, borderpad : padding, in fraction of the legend font size (or prop)
- sep : separation between labels and bars in points.
- **kwargs : additional arguments passed to base class constructor
"""
from matplotlib.patches import Rectangle
from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea
bars = AuxTransformBox(transform)
if sizex:
bars.add_artist(Rectangle((0, 0), sizex, 0, ec=barcolor, lw=barwidth, fc="none"))
if sizey:
bars.add_artist(Rectangle((0, 0), 0, sizey, ec=barcolor, lw=barwidth, fc="none"))
if sizex and labelx:
self.xlabel = TextArea(labelx)
bars = VPacker(children=[bars, self.xlabel], align="center", pad=0, sep=sep)
if sizey and labely:
self.ylabel = TextArea(labely)
bars = HPacker(children=[self.ylabel, bars], align="center", pad=0, sep=sep)
AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
child=bars, prop=prop, frameon=False, **kwargs)
def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, **kwargs):
""" Add scalebars to axes
Adds a set of scale bars to *ax*, matching the size to the ticks of the plot
and optionally hiding the x and y axes
- ax : the axis to attach ticks to
- matchx,matchy : if True, set size of scale bars to spacing between ticks
if False, size should be set using sizex and sizey params
- hidex,hidey : if True, hide x-axis and y-axis of parent
- **kwargs : additional arguments passed to AnchoredScaleBars
Returns created scalebar object
"""
def f(axis):
l = axis.get_majorticklocs()
return len(l) > 1 and (l[1] - l[0])
if matchx:
kwargs['sizex'] = f(ax.xaxis)
kwargs['labelx'] = str(kwargs['sizex'])
if matchy:
kwargs['sizey'] = f(ax.yaxis)
kwargs['labely'] = str(kwargs['sizey'])
sb = AnchoredScaleBar(ax.transData, **kwargs)
ax.add_artist(sb)
if hidex: ax.xaxis.set_visible(False)
if hidey: ax.yaxis.set_visible(False)
if hidex and hidey: ax.set_frame_on(False)
return sb
########################################################################################################################
def plot_ramp_V(ax, model='RS Pyramidal'): # , stop=750
model_ramp = pd.read_csv('./Figures/Data/model_ramp.csv')
ax.plot(model_ramp['t'], model_ramp[model], 'k', linewidth=0.25)
ax.set_ylabel('V')
ax.set_xlabel('Time [s]')
ax.set_ylim(-80, 60)
ax.axis('off')
ax.set_title(model)
#% plot setup
fig = plt.figure(figsize=(20,10))
gs0 = fig.add_gridspec(3, 2, wspace=0.1)
gs00 = gs0[:,0].subgridspec(7, 2, wspace=0.6, hspace=1)
gs01 = gs0[:,1].subgridspec(7, 2, wspace=0.6, hspace=1)
ax1_ramp = fig.add_subplot(gs00[0,0:2])
ax2_ramp = fig.add_subplot(gs01[0,0:2])
ax3_ramp = fig.add_subplot(gs00[1,0:2])
ax4_ramp = fig.add_subplot(gs01[1,0:2])
ax5_ramp = fig.add_subplot(gs00[2, 0:2])
ax6_ramp = fig.add_subplot(gs01[2, 0:2])
ax7_ramp = fig.add_subplot(gs00[3,0:2])
ax8_ramp = fig.add_subplot(gs01[3,0:2])
ax9_ramp = fig.add_subplot(gs00[4,0:2])
ax10_ramp = fig.add_subplot(gs01[4,0:2])
ax11_ramp = fig.add_subplot(gs00[5,0:2])
ax12_ramp = fig.add_subplot(gs01[5,0:2])
ramp_axs = [ax1_ramp, ax2_ramp, ax3_ramp, ax4_ramp, ax5_ramp,ax6_ramp, ax7_ramp, ax8_ramp,
ax9_ramp, ax10_ramp, ax11_ramp, ax12_ramp]
# order of models
models = ['Cb stellate','RS Inhibitory','FS', 'RS Pyramidal','RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN']
# plot ramps
for i in range(len(models)):
plot_ramp_V(ramp_axs[i], model=models[i])
# add scalebar
add_scalebar(ax11_ramp, matchx=False, matchy=False, hidex=True, hidey=True, sizex=1000, sizey=25, labelx='1 s',
labely='25 mV', loc=3, pad=-2, borderpad=0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.05, 0.1, 1, 1),
bbox_transform=ax11_ramp.transAxes)
# add_scalebar(ax12_ramp, matchx=False, matchy=False, hidex=True, hidey=True, sizex=1000, sizey=25, labelx='1 s',
# labely='25 mV', loc=3, pad=-2, borderpad=0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.05, 0.1, 1, 1),
# bbox_transform=ax12_ramp.transAxes)
# add subplot labels
for i in range(0,len(models)):
ramp_axs[i].text(-0.05, 1.08, string.ascii_uppercase[i], transform=ramp_axs[i].transAxes, size=16, weight='bold')
fig.savefig('./Figures/ramp_firing.pdf')
plt.show()

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 525 KiB

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

View File

@ -1,322 +0,0 @@
# # plot ramp protocol and responses of each model to ramp
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
# import matplotlib.gridspec as gridspec
# from matplotlib.transforms import Bbox
# import string
#
# def cm2inch(*tupl):
# inch = 2.54
# if isinstance(tupl[0], tuple):
# return tuple(i/inch for i in tupl[0])
# else:
# return tuple(i/inch for i in tupl)
#
# #### from https://gist.github.com/dmeliza/3251476 #####################################################################
# from matplotlib.offsetbox import AnchoredOffsetbox
# class AnchoredScaleBar(AnchoredOffsetbox):
# def __init__(self, transform, sizex=0, sizey=0, labelx=None, labely=None, loc=4,
# pad=0.1, borderpad=0.1, sep=2, prop=None, barcolor="black", barwidth=None,
# **kwargs):
# """
# Draw a horizontal and/or vertical bar with the size in data coordinate
# of the give axes. A label will be drawn underneath (center-aligned).
# - transform : the coordinate frame (typically axes.transData)
# - sizex,sizey : width of x,y bar, in data units. 0 to omit
# - labelx,labely : labels for x,y bars; None to omit
# - loc : position in containing axes
# - pad, borderpad : padding, in fraction of the legend font size (or prop)
# - sep : separation between labels and bars in points.
# - **kwargs : additional arguments passed to base class constructor
# """
# from matplotlib.patches import Rectangle
# from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea
# bars = AuxTransformBox(transform)
# if sizex:
# bars.add_artist(Rectangle((0, 0), sizex, 0, ec=barcolor, lw=barwidth, fc="none"))
# if sizey:
# bars.add_artist(Rectangle((0, 0), 0, sizey, ec=barcolor, lw=barwidth, fc="none"))
#
# if sizex and labelx:
# self.xlabel = TextArea(labelx)
# bars = VPacker(children=[bars, self.xlabel], align="center", pad=0, sep=sep)
# if sizey and labely:
# self.ylabel = TextArea(labely)
# bars = HPacker(children=[self.ylabel, bars], align="center", pad=0, sep=sep)
#
# AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
# child=bars, prop=prop, frameon=False, **kwargs)
#
#
# def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, **kwargs):
# """ Add scalebars to axes
# Adds a set of scale bars to *ax*, matching the size to the ticks of the plot
# and optionally hiding the x and y axes
# - ax : the axis to attach ticks to
# - matchx,matchy : if True, set size of scale bars to spacing between ticks
# if False, size should be set using sizex and sizey params
# - hidex,hidey : if True, hide x-axis and y-axis of parent
# - **kwargs : additional arguments passed to AnchoredScaleBars
# Returns created scalebar object
# """
#
# def f(axis):
# l = axis.get_majorticklocs()
# return len(l) > 1 and (l[1] - l[0])
#
# if matchx:
# kwargs['sizex'] = f(ax.xaxis)
# kwargs['labelx'] = str(kwargs['sizex'])
# if matchy:
# kwargs['sizey'] = f(ax.yaxis)
# kwargs['labely'] = str(kwargs['sizey'])
#
# sb = AnchoredScaleBar(ax.transData, **kwargs)
# ax.add_artist(sb)
#
# if hidex: ax.xaxis.set_visible(False)
# if hidey: ax.yaxis.set_visible(False)
# if hidex and hidey: ax.set_frame_on(False)
#
# return sb
# ########################################################################################################################
#
#
# def plot_ramp_V(ax, model='RS Pyramidal'): # , stop=750
# model_ramp = pd.read_csv('./Figures/Data/model_ramp.csv')
# ax.plot(model_ramp['t'], model_ramp[model], 'k', linewidth=0.025)
# ax.set_ylabel('V')
# ax.set_xlabel('Time [s]')
# ax.set_ylim(-80, 60)
# ax.axis('off')
# ax.set_title(model)
#
# #% plot setup
# fig = plt.figure(figsize=cm2inch(17.6,17.6))
#
# gs0 = fig.add_gridspec(3, 2, wspace=0.1)
# gs00 = gs0[:,0].subgridspec(7, 2, wspace=0.6, hspace=1)
# gs01 = gs0[:,1].subgridspec(7, 2, wspace=0.6, hspace=1)
#
# ax1_ramp = fig.add_subplot(gs00[0,0:2])
# ax2_ramp = fig.add_subplot(gs01[0,0:2])
# ax3_ramp = fig.add_subplot(gs00[1,0:2])
# ax4_ramp = fig.add_subplot(gs01[1,0:2])
# ax5_ramp = fig.add_subplot(gs00[2, 0:2])
# ax6_ramp = fig.add_subplot(gs01[2, 0:2])
# ax7_ramp = fig.add_subplot(gs00[3,0:2])
# ax8_ramp = fig.add_subplot(gs01[3,0:2])
# ax9_ramp = fig.add_subplot(gs00[4,0:2])
# ax10_ramp = fig.add_subplot(gs01[4,0:2])
# ax11_ramp = fig.add_subplot(gs00[5,0:2])
# ax12_ramp = fig.add_subplot(gs01[5,0:2])
#
# ramp_axs = [ax1_ramp, ax2_ramp, ax3_ramp, ax4_ramp, ax5_ramp,ax6_ramp, ax7_ramp, ax8_ramp,
# ax9_ramp, ax10_ramp, ax11_ramp, ax12_ramp]
#
# # order of models
# models = ['Cb stellate','RS Inhibitory','FS', 'RS Pyramidal','RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN']
#
# # plot ramps
# for i in range(len(models)):
# plot_ramp_V(ramp_axs[i], model=models[i])
#
# # add scalebar
# plt.rcParams.update({'font.size': 6})
#
# add_scalebar(ax11_ramp, matchx=False, matchy=False, hidex=True, hidey=True, sizex=1000, sizey=50, labelx='1 s',
# labely='50 mV', loc=3, pad=-2, borderpad=0, barwidth=1, bbox_to_anchor=Bbox.from_bounds(-0.05, 0.1, 1, 1),
# bbox_transform=ax11_ramp.transAxes)
# # add_scalebar(ax12_ramp, matchx=False, matchy=False, hidex=True, hidey=True, sizex=1000, sizey=25, labelx='1 s',
# # labely='25 mV', loc=3, pad=-2, borderpad=0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.05, 0.1, 1, 1),
# # bbox_transform=ax12_ramp.transAxes)
#
# # add subplot labels
# for i in range(0,len(models)):
# ramp_axs[i].text(-0.05, 1.08, string.ascii_uppercase[i], transform=ramp_axs[i].transAxes, size=10, weight='bold')
#
# fig.savefig('./Figures/ramp_firing.pdf', dpi=3000)
# plt.show()
# plot ramp protocol and responses of each model to ramp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.transforms import Bbox
import string
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
#### from https://gist.github.com/dmeliza/3251476 #####################################################################
from matplotlib.offsetbox import AnchoredOffsetbox
class AnchoredScaleBar(AnchoredOffsetbox):
def __init__(self, transform, sizex=0, sizey=0, labelx=None, labely=None, loc=4,
pad=0.1, borderpad=0.1, sep=2, prop=None, barcolor="black", barwidth=None,
**kwargs):
"""
Draw a horizontal and/or vertical bar with the size in data coordinate
of the give axes. A label will be drawn underneath (center-aligned).
- transform : the coordinate frame (typically axes.transData)
- sizex,sizey : width of x,y bar, in data units. 0 to omit
- labelx,labely : labels for x,y bars; None to omit
- loc : position in containing axes
- pad, borderpad : padding, in fraction of the legend font size (or prop)
- sep : separation between labels and bars in points.
- **kwargs : additional arguments passed to base class constructor
"""
from matplotlib.patches import Rectangle
from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea
bars = AuxTransformBox(transform)
if sizex:
bars.add_artist(Rectangle((0, 0), sizex, 0, ec=barcolor, lw=barwidth, fc="none"))
if sizey:
bars.add_artist(Rectangle((0, 0), 0, sizey, ec=barcolor, lw=barwidth, fc="none"))
if sizex and labelx:
self.xlabel = TextArea(labelx)
bars = VPacker(children=[bars, self.xlabel], align="center", pad=0, sep=sep)
if sizey and labely:
self.ylabel = TextArea(labely)
bars = HPacker(children=[self.ylabel, bars], align="center", pad=0, sep=sep)
AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
child=bars, prop=prop, frameon=False, **kwargs)
def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, **kwargs):
""" Add scalebars to axes
Adds a set of scale bars to *ax*, matching the size to the ticks of the plot
and optionally hiding the x and y axes
- ax : the axis to attach ticks to
- matchx,matchy : if True, set size of scale bars to spacing between ticks
if False, size should be set using sizex and sizey params
- hidex,hidey : if True, hide x-axis and y-axis of parent
- **kwargs : additional arguments passed to AnchoredScaleBars
Returns created scalebar object
"""
def f(axis):
l = axis.get_majorticklocs()
return len(l) > 1 and (l[1] - l[0])
if matchx:
kwargs['sizex'] = f(ax.xaxis)
kwargs['labelx'] = str(kwargs['sizex'])
if matchy:
kwargs['sizey'] = f(ax.yaxis)
kwargs['labely'] = str(kwargs['sizey'])
sb = AnchoredScaleBar(ax.transData, **kwargs)
ax.add_artist(sb)
if hidex: ax.xaxis.set_visible(False)
if hidey: ax.yaxis.set_visible(False)
if hidex and hidey: ax.set_frame_on(False)
return sb
########################################################################################################################
def plot_ramp_V(ax, model='RS Pyramidal'): # , stop=750
model_ramp = pd.read_csv('./Figures/Data/model_ramp.csv')
# ax.plot(model_ramp['t'], model_ramp[model], 'k', linewidth=0.0025)
ax.plot(model_ramp['t'], model_ramp[model], 'k', linewidth=0.1)
ax.set_ylabel('V')
ax.set_xlabel('Time [s]')
ax.set_ylim(-80, 60)
ax.axis('off')
ax.set_title(model, fontsize=8)
def plot_I_ramp(ax):
dt = 0.01
I_low = 0
I_high = 0.001
initial_period = 1000
sec = 4
ramp_len = int(4 * 1000 * 1 / dt)
stim_time = ramp_len * 2
I_amp = np.array([0])
I_amp = np.reshape(I_amp, (1, I_amp.shape[0]))
I_ramp = np.zeros((stim_time, 1)) @ I_amp
I_ramp[:, :] = np.ones((stim_time, 1)) @ I_amp
stim_num_step = I_ramp.shape[1]
start=0
I_ramp[start:int(start + ramp_len), 0] = np.linspace(0, I_high, ramp_len)
I_ramp[int(start + ramp_len):int(start + ramp_len * 2), 0] = np.linspace(I_high, 0, ramp_len)
t = np.arange(0, 4000 * 2, dt)
ax.plot(t, I_ramp)
ax.set_ylabel('I')
ax.set_xlabel('Time [s]')
ax.axis('off')
ax.set_title('Ramp Current', fontsize=8, x=0.5, y=-0.5)
return ax
#% plot setup
fig = plt.figure(figsize=cm2inch(17.6,25))
gs0 = fig.add_gridspec(2, 1, wspace=0.)
gs00 = gs0[:].subgridspec(13, 1, wspace=0.7, hspace=1.0)
ax1_ramp = fig.add_subplot(gs00[0])
ax2_ramp = fig.add_subplot(gs00[1])
ax3_ramp = fig.add_subplot(gs00[2])
ax4_ramp = fig.add_subplot(gs00[3])
ax5_ramp = fig.add_subplot(gs00[4])
ax6_ramp = fig.add_subplot(gs00[5])
ax7_ramp = fig.add_subplot(gs00[6])
ax8_ramp = fig.add_subplot(gs00[7])
ax9_ramp = fig.add_subplot(gs00[8])
ax10_ramp = fig.add_subplot(gs00[9])
ax11_ramp = fig.add_subplot(gs00[10])
ax12_ramp = fig.add_subplot(gs00[11])
ax13_I = fig.add_subplot(gs00[12])
ramp_axs = [ax1_ramp, ax2_ramp, ax3_ramp, ax4_ramp, ax5_ramp,ax6_ramp, ax7_ramp, ax8_ramp,
ax9_ramp, ax10_ramp, ax11_ramp, ax12_ramp]
# order of models
models = ['Cb stellate','RS Inhibitory','FS', 'RS Pyramidal','RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN']
# plot ramps
for i in range(len(models)):
plot_ramp_V(ramp_axs[i], model=models[i])
# add scalebar
plt.rcParams.update({'font.size': 6})
add_scalebar(ax12_ramp, matchx=False, matchy=False, hidex=True, hidey=True, sizex=1000, sizey=50, labelx='1 s',
labely='50 mV', loc=3, pad=-2, borderpad=0, barwidth=1, bbox_to_anchor=Bbox.from_bounds(0.01, 0.05, 1, 1),
bbox_transform=ax12_ramp.transAxes)
ax13_I = plot_I_ramp(ax13_I)
add_scalebar(ax13_I, matchx=False, matchy=False, hidex=True, hidey=True, sizex=1000, sizey=0.0005, labelx='1 s',
labely='0.5 $I_{max}$', loc=3, pad=-2, borderpad=0, barwidth=1,
bbox_to_anchor=Bbox.from_bounds(0.0, -0.01, 1, 1), bbox_transform=ax13_I.transAxes)
# add subplot labels
for i in range(0,len(models)):
ramp_axs[i].text(-0.01, 1.1, string.ascii_uppercase[i], transform=ramp_axs[i].transAxes, size=10, weight='bold')
#save
fig.set_size_inches(cm2inch(17.6,22))
fig.savefig('./Figures/ramp_firing.png', dpi=fig.dpi)#pdf #eps
plt.show()

View File

@ -1,322 +0,0 @@
# # plot ramp protocol and responses of each model to ramp
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
# import matplotlib.gridspec as gridspec
# from matplotlib.transforms import Bbox
# import string
#
# def cm2inch(*tupl):
# inch = 2.54
# if isinstance(tupl[0], tuple):
# return tuple(i/inch for i in tupl[0])
# else:
# return tuple(i/inch for i in tupl)
#
# #### from https://gist.github.com/dmeliza/3251476 #####################################################################
# from matplotlib.offsetbox import AnchoredOffsetbox
# class AnchoredScaleBar(AnchoredOffsetbox):
# def __init__(self, transform, sizex=0, sizey=0, labelx=None, labely=None, loc=4,
# pad=0.1, borderpad=0.1, sep=2, prop=None, barcolor="black", barwidth=None,
# **kwargs):
# """
# Draw a horizontal and/or vertical bar with the size in data coordinate
# of the give axes. A label will be drawn underneath (center-aligned).
# - transform : the coordinate frame (typically axes.transData)
# - sizex,sizey : width of x,y bar, in data units. 0 to omit
# - labelx,labely : labels for x,y bars; None to omit
# - loc : position in containing axes
# - pad, borderpad : padding, in fraction of the legend font size (or prop)
# - sep : separation between labels and bars in points.
# - **kwargs : additional arguments passed to base class constructor
# """
# from matplotlib.patches import Rectangle
# from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea
# bars = AuxTransformBox(transform)
# if sizex:
# bars.add_artist(Rectangle((0, 0), sizex, 0, ec=barcolor, lw=barwidth, fc="none"))
# if sizey:
# bars.add_artist(Rectangle((0, 0), 0, sizey, ec=barcolor, lw=barwidth, fc="none"))
#
# if sizex and labelx:
# self.xlabel = TextArea(labelx)
# bars = VPacker(children=[bars, self.xlabel], align="center", pad=0, sep=sep)
# if sizey and labely:
# self.ylabel = TextArea(labely)
# bars = HPacker(children=[self.ylabel, bars], align="center", pad=0, sep=sep)
#
# AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
# child=bars, prop=prop, frameon=False, **kwargs)
#
#
# def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, **kwargs):
# """ Add scalebars to axes
# Adds a set of scale bars to *ax*, matching the size to the ticks of the plot
# and optionally hiding the x and y axes
# - ax : the axis to attach ticks to
# - matchx,matchy : if True, set size of scale bars to spacing between ticks
# if False, size should be set using sizex and sizey params
# - hidex,hidey : if True, hide x-axis and y-axis of parent
# - **kwargs : additional arguments passed to AnchoredScaleBars
# Returns created scalebar object
# """
#
# def f(axis):
# l = axis.get_majorticklocs()
# return len(l) > 1 and (l[1] - l[0])
#
# if matchx:
# kwargs['sizex'] = f(ax.xaxis)
# kwargs['labelx'] = str(kwargs['sizex'])
# if matchy:
# kwargs['sizey'] = f(ax.yaxis)
# kwargs['labely'] = str(kwargs['sizey'])
#
# sb = AnchoredScaleBar(ax.transData, **kwargs)
# ax.add_artist(sb)
#
# if hidex: ax.xaxis.set_visible(False)
# if hidey: ax.yaxis.set_visible(False)
# if hidex and hidey: ax.set_frame_on(False)
#
# return sb
# ########################################################################################################################
#
#
# def plot_ramp_V(ax, model='RS Pyramidal'): # , stop=750
# model_ramp = pd.read_csv('./Figures/Data/model_ramp.csv')
# ax.plot(model_ramp['t'], model_ramp[model], 'k', linewidth=0.025)
# ax.set_ylabel('V')
# ax.set_xlabel('Time [s]')
# ax.set_ylim(-80, 60)
# ax.axis('off')
# ax.set_title(model)
#
# #% plot setup
# fig = plt.figure(figsize=cm2inch(17.6,17.6))
#
# gs0 = fig.add_gridspec(3, 2, wspace=0.1)
# gs00 = gs0[:,0].subgridspec(7, 2, wspace=0.6, hspace=1)
# gs01 = gs0[:,1].subgridspec(7, 2, wspace=0.6, hspace=1)
#
# ax1_ramp = fig.add_subplot(gs00[0,0:2])
# ax2_ramp = fig.add_subplot(gs01[0,0:2])
# ax3_ramp = fig.add_subplot(gs00[1,0:2])
# ax4_ramp = fig.add_subplot(gs01[1,0:2])
# ax5_ramp = fig.add_subplot(gs00[2, 0:2])
# ax6_ramp = fig.add_subplot(gs01[2, 0:2])
# ax7_ramp = fig.add_subplot(gs00[3,0:2])
# ax8_ramp = fig.add_subplot(gs01[3,0:2])
# ax9_ramp = fig.add_subplot(gs00[4,0:2])
# ax10_ramp = fig.add_subplot(gs01[4,0:2])
# ax11_ramp = fig.add_subplot(gs00[5,0:2])
# ax12_ramp = fig.add_subplot(gs01[5,0:2])
#
# ramp_axs = [ax1_ramp, ax2_ramp, ax3_ramp, ax4_ramp, ax5_ramp,ax6_ramp, ax7_ramp, ax8_ramp,
# ax9_ramp, ax10_ramp, ax11_ramp, ax12_ramp]
#
# # order of models
# models = ['Cb stellate','RS Inhibitory','FS', 'RS Pyramidal','RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN']
#
# # plot ramps
# for i in range(len(models)):
# plot_ramp_V(ramp_axs[i], model=models[i])
#
# # add scalebar
# plt.rcParams.update({'font.size': 6})
#
# add_scalebar(ax11_ramp, matchx=False, matchy=False, hidex=True, hidey=True, sizex=1000, sizey=50, labelx='1 s',
# labely='50 mV', loc=3, pad=-2, borderpad=0, barwidth=1, bbox_to_anchor=Bbox.from_bounds(-0.05, 0.1, 1, 1),
# bbox_transform=ax11_ramp.transAxes)
# # add_scalebar(ax12_ramp, matchx=False, matchy=False, hidex=True, hidey=True, sizex=1000, sizey=25, labelx='1 s',
# # labely='25 mV', loc=3, pad=-2, borderpad=0, barwidth=2, bbox_to_anchor=Bbox.from_bounds(-0.05, 0.1, 1, 1),
# # bbox_transform=ax12_ramp.transAxes)
#
# # add subplot labels
# for i in range(0,len(models)):
# ramp_axs[i].text(-0.05, 1.08, string.ascii_uppercase[i], transform=ramp_axs[i].transAxes, size=10, weight='bold')
#
# fig.savefig('./Figures/ramp_firing.pdf', dpi=3000)
# plt.show()
# plot ramp protocol and responses of each model to ramp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.transforms import Bbox
import string
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
#### from https://gist.github.com/dmeliza/3251476 #####################################################################
from matplotlib.offsetbox import AnchoredOffsetbox
class AnchoredScaleBar(AnchoredOffsetbox):
def __init__(self, transform, sizex=0, sizey=0, labelx=None, labely=None, loc=4,
pad=0.1, borderpad=0.1, sep=2, prop=None, barcolor="black", barwidth=None,
**kwargs):
"""
Draw a horizontal and/or vertical bar with the size in data coordinate
of the give axes. A label will be drawn underneath (center-aligned).
- transform : the coordinate frame (typically axes.transData)
- sizex,sizey : width of x,y bar, in data units. 0 to omit
- labelx,labely : labels for x,y bars; None to omit
- loc : position in containing axes
- pad, borderpad : padding, in fraction of the legend font size (or prop)
- sep : separation between labels and bars in points.
- **kwargs : additional arguments passed to base class constructor
"""
from matplotlib.patches import Rectangle
from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea
bars = AuxTransformBox(transform)
if sizex:
bars.add_artist(Rectangle((0, 0), sizex, 0, ec=barcolor, lw=barwidth, fc="none"))
if sizey:
bars.add_artist(Rectangle((0, 0), 0, sizey, ec=barcolor, lw=barwidth, fc="none"))
if sizex and labelx:
self.xlabel = TextArea(labelx)
bars = VPacker(children=[bars, self.xlabel], align="center", pad=0, sep=sep)
if sizey and labely:
self.ylabel = TextArea(labely)
bars = HPacker(children=[self.ylabel, bars], align="center", pad=0, sep=sep)
AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
child=bars, prop=prop, frameon=False, **kwargs)
def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, **kwargs):
""" Add scalebars to axes
Adds a set of scale bars to *ax*, matching the size to the ticks of the plot
and optionally hiding the x and y axes
- ax : the axis to attach ticks to
- matchx,matchy : if True, set size of scale bars to spacing between ticks
if False, size should be set using sizex and sizey params
- hidex,hidey : if True, hide x-axis and y-axis of parent
- **kwargs : additional arguments passed to AnchoredScaleBars
Returns created scalebar object
"""
def f(axis):
l = axis.get_majorticklocs()
return len(l) > 1 and (l[1] - l[0])
if matchx:
kwargs['sizex'] = f(ax.xaxis)
kwargs['labelx'] = str(kwargs['sizex'])
if matchy:
kwargs['sizey'] = f(ax.yaxis)
kwargs['labely'] = str(kwargs['sizey'])
sb = AnchoredScaleBar(ax.transData, **kwargs)
ax.add_artist(sb)
if hidex: ax.xaxis.set_visible(False)
if hidey: ax.yaxis.set_visible(False)
if hidex and hidey: ax.set_frame_on(False)
return sb
########################################################################################################################
def plot_ramp_V(ax, model='RS Pyramidal'): # , stop=750
model_ramp = pd.read_csv('./Figures/Data/model_ramp.csv')
# ax.plot(model_ramp['t'], model_ramp[model], 'k', linewidth=0.0025)
ax.plot(model_ramp['t'], model_ramp[model], 'k', linewidth=0.1)
ax.set_ylabel('V')
ax.set_xlabel('Time [s]')
ax.set_ylim(-80, 60)
ax.axis('off')
ax.set_title(model, fontsize=8)
def plot_I_ramp(ax):
dt = 0.01
I_low = 0
I_high = 0.001
initial_period = 1000
sec = 4
ramp_len = int(4 * 1000 * 1 / dt)
stim_time = ramp_len * 2
I_amp = np.array([0])
I_amp = np.reshape(I_amp, (1, I_amp.shape[0]))
I_ramp = np.zeros((stim_time, 1)) @ I_amp
I_ramp[:, :] = np.ones((stim_time, 1)) @ I_amp
stim_num_step = I_ramp.shape[1]
start=0
I_ramp[start:int(start + ramp_len), 0] = np.linspace(0, I_high, ramp_len)
I_ramp[int(start + ramp_len):int(start + ramp_len * 2), 0] = np.linspace(I_high, 0, ramp_len)
t = np.arange(0, 4000 * 2, dt)
ax.plot(t, I_ramp)
ax.set_ylabel('I')
ax.set_xlabel('Time [s]')
ax.axis('off')
ax.set_title('Ramp Current', fontsize=8, x=0.5, y=-0.5)
return ax
#% plot setup
fig = plt.figure(figsize=cm2inch(17.6,25))
gs0 = fig.add_gridspec(2, 1, wspace=0.)
gs00 = gs0[:].subgridspec(13, 1, wspace=0.7, hspace=1.0)
ax1_ramp = fig.add_subplot(gs00[0])
ax2_ramp = fig.add_subplot(gs00[1])
ax3_ramp = fig.add_subplot(gs00[2])
ax4_ramp = fig.add_subplot(gs00[3])
ax5_ramp = fig.add_subplot(gs00[4])
ax6_ramp = fig.add_subplot(gs00[5])
ax7_ramp = fig.add_subplot(gs00[6])
ax8_ramp = fig.add_subplot(gs00[7])
ax9_ramp = fig.add_subplot(gs00[8])
ax10_ramp = fig.add_subplot(gs00[9])
ax11_ramp = fig.add_subplot(gs00[10])
ax12_ramp = fig.add_subplot(gs00[11])
ax13_I = fig.add_subplot(gs00[12])
ramp_axs = [ax1_ramp, ax2_ramp, ax3_ramp, ax4_ramp, ax5_ramp,ax6_ramp, ax7_ramp, ax8_ramp,
ax9_ramp, ax10_ramp, ax11_ramp, ax12_ramp]
# order of models
models = ['Cb stellate','RS Inhibitory','FS', 'RS Pyramidal','RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN']
# plot ramps
for i in range(len(models)):
plot_ramp_V(ramp_axs[i], model=models[i])
# add scalebar
plt.rcParams.update({'font.size': 6})
add_scalebar(ax12_ramp, matchx=False, matchy=False, hidex=True, hidey=True, sizex=1000, sizey=50, labelx='1 s',
labely='50 mV', loc=3, pad=-2, borderpad=0, barwidth=1, bbox_to_anchor=Bbox.from_bounds(0.01, 0.05, 1, 1),
bbox_transform=ax12_ramp.transAxes)
ax13_I = plot_I_ramp(ax13_I)
add_scalebar(ax13_I, matchx=False, matchy=False, hidex=True, hidey=True, sizex=1000, sizey=0.0005, labelx='1 s',
labely='0.5 $I_{max}$', loc=3, pad=-2, borderpad=0, barwidth=1,
bbox_to_anchor=Bbox.from_bounds(0.0, -0.01, 1, 1), bbox_transform=ax13_I.transAxes)
# add subplot labels
for i in range(0,len(models)):
ramp_axs[i].text(-0.01, 1.1, string.ascii_uppercase[i], transform=ramp_axs[i].transAxes, size=10, weight='bold')
#save
fig.set_size_inches(cm2inch(17.6,22))
fig.savefig('./Figures/ramp_firing.jpg', dpi=fig.dpi)#pdf #eps
plt.show()

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 424 KiB

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 275 KiB

View File

@ -13,15 +13,7 @@ import matplotlib
import matplotlib.lines as mlines
from matplotlib import ticker
from matplotlib.ticker import NullFormatter
from Figures.plotstyle import boxplot_style
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
#%% ##################### From https://stackoverflow.com/questions/52878845/swarmplot-with-hue-affecting-marker-beyond-color ##
# to change marker types in seaborn swarmplot
@ -52,7 +44,7 @@ def GetColor2Marker(markers):
mkcolors = [(palette[i]) for i in range(len(markers))]
return dict(zip(mkcolors,markers))
def fixlegend(ax,markers,markersize=3,**kwargs):
def fixlegend(ax,markers,markersize=8,**kwargs):
# Fix Legend
legtitle = ax.get_legend().get_title().get_text()
_,l = ax.get_legend_handles_labels()
@ -94,44 +86,13 @@ def new_scatter(self, *args, **kwargs):
return FinalCollection
Axes.scatter = new_scatter
############## End hack. ##############
########################################################################################################################
#%% add gradient arrows
import matplotlib.pyplot as plt
import matplotlib.transforms
import matplotlib.path
from matplotlib.collections import LineCollection
def rainbowarrow(ax, start, end, cmap, n=50,lw=3):
# Arrow shaft: LineCollection
x = np.linspace(start[0],end[0],n)
y = np.linspace(start[1],end[1],n)
points = np.array([x,y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)
lc = LineCollection(segments, cmap=cmap, linewidth=lw)
lc.set_array(np.linspace(0,1,n))
ax.add_collection(lc)
# Arrow head: Triangle
tricoords = [(0,-0.02),(0.025,0),(0,0.02),(0,-0.02)]
angle = np.arctan2(end[1]-start[1],end[0]-start[0])
rot = matplotlib.transforms.Affine2D().rotate(angle)
tricoords2 = rot.transform(tricoords)
tri = matplotlib.path.Path(tricoords2, closed=True)
ax.scatter(end[0],end[1], c=1, s=(4*lw)**2, marker=tri, cmap=cmap,vmin=0)
ax.autoscale_view()
return ax
def gradientaxis(ax, start, end, cmap, n=100,lw=1):
# Arrow shaft: LineCollection
x = np.linspace(start[0],end[0],n)
y = np.linspace(start[1],end[1],n)
points = np.array([x,y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)
lc = LineCollection(segments, cmap=cmap, linewidth=lw,zorder=15)
lc.set_array(np.linspace(0,1,n))
ax.add_collection(lc)
return ax
#%%
def boxplot_with_markers(ax,max_width, alteration='shift', msize=2.2):
hlinewidth = 0.5
def boxplot_with_markers(ax,max_width, alteration='shift'):
# size =4
# ax.tick_params(axis='x', rotation=90)
model_names = ['RS pyramidal','RS inhibitory','FS',
'RS pyramidal +$K_V1.1$','RS inhibitory +$K_V1.1$',
'FS +$K_V1.1$','Cb stellate','Cb stellate +$K_V1.1$',
@ -153,87 +114,81 @@ def boxplot_with_markers(ax,max_width, alteration='shift', msize=2.2):
]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
colors = [matplotlib.colors.to_rgb(c) for c in colorslist] # sns.color_palette("hls", 14, desat=0.75)#[cm.tab20(i) for i in range(20)]
clr_dict = {}
for m in range(len(model_names)):
clr_dict[model_names[m]] = colors[m]
print(colors)
print(clr_dict)
Markers = ["o", "o", "o", "^", "^", "^", "D", "D", "D", "s", "s", "s"]
if alteration=='shift':
i = 3 # Kv1.1 act
ax.axvspan(i - 0.4, i + 0.4, fill=False, edgecolor='k')
df = pd.read_csv('./Figures/Data/rheo_shift_corr.csv')
sns.swarmplot(y="corr", x="$\Delta V_{1/2}$", hue="model", data=df,
palette=clr_dict, linewidth=0, orient='v', ax=ax, size=msize,
sns.swarmplot(y="corr", x="$\Delta V_{1/2}$", hue="model", data=df, #dodge=True,
palette=clr_dict, linewidth=0, orient='v', ax=ax,
order=['Na activation', 'Na inactivation', 'K activation', '$K_V1.1$ activation',
'$K_V1.1$ inactivation', 'A activation', 'A inactivation'],
hue_order=model_names, co2mk=Markers)
lim = ax.get_xlim()
ax.plot([lim[0], lim[1]], [0, 0], ':r',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [1, 1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [-1, -1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [0, 0], ':r')
ax.plot([lim[0], lim[1]], [1, 1], ':k')
ax.plot([lim[0], lim[1]], [-1, -1], ':k')
ax.set_title("Shift ($\Delta V_{1/2}$)", y=1.05)
ax.set_xticklabels(['Na \nactivation', 'Na \ninactivation', 'K \nactivation', '$K_V1.1$ \nactivation',
'$K_V1.1$ \ninactivation', 'A \nactivation', 'A \ninactivation'])
elif alteration=='slope':
i = 4 # Kv1.1 inact
ax.axvspan(i - 0.4, i + 0.4, fill=False, edgecolor='k')
df = pd.read_csv('./Figures/Data/rheo_scale_corr.csv')
# Add in points to show each observation
sns.swarmplot(y="corr", x="Slope (k)", hue="model", data=df,
palette=clr_dict, linewidth=0, orient='v', ax=ax, size=msize,
sns.swarmplot(y="corr", x="Slope (k)", hue="model", data=df, #dodge=True,
palette=clr_dict, linewidth=0, orient='v', ax=ax,
order=['Na activation', 'Na inactivation', 'K activation', '$K_V1.1$ activation',
'$K_V1.1$ inactivation', 'A activation', 'A inactivation'],
hue_order=model_names, co2mk=Markers)
lim = ax.get_xlim()
ax.plot([lim[0], lim[1]], [0, 0], ':r',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [1, 1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [-1, -1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [0, 0], ':r')
ax.plot([lim[0], lim[1]], [1, 1], ':k')
ax.plot([lim[0], lim[1]], [-1, -1], ':k')
ax.set_title("Slope (k)", y=1.05)
ax.set_xticklabels(['Na \nactivation', 'Na \ninactivation', 'K \nactivation', '$K_V1.1$ \nactivation',
'$K_V1.1$ \ninactivation', 'A \nactivation', 'A \ninactivation'])
elif alteration=='g':
i = 4 # Leak
ax.axvspan(i - 0.4, i + 0.4, fill=False, edgecolor='k')
df = pd.read_csv('./Figures/Data/rheo_g_corr.csv')
# Add in points to show each observation
sns.swarmplot(y="corr", x="g", hue="model", data=df,
palette=clr_dict, linewidth=0, orient='v', ax=ax, size=msize,
sns.swarmplot(y="corr", x="g", hue="model", data=df, #dodge=True,
palette=clr_dict, linewidth=0, orient='v', ax=ax,
order=['Na', 'K', '$K_V1.1$', 'A', 'Leak'],
hue_order=model_names, co2mk=Markers)
lim = ax.get_xlim()
ax.plot([lim[0], lim[1]], [0, 0], ':r',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [1, 1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [-1, -1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [0, 0], ':r')
ax.plot([lim[0], lim[1]], [1, 1], ':k')
ax.plot([lim[0], lim[1]], [-1, -1], ':k')
ax.set_title("Conductance (g)", y=1.05)
ax.set_xticklabels(textwrap.fill(x.get_text(), max_width) for x in ax.get_xticklabels())
else:
print('Please chose "shift", "slope" or "g"')
ax.get_legend().remove()
ax.xaxis.grid(False)
sns.despine(trim=True, bottom=True, ax=ax)
ax.set(xlabel=None, ylabel=r'Kendall $\it{\tau}$')
ax.set_xticklabels(textwrap.fill(x.get_text(), max_width) for x in ax.get_xticklabels())
def model_legend(ax, marker_s_leg, pos, ncol):
# colorslist = [ '#40A787', # cyan'#
# '#F0D730', # yellow
# '#C02717', # red
# '#007030', # dark green
# '#AAB71B', # lightgreen
# '#008797', # light blue
# '#F78017', # orange
# '#478010', # green
# '#53379B', # purple
# '#2060A7', # blue
# '#873770', # magenta
# '#D03050' # pink
# ]
# import matplotlib.colors
# colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
colorslist = [ '#40A787', # cyan'#
'#F0D730', # yellow
'#C02717', # red
'#007030', # dark green
'#AAB71B', # lightgreen
'#008797', # light blue
'#F78017', # orange
'#478010', # green
'#53379B', # purple
'#2060A7', # blue
'#873770', # magenta
'#D03050' # pink
]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist] #sns.color_palette("hls", 14, desat=0.75) #[cm.tab20(i) for i in range(20)]
model_pos = {'Cb stellate':0, 'RS Inhibitory':1, 'FS':2, 'RS Pyramidal':3,
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':4,
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':5, 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':6,
@ -241,30 +196,8 @@ def model_legend(ax, marker_s_leg, pos, ncol):
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':9,
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':10, 'STN':11}
# model_pos = {'Cb stellate': 0, 'RS Inhibitory': 1, 'FS': 2, 'RS Pyramidal': 3,
# 'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 4,
# 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 5,
# 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 6,
# 'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 7,
# 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 8,
# 'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 9,
# 'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 10, 'STN': 11}
colorslist = ['#007030', # dark green
'#F0D730', # yellow
'#C02717', # red
'#478010', # green
'#AAB71B', # lightgreen
'#F78017', # orange
'#40A787', # cyan'#
'#008797', # light blue
'#2060A7', # blue
'#D03050', # pink
'#53379B', # purple
'#873770', # magenta
]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
Markers = ["o", "o", "o", "^", "^", "^", "D", "D", "D", "s", "s", "s"]
RS_p = mlines.Line2D([], [], color=colors[model_pos['RS Pyramidal']], marker=Markers[model_pos['RS Pyramidal']], markersize=marker_s_leg, linestyle='None',
label='RS pyramidal')
@ -290,6 +223,7 @@ def model_legend(ax, marker_s_leg, pos, ncol):
ax.legend(handles=[RS_p, RS_i, FS, RS_p_Kv, RS_i_Kv, FS_Kv, Cb, Cb_pl, Cb_sw, STN, STN_pl, STN_sw], loc='center',
bbox_to_anchor=pos, ncol=ncol, frameon=False)
def plot_rheo_alt(ax, model='FS', color1='red', color2='dodgerblue', alteration='shift'):
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
@ -326,7 +260,8 @@ def plot_rheo_alt(ax, model='FS', color1='red', color2='dodgerblue', alteration=
'#873770', # magenta
]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
colors = [matplotlib.colors.to_rgb(c) for c in
colorslist] #sns.color_palette("hls", 14, desat=0.75)#[cm.tab20(i) for i in range(20)]
clr_dict = {}
for m in range(len(model_names)):
clr_dict[model_names[m]] = colors[m]
@ -340,45 +275,25 @@ def plot_rheo_alt(ax, model='FS', color1='red', color2='dodgerblue', alteration=
ax.set_xticks([0.5, 1, 2])
ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
ax.xaxis.set_minor_formatter(NullFormatter())
ax.set_xlabel('$k$/$k_{WT}$')
ax.set_xlabel('Slope factor k')
elif alteration=='g':
df = pd.read_csv('./Figures/Data/rheo_g_ex.csv')
ax.set_xscale("log")
ax.set_xticks([0.5, 1, 2])
ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
ax.xaxis.set_minor_formatter(NullFormatter())
ax.set_xlabel('$g$/$g_{WT}$')
ax.set_xlabel('g')
for mod in model_names:
if mod == model_name_dict[model]:
ax.plot(df['alteration'], df[mod], color=clr_dict[mod], alpha=1, zorder=10, linewidth=2)
ax.plot(df['alteration'], df[mod], color=clr_dict[mod], alpha=1, zorder=10, linewidth=2)
else:
ax.plot(df['alteration'], df[mod], color=clr_dict[mod], alpha=0.5, zorder=1, linewidth=1)
ax.plot(df['alteration'], df[mod], color=clr_dict[mod], alpha=1, zorder=1, linewidth=1)
ax.set_ylabel('$\Delta$ Rheobase (nA)', labelpad=0)
ax.set_ylabel('$\Delta$ Rheobase (nA)')
x = df['alteration']
y = df[model_name_dict[model]]
ax.set_xlim(x.min(), x.max())
ax.set_ylim(df[model_names].min().min(), df[model_names].max().max())
# x axis color gradient
cvals = [-2., 2]
colors = ['lightgrey', 'k']
norm = plt.Normalize(min(cvals), max(cvals))
tuples = list(zip(map(norm, cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
(xstart, xend) = ax.get_xlim()
(ystart, yend) = ax.get_ylim()
print(ystart, yend)
start = (xstart, ystart*1.0)
end = (xend, ystart*1.0)
ax = gradientaxis(ax, start, end, cmap, n=200,lw=4)
ax.spines['bottom'].set_visible(False)
# ax.set_ylim(ystart, yend)
#xlabel tick colors
# my_colors = ['lightgrey', 'grey', 'k']
# for ticklabel, tickcolor in zip(ax.get_xticklabels(), my_colors):
# ticklabel.set_color(tickcolor)
return ax
def plot_fI(ax, model='RS Pyramidal', type='shift', alt='m', color1='red', color2='dodgerblue'):
@ -409,30 +324,9 @@ def plot_fI(ax, model='RS Pyramidal', type='shift', alt='m', color1='red', color
for i in newdf.index:
ax.plot(json.loads(newdf.loc[i, 'I']), json.loads(newdf.loc[i, 'F']), color=colors[c])
c += 1
# colors2 = [colors[10, :], 'k']
# norm2 = plt.Normalize(min(cvals), max(cvals))
# tuples2 = list(zip(map(norm2, cvals), colors2))
# cmap2 = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples2)
#
# colors3 = [colors[11, :], 'lightgrey']
# norm3 = plt.Normalize(min(cvals), max(cvals))
# tuples3 = list(zip(map(norm3, cvals), colors3))
# cmap3 = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples3)
#
# start = (1.1, json.loads(newdf.loc[10, 'F'])[-1])
# end = (1.1, json.loads(newdf.loc[20, 'F'])[-1])#-json.loads(newdf.loc[20, 'F'])[-1]*0.1)
# ax = rainbowarrow(ax, start, end, cmap2, n=50, lw=1)
# ax.text(1.15, json.loads(newdf.loc[20, 'F'])[-1], '$+ \Delta V$', fontsize=4, color='k')
#
# start = (1.1, json.loads(newdf.loc[10, 'F'])[-1])
# end = (1.1, json.loads(newdf.loc[0, 'F'])[-1])#-json.loads(newdf.loc[0, 'F'])[-1]*0.1)
# ax = rainbowarrow(ax, start, end, cmap3, n=50, lw=1)
# ax.text(1.15, json.loads(newdf.loc[0, 'F'])[-1], '$- \Delta V$', fontsize=4, color='lightgrey')
ax.set_ylabel('Frequency [Hz]')
ax.set_xlabel('Current [nA]')
ax.set_title(model, x=0.2, y=1.025)
ax.set_title(model)
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
L = ax.get_ylim()
@ -441,7 +335,6 @@ def plot_fI(ax, model='RS Pyramidal', type='shift', alt='m', color1='red', color
#%%
boxplot_style()
color_dict = {'Cb stellate': '#40A787', # cyan'#
'RS Inhibitory': '#F0D730', # yellow
'FS': '#C02717', # red
@ -457,42 +350,46 @@ color_dict = {'Cb stellate': '#40A787', # cyan'#
}
# plot setup
marker_s_leg = 2
max_width = 20
pad_x = 0.85
pad_y= 0.4
pad_w = 1.1
pad_h = 0.7
fig = plt.figure()
gs = fig.add_gridspec(3, 7, wspace=1.2, hspace=1.)
ax0 = fig.add_subplot(gs[0,2:7])
marker_s_leg = 8
max_width = 10
pad_x = 0.6
pad_y= 0.3
pad_w = 0.8
pad_h = 0.5
fig = plt.figure(figsize=(18,10))
gs = fig.add_gridspec(3, 6, wspace=0.9)
plt.subplots_adjust(hspace=0.8) #, wspace=0.6
ax0 = fig.add_subplot(gs[0,2:6])
ax0_ex = fig.add_subplot(gs[0,1])
ax0_fI = fig.add_subplot(gs[0,0])
ax1 = fig.add_subplot(gs[1,2:7])
ax1 = fig.add_subplot(gs[1,2:6])
ax1_ex = fig.add_subplot(gs[1,1])
ax1_fI = fig.add_subplot(gs[1,0])
ax2 = fig.add_subplot(gs[2,2:7])
ax2 = fig.add_subplot(gs[2,2:6])
ax2_ex = fig.add_subplot(gs[2,1])
ax2_fI = fig.add_subplot(gs[2,0])
line_width = 1
# plot fI curves
ax0_fI = plot_fI(ax0_fI, model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='shift', alt='s', color1='lightgrey', color2='k')
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=line_width,transform=ax0_fI.transAxes, color=color_dict['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=2,transform=ax0_fI.transAxes, color=color_dict['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = ax0_fI.add_patch(rec)
rec.set_clip_on(False)
ax1_fI = plot_fI(ax1_fI, model='Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='slope', alt='u', color1='lightgrey', color2='k')
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=line_width,transform=ax1_fI.transAxes, color=color_dict['Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=2,transform=ax1_fI.transAxes, color=color_dict['Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = ax1_fI.add_patch(rec)
rec.set_clip_on(False)
ax2_fI = plot_fI(ax2_fI, model='Cb stellate', type='g', alt='Leak', color1='lightgrey', color2='k')
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=line_width,transform=ax2_fI.transAxes, color=color_dict['Cb stellate'], alpha=1, zorder=-1)
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=2,transform=ax2_fI.transAxes, color=color_dict['Cb stellate'], alpha=1, zorder=-1)
rec = ax2_fI.add_patch(rec)
rec.set_clip_on(False)
# label fI subplots with letters
ax0_fI.text(-0.6, 1.28, string.ascii_uppercase[0], transform=ax0_fI.transAxes, size=16, weight='bold') #-0.09
ax1_fI.text(-0.6, 1.28, string.ascii_uppercase[1], transform=ax1_fI.transAxes,size=16, weight='bold')
ax2_fI.text(-0.6, 1.28, string.ascii_uppercase[2], transform=ax2_fI.transAxes,size=16, weight='bold')
# plot boxplots
boxplot_with_markers(ax0,max_width, alteration='shift')
@ -500,8 +397,8 @@ boxplot_with_markers(ax1,max_width, alteration='slope')
boxplot_with_markers(ax2,max_width, alteration='g')
# plot legend
pos = (0.225, -0.9)
ncol = 5
pos = (0.25, -0.6)
ncol = 6
model_legend(ax2, marker_s_leg, pos, ncol)
# plot rheo across model for example alteration
@ -509,56 +406,67 @@ plot_rheo_alt(ax0_ex,model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='
plot_rheo_alt(ax1_ex,model='Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k',alteration='slope')
plot_rheo_alt(ax2_ex, model='Cb stellate', color1='lightgrey', color2='k', alteration='g')
# label subplots with letters
ax0_fI.text(-0.875, 1.35, string.ascii_uppercase[0], transform=ax0_fI.transAxes, size=10, weight='bold')
ax0_ex.text(-0.8, 1.35, string.ascii_uppercase[1], transform=ax0_ex.transAxes, size=10, weight='bold')
ax0.text(-0.075, 1.35, string.ascii_uppercase[2], transform=ax0.transAxes, size=10, weight='bold')
ax1_fI.text(-0.875, 1.35, string.ascii_uppercase[3], transform=ax1_fI.transAxes,size=10, weight='bold')
ax1_ex.text(-0.8, 1.35, string.ascii_uppercase[4], transform=ax1_ex.transAxes, size=10, weight='bold')
ax1.text(-0.075, 1.35, string.ascii_uppercase[5], transform=ax1.transAxes, size=10, weight='bold')
ax2_fI.text(-0.875, 1.35, string.ascii_uppercase[6], transform=ax2_fI.transAxes,size=10, weight='bold')
ax2_ex.text(-0.8, 1.35, string.ascii_uppercase[7], transform=ax2_ex.transAxes, size=10, weight='bold')
ax2.text(-0.075, 1.35, string.ascii_uppercase[8], transform=ax2.transAxes, size=10, weight='bold')
# save
fig.set_size_inches(cm2inch(20.75,12))
fig.savefig('./Figures/rheobase_correlation.pdf', dpi=fig.dpi)
# fig.savefig('./Figures/rheobase_correlation.png', dpi=fig.dpi) #bbox_inches='tight', dpi=fig.dpi # eps # pdf
fig.savefig('./Figures/rheobase_correlation.pdf', bbox_inches='tight')
plt.show()
#%%
# fig, axs = plt.subplots(1,2)
# axs[0] = plot_fI(axs[0] , model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='shift', alt='s', color1='lightgrey', color2='k')
# plt.show()
#%%
# #%% alternative layout
# marker_s_leg = 8
# max_width = 10
# pad_x = 0.2
# pad_y= 0.4
# pad_w = 0.22
# pad_h = 0.6
#
# fig = plt.figure(figsize=(12,20))
# gs = fig.add_gridspec(3, 1, hspace=0.4, wspace=0.4)
# gs0 = gs[0].subgridspec(2, 4, wspace=0.6, hspace=1.)
# gs1 = gs[1].subgridspec(2, 4, wspace=0.6, hspace=1.)
# gs2 = gs[2].subgridspec(2, 4, wspace=0.6, hspace=1.)
# ax0 = fig.add_subplot(gs0[1,:])
# ax0_ex = fig.add_subplot(gs0[0,2:])
# ax0_fI = fig.add_subplot(gs0[0,:2])
# ax1 = fig.add_subplot(gs1[1,:])
# ax1_ex = fig.add_subplot(gs1[0,2:])
# ax1_fI = fig.add_subplot(gs1[0,:2])
# ax2 = fig.add_subplot(gs2[1,:])
# ax2_ex = fig.add_subplot(gs2[0,2:])
# ax2_fI = fig.add_subplot(gs2[0,:2])
#
#
# ax0_fI = plot_fI(ax0_fI, model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='shift', alt='s', color1='lightgrey', color2='k')
# rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=2,transform=ax0_fI.transAxes, color=color_dict['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
# rec = ax0_fI.add_patch(rec)
# rec.set_clip_on(False)
#
# ax1_fI = plot_fI(ax1_fI, model='Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='slope', alt='u', color1='lightgrey', color2='k')
# rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=2,transform=ax1_fI.transAxes, color=color_dict['Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
# rec = ax1_fI.add_patch(rec)
# rec.set_clip_on(False)
#
# cvals = [-2., 2]
# colors = ['lightgrey', 'k']
# ax2_fI = plot_fI(ax2_fI, model='Cb stellate', type='g', alt='Leak', color1='lightgrey', color2='k')
# rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=2,transform=ax2_fI.transAxes, color=color_dict['Cb stellate'], alpha=1, zorder=-1)
# rec = ax2_fI.add_patch(rec)
# rec.set_clip_on(False)
#
# norm = plt.Normalize(min(cvals), max(cvals))
# tuples = list(zip(map(norm, cvals), colors))
# cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
# colors = cmap(np.linspace(0, 1, 22))
# # label subplots with letters
# ax0_fI.text(-0.2, 1.38, string.ascii_uppercase[0], transform=ax0_fI.transAxes, size=16, weight='bold') #-0.09
# ax1_fI.text(-0.2, 1.38, string.ascii_uppercase[1], transform=ax1_fI.transAxes,size=16, weight='bold')
# ax2_fI.text(-0.2, 1.38, string.ascii_uppercase[2], transform=ax2_fI.transAxes,size=16, weight='bold')
#
# colors2 = [colors[10,:], 'k']
# norm2 = plt.Normalize(min(cvals), max(cvals))
# tuples2 = list(zip(map(norm2, cvals), colors2))
# cmap2 = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples2)
# # plot boxplots
# boxplot_with_markers(ax0,max_width, alteration='shift')
# boxplot_with_markers(ax1,max_width, alteration='slope')
# boxplot_with_markers(ax2,max_width, alteration='g')
# # plot legend
# pos = (0.5, -1.)
# ncol = 6
# model_legend(ax2, marker_s_leg, pos, ncol)
#
# colors3 = [colors[11,:], 'lightgrey']
# norm3 = plt.Normalize(min(cvals), max(cvals))
# tuples3 = list(zip(map(norm3, cvals), colors3))
# cmap3 = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples3)
# # # plot rheo across model for example alteration
# plot_rheo_alt(ax0_ex,model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k', alteration='shift')
# plot_rheo_alt(ax1_ex,model='Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k',alteration='slope')
# plot_rheo_alt(ax2_ex, model='Cb stellate', color1='lightgrey', color2='k', alteration='g')
#
# fig, axs = plt.subplots(1,2)
# start = (0,0)
# end = (1,1)
# axs[0] = rainbowarrow(axs[0], start, end, cmap2, n=50,lw=3)
# start = (0,0)
# end = (-1,-1)
# axs[0] = rainbowarrow(axs[0], start, end, cmap3, n=50,lw=3)
# fig.savefig('rheobase_correlation_2.pdf', bbox_inches='tight')
# plt.show()

View File

@ -1,648 +0,0 @@
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 3 19:52:04 2021
@author: nils
"""
import pandas as pd
import numpy as np
import string
import textwrap
import json
import matplotlib
import matplotlib.lines as mlines
from matplotlib import ticker
from matplotlib.ticker import NullFormatter
from Figures.plotstyle import boxplot_style
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
#%% ##################### From https://stackoverflow.com/questions/52878845/swarmplot-with-hue-affecting-marker-beyond-color ##
# to change marker types in seaborn swarmplot
import seaborn as sns
import matplotlib.pyplot as plt
############## Begin hack ##############
from matplotlib.axes._axes import Axes
from matplotlib.markers import MarkerStyle
from numpy import ndarray
def GetColor2Marker(markers):
colorslist = ['#40A787', # cyan'#
'#F0D730', # yellow
'#C02717', # red
'#007030', # dark green
'#AAB71B', # lightgreen
'#008797', # light blue
'#F78017', # orange
'#478010', # green
'#53379B', # purple
'#2060A7', # blue
'#873770', # magenta
'#D03050' # pink
]
import matplotlib.colors
palette = [matplotlib.colors.to_rgb(c) for c in colorslist] #
mkcolors = [(palette[i]) for i in range(len(markers))]
return dict(zip(mkcolors,markers))
def fixlegend(ax,markers,markersize=3,**kwargs):
# Fix Legend
legtitle = ax.get_legend().get_title().get_text()
_,l = ax.get_legend_handles_labels()
colorslist = ['#40A787', # cyan'#
'#F0D730', # yellow
'#C02717', # red
'#007030', # dark green
'#AAB71B', # lightgreen
'#008797', # light blue
'#F78017', # orange
'#478010', # green
'#53379B', # purple
'#2060A7', # blue
'#873770', # magenta
'#D03050' # pink
]
import matplotlib.colors
palette = [matplotlib.colors.to_rgb(c) for c in colorslist]
mkcolors = [(palette[i]) for i in range(len(markers))]
newHandles = [plt.Line2D([0],[0], ls="none", marker=m, color=c, mec="none", markersize=markersize,**kwargs) \
for m,c in zip(markers, mkcolors)]
ax.legend(newHandles,l)
leg = ax.get_legend()
leg.set_title(legtitle)
old_scatter = Axes.scatter
def new_scatter(self, *args, **kwargs):
colors = kwargs.get("c", None)
co2mk = kwargs.pop("co2mk",None)
FinalCollection = old_scatter(self, *args, **kwargs)
if co2mk is not None and isinstance(colors, ndarray):
Color2Marker = GetColor2Marker(co2mk)
paths=[]
for col in colors:
mk=Color2Marker[tuple(col)]
marker_obj = MarkerStyle(mk)
paths.append(marker_obj.get_path().transformed(marker_obj.get_transform()))
FinalCollection.set_paths(paths)
return FinalCollection
Axes.scatter = new_scatter
############## End hack. ##############
########################################################################################################################
#%% add gradient arrows
import matplotlib.pyplot as plt
import matplotlib.transforms
import matplotlib.path
from matplotlib.collections import LineCollection
def rainbowarrow(ax, start, end, cmap, n=50,lw=3):
# Arrow shaft: LineCollection
x = np.linspace(start[0],end[0],n)
y = np.linspace(start[1],end[1],n)
points = np.array([x,y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)
lc = LineCollection(segments, cmap=cmap, linewidth=lw)
lc.set_array(np.linspace(0,1,n))
ax.add_collection(lc)
# Arrow head: Triangle
tricoords = [(0,-0.02),(0.025,0),(0,0.02),(0,-0.02)]
angle = np.arctan2(end[1]-start[1],end[0]-start[0])
rot = matplotlib.transforms.Affine2D().rotate(angle)
tricoords2 = rot.transform(tricoords)
tri = matplotlib.path.Path(tricoords2, closed=True)
ax.scatter(end[0],end[1], c=1, s=(4*lw)**2, marker=tri, cmap=cmap,vmin=0)
ax.autoscale_view()
return ax
def gradientaxis(ax, start, end, cmap, n=100,lw=1):
# Arrow shaft: LineCollection
x = np.linspace(start[0],end[0],n)
y = np.linspace(start[1],end[1],n)
points = np.array([x,y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)
lc = LineCollection(segments, cmap=cmap, linewidth=lw,zorder=15)
lc.set_array(np.linspace(0,1,n))
ax.add_collection(lc)
return ax
#%%
def boxplot_with_markers(ax,max_width, alteration='shift', msize=2.2):
hlinewidth = 0.5
model_names = ['RS pyramidal','RS inhibitory','FS',
'RS pyramidal +$K_V1.1$','RS inhibitory +$K_V1.1$',
'FS +$K_V1.1$','Cb stellate','Cb stellate +$K_V1.1$',
'Cb stellate $\Delta$$K_V1.1$','STN','STN +$K_V1.1$',
'STN $\Delta$$K_V1.1$']
colorslist = ['#007030', # dark green
'#F0D730', # yellow
'#C02717', # red
'#478010', # green
'#AAB71B', # lightgreen
'#F78017', # orange
'#40A787', # cyan'#
'#008797', # light blue
'#2060A7', # blue
'#D03050', # pink
'#53379B', # purple
'#873770', # magenta
]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
clr_dict = {}
for m in range(len(model_names)):
clr_dict[model_names[m]] = colors[m]
Markers = ["o", "o", "o", "^", "^", "^", "D", "D", "D", "s", "s", "s"]
if alteration=='shift':
i = 3 # Kv1.1 act
ax.axvspan(i - 0.4, i + 0.4, fill=False, edgecolor='k')
df = pd.read_csv('./Figures/Data/rheo_shift_corr.csv')
sns.swarmplot(y="corr", x="$\Delta V_{1/2}$", hue="model", data=df,
palette=clr_dict, linewidth=0, orient='v', ax=ax, size=msize,
order=['Na activation', 'Na inactivation', 'K activation', '$K_V1.1$ activation',
'$K_V1.1$ inactivation', 'A activation', 'A inactivation'],
hue_order=model_names, co2mk=Markers)
lim = ax.get_xlim()
ax.plot([lim[0], lim[1]], [0, 0], ':r',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [1, 1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [-1, -1], ':k',linewidth=hlinewidth)
ax.set_title("Shift ($\Delta V_{1/2}$)", y=1.05)
ax.set_xticklabels(['Na \nactivation', 'Na \ninactivation', 'K \nactivation', '$K_V1.1$ \nactivation',
'$K_V1.1$ \ninactivation', 'A \nactivation', 'A \ninactivation'])
elif alteration=='slope':
i = 4 # Kv1.1 inact
ax.axvspan(i - 0.4, i + 0.4, fill=False, edgecolor='k')
df = pd.read_csv('./Figures/Data/rheo_scale_corr.csv')
# Add in points to show each observation
sns.swarmplot(y="corr", x="Slope (k)", hue="model", data=df,
palette=clr_dict, linewidth=0, orient='v', ax=ax, size=msize,
order=['Na activation', 'Na inactivation', 'K activation', '$K_V1.1$ activation',
'$K_V1.1$ inactivation', 'A activation', 'A inactivation'],
hue_order=model_names, co2mk=Markers)
lim = ax.get_xlim()
ax.plot([lim[0], lim[1]], [0, 0], ':r',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [1, 1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [-1, -1], ':k',linewidth=hlinewidth)
ax.set_title("Slope (k)", y=1.05)
ax.set_xticklabels(['Na \nactivation', 'Na \ninactivation', 'K \nactivation', '$K_V1.1$ \nactivation',
'$K_V1.1$ \ninactivation', 'A \nactivation', 'A \ninactivation'])
elif alteration=='g':
i = 4 # Leak
ax.axvspan(i - 0.4, i + 0.4, fill=False, edgecolor='k')
df = pd.read_csv('./Figures/Data/rheo_g_corr.csv')
# Add in points to show each observation
sns.swarmplot(y="corr", x="g", hue="model", data=df,
palette=clr_dict, linewidth=0, orient='v', ax=ax, size=msize,
order=['Na', 'K', '$K_V1.1$', 'A', 'Leak'],
hue_order=model_names, co2mk=Markers)
lim = ax.get_xlim()
ax.plot([lim[0], lim[1]], [0, 0], ':r',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [1, 1], ':k',linewidth=hlinewidth)
ax.plot([lim[0], lim[1]], [-1, -1], ':k',linewidth=hlinewidth)
ax.set_title("Conductance (g)", y=1.05)
ax.set_xticklabels(textwrap.fill(x.get_text(), max_width) for x in ax.get_xticklabels())
else:
print('Please chose "shift", "slope" or "g"')
ax.get_legend().remove()
ax.xaxis.grid(False)
sns.despine(trim=True, bottom=True, ax=ax)
ax.set(xlabel=None, ylabel=r'Kendall $\it{\tau}$')
def model_legend(ax, marker_s_leg, pos, ncol):
colorslist = [ '#40A787', # cyan'#
'#F0D730', # yellow
'#C02717', # red
'#007030', # dark green
'#AAB71B', # lightgreen
'#008797', # light blue
'#F78017', # orange
'#478010', # green
'#53379B', # purple
'#2060A7', # blue
'#873770', # magenta
'#D03050' # pink
]
model_names = ['RS pyramidal', 'RS inhibitory', 'FS',
'RS pyramidal +$K_V1.1$', 'RS inhibitory +$K_V1.1$',
'FS +$K_V1.1$', 'Cb stellate', 'Cb stellate +$K_V1.1$',
'Cb stellate $\Delta$$K_V1.1$', 'STN', 'STN +$K_V1.1$',
'STN $\Delta$$K_V1.1$']
# colorslist = ['#007030', # dark green
# '#F0D730', # yellow
# '#C02717', # red
# '#478010', # green
# '#AAB71B', # lightgreen
# '#F78017', # orange
# '#40A787', # cyan'#
# '#008797', # light blue
# '#2060A7', # blue
# '#D03050', # pink
# '#53379B', # purple
# '#873770', # magenta
# ]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
clr_dict = {}
for m in range(len(model_names)):
clr_dict[model_names[m]] = colors[m]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
# model_pos = {'Cb stellate':0, 'RS Inhibitory':1, 'FS':2, 'RS Pyramidal':3,
# 'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':4,
# 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':5, 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':6,
# 'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':7, 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':8,
# 'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':9,
# 'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':10, 'STN':11}
Markers = ["o", "o", "o", "^", "^", "^", "D", "D", "D", "s", "s", "s"]
model_pos = {'RS Pyramidal':0, 'RS Inhibitory':1, 'FS':2,
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':3, 'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':4,
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':5, 'Cb stellate':6, 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':7,
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':8, 'STN':9, 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':10,
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':11}
RS_p = mlines.Line2D([], [], color='#007030', marker="^",
markersize=marker_s_leg, linestyle='None',
label='Model D')
RS_i = mlines.Line2D([], [], color='#F0D730', marker="o",
markersize=marker_s_leg, linestyle='None',
label='Model B')
FS = mlines.Line2D([], [], color='#C02717', marker="o", markersize=marker_s_leg,
linestyle='None', label='Model C')
RS_p_Kv = mlines.Line2D([], [], color='#478010',
marker="D",
markersize=marker_s_leg, linestyle='None',
label='Model H')
RS_i_Kv = mlines.Line2D([], [], color='#AAB71B',
marker="^",
markersize=marker_s_leg, linestyle='None',
label='Model E')
FS_Kv = mlines.Line2D([], [], color='#F78017',
marker="D", markersize=marker_s_leg,
linestyle='None', label='Model G')
Cb = mlines.Line2D([], [], color='#40A787', marker="o",
markersize=marker_s_leg, linestyle='None',
label='Model A')
Cb_pl = mlines.Line2D([], [], color='#008797',
marker="^",
markersize=marker_s_leg, linestyle='None',
label='Model F')
Cb_sw = mlines.Line2D([], [], color='#2060A7',
marker="s",
markersize=marker_s_leg, linestyle='None',
label='Model J')
STN = mlines.Line2D([], [], color='#D03050', marker="s", markersize=marker_s_leg,
linestyle='None', label='Model L')
STN_pl = mlines.Line2D([], [], color='#53379B',
marker="D",
markersize=marker_s_leg, linestyle='None',
label='Model I')
STN_sw = mlines.Line2D([], [], color='#873770',
marker="s",
markersize=marker_s_leg, linestyle='None',
label='Model K')
#
# RS_p = mlines.Line2D([], [], color=colors[model_pos['RS Pyramidal']], marker=Markers[model_pos['RS Pyramidal']],
# markersize=marker_s_leg, linestyle='None',
# label='Model D')
# RS_i = mlines.Line2D([], [], color=colors[model_pos['RS Inhibitory']], marker=Markers[model_pos['RS Inhibitory']],
# markersize=marker_s_leg, linestyle='None',
# label='Model B')
# FS = mlines.Line2D([], [], color=colors[model_pos['FS']], marker=Markers[model_pos['FS']], markersize=marker_s_leg,
# linestyle='None', label='Model C')
# RS_p_Kv = mlines.Line2D([], [], color=colors[model_pos['RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# marker=Markers[model_pos['RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# markersize=marker_s_leg, linestyle='None',
# label='Model H')
# RS_i_Kv = mlines.Line2D([], [], color=colors[model_pos['RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# marker=Markers[model_pos['RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# markersize=marker_s_leg, linestyle='None',
# label='Model E')
# FS_Kv = mlines.Line2D([], [], color=colors[model_pos['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# marker=Markers[model_pos['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']], markersize=marker_s_leg,
# linestyle='None', label='Model G')
# Cb = mlines.Line2D([], [], color=colors[model_pos['Cb stellate']], marker=Markers[model_pos['Cb stellate']],
# markersize=marker_s_leg, linestyle='None',
# label='Model A')
# Cb_pl = mlines.Line2D([], [], color=colors[model_pos['Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# marker=Markers[model_pos['Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# markersize=marker_s_leg, linestyle='None',
# label='Model F')
# Cb_sw = mlines.Line2D([], [], color=colors[model_pos['Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# marker=Markers[model_pos['Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# markersize=marker_s_leg, linestyle='None',
# label='Model J')
# STN = mlines.Line2D([], [], color=colors[model_pos['STN']], marker=Markers[model_pos['STN']], markersize=marker_s_leg,
# linestyle='None', label='Model L')
# STN_pl = mlines.Line2D([], [], color=colors[model_pos['STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# marker=Markers[model_pos['STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# markersize=marker_s_leg, linestyle='None',
# label='Model I')
# STN_sw = mlines.Line2D([], [], color=colors[model_pos['STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# marker=Markers[model_pos['STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']],
# markersize=marker_s_leg, linestyle='None',
# label='Model K')
# ax.legend(handles=[RS_p, RS_i, FS, RS_p_Kv, RS_i_Kv, FS_Kv, Cb, Cb_pl, Cb_sw, STN, STN_pl, STN_sw], loc='center',
# bbox_to_anchor=pos, ncol=ncol, frameon=False)
ax.legend(handles=[Cb, RS_i, FS, RS_p, RS_i_Kv, Cb_pl, FS_Kv, RS_p_Kv, STN_pl, Cb_sw, STN_sw, STN], loc='center',
bbox_to_anchor=pos, ncol=ncol, frameon=False)
def plot_rheo_alt(ax, model='FS', color1='red', color2='dodgerblue', alteration='shift'):
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
model_names = ['RS Pyramidal','RS Inhibitory','FS',
'RS Pyramidal +$K_V1.1$','RS Inhibitory +$K_V1.1$',
'FS +$K_V1.1$','Cb stellate','Cb stellate +$K_V1.1$',
'Cb stellate $\Delta$$K_V1.1$','STN','STN +$K_V1.1$',
'STN $\Delta$$K_V1.1$']
model_name_dict = {'RS Pyramidal': 'RS Pyramidal',
'RS Inhibitory': 'RS Inhibitory',
'FS': 'FS',
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'RS Pyramidal +$K_V1.1$',
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'RS Inhibitory +$K_V1.1$',
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'FS +$K_V1.1$',
'Cb stellate': 'Cb stellate',
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'Cb stellate +$K_V1.1$',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'Cb stellate $\Delta$$K_V1.1$',
'STN': 'STN',
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'STN +$K_V1.1$',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'STN $\Delta$$K_V1.1$'}
colorslist = ['#007030', # dark green
'#F0D730', # yellow
'#C02717', # red
'#478010', # green
'#AAB71B', # lightgreen
'#F78017', # orange
'#40A787', # cyan'#
'#008797', # light blue
'#2060A7', # blue
'#D03050', # pink
'#53379B', # purple
'#873770', # magenta
]
import matplotlib.colors
colors = [matplotlib.colors.to_rgb(c) for c in colorslist]
clr_dict = {}
for m in range(len(model_names)):
clr_dict[model_names[m]] = colors[m]
if alteration=='shift':
df = pd.read_csv('./Figures/Data/rheo_shift_ex.csv')
df = df.sort_values('alteration')
ax.set_xlabel('$\Delta$$V_{1/2}$')
elif alteration=='slope':
df = pd.read_csv('./Figures/Data/rheo_slope_ex.csv')
ax.set_xscale("log")
ax.set_xticks([0.5, 1, 2])
ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
ax.xaxis.set_minor_formatter(NullFormatter())
ax.set_xlabel('$k$/$k_{WT}$')
elif alteration=='g':
df = pd.read_csv('./Figures/Data/rheo_g_ex.csv')
ax.set_xscale("log")
ax.set_xticks([0.5, 1, 2])
ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
ax.xaxis.set_minor_formatter(NullFormatter())
ax.set_xlabel('$g$/$g_{WT}$')
for mod in model_names:
if mod == model_name_dict[model]:
ax.plot(df['alteration'], df[mod], color=clr_dict[mod], alpha=1, zorder=10, linewidth=2)
else:
ax.plot(df['alteration'], df[mod], color=clr_dict[mod], alpha=0.5, zorder=1, linewidth=1)
ax.set_ylabel('$\Delta$ Rheobase (nA)', labelpad=0)
x = df['alteration']
y = df[model_name_dict[model]]
ax.set_xlim(x.min(), x.max())
ax.set_ylim(df[model_names].min().min(), df[model_names].max().max())
# x axis color gradient
cvals = [-2., 2]
colors = ['lightgrey', 'k']
norm = plt.Normalize(min(cvals), max(cvals))
tuples = list(zip(map(norm, cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
(xstart, xend) = ax.get_xlim()
(ystart, yend) = ax.get_ylim()
print(ystart, yend)
start = (xstart, ystart*1.0)
end = (xend, ystart*1.0)
ax = gradientaxis(ax, start, end, cmap, n=200,lw=4)
ax.spines['bottom'].set_visible(False)
# ax.set_ylim(ystart, yend)
#xlabel tick colors
# my_colors = ['lightgrey', 'grey', 'k']
# for ticklabel, tickcolor in zip(ax.get_xticklabels(), my_colors):
# ticklabel.set_color(tickcolor)
return ax
def plot_fI(ax, model='RS Pyramidal', type='shift', alt='m', color1='red', color2='dodgerblue'):
model_save_name = {'RS Pyramidal': 'RS_pyr_posp',
'RS Inhibitory': 'RS_inhib_posp',
'FS': 'FS_posp',
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'RS_pyr_Kv',
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'RS_inhib_Kv',
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'FS_Kv',
'Cb stellate': 'Cb_stellate',
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'Cb_stellate_Kv',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'Cb_stellate_Kv_only',
'STN': 'STN',
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'STN_Kv',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': 'STN_Kv_only'}
cvals = [-2., 2]
colors = [color1, color2]
norm = plt.Normalize(min(cvals), max(cvals))
tuples = list(zip(map(norm, cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
colors = cmap(np.linspace(0, 1, 22))
df = pd.read_csv('./Figures/Data/Model_fI/{}_fI.csv'.format(model_save_name[model]))
df.drop(['Unnamed: 0'], axis=1)
newdf = df.loc[df.index[(df['alt'] == alt) & (df['type'] == type)], :]
newdf['mag'] = newdf['mag'].astype('float')
newdf = newdf.sort_values('mag').reset_index()
c = 0
for i in newdf.index:
ax.plot(json.loads(newdf.loc[i, 'I']), json.loads(newdf.loc[i, 'F']), color=colors[c])
c += 1
# colors2 = [colors[10, :], 'k']
# norm2 = plt.Normalize(min(cvals), max(cvals))
# tuples2 = list(zip(map(norm2, cvals), colors2))
# cmap2 = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples2)
#
# colors3 = [colors[11, :], 'lightgrey']
# norm3 = plt.Normalize(min(cvals), max(cvals))
# tuples3 = list(zip(map(norm3, cvals), colors3))
# cmap3 = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples3)
#
# start = (1.1, json.loads(newdf.loc[10, 'F'])[-1])
# end = (1.1, json.loads(newdf.loc[20, 'F'])[-1])#-json.loads(newdf.loc[20, 'F'])[-1]*0.1)
# ax = rainbowarrow(ax, start, end, cmap2, n=50, lw=1)
# ax.text(1.15, json.loads(newdf.loc[20, 'F'])[-1], '$+ \Delta V$', fontsize=4, color='k')
#
# start = (1.1, json.loads(newdf.loc[10, 'F'])[-1])
# end = (1.1, json.loads(newdf.loc[0, 'F'])[-1])#-json.loads(newdf.loc[0, 'F'])[-1]*0.1)
# ax = rainbowarrow(ax, start, end, cmap3, n=50, lw=1)
# ax.text(1.15, json.loads(newdf.loc[0, 'F'])[-1], '$- \Delta V$', fontsize=4, color='lightgrey')
ax.set_ylabel('Frequency [Hz]')
ax.set_xlabel('Current [nA]')
if model == 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':
ax.set_title("Model G", x=0.2, y=1.0)
elif model == 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$':
ax.set_title("Model F", x=0.2, y=1.0)
elif model == 'Cb stellate':
ax.set_title("Model A", x=0.2, y=1.0)
else:
ax.set_title("", x=0.2, y=1.0)
# plot_rheo_alt(ax0_ex, model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k',
# alteration='shift')
# plot_rheo_alt(ax1_ex, model='Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k',
# alteration='slope')
# plot_rheo_alt(ax2_ex, model='Cb stellate', color1='lightgrey', color2='k', alteration='g')
# ax.set_title(model, x=0.2, y=1.025)
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
L = ax.get_ylim()
ax.set_ylim([0, L[1]])
return ax
#%%
boxplot_style()
color_dict = {'Cb stellate': '#40A787', # cyan'#
'RS Inhibitory': '#F0D730', # yellow
'FS': '#C02717', # red
'RS Pyramidal': '#007030', # dark green
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#AAB71B', # lightgreen
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#008797', # light blue
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#F78017', # orange
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#478010', # green
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#53379B', # purple
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#2060A7', # blue
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': '#873770', # magenta
'STN': '#D03050' # pink
}
# plot setup
marker_s_leg = 2
max_width = 20
pad_x = 0.85
pad_y= 0.4
pad_w = 1.1
pad_h = 0.7
fig = plt.figure()
gs = fig.add_gridspec(3, 7, wspace=1.2, hspace=1.)
ax0 = fig.add_subplot(gs[0,2:7])
ax0_ex = fig.add_subplot(gs[0,1])
ax0_fI = fig.add_subplot(gs[0,0])
ax1 = fig.add_subplot(gs[1,2:7])
ax1_ex = fig.add_subplot(gs[1,1])
ax1_fI = fig.add_subplot(gs[1,0])
ax2 = fig.add_subplot(gs[2,2:7])
ax2_ex = fig.add_subplot(gs[2,1])
ax2_fI = fig.add_subplot(gs[2,0])
line_width = 1
# plot fI curves
ax0_fI = plot_fI(ax0_fI, model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='shift', alt='s', color1='lightgrey', color2='k')
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=line_width,transform=ax0_fI.transAxes, color=color_dict['FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = ax0_fI.add_patch(rec)
rec.set_clip_on(False)
ax1_fI = plot_fI(ax1_fI, model='Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='slope', alt='u', color1='lightgrey', color2='k')
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=line_width,transform=ax1_fI.transAxes, color=color_dict['Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$'], alpha=1, zorder=-1)
rec = ax1_fI.add_patch(rec)
rec.set_clip_on(False)
ax2_fI = plot_fI(ax2_fI, model='Cb stellate', type='g', alt='Leak', color1='lightgrey', color2='k')
rec = plt.Rectangle((-pad_x, -pad_y), 1 + pad_w, 1 + pad_h, fill=False, lw=line_width,transform=ax2_fI.transAxes, color=color_dict['Cb stellate'], alpha=1, zorder=-1)
rec = ax2_fI.add_patch(rec)
rec.set_clip_on(False)
# plot boxplots
boxplot_with_markers(ax0,max_width, alteration='shift')
boxplot_with_markers(ax1,max_width, alteration='slope')
boxplot_with_markers(ax2,max_width, alteration='g')
# plot legend
pos = (0.225, -0.9)
ncol = 6
model_legend(ax2, marker_s_leg, pos, ncol)
# plot rheo across model for example alteration
plot_rheo_alt(ax0_ex,model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k', alteration='shift')
plot_rheo_alt(ax1_ex,model='Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', color1='lightgrey', color2='k',alteration='slope')
plot_rheo_alt(ax2_ex, model='Cb stellate', color1='lightgrey', color2='k', alteration='g')
# label subplots with letters
ax0_fI.text(-0.875, 1.35, string.ascii_uppercase[0], transform=ax0_fI.transAxes, size=10, weight='bold')
ax0_ex.text(-0.8, 1.35, string.ascii_uppercase[1], transform=ax0_ex.transAxes, size=10, weight='bold')
ax0.text(-0.075, 1.35, string.ascii_uppercase[2], transform=ax0.transAxes, size=10, weight='bold')
ax1_fI.text(-0.875, 1.35, string.ascii_uppercase[3], transform=ax1_fI.transAxes,size=10, weight='bold')
ax1_ex.text(-0.8, 1.35, string.ascii_uppercase[4], transform=ax1_ex.transAxes, size=10, weight='bold')
ax1.text(-0.075, 1.35, string.ascii_uppercase[5], transform=ax1.transAxes, size=10, weight='bold')
ax2_fI.text(-0.875, 1.35, string.ascii_uppercase[6], transform=ax2_fI.transAxes,size=10, weight='bold')
ax2_ex.text(-0.8, 1.35, string.ascii_uppercase[7], transform=ax2_ex.transAxes, size=10, weight='bold')
ax2.text(-0.075, 1.35, string.ascii_uppercase[8], transform=ax2.transAxes, size=10, weight='bold')
# save
fig.set_size_inches(cm2inch(20.75,12))
# fig.savefig('./Figures/rheobase_correlation.pdf', dpi=fig.dpi)
fig.savefig('./Figures/rheobase_correlation.jpg', dpi=fig.dpi) #bbox_inches='tight', dpi=fig.dpi # eps # pdf
plt.show()
#%%
# fig, axs = plt.subplots(1,2)
# axs[0] = plot_fI(axs[0] , model='FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', type='shift', alt='s', color1='lightgrey', color2='k')
# plt.show()
#%%
#
#
# cvals = [-2., 2]
# colors = ['lightgrey', 'k']
#
# norm = plt.Normalize(min(cvals), max(cvals))
# tuples = list(zip(map(norm, cvals), colors))
# cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
# colors = cmap(np.linspace(0, 1, 22))
#
# colors2 = [colors[10,:], 'k']
# norm2 = plt.Normalize(min(cvals), max(cvals))
# tuples2 = list(zip(map(norm2, cvals), colors2))
# cmap2 = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples2)
#
# colors3 = [colors[11,:], 'lightgrey']
# norm3 = plt.Normalize(min(cvals), max(cvals))
# tuples3 = list(zip(map(norm3, cvals), colors3))
# cmap3 = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples3)
#
# fig, axs = plt.subplots(1,2)
# start = (0,0)
# end = (1,1)
# axs[0] = rainbowarrow(axs[0], start, end, cmap2, n=50,lw=3)
# start = (0,0)
# end = (-1,-1)
# axs[0] = rainbowarrow(axs[0], start, end, cmap3, n=50,lw=3)
# plt.show()

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 436 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 284 KiB

View File

@ -3,34 +3,30 @@ import matplotlib.pyplot as plt
import pandas as pd
import os
import string
from Figures.plotstyle import sim_style
from plotstyle import plot_style
import seaborn as sns
import scipy.stats as stats
import matplotlib.lines as mlines
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
def Kendall_tau(df):
tau = df.corr(method='kendall')
p = pd.DataFrame(columns=df.columns, index=df.columns)
for col in range((df.columns).shape[0]):
for col2 in range((df.columns).shape[0]):
# print(col, col2)
if col != col2:
_, p.loc[df.columns[col], df.columns[col2]] = stats.kendalltau(
df[df.columns[col]], df[df.columns[col2]], nan_policy='omit')
return tau, p
def correlation_plot(ax, df='AUC', title='', cbar=False):
cbar_ax = fig.add_axes([0.685, 0.44, .15, .01])
cbar_ax = fig.add_axes([0.94, .25, .03, .4])
cbar_ax.spines['left'].set_visible(False)
cbar_ax.spines['bottom'].set_visible(False)
cbar_ax.spines['right'].set_visible(False)
cbar_ax.spines['top'].set_visible(False)
# cbar_ax.axis('off')
cbar_ax.set_xticks([])
cbar_ax.set_yticks([])
if df == 'AUC':
@ -58,7 +54,7 @@ def correlation_plot(ax, df='AUC', title='', cbar=False):
tau = tau.drop(columns='STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', index='RS pyramidal')
# mask to hide upper triangle of matrix
mask = np.zeros_like(tau, dtype=bool)
mask = np.zeros_like(tau, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
np.fill_diagonal(mask, False)
@ -85,20 +81,14 @@ def correlation_plot(ax, df='AUC', title='', cbar=False):
cbar=False, cmap=cmap, cbar_ax=cbar_ax, cbar_kws={"shrink": .52})
else:
res = sns.heatmap(tau, annot=False, mask=mask, center=0, vmax=1, vmin=-1, linewidths=.5, square=True, ax=ax,
cbar=True, cmap=cmap, cbar_ax=cbar_ax,
cbar_kws={"orientation": "horizontal",
"ticks": [-1,-0.5, 0, 0.5, 1]} )
cbar_ax.set_title(r'Kendall $\tau$', y=1.02, loc='center', fontsize=6)
cbar_ax.tick_params(length=3)
for tick in cbar_ax.xaxis.get_major_ticks():
tick.label.set_fontsize(6)
ax.set_title(title, fontsize=8)
cbar=True, cmap=cmap, cbar_ax=cbar_ax, )
cbar_ax.set_title(r'Kendall $\tau$', y=1.05)
ax.set_title(title)
def mutation_plot(ax, model='RS_pramidal'):
def mutation_plot2(ax, model='RS_pramidal'):
models = ['RS_pyramidal', 'RS_inhib', 'FS', 'Cb_stellate', 'Cb_stellate_Kv', 'Cb_stellate_Kv_only', 'STN',
'STN_Kv', 'STN_Kv_only']
model_names = ['RS pyramidal', 'RS inhibitory', 'FS',
model_names = ['RS pyramidal', 'RS inhibitory', 'FS', #'RS pyramidal', 'RS inhibitory', 'FS', 'IB',
'Cb stellate', 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN', 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']
model_display_names = ['RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'Cb stellate',
@ -113,6 +103,7 @@ def mutation_plot(ax, model='RS_pramidal'):
ax_dict['RS_pyramidal'] = (0, 0)
ax_dict['RS_inhib'] = (0, 1)
ax_dict['FS'] = (1, 0)
# ax_dict['IB'] = (1, 1)
ax_dict['Cb_stellate'] = (2, 0)
ax_dict['Cb_stellate_Kv'] = (2, 1)
ax_dict['Cb_stellate_Kv_only'] = (3, 0)
@ -124,6 +115,7 @@ def mutation_plot(ax, model='RS_pramidal'):
ylim_dict['RS_pyramidal'] = (-0.1, 0.3)
ylim_dict['RS_inhib'] = (-0.6, 0.6)
ylim_dict['FS'] = (-0.06, 0.08)
# ylim_dict['IB'] = (-0.2, 0.2)
ylim_dict['Cb_stellate'] = (-0.1, 0.4)
ylim_dict['Cb_stellate_Kv'] = (-0.1, 0.5)
ylim_dict['Cb_stellate_Kv_only'] = (-1, 0.8)
@ -144,32 +136,26 @@ def mutation_plot(ax, model='RS_pramidal'):
mod = models.index(model)
mut_names = AUC.index
ax.plot(rheo.loc[mut_names, model_names[mod]]*1000, AUC.loc[mut_names, model_names[mod]]*100, linestyle='',
ax.plot(rheo.loc[mut_names, model_names[mod]], AUC.loc[mut_names, model_names[mod]], linestyle='',
markeredgecolor='grey', markerfacecolor='grey', marker=Marker_dict[model_display_names[mod]],
markersize=2)
markersize=4) # markeredgecolor=clr_dict[model_names[mod]],markerfacecolor=clr_dict[model_names[mod]],
ax.plot(rheo.loc['wt', model_names[mod]], AUC.loc['wt', model_names[mod]]*100, 'sk')
ax.plot(rheo.loc['wt', model_names[mod]], AUC.loc['wt', model_names[mod]], 'sk')
mut_col = sns.color_palette("pastel")
ax.plot(rheo.loc['V174F', model_names[mod]]*1000, AUC.loc['V174F', model_names[mod]]*100, linestyle='',
ax.plot(rheo.loc['V174F', model_names[mod]], AUC.loc['V174F', model_names[mod]], linestyle='',
markeredgecolor=mut_col[0], markerfacecolor=mut_col[0], marker=Marker_dict[model_display_names[mod]],markersize=4)
ax.plot(rheo.loc['F414C', model_names[mod]]*1000, AUC.loc['F414C', model_names[mod]]*100, linestyle='',
ax.plot(rheo.loc['F414C', model_names[mod]], AUC.loc['F414C', model_names[mod]], linestyle='',
markeredgecolor=mut_col[1], markerfacecolor=mut_col[1], marker=Marker_dict[model_display_names[mod]],markersize=4)
ax.plot(rheo.loc['E283K', model_names[mod]]*1000, AUC.loc['E283K', model_names[mod]]*100, linestyle='',
ax.plot(rheo.loc['E283K', model_names[mod]], AUC.loc['E283K', model_names[mod]], linestyle='',
markeredgecolor=mut_col[2], markerfacecolor=mut_col[2], marker=Marker_dict[model_display_names[mod]],markersize=4)
ax.plot(rheo.loc['V404I', model_names[mod]]*1000, AUC.loc['V404I', model_names[mod]]*100, linestyle='',
ax.plot(rheo.loc['V404I', model_names[mod]], AUC.loc['V404I', model_names[mod]], linestyle='',
markeredgecolor=mut_col[3], markerfacecolor=mut_col[5], marker=Marker_dict[model_display_names[mod]],markersize=4)
ax.set_title(model_display_names[mod], pad=14)
ax.set_xlabel('$\Delta$Rheobase [pA]')
ax.set_ylabel('Normalized $\Delta$AUC (%)')
ax.set_title(model_display_names[mod], fontsize=14)#, color=clr_dict[models[mod]])
ax.set_xlabel('$\Delta$ Rheobase (nA)')
ax.set_ylabel('$AUC_{contrast}$')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# ax.ticklabel_format(axis="y", style="sci", scilimits=(0, 0),useMathText=True)
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
ax.hlines(0, xmin, xmax, colors='lightgrey', linestyles='--')
ax.vlines(0, ymin,ymax, colors='lightgrey', linestyles='--')
return ax
def mutation_legend(ax, marker_s_leg, pos, ncol):
@ -183,18 +169,19 @@ def mutation_legend(ax, marker_s_leg, pos, ncol):
E283K = mlines.Line2D([], [], color=colors[2], marker=Markers[2], markersize=marker_s_leg, linestyle='None', label='E283K')
V404I = mlines.Line2D([], [], color=colors[5], marker=Markers[3], markersize=marker_s_leg, linestyle='None',
label='V404I')
WT = mlines.Line2D([], [], color='k', marker='s', markersize=marker_s_leg+2, linestyle='None', label='Wild type')
WT = mlines.Line2D([], [], color='k', marker='s', markersize=marker_s_leg+5, linestyle='None', label='Wild type')
ax.legend(handles=[WT, V174F, F414C, E283K, V404I], loc='center', bbox_to_anchor=pos, ncol=ncol, frameon=False)
sim_style()
plot_style()
# plot setup
fig = plt.figure()
gs0 = fig.add_gridspec(1, 6, wspace=-0.2)
gsl = gs0[0:3].subgridspec(3, 3, wspace=0.9, hspace=0.8)
gsr = gs0[4:6].subgridspec(6, 1, wspace=0.6, hspace=1)
fig = plt.figure(figsize=(18,12))
gs0 = fig.add_gridspec(1, 5, wspace=3.5)
gsl = gs0[0:3].subgridspec(3, 3, wspace=0.6, hspace=0.6)
gsr = gs0[3:5].subgridspec(2, 1, wspace=0.6, hspace=0.8)
ax00 = fig.add_subplot(gsl[0,0])
ax01 = fig.add_subplot(gsl[0,1])
@ -206,42 +193,38 @@ ax20 = fig.add_subplot(gsl[2,0])
ax21 = fig.add_subplot(gsl[2,1])
ax22 = fig.add_subplot(gsl[2,2])
axr0 = fig.add_subplot(gsr[0:2,0])
axr1 = fig.add_subplot(gsr[4:,0])
axr0 = fig.add_subplot(gsr[0,0])
axr1 = fig.add_subplot(gsr[1,0])
# plot mutations in each model
ax00 = mutation_plot(ax00, model='RS_pyramidal')
ax01 = mutation_plot(ax01, model='RS_inhib')
ax02 = mutation_plot(ax02, model='FS')
ax10 = mutation_plot(ax10, model='Cb_stellate')
ax11 = mutation_plot(ax11, model='Cb_stellate_Kv')
ax12 = mutation_plot(ax12, model='Cb_stellate_Kv_only')
ax20 = mutation_plot(ax20, model='STN')
ax21 = mutation_plot(ax21, model='STN_Kv')
ax22 = mutation_plot(ax22, model='STN_Kv_only')
ax00 = mutation_plot2(ax00, model='RS_pyramidal')
ax01 = mutation_plot2(ax01, model='RS_inhib')
ax02 = mutation_plot2(ax02, model='FS')
ax10 = mutation_plot2(ax10, model='Cb_stellate')
ax11 = mutation_plot2(ax11, model='Cb_stellate_Kv')
ax12 = mutation_plot2(ax12, model='Cb_stellate_Kv_only')
ax20 = mutation_plot2(ax20, model='STN')
ax21 = mutation_plot2(ax21, model='STN_Kv')
ax22 = mutation_plot2(ax22, model='STN_Kv_only')
marker_s_leg = 4
pos = (0.425, -0.7)
pos = (0.25, -0.45)
ncol = 5
mutation_legend(ax21, marker_s_leg, pos, ncol)
# plot correlation matrices
correlation_plot(axr1,df = 'AUC', title='Normalized $\Delta$AUC', cbar=False)
correlation_plot(axr0,df = 'rheo', title='$\Delta$Rheobase', cbar=True)
correlation_plot(axr1,df = 'AUC', title='$AUC_{contrast}$', cbar=False)
correlation_plot(axr0,df = 'rheo', title='$\Delta rheobase$', cbar=True)
# add subplot labels
axs = [ax00, ax01,ax02, ax10, ax11, ax12, ax20, ax21, ax22]
j=0
for i in range(0,9):
# axs[i].text(-0.48, 1.175, string.ascii_uppercase[i], transform=axs[i].transAxes, size=10, weight='bold')
axs[i].text(-0.625, 1.25, string.ascii_uppercase[i], transform=axs[i].transAxes, size=10, weight='bold')
axs[i].text(-0.28, 1.08, string.ascii_uppercase[i], transform=axs[i].transAxes, size=16, weight='bold')
j +=1
axr0.text(-0.77, 1.1, string.ascii_uppercase[j], transform=axr0.transAxes, size=10, weight='bold')
axr1.text(-0.77, 1.1, string.ascii_uppercase[j+1], transform=axr1.transAxes, size=10, weight='bold')
axr0.text(-0.38, 1.2, string.ascii_uppercase[j], transform=axr0.transAxes, size=16, weight='bold')
axr1.text(-0.38, 1.2, string.ascii_uppercase[j+1], transform=axr1.transAxes, size=16, weight='bold')
# save
fig.set_size_inches(cm2inch(22.2,15))
fig.savefig('./Figures/simulation_model_comparison.pdf', dpi=fig.dpi) #eps
# fig.savefig('./Figures/simulation_model_comparison.png', dpi=fig.dpi) #eps
fig.savefig('./Figures/simulation_model_comparison.pdf', bbox_inches='tight')
plt.show()

View File

@ -1,275 +0,0 @@
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
import string
from Figures.plotstyle import sim_style
import seaborn as sns
import scipy.stats as stats
import matplotlib.lines as mlines
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
def Kendall_tau(df):
tau = df.corr(method='kendall')
p = pd.DataFrame(columns=df.columns, index=df.columns)
for col in range((df.columns).shape[0]):
for col2 in range((df.columns).shape[0]):
if col != col2:
_, p.loc[df.columns[col], df.columns[col2]] = stats.kendalltau(
df[df.columns[col]], df[df.columns[col2]], nan_policy='omit')
return tau, p
def correlation_plot(ax, df='AUC', title='', cbar=False):
# cbar_ax = fig.add_axes([0.685, 0.44, .15, .01])
cbar_ax = fig.add_axes([0.685, 0.48, .15, .01])
cbar_ax.spines['left'].set_visible(False)
cbar_ax.spines['bottom'].set_visible(False)
cbar_ax.spines['right'].set_visible(False)
cbar_ax.spines['top'].set_visible(False)
cbar_ax.set_xticks([])
cbar_ax.set_yticks([])
if df == 'AUC':
df = pd.read_csv(os.path.join('./Figures/Data/sim_mut_AUC.csv'), index_col='Unnamed: 0')
elif df == 'rheo':
df = pd.read_csv(os.path.join('./Figures/Data/sim_mut_rheo.csv'), index_col='Unnamed: 0')
# array for names
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# models = ['RS_pyramidal', 'RS_inhib', 'FS', 'Cb_stellate', 'Cb_stellate_Kv', 'Cb_stellate_Kv_only', 'STN',
# 'STN_Kv', 'STN_Kv_only']
# model_names = ['RS pyramidal', 'RS inhibitory', 'FS', 'Cb stellate',
# 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN',
# 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']
# model_letter_names = ['H', 'E', 'G', 'A', 'F', 'J', 'L', 'I', 'K']
models =['Cb_stellate','RS_inhib','Cb_stellate_Kv','FS', 'RS_pyramidal','STN_Kv', 'Cb_stellate_Kv_only','STN_Kv_only', 'STN']
model_names = ['Cb stellate','RS inhibitory', 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'FS',
'RS pyramidal', 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$','STN']
model_letter_names = ['A', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']
col_dict = {}
for m in range(len(models)):
col_dict[model_names[m]] = model_letter_names[m]
df.rename(columns=col_dict, inplace=True)
df = df[model_letter_names]
# calculate correlation matrix
tau, p = Kendall_tau(df)
# tau = tau.drop(columns='STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', index='RS pyramidal')
# mask to hide upper triangle of matrix
mask = np.zeros_like(tau, dtype=bool)
mask[np.triu_indices_from(mask)] = True
np.fill_diagonal(mask, False)
# models and renaming of tau
# models = ['RS pyramidal', 'RS inhibitory', 'FS', 'Cb stellate',
# 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN',
# 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']
# model_names = ['RS pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'RS inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'Cb stellate', 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
# 'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN',
# 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']
# # model_letter_names = ['Model H', 'Model E', 'Model G', 'Model A', 'Model F', 'Model J', 'Model L', 'Model I', 'Model K']
# model_letter_names = ['H', 'E', 'G', 'A', 'F', 'J', 'L', 'I', 'K']
models = ['Cb_stellate', 'RS_inhib', 'Cb_stellate_Kv', 'FS', 'RS_pyramidal', 'STN_Kv', 'Cb_stellate_Kv_only',
'STN_Kv_only', 'STN']
model_names = ['Cb stellate', 'RS inhibitory', 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'FS',
'RS pyramidal', 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN']
model_letter_names = ['A', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']
col_dict = {}
for m in range(len(models)):
col_dict[model_names[m]] = model_letter_names[m]
tau.rename(columns=col_dict, index=col_dict, inplace=True)
tau = tau[model_letter_names]
# plotting with or without colorbar
if cbar==False:
res = sns.heatmap(tau, annot=False, mask=mask, center=0, vmax=1, vmin=-1, linewidths=.5, square=True, ax=ax,
cbar=False, cmap=cmap, cbar_ax=cbar_ax, cbar_kws={"shrink": .52})
else:
res = sns.heatmap(tau, annot=False, mask=mask, center=0, vmax=1, vmin=-1, linewidths=.5, square=True, ax=ax,
cbar=True, cmap=cmap, cbar_ax=cbar_ax,
cbar_kws={"orientation": "horizontal",
"ticks": [-1,-0.5, 0, 0.5, 1]} )
cbar_ax.set_title(r'Kendall $\tau$', y=1.02, loc='center', fontsize=6)
cbar_ax.tick_params(length=3)
for tick in cbar_ax.xaxis.get_major_ticks():
tick.label.set_fontsize(6)
ax.set_title(title, fontsize=8)
ax.set_xlabel("Model")
ax.set_ylabel("Model")
def mutation_plot(ax, model='RS_pyramidal'):
models = ['RS_pyramidal', 'RS_inhib', 'FS', 'Cb_stellate', 'Cb_stellate_Kv', 'Cb_stellate_Kv_only', 'STN',
'STN_Kv', 'STN_Kv_only']
model_names = ['RS pyramidal', 'RS inhibitory', 'FS',
'Cb stellate', 'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN', 'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']
model_display_names = ['RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'Cb stellate',
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$',
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN',
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$', 'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$']
model_letter_names = ['Model H',
'Model E',
'Model G', 'Model A',
'Model F',
'Model J', 'Model L',
'Model I',
'Model K']
col_dict = {}
for m in range(len(models)):
col_dict[models[m]] = model_display_names[m]
ax_dict = {}
ax_dict['RS_pyramidal'] = (0, 0)
ax_dict['RS_inhib'] = (0, 1)
ax_dict['FS'] = (1, 0)
ax_dict['Cb_stellate'] = (2, 0)
ax_dict['Cb_stellate_Kv'] = (2, 1)
ax_dict['Cb_stellate_Kv_only'] = (3, 0)
ax_dict['STN'] = (3, 1)
ax_dict['STN_Kv'] = (4, 0)
ax_dict['STN_Kv_only'] = (4, 1)
ylim_dict = {}
ylim_dict['RS_pyramidal'] = (-0.1, 0.3)
ylim_dict['RS_inhib'] = (-0.6, 0.6)
ylim_dict['FS'] = (-0.06, 0.08)
ylim_dict['Cb_stellate'] = (-0.1, 0.4)
ylim_dict['Cb_stellate_Kv'] = (-0.1, 0.5)
ylim_dict['Cb_stellate_Kv_only'] = (-1, 0.8)
ylim_dict['STN'] = (-0.01, 0.015)
ylim_dict['STN_Kv'] = (-0.4, 0.6)
ylim_dict['STN_Kv_only'] = (-0.03, 0.3)
Marker_dict = {'Cb stellate': 'o', 'RS Inhibitory': 'o', 'FS': 'o', 'RS Pyramidal': "^",
'RS Inhibitory +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': "^",
'Cb stellate +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': "^",
'FS +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': "D",
'RS Pyramidal +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': "D",
'STN +$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': "D",
'Cb stellate $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': "s",
'STN $\Delta$$\mathrm{K}_{\mathrm{V}}\mathrm{1.1}$': "s", 'STN': "s"}
AUC = pd.read_csv(os.path.join('./Figures/Data/sim_mut_AUC.csv'), index_col='Unnamed: 0')
rheo = pd.read_csv(os.path.join('./Figures/Data/sim_mut_rheo.csv'), index_col='Unnamed: 0')
mod = models.index(model)
mut_names = AUC.index
ax.plot(rheo.loc[mut_names, model_names[mod]]*1000, AUC.loc[mut_names, model_names[mod]]*100, linestyle='',
markeredgecolor='grey', markerfacecolor='grey', marker=Marker_dict[model_display_names[mod]],
markersize=2)
ax.plot(rheo.loc['wt', model_names[mod]], AUC.loc['wt', model_names[mod]]*100, 'sk')
mut_col = sns.color_palette("pastel")
ax.plot(rheo.loc['V174F', model_names[mod]]*1000, AUC.loc['V174F', model_names[mod]]*100, linestyle='',
markeredgecolor=mut_col[0], markerfacecolor=mut_col[0], marker=Marker_dict[model_display_names[mod]],markersize=4)
ax.plot(rheo.loc['F414C', model_names[mod]]*1000, AUC.loc['F414C', model_names[mod]]*100, linestyle='',
markeredgecolor=mut_col[1], markerfacecolor=mut_col[1], marker=Marker_dict[model_display_names[mod]],markersize=4)
ax.plot(rheo.loc['E283K', model_names[mod]]*1000, AUC.loc['E283K', model_names[mod]]*100, linestyle='',
markeredgecolor=mut_col[2], markerfacecolor=mut_col[2], marker=Marker_dict[model_display_names[mod]],markersize=4)
ax.plot(rheo.loc['V404I', model_names[mod]]*1000, AUC.loc['V404I', model_names[mod]]*100, linestyle='',
markeredgecolor=mut_col[3], markerfacecolor=mut_col[5], marker=Marker_dict[model_display_names[mod]],markersize=4)
ax.set_title(model_letter_names[mod], pad=14)
ax.set_xlabel('$\Delta$Rheobase [pA]')
ax.set_ylabel('Normalized $\Delta$AUC (%)')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# ax.ticklabel_format(axis="y", style="sci", scilimits=(0, 0),useMathText=True)
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
ax.hlines(0, xmin, xmax, colors='lightgrey', linestyles='--')
ax.vlines(0, ymin,ymax, colors='lightgrey', linestyles='--')
return ax
def mutation_legend(ax, marker_s_leg, pos, ncol):
colors = sns.color_palette("pastel")
Markers = ["o", "o", "o", "o"]
V174F = mlines.Line2D([], [], color=colors[0], marker=Markers[0], markersize=marker_s_leg, linestyle='None',
label='V174F')
F414C = mlines.Line2D([], [], color=colors[1], marker=Markers[1], markersize=marker_s_leg, linestyle='None',
label='F414C')
E283K = mlines.Line2D([], [], color=colors[2], marker=Markers[2], markersize=marker_s_leg, linestyle='None', label='E283K')
V404I = mlines.Line2D([], [], color=colors[5], marker=Markers[3], markersize=marker_s_leg, linestyle='None',
label='V404I')
WT = mlines.Line2D([], [], color='k', marker='s', markersize=marker_s_leg+2, linestyle='None', label='Wild type')
ax.legend(handles=[WT, V174F, F414C, E283K, V404I], loc='center', bbox_to_anchor=pos, ncol=ncol, frameon=False)
sim_style()
# plot setup
fig = plt.figure()
gs0 = fig.add_gridspec(1, 6, wspace=-0.2)
gsl = gs0[0:3].subgridspec(3, 3, wspace=0.9, hspace=0.8)
gsr = gs0[4:6].subgridspec(7, 1, wspace=0.6, hspace=3.8)
ax00 = fig.add_subplot(gsl[1,1]) #model H
ax01 = fig.add_subplot(gsl[0,1]) # model E
ax02 = fig.add_subplot(gsl[1,0]) # model G
ax10 = fig.add_subplot(gsl[0,0]) # model A
ax11 = fig.add_subplot(gsl[0,2]) # model F
ax12 = fig.add_subplot(gsl[2,0]) # model J
ax20 = fig.add_subplot(gsl[2,2]) # model L
ax21 = fig.add_subplot(gsl[1,2]) # model I
ax22 = fig.add_subplot(gsl[2,1]) # model K
axr0 = fig.add_subplot(gsr[0:3,0])
axr1 = fig.add_subplot(gsr[4:,0])
# plot mutations in each model
ax00 = mutation_plot(ax00, model='RS_pyramidal')
ax01 = mutation_plot(ax01, model='RS_inhib')
ax02 = mutation_plot(ax02, model='FS')
ax10 = mutation_plot(ax10, model='Cb_stellate')
ax11 = mutation_plot(ax11, model='Cb_stellate_Kv')
ax12 = mutation_plot(ax12, model='Cb_stellate_Kv_only')
ax20 = mutation_plot(ax20, model='STN')
ax21 = mutation_plot(ax21, model='STN_Kv')
ax22 = mutation_plot(ax22, model='STN_Kv_only')
marker_s_leg = 4
pos = (0.425, -0.7)
ncol = 5
mutation_legend(ax22, marker_s_leg, pos, ncol)
# plot correlation matrices
correlation_plot(axr1,df = 'AUC', title='Normalized $\Delta$AUC', cbar=False)
correlation_plot(axr0,df = 'rheo', title='$\Delta$Rheobase', cbar=True)
# add subplot labels
# axs = [ax00, ax01,ax02, ax10, ax11, ax12, ax20, ax21, ax22]
axs = [ax10, ax01, ax11, ax02, ax00, ax21, ax12, ax22, ax20]
j=0
for i in range(0,9):
# axs[i].text(-0.48, 1.175, string.ascii_uppercase[i], transform=axs[i].transAxes, size=10, weight='bold')
axs[i].text(-0.625, 1.25, string.ascii_uppercase[i], transform=axs[i].transAxes, size=10, weight='bold')
j +=1
axr0.text(-0.27, 1.075, string.ascii_uppercase[j], transform=axr0.transAxes, size=10, weight='bold')
axr1.text(-0.27, 1.075, string.ascii_uppercase[j+1], transform=axr1.transAxes, size=10, weight='bold')
# save
fig.set_size_inches(cm2inch(22.2,15))
# fig.savefig('./Figures/simulation_model_comparison.pdf', dpi=fig.dpi) #eps
fig.savefig('./Figures/simulation_model_comparison.jpg', dpi=fig.dpi) #eps
plt.show()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 713 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 870 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 928 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 271 KiB

Some files were not shown because too many files have changed in this diff Show More