source: trunk/src/series/merge_proj_special.m @ 811

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