"""
init.py

Starting script to run NetPyNE-based cortical network model to study epilepsy.


Usage:
    python init.py # Run simulation, optionally plot a raster


MPI usage:
    mpiexec -n 4 nrniv -python -mpi init.py


Contributors: salvadordura@gmail.com
"""

import matplotlib; matplotlib.use('Agg')  # to avoid graphics error in servers

from netpyne import sim
import random as random
import time
random.seed(1072)
import os
import pickle
#import math

# read parameter files
cfg, netParams = sim.readCmdLineArgs(simConfigDefault='cfg_net.py', netParamsDefault='netParams_net.py')

# create network, run simulation and analyze output
#sim.createSimulateAnalyze(netParams, cfg)

sim.pc.timeout(0)
sim.initialize(netParams, cfg)  # create network object and set cfg and net params
sim.net.createPops()                  # instantiate network populations
sim.net.createCells()                 # instantiate network cells based on defined populations
sim.net.defineCellShapes()
sim.net.connectCells()                # create connections between cells based on params
sim.net.addStims()                    # add external stimulation to cells (IClamps etc)
sim.net.addRxD()                      # add reaction-diffusion (RxD)
sim.setupRecording()             # setup variables to record for each cell (spikes, V traces, etc)

for cell in sim.net.cells:
    for sec in cell.secs.values():
        sec['vinit'] = random.uniform(-90.0,+10.0)
    cell.initV()


# Interval
#sim.runSimIntervalSaving(100000)
#sim.pc.barrier()
#sim.gatherData()
#sim.pc.barrier()
#sim.saveData()
#sim.pc.barrier()
#sim.analysis.plotData()



# Normal
#sim.simulate()
#sim.pc.barrier()
#sim.analyze() 
#sim.pc.barrier()


# Nodes 
# sim.runSim()
sim.runSimWithIntervalFunc(1000000, sim.saveDataInNodes)
print("File names\n")

sim.pc.barrier()
print("A. sim rank is "+str(sim.rank)+"\n")
if sim.rank==0:
    os.rename('./output','./node_interval_results')
sim.pc.barrier()
sim.saveDataInNodes()
sim.pc.barrier()

if sim.rank==0:
    os.rename('./output','./data_net_data')
print("B. sim rank is "+str(sim.rank)+"\n")

sim.pc.barrier()
sim.gatherDataFromFiles()
sim.pc.barrier()

print("C. sim rank is "+str(sim.rank)+"\n")
if sim.rank==0:
    os.rename('./data_net_data','./output')
    x = {'simData':sim.allSimData}
    #print(x['simData'])
    with open("./output/data_net_data.pkl", 'wb') as fileObj:
        pickle.dump(x,fileObj)

sim.pc.barrier()
sim.analysis.plotData()
print("D. sim.rank is "+str(sim.rank)+"\n")

#if sim.rank!=0:
#    time.sleep(20)

quit()