Exemplo n.º 1
0
def main(argv):
    integrationFilename = 'results/integrationINapIKFig10_10_INapIKLowThreshold_2-1Sync.npz'
    figFilename = 'figures/fig10_10c_INapIKLowThreshold_2-1Sync.eps'
    fontsize = 20
    marker = "o"

    integrationRes = np.load(integrationFilename)

    spikeIndices = getPeakIndices(v=integrationRes["ysDCTrainPulses"][0, :])
    spikeTimes = integrationRes["timesDCTrainPulses"][spikeIndices]

    pulseTimes = np.arange(start=integrationRes["tPulse"],
                           stop=spikeTimes[-1],
                           step=integrationRes["Ts"])

    pulsePhases = np.empty(pulseTimes.shape)
    for i in range(len(pulsePhases)):
        precedingSpikeIndex = np.nonzero(spikeTimes < pulseTimes[i])[0][-1]
        pulsePhases[i] = pulseTimes[i] - spikeTimes[precedingSpikeIndex]

    plt.plot(np.arange(start=1, stop=len(pulseTimes) + 1, step=1),
             pulsePhases,
             marker=marker)
    plt.xlabel("pulse number, n")
    plt.ylabel(r'phase, $\theta_n$')
    plt.grid()

    # for i in range(len(pulsePhases)):
    #     annotation = r"$\theta_{%d}$"%(i+1)
    #     plt.annotate(annotation, xy=(i+1, pulsePhases[i]), fontsize=fontsize)

    plt.savefig(figFilename)
    plt.show()
    pdb.set_trace()
def main(argv):
    fontsize = 20
    marker = "o"
    integrationFilename = 'results/integrationINapIKFig10_10_INapIKLowThreshold_belowUnstable.npz'
    prcFilename = 'results/prcINapIKFig10_4RightPanel_INapIKLowThreshold.npz'
    figFilename = 'figures/fig10_10d_INapIKLowThreshold_belowUnstable.eps'

    prcRes = np.load(prcFilename)
    integrationRes = np.load(integrationFilename)

    poincarePhaseMap = (prcRes["phases"]+prcRes["prc"]+integrationRes["Ts"])%prcRes["T"]

    plt.plot(prcRes["phases"], poincarePhaseMap, marker="o")
    plt.plot(prcRes["phases"], prcRes["phases"], marker="o")
    plt.xlabel(r"$\theta_n$")
    plt.ylabel(r"$\theta_{n+1}$")
    # plt.xlim((0, .9))
    # plt.ylim((0, .9))
    spikeIndices = getPeakIndices(v=integrationRes["ysDCTrainPulses"][0,:])
    spikeTimes = integrationRes["timesDCTrainPulses"][spikeIndices]

    pulseTimes = np.arange(start=integrationRes["tPulse"], stop=spikeTimes[-1], step=integrationRes["Ts"])

    pulsePhases = np.empty(pulseTimes.shape)
    for i in range(len(pulsePhases)):
        precedingSpikeIndex = np.nonzero(spikeTimes<pulseTimes[i])[0][-1]
        pulsePhases[i] = pulseTimes[i]-spikeTimes[precedingSpikeIndex]

    for i in range(len(pulsePhases)):
        annotation = r"$\theta_{%d}$"%(i+1)
        plt.annotate(annotation, xy=(pulsePhases[i], pulsePhases[i]), fontsize=fontsize)

    plt.savefig(figFilename)
    plt.show()
    pdb.set_trace()
def main(argv):
    resultsFilename = 'results/integrationINapIKFig10_10.npz'
    figFilename = 'figures/fig10_10c.eps'
    nPhases = 7
    fontsize = 20
    marker = "o"

    results = np.load(resultsFilename)

    pulseTimes = results["offset"]+\
                  np.arange(start=0, stop=nPhases, step=1)*results["Ts"]

    spikeIndices = getPeakIndices(v=results["ys"][0, :])
    spikeTimes = results["times"][spikeIndices]

    pulsePhases = np.empty(pulseTimes.shape)
    for i in range(len(pulsePhases)):
        precedingSpikeIndex = np.nonzero(spikeTimes < pulseTimes[i])[0][-1]
        pulsePhases[i] = pulseTimes[i] - spikeTimes[precedingSpikeIndex]

    plt.plot(np.arange(start=1, stop=nPhases + 1, step=1),
             pulsePhases,
             marker=marker)
    plt.xlabel("pulse number, n")
    plt.ylabel(r'phase, $\theta_n$')
    plt.grid()

    for i in range(len(pulsePhases)):
        annotation = r"$\theta_{%d}$" % (i + 1)
        plt.annotate(annotation, xy=(i + 1, pulsePhases[i]), fontsize=fontsize)

    plt.savefig(figFilename)
    plt.show()
    pdb.set_trace()
Exemplo n.º 4
0
def main(argv):
    resultsFilename = 'results/integrationINapIKFig10_1.npz'
    aFigFilename = 'figures/fig10_1a.eps'

    results = np.load(resultsFilename)
    times = results['times']
    ys = results['ys']
    spikeIndices = getPeakIndices(v=ys[0, :])
    spikeTimes = times[spikeIndices]

    print("Spike times:")
    print(spikeTimes)

    times = np.delete(times, np.arange(0, spikeIndices[0]))
    spikeTimes = spikeTimes - times[0]
    times = times - times[0]
    ys = np.delete(ys, np.arange(0, spikeIndices[0]), axis=1)
    plt.plot(times, ys[0, :])
    for spikeTime in spikeTimes:
        plt.axvline(x=spikeTime, color="r")
    plt.xlabel("Time (ms)")
    plt.ylabel("Membrane Potential (mV)")
    plt.savefig(aFigFilename)
    plt.show()

    pdb.set_trace()
def main(argv):
    i0 = 35
    numberOfPhaseMarks = 8
    annotationGap = 0.02
    initialTransientLength = 10
    resultsFilename = 'results/integrationINapIKFig10_1_INapIKLowThreshold.npz'
    aFigFilename = 'figures/fig10_1b_INapIKLowThreshold.eps'

    results = np.load(resultsFilename)
    times = results['times']
    ys = results['ys']
    transientIndices = np.nonzero(times < initialTransientLength)[0]
    pdb.set_trace()
    times = np.delete(arr=times, obj=transientIndices)
    ys = np.delete(arr=ys, obj=transientIndices, axis=1)
    spikeIndices = getPeakIndices(v=ys[0, :])
    spikeTimes = times[spikeIndices]

    times = np.delete(times, np.arange(0, spikeIndices[0]))
    times = times - times[0]
    ys = np.delete(ys, np.arange(0, spikeIndices[0]), axis=1)
    spikeIndices = spikeIndices - spikeIndices[0]
    spikeTimes = spikeTimes - spikeTimes[0]
    period = spikeTimes[1] - spikeTimes[0]
    phases = times % period
    phasesToPlot = np.arange(0, period, period / numberOfPhaseMarks)
    indicesBtwFirstAndSecondSpike = np.arange(0, spikeIndices[1])
    phasesToSearch = phases[indicesBtwFirstAndSecondSpike]

    indicesPhasesToPlot = np.empty(len(phasesToPlot), dtype=np.int64)
    for i in xrange(len(phasesToPlot)):
        phaseToPlot = phasesToPlot[i]
        indicesPhasesToPlot[i] = np.argmin(np.abs(phasesToSearch -
                                                  phaseToPlot))

    plt.figure()
    plotLowThresholdINapIKVectorField(i=i0)
    plt.plot(ys[0, :], ys[1, :], label="limit cycle attractor")
    plt.plot(ys[0, indicesPhasesToPlot], ys[1, indicesPhasesToPlot], 'ro')
    plt.annotate("0,T",
                 xy=ys[:, 0],
                 xytext=ys[:, indicesPhasesToPlot[0]] + annotationGap,
                 color="red",
                 size=14)
    for i in xrange(1, len(indicesPhasesToPlot)):
        plt.annotate("%d/%dT" % (i, numberOfPhaseMarks),
                     xy=ys[:, indicesPhasesToPlot[i]],
                     xytext=ys[:, indicesPhasesToPlot[i]] + annotationGap,
                     color="red",
                     size=14)
    plt.grid()
    plt.legend(loc="upper left")
    plt.xlabel('Voltage (mv)')
    plt.ylabel('K activation variable, n')
    plt.ylim((-0.1, 0.8))
    plt.savefig(aFigFilename)
    plt.show()

    pdb.set_trace()
Exemplo n.º 6
0
def main(argv):
    if len(argv) != 3:
        sys.exit("Usage: %s <phase index> <number of phases>" % argv[0])
    indexPhaseX0 = int(argv[1])
    numberOfPhasesForX0 = int(argv[2])
    i0 = 10
    factorsDeltaT = 1.0 / 32.0 * np.arange(1, 6)
    # factorsDeltaT = 1.0/32.0*np.arange(5, 6)
    nInitialConditions = 10
    maxDeltaX0 = 1.0
    maxDeltaX1 = 0.01
    dt = 1e-5
    integrationFilename = "results/integrationINapIKFig10_1.npz"
    isochronFilename = \
     "results/isochronINapIKFig10_1Phase%02dOver%d.npz"%(indexPhaseX0,
                                                          numberOfPhasesForX0)

    results = np.load(integrationFilename)
    times = results["times"]
    ys = results["ys"]
    spikeIndices = getPeakIndices(v=ys[0, :])
    spikeTimes = times[spikeIndices]

    times = np.delete(times, np.arange(0, spikeIndices[0]))
    times = times - times[0]
    ys = np.delete(ys, np.arange(0, spikeIndices[0]), axis=1)
    spikeIndices = spikeIndices - spikeIndices[0]
    spikeTimes = spikeTimes - spikeTimes[0]
    period = spikeTimes[1] - spikeTimes[0]
    phases = times % period
    phasesForX0 = np.arange(0, period, period / numberOfPhasesForX0)
    indicesBtwFirstAndSecondSpike = np.arange(0, spikeIndices[1])
    phasesToSearch = phases[indicesBtwFirstAndSecondSpike]

    indicesPhasesForX0 = np.empty(len(phasesForX0), dtype=np.int64)
    for i in xrange(len(phasesForX0)):
        phaseForX0 = phasesForX0[i]
        indicesPhasesForX0[i] = np.argmin(np.abs(phasesToSearch - phaseForX0))
    x0 = ys[:, indicesPhasesForX0[indexPhaseX0]]

    def i(t):
        return (i0)

    model = INapIKModel.getHighThresholdInstance(i=i)
    isochron = computeIsochron(model,
                               x0=x0,
                               deltaTs=factorsDeltaT * period,
                               nInitialConditions=nInitialConditions,
                               maxDeltaX0=maxDeltaX0,
                               maxDeltaX1=maxDeltaX1,
                               dt=dt)
    np.savez(isochronFilename, isochron=isochron)
Exemplo n.º 7
0
def main(argv):
    integrationFilename = "results/integrationINapIKFig10_10_matching1-1Sync.npz"
    figFilename = "figures/fig10_10b_matching1-1Sync.eps"
    nPhases = 6
    ylim = (-.1, .7)
    fontsize = 20

    integrationRes = np.load(integrationFilename)

    plt.plot(integrationRes["ysDCTrainPulses"][0, :],
             integrationRes["ysDCTrainPulses"][1, :],
             label="train pulses")
    plt.plot(integrationRes["ysDC"][0, :],
             integrationRes["ysDC"][1, :],
             label="DC")
    plotHighThresholdINapIKVectorField(i=integrationRes["i0"])
    plt.xlabel("Membrane Potential (V)")
    plt.ylabel("K activation variable, n")
    plt.ylim(ylim)

    spikeIndices = getPeakIndices(v=integrationRes["ysDCTrainPulses"][0, :])
    spikeTimes = integrationRes["timesDCTrainPulses"][spikeIndices]

    pulseTimes = np.arange(start=integrationRes["tPulse"],
                           stop=spikeTimes[-1],
                           step=integrationRes["Ts"])

    pulseIndices = np.empty(pulseTimes.shape)
    for i in range(len(pulseIndices)):
        pulseIndices[i] = np.argmin(
            np.abs(pulseTimes[i] - integrationRes["timesDCTrainPulses"]))

    for i in range(len(pulseIndices)):
        annotation = r"$\theta_{%d}$" % (i + 1)
        plt.annotate(annotation,
                     xy=(integrationRes["ysDCTrainPulses"][0, pulseIndices[i]],
                         integrationRes["ysDCTrainPulses"][1,
                                                           pulseIndices[i]]),
                     fontsize=fontsize)
    plt.savefig(figFilename)
    plt.show()
    pdb.set_trace()
def main(argv):
    nPhases = 6
    fontsize = 20
    marker = "o"
    integrationFilename = 'results/integrationINapIKFig10_10.npz'
    prcFilename = 'results/prcINapIKFig10_4RightPanel.npz'
    figFilename = 'figures/fig10_10d.eps'

    prcRes = np.load(prcFilename)
    integrationRes = np.load(integrationFilename)

    poincarePhaseMap = (prcRes["phases"] + prcRes["prc"] +
                        integrationRes["Ts"]) % prcRes["T"]

    plt.plot(prcRes["phases"], poincarePhaseMap)
    plt.plot(prcRes["phases"], prcRes["phases"])
    plt.xlabel(r"$\theta_n$")
    plt.ylabel(r"$\theta_{n+1}$")
    pulseTimes = integrationRes["offset"]+\
                  np.arange(start=0, stop=nPhases, step=1)*integrationRes["Ts"]

    spikeIndices = getPeakIndices(v=integrationRes["ys"][0, :])
    spikeTimes = integrationRes["times"][spikeIndices]

    pulsePhases = np.empty(pulseTimes.shape)
    for i in range(len(pulsePhases)):
        precedingSpikeIndex = np.nonzero(spikeTimes < pulseTimes[i])[0][-1]
        pulsePhases[i] = pulseTimes[i] - spikeTimes[precedingSpikeIndex]

    for i in range(len(pulsePhases)):
        annotation = r"$\theta_{%d}$" % (i + 1)
        plt.annotate(annotation,
                     xy=(pulsePhases[i], pulsePhases[i]),
                     fontsize=fontsize)

    plt.savefig(figFilename)
    plt.show()
    pdb.set_trace()
def main(argv):
    indexPhaseX0 = 1
    numberOfPhasesForX0 = 40
    i0 = 10
    nSPLUNew = 1000
    vMin = -90
    vMax = 15
    nMin = -0.1
    nMax = 0.8
    integrationFilename = "results/integrationINapIKFig10_1.npz"
    isochronFilename = \
     "results/isochronINapIKFig10_1Phase%02dOver%d.npz"%(indexPhaseX0,
                                                          numberOfPhasesForX0)
    figFilename = \
     "figures/isochronINapIKFig10_1Phase%02dOver%d.eps"%(indexPhaseX0,
                                                          numberOfPhasesForX0)

    results = np.load(integrationFilename)
    times = results["times"]
    ys = results["ys"]
    spikeIndices = getPeakIndices(v=ys[0, :])
    spikeTimes = times[spikeIndices]

    times = np.delete(times, np.arange(0, spikeIndices[0]))
    times = times - times[0]
    ys = np.delete(ys, np.arange(0, spikeIndices[0]), axis=1)
    spikeIndices = spikeIndices - spikeIndices[0]
    spikeTimes = spikeTimes - spikeTimes[0]
    period = spikeTimes[1] - spikeTimes[0]
    phases = times % period
    phasesForX0 = np.arange(0, period, period / numberOfPhasesForX0)
    indicesBtwFirstAndSecondSpike = np.arange(0, spikeIndices[1])
    phasesToSearch = phases[indicesBtwFirstAndSecondSpike]

    indicesPhasesForX0 = np.empty(len(phasesForX0), dtype=np.int64)
    for i in xrange(len(phasesForX0)):
        phaseForX0 = phasesForX0[i]
        indicesPhasesForX0[i] = np.argmin(np.abs(phasesToSearch - phaseForX0))
    x0 = ys[:, indicesPhasesForX0[indexPhaseX0]]

    results = np.load(isochronFilename)
    isochron = results["isochron"]

    validIndices = np.logical_and(
        np.logical_and(vMin <= isochron[0, :], isochron[0, :] <= vMax),
        np.logical_and(nMin <= isochron[1, :],
                       isochron[1, :] <= nMax)).nonzero()[0]
    isochron = isochron[:, validIndices]

    sortedIsochron = sortIsochron(isochron=isochron)

    splTck, splU = splprep(sortedIsochron, s=5.0)
    splUNew = np.linspace(splU.min(), splU.max(), nSPLUNew)
    splXInter, splYInter = splev(splUNew, splTck, der=0)

    # plt.figure()
    # plotHighThresholdINapIKVectorField(i=i0)
    plt.plot(ys[0, :], ys[1, :], label="limit cycle attractor")
    # pdb.set_trace()

    plt.annotate("x0", xy=x0, color="red", size=14)

    def i(t):
        return (i0)

    model = INapIKModel.getHighThresholdInstance(i=i)
    plotINapIKNullclines(i=i0,
                         eL=model._eL,
                         gL=model._gL,
                         eNa=model._eNa,
                         gNa=model._gNa,
                         eK=model._eK,
                         gK=model._gK,
                         mVOneHalf=model._mVOneHalf,
                         mK=model._mK,
                         nVOneHalf=model._nVOneHalf,
                         nK=model._nK)
    plt.plot(isochron[0, :],
             isochron[1, :],
             marker="o",
             color="red",
             linestyle="None")
    plt.plot(splXInter, splYInter, color="gray", linestyle="solid")
    plt.legend(loc="upper left")
    plt.xlabel("Voltage (mv)")
    plt.ylabel("K activation variable, n")
    plt.xlim((-90, 15))
    plt.ylim((-0.1, 0.8))
    plt.savefig(figFilename)
    plt.show()
    pdb.set_trace()
def main(argv):
    # if len(argv)!=3:
    # sys.exit("Usage: %s <phase index> <number of phases>"%argv[0])
    # indexPhaseX0 = int(argv[1])
    # numberOfPhasesForX0 = int(argv[2])
    indexPhaseX0 = 5
    numberOfPhasesForX0 = 40
    i0 = 10
    # factorsDeltaT = 1.0/12.0*np.arange(1, 11)
    factorsDeltaT = 1.0 / 36.0 * np.arange(5, 6)
    # factorsDeltaT = 1.0/32.0*np.arange(1, 6)
    # factorsDeltaT = 1.0/32.0*np.arange(5, 6)
    nInitialConditions = 40
    # maxDeltaX0 = 1.0
    # maxDeltaX1 = 0.01
    maxDistance = 0.02
    dt = 1e-5
    vMin = -50.0
    vMax = -20.0
    tol = 1e-3
    addIntersectNullclines = False
    integrationFilename = "results/integrationINapIKFig10_1.npz"
    isochronFilename = \
     "results/isochronINapIKFig10_1Phase%02dOver%d.npz"%(indexPhaseX0,
                                                          numberOfPhasesForX0)

    results = np.load(integrationFilename)
    times = results["times"]
    ys = results["ys"]
    spikeIndices = getPeakIndices(v=ys[0, :])
    spikeTimes = times[spikeIndices]

    times = np.delete(times, np.arange(0, spikeIndices[0]))
    times = times - times[0]
    ys = np.delete(ys, np.arange(0, spikeIndices[0]), axis=1)
    spikeIndices = spikeIndices - spikeIndices[0]
    spikeTimes = spikeTimes - spikeTimes[0]
    period = spikeTimes[1] - spikeTimes[0]
    phases = times % period
    phasesForX0 = np.arange(0, period, period / numberOfPhasesForX0)
    indicesBtwFirstAndSecondSpike = np.arange(0, spikeIndices[1])
    phasesToSearch = phases[indicesBtwFirstAndSecondSpike]

    indicesPhasesForX0 = np.empty(len(phasesForX0), dtype=np.int64)
    for i in xrange(len(phasesForX0)):
        phaseForX0 = phasesForX0[i]
        indicesPhasesForX0[i] = np.argmin(np.abs(phasesToSearch - phaseForX0))
    x0 = ys[:, indicesPhasesForX0[indexPhaseX0]]

    def i(t):
        return (i0)

    model = INapIKModel.getHighThresholdInstance(i=i)
    print("Processing x0=(%.2f,%.4f)" % (x0[0], x0[1]))
    plt.annotate("x0", xy=x0, color="red", size=14)
    #     isochron = computeIsochron(model, x0=x0, deltaTs=factorsDeltaT*period, nInitialConditions=nInitialConditions, maxDeltaX0=maxDeltaX0, maxDeltaX1=maxDeltaX1, dt=dt)
    isochron = computeIsochron(model,
                               x0=x0,
                               deltaTs=factorsDeltaT * period,
                               nInitialConditions=nInitialConditions,
                               maxDistance=maxDistance,
                               dt=dt)
    if addIntersectNullclines:
        xIntersectionNullclines = model.getIntersectionOfNullclines(vMin=vMin,
                                                                    vMax=vMax,
                                                                    tol=tol)
        isochron = np.append(xIntersectionNullclines, isochron, 1)
    np.savez(isochronFilename, isochron=isochron)
Exemplo n.º 11
0
def main(argv):
    resultsFilename = "results/integrationINapIKFig10_10_INapIKLowThreshold_belowUnstable.npz"
    v0 = -60.00
    t0 = 0.0
    tf = 800.0
    dt = 1e-3
    nTSteps = int(round((tf - t0) / dt))
    times = np.empty(nTSteps + 1)
    i0 = 50
    nTransientSpikes = 6
    pulsePhase = 0.44
    pulseStrength = 10.0
    pulseWidthFactor = 100
    Ts = 3.403

    pulseWidth = pulseWidthFactor * dt

    def iDC(t):
        return (i0)

    iNapIKModelDC = INapIKModel.getLowThresholdInstance()
    iNapIKModelDC.setI(i=iDC)
    n0DC = iNapIKModelDC._nInf(v=v0)
    y0DC = np.array([v0, n0DC])
    resDC = integrateModelForward(model=iNapIKModelDC,
                                  y0=y0DC,
                                  dt=dt,
                                  nTSteps=nTSteps)
    spikeIndices = getPeakIndices(v=resDC["ys"][0, :])
    if len(spikeIndices) <= nTransientSpikes:
        raise ValueError("nTransientSpikes=%d is too large" %
                         (nTransientSpikes))
    spikeTimes = resDC["times"][spikeIndices]
    tPulse = spikeTimes[nTransientSpikes + 1] + pulsePhase

    def iDCTrainPulses(t):
        if t > tPulse:
            r = (t - tPulse) % Ts
            if r < pulseWidth / 2 or Ts - pulseWidth / 2 < r:
                return (i0 + pulseStrength)
        return (i0)

    model = INapIKModel.getLowThresholdInstance()
    model.setI(i=iDCTrainPulses)
    n0 = model._nInf(v=v0)
    y0 = np.array([v0, n0])
    resDCTrainPulses = integrateModelForward(model=model,
                                             y0=y0,
                                             dt=dt,
                                             nTSteps=nTSteps)
    # peakIndices = getPeakIndices(v=resDCTrainPulses["ys"][0,:])
    # resDCTrainPulses["ys"] = resDCTrainPulses["ys"][:,peakIndices[0]:]
    # resDCTrainPulses["times"] = resDCTrainPulses["times"][peakIndices[0]:]-\
    #                             resDCTrainPulses["times"][peakIndices[0]]

    appliedIs = np.empty(resDCTrainPulses["times"].shape)
    for i in range(len(resDCTrainPulses["times"])):
        appliedIs[i] = iDCTrainPulses(t=resDCTrainPulses["times"][i])

    np.savez(resultsFilename,
             timesDC=resDC["times"],
             ysDC=resDC["ys"],
             timesDCTrainPulses=resDCTrainPulses["times"],
             ysDCTrainPulses=resDCTrainPulses["ys"],
             i0=i0,
             i=appliedIs,
             Ts=Ts,
             tPulse=tPulse)

    plt.plot(resDC["times"], resDC["ys"][0, :], color="blue", label="DC stim")
    plt.plot(resDCTrainPulses["times"],
             resDCTrainPulses["ys"][0, :],
             color="magenta",
             label="Pulse stim")
    plt.xlabel("Time (sec)")
    plt.ylabel("Membrane Potential (mV)")
    plt.legend(loc="upper left")
    ax = plt.gca()
    ax2 = ax.twinx()
    ax2.plot(resDCTrainPulses["times"], appliedIs, color="lightgray")
    ax2.set_ylabel("Input Current (mA)")
    plt.show()
    pdb.set_trace()
Exemplo n.º 12
0
def main(argv):
    resultsFilename = "results/integrationINapIKFig10_10_2-1Sync.npz"
    v0 = -60.00
    t0 = 0.0
    tf = 198.0
    dt = 1e-3
    nTSteps = int(round((tf - t0) / dt))
    times = np.empty(nTSteps + 1)
    # i0 = 4.7
    i0 = 9.4
    nTransientSpikes = 6
    pulseStrength = 200.0
    pulseWidth = 100 * dt
    Ts = 18.37
    offset = 9.0

    # offset = 14.0

    def iDC(t):
        return (i0)

    iNapIKModelDC = INapIKModel.getHighThresholdInstance()
    iNapIKModelDC.setI(i=iDC)
    n0DC = iNapIKModelDC._nInf(v=v0)
    y0DC = np.array([v0, n0DC])
    resDC = integrateForward(deriv=iNapIKModelDC.deriv,
                             t0=t0,
                             y0=y0DC,
                             dt=dt,
                             nTSteps=nTSteps)

    def iDCTrainPulses(t):
        r = (t - offset) % Ts
        if r < pulseWidth / 2 or Ts - pulseWidth / 2 < r:
            return (i0 + pulseStrength)
        return (i0)

    model = INapIKModel.getHighThresholdInstance()
    model.setI(i=iDCTrainPulses)
    n0 = model._nInf(v=v0)
    y0 = np.array([v0, n0])
    resDCTrainPulses = integrateForward(deriv=model.deriv,
                                        t0=t0,
                                        y0=y0,
                                        dt=dt,
                                        nTSteps=nTSteps)
    # peakIndices = getPeakIndices(v=resDCTrainPulses["ys"][0,:])
    # resDCTrainPulses["ys"] = resDCTrainPulses["ys"][:,peakIndices[0]:]
    # resDCTrainPulses["times"] = resDCTrainPulses["times"][peakIndices[0]:]-\
    #                             resDCTrainPulses["times"][peakIndices[0]]

    appliedIs = np.empty(resDCTrainPulses["times"].shape)
    for i in range(len(resDCTrainPulses["times"])):
        appliedIs[i] = iDCTrainPulses(t=resDCTrainPulses["times"][i])

    # np.savez(resultsFilename, times=resDCTrainPulses["times"],
    #                           ys=resDCTrainPulses["ys"],
    #                           i0=i0, i=appliedIs, Ts=Ts, offset=offset)

    # np.savez(resultsFilename,
    #           timesDC=resDC["times"],
    #           ysDC=resDC["ys"],
    #           timesDCTrainPulses=resDCTrainPulses["times"],
    #           ysDCTrainPulses=resDCTrainPulses["ys"],
    #           i0=i0, i=appliedIs, Ts=Ts, tPulse=tPulse)

    spikeIndices = getPeakIndices(v=resDC["ys"][0, :])
    if len(spikeIndices) <= nTransientSpikes:
        raise ValueError("nTransientSpikes=%d is too large" %
                         (nTransientSpikes))
    spikeTimes = resDC["times"][spikeIndices]

    ts = spikeTimes[1:] - spikeTimes[:-1]
    T = np.mean(ts)
    print("T=%.02f" % (T))

    plt.plot(resDCTrainPulses["times"],
             resDCTrainPulses["ys"][0, :],
             color="blue")
    plt.xlabel("Time (sec)")
    plt.ylabel("Membrane Potential (mV)")
    ax = plt.gca()
    ax2 = ax.twinx()
    ax2.plot(resDCTrainPulses["times"], appliedIs, color="red")
    ax2.set_ylabel("Input Current (mA)")
    plt.show()
def main(argv):
    i0 = 10
    numberOfPhasesForX0 = 40
    indexPhaseX0 = 38
    annotationGap = 0.02
    factorsDeltaT = 1.0 / 32.0 * np.arange(1, 6)
    # factorsDeltaT = 1.0/32.0*np.arange(5, 6)
    nInitialConditions = 10
    maxDeltaX0 = 1.0
    maxDeltaX1 = 0.01
    dt = 1e-5
    nSPLUNew = 1000
    vMin = -90
    vMax = 15
    nMin = -0.1
    nMax = 0.8
    resultsFilename = "results/integrationINapIKFig10_1.npz"
    aFigFilename = "figures/fig10_1b.eps"

    results = np.load(resultsFilename)
    times = results["times"]
    ys = results["ys"]
    spikeIndices = getPeakIndices(v=ys[0, :])
    spikeTimes = times[spikeIndices]

    times = np.delete(times, np.arange(0, spikeIndices[0]))
    times = times - times[0]
    ys = np.delete(ys, np.arange(0, spikeIndices[0]), axis=1)
    spikeIndices = spikeIndices - spikeIndices[0]
    spikeTimes = spikeTimes - spikeTimes[0]
    period = spikeTimes[1] - spikeTimes[0]
    phases = times % period
    phasesForX0 = np.arange(0, period, period / numberOfPhasesForX0)
    indicesBtwFirstAndSecondSpike = np.arange(0, spikeIndices[1])
    phasesToSearch = phases[indicesBtwFirstAndSecondSpike]

    indicesPhasesForX0 = np.empty(len(phasesForX0), dtype=np.int64)
    for i in xrange(len(phasesForX0)):
        phaseForX0 = phasesForX0[i]
        indicesPhasesForX0[i] = np.argmin(np.abs(phasesToSearch - phaseForX0))
    x0 = ys[:, indicesPhasesForX0[indexPhaseX0]]

    def i(t):
        return (i0)

    model = INapIKModel.getHighThresholdInstance(i=i)
    isochron = computeIsochron(model,
                               x0=x0,
                               deltaTs=factorsDeltaT * period,
                               nInitialConditions=nInitialConditions,
                               maxDeltaX0=maxDeltaX0,
                               maxDeltaX1=maxDeltaX1,
                               dt=dt)
    # begin tmp code
    np.savez("~/tmp/isochron.npz", isochron=isochron)
    # results = np.load("/tmp/isochron.npz")
    # isochron = results["isochron"]
    # end tmp code

    validIndices = np.logical_and(
        np.logical_and(vMin <= isochron[0, :], isochron[0, :] <= vMax),
        np.logical_and(nMin <= isochron[1, :],
                       isochron[1, :] <= nMax)).nonzero()[0]
    isochron = isochron[:, validIndices]
    sortOrder = np.argsort(isochron[1, :])
    isochron = isochron[:, sortOrder]
    splTck, splU = splprep(isochron, s=5.0)
    splUNew = np.linspace(splU.min(), splU.max(), nSPLUNew)
    splXInter, splYInter = splev(splUNew, splTck, der=0)

    # plt.figure()
    # plotHighThresholdINapIKVectorField(i=i0)
    plt.plot(ys[0, :], ys[1, :], label="limit cycle attractor")
    # pdb.set_trace()

    plt.annotate("x0", xy=x0, color="red", size=14)

    plotINapIKNullclines(i=i0,
                         eL=model._eL,
                         gL=model._gL,
                         eNa=model._eNa,
                         gNa=model._gNa,
                         eK=model._eK,
                         gK=model._gK,
                         mVOneHalf=model._mVOneHalf,
                         mK=model._mK,
                         nVOneHalf=model._nVOneHalf,
                         nK=model._nK)
    plt.plot(isochron[0, :],
             isochron[1, :],
             marker="o",
             color="red",
             linestyle="None")
    plt.plot(splXInter, splYInter, color="gray", linestyle="solid")
    plt.legend(loc="upper left")
    plt.xlabel("Voltage (mv)")
    plt.ylabel("K activation variable, n")
    plt.xlim((-90, 15))
    plt.ylim((-0.1, 0.8))
    plt.show()
    pdb.set_trace()