{load_file("nrngui.hoc")}

begintemplate VSigmoidRate

public A, k, d, f, inv, Asol, ksol, form, parms, save_data, restore, type
public kstset, parm2vec, vec2parm, chk

proc init() {
	parms(1, .1, -40)
}

proc kstset() {
	parms(1, .1, -40)
	$o1.set_f($2, type(), new Vector(3))
	parm2vec($o1.parm($2))
}	

proc chk() {
	if ($o3.x[0] < 0) { $o3.x[0] = 0 }
	if ($1 == 1) if ($2 == 0) $o3.x[0] = 1
}

proc parm2vec() {
	$o1.resize(0)
	$o1.append(A, k, d)
}

proc vec2parm() {
	A = $o1.x[0]
	k = $o1.x[1]
	d = $o1.x[2]
}

func type() { return 4 }

proc parms() {
	A = $1  k = $2  d=$3
}

proc save_data() {
	sprint($s2, "%g %g %g", A, k, d)
	$o1.save($s2)
}
proc restore() {
	parms(fscan(), fscan(), fscan())
}

proc form() {
	if ($2 == 1) {
		sprint($s1, "A%s/(1 + exp(-k%s*(d%s - v)))", $s3, $s3, $s3)
	}else{
		sprint($s1, "%.4g/(1 + exp(%.4g*(%.4g - v)))", A, -k, d)
	}
}

func f() {local x
    x = k*($1 - d)
    if (x > 700) { return 0 }
    return A/(1 + exp(x))
}

func inv() {local x
	if ($1 >= A) {
		x = 700
	}else if ($1 <= 0){
		x = -700
	}else{
		x = log(A/$1 - 1)
	}
	if (k == 0) {
		return 1e9
	}
	return d + x/k
}
	
func Asol() {
	return $2*2
}

func ksol() {local x
	x = $1 - d
	if (abs(x) < 1e-6) { x = 1e-6 }
	if ($2 < 0) { $2 = 1e-6 } else if ($2 > A) {$2 = 1 - 1e-6}
	x = log(A/$2 - 1)/x
	return x
}

endtemplate VSigmoidRate
