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

Last change on this file since 464 was 464, checked in by sommeria, 12 years ago

a few bug repairs and update in the series fcts

File size: 20.4 KB
Line 
1%'merge_proj': project and concatene fieldsmerge_proj
2% can be used as a template for applying an operation (here projection and concateantion) on each field of an input series
3%------------------------------------------------------------------------
4% function ParamOut=merge_proj(Param)
5%------------------------------------------------------------------------
6
7%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
8%
9% This function is used in four modes by the GUI series:
10%           1) config GUI: with no input argument, the function determine the suitable GUI configuration
11%           2) interactive input: the function is used to interactively introduce input parameters, and then stops
12%           3) RUN: the function itself runs, when an appropriate input  structure Param has been introduced.
13%           4) BATCH: the function itself proceeds in BATCH mode, using an xml file 'Param' as input.
14%
15% This function is used in four modes by the GUI series:
16%           1) config GUI: with no input argument, the function determine the suitable GUI configuration
17%           2) interactive input: the function is used to interactively introduce input parameters, and then stops
18%           3) RUN: the function itself runs, when an appropriate input  structure Param has been introduced.
19%           4) BATCH: the function itself proceeds in BATCH mode, using an xml file 'Param' as input.
20%
21%OUTPUT
22% GUI_input=list of options in the GUI series.fig needed for the function
23%
24%INPUT:
25% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
26% In batch mode, Param is the name of the corresponding xml file containing the same information
27% In the absence of input (as activated when the current Action is selected
28% in series), the function ouput GUI_input set the activation of the needed GUI elements
29%
30% Param contains the elements:(use the menu bar command 'export/GUI config' in series to see the current structure Param)
31%    .InputTable: cell of input file names, (several lines for multiple input)
32%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
33%    .OutputSubDir: name of the subdirectory for data outputs
34%    .OutputDir: directory for data outputs, including path
35%    .Action: .ActionName: name of the current activated function
36%             .ActionPath:   path of the current activated function
37%    .IndexRange: set the file or frame indices on which the action must be performed
38%    .FieldTransform: .TransformName: name of the selected transform function
39%                     .TransformPath:   path  of the selected transform function
40%                     .TransformHandle: corresponding function handle
41%    .InputFields: sub structure describing the input fields withfields
42%              .FieldName: name of the field
43%              .VelType: velocity type
44%              .FieldName_1: name of the second field in case of two input series
45%              .VelType_1: velocity type of the second field in case of two input series
46%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
47%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
48
49function ParamOut=merge_proj(Param)
50
51%% set the input elements needed on the GUI series when the action is selected in the menu ActionName
52if ~exist('Param','var') % case with no input parameter
53    ParamOut={'NbViewMax';'';...% max nbre of input file series (default='' , no limitation)
54        'AllowInputSort';'off';...% allow alphabetic sorting of the list of input files (options 'off'/'on', 'off' by default)
55        'WholeIndexRange';'off';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
56        'NbSlice';'on'; ...%nbre of slices ('off' by default)
57        'VelType';'one';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
58        'FieldName';'one';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
59        'FieldTransform'; 'on';...%can use a transform function
60        'ProjObject';'on';...%can use projection object(option 'off'/'on',
61        'Mask';'off';...%can use mask option   (option 'off'/'on', 'off' by default)
62        'OutputDirExt';'.mproj';...%set the output dir extension
63               ''};
64        return
65end
66
67%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
68%% select different modes,  RUN, parameter input, BATCH
69% BATCH  case: read the xml file for batch case
70if ischar(Param)
71        Param=xml2struct(Param);
72        checkrun=0;
73% RUN case: parameters introduced as the input structure Param
74else
75    hseries=guidata(Param.hseries);%handles of the GUI series
76    WaitbarPos=get(hseries.waitbar_frame,'Position');%position of the waitbar on the GUI series
77    if isfield(Param,'Specific')&& strcmp(Param.Specific,'?')
78        checkrun=1;% will only search interactive input parameters (preparation of BATCH mode)
79    else
80        checkrun=2; % indicate the RUN option is used
81    end
82end
83ParamOut=Param; %default output
84
85%% root input file(s) and type
86RootPath=Param.InputTable(:,1);
87RootFile=Param.InputTable(:,3);
88SubDir=Param.InputTable(:,2);
89NomType=Param.InputTable(:,4);
90FileExt=Param.InputTable(:,5);
91
92% get the set of input file names (cell array filecell), and the lists of
93% input file or frame indices i1_series,i2_series,j1_series,j2_series
94[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
95% filecell{iview,fileindex}: cell array representing the list of file names
96%        iview: line in the table corresponding to a given file series
97%        fileindex: file index within  the file series,
98% 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
99% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
100% set of frame indices used for movie or multimage input
101% numbers of slices and file indices
102
103NbSlice=1;%default
104if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
105    NbSlice=Param.IndexRange.NbSlice;
106end
107nbview=numel(i1_series);%number of input file series (lines in InputTable)
108nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
109nbfield_i=size(i1_series{1},2); %nb of fields for the i index
110nbfield=nbfield_j*nbfield_i; %total number of fields
111nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
112nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
113
114%determine the file type on each line from the first input file
115ImageTypeOptions={'image','multimage','mmreader','video'};
116NcTypeOptions={'netcdf','civx','civdata'};
117for iview=1:nbview
118    if ~exist(filecell{iview,1}','file')
119        msgbox_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'])
120        return
121    end
122    [FileType{iview},FileInfo{iview},MovieObject{iview}]=get_file_type(filecell{iview,1});
123    CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
124    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
125    if ~isempty(j1_series{iview})
126        frame_index{iview}=j1_series{iview};
127    else
128        frame_index{iview}=i1_series{iview};
129    end
130end
131
132%% calibration data and timing: read the ImaDoc files
133mode=''; %default
134timecell={};
135itime=0;
136NbSlice_calib={};
137XmlData=cell(1,nbview);%initiate the structures containing the data from the xml file (calibration and timing)
138
139for iview=1:nbview%Loop on views
140    SubDirBase=regexprep(SubDir{iview},'\..*','');%take the root part of SubDir, before the first dot '.'
141    filexml=[fullfile(RootPath{iview},SubDirBase) '.xml'];%new convention: xml at the level of the image folder
142    if ~exist(filexml,'file')
143        filexml=[fullfile(RootPath{iview},SubDir{iview},RootFile{iview}) '.xml']; % old convention: xml inside the image folder
144        if ~exist(filexml,'file')
145            filexml=[fullfile(RootPath{iview},SubDir{iview},RootFile{iview}) '.civ']; % very old convention: .civ file
146            if ~exist(filexml,'file')
147                filexml='';
148            end
149        end
150    end
151    if ~isempty(filexml)
152        [XmlData{iview},error]=imadoc2struct(filexml);
153    end
154    if isfield(XmlData{iview},'Time')
155        itime=itime+1;
156        timecell{itime}=XmlData{iview}.Time;
157    end
158    if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
159        NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
160        if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
161            msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
162        end
163    end
164end
165
166
167%% check coincidence in time for several input file series
168multitime=0;
169if isempty(timecell)
170    time=[];
171elseif length(timecell)==1
172    time=timecell{1};
173elseif length(timecell)>1
174    multitime=1;
175    for icell=1:length(timecell)
176        if ~isequal(size(timecell{icell}),size(timecell{1}))
177            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
178            time=timecell{1};
179            multitime=0;
180            break
181        end
182    end
183end
184if multitime
185    for icell=1:length(timecell)
186        time(icell,:,:)=timecell{icell};
187    end
188    diff_time=max(max(diff(time)));
189    if diff_time>0
190        msgbox_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time)])
191    end   
192end
193if size(time,2) < i2_series{1}(end) ||( ~isempty(j2_series{1}) && size(time,3) < j2_series{1}(end))% time array absent or too short in ImaDoc xml file'
194    time=[];
195end
196
197%% coordinate transform or other user defined transform
198transform_fct='';%default
199if isfield(Param,'FieldTransform')&&isfield(Param.FieldTransform,'TransformHandle')
200    transform_fct=Param.FieldTransform.TransformHandle;
201end
202%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
203 % EDIT FROM HERE
204
205%% check the validity of  input file types
206if CheckImage{1}
207    FileExtOut='.png'; % write result as .png images for image inputs
208elseif CheckNc{1}
209    FileExtOut='.nc';% write result as .nc files for netcdf inputs
210else
211    msgbox_uvmat('ERROR',['invalid file type input ' FileType{1}])
212    return
213end
214for iview=1:nbview
215        if ~isequal(CheckImage{iview},CheckImage{1})||~isequal(CheckNc{iview},CheckNc{1})
216        msgbox_uvmat('ERROR','input set of input series: need  either netcdf either image series')
217    return
218    end
219end
220NomTypeOut=NomType;% output file index will indicate the first and last ref index in the series
221
222%% Set field names and velocity types
223%use Param.InputFields for all views
224
225%% Initiate output fields
226%initiate the output structure as a copy of the first input one (reproduce fields)
227[DataOut,tild,errormsg] = read_field(filecell{1,1},FileType{1},Param.InputFields,1);
228if ~isempty(errormsg)
229    msgbox_uvmat('ERROR',['error reading ' filecell{1,1} ': ' errormsg])
230    return
231end
232time_1=[];
233if isfield(DataOut,'Time')
234    time_1=DataOut.Time(1);
235end
236if CheckNc{iview}
237    if isempty(strcmp('Conventions',DataOut.ListGlobalAttribute))
238        DataOut.ListGlobalAttribute=['Conventions' DataOut.ListGlobalAttribute];
239    end
240    DataOut.Conventions='uvmat';
241    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {Param.Action}];
242    ActionKey='Action';
243    while isfield(DataOut,ActionKey)
244        ActionKey=[ActionKey '_1'];
245    end
246    DataOut.(ActionKey)=Param.Action;
247    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {ActionKey}];
248    if isfield(DataOut,'Time')
249        DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {'Time','Time_end'}];
250    end
251end
252
253%% MAIN LOOP ON SLICES
254%%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
255for i_slice=1:NbSlice
256    index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
257    nbfiles=0;
258    nbmissing=0;
259   
260    %initiate result fields
261   
262    for ivar=1:length(DataOut.ListVarName)
263        DataOut.(DataOut.ListVarName{ivar})=0; % initialise all fields to zero
264    end
265   
266    %%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
267    for index=index_slice
268        if checkrun
269            update_waitbar(hseries.waitbar_frame,WaitbarPos,index/(nbfield))
270            stopstate=get(hseries.RUN,'BusyAction');
271        else
272            stopstate='queue';
273        end
274       
275        %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
276        Data=cell(1,nbview);%initiate the set Data
277        nbtime=0;
278        for iview=1:nbview
279            % reading input file(s)
280            [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},Param.InputFields,frame_index{iview}(index));
281            if ~isempty(errormsg)
282                errormsg=['error of input reading: ' errormsg];
283                break
284            end
285            timeread(iview)=0;
286            if isfield(Data{iview},'Time')
287                    timeread(iview)=Field{iview}.Time;
288                    nbtime=nbtime+1;
289                end
290            if ~isempty(NbSlice_calib)
291                Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
292            end
293            %transform the input field (e.g; phys) if requested
294            if ~isempty(transform_fct)
295                Data{iview}=transform_fct(Data{iview},XmlData{iview});  %transform to phys if requested
296            end
297            % field calculation (vort, div...)
298            if strcmp(FileType{iview},'civx')||strcmp(FileType{iview},'civ')
299                Data{iview}=calc_field(Param.InputFields.FieldName,Data{iview});%calculate field (vort..)
300            end
301           
302            %projection on object (gridded plane)
303            if Param.CheckObject
304                [Data{iview},errormsg]=proj_field(Data{iview},Param.ProjObject);
305                if ~isempty(errormsg)
306                    msgbox_uvmat('ERROR',['error in merge_proge/proj_field: ' errormsg])
307                    return
308                end
309            end
310        end
311        %----------END LOOP ON VIEWS----------------------
312       
313        %% merge the nbview fields
314        MergeData=merge_field(Data);
315        if isfield(MergeData,'Txt')
316            msgbox_uvmat('ERROR',MergeData.Txt)
317            return
318        end
319             % time of the merged field:
320        time_i=0;%default
321        if isempty(time)% time from ImaDoc prevails
322            time_i=sum(timeread)/nbtime;
323        else
324            time_i=(time(i1,j1)+time(i2,j2))/2; %TODO: upgrade
325        end
326        % generating the name of the merged field
327        i1=i1_series{iview}(index);
328        if ~isempty(i2_series{iview})
329            i2=i2_series{iview}(index);
330        else
331            i2=i1;
332        end
333        j1=1;
334        j2=1;
335        if ~isempty(j1_series{iview})
336            j1=j1_series{iview}(index);
337            if ~isempty(j2_series{iview})
338                j2=j2_series{iview}(index);
339            else
340                j2=j1;
341            end
342        end
343        OutputFile=fullfile_uvmat(RootPath{1},Param.OutputSubDir,RootFile{1},FileExtOut,NomType{1},i1,i2,j1,j2);
344       
345        % time of the merged field:
346        time_i=0;%default
347        if isempty(time)% time from ImaDoc prevails
348            time_i=sum(timeread)/nbtime;
349        else
350            % time_i=i1;
351            time_i=(time(i1,j1)+time(i2,j2))/2; %TODO: upgrade
352        end
353       
354        % recording the merged field
355        if CheckImage{1}    %in case of input images an image is produced
356            if isa(MergeData.A,'uint8')
357                bitdepth=8;
358            elseif isa(MergeData.A,'uint16')
359                bitdepth=16;
360            end
361            imwrite(MergeData.A,OutputFile,'BitDepth',bitdepth);
362            %write xml calibration file
363            siz=size(MergeData.A);
364            npy=siz(1);
365            npx=siz(2);
366            if isfield(MergeData,'VarAttribute')&&isfield(MergeData.VarAttribute{1},'Coord_2')&&isfield(MergeData.VarAttribute{1},'Coord_1')
367                Rangx=MergeData.VarAttribute{1}.Coord_2;
368                Rangy=MergeData.VarAttribute{1}.Coord_1;
369            elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
370                Rangx=[MergeData.AX(1) MergeData.AX(end)];
371                Rangy=[MergeData.AY(1) MergeData.AY(end)];
372            else
373                Rangx=[0.5 npx-0.5];
374                Rangy=[npy-0.5 0.5];%default
375            end
376            pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
377            pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
378            T_x=-pxcmx*Rangx(1)+0.5;
379            T_y=-pxcmy*Rangy(2)+0.5;
380            GeometryCal.focal=1;
381            GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
382            GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
383            ImaDoc.GeometryCalib=GeometryCal;
384            t=struct2xml(ImaDoc);
385            t=set(t,1,'name','ImaDoc');
386            save(t,[filebase_merge '.xml'])
387            display([filebase_merge '.xml saved'])
388        else
389            MergeData.ListGlobalAttribute={'Conventions','Project','InputFile_1','InputFile_end','nb_coord','nb_dim','dt','Time','civ'};
390            MergeData.Conventions='uvmat';
391            MergeData.nb_coord=2;
392            MergeData.nb_dim=2;
393            dt=[];
394            if isfield(Data{1},'dt')&& isnumeric(Data{1}.dt)
395                dt=Data{1}.dt;
396            end
397            for iview =2:numel(Data)
398                if ~(isfield(Data{iview},'dt')&& isequal(Data{iview}.dt,dt))
399                    dt=[];%dt not the same for all fields
400                end
401            end
402            if isempty(dt)
403                MergeData.ListGlobalAttribute(6)=[];
404            else
405                MergeData.dt=dt;
406            end
407            MergeData.Time=time_i;
408            error=struct2nc(OutputFile,MergeData);%save result file
409            if isempty(error)
410                display(['output file ' OutputFile ' written'])
411            else
412                display(error)
413            end
414        end
415    end
416end
417
418%'merge_field': concatene fields
419%------------------------------------------------------------------------
420function MergeData=merge_field(Data)
421%% default output
422if isempty(Data)||~iscell(Data)
423    MergeData=[];
424    return
425end
426MergeData=Data{1};%default
427error=0;
428nbview=length(Data);
429if nbview==1
430    return
431end
432
433%% group the variables (fields of 'FieldData') in cells of variables with the same dimensions
434[CellVarIndex,NbDim,VarTypeCell]=find_field_indices(Data{1});
435%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
436% CellVarIndex=cells of variable index arrays
437ivar_new=0; % index of the current variable in the projected field
438for icell=1:length(CellVarIndex)
439    if NbDim(icell)==1
440        continue
441    end
442    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
443    VarType=VarTypeCell{icell};
444    ivar_X=VarType.coord_x;
445    ivar_Y=VarType.coord_y;
446    ivar_FF=VarType.errorflag;
447    if isempty(ivar_X)
448        test_grid=1;%test for input data on regular grid (e.g. image)coordinates
449    else
450        if length(ivar_Y)~=1
451                msgbox_uvmat('ERROR','y coordinate missing in proj_field.m')
452                return
453        end
454        test_grid=0;
455    end
456    %case of input fields with unstructured coordinates
457    if ~test_grid
458        for ivar=VarIndex
459            VarName=MergeData.ListVarName{ivar};
460            for iview=1:nbview
461                eval(['MergeData.' VarName '=[MergeData.' VarName '; Data{iview}.' VarName '];'])
462            end
463        end
464    %case of fields defined on a structured  grid
465    else 
466        testFF=0;
467        for iview=2:nbview
468            for ivar=VarIndex
469                VarName=MergeData.ListVarName{ivar};
470                if isfield(MergeData,'VarAttribute')
471                    if length(MergeData.VarAttribute)>=ivar && isfield(MergeData.VarAttribute{ivar},'Role') && isequal(MergeData.VarAttribute{ivar}.Role,'errorflag')
472                        testFF=1;
473                    end
474                end
475                eval(['MergeData.' VarName '=MergeData.' VarName '+ Data{iview}.' VarName ';'])
476            end
477        end
478        if testFF
479            nbaver=nbview-MergeData.FF;
480            indgood=find(nbaver>0);
481            for ivar=VarIndex
482                VarName=MergeData.ListVarName{ivar};
483                eval(['MergeData.' VarName '(indgood)=double(MergeData.' VarName '(indgood))./nbaver(indgood);'])
484            end
485        else
486            for ivar=VarIndex
487                VarName=MergeData.ListVarName{ivar};
488                eval(['MergeData.' VarName '=double(MergeData.' VarName ')./nbview;'])
489            end   
490        end
491    end
492end
493
494   
Note: See TracBrowser for help on using the repository browser.