예제 #1
0
def get_target_grid(conn,
                    dataset_name,
                    configdata_id,
                    configprocess_id,
                    He,
                    print_target=False):

    # get source values
    x1, x2, x3, p2, nsources = get_target_values(conn, dataset_name,
                                                 configdata_id, He)

    # get names of config tables belonging to dataset
    configprocess_name = read_columns(conn=conn,
                                      table_name='datasets',
                                      column_names=['configprocess_name'],
                                      condition_column_name=['dataset_name'],
                                      condition_value=[dataset_name])
    configprocess_name = configprocess_name[0]

    # get grid id and mpos id
    grid_id, mpos_id = read_columns(conn=conn,
                                    table_name=configprocess_name,
                                    column_names=['grid_id', 'mpos_id'],
                                    condition_column_name=['id'],
                                    condition_value=[configprocess_id])
    # get aperture value
    ap = read_columns(conn=conn,
                      table_name='mpos',
                      column_names=['aperture'],
                      condition_column_name=['id'],
                      condition_value=[mpos_id])

    ap = ap[0]
    # get acoular grid
    grid = get_acoular_grid(conn, grid_id, ap)

    # build map
    if nsources == 1:
        target_map = zeros((grid.nxsteps, grid.nysteps),
                           dtype=float32)  # initialize map with zeros
        grid_index = grid.index(x1 * ap, x2 * ap)
        target_map[grid_index[0], grid_index[1]] = p2

    if print_target:
        extent = (grid.x_min, grid.x_max, grid.y_min, grid.y_max)
        print(extent)
        figure(1)
        imshow(L_p(target_map).T,
               origin='lower',
               vmax=L_p(target_map.max()),
               vmin=L_p(target_map.max()) - 10,
               extent=extent)
        plot(x1 * ap, x2 * ap, 'rx')
        colorbar()
        show()

    return target_map, grid_index, p2, x1, x2, x3, nsources
예제 #2
0
def run():

    from os import path
    from acoular import __file__ as bpath, MicGeom, WNoiseGenerator, PointSource,\
     Mixer, WriteH5, TimeSamples, PowerSpectra, RectGrid, SteeringVector,\
     BeamformerBase, L_p
    from pylab import figure, plot, axis, imshow, colorbar, show

    # set up the parameters
    sfreq = 51200
    duration = 1
    nsamples = duration * sfreq
    micgeofile = path.join(path.split(bpath)[0], 'xml', 'array_64.xml')
    h5savefile = 'three_sources.h5'

    # generate test data, in real life this would come from an array measurement
    mg = MicGeom(from_file=micgeofile)
    n1 = WNoiseGenerator(sample_freq=sfreq, numsamples=nsamples, seed=1)
    n2 = WNoiseGenerator(sample_freq=sfreq,
                         numsamples=nsamples,
                         seed=2,
                         rms=0.7)
    n3 = WNoiseGenerator(sample_freq=sfreq,
                         numsamples=nsamples,
                         seed=3,
                         rms=0.5)
    p1 = PointSource(signal=n1, mics=mg, loc=(-0.1, -0.1, 0.3))
    p2 = PointSource(signal=n2, mics=mg, loc=(0.15, 0, 0.3))
    p3 = PointSource(signal=n3, mics=mg, loc=(0, 0.1, 0.3))
    pa = Mixer(source=p1, sources=[p2, p3])
    wh5 = WriteH5(source=pa, name=h5savefile)
    wh5.save()

    # analyze the data and generate map

    ts = TimeSamples(name=h5savefile)
    ps = PowerSpectra(time_data=ts, block_size=128, window='Hanning')

    rg = RectGrid( x_min=-0.2, x_max=0.2, y_min=-0.2, y_max=0.2, z=0.3, \
    increment=0.01 )
    st = SteeringVector(grid=rg, mics=mg)

    bb = BeamformerBase(freq_data=ps, steer=st)
    pm = bb.synthetic(8000, 3)
    Lm = L_p(pm)

    # show map
    imshow( Lm.T, origin='lower', vmin=Lm.max()-10, extent=rg.extend(), \
    interpolation='bicubic')
    colorbar()

    # plot microphone geometry
    figure(2)
    plot(mg.mpos[0], mg.mpos[1], 'o')
    axis('equal')

    show()
예제 #3
0
def audio_csv_extraction(filepath, trackname, st, firstframe):

    if DETAILEDINFO_LVL >= 3:
        print('[Azimuth, Elevation], max_value')

    ts = WavSamples(name=filepath,start=firstframe*NUM,stop=(firstframe+1)*NUM)
    ps = PowerSpectra(time_data=ts, block_size=512, window='Hanning')
    be = BeamformerEig(freq_data=ps, steer=st, r_diag=True, n=3)


    # be = BeamformerBase(freq_data=ps, steer=st, r_diag=True)

    # bb = BeamformerBase(freq_data=ps, steer=st)
    # bo = BeamformerOrth(beamformer=be, eva_list=[3])
    
# Extraktion von Framenummer (Spalte 0), Geräuschklasse (Spalte 1), Azi (Spalte 3) und Ele (Spalte 4) aus .csv-Datei
    csvpath = CSV_DIR+trackname+".csv"
    rawdata = loadtxt(open(csvpath, "rb"), dtype="int32", delimiter=",", usecols=(0,1,3,4))


    if TRAINING or JUST_1SOURCE_FRAMES:
        labeldata = rawdata = rm_2sources_frames(rawdata)


    if THRESHOLD_FILTER:
        soundpressure = zeros((600,1))
        
    ## Sound Pressure Level ##
        wavsamples = WavSamples(name = filepath).data[:,3]
        for frameindex, _ in enumerate(soundpressure[:,0]):
            soundpressure[frameindex,0] = sum(wavsamples[frameindex*NUM:(frameindex+1)*NUM]**2)/NUM
        spl = L_p(soundpressure[:,0])
    ##########################

        threshold = threshold_calculator(spl)

    ## Liste der per Threshold gefilterten Frames ##
        active_frames = []
        for index, frame in enumerate(spl):
            if frame > threshold:
                active_frames.append(index)
    ################################################
        # active_frames weiterhin eine Liste, aus der man Elemente
        # auch zwischendrin löschen kann
        # thrdata = array(active_frames).reshape((len(active_frames),1))

        thrdata = []
        for ind, frame in enumerate(rawdata[:,0]):
            if frame in active_frames:
                thrdata.append(rawdata[ind,:])
            
        labeldata = array(thrdata)

    if not(TRAINING or THRESHOLD_FILTER):
        labeldata = rawdata


    return ts, be, labeldata
예제 #4
0
    def do_beamforming(self, mic_data):
        """ Beamforming using Acoular """
        mg, rg, st = self.get_acoular_essentials()

        count = 0
        #Divide audio samples as per frame rate (10fps) and do beamforming
        for s_time in tqdm(
                np.arange(self.start_time, self.end_time, self.interval)):

            audio_data = mic_data[:,
                                  int(s_time *
                                      self.sample_rate):int((s_time +
                                                             self.interval) *
                                                            self.sample_rate)]
            audio_data = np.transpose(audio_data)

            if audio_data.shape[0] == 0:
                continue

            #Acoular needs audio input through .h5 file
            target_file = self.outfile + '/temp.h5'

            if os.path.exists(target_file):
                os.remove(target_file)

            with h5py.File(target_file, 'w') as data_file:
                data_file.create_dataset('time_data', data=audio_data)
                data_file['time_data'].attrs.__setitem__(
                    'sample_freq', self.sample_rate)

            #.h5 file has issues with closing. Change 'ulimit' if not working

            ts = TimeSamples(name=target_file)
            ps = PowerSpectra(time_data=ts,
                              block_size=128,
                              window='Hanning',
                              overlap='50%')
            bb = BeamformerEig(freq_data=ps, steer=st)

            pm = bb.synthetic(self.freq_query, self.octave_band)
            Lm = L_p(pm)

            if count == 0:
                bf_data = np.zeros(
                    (Lm.shape[0], Lm.shape[1],
                     len(
                         np.arange(self.start_time, self.end_time,
                                   self.interval))))
                bf_data[:, :, count] = Lm
            else:
                bf_data[:, :, count] = Lm

            count += 1

        # remove temp.h5 file after its finished
        os.remove(target_file)

        return bf_data, rg
예제 #5
0
# this provides the cross spectral matrix and defines the beamformer
# usually, another type of beamformer (e.g. CLEAN-SC) would be more appropriate
# to be really fast, we restrict ourselves to only 10 frequencies
# in the range 2000 - 6000 Hz (5*400 - 15*400)
#===============================================================================

f = EigSpectra(time_data=t, window='Hanning', overlap='50%', block_size=128, \
    ind_low=5, ind_high=15)
b = BeamformerBase(freq_data=f, grid=g, mpos=m, r_diag=True, c=346.04)

#===============================================================================
# reads the data, finds the maximum value (to properly scale the views)
#===============================================================================

map = b.synthetic(4000,1)
L1 = L_p(map)
mx = L1.max()

#===============================================================================
# print out the result integrated over an 3d-sector of the 3d map
#===============================================================================

print(L_p(b.integrate((-0.3,-0.1,0.58,-0.1,0.1,0.78)))[f.ind_low:f.ind_high])

#===============================================================================
# displays the 3d view
#===============================================================================

X,Y,Z = mgrid[g.x_min:g.x_max:1j*g.nxsteps,\
            g.y_min:g.y_max:1j*g.nysteps,\
            g.z_min:g.z_max:1j*g.nzsteps]
예제 #6
0
bdp6432Res  = bdp6432.synthetic(cfreq,1)

#64 Bit
bd6464 = BeamformerDamas(beamformer=bb64, n_iter=100, psf_precision='float64')
bd6464Res = bd6464.synthetic(cfreq,1)
bc6464 = BeamformerClean(beamformer=bb64, psf_precision='float64')
bc6464Res = bc6464.synthetic(cfreq,1)
bdp6464 = BeamformerDamasPlus(beamformer=bb64, n_iter=100, psf_precision='float64')
bdp6464Res  = bdp6464.synthetic(cfreq,1)



#===============================================================================
# plot result maps for different beamformers in frequency domain
#===============================================================================
i1 = 1
for b in (bb32, bd3232, bc3232, bdp3232, bd3264, bc3264, bdp3264,
          bb64, bd6432, bc6432, bdp6432, bd6464, bc6464, bdp6464):
    subplot(2, 7, i1)
    i1 += 1
    res = b.synthetic(cfreq,1)
    mx = L_p(res.max())
    imshow(L_p(res.T), vmax=mx, vmin=mx-15, 
           interpolation='nearest', extent=g.extend())
    print(b.steer)
    colorbar()
    title(b.__class__.__name__ + b.precision,fontsize='small')


show()
        # zugehörige .csv-Datei, um aktive Frames zu plotten
        _name = wavfile.name[:-4]
        csvfile = CSV_DIR + _name + '.csv'
        csv_frames = np.loadtxt(open(csvfile, "rb"),
                                dtype="int32",
                                delimiter=",",
                                usecols=(0))

        ts = WavSamples(name=wavfile.path).data[:, 3]
        print(wavfile.name)
        for frameindex, _ in enumerate(soundpressure):
            soundpressure[frameindex] = np.sum(
                ts[frameindex * NUM:(frameindex + 1) * NUM]**2) / NUM
        frames = np.linspace(0, len(ts) / NUM, num=int(len(ts) / NUM))

        spl = L_p(soundpressure)

        fig1 = plt.subplot(211)

        threshold = threshold_calculator(spl)
        fig1.axhline(threshold)
        #fig1.axhline(threshold2, c='r')
        plt.plot(frames, spl)
        plt.setp(fig1.get_xticklabels())  #, visible=False)
        plt.title(wavfile.name + " 0:20 " + str(threshold))

        fig2 = plt.subplot(212)
        fig2.axhline(0.04)
        plt.plot(frames, spl / np.linalg.norm(spl))
        # plt.yscale('log')
        # AKTIVE Frames: Plot bekommt Hintergrundfarbe
예제 #8
0
n1 = WNoiseGenerator( sample_freq=sfreq, numsamples=nsamples, seed=1 )
n2 = WNoiseGenerator( sample_freq=sfreq, numsamples=nsamples, seed=2, rms=0.7 )
n3 = WNoiseGenerator( sample_freq=sfreq, numsamples=nsamples, seed=3, rms=0.5 )
p1 = PointSource( signal=n1, mpos=mg,  loc=(-0.1,-0.1,0.3) )
p2 = PointSource( signal=n2, mpos=mg,  loc=(0.15,0,0.3) )
p3 = PointSource( signal=n3, mpos=mg,  loc=(0,0.1,0.3) )
pa = Mixer( source=p1, sources=[p2,p3] )
wh5 = WriteH5( source=pa, name=h5savefile )
wh5.save()

# analyze the data and generate map
ts = TimeSamples( name=h5savefile )
ps = PowerSpectra( time_data=ts, block_size=128, window='Hanning' )
rg = RectGrid( x_min=-0.2, x_max=0.2, y_min=-0.2, y_max=0.2, z=0.3, \
increment=0.01 )
bb = BeamformerBase( freq_data=ps, grid=rg, mpos=mg )
pm = bb.synthetic( 8000, 3 )
Lm = L_p( pm )

# show map
imshow( Lm.T, origin='lower', vmin=Lm.max()-10, extent=rg.extend(), \
interpolation='bicubic')
colorbar()

# plot microphone geometry
figure(2)
plot(mg.mpos[0],mg.mpos[1],'o')
axis('equal')

show()
예제 #9
0
# create power spectrum
f = PowerSpectra(time_data=t, window='Hanning', overlap='50%', block_size=4096)

# get spectrum data
spectrum_data = real(f.csm[:, 0,
                           0])  # get power spectrum from cross-spectral matrix
freqs = f.fftfreq()  # FFT frequencies

# use barspectrum from acoular.tools to create third octave plot data
(f_borders, p, f_center) = barspectrum(spectrum_data, freqs, band, bar=True)
(f_borders_, p_, f_center_) = barspectrum(spectrum_data,
                                          freqs,
                                          band,
                                          bar=False)

# create figure with barspectra
figure(figsize=(20, 6))
title("Powerspectrum")
plot(f_borders, L_p(p), label="bar=True")
plot(f_borders_, L_p(p_), label="bar=False")
xlim(f_borders[0] * 2**(-1. / 6), f_borders[-1] * 2**(1. / 6))
ylim(50, 90)
xscale('symlog')
label_freqs = [str(int(_)) for _ in f_center]  # create string labels
xticks(f_center, label_freqs)
xlabel('f in Hz')
ylabel('SPL in dB')
grid(True)
legend()
show()
예제 #10
0
파일: example2.py 프로젝트: xinkez/acoular
fi = FiltFiltOctave(source=t, band=freq, fraction='Third octave')
bt = BeamformerTimeSq(source=fi, grid=g, mpos=m, r_diag=True, c=c0)
avgt = TimeAverage(source=bt,
                   naverage=int(sfreq * tmax / 16))  # 16 single images
cacht = TimeCache(source=avgt)  # cache to prevent recalculation
map2 = zeros(g.shape)  # accumulator for average
# plot single frames
figure(1, (8, 7))
i = 1
for res in cacht.result(1):
    res0 = res[0].reshape(g.shape)
    map2 += res0  # average
    i += 1
    subplot(4, 4, i)
    mx = L_p(res0.max())
    imshow(L_p(transpose(res0)), vmax=mx, vmin=mx-10, interpolation='nearest',\
        extent=g.extend(), origin='lower')
    colorbar()
map2 /= i

subplot(4, 4, 1)
text(0.4, 0.25, 'fixed\nfocus', fontsize=15, ha='center')
axis('off')
tight_layout()

#===============================================================================
# moving focus time domain beamforming
#===============================================================================

# new grid needed, the trajectory starts at origin and is oriented towards +x
예제 #11
0
# to be really fast, we restrict ourselves to only 10 frequencies
# in the range 2000 - 6000 Hz (5*400 - 15*400)
#===============================================================================

f = PowerSpectra(time_data=t, window='Hanning', overlap='50%', block_size=128, \
    ind_low=5, ind_high=15)
env = Environment(c=346.04)
st = SteeringVector(grid=g, mics=m, env=env)
b = BeamformerBase(freq_data=f, steer=st, r_diag=True)

#===============================================================================
# reads the data, finds the maximum value (to properly scale the views)
#===============================================================================

map = b.synthetic(4000,1)
L1 = L_p(map)
mx = L1.max()

#===============================================================================
# print out the result integrated over an 3d-sector of the 3d map
#===============================================================================

print(L_p(b.integrate((-0.3,-0.1,0.58,-0.1,0.1,0.78)))[f.ind_low:f.ind_high])

#===============================================================================
# displays the 3d view
#===============================================================================

X,Y,Z = mgrid[g.x_min:g.x_max:1j*g.nxsteps,\
            g.y_min:g.y_max:1j*g.nysteps,\
            g.z_min:g.z_max:1j*g.nzsteps]
예제 #12
0
def fbeamextraction(mg, rg, ts, be, firstframe, lastframe, csvdata, _name,
                    fbeamplot, fbeamplot_2ndSrc, algoplot, algoplot_2ndSrc):

    #####################  DeepLearning-Matrix (Framewise)  #########################
    ################    Elevation     Azimuth    Frequenzbänder   ###################
    DL_Matrix = zeros((NPOINTS_ELE, NPOINTS_AZI, len(FREQBANDS)),
                      dtype="float32")  ##
    #################################################################################

    for frame in range(firstframe, lastframe):
        if frame in csvdata[:, 0]:
            fr_index = where(csvdata[:, 0] == frame)[0][0]
            if DETAILEDINFO_LVL >= 1:
                print('  FRAME: ', frame - firstframe, ' (', frame, ')')
            ts.start = frame * NUM
            ts.stop = (frame + 1) * NUM

            # Zur Berechnung des Mittelwerts der Richtungswinkel
            if not (TRAINING):
                azis = list(zeros(len(FREQBANDS)))
                azic = list(zeros(len(FREQBANDS)))
                eles = list(zeros(len(FREQBANDS)))
                elec = list(zeros(len(FREQBANDS)))
                azis_2nd = list(zeros(len(FREQBANDS)))
                azic_2nd = list(zeros(len(FREQBANDS)))
                eles_2nd = list(zeros(len(FREQBANDS)))
                elec_2nd = list(zeros(len(FREQBANDS)))

#%%  1. Quelle  ##############################
# Zur Angle-Prediction ohne händischem Algo
            glob_maxval = 0
            glob_maxidx = 0
            for freq_index, freq in enumerate(FREQBANDS):

                be.n = -1  #Eigenwerte sind der Größe nach sortiert! -> größter Eigenwert (default)
                Lm = L_p(be.synthetic(freq, 3)).reshape(rg.shape).flatten()

                DL_Matrix[:, :, freq_index] = Lm.reshape(rg.shape).T

                if PLOTBEAMMAPS or DETAILEDINFO_LVL >= 3 or not (TRAINING):
                    max_idx = argmax(Lm.flatten(
                    ))  # position in grid with max source strength
                    max_value = amax(Lm.flatten())
                    if glob_maxval < max_value:  # TODO: 'and freq != 500:' !?!
                        glob_maxidx = max_idx
                        glob_maxval = max_value
                    # min_value = amin(Lm.flatten())

                    max_cartcoord = rg.gpos[:, max_idx]

                    temp_azi = arctan2(sin(rg.phi[max_idx]),
                                       cos(rg.phi[max_idx]))
                    temp_ele = pi / 2 - rg.theta[max_idx]

                    max_polcoord = [rad2deg(temp_azi), rad2deg(temp_ele)]

                    azis[freq_index] = sin(temp_azi)
                    azic[freq_index] = cos(temp_azi)
                    eles[freq_index] = sin(temp_ele)
                    elec[freq_index] = cos(temp_ele)

                if PLOTBEAMMAPS:
                    #### 3D-Plot ###
                    fig = plt.figure()
                    ax = fig.add_subplot(121, projection='3d')
                    ax.set_xlabel('x-Achse')
                    ax.set_ylabel('y-Achse')
                    ax.set_zlabel('z-Achse')
                    ax.set_xlim(-1, 1)
                    ax.set_ylim(-1, 1)
                    ax.set_zlim(-1, 1)
                    cmhot = plt.get_cmap("hot_r")
                    if frame == firstframe:
                        ax.scatter(rg.gpos[0],
                                   rg.gpos[1],
                                   -rg.gpos[2],
                                   s=50,
                                   c=Lm,
                                   cmap=cmhot,
                                   marker='.')
                    # Mikros
                    ax.scatter(mg.mpos[0], mg.mpos[1], mg.mpos[2], 'o')
                    ax.scatter(max_cartcoord[0],
                               max_cartcoord[1],
                               max_cartcoord[2],
                               s=60,
                               c='blue')
                    ### 3D-Plot Ende ###

                    ### 2D-Map ###
                    ax2 = fig.add_subplot(122)
                    ax2.set_xticks(arange(-180, 270, step=90))
                    ax2.set_yticks(arange(-90, 135, step=45))
                    cax2 = ax2.imshow(Lm.reshape(rg.shape).T,
                                      cmap=cmhot,
                                      vmin=Lm.max() - 6,
                                      vmax=Lm.max(),
                                      extent=[-180, 180, -90, 90])
                    ax2.plot(max_polcoord[0], max_polcoord[1], 'bo')

                    fig.set_figheight(4)
                    fig.set_figwidth(8)
                    fig.colorbar(cax2)
                    fig.tight_layout(pad=3.0)
                    fig.suptitle(_name + ' ' + str(frame) + ' ' + str(freq))
                    plt.show()
        ### 2D-Map Ende ###

                if DETAILEDINFO_LVL >= 3:
                    print('   {:4d} [{:7.2f}, {:7.2f}] {}'.format(
                        freq, round(max_polcoord[0], 2),
                        round(max_polcoord[1], 2), round(max_value, 2)))
                    #print('   ',freq, max_cartcoord, max_value)

            if DETAILEDINFO_LVL >= 2 and TRAINING:
                print("   .csv-Values: Class  Azi  Ele")
                print("                ", '{:4d}'.format(csvdata[fr_index, 1]),
                      '{:4d}'.format(csvdata[fr_index, 2]),
                      '{:4d}'.format(csvdata[fr_index, 3]))

            if TRAINING:
                feature_dict = {
                    'inputmap': _float_list_feature(DL_Matrix),
                    'class': _int64_feature(csvdata[fr_index, 1]),
                    'azi': _int64_feature(csvdata[fr_index, 2]),
                    'ele': _int64_feature(csvdata[fr_index, 3]),
                }
            if not (TRAINING):
                # Prediction nur übers globale Maximum
                azi_pred = arctan2(sin(rg.phi[glob_maxidx]),
                                   cos(rg.phi[glob_maxidx]))
                ele_pred = pi / 2 - rg.theta[glob_maxidx]
                fbeamplot.append([frame, rad2deg(azi_pred), rad2deg(ele_pred)])

                # Calculation per Algorithmus (basierend auf Ergebnissen des fbeamformings)
                azi_algo, ele_algo = angle_calc_algo(azis, azic, eles, elec)
                algoplot.append([frame, rad2deg(azi_algo), rad2deg(ele_algo)])

                feature_dict = {'inputmap': _float_list_feature(DL_Matrix)}

            yield feature_dict

            #%%  2. Quelle  ##############################
            # Nur, wenn nicht bereits am Ende des Arrays (wenn bei letztem aktiven Frame nur 1 Quelle)
            if not (fr_index + 1 == len(csvdata)):

                if not (JUST_1SOURCE_FRAMES
                        or TRAINING) and (frame == csvdata[fr_index + 1, 0]):
                    glob_maxval = 0
                    glob_maxidx = 0

                    if DETAILEDINFO_LVL >= 1:
                        print('  FRAME: ', frame - firstframe, ' (', frame,
                              '), 2nd Src')

                    for freq_index, freq in enumerate(FREQBANDS):

                        be.n = -2  # zweitgrößter Eigenwert -> zweitstärkste Quelle
                        Lm = L_p(be.synthetic(freq,
                                              3)).reshape(rg.shape).flatten()
                        DL_Matrix[:, :, freq_index] = Lm.reshape(rg.shape).T

                        max_idx = argmax(Lm.flatten(
                        ))  # position in grid with max source strength
                        max_value = amax(Lm.flatten())
                        if glob_maxval < max_value:  # TODO: 'and freq != 500:' !?!
                            glob_maxidx = max_idx
                            glob_maxval = max_value

                        max_cartcoord = rg.gpos[:, max_idx]

                        temp_azi = arctan2(sin(rg.phi[max_idx]),
                                           cos(rg.phi[max_idx]))
                        temp_ele = pi / 2 - rg.theta[max_idx]

                        max_polcoord = [rad2deg(temp_azi), rad2deg(temp_ele)]

                        azis_2nd[freq_index] = sin(temp_azi)
                        azic_2nd[freq_index] = cos(temp_azi)
                        eles_2nd[freq_index] = sin(temp_ele)
                        elec_2nd[freq_index] = cos(temp_ele)

                        if PLOTBEAMMAPS:
                            #### 3D-Plot ###
                            fig = plt.figure()
                            ax = fig.add_subplot(121, projection='3d')
                            ax.set_xlabel('x-Achse')
                            ax.set_ylabel('y-Achse')
                            ax.set_zlabel('z-Achse')
                            ax.set_xlim(-1, 1)
                            ax.set_ylim(-1, 1)
                            ax.set_zlim(-1, 1)
                            cmhot = plt.get_cmap("hot_r")
                            if frame == firstframe:
                                ax.scatter(rg.gpos[0],
                                           rg.gpos[1],
                                           -rg.gpos[2],
                                           s=50,
                                           c=Lm,
                                           cmap=cmhot,
                                           marker='.')
                            # Mikros
                            ax.scatter(mg.mpos[0], mg.mpos[1], mg.mpos[2], 'o')
                            ax.scatter(max_cartcoord[0],
                                       max_cartcoord[1],
                                       max_cartcoord[2],
                                       s=60,
                                       c='blue')
                            ### 3D-Plot Ende ###

                            ### 2D-Map ###
                            ax2 = fig.add_subplot(122)
                            ax2.set_xticks(arange(-180, 270, step=90))
                            ax2.set_yticks(arange(-90, 135, step=45))
                            cax2 = ax2.imshow(Lm.reshape(rg.shape).T,
                                              cmap=cmhot,
                                              vmin=Lm.max() - 6,
                                              vmax=Lm.max(),
                                              extent=[-180, 180, -90, 90])
                            ax2.plot(max_polcoord[0], max_polcoord[1], 'bo')

                            fig.set_figheight(4)
                            fig.set_figwidth(8)
                            fig.colorbar(cax2)
                            fig.tight_layout(pad=3.0)
                            fig.suptitle(_name + ' (Frame:' + str(frame) +
                                         ', Freq:' + str(freq) +
                                         ') 2nd Source')
                            plt.show()
                ### 2D-Map Ende ###

                        if DETAILEDINFO_LVL >= 3:
                            print('   {:4d} [{:7.2f}, {:7.2f}] {} (2nd Src)'.
                                  format(freq, round(max_polcoord[0], 2),
                                         round(max_polcoord[1], 2),
                                         round(max_value, 2)))
                            #print('   ',freq, max_cartcoord, max_value)

                    # Prediction nur übers globale Maximum
                    azi_pred_2nd = arctan2(sin(rg.phi[glob_maxidx]),
                                           cos(rg.phi[glob_maxidx]))
                    ele_pred_2nd = pi / 2 - rg.theta[glob_maxidx]
                    fbeamplot_2ndSrc.append(
                        [frame,
                         rad2deg(azi_pred_2nd),
                         rad2deg(ele_pred_2nd)])

                    # Calculation per Algorithmus (basierend auf Ergebnissen des fbeamformings)
                    azi_algo_2nd, ele_algo_2nd = angle_calc_algo(
                        azis_2nd, azic_2nd, eles_2nd, elec_2nd)
                    algoplot_2ndSrc.append(
                        [frame,
                         rad2deg(azi_algo_2nd),
                         rad2deg(ele_algo_2nd)])

                    feature_dict = {'inputmap': _float_list_feature(DL_Matrix)}

                    yield feature_dict
예제 #13
0
object_name.configure_traits()
m = MicGeom(from_file='UCA8.xml')



import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from os import path
import acoular
from acoular import L_p, Calib, MicGeom, TimeSamples, \
RectGrid, BeamformerBase, EigSpectra, BeamformerOrth, BeamformerCleansc, \
MaskedTimeSamples, FiltFiltOctave, BeamformerTimeSq, TimeAverage, \
TimeCache, BeamformerTime, TimePower, BeamformerCMF, \
BeamformerCapon, BeamformerMusic, BeamformerDamas, BeamformerClean, \
BeamformerFunctional

object_name.configure_traits()
m = MicGeom(from_file='UCA8.xml')

m = MicGeom(from_file='UCA8.xml')
g = RectGrid(x_min=-0.8, x_max=-0.2, y_min=-0.1, y_max=0.3, z=0.8, increment=0.01)
t1 = TimeSamples(name='cry_n0000001.wav')
f1 = EigSpectra(time_data=t1, block_size=256, window="Hanning", overlap='75%')
e1 = BeamformerBase(freq_data=f1, grid=g, mpos=m, r_diag=False)
fr = 4000
L1 = L_p(e1.synthetic(fr, 0))

object_name.configure_traits()
m = MicGeom(from_file='UCA8.xml')
예제 #14
0
bo = BeamformerOrth(beamformer=be, eva_list=list(range(38,54)))

#===============================================================================
# save all beamformers in an external file
# important: import dump from cPickle !!!
#===============================================================================
all_bf = (bb0, bb1, bb2, bb3, bs0, bs1, bs2, bs3, bo)
fi = open('all_bf.sav','wb')
dump(all_bf,fi,-1) # uses newest pickle protocol -1 (default = 0)
fi.close()

#===============================================================================
# plot result maps for different beamformers in frequency domain
#===============================================================================
figure(1,(10,6))
i1 = 1 #no of subplot
for b in all_bf:
    subplot(3,4,i1)
    i1 += 1
    map = b.synthetic(cfreq,1)[:,0,:]
    mx = L_p(map.max())
    imshow(L_p(map.T), vmax=mx, vmin=mx-15, 
           interpolation='nearest', extent=(g.x_min,g.x_max,g.z_min,g.z_max),
           origin='lower')
    colorbar()
    title(b.__class__.__name__+'\n '+b.steer, size=10)

tight_layout()
# only display result on screen if this script is run directly
if __name__ == '__main__': show()
예제 #15
0
    t = PointSource(signal=n1, mpos=m, loc=(1, 0, 1))

    f = PowerSpectra(time_data=t,
                     window='Hanning',
                     overlap='50%',
                     block_size=4096)
    ###################################################################
    ### Plotting ###
    from pylab import figure, plot, show, xlim, ylim, xscale, xticks, xlabel, ylabel, grid, real
    from acoular import L_p

    band = 3  # octave: 1 ;   1/3-octave: 3
    (f_borders, p, f_center) = barspectrum(real(f.csm[:, 0, 0]), f.fftfreq(),
                                           band)

    label_freqs = [str(int(_)) for _ in f_center]

    figure(figsize=(20, 6))

    plot(f_borders, L_p(p))

    xlim(f_borders[0] * 2**(-1. / 6), f_borders[-1] * 2**(1. / 6))
    ylim(40, 90)

    xscale('symlog')
    xticks(f_center, label_freqs)
    xlabel('f in Hz')
    ylabel('SPL in dB')
    grid(True)
    show()
#===============================================================================
# Display views of setup and result.
# For each view, the values along the repsective axis are summed.
# Note that, while Acoular uses a left-oriented coordinate system,
# for display purposes, the z-axis is inverted, plotting the data in
# a right-oriented coordinate system.
#===============================================================================

fig = figure(1, (8, 8))

# plot the results

subplot(221)
map_z = sum(map, 2)
mx = L_p(map_z.max())
imshow(L_p(map_z.T),
       vmax=mx,
       vmin=mx - 20,
       origin='lower',
       interpolation='nearest',
       extent=(g.x_min, g.x_max, g.y_min, g.y_max))
xlabel('x')
ylabel('y')
title('Top view (xy)')

subplot(223)
map_y = sum(map, 1)
imshow(L_p(map_y.T),
       vmax=mx,
       vmin=mx - 20,
예제 #17
0
n1 = WNoiseGenerator( sample_freq=sfreq, numsamples=nsamples, seed=1 )
n2 = WNoiseGenerator( sample_freq=sfreq, numsamples=nsamples, seed=2, rms=0.7 )
n3 = WNoiseGenerator( sample_freq=sfreq, numsamples=nsamples, seed=3, rms=0.5 )
p1 = PointSource( signal=n1, mpos=mg,  loc=(-0.1,-0.1,0.3) )
p2 = PointSource( signal=n2, mpos=mg,  loc=(0.15,0,0.3) )
p3 = PointSource( signal=n3, mpos=mg,  loc=(0,0.1,0.3) )
pa = Mixer( source=p1, sources=[p2,p3] )
wh5 = WriteH5( source=pa, name=h5savefile )
wh5.save()

# analyze the data and generate map
ts = TimeSamples( name=h5savefile )
ps = PowerSpectra( time_data=ts, block_size=128, window='Hanning' )
rg = RectGrid( x_min=-0.2, x_max=0.2, y_min=-0.2, y_max=0.2, z=0.3, \
increment=0.01 )
bb = BeamformerBase( freq_data=ps, grid=rg, mpos=mg )
pm = bb.synthetic( 8000, 3 )
Lm = L_p( pm )

# show map
imshow( Lm.T, origin='lower', vmin=Lm.max()-10, extent=rg.extend(), \
interpolation='bicubic')
colorbar()

# plot microphone geometry
figure(2)
plot(mg.mpos[0],mg.mpos[1],'o')
axis('equal')

show()
예제 #18
0
btSq_ps_h5 = BeamformerTimeSq(source=mt1, grid=g, mpos=m, r_diag=True, c=c0)

avgt_ps = TimeAverage(source=bt_ps, naverage=int(sfreq * tmax / 2))
avgt_psSq = TimeAverage(source=btSq_ps, naverage=int(sfreq * tmax / 2))
avgt_ps_h5 = TimeAverage(source=bt_ps_h5, naverage=int(sfreq * tmax / 2))
avgt_psSq_h5 = TimeAverage(source=btSq_ps_h5, naverage=int(sfreq * tmax / 2))

#==============================================================================
#plot point source
#==============================================================================

figure(1)
for res in avgt_ps.result(1):
    res_ps = res[0].reshape(g.shape)
    subplot(2, 2, 1)
    mx = L_p(res_ps.max())
    imshow(L_p(transpose(res_ps)), vmax=mx, vmin=mx-10, interpolation='nearest',\
           extent=g.extend(), origin='lower')
    title("ps bft avgt")
    colorbar()
for res in avgt_ps_h5.result(1):
    res_ps = res[0].reshape(g.shape)
    subplot(2, 2, 2)
    mx = L_p(res_ps.max())
    imshow(L_p(transpose(res_ps)), vmax=mx, vmin=mx-10, interpolation='nearest',\
           extent=g.extend(), origin='lower')
    title("ps bft avgt h5")
    colorbar()
for res in avgt_psSq.result(1):
    res_ps = res[0].reshape(g.shape)
    subplot(2, 2, 3)
예제 #19
0
#colorbar()

# # hier muss man sich jetzt überlegen, wie man am Besten die sphärischen
# Datenpunkte plottet. Scatter ist eine Variante

x = rg.gpos[0]
y = rg.gpos[1]
z = rg.gpos[2]

summed_azi_x = 0.0
summed_azi_y = 0.0
summed_ele = 0.0
summed_max_v = 0.0
print('[Azimuth, Elevation], max_value')
for frame in range(0, FRAMES):
    Lm = L_p(next(gen)).reshape(
        rg.shape)  # get next block from generator pipeline
    max_idx = argmax(Lm.flatten())  # position in grid with max source strength
    max_cartcoord = rg.gpos[:, max_idx]

    fig = plt.figure(frame)
    ax = fig.add_subplot(121, projection='3d')
    ax.set_xlabel('x-Achse')
    ax.set_ylabel('y-Achse')
    ax.set_zlabel('z-Achse')
    ax.set_xlim(-1, 1)
    ax.set_ylim(-1, 1)
    ax.set_zlim(-1, 1)
    cmhot = plt.get_cmap("hot_r")

    if frame == 0:
        cax = ax.scatter(x, y, -z, s=50, c=Lm, cmap=cmhot, marker='.')
    print('### FRAME: ', frame - STARTFRAME, ' (', frame, ') ###')
    for freq_index, freq in enumerate(FREQBANDS):
        print('FREQ =', freq)
        ts.start = frame * NUM
        ts.stop = (frame + 1) * NUM

        result = zeros((4, rg.shape[0], rg.shape[1]))
        for i in range(4):
            be.n = i
            result[i] = be.synthetic(freq, 3)

        maxind = argmax(result.max((1, 2)))
        # WARUM IMMER MAXINDEX = 3 ???
        #        print('Result Beamforming: Maxindex = ', maxind)

        Lm = L_p(result[maxind]).reshape(rg.shape).flatten()

        max_idx = argmax(
            Lm.flatten())  # position in grid with max source strength
        max_cartcoord = rg.gpos[:, max_idx]

        max_idx = argmax(
            Lm.flatten())  # position in grid with max source strength
        max_value = amax(Lm.flatten())
        temp_azi = arctan2(sin(rg.phi[max_idx]), cos(rg.phi[max_idx]))
        temp_ele = pi / 2 - rg.theta[max_idx]

        max_polcoord = [rad2deg(temp_azi), rad2deg(temp_ele)]

        #### 3D-Plot ###
        # fig = plt.figure()
예제 #21
0
bcmf = BeamformerCMF(freq_data=f, grid=g, mpos=m, c=346.04, \
    method='LassoLarsBIC')
bl = BeamformerClean(beamformer=bb, n_iter=100)
bf = BeamformerFunctional(freq_data=f, grid=g, mpos=m, r_diag=False, c=346.04, \
    gamma=4)

#===============================================================================
# plot result maps for different beamformers in frequency domain
#===============================================================================
figure(1,(10,6))
i1 = 1 #no of subplot
for b in (bb, bc, be, bm, bl, bo, bs, bd, bcmf, bf):
    subplot(3,4,i1)
    i1 += 1
    map = b.synthetic(cfreq,1)
    mx = L_p(map.max())
    imshow(L_p(map.T), origin='lower', vmin=mx-15,
           interpolation='nearest', extent=g.extend())
    colorbar()
    title(b.__class__.__name__)

#===============================================================================
# delay and sum beamformer in time domain
# processing chain: beamforming, filtering, power, average
#===============================================================================
bt = BeamformerTime(source=t1, grid=g, mpos=m, c=346.04)
ft = FiltFiltOctave(source=bt, band=cfreq)
pt = TimePower(source=ft)
avgt = TimeAverage(source=pt, naverage = 1024)
cacht = TimeCache( source = avgt) # cache to prevent recalculation
                         r_diag=False,
                         c=346.04,
                         steer='inverse')
bb3Full = BeamformerBase(freq_data=f,
                         grid=g,
                         mpos=m,
                         r_diag=False,
                         c=346.04,
                         steer='true level')
bb4Full = BeamformerBase(freq_data=f,
                         grid=g,
                         mpos=m,
                         r_diag=False,
                         c=346.04,
                         steer='true location')
Lbb1Rem = L_p(bb1Rem.synthetic(4000, 1))
Lbb2Rem = L_p(bb2Rem.synthetic(4000, 1))
Lbb3Rem = L_p(bb3Rem.synthetic(4000, 1))
Lbb4Rem = L_p(bb4Rem.synthetic(4000, 1))
Lbb1Full = L_p(bb1Full.synthetic(4000, 1))
Lbb2Full = L_p(bb2Full.synthetic(4000, 1))
Lbb3Full = L_p(bb3Full.synthetic(4000, 1))
Lbb4Full = L_p(bb4Full.synthetic(4000, 1))

bf1Rem = BeamformerFunctional(freq_data=f,
                              grid=g,
                              mpos=m,
                              r_diag=True,
                              c=346.04,
                              steer='classic',
                              gamma=3)
예제 #23
0
bcmf = BeamformerCMF(freq_data=f, grid=g, mpos=m, c=346.04, \
    method='LassoLarsBIC')
bl = BeamformerClean(beamformer=bb, n_iter=100)
bf = BeamformerFunctional(freq_data=f, grid=g, mpos=m, r_diag=False, c=346.04, \
    gamma=4)

#===============================================================================
# plot result maps for different beamformers in frequency domain
#===============================================================================
figure(1, (10, 6))
i1 = 1  #no of subplot
for b in (bb, bc, be, bm, bl, bo, bs, bd, bcmf, bf):
    subplot(3, 4, i1)
    i1 += 1
    map = b.synthetic(cfreq, 1)
    mx = L_p(map.max())
    imshow(L_p(map.T),
           origin='lower',
           vmin=mx - 15,
           interpolation='nearest',
           extent=g.extend())
    colorbar()
    title(b.__class__.__name__)

#===============================================================================
# delay and sum beamformer in time domain
# processing chain: beamforming, filtering, power, average
#===============================================================================
bt = BeamformerTime(source=t1, grid=g, mpos=m, c=346.04)
ft = FiltFiltOctave(source=bt, band=cfreq)
pt = TimePower(source=ft)
예제 #24
0
# Opt 1
maxval1 = zeros(len(FREQBANDS))
maxval2 = zeros(len(FREQBANDS))

# Opt 2
tot_maxval1 = 0
tot_maxval2 = 0

# Opt 3
tot_maxval = 0

# Befüllen von Src1_Matrix und Src2_Matrix
for freq_index, freq in enumerate(FREQBANDS):
    
    be.n = -1 #Eigenwerte der Größe nach sortiert -> größter Eigenwert (default)
    Lm = L_p(be.synthetic(freq, 3)).reshape(rg.shape).flatten()
    Src1_Matrix[:,:,freq_index] = Lm.reshape(rg.shape).T

    max_idx1 = argmax(Lm.flatten()) # position in grid with max source strength
    max_value1 = amax(Lm.flatten())


    be.n = -2 #Eigenwerte der Größe nach sortiert -> größter Eigenwert (default)
    Lm = L_p(be.synthetic(freq, 3)).reshape(rg.shape).flatten()
    Src2_Matrix[:,:,freq_index] = Lm.reshape(rg.shape).T

    max_idx2 = argmax(Lm.flatten()) # position in grid with max source strength
    max_value2 = amax(Lm.flatten())
    
    # Opt 1
    maxval1[freq_index] = max_value1