source: trunk/src/series/beam_forming.m @ 1184

Last change on this file since 1184 was 1184, checked in by sommeria, 4 weeks ago

bed-scan updated and many updates

File size: 16.0 KB
Line 
1%'beam_forming': create images from multi-array acoustic signal (cf. project Philippe Roux)
2%------------------------------------------------------------------------
3% function ParamOut=beam_forming(Param)
4%------------------------------------------------------------------------
5%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
6%
7%OUTPUT
8% ParamOut: sets options in the GUI series.fig needed for the function
9%
10%INPUT:
11% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
12% In batch mode, Param is the name of the corresponding xml file containing the same information
13% when Param.Action.RUN=0 (as activated when the current Action is selected
14% in series), the function ouput paramOut set the activation of the needed GUI elements
15%
16% Param contains the elements:(use the menu bar command 'export/GUI config' in series to
17% see the current structure Param)
18%    .InputTable: cell of input file names, (several lines for multiple input)
19%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
20%    .OutputSubDir: name of the subdirectory for data outputs
21%    .OutputDirExt: directory extension for data outputs
22%    .Action: .ActionName: name of the current activated function
23%             .ActionPath:   path of the current activated function
24%             .ActionExt: fct extension ('.m', Matlab fct, '.sh', compiled   Matlab fct
25%             .RUN =0 for GUI input, =1 for function activation
26%             .RunMode='local','background', 'cluster': type of function  use
27%             
28%    .IndexRange: set the file or frame indices on which the action must be performed
29%    .FieldTransform: .TransformName: name of the selected transform function
30%                     .TransformPath:   path  of the selected transform function
31%    .InputFields: sub structure describing the input fields withfields
32%              .FieldName: name(s) of the field
33%              .VelType: velocity type
34%              .FieldName_1: name of the second field in case of two input series
35%              .VelType_1: velocity type of the second field in case of two input series
36%              .Coord_y: name of y coordinate variable
37%              .Coord_x: name of x coordinate variable
38%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
39%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40
41
42%=======================================================================
43% Copyright 2008-2024, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
44%   http://www.legi.grenoble-inp.fr
45%   Joel.Sommeria - Joel.Sommeria (A) univ-grenoble-alpes.fr
46%
47%     This file is part of the toolbox UVMAT.
48%
49%     UVMAT is free software; you can redistribute it and/or modify
50%     it under the terms of the GNU General Public License as published
51%     by the Free Software Foundation; either version 2 of the license,
52%     or (at your option) any later version.
53%
54%     UVMAT is distributed in the hope that it will be useful,
55%     but WITHOUT ANY WARRANTY; without even the implied warranty of
56%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
57%     GNU General Public License (see LICENSE.txt) for more details.
58%=======================================================================
59
60function ParamOut=beam_forming(Param)
61
62%% set the input elements needed on the GUI series when the function is selected in the menu ActionName or InputTable refreshed
63if isstruct(Param) && isequal(Param.Action.RUN,0)
64    ParamOut.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
65    ParamOut.WholeIndexRange='on';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
66    ParamOut.NbSlice='off'; %nbre of slices ('off' by default)
67    ParamOut.VelType='off';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
68    ParamOut.FieldName='off';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
69    ParamOut.FieldTransform = 'off';%can use a transform function
70    %ParamOut.TransformPath=fullfile(fileparts(which('uvmat')),'transform_field');% path to transform functions (needed for compilation only)
71    ParamOut.ProjObject='off';%can use projection object(option 'off'/'on',
72    ParamOut.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
73    index=msgbox_uvmat('INPUT_TXT','index of the series to process (1 to 5)');%choose the i index of the dat files
74    ParamOut.OutputDirExt=['.p_formed_' index];%set the output dir extension
75    hseries=findobj(allchild(0),'Tag','series');
76    hhseries=guidata(hseries);
77    set(hhseries.num_last_i,'String',index)
78    set(hhseries.num_first_i,'String',index)
79    ParamOut.OutputFileMode='NbInput';% '=NbInput': 1 output file per input file index, '=NbInput_i': 1 file per input file index i, '=NbSlice': 1 file per slice
80      %check the input files
81    first_j=[];
82    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
83    PairString='';
84    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
85    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
86    FirstFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
87        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
88    if ~exist(FirstFileName,'file')
89        msgbox_uvmat('WARNING',['the first input file ' FirstFileName ' does not exist'])
90    end
91    return
92end
93
94ParamOut=[]; %default output
95%% read input parameters from an xml file if input is a file name (batch mode)
96checkrun=1;
97if ischar(Param)
98    Param=xml2struct(Param);% read Param as input file (batch case)
99    checkrun=0;
100end
101hseries=findobj(allchild(0),'Tag','series');
102RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
103WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
104
105%% define the directory for result file (with path=RootPath{1})
106OutputDir=[Param.OutputSubDir Param.OutputDirExt];% subdirectory for output files
107if ~isfield(Param,'InputFields')
108    Param.InputFields.FieldName='';
109end
110
111%% root input file type
112RootPath=Param.InputTable{1,1};
113RootFile=Param.InputTable{1,3};
114SubDir=Param.InputTable{1,2};
115NomType=Param.InputTable{1,4};
116FileExt=Param.InputTable{1,5};
117[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
118%%%%%%%%%%%%.sback.sback
119% The cell array filecell is the list of input file names, while
120% filecell{iview,fileindex}:
121%        iview: line in the table corresponding to a given file series
122%        fileindex: file index within  the file series,
123% i1_series(iview,ref_j,ref_i)... are the corresponding arrays of indices i1,i2,j1,j2, depending on the input line iview and the two reference indices ref_i,ref_j
124% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
125%%%%%%%%%%%%
126% NbSlice=1;%default
127% if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
128%     NbSlice=Param.IndexRange.NbSlice;
129% end
130NbView=numel(i1_series);%number of input file series (lines in InputTable)
131NbField_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
132NbField_i=size(i1_series{1},2); %nb of fields for the i index
133NbField=NbField_j*NbField_i; %total number of fields
134
135%% determine the file type on each line from the first input file
136NcTypeOptions={'netcdf','civx','civdata'};
137for iview=1:NbView
138    if ~exist(filecell{iview,1}','file')
139        disp_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
140        return
141    end
142    [FileInfo{iview},MovieObject{iview}]=get_file_info(filecell{iview,1});
143    FileType{iview}=FileInfo{iview}.FileType;
144   CheckImage{iview}=strcmp(FileInfo{iview}.FieldType,'image');% =1 for images
145    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
146    if ~isempty(j1_series{iview})
147        frame_index{iview}=j1_series{iview};
148    else
149        frame_index{iview}=i1_series{iview};
150    end
151end
152
153% clear all
154% close all.sback
155% read_data=1;
156affichage=0;
157% soustraction=0;
158
159%%%%%% Prepare output
160load (fullfile(RootPath,SubDir,[RootFile '.mat']))
161Data.ListGlobalAttribute={'CoordUnit'}; %%TODO: add also time, how to get it  ?????
162Data.CoordUnit='pixel';
163Data.ListVarName={'Coord_x','Coord_y','A'};
164Data.VarDimName={'Coord_x','Coord_y',{'Coord_y','Coord_x'}};
165%Data.Coord_x=5*(nbvoie_reception-0.5)/numel(nbvoie_reception); % totql length of e
166Data.Coord_x=1:65;
167%Data.Coord_z=(1:A)/133 ;% to check from input parameter ....
168Data.Coord_y=1:332;
169%%%%%%
170%
171% while test_fin_fichier>0
172%     if read_data==1
173%directory='manip_lgit';%%%%%%%%%%%%%%%%%
174%name='test';%%%%%%%%%%%%%%%%%
175%         number=2;
176number=str2num(Param.OutputDirExt(11:end));%extract the subsequence index (from 1 to 5)
177numero_tir_fin_old=1%%%%%%% =0 ?????
178pas_fichier=20;%  %20;% nbre of successive shots to read (to account for computer memory limit)
179Nmoy=800;  %%%%% value 20  FOR TEST : to shift to VALUE 8000 set by the .mat file
180
181test_fin_fichier=1;% test to stop input file reading
182while test_fin_fichier>0
183    numero_tir_debut=1;
184    numero_tir_fin=numero_tir_fin_old+pas_fichier-1;
185   
186    %  eval(['load ' directory '\' name '.mat'])
187    matrice_finale=zeros(A,length(nbvoie_reception),numero_tir_fin);%A=nbre of times (coord z)=2650, numero_tir_fin=time index
188    time=(b/rsf+[0:A-1]/rsf); %b=250, rsf=10,
189    freq1=0.5;freq2=1.5;
190    [BB AA]=butter(4,[freq1 freq2]/rsf*2);
191
192    for ii=1:length(nbvoie_reception)%=64
193        %eval(['fid=fopen(''E:\ManipLGITLecoeur\' directory '\' name '_' num2str(number) '_' num2str(nbvoie_reception(ii)) '.dat'',''r'');']);
194        filename=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,number,[],ii); % input file name
195        fid=fopen(filename);
196        toto=zeros(Nsequence*A*numero_tir_fin+31,1);% Nsequence=1
197        toto=fread(fid,numero_tir_fin*A*Nsequence+31,'int16','ieee-le') ;% why shift by 31 ?????
198        toto=double(bitxor(uint16(toto),uint16(2048)));
199        toto(1:31)=[];toto(numero_tir_fin*A*Nsequence)=mean(toto);
200        fclose(fid);
201       
202        tata=reshape(toto-2048,A,numero_tir_fin);
203        matrice_finale(:,ii,:)=reshape(tata,[A,1,numero_tir_fin]);
204        clear toto tata
205    end
206   
207   % matrice_finale(:,:,numero_tir_debut:numero_tir_fin_old)=[];%%%%%%% first field removed (when numero_tir_fin_old=1) ?????
208     matrice_finale(:,:,numero_tir_debut:numero_tir_fin_old-1)=[];%%%%%%%
209  %  numero_tir_fin=numero_tir_fin-1;  ?????
210    matrice_finale=reshape(filtfilt(BB,AA,matrice_finale(:,:)),size(matrice_finale));% low pass filtered input signal,along first (time) index?
211   
212    % if soustraction==1
213    %     eval(['load moyenne_' name '_' num2str(number) '.mat matrice_finale_moy'])
214    %     for kk=1:size(matrice_finale,3)
215    %         matrice_finale(:,:,kk)=matrice_finale(:,:,kk)-matrice_finale_moy;
216    %     end
217    % end
218    %eval(['save matrice_finale_' num2str(numero_tir_fin_old) '_' num2str(numero_tir_fin) '.mat'])
219   
220    %%%%%%%%%%%%%%Imagerie
221    fe=rsf*1e6;% sampling frequency for receptor (in Hz)
222    cc=1475;%speed of sound
223    hanning_window=25;
224    hanning_vect=hanning(2*hanning_window+1);
225    interval=[1:size(matrice_finale,1)];
226    freq=0:fe/length(interval):fe*(1-1/length(interval));
227   
228    pas_reseau_z=0.75e-3;%0.75e-3
229    pas_reseau_r=0;
230    voie_mean=length(nbvoie_reception)/2;%32;
231    reseau_z=[0:length(nbvoie_reception)-1]*pas_reseau_z;
232    reseau_z=reseau_z-reseau_z(voie_mean);
233    reseau_r=[0:length(nbvoie_reception)-1]*pas_reseau_r;
234    reseau_r=reseau_r-reseau_r(voie_mean);
235   
236    debut_r=(time(1)+20)*1e-6*cc/2;
237    fin_r=(time(end)-20)*1e-6*cc/2;
238   
239    image_r=debut_r:.5e-3:fin_r;
240    image_z=-24e-3:.75e-3:24e-3;
241   
242    image_fin=zeros(length(image_r),length(image_z),size(matrice_finale,3));%size=(332,65,pas_fichier)
243    %image_fin_bis=zeros(length(image_r),length(image_z),size(matrice_finale,3));
244    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
245   
246    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
247    for kk=1:size(matrice_finale,3)
248        disp(kk)
249        signal=squeeze(matrice_finale(interval,:,kk));
250        tata_fft=fft(signal,[],1);%FFT of the time signal size=(2650,64)     
251        if kk==1           
252            matrice_freq_mean=mean(abs(fft(signal,[],1)),2);
253            X=[freq1*1e6 freq2*1e6];
254            [I J]=find(freq>=X(1) & freq<=X(2));
255            int_freq=find(matrice_freq_mean(round(1:length(freq)/2))>max(matrice_freq_mean(round(1:length(freq)/2)))/2);
256            bandwidth=freq(int_freq(end)-int_freq(1));
257            %clear matrice_freq_mean
258        end
259       
260        for ii=1:length(image_r)
261            for jj=1:length(image_z)
262               
263                delay=zeros(length(nbvoie_reception),1);
264                delay=1/cc*sqrt((reseau_z-image_z(jj)).^2+(reseau_r-image_r(ii)).^2);
265               
266                [ind centre_z]=min(abs((reseau_z-image_z(jj))));
267                interval_utile=round(((delay(centre_z)+1/cc*abs(image_r(ii)))*fe)-(b+interval(1)-1)+round(length(motifbase)/2)+[-fe/bandwidth/2:fe/bandwidth/2]);
268                delay=delay-delay(centre_z);
269               
270                hanning_vecteur=zeros(1,length(nbvoie_reception));
271                if centre_z>hanning_window & centre_z<(length(nbvoie_reception)-hanning_window)
272                    hanning_vecteur(centre_z+[-hanning_window:hanning_window])=hanning_vect;
273                elseif centre_z<=hanning_window
274                    test=hanning_vect((centre_z+[-hanning_window:hanning_window])>=1);
275                    hanning_vecteur(1:length(test))=test;
276                elseif centre_z>=(length(nbvoie_reception)-hanning_window)
277                    test=hanning_vect((centre_z+[-hanning_window:hanning_window])<=length(nbvoie_reception));
278                    hanning_vecteur(length(nbvoie_reception)+[-length(test)+1:0])=test;
279                end
280                hanning_vecteur=hanning_vecteur/norm(hanning_vecteur);
281                clear test;
282               
283                amplitude_weight=ones(size(signal,1),1)*hanning_vecteur;
284                signal_new_rec=zeros(size(signal,1),length(nbvoie_reception));
285               
286                tata=zeros(size(signal,1),size(signal,2));
287                tata(J,:)=tata_fft(J,:).*exp(1i*2*pi*(freq(J)'*delay));
288                signal_new_rec=2*real(ifft(tata,[],1)).*amplitude_weight;
289                index_interval_utile=find(interval_utile>0 & interval_utile<size(signal,1));
290                toto=zeros(length(index_interval_utile),1);
291                toto=mean(signal_new_rec(interval_utile(index_interval_utile),:),2);
292                image_fin(ii,jj,kk)=sqrt(mean(toto.^2));
293                clear signal_bis interval_utile index_interval_utile hanning_vecteur
294            end
295        end
296    end
297   
298    clear signal_new_em signal_new_rec m delay toto toto_bis tata tata_fft
299   
300    if affichage==1
301        for kk=1:size(image_fin,3)
302           
303            figure(1)
304            imagesc(image_r*1e2,image_z*1e2,image_fin(:,:,kk)'/max(max(image_fin(:,:,kk)))');
305            title(['avec beamforming - energie max = ' num2str(max(max(image_fin(:,:,kk))))])
306            colorbar;
307            xlabel('r (cm)');ylabel('z (cm)');
308            drawnow
309            pause(.2);
310        end
311    end
312   
313    clear matrice_finale
314   
315    %%%%%%% TO ADAPT
316    for iii=1:size(image_fin,3)
317        Data.A=image_fin(:,:,iii);% time lapse decreasesas z coordinate increases.
318        FileIndex=numero_tir_fin - pas_fichier+iii;%%%%%%TO CHECK!!!!!
319        %%%%%%%%%%
320        %eval(['save analyse_' name '_' num2str(number) '_' num2str(numero_tir_fin_old) '_' num2str(numero_tir_fin) '.mat'])
321        OutputFile=fullfile_uvmat(RootPath,OutputDir,'signal','.nc','_00001',FileIndex);
322        error=struct2nc(OutputFile,Data);%save result file
323        if isempty(error)
324            disp(['output file ' OutputFile ' written'])
325        else
326            disp(error)
327        end
328    end
329    numero_tir_fin_old=numero_tir_fin+1% first index for next bloc reading
330     if (numero_tir_fin_old+pas_fichier-1)>Nmoy
331    test_fin_fichier=-1;
332    end
333end
334
335
Note: See TracBrowser for help on using the repository browser.