load_file("stdlib.hoc")
load_file("ObliquePath.hoc")

objref cvode
cvode = new CVode()
cvode.active(0)


create axon[2]
objref SD, AXON, SA, Basal, Trunk, AIS, Trial
objref LM, RAD, RADt, LUC, PSA, PSB, ORI
create soma[1], apical[1], basal[1]
objref pl[150], opl[150]

objref netlist, s, ampasyn, f1, DEND, sapamp, somavec, sampvec
strdef  str2



dt = 0.025
tstop = 1650// 1050 //1sec (first 50ms not counted)
steps_per_ms=40

Rm_soma=80000
Rm_end=400
Rm_dend = Rm_soma
Rm_axon = Rm_soma
rm_xhalf = 225
rm_slope = 30


/*Rm_soma=155000
 Rm_end=95000
 Rm_dend = Rm_soma
 Rm_axon = Rm_soma
 */

Ra_soma=150
Ra_end=150
Ra_axon = Ra_soma
Ra_xhalf = 210
Ra_slope = 50


c_m       = 1
cmsoma    = c_m
cmdend    = c_m*1.8
cmaxon    = c_m

Vrest = -65
v_init = -65
celsius = 34.0




// uncomment/call find_epsp_amplitudes whenever u change any of the following parameters ..

//gna=0.008//0.005//0.005//0.0066//0.0033
//gkdr =0.006// 0.00167//0.000267//0.00167//0.058

gna=0.02
gkdr=0.0014
//gna=0
//gkdr=0

gexFac = 0.9

AISFactor=5
epsp_amp = 0.0025  //mV



objref ampa_filename
ampa_filename = new String()
gh=0//µS set to the value for which you'll be running withH.hoc and WithHfast.hoc
ghmax=20  //35  //40  //50  //60  //95
xhalf=250  //350  //250  //350
slopegrad=50//5


sprint(ampa_filename.s,"g_dist_withgh0_epspAmp_%f_calculated.txt",epsp_amp)


/********************************************************************/


Ek = -90
Ena = 55
Eh = -30


/********************************************************************/
//radial distance calculation

somax=2.497
somay=-13.006
somaz=11.12
double distances[200]

func raddist() {
	distn0=distance(0)
	distances[0]=0
	sum=0
    
	for i=1,n3d()-1 {
		xx=(x3d(i)-x3d(i-1))*(x3d(i)-x3d(i-1))
		yy=(y3d(i)-y3d(i-1))*(y3d(i)-y3d(i-1))
		zz=(z3d(i)-z3d(i-1))*(z3d(i)-z3d(i-1))
		sum=sum+sqrt(xx+yy+zz)
		distances[i]=sum
	}
    
	xval=$1
    
    // Amoung the various pt3d's find which one matches the distance of
    //  x closely
    
	distn=distance(xval)
	match=distn-distn0
	matchptdist=100000
	for i=0,n3d()-1 {
		matptdist=(match-distances[i])*(match-distances[i])
		if(matchptdist>matptdist){
			matchptdist=matptdist
			matchi=i
		}
	}
    
	//print "Match for ", x, " is ", matchi, " XDIST ", match, " MATCH ", distances[matchi], " ERROR ", sqrt(matchptdist)
    
    
    // Find the distance of the closely matched point to the somatic
    // centroid and use that as the distance for this BPAP measurement
    
	xx=(x3d(matchi)-somax)*(x3d(matchi)-somax)
	yy=(y3d(matchi)-somay)*(y3d(matchi)-somay)
	zz=(z3d(matchi)-somaz)*(z3d(matchi)-somaz)
	return sqrt(xx+yy+zz)
}

/********************************************************************/

proc update_init(){
	finitialize(v_init)
	fcurrent()
    forall {
        for (x){
            if (ismembrane("hd")||ismembrane("nas")||ismembrane("na3")||ismembrane("nax")) {
                e_pas(x)=v(x)+(i_hd(x)+ina(x)+ik(x))/g_pas(x)
            } else {
                e_pas(x)=v(x)
            }
        }
    }
}
/********************************************************************/

/**********************************************************************/
// Passive Conductances

proc setpassive(){
    forall {
        insert pas
        e_pas = v_init
        Ra=Ra_soma
    }
    forsec SD{		// For somato-dendritic compartments
        cm=cmdend
        g_pas=1/Rm_dend
    }
    forsec "soma" {
        cm = cmsoma
        g_pas=1/Rm_soma
    }
    forsec Trunk {
        for (x) {
            rdist=raddist(x)
            rm = Rm_soma + (Rm_end - Rm_soma)/(1.0 + exp((rm_xhalf-rdist)/rm_slope))

            Ra = Ra_soma + (Ra_end - Ra_soma)/(1.0 + exp((Ra_xhalf-rdist)/Ra_slope))
            g_pas(x)=1/rm
        }
    }
    
    for i=0,plcount {
        seccount=0
        forsec pl[i] {
            if(!seccount){
                trunk_pas=g_pas(1)
                seccount=seccount+1
            } else {
                g_pas=trunk_pas
                seccount=seccount+1
            }
            //print secname()
        }
    }
    
}
/**********************************************************************/
// Active Conductances



proc setactive () {
    
	forall{
        insert na3
        gbar_na3= gna
        insert kdr
        gkdrbar_kdr=gkdr
        
        
        insert hd
		ghdbar_hd=gh vhalfl_hd=-82
        tfactor_hd=1
	}
    
	forsec AXON{
        gbar_na3= 0
        gkdrbar_kdr=0
        ghdbar_hd=0
        
    }
    
    
    forsec "apical"{
        insert nas
        gbar_nas = gna //has a slow "s" factor
        
        gbar_na3 = 0 //since this was added forall, remove from apical section
        
    }
    
    forsec AIS {
        gbar_na3= 0
        insert nax
        gbar_nax = gna*AISFactor
        
        gkdrbar_kdr=gkdr
        ghdbar_hd=0
	}
    
    forall{
        if(ismembrane("hd")){
            ehd_hd=-30
        }
        
        if(ismembrane("na3") || ismembrane("nas") || ismembrane("nax")){
            ena=55
        }
        
        if(ismembrane("kdr")){
            ek=-90
        }
        
        
        
    }
    
    
	
}


/********************************************************************/
proc gh_gradient(){
	
	
	forsec Trunk {	// Trunk
        
		for (x) {
			xdist=raddist(x)
			

            ghdbar_hd(x) = gh*(1+ghmax/(1+exp(-(xdist-xhalf)/slopegrad)))
            
            
			if (xdist > 100){
				if (xdist>300) {
					ndist=300
				} else { // 100 <= xdist <= 300
					ndist=xdist
				}
				vhalfl_hd(x)=-82-8*(ndist-100)/200
			} else {	// xdist < 100
				vhalfl_hd(x)=-82
			}
            
		}
	}
    
	for i=0,plcount { // Apical obliques
    	seccount=0
    	forsec pl[i] {
        	if(!seccount){	// The first section is the trunk
            	trunk_h=ghdbar_hd(1)
				trunk_vhalf=vhalfl_hd(1)
				seccount=seccount+1
        	} else {
				
            	ghdbar_hd=trunk_h
				vhalfl_hd=trunk_vhalf
				seccount=seccount+1
        	}
        	//print secname()
    	}
	}
    
	forsec "soma" {
        ghdbar_hd=gh vhalfl_hd=-82
	}
    
	forsec Basal {
        ghdbar_hd=gh vhalfl_hd=-82
	}
    
	forall if (ismembrane("hd") ) ehd_hd = Eh
        
        
        
        
        }


/**********************************************************************/
proc load_3dcell() {
    
    // $s1 filename
    
	forall delete_section()
	xopen($s1)
    
	access soma[2] //define origin for distance calculation
	distance()
    
    
	SD = new SectionList() //Somato-dendritic section
	SA = new SectionList() // Somato-axonic section
	Trunk = new SectionList() //Trunk
	Basal = new SectionList() //Basal
    Trial = new SectionList()
    
	forsec "soma" {
		SD.append()
		SA.append()
	}
    
	forsec "basal" {
		SD.append()
		Basal.append()
	}
    
	forsec "apical"{
		SD.append()
		SA.append()
	}
    
	// Trunk.
    
	soma[0]	   Trunk.append()
	apical[0]  Trunk.append()
	apical[4]  Trunk.append()
	apical[6]  Trunk.append()
	apical[14] Trunk.append()
	apical[15] Trunk.append()
	apical[16] Trunk.append()
	apical[22] Trunk.append()
	apical[23] Trunk.append()
	apical[25] Trunk.append()
	apical[26] Trunk.append()
	apical[27] Trunk.append()
	apical[41] Trunk.append()
	apical[42] Trunk.append()
	apical[46] Trunk.append()
	apical[48] Trunk.append()
	apical[56] Trunk.append()
	apical[58] Trunk.append()
	apical[60] Trunk.append()
	apical[62] Trunk.append()
	apical[64] Trunk.append()
	apical[65] Trunk.append()
	apical[69] Trunk.append()
	apical[71] Trunk.append()
	apical[81] Trunk.append()
	apical[83] Trunk.append()
	apical[95] Trunk.append()
	apical[103] Trunk.append()
	apical[104] Trunk.append()
    
    
    soma[0] Trial.append()
	apical[58] Trial.append() // 196 µm
	apical[64] Trial.append() // 242 µm
	apical[69] Trial.append() // 300 µm
	apical[103] Trial.append() // 420 µm
    
    load_file("oblique-paths.hoc")
    
    setpassive() //before setting the nseg
    // The lambda constraint
    totcomp=0
    forall{
        nseg=int((L/(0.1*lambda_f(100))+0.9)/2)*2+1
        totcomp=totcomp+nseg
    }
    print "totcomp = ",totcomp
    
    
    
	init_cell() //calls setpassive()
    
    DEND = new SectionList()
    forsec "apical"{
        xdist=raddist(1)
        if(xdist<300 && xdist > 50){
            DEND.append()
        }
    }
    
    
    
	
}

/**********************************************************************/
// For cell number n123 on the DSArchive, converted with CVAPP to give
// HOC file, the following definition holds. This is the same as Poirazi et
// al. have used in Neuron, 2003. The argument is that the subtree seems
// so long to be a dendrite, and the cell does not have a specific axon.
// There is a catch, though, if the morphology is closely scanned, then
// basal dendrites would branch from these axonal segments - which
// may be fine given the amount of ambiguity one has while tracing!

proc addaxon() {
    
	AXON = new SectionList()
    AIS = new SectionList() // Axonal initial segment
    
	for i = 30,34 basal[i] {
		AXON.append()
		Basal.remove()
	}
    
	for i = 18,22 basal[i] {
		AXON.append()
        AIS.append()
		Basal.remove()
	}
    
	forsec AXON {
		e_pas=v_init
		g_pas = 1/Rm_axon
		Ra=Ra_axon
		cm=cmaxon
	}
}

/********************************************************************/





proc init_cell() {
	setpassive()
	addaxon()
	setactive()
	gh_gradient() //sets the gh gradient
	
	access soma[2]	// Reinitializing distance origin
	distance()
    
	finitialize(v_init)
	fcurrent()
    forall {
        for (x) {
            if (ismembrane("hd")||ismembrane("nas")||ismembrane("na3")||ismembrane("nax")) {
                e_pas(x)=v(x)+(i_hd(x)+ina(x)+ik(x))/g_pas(x)
            } else {
                e_pas(x)=v(x)
            }
        }
    }
}


/********************************************************************/


load_3dcell("n123.hoc") //calls setpassive()

/*****************************************************************/

proc find_epsp_amplitudes() { //always call this function whenever any parameter is changed to ensure correct gex values are used
	nmdaamparat=0.25
	atrise=2.0
	atau=3
	ntrise=5
	ntau=50
    
    netlist=new List()
    
    
	tstop=40
    Gstart=1e-5
    Gend=1
    
    wopen(ampa_filename.s)
    
    
    soma[2] s = new NetStim(0.5)
    s.interval=1   // ms (mean) time between spikes
    s.number=1     // (average) number of spikes
    s.start=2   // ms (mean) start time of first spike
    s.noise=0      // range 0 to 1. Fractional randomness.
    
    access soma[2]
    distance()
    
    forsec DEND {
        
        for (x) {
            if (x!=0 && x!=1){
                xdist=raddist(x)
                // fprint("%f\n", xdist)
                
                G=Gstart
                //            ampasyn=new AMPA(x)
                //            ampasyn.TRise=atrise
                //            ampasyn.tau=atau
                
                print secname(), " ", x, " ", xdist //distance(x)
                ampasyn=new Exp2Syn(x)
                ampasyn.e=0
                ampasyn.tau1=0.1
                ampasyn.tau2=5
                
                netlist.append(new NetCon(s,ampasyn,1,0,0))
                
                
                
                while(G<=Gend){
                    //                ampasyn.gmax=G
                    
                    netlist.remove_all()
                    
                    netlist.append(new NetCon(s,ampasyn,1,0,G))
                    
                    
                    finitialize(v_init)
                    fcurrent()
                    
                    MAX=-70
                    
                    while (t <tstop){
                        fadvance()
                        if(soma[2].v(0.5)>MAX) {
                            MAX=soma[2].v(0.5)
                        }
                        
                    }
                    
                    if(MAX>(Vrest+epsp_amp)) {
                        fprint("%f\n", G)
                        print G ," ", MAX
                        //update_init()
                        break
                    }
                    //print G ," ", MAX
                    G=G+1e-5
                }
                if(G>=Gend){
                    print secname(), " ", x, " ", distance(x), "-1"
                    //  fprint("-1\n")
                }
            }
        }
    }
    wopen()
    
}


find_epsp_amplitudes()

/*****************************************************************/

///****************************************************************/

objref g_ampa,f1,f2

g_ampa= new Vector(220)

f1=new File()
f1.ropen(ampa_filename.s)
g_ampa.scanf(f1) //reading into vector
f1.close()

f2=new File()
f2.wopen("Calculated_EpspAmp.txt")

proc calc_epsp_amplitudes() {

netlist=new List()


tstop=40
soma[2] s = new NetStim(0.5)
s.interval=1   // ms (mean) time between spikes
s.number=1     // (average) number of spikes
s.start=2   // ms (mean) start time of first spike
s.noise=0      // range 0 to 1. Fractional randomness.



access soma[2]
distance()

count = 0
forsec DEND {

for (x) {
if (x!=0 && x!=1){
xdist=raddist(x)
// fprint("%f\n", xdist)
G=g_ampa.x[count]/gexFac
ampasyn=new Exp2Syn(x)
ampasyn.e=0
ampasyn.tau1=0.1
ampasyn.tau2=5

netlist.append(new NetCon(s,ampasyn,1,0,0))
netlist.remove_all()

netlist.append(new NetCon(s,ampasyn,1,0,G))

finitialize(v_init)
fcurrent()

MAX=-80

while (t <tstop){
fadvance()
if(soma[2].v(0.5)>MAX) {
MAX=soma[2].v(0.5)
}

}


f2.printf("%f\n", (MAX-Vrest))
// print xdist ," ", MAX-Vrest
//  print xdist

count += 1
} //end of if()
}   //end for(x)
}	//end forsec DEND

print count
wopen()

}

//calc_epsp_amplitudes()

///****************************************************************/