Example #1
0
def search(stimset='../Search'):

    # Connect network handler
    ip = '127.0.0.1'
    port = 5556
    timeout = 1.

    url = "tcp://%s:%d" % (ip, port)

    songfiles = glob.glob(stimset + '/*.wav')
    size = len(songfiles)
    present_order = sdk.seqorder(size)
    stim, Fs, songname = ss.dBclean(stimset)
    print(songname)

    with zmq.Context() as context:
        with context.socket(zmq.REQ) as socket:
            socket.RCVTIMEO = int(timeout * 1000)  # timeout in milliseconds
            socket.connect(url)

            # Start data acquisition
            socket.send_string('StartAcquisition')
            print(socket.recv().decode())
            time.sleep(5)

            socket.send_string('IsAcquiring')
            print("IsAcquiring:", socket.recv().decode())
            print("")
            print("Playing search stimuli...")
            print("To end, press CTRL-C")

            try:
                while True:
                    for i in range(len(present_order)):
                        sd.play(ss.pulsestim(stim[present_order[i] - 1], True),
                                Fs)
                        sd.wait()
                        time.sleep(2)
            except KeyboardInterrupt:
                print("")
                socket.send_string('StopAcquisition')
                print(socket.recv().decode())
                time.sleep(1)
                socket.send_string('IsAcquiring')
                print("IsAcquiring:", socket.recv().decode())
                pass
Example #2
0
def align_audio(fp,log,thresh=1):
    data = h5py.File(fp)
    with open(log) as json_file:
        meta = json.load(json_file)
    n = len(meta['presentation'])
    present_order = sdk.seqorder(n//10)
    total_start = 0
    df = pd.DataFrame(index=np.arange(0, n), columns = ['rec','song','condition','stim','total_start','total_stop','total_pulse','local_pulse'])
    for i in range(n):
        try:
            data['rec_'+str(i)]
            if len({len(data['rec_0/'+i]) for i in list(data['rec_0'].keys()) if 'channel' in i}) == 1:
                pulse = data['rec_'+str(i)+'/channel37']
                points = np.where(pulse[:]>thresh)[0]
                dist = np.diff(points)
                points = np.delete(points,np.where(dist==1))
                ind = present_order[i]-1
                if len(points) > 1:
                    print("Expecting 1 pulse, got "+str(len(points))+". Adjust threshold.")
                else:
                    if type(meta['presentation']) == list:
                        song = meta['presentation'][i].split(' ')[0]
                        condition = ' '.join(meta['presentation'][i].split(' ')[1:])
                    else:
                        song = meta['presentation'][str(i)]['song']
                        condition = meta['presentation'][str(i)]['type']
                    df.loc[i]=[i,song,condition,ind,total_start,total_start+len(pulse)-1,total_start+points[0],points[0]]
                    total_start = total_start+len(pulse)
            else:
                raise ValueError('Not all channels have same length!')
        except:
            ind = present_order[i]-1
            if type(meta['presentation']) == list:
                song = meta['presentation'][i].split(' ')[0]
                condition = ' '.join(meta['presentation'][i].split(' ')[1:])
            else:
                song = meta['presentation'][str(i)]['song']
                condition = meta['presentation'][str(i)]['type']
            df.loc[i]=[i,song,condition,ind,np.nan,np.nan,np.nan,np.nan]
    df.to_csv('/'.join(fp.split('/')[:-1])+'/alignment.csv',index=False)
    data.close()
Example #3
0
def make_stims(stimset, seed):
    if '180B' in stimset or '178B' in stimset:
        song, Fs, songname = ss.dBclean('../178B')
        song2, Fs, songname2 = ss.dBclean('../180B')
        song = np.concatenate((song, song2), 0)
        songname = songname + songname2
    else:
        song, Fs, songname = ss.dBclean(stimset)
    stype = [
        'continuous', 'continuousnoise1', 'continuousnoise2', 'gap1', 'gap2',
        'gapnoise1', 'gapnoise2', 'noise1', 'noise2'
    ]
    syllables = pd.read_csv('../gap-locations.csv')
    conditions = len(stype)
    trials = 10
    size = len(songname) * conditions
    present_order = sdk.seqorder(size, trials)
    presentation = {}
    stims = []
    np.random.seed(seed)
    for i in range(len(songname)):
        ssyll = syllables.loc[syllables.song == songname[i]]
        blocks = np.zeros((2, 2))
        blocks[:, 0] = np.asarray(
            (ssyll.start1.values[0], ssyll.start2.values[0]))
        blocks[:, 1] = np.asarray((ssyll.end1.values[0], ssyll.end2.values[0]))
        blocks = blocks * Fs
        blocks = blocks.astype(int)
        gsize = int(0.1 * Fs)
        wnamp = 25000
        wndB = 85
        if blocks[0, 1] - blocks[0, 0] > gsize:
            blocks[0, 1] = blocks[0, 0] + gsize
        if blocks[1, 1] - blocks[1, 0] > gsize:
            blocks[1, 1] = blocks[1, 0] + gsize
        N = 120
        ix = np.arange(N * 3)
        signal = np.cos(2 * np.pi * ix / float(N * 2)) * 0.5 + 0.5
        fadein = signal[120:240]
        fadeout = signal[0:120]
        wn1 = np.random.normal(0, wnamp, size=blocks[0, 1] - blocks[0, 0])
        wn1 = (wn1 / rms(wn1)) * scale(wndB)
        wn2 = np.random.normal(0, wnamp, size=blocks[1, 1] - blocks[1, 0])
        wn2 = (wn2 / rms(wn2)) * scale(wndB)
        for k in range(conditions):
            order = (i * conditions) + k
            presentation[order] = {
                "song": songname[i],
                "type": stype[k],
            }
            if k == 0:
                stims.append(song[i])
            elif k == 1:
                presentation[order]['gaps'] = blocks[0].tolist()
                stims.append(
                    np.concatenate((song[i][:blocks[0, 0]],
                                    song[i][blocks[0, 0]:blocks[0, 1]] + wn1,
                                    song[i][blocks[0, 1]:])))
            elif k == 2:
                presentation[order]['gaps'] = blocks[1].tolist()

                stims.append(
                    np.concatenate((song[i][:blocks[1, 0]],
                                    song[i][blocks[1, 0]:blocks[1, 1]] + wn2,
                                    song[i][blocks[1, 1]:])))
            elif k == 3:
                presentation[order]['gaps'] = blocks[0].tolist()
                stims.append(
                    np.concatenate(
                        (song[i][:blocks[0, 0]],
                         song[i][blocks[0, 0]:blocks[0, 0] + len(fadein)] *
                         fadeout,
                         np.zeros(blocks[0, 1] - blocks[0, 0] -
                                  len(fadein) * 2),
                         song[i][blocks[0, 1] - len(fadein):blocks[0, 1]] *
                         fadein, song[i][blocks[0, 1]:])))
            elif k == 4:
                presentation[order]['gaps'] = blocks[1].tolist()
                stims.append(
                    np.concatenate(
                        (song[i][:blocks[1, 0]],
                         song[i][blocks[1, 0]:blocks[1, 0] + len(fadein)] *
                         fadeout,
                         np.zeros(blocks[1, 1] - blocks[1, 0] -
                                  len(fadein) * 2),
                         song[i][blocks[1, 1] - len(fadein):blocks[1, 1]] *
                         fadein, song[i][blocks[1, 1]:])))
            elif k == 5:
                presentation[order]['gaps'] = blocks[0].tolist()
                stims.append(
                    np.concatenate(
                        (song[i][:blocks[0, 0]], wn1, song[i][blocks[0, 1]:])))
            elif k == 6:
                presentation[order]['gaps'] = blocks[1].tolist()
                stims.append(
                    np.concatenate(
                        (song[i][:blocks[1, 0]], wn2, song[i][blocks[1, 1]:])))
            elif k == 7:
                presentation[order]['gaps'] = blocks[0].tolist()
                temp = np.zeros(len(song[i]))
                stims.append(
                    np.concatenate(
                        (temp[:blocks[0, 0]], wn1, temp[blocks[0, 1]:])))
            elif k == 8:
                presentation[order]['gaps'] = blocks[1].tolist()
                temp = np.zeros(len(song[i]))
                stims.append(
                    np.concatenate(
                        (temp[:blocks[1, 0]], wn2, temp[blocks[1, 1]:])))
            else:
                print("Undefined stim type")
    stims = np.asarray(stims)

    return (Fs, stype, present_order, presentation, stims, songname)
Example #4
0
def run_chorus(bird,
               location,
               seed,
               rec_dir='/home/melizalab/Data',
               stimset='../Chorus'):
    # Basic start/stop commands
    start_cmd = 'StartRecord'
    stop_cmd = 'StopRecord'
    experiment = 'chorus'

    print("Bird:", bird)
    print("Recording location:", location)
    print("Randomization seed:", str(seed))
    print("Stimulus directory:", stimset)
    print("Outer directory:", rec_dir)

    command = start_cmd + ' RecDir=%s' % rec_dir + ' PrependText=%s' % bird + ' AppendText=%s' % experiment

    # Connect network handler
    ip = '127.0.0.1'
    port = 5556
    timeout = 1.

    url = "tcp://%s:%d" % (ip, port)

    songfiles = glob.glob('../Chorus/*stim*wav')
    scenefiles = glob.glob('../Chorus/scene*wav')
    songfiles.sort()
    scenefiles.sort()

    songname = [os.path.basename(song).strip('.wav') for song in songfiles]
    scenename = [os.path.basename(scene).strip('.wav') for scene in scenefiles]
    songs = []
    scenes = []
    name = []
    for i in songfiles:
        Fs, s = read(i)
        songs.append(s)
    songs = np.asarray(songs)
    for i in scenefiles:
        Fsc, c = read(i)
        scenes.append(c)
    scenes = np.asarray(scenes)

    stype = ['silence', 'chorus']
    conditions = len(stype)
    size = len(songname) * conditions
    present_order = sdk.seqorder(size)
    presentation = {}
    stim = np.zeros((len(songs), len(scenes[0])))
    scenestim = np.zeros((len(songs) * len(scenes), len(scenes[0])))

    for i in range(len(songs)):
        stimstart = (len(scenes[0]) - len(songs[i])) // 2
        stim[i, stimstart:stimstart + len(songs[i])] = songs[i]
        for j in range(len(scenes)):
            scenestim[(i * len(scenes)) + j] = scenes[j] + stim[i]
            name.append(songname[i] + ' ' + scenename[j])

    np.random.seed(seed)

    presentation = {}
    pstims = np.zeros((len(songs), len(scenes[0]), 2))
    pscenes = np.zeros((len(songs) * len(scenes), len(scenes[0]), 2))
    for i in range(len(stim)):
        pstims[i] = ss.pulsestim(stim[i])
    for i in range(len(scenestim)):
        pscenes[i] = ss.pulsestim(scenestim[i])

    with zmq.Context() as context:
        with context.socket(zmq.REQ) as socket:
            socket.RCVTIMEO = int(timeout * 1000)  # timeout in milliseconds
            socket.connect(url)

            # Start data acquisition
            socket.send_string('StartAcquisition')
            print(socket.recv().decode())
            time.sleep(5)

            socket.send_string('IsAcquiring')
            print("IsAcquiring:", socket.recv().decode())
            print("")

            socket.send_string(command)
            print(socket.recv().decode())

            for i in range(len(present_order)):

                if i == 0:
                    socket.send_string('IsRecording')
                    print("IsRecording:", socket.recv().decode())
                    socket.send_string('GetRecordingPath')
                    recpath = socket.recv()
                    print("Recording path:", recpath.decode())
                    print("")
                else:
                    socket.send_string(start_cmd)
                    print(socket.recv().decode())

                socket.send_string('IsRecording')
                print("IsRecording:", socket.recv().decode())
                time.sleep(0.5)

                if present_order[i] <= len(pstims):
                    songnum = present_order[i] - 1
                    print("Presentation number " + str(i + 1) + ": " +
                          songname[songnum])
                    sd.play(pstims[songnum], Fs)
                    sd.wait()
                    presentation[i] = {
                        "song": songname[songnum],
                        "type": "no-scene",
                    }
                else:
                    scenenum = (present_order[i] - len(songname) -
                                1) + (len(songname) * (i //
                                                       (len(songname) * 2)))
                    songnum = scenenum // 10
                    print("Presentation number " + str(i + 1) + ": " +
                          songname[songnum] + " with chorus")
                    sd.play(pscenes[scenenum], Fsc)
                    sd.wait()
                    presentation[i] = {
                        "song": name[scenenum].split(' ')[0],
                        "type": name[scenenum].split(' ')[1],
                    }

                socket.send_string(stop_cmd)
                print(socket.recv().decode())
                socket.send_string('IsRecording')
                print("IsRecording:", socket.recv().decode())
                print("")
                time.sleep(0.5)

            time.sleep(0.5)

            write_log(bird, location, stimset, experiment, songname, recpath,
                      presentation, seed)

            socket.send_string('StopAcquisition')
            print(socket.recv().decode())
Example #5
0
def run_clean(bird,
              location,
              rec_dir='/home/melizalab/Data',
              stimset='../Stims1'):
    # Basic start/stop commands
    start_cmd = 'StartRecord'
    stop_cmd = 'StopRecord'
    experiment = 'selectivity'

    print("Bird:", bird)
    print("Recording location:", location)
    print("Stimulus directory:", stimset)
    print("Outer directory:", rec_dir)

    command = start_cmd + ' RecDir=%s' % rec_dir + ' PrependText=%s' % bird + ' AppendText=%s' % stimtype

    # Connect network handler
    ip = '127.0.0.1'
    port = 5556
    timeout = 1.

    url = "tcp://%s:%d" % (ip, port)

    songfiles = glob.glob(stimset + '/*.wav')
    size = len(songfiles)
    present_order = sdk.seqorder(size)
    presentation = []
    stim, Fs, songname = ss.clean(stimset)
    pstims = np.zeros((size, len(stim[0]), 2))
    for i in range(len(stim)):
        pstims[i] = ss.pulsestim(stim[i])

    with zmq.Context() as context:
        with context.socket(zmq.REQ) as socket:
            socket.RCVTIMEO = int(timeout * 1000)  # timeout in milliseconds
            socket.connect(url)

            # Start data acquisition
            socket.send_string('StartAcquisition')
            print(socket.recv().decode())
            time.sleep(5)

            socket.send_string('IsAcquiring')
            print("IsAcquiring:", socket.recv().decode())
            print("")

            socket.send_string(command)
            print(socket.recv().decode())

            for i in range(len(present_order)):

                if i == 0:
                    socket.send_string('IsRecording')
                    print("IsRecording:", socket.recv().decode())
                    socket.send_string('GetRecordingPath')
                    recpath = socket.recv()
                    print("Recording path:", recpath.decode())
                    print("")
                else:
                    socket.send_string(start_cmd)
                    print(socket.recv().decode())
                socket.send_string('IsRecording')
                print("IsRecording:", socket.recv().decode())
                time.sleep(1)

                next_stim(pstims, present_order, i, songname, Fs)

                time.sleep(1)
                socket.send_string(stop_cmd)
                print(socket.recv().decode())
                socket.send_string('IsRecording')
                print("IsRecording:", socket.recv().decode())
                print("")
                time.sleep(0.5)
            #socket.send_string(stop_cmd)
            #print(socket.recv().decode())
            #socket.send_string('IsRecording')
            #print("IsRecording:", socket.recv().decode())
            # Finally, stop data acquisition; it might be a good idea to
            # wait a little bit until all data have been written to hard drive
            time.sleep(0.5)

            write_log(bird, location, stimset, experiment, songname, recpath,
                      presentation)

            socket.send_string('StopAcquisition')
            print(socket.recv().decode())
def make_stims(stimset, seed):
    song, Fs, songname = ss.clean(stimset)
    stype = [
        'continuous', 'continuous+mask', 'continuous+noise', 'gap+mask', 'gap',
        'gap+noise', 'noise'
    ]
    syllables = pd.read_csv('../syllables.csv')
    conditions = len(stype)
    trials = 10
    size = len(songname) * conditions
    present_order = sdk.seqorder(size, trials)
    presentation = {}
    stims = np.zeros((size, len(song[0])))
    np.random.seed(seed)
    for i in range(len(songname)):
        ssyll = syllables.loc[syllables.songid == songname[i]]
        sg = np.random.choice(len(ssyll.loc[ssyll.motif == 1][1:-1]))
        blocks = np.zeros((2, 2))
        blocks[:, 0] = np.asarray(
            [list(ssyll.start[ssyll.motif == x])[sg + 1] for x in range(1, 3)])
        blocks[:, 1] = np.asarray(
            [list(ssyll.end[ssyll.motif == x])[sg + 1] for x in range(1, 3)])
        blocks = blocks * Fs
        blocks = blocks.astype(int)
        gsize = int(0.1 * Fs)
        wnamp = 25000
        if blocks[0, 1] - blocks[0, 0] > gsize:
            middle = np.mean(blocks, 1)
            blocks[:, 0] = middle - int(gsize / 2) - 50
            blocks[:, 1] = blocks[:, 0] + gsize
        N = 50
        ix = np.arange(N * 3)
        signal = np.cos(2 * np.pi * ix / float(N * 2)) * 0.5 + 0.5
        fadein = signal[50:100]
        fadeout = signal[0:50]
        for k in range(conditions):
            order = (i * conditions) + k
            presentation[order] = {
                "song": songname[i],
                "type": stype[k],
            }
            if k == 0:
                stims[order] = song[i]
            elif k == 1:
                mask = np.zeros((2, 2))
                mask[:, 0] = np.asarray([
                    list(ssyll.start[ssyll.motif == x])[0]
                    for x in range(1, 3)
                ])
                mask[:, 1] = np.asarray([
                    list(ssyll.end[ssyll.motif == x])[-1] for x in range(1, 3)
                ])
                mask = mask * Fs
                mask = mask.astype(int)
                wn1 = np.random.normal(0, wnamp, size=mask[0, 1] - mask[0, 0])
                wn2 = np.random.normal(0, wnamp, size=mask[1, 1] - mask[1, 0])
                stims[order] = np.concatenate(
                    (song[i][:mask[0,
                                   0]], song[i][mask[0, 0]:mask[0, 1]] + wn1,
                     song[i][mask[0, 1]:mask[1, 0]],
                     song[i][mask[1, 0]:mask[1, 1]] + wn2, song[i][mask[1,
                                                                        1]:]))
            elif k == 2:
                presentation[order]['gaps'] = blocks.tolist()
                wn1 = np.random.normal(0,
                                       wnamp,
                                       size=blocks[0, 1] - blocks[0, 0])
                wn2 = np.random.normal(0,
                                       wnamp,
                                       size=blocks[1, 1] - blocks[1, 0])
                stims[order] = np.concatenate(
                    (song[i][:blocks[0, 0]],
                     song[i][blocks[0, 0]:blocks[0, 1]] + wn1,
                     song[i][blocks[0, 1]:blocks[1, 0]],
                     song[i][blocks[1, 0]:blocks[1, 1]] + wn2,
                     song[i][blocks[1, 1]:]))
            elif k == 3:
                presentation[order]['gaps'] = blocks.tolist()
                mask = np.zeros((2, 2))
                mask[:, 0] = np.asarray([
                    list(ssyll.start[ssyll.motif == x])[0]
                    for x in range(1, 3)
                ])
                mask[:, 1] = np.asarray([
                    list(ssyll.end[ssyll.motif == x])[-1] for x in range(1, 3)
                ])
                mask = mask * Fs
                mask = mask.astype(int)
                wn1 = np.random.normal(0, wnamp, size=mask[0, 1] - mask[0, 0])
                wn2 = np.random.normal(0, wnamp, size=mask[1, 1] - mask[1, 0])
                temp = np.concatenate(
                    (song[i][:blocks[0, 0]],
                     song[i][blocks[0, 0]:blocks[0, 0] + len(fadein)] *
                     fadeout,
                     np.zeros(blocks[0, 1] - blocks[0, 0] - len(fadein) * 2),
                     song[i][blocks[0, 1] - len(fadein):blocks[0, 1]] * fadein,
                     song[i][blocks[0, 1]:blocks[1, 0]],
                     song[i][blocks[1, 0]:blocks[1, 0] + len(fadein)] *
                     fadeout,
                     np.zeros(blocks[1, 1] - blocks[1, 0] - len(fadein) * 2),
                     song[i][blocks[1, 1] - len(fadein):blocks[1, 1]] * fadein,
                     song[i][blocks[1, 1]:]))
                stims[order] = np.concatenate(
                    (temp[:mask[0, 0]], temp[mask[0, 0]:mask[0, 1]] + wn1,
                     temp[mask[0, 1]:mask[1, 0]],
                     temp[mask[1, 0]:mask[1, 1]] + wn2, temp[mask[1, 1]:]))
            elif k == 4:
                presentation[order]['gaps'] = blocks.tolist()
                stims[order] = np.concatenate(
                    (song[i][:blocks[0, 0]],
                     song[i][blocks[0, 0]:blocks[0, 0] + len(fadein)] *
                     fadeout,
                     np.zeros(blocks[0, 1] - blocks[0, 0] - len(fadein) * 2),
                     song[i][blocks[0, 1] - len(fadein):blocks[0, 1]] * fadein,
                     song[i][blocks[0, 1]:blocks[1, 0]],
                     song[i][blocks[1, 0]:blocks[1, 0] + len(fadein)] *
                     fadeout,
                     np.zeros(blocks[1, 1] - blocks[1, 0] - len(fadein) * 2),
                     song[i][blocks[1, 1] - len(fadein):blocks[1, 1]] * fadein,
                     song[i][blocks[1, 1]:]))
            elif k == 5:
                presentation[order]['gaps'] = blocks.tolist()
                wn1 = np.random.normal(0,
                                       wnamp,
                                       size=blocks[0, 1] - blocks[0, 0])
                wn2 = np.random.normal(0,
                                       wnamp,
                                       size=blocks[1, 1] - blocks[1, 0])
                stims[order] = np.concatenate(
                    (song[i][:blocks[0, 0]], wn1, song[i][blocks[0,
                                                                 1]:blocks[1,
                                                                           0]],
                     wn2, song[i][blocks[1, 1]:]))
            elif k == 6:
                presentation[order]['gaps'] = blocks.tolist()
                wn1 = np.random.normal(0,
                                       wnamp,
                                       size=blocks[0, 1] - blocks[0, 0])
                wn2 = np.random.normal(0,
                                       wnamp,
                                       size=blocks[1, 1] - blocks[1, 0])
                temp = np.zeros(len(song[i]))
                stims[order] = np.concatenate(
                    (temp[:blocks[0, 0]], wn1, temp[blocks[0, 1]:blocks[1, 0]],
                     wn2, temp[blocks[1, 1]:]))


#            elif k==7:
#                presentation[order]['gaps'] = blocks.tolist()
#                wn1 = np.random.normal(0,wnamp,size=(blocks[0,1]-blocks[0,0]-len(fadein)*2)-800)
#                wn2 = np.random.normal(0,wnamp,size=(blocks[1,1]-blocks[1,0]-len(fadein)*2)-800)
#                stims[order] = np.concatenate((song[i][:blocks[0,0]],
#                                                 song[i][blocks[0,0]:blocks[0,0]+len(fadein)]*fadeout,
#                                                 np.zeros(400),
#                                                 wn1,
#                                                 np.zeros(400),
#                                                 song[i][blocks[0,1]-len(fadein):blocks[0,1]]*fadein,
#                                                 song[i][blocks[0,1]:blocks[1,0]],
#                                                 song[i][blocks[1,0]:blocks[1,0]+len(fadein)]*fadeout,
#                                                 np.zeros(400),
#                                                 wn2,
#                                                 np.zeros(400),
#                                                 song[i][blocks[1,1]-len(fadein):blocks[1,1]]*fadein,
#                                                 song[i][blocks[1,1]:]))
            else:
                print("Undefined stim type")
    scale = np.max(stims)
    pstims = np.zeros((size, len(song[0]), 2))
    for i in range(len(pstims)):
        temp = (stims[i] / scale) * (2**15 - 1)
        pstims[i] = ss.pulsestim(temp)

    return (Fs, stype, present_order, presentation, pstims, songname)
Example #7
0
def make_stims(stimset, seed, dBval):
    if '180B' in stimset or '178B' in stimset:
        song, Fs, songname = ss.dBclean('../178B', 54)
        song2, Fs, songname2 = ss.dBclean('../180B', 54)
        song = np.concatenate((song, song2), 0)
        songname = songname + songname2
    else:
        song, Fs, songname = ss.dBclean(stimset)
    stype = [
        'continuous', 'continuousnoise1', 'continuousnoise2', 'gap1', 'gap2',
        'gapnoise1', 'gapnoise2', 'noise1', 'noise2', 'continuousmask',
        'gapmask'
    ]
    syllables = pd.read_csv('../gap-locations.csv')
    conditions = len(stype)
    trials = 10
    size = len(songname) * conditions
    present_order = sdk.seqorder(size, trials)
    presentation = {}
    stims = []
    np.random.seed(seed)
    for i in range(len(songname)):
        ssyll = syllables.loc[syllables.song == songname[i]]
        #sg = np.random.choice(ssyll.iloc[1:-1].index,2,replace=False)
        blocks = np.zeros((2, 2))
        #print(ssyll.start1.values[0])
        #print(ssyll.start2)
        blocks[:, 0] = np.asarray(
            (ssyll.start1.values[0], ssyll.start2.values[0]))
        blocks[:, 1] = np.asarray((ssyll.end1.values[0], ssyll.end2.values[0]))
        blocks = blocks * Fs
        blocks = blocks.astype(int)
        gsize = int(0.1 * Fs)
        wnamp = 25000
        wndB = dBval
        if blocks[0, 1] - blocks[0, 0] > gsize:
            #middle = np.mean(blocks,1)
            #blocks[0,0] = middle[0]-int(gsize/2)-50
            blocks[0, 1] = blocks[0, 0] + gsize
        if blocks[1, 1] - blocks[1, 0] > gsize:
            #middle = np.mean(blocks,1)
            #blocks[1,0] = middle[1]-int(gsize/2)-50
            blocks[1, 1] = blocks[1, 0] + gsize
        N = 120
        ix = np.arange(N * 3)
        signal = np.cos(2 * np.pi * ix / float(N * 2)) * 0.5 + 0.5
        fadein = signal[120:240]
        fadeout = signal[0:120]
        wn1 = np.random.normal(0, wnamp, size=blocks[0, 1] - blocks[0, 0])
        wn1 = (wn1 / rms(wn1)) * scale(wndB)
        wn2 = np.random.normal(0, wnamp, size=blocks[1, 1] - blocks[1, 0])
        wn2 = (wn2 / rms(wn2)) * scale(wndB)
        mask = np.random.normal(0, wnamp, size=len(song[i]))
        mask = (mask / rms(mask)) * scale(wndB)
        mN = 1000
        mix = np.arange(mN * 3)
        msignal = np.cos(2 * np.pi * mix / float(mN * 2)) * 0.5 + 0.5
        mfadein = msignal[1000:2000] * np.random.normal(0, wnamp, size=1000)
        mfadein = (mfadein / rms(mfadein)) * scale(wndB)
        mfadeout = msignal[0:1000] * np.random.normal(0, wnamp, size=1000)
        mfadeout = (mfadeout / rms(mfadeout)) * scale(wndB)
        for k in range(conditions):
            order = (i * conditions) + k
            presentation[order] = {
                "song": songname[i],
                "type": stype[k],
            }
            if k == 0:
                stims.append(song[i])
            elif k == 1:
                presentation[order]['gaps'] = blocks[0].tolist()
                stims.append(
                    np.concatenate((song[i][:blocks[0, 0]],
                                    song[i][blocks[0, 0]:blocks[0, 1]] + wn1,
                                    song[i][blocks[0, 1]:])))
            elif k == 2:
                presentation[order]['gaps'] = blocks[1].tolist()
                stims.append(
                    np.concatenate((song[i][:blocks[1, 0]],
                                    song[i][blocks[1, 0]:blocks[1, 1]] + wn2,
                                    song[i][blocks[1, 1]:])))
            elif k == 3:
                presentation[order]['gaps'] = blocks[0].tolist()
                stims.append(
                    np.concatenate(
                        (song[i][:blocks[0, 0]],
                         song[i][blocks[0, 0]:blocks[0, 0] + len(fadein)] *
                         fadeout,
                         np.zeros(blocks[0, 1] - blocks[0, 0] -
                                  len(fadein) * 2),
                         song[i][blocks[0, 1] - len(fadein):blocks[0, 1]] *
                         fadein, song[i][blocks[0, 1]:])))
            elif k == 4:
                presentation[order]['gaps'] = blocks[1].tolist()
                stims.append(
                    np.concatenate(
                        (song[i][:blocks[1, 0]],
                         song[i][blocks[1, 0]:blocks[1, 0] + len(fadein)] *
                         fadeout,
                         np.zeros(blocks[1, 1] - blocks[1, 0] -
                                  len(fadein) * 2),
                         song[i][blocks[1, 1] - len(fadein):blocks[1, 1]] *
                         fadein, song[i][blocks[1, 1]:])))
            elif k == 5:
                presentation[order]['gaps'] = blocks[0].tolist()
                stims.append(
                    np.concatenate(
                        (song[i][:blocks[0, 0]], wn1, song[i][blocks[0, 1]:])))
            elif k == 6:
                presentation[order]['gaps'] = blocks[1].tolist()
                stims.append(
                    np.concatenate(
                        (song[i][:blocks[1, 0]], wn2, song[i][blocks[1, 1]:])))
            elif k == 7:
                presentation[order]['gaps'] = blocks[0].tolist()
                temp = np.zeros(len(song[i]))
                stims.append(
                    np.concatenate(
                        (temp[:blocks[0, 0]], wn1, temp[blocks[0, 1]:])))
            elif k == 8:
                presentation[order]['gaps'] = blocks[1].tolist()
                temp = np.zeros(len(song[i]))
                stims.append(
                    np.concatenate(
                        (temp[:blocks[1, 0]], wn2, temp[blocks[1, 1]:])))
            elif k == 9:
                stims.append(
                    np.concatenate((mfadein, song[i] + mask, mfadeout)))
            elif k == 10:
                stims.append(
                    np.concatenate(
                        (mfadein, song[i][:blocks[1, 0]] + mask[:blocks[1, 0]],
                         song[i][blocks[1, 0]:blocks[1, 0] + len(fadein)] *
                         fadeout +
                         mask[blocks[1, 0]:blocks[1, 0] + len(fadein)],
                         mask[blocks[1, 0] + len(fadein):blocks[1, 1] -
                              len(fadein)],
                         song[i][blocks[1, 1] - len(fadein):blocks[1, 1]] *
                         fadein +
                         mask[blocks[1, 1] - len(fadein):blocks[1, 1]],
                         song[i][blocks[1, 1]:] + mask[blocks[1, 1]:],
                         mfadeout)))
            else:
                print("Undefined stim type")
    stims = np.asarray(stims)
    #scale = np.max(stims)
    #pstims = np.zeros((size,len(song[0]),2))
    #for i in range(len(pstims)):
    #temp = (stims[i]/scale)*(2**15-1)
    #pstims[i] = ss.pulsestim(temp)
    #pstims[i] = ss.pulsestim(stims[i])

    return (Fs, stype, present_order, presentation, stims, songname)