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

Last change on this file since 718 was 716, checked in by sommeria, 11 years ago

fct improved by reducing the input file check when selected.

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