source: trunk/src/series/merge_proj.m @ 746

Last change on this file since 746 was 746, checked in by sommeria, 10 years ago
File size: 19.2 KB
RevLine 
[573]1%'merge_proj': concatene several fields from series, can project them on a regular grid in phys coordinates
[457]2%------------------------------------------------------------------------
[464]3% function ParamOut=merge_proj(Param)
[457]4%------------------------------------------------------------------------
5%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
[169]6%
7%OUTPUT
[596]8% ParamOut: sets options in the GUI series.fig needed for the function
[169]9%
10%INPUT:
[457]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
[596]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
[169]15%
[596]16% Param contains the elements:(use the menu bar command 'export/GUI config' in series to
17% see the current structure Param)
[457]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
[474]21%    .OutputDirExt: directory extension for data outputs
[457]22%    .Action: .ActionName: name of the current activated function
23%             .ActionPath:   path of the current activated function
[596]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%             
[457]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
[596]32%              .FieldName: name(s) of the field
[457]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
[596]36%              .Coord_y: name of y coordinate variable
37%              .Coord_x: name of x coordinate variable
[457]38%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
39%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40
[462]41function ParamOut=merge_proj(Param)
[29]42
[606]43%% set the input elements needed on the GUI series when the function is selected in the menu ActionName or InputTable refreshed
[592]44if isstruct(Param) && isequal(Param.Action.RUN,0)
[606]45    ParamOut.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
[632]46    ParamOut.WholeIndexRange='off';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
[606]47    ParamOut.NbSlice='off'; %nbre of slices ('off' by default)
48    ParamOut.VelType='one';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
49    ParamOut.FieldName='one';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
50    ParamOut.FieldTransform = 'on';%can use a transform function
51    ParamOut.TransformPath=fullfile(fileparts(which('uvmat')),'transform_field');% path to transform functions (needed for compilation only)
52    ParamOut.ProjObject='on';%can use projection object(option 'off'/'on',
[635]53    ParamOut.Mask='on';%can use mask option   (option 'off'/'on', 'off' by default)
[592]54    ParamOut.OutputDirExt='.mproj';%set the output dir extension
[605]55    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
[716]56      %check the input files
57    first_j=[];
58    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
59    PairString='';
60    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
61    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
62    FirstFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
63        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
64    if ~exist(FirstFileName,'file')
65        msgbox_uvmat('WARNING',['the first input file ' FirstFileName ' does not exist'])
[605]66    elseif isequal(size(Param.InputTable,1),1) && ~isfield(Param,'ProjObject')
[635]67        msgbox_uvmat('WARNING','You may need a projection object of type plane for merge_proj')
[605]68    end
[606]69    return
[29]70end
71
[457]72%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
[632]73ParamOut=[]; %default output
[592]74%% read input parameters from an xml file if input is a file name (batch mode)
75checkrun=1;
[457]76if ischar(Param)
[592]77    Param=xml2struct(Param);% read Param as input file (batch case)
78    checkrun=0;
[374]79end
[624]80hseries=findobj(allchild(0),'Tag','series');
81RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
82WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
[592]83
[624]84%% define the directory for result file (with path=RootPath{1})
85OutputDir=[Param.OutputSubDir Param.OutputDirExt];% subdirectory for output files
86
[550]87if ~isfield(Param,'InputFields')
88    Param.InputFields.FieldName='';
89end
[457]90
[577]91%% root input file type
[457]92RootPath=Param.InputTable(:,1);
93RootFile=Param.InputTable(:,3);
94SubDir=Param.InputTable(:,2);
95NomType=Param.InputTable(:,4);
96FileExt=Param.InputTable(:,5);
[374]97[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
[474]98%%%%%%%%%%%%
99% The cell array filecell is the list of input file names, while
100% filecell{iview,fileindex}:
[457]101%        iview: line in the table corresponding to a given file series
102%        fileindex: file index within  the file series,
103% 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
104% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
[474]105%%%%%%%%%%%%
[606]106% NbSlice=1;%default
107% if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
108%     NbSlice=Param.IndexRange.NbSlice;
109% end
110NbView=numel(i1_series);%number of input file series (lines in InputTable)
111NbField_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
112NbField_i=size(i1_series{1},2); %nb of fields for the i index
113NbField=NbField_j*NbField_i; %total number of fields
[457]114
[673]115%% determine the file type on each line from the first input file
[462]116ImageTypeOptions={'image','multimage','mmreader','video'};
117NcTypeOptions={'netcdf','civx','civdata'};
[606]118for iview=1:NbView
[462]119    if ~exist(filecell{iview,1}','file')
[668]120        disp_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
[462]121        return
122    end
123    [FileType{iview},FileInfo{iview},MovieObject{iview}]=get_file_type(filecell{iview,1});
124    CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
125    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
126    if ~isempty(j1_series{iview})
127        frame_index{iview}=j1_series{iview};
128    else
129        frame_index{iview}=i1_series{iview};
130    end
[457]131end
[739]132if NbView >1 && max(cell2mat(CheckImage))>0 && ~isfield(Param,'ProjObject')
133    disp_uvmat('ERROR','projection on a common grid is needed to concatene images: use a Projection Object of type ''plane'' with ProjMode=''interp_lin''',checkrun)
134    return
135end
[457]136
137%% calibration data and timing: read the ImaDoc files
[470]138[XmlData,NbSlice_calib,time,errormsg]=read_multimadoc(RootPath,SubDir,RootFile,FileExt,i1_series,i2_series,j1_series,j2_series);
139if size(time,1)>1
[457]140    diff_time=max(max(diff(time)));
[474]141    if diff_time>0
[676]142        disp_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time) ': the mean time is chosen in result'],checkrun)
[457]143    end   
144end
[676]145if ~isempty(errormsg)
146    disp_uvmat('WARNING',erromsg,checkrun)
147end
148time=mean(time,1); %averaged time taken for the merged field
[457]149
[409]150%% coordinate transform or other user defined transform
[606]151transform_fct='';%default fct handle
[478]152if isfield(Param,'FieldTransform')&&~isempty(Param.FieldTransform.TransformName)
[606]153        currentdir=pwd;
154        cd(Param.FieldTransform.TransformPath)
155        transform_fct=str2func(Param.FieldTransform.TransformName);
156        cd (currentdir)
[374]157end
[457]158%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
159 % EDIT FROM HERE
[116]160
[457]161%% check the validity of  input file types
[606]162for iview=1:NbView
[673]163    if ~isequal(CheckImage{iview},1)&&~isequal(CheckNc{iview},1)
[668]164        disp_uvmat('ERROR','input set of input series: need  either netcdf either image series',checkrun)
[632]165        return
[464]166    end
[457]167end
[673]168
169%% output file type
170if min(cell2mat(CheckImage))==1 && (~Param.CheckObject || strcmp(Param.ProjObject.Type,'plane'))
171    FileExtOut='.png'; %image output (input and proj result = image)
172    for iview=1:NbView
173        BitDepth(iview)=FileInfo{iview}.BitDepth;
174    end
175    BitDepth=max(BitDepth);
176else
177    FileExtOut='.nc'; %netcdf output
178end
[462]179NomTypeOut=NomType;% output file index will indicate the first and last ref index in the series
[673]180RootFileOut=RootFile{1};
181for iview=2:NbView
182    if ~strcmp(RootFile{iview},RootFile{1})
183        RootFileOut='mproj';
184        break
185    end
186end
[457]187
[642]188%% mask (TODO: case of multilevels)
[668]189MaskData=cell(NbView,1);
[642]190if Param.CheckMask
[676]191    if ischar(Param.MaskTable)% case of a single mask (char chain)
192        Param.MaskTable={Param.MaskTable};
193    end
[668]194    for iview=1:numel(Param.MaskTable)
[673]195        if exist(Param.MaskTable{iview},'file')
196            [MaskData{iview},tild,errormsg] = read_field(Param.MaskTable{iview},'image');
197            if ~isempty(transform_fct) && nargin(transform_fct)>=2
198                MaskData{iview}=transform_fct(MaskData{iview},XmlData{iview});
199            end
[642]200        end
201    end
202end
203
[457]204%% Set field names and velocity types
[462]205%use Param.InputFields for all views
[457]206
[640]207%% MAIN LOOP ON FIELDS
[457]208%%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
[606]209% for i_slice=1:NbSlice
210%     index_slice=i_slice:NbSlice:NbField;% select file indices of the slice
211%     NbFiles=0;
212%     nbmissing=0;
[474]213
[457]214    %%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
[606]215for index=1:NbField
[626]216        update_waitbar(WaitbarHandle,index/NbField)
[642]217    if ~isempty(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
[624]218        disp('program stopped by user')
[606]219        return
220    end
[673]221   
[606]222    %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
223    Data=cell(1,NbView);%initiate the set Data
[676]224    timeread=zeros(1,NbView);
[606]225    for iview=1:NbView
226        %% reading input file(s)
227        [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},Param.InputFields,frame_index{iview}(index));
228        if ~isempty(errormsg)
[746]229            disp_uvmat('ERROR',['ERROR in merge_proj/read_field/' errormsg],checkrun)
[614]230            return
[457]231        end
[676]232        % get the time defined in the current file if not already defined from the xml file
233        if ~isempty(time) && isfield(Data{iview},'Time')
[606]234            timeread(iview)=Data{iview}.Time;
[595]235        end
[606]236        if ~isempty(NbSlice_calib)
237            Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
238        end
[642]239       
[632]240        %% transform the input field (e.g; phys) if requested (no transform involving two input fields)
[606]241        if ~isempty(transform_fct)
242            if nargin(transform_fct)>=2
243                Data{iview}=transform_fct(Data{iview},XmlData{iview});
244            else
245                Data{iview}=transform_fct(Data{iview});
[29]246            end
[606]247        end
[632]248       
[642]249        %% calculate tps coefficients if needed
[614]250        check_proj_tps= isfield(Param,'ProjObject')&&~isempty(Param.ProjObject)&& strcmp(Param.ProjObject.ProjMode,'interp_tps')&&~isfield(Data{iview},'Coord_tps');
[606]251        Data{iview}=tps_coeff_field(Data{iview},check_proj_tps);
[642]252       
[606]253        %% projection on object (gridded plane)
254        if Param.CheckObject
255            [Data{iview},errormsg]=proj_field(Data{iview},Param.ProjObject);
256            if ~isempty(errormsg)
[746]257                disp_uvmat('ERROR',['ERROR in merge_proge/proj_field: ' errormsg],checkrun)
[606]258                return
[29]259            end
[464]260        end
[640]261       
262        %% mask
[642]263        if Param.CheckMask && ~isempty(MaskData{iview})
264             [Data{iview},errormsg]=mask_proj(Data{iview},MaskData{iview});
[640]265        end
[606]266    end
[673]267    %%%%%%%%%%%%%%%% END LOOP ON VIEWS %%%%%%%%%%%%%%%%
[606]268
269    %% merge the NbView fields
[739]270    [MergeData,errormsg]=merge_field(Data);
271    if ~isempty(errormsg)
272        disp_uvmat('ERROR',errormsg,checkrun);
[606]273        return
274    end
275
[673]276    %% time of the merged field: take the average of the different views
[676]277    if ~isempty(time)
278        timeread=time(index);   
279    elseif ~isempty(find(timeread))% time defined from ImaDoc
280        timeread=mean(timeread(timeread~=0));% take average over times form the files (when defined)
281    else
282        timeread=index;% take time=file index
[606]283    end
284
[673]285    %% generating the name of the merged field
286    i1=i1_series{1}(index);
287    if ~isempty(i2_series{end})
288        i2=i2_series{end}(index);
[606]289    else
290        i2=i1;
291    end
292    j1=1;
293    j2=1;
[673]294    if ~isempty(j1_series{1})
295        j1=j1_series{1}(index);
296        if ~isempty(j2_series{end})
297            j2=j2_series{end}(index);
[606]298        else
299            j2=j1;
[464]300        end
[606]301    end
[673]302    OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFileOut,FileExtOut,NomType{1},i1,i2,j1,j2);
[606]303
[673]304    %% recording the merged field
305    if strcmp(FileExtOut,'.png')    %output as image
306        if BitDepth==8
307            imwrite(uint8(MergeData.A),OutputFile,'BitDepth',8)
[464]308        else
[673]309            imwrite(uint16(MergeData.A),OutputFile,'BitDepth',16)
[464]310        end
[673]311        if index==1
312            %write xml calibration file, using the first file
313            siz=size(MergeData.A);
314            npy=siz(1);
315            npx=siz(2);
316            if isfield(MergeData,'coord_x') && isfield(MergeData,'coord_y')
317                Rangx=MergeData.coord_x;
318                Rangy=MergeData.coord_y;
319            elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
320                Rangx=[MergeData.AX(1) MergeData.AX(end)];
321                Rangy=[MergeData.AY(1) MergeData.AY(end)];
322            else
323                Rangx=[0.5 npx-0.5];
324                Rangy=[npy-0.5 0.5];%default
325            end
326            pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
327            pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
328            T_x=-pxcmx*Rangx(1)+0.5;
329            T_y=-pxcmy*Rangy(2)+0.5;
330            GeometryCal.CalibrationType='rescale';
331            GeometryCal.CoordUnit=MergeData.CoordUnit;
332            GeometryCal.focal=1;
333            GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
334            GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
335            ImaDoc.GeometryCalib=GeometryCal;
336            t=struct2xml(ImaDoc);
337            t=set(t,1,'name','ImaDoc');
338            save(t,[fileparts(OutputFile) '.xml'])
339        end
340       
[606]341    else
[676]342        MergeData.ListGlobalAttribute={'Conventions','Project','InputFile_1','InputFile_end','nb_coord','nb_dim'};
[606]343        MergeData.Conventions='uvmat';
344        MergeData.nb_coord=2;
345        MergeData.nb_dim=2;
346        dt=[];
347        if isfield(Data{1},'dt')&& isnumeric(Data{1}.dt)
348            dt=Data{1}.dt;
349        end
350        for iview =2:numel(Data)
351            if ~(isfield(Data{iview},'dt')&& isequal(Data{iview}.dt,dt))
352                dt=[];%dt not the same for all fields
[464]353            end
354        end
[676]355        if ~isempty(timeread)
356            MergeData.ListGlobalAttribute=[MergeData.ListGlobalAttribute {'Time'}];
357            MergeData.Time=timeread;
358        end
359        if ~isempty(dt)
360            MergeData.ListGlobalAttribute=[MergeData.ListGlobalAttribute {'dt'}];
[606]361            MergeData.dt=dt;
[29]362        end
[606]363        error=struct2nc(OutputFile,MergeData);%save result file
364        if isempty(error)
[739]365            disp(['output file ' OutputFile ' written'])
[606]366        else
[739]367            disp(error)
[606]368        end
[29]369    end
370end
371
[606]372
[222]373%'merge_field': concatene fields
374%------------------------------------------------------------------------
[739]375function [MergeData,errormsg]=merge_field(Data)
[222]376%% default output
[29]377if isempty(Data)||~iscell(Data)
378    MergeData=[];
379    return
380end
[739]381errormsg='';
[673]382MergeData=Data{1};% merged field= first field by default, reproduces the glabal attributes of the first field
[606]383NbView=length(Data);
384if NbView==1
[29]385    return
386end
[222]387
[522]388%% group the variables (fields of 'Data') in cells of variables with the same dimensions
[668]389[CellInfo,NbDim,errormsg]=find_field_cells(Data{1});
[739]390if ~isempty(errormsg)
391    return
392end
[670]393
[89]394%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
[668]395for icell=1:length(CellInfo)
[670]396    if NbDim(icell)~=1 % skip field cells which are of dim 1
397        switch CellInfo{icell}.CoordType
398            case 'scattered'  %case of input fields with unstructured coordinates: just concacene data
399                for ivar=CellInfo{icell}.VarIndex %  indices of the selected variables in the list FieldData.ListVarName
400                    VarName=Data{1}.ListVarName{ivar};
401                    %MergeData=Data{1};% merged field= first field by default, reproduces the glabal attributes of the first field
402                    for iview=2:NbView
403                        MergeData.(VarName)=[MergeData.(VarName); Data{iview}.(VarName)];
[89]404                    end
405                end
[670]406            case 'grid'        %case of fields defined on a structured  grid
407                FFName='';
[676]408                if isfield(CellInfo{icell},'VarIndex_errorflag') && ~isempty(CellInfo{icell}.VarIndex_errorflag)
[670]409                    FFName=Data{1}.ListVarName{CellInfo{icell}.VarIndex_errorflag};% name of errorflag variable
410                end
411                % select good data on each view
412                for ivar=CellInfo{icell}.VarIndex  %  indices of the selected variables in the list FieldData.ListVarName
413                    VarName=Data{1}.ListVarName{ivar};
414                    for iview=1:NbView
415                        if isempty(FFName)
416                            check_bad=isnan(Data{iview}.(VarName));%=0 for NaN data values, 1 else
417                        else
418                            check_bad=isnan(Data{iview}.(VarName)) | Data{iview}.(FFName)~=0;%=0 for NaN or error flagged data values, 1 else
419                        end
420                        Data{iview}.(VarName)(check_bad)=0; %set to zero NaN or masked data
421                        if iview==1
422                            MergeData.(VarName)=Data{1}.(VarName);% correct the field of MergeData
423                            NbAver=~check_bad;% initiate NbAver: the nbre of good data for each point
[739]424                        elseif size(Data{iview}.(VarName))~=size(MergeData.(VarName))
425                            errormsg='sizes of the input matrices do not agree, need to interpolate on a common grid using a projection object';
426                            return
427                        else                     
[670]428                            MergeData.(VarName)=MergeData.(VarName) + Data{iview}.(VarName);%add data
429                            NbAver=NbAver + ~check_bad;% add 1 for good data, 0 else
430                        end
431                    end
432                    MergeData.(VarName)(NbAver~=0)=MergeData.(VarName)(NbAver~=0)./NbAver(NbAver~=0);% take average of defined data at each point
433                end
[89]434        end
[670]435        if isempty(FFName)
436            FFName='FF';
[89]437        end
[670]438        MergeData.(FFName)(NbAver~=0)=0;% flag to 1 undefined summed data
439        MergeData.(FFName)(NbAver==0)=1;% flag to 1 undefined summed data
[89]440    end
441end
[222]442
[670]443
[89]444   
Note: See TracBrowser for help on using the repository browser.