"""
example5 -- large networks

demonstrates default value, named times

requires matplotlib

has delays, so must use fast_xpp_integrator, so OSX and linux only
"""

from snnet import *

# set the maximum delay
fast_xpp_integrator.delay = 10

def simulation():
    # name defaults... this will allow parameter sweeps over these values,
    # and it is also more readable than magic numbers
    default_value('vsyne', 0)
    default_value('vsyni', -80)
    default_value('gsyne', .07)
    default_value('gsyni', .005)
    default_value('nume', 30)
    default_value('numi', 30)
    default_value('boost', 10)
    default_value('t1', 200)
    default_value('t2', 300)

    # create two groups of cells
    ecells = neurons('hh_syn.snnet', 'nume')
    icells = neurons('hh_syn2.snnet', 'numi')    

    # create a list of synapses, identical except with varying delays (1, 2, 3, 4, or 5)
    synapses = [ion_synapse('gsyne', 'vsyne', 's', delay=d) for d in [1, 2, 3, 4, 5]]
    
    # ecells have an excitatory effect on the icells because vsyn is high
    # icells have an inhibitory effect of the ecells because vsyn is low
    ecells.connect(ecells, p=.5, synapse=synapses)
    icells.connect(ecells, p=.3, synapse=ion_synapse('gsyne', 'vsyne', 's'))
    ecells.connect(icells, p=.5, synapse=ion_synapse('gsyni', 'vsyni', 's'))    
    
    # apply a current to the ecells
    old_iapp = ecells.iapp
    ecells.iapp = 'boost [20%]'
    
    # run for t1 ms
    advance('t1')    
    name_time('end_stim')
    
    # restore the original current
    ecells.iapp = old_iapp
    
    # run for another t2 ms
    advance('t2')
    name_time('end_simulation')
    
data = run(simulation, integrator=fast_xpp_integrator)

# raster diagram
raster(data, shading=[[0, 'end_stim']])
savefig('example5_raster.pdf')
close()

# histogram of ISIs, values between 0 and 30, 1 ms bins
isis = data.isi(cells='ecells', time_range=('end_stim', 'end_simulation'), combine_cells=True)
hist(isis, range(0, 30, 1))
title('Distribution of interspike intervals for ecells after stimulus period')
xlabel('ISI (ms)')
ylabel('Count')
savefig('example5_isi.pdf')
close()
