Exemple #1
0
def rescue1ch(filetrnk, xunits="ms", yunits="mV", dt=0.02):
    sys.stdout.write("NICOMEDI: Rescuing file: Reading temp files...\n")
    sys.stdout.flush()

    fntmp = filetrnk + "_tmp.bin"
    fntmp2 = filetrnk + "_tmp2.bin"
    entmp = filetrnk + "_edge.bin"
    fn = filetrnk + ".h5"

    ftmp = open(fntmp, 'rb')
    ftmp2 = open(fntmp2, 'rb')
    databstr = ftmp.read()
    databstr2 = ftmp2.read()
    sys.stdout.write("NICOMEDI: Saving to file: Processing data...\n")
    sys.stdout.flush()
    datalist = np.fromstring(databstr, np.float32)
    frames = np.fromstring(databstr2, np.int8)
    # Write to hdf5:
    sys.stdout.write("NICOMEDI: Saving to file: Converting to hdf5...\n")
    sys.stdout.flush()
    chlist = [
        stfio.Channel([
            stfio.Section(np.array(datalist, dtype=np.float)),
        ]),
    ]
    chlist[0].yunits = yunits
    rec = stfio.Recording(chlist)
    rec.dt = dt  # set sampling interval
    rec.xunits = xunits  # set time units
    sys.stdout.write("NICOMEDI: Saving to file: Writing hdf5...")
    sys.stdout.flush()
    rec.write(fn)
    sys.stdout.write("done\n")
    sys.stdout.flush()

    # Write frame transition times
    if frames[0] != 0:
        sys.stdout.write("NICOMEDI: Warning: first frame isn't 0\n")
    edges = find_edges(frames)
    etmp = open(entmp, 'wb')
    etmp.write(edges.astype(np.int32).tostring())
    etmp.close()

    # Close and delete temp file:
    ftmp.close()
    ftmp2.close()
    os.remove(fntmp)
    os.remove(fntmp2)
    sys.stdout.write("\nNICOMEDI: Stopping acquisition, read %d samples\n" \
                     % len(datalist))
    sys.stdout.flush()
def convert_ws_to_stfio(infile):

    wsfile = ws.wsfile(infile)

    data = wsfile.data()
    units = wsfile.unitslist
    chlist = []

    for channel, traces in data.iteritems():

        seclist = [stfio.Section(trace) for trace in traces if np.any(trace)]
        chlist.append(stfio.Channel(seclist))
        chlist[-1].yunits = units[channel]
        chlist[-1].name = channel

    rec = stfio.Recording(chlist)
    rec.date = wsfile.dstamp.strftime("%Y-%m-%d")
    rec.time = wsfile.dstamp.strftime("%H-%M-%S")
    rec.dt = 1000.0 / wsfile.SampleRate
    rec.dt
    rec.xunits = 'ms'

    return rec
Exemple #3
0
def neo2stfio(neo_obj):
    """Convert neo object to stfio recording.
       Restrictions:
       * Only converts the first block
       * Assumes that the sampling rate is constant throughout segments
       * Assumes that we have the same number of channels throughout segments
       * Assumes that the channel units do not change

       Usage:
           >>> import neo
           >>> neo_obj = neo.io.AxonIO("filename.abf")
           >>> import stfio
           >>> stfio_obj = stfio.neo.neo2stfio(neo_obj)
           >>> assert(stfio_obj[0][0][0] == neo_obj.read()[0].segments[0].analogsignals[0][0])
    """
    
    blocks = neo_obj.read()
    if len(blocks) > 1:
        sys.stderr.write("Warning: Only the first block" +  
                         "of this neo object will be converted\n")

    reference_signal = blocks[0].segments[0].analogsignals

    nchannels = len(reference_signal)

    rec = stfio.Recording([
        stfio.Channel([
            stfio.Section(np.array(seg.analogsignals[nc], dtype=np.float64))
            for seg in blocks[0].segments
        ], reference_signal[nc].units.dimensionality.string)
        for nc in range(nchannels)
    ])
    rec.dt = float(reference_signal[0].sampling_period.rescale('ms'))
    rec.xunits = "ms"

    return rec
Exemple #4
0
def stop(aichIC, aichEC, aichFR, dt, xunits, yunitsIC, yunitsEC, gainIC,
         gainEC, fn, ftmpIC, fntmpIC, ftmpEC, fntmpEC, ftmpFR, fntmpFR, entmp,
         s, connic, connec, connfr, plot_sample, databstr_old):

    # Close device:
    ret = c.comedi_cancel(aichIC.dev, aichIC.subdev)
    # time stamp for last sample
    s.send(np.array([
        time.time(),
    ], dtype=np.float64).tostring())
    if ret != 0:
        comedi_errcheck()

    # Empty buffer:
    # ret = c.comedi_poll(aich.dev, aich.subdev)
    # if ret < 0:
    #     comedi_errcheck()
    read_buffer(aichIC, aichEC, aichFR, gainIC, gainEC, connic, connec, connfr,
                plot_sample, ftmpIC, ftmpEC, ftmpFR, databstr_old)
    ftmpIC.close()
    ftmpEC.close()
    ftmpFR.close()

    # Scale temporary file:
    sys.stdout.write("NICOMEDI: Saving to file: Reading temp file...\n")
    sys.stdout.flush()
    ftmpIC = open(fntmpIC, 'rb')
    ftmpEC = open(fntmpEC, 'rb')
    ftmpFR = open(fntmpFR, 'rb')
    databstrIC = ftmpIC.read()
    databstrEC = ftmpEC.read()
    databstrFR = ftmpFR.read()
    sys.stdout.write("NICOMEDI: Saving to file: Processing data...\n")
    sys.stdout.flush()
    datalistIC = np.fromstring(databstrIC, np.float32)
    datalistEC = np.fromstring(databstrEC, np.float32)
    frames = np.fromstring(databstrFR, np.int8)
    # Write to hdf5:
    sys.stdout.write("NICOMEDI: Saving to file: Converting to hdf5...\n")
    sys.stdout.flush()
    chlist = [
        stfio.Channel([
            stfio.Section(np.array(datalistIC, dtype=np.float)),
        ]),
        stfio.Channel([
            stfio.Section(np.array(datalistEC, dtype=np.float)),
        ])
    ]
    chlist[0].yunits = yunitsIC
    chlist[1].yunits = yunitsEC
    rec = stfio.Recording(chlist)
    rec.dt = dt  # set sampling interval
    rec.xunits = xunits  # set time units
    sys.stdout.write("NICOMEDI: Saving to file: Writing hdf5 to %s..." % fn)
    sys.stdout.flush()
    if sys.version_info >= (3, ):
        rec.write(fn)
    else:
        rec.write(fn.encode('latin-1'))
    sys.stdout.write("done\n")
    sys.stdout.flush()

    # Write frame transition times
    if frames[0] != 0:
        sys.stdout.write("NICOMEDI: Warning: first frame isn't 0\n")
    edges = find_edges(frames)
    etmp = open(entmp, 'wb')
    etmp.write(edges.astype(np.int32).tostring())
    etmp.close()

    # Close and delete temp file:
    ftmpIC.close()
    ftmpEC.close()
    ftmpFR.close()
    # Do not remove temp files, CSH 2013-10-11
    # os.remove(fntmpIC)
    # os.remove(fntmpEC)
    # os.remove(fntmpFR)
    sys.stdout.write("\nNICOMEDI: Stopping acquisition, read %d samples\n" \
                     % len(datalistIC))
    sys.stdout.flush()

    sys.stdout.write("NICOMEDI: Synchronizing in background\n")
    locald = os.path.dirname(fn)
    netd = os.path.dirname(
        locald.replace(settings.local_data_dir,
                       settings.net_data_dir_mnt)) + '/'
    if not os.path.exists(netd):
        args = ["/usr/local/bin/sync_rackstation.sh"]
    else:
        netd = os.path.dirname(
            locald.replace(settings.local_data_dir,
                           settings.net_data_dir)) + """/'"""
        args = ["/usr/bin/rsync", "-a", locald, netd]
    subprocess.Popen(args)
Exemple #5
0
def run(dt_nrn, tstop, mean_f):

    module_dir = os.path.dirname(__file__)
    if os.path.exists("%s/dat/events.h5" % module_dir):
        rec = stfio.read("%s/dat/events.h5" % module_dir)
        spiketimes = np.load("%s/dat/spiketimes.npy" % module_dir)
        return rec, spiketimes

    if os.path.exists("%s/dat/events_nonoise.npy" % module_dir):
        mrec = np.load("%s/dat/events_nonoise.npy" % module_dir)
        spiketimes = np.load("%s/dat/spiketimes.npy" % module_dir)
    else:
        from neuron import h
        h.load_file('stdrun.hoc')

        soma, dend = ball_and_stick(h)
        h.tstop = tstop

        trange = np.arange(0, tstop + dt_nrn, dt_nrn)
        spiketimes = generate_events(trange, mean_f)
        np.save("%s/dat/spiketimes.npy" % module_dir, spiketimes)

        syn_AMPA, spiketimes_nrn, vecstim, netcon = [], [], [], []
        for spike in spiketimes:
            loc = 0.8 * np.random.normal(1.0, 0.03)
            if loc < 0:
                loc = 0
            if loc > 1:
                loc = 1
            syn_AMPA.append(h.Exp2Syn(dend(loc), sec=dend))
            spiketimes_nrn.append(h.Vector([spike]))
            vecstim.append(h.VecStim())
            netcon.append(h.NetCon(vecstim[-1], syn_AMPA[-1]))

            syn_AMPA[-1].tau1 = 0.2 * np.random.normal(1.0, 0.3)
            if syn_AMPA[-1].tau1 < 0.05:
                syn_AMPA[-1].tau1 = 0.05
            syn_AMPA[-1].tau2 = 2.5 * np.random.normal(1.0, 0.3)
            if syn_AMPA[-1].tau2 < syn_AMPA[-1].tau1 * 1.5:
                syn_AMPA[-1].tau2 = syn_AMPA[-1].tau1 * 1.5
            syn_AMPA[-1].e = 0

            vecstim[-1].play(spiketimes_nrn[-1])
            netcon[-1].weight[0] = np.random.normal(1.0e-3, 1.0e-4)
            if netcon[-1].weight[0] < 0:
                netcon[-1].weight[0] = 0
            netcon[-1].threshold = 0.0

        vclamp = h.SEClamp(soma(0.5), sec=soma)
        vclamp.dur1 = tstop
        vclamp.amp1 = -80.0
        vclamp.rs = 5.0
        mrec = h.Vector()
        mrec.record(vclamp._ref_i)

        h.dt = dt_nrn  # ms
        h.steps_per_ms = 1.0 / h.dt
        h.v_init = -80.0
        h.run()

        mrec = np.array(mrec)
        np.save("%s/dat/events_nonoise.npy" % module_dir, mrec)

    plt.plot(np.arange(len(mrec), dtype=np.float) * dt_nrn, mrec)

    peak_window_i = 20.0 / dt_nrn
    amps_i = np.array([
        int(np.argmin(mrec[onset_i:onset_i + peak_window_i]) + onset_i)
        for onset_i in spiketimes / dt_nrn
    ],
                      dtype=np.int)

    plt.plot(amps_i * dt_nrn, mrec[amps_i], 'o')

    mean_amp = np.abs(mrec[amps_i].mean())
    print(mean_amp)
    mrec = add_noise(mrec, dt_nrn, mean_amp)
    plt.plot(np.arange(len(mrec), dtype=np.float) * dt_nrn, mrec)

    seclist = [
        stfio.Section(mrec),
    ]
    chlist = [
        stfio.Channel(seclist),
    ]
    chlist[0].yunits = "pA"
    rec = stfio.Recording(chlist)
    rec.dt = dt_nrn
    rec.xunits = "ms"
    rec.write("%s/dat/events.h5" % module_dir)

    return rec, spiketimes