<commit_before># Author <NAME>
# Wed Mar 18 17:51:51 GMT 2009

import logging
import numpy as np
import math

import sys
import os

from neuron import h

import matplotlib
from ecellControl.ecellManager import EcellManager
backend = 'Agg'
matplotlib.use(backend)
import matplotlib.pyplot as plt

from neuronControl import nrnSim, synapse 
from neuronControl.stimul import Stimul 

from neuronvisio.manager import Manager
from sumatra.external.NeuroTools import parameters

import tables 
from extref import ExtRef 

    
def build_vecs_to_plot(var, secs, anyRefs):
    """Create the dictionary of section->vectors to plot"""
    vecs_to_plot = {}
    for secName in secs:
        for ref in anyRefs:
            if secName == ref.sec_name:
                if ref.vecs.has_key(var):
                    vecs_to_plot[secName] = ref.vecs[var]
    return vecs_to_plot

def kir_gkbar(gkbar):
    for sec in h.allsec():
        for seg in sec:
            for mech in seg:
                if mech.name() == 'kir':
                    mech.gkbar = gkbar


def iClamptest(delay=10, duration=250, amplititude=0.248):
    """# Quick Iclamp test to check the current dynamics"""
    iclamp = h.IClamp(h.MSP_Cell[0].soma(0.5))
    iclamp.delay = delay
    iclamp.dur = duration
    iclamp.amp = amplititude

def advance_neuron(tmp_tstop):
    """
    Advance Neuron till tmp_tstop.
       
    Parameters
    ----------
    tmp_stop: Temporary tstop. It has to be expressed in milliseconds.
    """
    nrnSim.run(tmp_tstop)
    
def advance_ecell(spine, delta_t):
    """
    Advance ecell simulator in `spine` of `delta_t`.
    
    Paramters:
    ----------
    tmp_tstop: Temporary tstop. It has to be expressed in seconds
    """
    current_time = spine.ecellMan.ses.getCurrentTime()
    len_current_time = len (spine.ecellMan.loggers['ca'].getData()[:,0])
    print ("Ecell current time: %s in %s. Advancing of: %s seconds.\
    Current time len: %s") %(current_time, spine.id, delta_t, len_current_time)
    spine.ecellMan.ses.run(delta_t)
    
    

def synch_simulators(tmp_tstop, stim_spines_id,
                     dtNeuron,
                     delta_calcium_sampling, 
                     weight_baseline):
    """
    Calculate the synapse weight, using the calcium in the spine_heads 
    as input.
    
    Synch the two simulators using the following steps:
    1. Calculate the calcium concentration in the spines head in 
    NEURON and set this value in ecell.
    2. Advance ecell for the specified_delta
    3. Update the electric weight of the synapses in NEURON
    """
    print ("Synchronizing sims till [ms] %s") %tmp_tstop
    
    while h.t < tmp_tstop:
        h.fadvance() # run Neuron for step
        #for every ms in NEURON we update the ecellMan
        if np.round(h.t, decimals = 4) % delta_calcium_sampling == 0:
            for spine_id in stim_spines_id :
                spine = nrnSim.spines[spine_id]
                sync_calcium(spine, dtNeuron, delta_calcium_sampling)
                advance_ecell(spine, delta_calcium_sampling / 1e3)
                spine.ecellMan.ca_in['k'] = 0
                update_synape_weight(spine, weight_baseline)

def sync_calcium(spine, dtNeuron, delta_calcium_sampling):
    """"
    Calculate the flux of the calcium in the spine_head and synch 
    it with ecell. 
    """
    if hasattr(spine, 'ecellMan'):
        
        k_ca_flux = get_calcium_flux(dtNeuron, 
                                     delta_calcium_sampling, 
                                     spine)
        # Unit conversion in update_calcium
        spine.update_calcium(k_ca_flux)

def get_calcium_flux(dtNeuron, delta_calcium_sampling, spine):
    """
    Retrieving the calcium in the interval. end is always -1 because is
    the last timepoint available, start is when the interval has begun
    """
    start_index = -int(dtNeuron / delta_calcium_sampling)
    # Getting the calcium value
    vec_spine_head_cai = manager.get_vector(spine.head, 'cai')
    vec_spine_head_cali = manager.get_vector(spine.head, 'cali')
    
    head_cai = vec_spine_head_cai.x[start_index]
    head_cali = vec_spine_head_cali.x[start_index]
    electrical_ca_start = head_cai + head_cali
    
    head_cai = vec_spine_head_cai.x[-1]
    head_cali = vec_spine_head_cali.x[-1]
    electrical_ca_end = head_cai + head_cali
    electrical_diff = electrical_ca_end - electrical_ca_start
    print "Len vecs: %s start_idx: %s" %(len(head_cali), start_index)
    print "Electrical calcium start: %s end: %s difference: %s" %(electrical_ca_start,
                                                                  electrical_ca_end,
                                                                  electrical_diff)
    # Calculating the flux
    k_calcium_flux = electrical_diff / delta_calcium_sampling
    
    return k_calcium_flux
    

def update_synape_weight(spine, baseline):
    """
    Update the electrical weight's synapses.
    
    spine : the spine where the weight should be updated
    baseline : the equilibrium concentration of AMPAR-P which we use as reference
    and  put equal to one.
    """    
    
    # Updating the AMPA synapses
    for synapse in spine.synapses:
        if synapse.chan_type == 'ampa':                       
        # Retrieve the value of the weight.<commit_msg>Getting the len from the vector. Wrong variable.<commit_after># Author <NAME>
# Wed Mar 18 17:51:51 GMT 2009

import logging
import numpy as np
import math

import sys
import os

from neuron import h

import matplotlib
from ecellControl.ecellManager import EcellManager
backend = 'Agg'
matplotlib.use(backend)
import matplotlib.pyplot as plt

from neuronControl import nrnSim, synapse 
from neuronControl.stimul import Stimul 

from neuronvisio.manager import Manager
from sumatra.external.NeuroTools import parameters

import tables 
from extref import ExtRef 

    
def build_vecs_to_plot(var, secs, anyRefs):
    """Create the dictionary of section->vectors to plot"""
    vecs_to_plot = {}
    for secName in secs:
        for ref in anyRefs:
            if secName == ref.sec_name:
                if ref.vecs.has_key(var):
                    vecs_to_plot[secName] = ref.vecs[var]
    return vecs_to_plot

def kir_gkbar(gkbar):
    for sec in h.allsec():
        for seg in sec:
            for mech in seg:
                if mech.name() == 'kir':
                    mech.gkbar = gkbar


def iClamptest(delay=10, duration=250, amplititude=0.248):
    """# Quick Iclamp test to check the current dynamics"""
    iclamp = h.IClamp(h.MSP_Cell[0].soma(0.5))
    iclamp.delay = delay
    iclamp.dur = duration
    iclamp.amp = amplititude

def advance_neuron(tmp_tstop):
    """
    Advance Neuron till tmp_tstop.
       
    Parameters
    ----------
    tmp_stop: Temporary tstop. It has to be expressed in milliseconds.
    """
    nrnSim.run(tmp_tstop)
    
def advance_ecell(spine, delta_t):
    """
    Advance ecell simulator in `spine` of `delta_t`.
    
    Paramters:
    ----------
    tmp_tstop: Temporary tstop. It has to be expressed in seconds
    """
    current_time = spine.ecellMan.ses.getCurrentTime()
    len_current_time = len (spine.ecellMan.loggers['ca'].getData()[:,0])
    print ("Ecell current time: %s in %s. Advancing of: %s seconds.\
    Current time len: %s") %(current_time, spine.id, delta_t, len_current_time)
    spine.ecellMan.ses.run(delta_t)
    
    

def synch_simulators(tmp_tstop, stim_spines_id,
                     dtNeuron,
                     delta_calcium_sampling, 
                     weight_baseline):
    """
    Calculate the synapse weight, using the calcium in the spine_heads 
    as input.
    
    Synch the two simulators using the following steps:
    1. Calculate the calcium concentration in the spines head in 
    NEURON and set this value in ecell.
    2. Advance ecell for the specified_delta
    3. Update the electric weight of the synapses in NEURON
    """
    print ("Synchronizing sims till [ms] %s") %tmp_tstop
    
    while h.t < tmp_tstop:
        h.fadvance() # run Neuron for step
        #for every ms in NEURON we update the ecellMan
        if np.round(h.t, decimals = 4) % delta_calcium_sampling == 0:
            for spine_id in stim_spines_id :
                spine = nrnSim.spines[spine_id]
                sync_calcium(spine, dtNeuron, delta_calcium_sampling)
                advance_ecell(spine, delta_calcium_sampling / 1e3)
                spine.ecellMan.ca_in['k'] = 0
                update_synape_weight(spine, weight_baseline)

def sync_calcium(spine, dtNeuron, delta_calcium_sampling):
    """"
    Calculate the flux of the calcium in the spine_head and synch 
    it with ecell. 
    """
    if hasattr(spine, 'ecellMan'):
        
        k_ca_flux = get_calcium_flux(dtNeuron, 
                                     delta_calcium_sampling, 
                                     spine)
        # Unit conversion in update_calcium
        spine.update_calcium(k_ca_flux)

def get_calcium_flux(dtNeuron, delta_calcium_sampling, spine):
    """
    Retrieving the calcium in the interval. end is always -1 because is
    the last timepoint available, start is when the interval has begun
    """
    start_index = -int(dtNeuron / delta_calcium_sampling)
    # Getting the calcium value
    vec_spine_head_cai = manager.get_vector(spine.head, 'cai')
    vec_spine_head_cali = manager.get_vector(spine.head, 'cali')
    
    head_cai = vec_spine_head_cai.x[start_index]
    head_cali = vec_spine_head_cali.x[start_index]
    electrical_ca_start = head_cai + head_cali
    
    head_cai = vec_spine_head_cai.x[-1]
    head_cali = vec_spine_head_cali.x[-1]
    electrical_ca_end = head_cai + head_cali
    electrical_diff = electrical_ca_end - electrical_ca_start
    print "Len vecs: %s start_idx: %s" %(len(vec_spine_head_cali), start_index)
    print "Electrical calcium start: %s end: %s difference: %s" %(electrical_ca_start,
                                                                  electrical_ca_end,
                                                                  electrical_diff)
    # Calculating the flux
    k_calcium_flux = electrical_diff / delta_calcium_sampling
    
    return k_calcium_flux
    

def update_synape_weight(spine, baseline):
    """
    Update the electrical weight's synapses.
    
    spine : the spine where the weight should be updated
    baseline : the equilibrium concentration of AMPAR-P which we use as reference
    and  put equal to one.
    """    
    
    # Updating the AMPA synapses
    for synapse in spine.synapses:
        if synapse.chan_type == 'ampa':                       
        # Retrieve the value of the weight.
{'fraction_non_alphanumeric': 0.0787974978993558, 'fraction_numerical': 0.006722061432172533, 'mean_word_length': 2.366436203645506, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '70841', 'n_tokens_mistral': 3577, 'n_tokens_neox': 3360, 'n_words': 932}