# Morpho_Funcs
# Chris Knowlton Dec 2020
# functions for dealing with arbitrary morphologies of DA neurons

# 35 microns

from neuron import h
import numpy as np

def add_AIS(nrnobj, length, dfsoma, diam):
		
	h.pop_section() # distance calculations can create issues when there are many neurons in memory
	placed = 0
	for s in nrnobj.all:
		h.distance(0,0.5,sec=nrnobj.soma)
		start_dist = h.distance(0,sec=s)
		if start_dist > 1e9 and not h.issection('.*ais.*',sec=s):
			print( s, 'error, sections not connected')
			quit()
		if start_dist < dfsoma+nrnobj.soma.L/2 and start_dist+s.L > dfsoma+nrnobj.soma.L/2 and not placed:
			#nrnais = h.Section(name='ais',cell=nrnobj)
			placed = 1
			loc_on_s = (dfsoma+nrnobj.soma.L/2-start_dist)/s.L
			while s.nseg < s.L/25 and s.nseg < 9:
				s.nseg += 2 # minimize errors # ideal solution would be to disconnect the section, then re-generate 2 sections
			nrnobj.ais.connect(s(loc_on_s),0)
			#nrnobj.all.append(nrnobj.ais)
			#nrnobj.excitozone.append(nrnobj.ais)
			#print nrnobj.excitozone
			nrnobj.ais.L= length
			nrnobj.ais.diam = diam # per Meza et al 0.9 is the mean assuming cylinder [diam = area/(L*pi)]
			break # for now just quit after first valid location
			
		
		
	
	#h.pop_section() # probably not required
	return nrnobj
