source: trunk/src/proj_field.m @ 527

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

various bugs corrected

File size: 106.7 KB
Line 
1%'proj_field': projects the field on a projection object
2%--------------------------------------------------------------------------
3%  function [ProjData,errormsg]=proj_field(FieldData,ObjectData)
4%
5% OUTPUT:
6% ProjData structure containing the fields of the input field FieldData,
7% transmitted or projected on the object, plus the additional fields
8%    .UMax, .UMin, .VMax, .VMin: min and max of velocity components in a domain
9%    .UMean,VMean: mean of the velocity components in a domain
10%    .AMin, AMax: min and max of a scalar
11%    .AMean: mean of a scalar in a domain 
12%  .NbPix;
13%  .DimName=  names of the matrix dimensions (matlab cell)
14%  .VarName= names of the variables [ProjData.VarName {'A','AMean','AMin','AMax'}];
15%  .VarDimNameIndex= dimensions of the variables, indicated by indices in the list .DimName;
16%
17%INPUT
18% ObjectData: structure characterizing the projection object
19%    .Type : type of projection object
20%    .ProjMode=mode of projection ;
21%    .CoordUnit: 'px', 'cm' units for the coordinates defining the object
22%    .Angle (  angles of rotation (=[0 0 0] by default)
23%    .ProjAngle=angle of projection;
24%    .DX,.DY,.DZ=increments along each coordinate
25%    .Coord(nbpoints,3): set of coordinates defining the object position;
26
27%FieldData: data of the field to be projected on the projection object, with optional fields
28%    .Txt: error message, transmitted to the projection
29%    .FieldList: cell array of strings representing the fields to calculate
30%    .Mesh: typical distance between data points (used for mouse action or display), transmitted
31%    .CoordUnit, .TimeUnit, .dt: transmitted
32% standardised description of fields, nc-formated Matlab structure with fields:
33%         .ListGlobalAttribute: cell listing the names of the global attributes
34%        .Att_1,Att_2... : values of the global attributes
35%            .ListVarName: cell listing the names of the variables
36%           .VarAttribute: cell of structures s containing names and values of variable attributes (s.name=value) for each variable of .ListVarName
37%        .Var1, .Var2....: variables (Matlab arrays) with names listed in .ListVarName
38% The variables are grouped in 'fields', made of a set of variables with common dimensions (using the function find_field_cells)
39% The variable attribute 'Role' is used to define the role for plotting:
40%       Role = 'scalar':  (default) represents a scalar field
41%            = 'coord':  represents a set of unstructured coordinates, whose
42%                     space dimension is given by the last array dimension (called 'NbDim').
43%            = 'coord_x', 'coord_y',  'coord_z': represents a separate set of
44%                        unstructured coordinate x, y  or z
45%            = 'vector': represents a vector field whose number of components
46%                is given by the last dimension (called 'NbDim')
47%            = 'vector_x', 'vector_y', 'vector_z'  :represents the x, y or z  component of a vector 
48%            = 'warnflag' : provides a warning flag about the quality of data in a 'Field', default=0, no warning
49%            = 'errorflag': provides an error flag marking false data,
50%                   default=0, no error. Different non zero values can represent different criteria of elimination.
51%
52% Default role of variables (by name)
53%  vector field:
54%    .X,.Y: position of the velocity vectors, projected on the object
55%    .U, .V, .W: velocity components, projected on the object
56%    .C, .CName: scalar associated to the vector
57%    .F : equivalent to 'warnflag'
58%    .FF: equivalent to 'errorflag'
59%  scalar field or image:
60%    .AName: name of a scalar (to be calculated from velocity fields after projection), transmitted
61%    .A: scalar, projected on the object
62%    .AX, .AY: positions for the scalar
63%     case of a structured grid: A is a dim 2 matrix and .AX=[first last] (length 2 vector) represents the first and last abscissa of the grid
64%     case of an unstructured scalar: A is a vector, AX and AY the corresponding coordinates
65%
66%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
67%  Copyright Joel Sommeria, 2008, LEGI / CNRS-UJF-INPG, sommeria@coriolis-legi.org.
68%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
69%     This file is part of the toolbox UVMAT.
70%
71%     UVMAT is free software; you can redistribute it and/or modify
72%     it under the terms of the GNU General Public License as published by
73%     the Free Software Foundation; either version 2 of the License, or
74%     (at your option) any later version.
75%
76%     UVMAT is distributed in the hope that it will be useful,
77%     but WITHOUT ANY WARRANTY; without even the implied warranty of
78%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
79%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
80%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
81
82function [ProjData,errormsg]=proj_field(FieldData,ObjectData)
83errormsg='';%default
84ProjData=[];
85
86%% in the absence of object Type or projection mode, or object coordinaes, the output is empty
87if ~isfield(ObjectData,'Type')||~isfield(ObjectData,'ProjMode')
88    return
89end
90% case of no projection (object is used only as graph display)
91if isequal(ObjectData.ProjMode,'none')||isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside')
92    return
93end
94if ~isfield(ObjectData,'Coord')||isempty(ObjectData.Coord)
95    if strcmp(ObjectData.Type,'plane')
96        ObjectData.Coord=[0 0 0];%default
97    else
98        return
99    end
100end
101
102%% apply projection depending on the object type
103switch ObjectData.Type
104    case 'points'
105    [ProjData,errormsg]=proj_points(FieldData,ObjectData);
106    case {'line','polyline'}
107     [ProjData,errormsg] = proj_line(FieldData,ObjectData);
108    case {'polygon','rectangle','ellipse'}
109        if isequal(ObjectData.ProjMode,'inside')||isequal(ObjectData.ProjMode,'outside')
110            [ProjData,errormsg] = proj_patch(FieldData,ObjectData);
111        else
112            [ProjData,errormsg] = proj_line(FieldData,ObjectData);
113        end
114    case 'plane'
115            [ProjData,errormsg] = proj_plane(FieldData,ObjectData);
116    case 'volume'
117        [ProjData,errormsg] = proj_volume(FieldData,ObjectData);
118end
119
120%-----------------------------------------------------------------
121%project on a set of points
122function  [ProjData,errormsg]=proj_points(FieldData,ObjectData)%%
123%-------------------------------------------------------------------
124
125siz=size(ObjectData.Coord);
126width=0;
127if isfield(ObjectData,'Range')
128    width=ObjectData.Range(1,2);
129end
130if isfield(ObjectData,'RangeX')&&~isempty(ObjectData.RangeX)
131    width=max(ObjectData.RangeX);
132end
133if isfield(ObjectData,'RangeY')&&~isempty(ObjectData.RangeY)
134    width=max(width,max(ObjectData.RangeY));
135end
136if isfield(ObjectData,'RangeZ')&&~isempty(ObjectData.RangeZ)
137    width=max(width,max(ObjectData.RangeZ));
138end
139if isequal(ObjectData.ProjMode,'projection')
140    if width==0
141        errormsg='projection range around points needed';
142        return
143    end
144elseif  ~isequal(ObjectData.ProjMode,'interp')
145    errormsg=(['ProjMode option ' ObjectData.ProjMode ' not available in proj_field']);
146        return
147end
148[ProjData,errormsg]=proj_heading(FieldData,ObjectData);
149ProjData.NbDim=0;
150[CellVarIndex,NbDimCell,VarTypeCell,errormsg]=find_field_cells(FieldData);
151if ~isempty(errormsg)
152    errormsg=['error in proj_field/proj_points:' errormsg];
153    return
154end
155%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
156for icell=1:length(CellVarIndex)
157    if NbDimCell(icell)==1
158        continue
159    end
160    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
161    VarType=VarTypeCell{icell};% structure defining the types of variables in the cell
162    ivar_X=VarType.coord_x;
163    ivar_Y=VarType.coord_y;
164    ivar_Z=VarType.coord_z;
165    ivar_Anc=VarType.ancillary;
166    test_anc(ivar_Anc)=ones(size(ivar_Anc));
167    ivar_F=VarType.warnflag;
168    ivar_FF=VarType.errorflag;
169    VarIndex([ivar_X ivar_Y ivar_Z ivar_Anc ivar_F ivar_FF])=[];% not projected variables removed frlom list
170    if isempty(ivar_X)
171        test_grid=1;%test for input data on regular grid (e.g. image)coordinates     
172    else
173        if length(ivar_X)>1 || length(ivar_Y)>1 || length(ivar_Z)>1
174                 errormsg='multiple coordinate input in proj_field.m';
175                    return
176        end
177        if length(ivar_Y)~=1
178                errormsg='y coordinate not defined in proj_field.m';
179                return
180        end
181        test_grid=0;
182    end
183    ProjData.ListVarName={'Y','X','NbVal'};
184    ProjData.VarDimName={'nb_points','nb_points','nb_points'};
185    ProjData.VarAttribute{1}.Role='ancillary';
186    ProjData.VarAttribute{2}.Role='ancillary';
187    ProjData.VarAttribute{3}.Role='ancillary';
188    for ivar=VarIndex       
189        VarName=FieldData.ListVarName{ivar};
190        ProjData.ListVarName=[ProjData.ListVarName {VarName}];% add the current variable to the list of projected variables
191        ProjData.VarDimName=[ProjData.VarDimName {'nb_points'}]; % projected VarName has a single dimension called 'nb_points' (set of projection points)
192    end
193    if ~test_grid
194        eval(['coord_x=FieldData.' FieldData.ListVarName{ivar_X} ';'])
195        eval(['coord_y=FieldData.' FieldData.ListVarName{ivar_Y} ';'])
196        test3D=0;% TEST 3D CASE : NOT COMPLETED ,  3D CASE : NOT COMPLETED
197        if length(ivar_Z)==1
198            eval(['coord_z=FieldData.' FieldData.ListVarName{ivar_Z} ';'])
199            test3D=1;
200        end
201        if length(ivar_F)>1 || length(ivar_FF)>1
202                 msgbox_uvmat('ERROR','multiple flag input in proj_field.m')
203                    return
204        end     
205        for ipoint=1:siz(1)
206           Xpoint=ObjectData.Coord(ipoint,:);
207           distX=coord_x-Xpoint(1);
208           distY=coord_y-Xpoint(2);         
209           dist=distX.*distX+distY.*distY;
210           indsel=find(dist<width*width);
211           ProjData.X(ipoint,1)=Xpoint(1);
212           ProjData.Y(ipoint,1)=Xpoint(2);
213           if isequal(length(ivar_FF),1)
214               FFName=FieldData.ListVarName{ivar_FF};
215               FF=FieldData.(FFName)(indsel);
216               indsel=indsel(~FF);
217           end
218           ProjData.NbVal(ipoint,1)=length(indsel);
219            for ivar=VarIndex
220               VarName=FieldData.ListVarName{ivar};
221               if isempty(indsel)
222                    ProjData.(VarName)(ipoint,1)=NaN;
223               else
224                    Var=FieldData.(VarName)(indsel);
225                    ProjData.(VarName)(ipoint,1)=mean(Var);
226                    if isequal(ObjectData.ProjMode,'interp')
227                         ProjData.(VarName)(ipoint,1)=griddata_uvmat(coord_x(indsel),coord_y(indsel),Var,Xpoint(1),Xpoint(2));
228                    end
229               end
230            end
231        end
232    else    %case of structured coordinates
233        if  numel(VarType.coord)>=2 & VarType.coord(1:2) > 0;
234            AYName=FieldData.ListVarName{VarType.coord(1)};
235            AXName=FieldData.ListVarName{VarType.coord(2)};
236            eval(['AX=FieldData.' AXName ';']);% set of x positions
237            eval(['AY=FieldData.' AYName ';']);% set of y positions 
238            AName=FieldData.ListVarName{VarIndex(1)};% a single variable assumed in the current cell
239            eval(['A=FieldData.' AName ';']);% scalar
240            npxy=size(A);       
241            NbDim=numel(VarType.coord(VarType.coord>0));%number of space dimensions
242            %update VarDimName in case of components (non coordinate dimensions e;g. color components)
243            if numel(npxy)>NbDim
244                ProjData.VarDimName{end}={'nb_points','component'};
245            end
246            for idim=1:NbDim %loop on space dimensions
247                test_interp(idim)=0;%test for coordiate interpolation (non regular grid), =0 by default
248                test_coord(idim)=0;%test for defined coordinates, =0 by default
249                ivar=VarType.coord(idim);
250                Coord{idim}=FieldData.(FieldData.ListVarName{ivar}); % position for the first index
251                if numel(Coord{idim})==2
252                    DCoord_min(idim)= (Coord{idim}(2)-Coord{idim}(1))/(npxy(idim)-1);
253                else
254                    DCoord=diff(Coord{idim});
255                    DCoord_min(idim)=min(DCoord);
256                    DCoord_max=max(DCoord);
257                    test_direct(idim)=DCoord_max>0;% =1 for increasing values, 0 otherwise
258                    test_direct_min=DCoord_min(idim)>0;% =1 for increasing values, 0 otherwise
259                    if ~isequal(test_direct(idim),test_direct_min)
260                        errormsg=['non monotonic dimension variable # ' num2str(idim)  ' in proj_field.m'];
261                        return
262                    end
263                    test_interp(idim)=(DCoord_max-DCoord_min(idim))> 0.0001*abs(DCoord_max);% test grid regularity
264                    test_coord(idim)=1;
265                end
266            end
267            DX=DCoord_min(2);
268            DY=DCoord_min(1);
269            for ipoint=1:siz(1)
270                xwidth=width/(abs(DX));
271                ywidth=width/(abs(DY));
272                i_min=round((ObjectData.Coord(ipoint,1)-Coord{2}(1))/DX+0.5-xwidth); %minimum index of the selected region
273                i_min=max(1,i_min);%restrict to field limit
274                i_plus=round((ObjectData.Coord(ipoint,1)-Coord{2}(1))/DX+0.5+xwidth);
275                i_plus=min(npxy(2),i_plus); %restrict to field limit
276                j_min=round((ObjectData.Coord(ipoint,2)-Coord{1}(1))/DY-ywidth+0.5);
277                j_min=max(1,j_min);
278                j_plus=round((ObjectData.Coord(ipoint,2)-Coord{1}(1))/DY+ywidth+0.5);
279                j_plus=min(npxy(1),j_plus);
280                ProjData.X(ipoint,1)=ObjectData.Coord(ipoint,1);
281                ProjData.Y(ipoint,1)=ObjectData.Coord(ipoint,2);
282                i_int=(i_min:i_plus);
283                j_int=(j_min:j_plus);
284                ProjData.NbVal(ipoint,1)=length(j_int)*length(i_int);
285                if isempty(i_int) || isempty(j_int)
286                   for ivar=VarIndex   
287                        eval(['ProjData.' FieldData.ListVarName{ivar} '(ipoint,:)=NaN;']);
288                   end
289                   errormsg=['no data points in the selected projection range ' num2str(width) ];
290                else
291                    %TODO: introduce circle in the selected subregion
292                    %[I,J]=meshgrid([1:j_int],[1:i_int]);
293                    for ivar=VarIndex   
294                        Avalue=FieldData.(FieldData.ListVarName{ivar})(j_int,i_int,:);
295                        ProjData.(FieldData.ListVarName{ivar})(ipoint,:)=mean(mean(Avalue));
296                    end
297                end
298            end
299        end
300   end
301end
302
303%-----------------------------------------------------------------
304%project in a patch
305function  [ProjData,errormsg]=proj_patch(FieldData,ObjectData)%%
306%-------------------------------------------------------------------
307[ProjData,errormsg]=proj_heading(FieldData,ObjectData);
308
309objectfield=fieldnames(ObjectData);
310widthx=0;
311widthy=0;
312if isfield(ObjectData,'RangeX')&~isempty(ObjectData.RangeX)
313    widthx=max(ObjectData.RangeX);
314end
315if isfield(ObjectData,'RangeY')&~isempty(ObjectData.RangeY)
316    widthy=max(ObjectData.RangeY);
317end
318
319%A REVOIR, GENERALISER: UTILISER proj_line
320ProjData.NbDim=1;
321ProjData.ListVarName={};
322ProjData.VarDimName={};
323ProjData.VarAttribute={};
324
325Mesh=zeros(1,numel(FieldData.ListVarName));
326if isfield (FieldData,'VarAttribute')
327    %ProjData.VarAttribute=FieldData.VarAttribute;%list of variable attribute names
328    for iattr=1:length(FieldData.VarAttribute)%initialization of variable attribute values
329%         ProjData.VarAttribute{iattr}={};
330        if isfield(FieldData.VarAttribute{iattr},'Unit')
331            unit{iattr}=FieldData.VarAttribute{iattr}.Unit;
332        end
333        if isfield(FieldData.VarAttribute{iattr},'Mesh')
334            Mesh(iattr)=FieldData.VarAttribute{iattr}.Mesh;
335        end
336    end
337end
338
339%group the variables (fields of 'FieldData') in cells of variables with the same dimensions
340testfalse=0;
341ListIndex={};
342% DimVarIndex=0;%initilise list of indices for dimension variables
343idimvar=0;
344[CellVarIndex,NbDim,VarTypeCell,errormsg]=find_field_cells(FieldData);
345if ~isempty(errormsg)
346    errormsg=['error in proj_field/proj_patch:' errormsg];
347    return
348end
349
350%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
351dimcounter=0;
352for icell=1:length(CellVarIndex)
353    testX=0;
354    testY=0;
355    test_Amat=0;
356    testfalse=0;
357    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
358    VarType=VarTypeCell{icell};
359  %  DimIndices=FieldData.VarDimIndex{VarIndex(1)};%indices of the dimensions of the first variable (common to all variables in the cell)
360    if NbDim(icell)~=2% proj_patch acts only on fields of space dimension 2
361        continue
362    end
363    testX=~isempty(VarType.coord_x) && ~isempty(VarType.coord_y);
364    testfalse=~isempty(VarType.errorflag);
365    testproj(VarIndex)=zeros(size(VarIndex));%default
366    testproj(VarType.scalar)=1;
367    testproj(VarType.vector_x)=1;
368    testproj(VarType.vector_y)=1;
369    testproj(VarType.vector_z)=1;
370    testproj(VarType.image)=1;
371    testproj(VarType.color)=1;
372    VarIndex=VarIndex(find(testproj(VarIndex)));%select only the projected variables
373    if check_unstructured%case of unstructured coordinates
374         eval(['nbpoint=numel(FieldData.' FieldData.ListVarName{VarIndex(1)} ');'])
375         for ivar=[VarIndex VarType.coord_x VarType.coord_y VarType.errorflag]
376               VarName=FieldData.ListVarName{ivar};
377            eval(['FieldData.' VarName '=reshape(FieldData.' VarName ',nbpoint,1);'])
378         end
379         XName=FieldData.ListVarName{VarType.coord_x};
380         YName=FieldData.ListVarName{VarType.coord_y};
381         eval(['coord_x=FieldData.' XName ';'])
382         eval(['coord_y=FieldData.' YName ';'])
383    end
384    if testfalse
385        FFName=FieldData.ListVarName{VarType.errorflag};
386        eval(['errorflag=FieldData.' FFName ';'])
387    end
388    % image or 2D matrix
389    if numel(VarType.coord)>=2 & VarType.coord(1:2) > 0;
390        test_Amat=1;% test for image or 2D matrix
391        AYName=FieldData.ListVarName{VarType.coord(1)};
392        AXName=FieldData.ListVarName{VarType.coord(2)};
393        eval(['AX=FieldData.' AXName ';'])% x coordinate
394        eval(['AY=FieldData.' AYName ';'])% y coordinate
395        VarName=FieldData.ListVarName{VarIndex(1)};
396        DimValue=size(FieldData.(VarName));
397       if length(AX)==2
398           AX=linspace(AX(1),AX(end),DimValue(2));
399       end
400       if length(AY)==2
401           AY=linspace(AY(1),AY(end),DimValue(1));
402       end
403%         for idim=1:length(DimValue)       
404%             Coord_i_str=['Coord_' num2str(idim)];
405%             DCoord_min(idim)=1;%default
406%             Coord{idim}=[0.5 DimValue(idim)];
407%             test_direct(idim)=1;
408%         end
409%         AX=linspace(Coord{2}(1),Coord{2}(2),DimValue(2));
410%         AY=linspace(Coord{1}(1),Coord{1}(2),DimValue(1));  %TODO : 3D case
411%         testcolor=find(numel(DimValue)==3);
412        if length(DimValue)==3
413            testcolor=1;
414            npxy(3)=3;
415        else
416            testcolor=0;
417            npxy(3)=1;
418        end
419        [Xi,Yi]=meshgrid(AX,AY);
420        npxy(1)=length(AY);
421        npxy(2)=length(AX);
422        Xi=reshape(Xi,npxy(1)*npxy(2),1);
423        Yi=reshape(Yi,npxy(1)*npxy(2),1);
424        for ivar=1:length(VarIndex)
425            VarName=FieldData.ListVarName{VarIndex(ivar)};
426            FieldData.(VarName)=reshape(FieldData.(VarName),npxy(1)*npxy(2),npxy(3)); % keep only non false vectors
427        end
428    end
429%select the indices in the range of action
430    testin=[];%default
431    if isequal(ObjectData.Type,'rectangle')
432%            if ~isfield(ObjectData,'RangeX')|~isfield(ObjectData,'RangeY')
433%                 errormsg='rectangle half sides RangeX and RangeY needed'
434%                 return
435%            end
436       if testX
437            distX=abs(coord_x-ObjectData.Coord(1,1));
438            distY=abs(coord_y-ObjectData.Coord(1,2));
439            testin=distX<widthx & distY<widthy;
440       elseif test_Amat
441           distX=abs(Xi-ObjectData.Coord(1,1));
442           distY=abs(Yi-ObjectData.Coord(1,2));
443           testin=distX<widthx & distY<widthy;
444       end
445    elseif isequal(ObjectData.Type,'polygon')
446        if testX
447            testin=inpolygon(coord_x,coord_y,ObjectData.Coord(:,1),ObjectData.Coord(:,2));
448        elseif test_Amat
449           testin=inpolygon(Xi,Yi,ObjectData.Coord(:,1),ObjectData.Coord(:,2));
450       else%calculate the scalar
451           testin=[]; %A REVOIR
452       end
453    elseif isequal(ObjectData.Type,'ellipse')
454       X2Max=widthx*widthx;
455       Y2Max=(widthy)*(widthy);
456       if testX
457            distX=(coord_x-ObjectData.Coord(1,1));
458            distY=(coord_y-ObjectData.Coord(1,2));
459            testin=(distX.*distX/X2Max+distY.*distY/Y2Max)<1;
460       elseif test_Amat %case of usual 2x2 matrix
461           distX=(Xi-ObjectData.Coord(1,1));
462           distY=(Yi-ObjectData.Coord(1,2));
463           testin=(distX.*distX/X2Max+distY.*distY/Y2Max)<1;
464       end
465    end
466    %selected indices
467    if isequal(ObjectData.ProjMode,'outside')
468            testin=~testin;
469    end
470    if testfalse
471        testin=testin & (errorflag==0); % keep only non false vectors         
472    end
473    indsel=find(testin);
474    for ivar=VarIndex
475        if testproj(ivar)
476            VarName=FieldData.ListVarName{ivar};
477            ProjData.([VarName 'Mean'])=mean(double(FieldData.(VarName)(indsel,:))); % take the mean in the selected region, for each color component
478            ProjData.([VarName 'Min'])=min(double(FieldData.(VarName)(indsel,:))); % take the min in the selected region , for each color component 
479            ProjData.([VarName 'Max'])=max(double(FieldData.(VarName)(indsel,:))); % take the max in the selected region , for each color component
480            if isequal(Mesh(ivar),0)
481                eval(['[ProjData.' VarName 'Histo,ProjData.' VarName ']=hist(double(FieldData.' VarName '(indsel,:,:)),100);']); % default histogram with 100 bins
482            else
483                eval(['ProjData.' VarName '=(ProjData.' VarName 'Min+Mesh(ivar)/2:Mesh(ivar):ProjData.' VarName 'Max);']); % list of bin values
484                eval(['ProjData.' VarName 'Histo=hist(double(FieldData.' VarName '(indsel,:)),ProjData.' VarName ');']); % histogram at predefined bin positions
485            end
486            ProjData.ListVarName=[ProjData.ListVarName {VarName} {[VarName 'Histo']} {[VarName 'Mean']} {[VarName 'Min']} {[VarName 'Max']}];
487            if test_Amat && testcolor
488                 ProjData.VarDimName=[ProjData.VarDimName  {VarName} {{VarName,'rgb'}} {'rgb'} {'rgb'} {'rgb'}];%{{'nb_point','rgb'}};
489            else
490               ProjData.VarDimName=[ProjData.VarDimName {VarName} {VarName} {'one'} {'one'} {'one'}];
491            end
492            ProjData.VarAttribute=[ProjData.VarAttribute FieldData.VarAttribute{ivar} {[]} {[]} {[]} {[]}];
493        end
494    end
495%     if test_Amat & testcolor
496%        %ProjData.ListDimName=[ProjData.ListDimName {'rgb'}];
497%       % ProjData.DimValue=[ProjData.DimValue 3];
498%       % ProjData.VarDimIndex={[1 2]};
499%        ProjData.VarDimName=[ProjData.VarDimName {VarName} {VarName,'rgb'}];%{{'nb_point','rgb'}};
500%        ProjData.VarDimName
501%     end
502end
503
504
505%-----------------------------------------------------------------
506%project on a line
507% AJOUTER flux,circul,error
508% OUTPUT:
509% ProjData: projected field
510%
511function  [ProjData,errormsg] = proj_line(FieldData, ObjectData)
512%-----------------------------------------------------------------
513[ProjData,errormsg]=proj_heading(FieldData,ObjectData);%transfer global attributes
514if ~isempty(errormsg)
515    return
516end
517ProjData.NbDim=1;
518%initialisation of the input parameters and defaultoutput
519ProjMode=ObjectData.ProjMode;
520% ProjAngle=90; %90 degrees projection by default
521
522width=0;%default width of the projection band
523if isfield(ObjectData,'Range')&&size(ObjectData.Range,2)>=2
524    width=abs(ObjectData.Range(1,2));
525end
526if isfield(ObjectData,'RangeY')
527    width=max(ObjectData.RangeY);
528end
529
530% default output
531errormsg=[];%default
532Xline=[];
533flux=0;
534circul=0;
535liny=ObjectData.Coord(:,2);
536siz_line=size(ObjectData.Coord);
537if siz_line(1)<2
538    return% line needs at least 2 points to be defined
539end
540testfalse=0;
541ListIndex={};
542
543%% angles of the polyline and boundaries of action
544dlinx=diff(ObjectData.Coord(:,1));
545dliny=diff(ObjectData.Coord(:,2));
546theta=angle(dlinx+1i*dliny);%angle of each segment
547theta(siz_line(1))=theta(siz_line(1)-1);
548% determine a rectangles at +-width from the line (only used for the ProjMode='projection or 'filter')
549xsup=zeros(1,siz_line(1)); xinf=zeros(1,siz_line(1)); ysup=zeros(1,siz_line(1)); yinf=zeros(1,siz_line(1));
550if isequal(ProjMode,'projection') || isequal(ProjMode,'filter')
551    xsup(1)=ObjectData.Coord(1,1)-width*sin(theta(1));
552    xinf(1)=ObjectData.Coord(1,1)+width*sin(theta(1));
553    ysup(1)=ObjectData.Coord(1,2)+width*cos(theta(1));
554    yinf(1)=ObjectData.Coord(1,2)-width*cos(theta(1));
555    for ip=2:siz_line(1)
556        xsup(ip)=ObjectData.Coord(ip,1)-width*sin((theta(ip)+theta(ip-1))/2)/cos((theta(ip-1)-theta(ip))/2);
557        xinf(ip)=ObjectData.Coord(ip,1)+width*sin((theta(ip)+theta(ip-1))/2)/cos((theta(ip-1)-theta(ip))/2);
558        ysup(ip)=ObjectData.Coord(ip,2)+width*cos((theta(ip)+theta(ip-1))/2)/cos((theta(ip-1)-theta(ip))/2);
559        yinf(ip)=ObjectData.Coord(ip,2)-width*cos((theta(ip)+theta(ip-1))/2)/cos((theta(ip-1)-theta(ip))/2);
560    end
561end
562
563%% group the variables (fields of 'FieldData') in cells of variables with the same dimensions
564[CellVarIndex,NbDim,VarTypeCell,errormsg]=find_field_cells(FieldData);
565if ~isempty(errormsg)
566    errormsg=['error in proj_field/proj_line:' errormsg];
567    return
568end
569
570%% loop on variable cells with the same space dimension
571ProjData.ListVarName={};
572ProjData.VarDimName={};
573testproj=zeros(size(FieldData.ListVarName));
574for icell=1:length(CellVarIndex)
575    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
576    VarType=VarTypeCell{icell}; %types of variables
577    if NbDim(icell)~=2% proj_line acts only on fields of space dimension 2, TODO: check 3D case
578        continue
579    end
580    check_unstructured=~isempty(VarType.coord_x) && ~isempty(VarType.coord_y);% test for unstructured coordinates
581    test_tps=~isempty(VarType.coord_tps);
582    testU=~isempty(VarType.vector_x) && ~isempty(VarType.vector_y);% test for vectors
583    testfalse=~isempty(VarType.errorflag);% test for error flag
584    testproj(VarIndex)=zeros(size(VarIndex));% test =1 for simply projected variables, default =0
585                                             %=0 for vector components, treated separately
586    testproj([VarType.scalar VarType.image VarType.color VarType.vector_x VarType.vector_y])=1;
587    VarIndex=VarIndex(find(testproj(VarIndex)));%select only the projected variables
588
589    %identify vector components   
590    if testU
591        UName=FieldData.ListVarName{VarType.vector_x};
592        VName=FieldData.ListVarName{VarType.vector_y};
593        vector_x=FieldData.(UName);
594        vector_y=FieldData.(VName);
595    end 
596    %identify error flag
597    if testfalse
598        FFName=FieldData.ListVarName{VarType.errorflag};
599        errorflag=FieldData.(FFName);
600    end   
601    % check needed object properties for unstructured positions (position given by the variables with role coord_x, coord_y
602    if check_unstructured
603        if  ~isequal(ProjMode,'interp')
604            if width==0
605                errormsg='range of the projection object is missing';
606                return     
607            else
608                lambda=2/(width*width); %smoothing factor used for filter: weight exp(-2) at distance width from the line
609            end
610        end
611        if ~isequal(ProjMode,'projection')
612            if isfield(ObjectData,'DX')&~isempty(ObjectData.DX)
613                DX=abs(ObjectData.DX);%mesh of interpolation points along the line
614            else
615                errormsg='DX missing';
616                return
617            end
618        end
619        XName= FieldData.ListVarName{VarType.coord_x};
620        YName= FieldData.ListVarName{VarType.coord_y};
621        coord_x=FieldData.(XName);   
622        coord_y=FieldData.(YName);
623    end   
624    %initiate projection
625    for ivar=1:length(VarIndex)
626        ProjLine{ivar}=[];
627    end
628    XLine=[];
629    linelengthtot=0;
630
631%         circul=0;
632%         flux=0;
633  %%%%%%%  % A FAIRE CALCULER MEAN DES QUANTITES    %%%%%%
634   %case of unstructured coordinates
635    if check_unstructured   
636        for ip=1:siz_line(1)-1     %Loop on the segments of the polyline
637            linelength=sqrt(dlinx(ip)*dlinx(ip)+dliny(ip)*dliny(ip)); 
638            %select the vector indices in the range of action
639            if testfalse
640                flagsel=(errorflag==0); % keep only non false vectors
641            else
642                flagsel=ones(size(coord_x));
643            end
644            if isequal(ProjMode,'projection') | isequal(ProjMode,'filter')
645                flagsel=flagsel & ((coord_y -yinf(ip))*(xinf(ip+1)-xinf(ip))>(coord_x-xinf(ip))*(yinf(ip+1)-yinf(ip))) ...
646                & ((coord_y -ysup(ip))*(xsup(ip+1)-xsup(ip))<(coord_x-xsup(ip))*(ysup(ip+1)-ysup(ip))) ...
647                & ((coord_y -yinf(ip+1))*(xsup(ip+1)-xinf(ip+1))>(coord_x-xinf(ip+1))*(ysup(ip+1)-yinf(ip+1))) ...
648                & ((coord_y -yinf(ip))*(xsup(ip)-xinf(ip))<(coord_x-xinf(ip))*(ysup(ip)-yinf(ip)));
649            end
650            indsel=find(flagsel);%indsel =indices of good vectors
651            X_sel=coord_x(indsel);
652            Y_sel=coord_y(indsel);
653            nbvar=0;
654            for iselect=1:numel(VarIndex)-2*testU
655                VarName=FieldData.ListVarName{VarIndex(iselect)};
656                eval(['ProjVar{iselect}=FieldData.' VarName '(indsel);']);%scalar value
657            end   
658            if testU
659                ProjVar{numel(VarIndex)-1}=cos(theta(ip))*vector_x(indsel)+sin(theta(ip))*vector_y(indsel);% longitudinal component
660                ProjVar{numel(VarIndex)}=-sin(theta(ip))*vector_x(indsel)+cos(theta(ip))*vector_y(indsel);%transverse component         
661            end
662            if isequal(ProjMode,'projection')
663                sintheta=sin(theta(ip));
664                costheta=cos(theta(ip));
665                Xproj=(X_sel-ObjectData.Coord(ip,1))*costheta + (Y_sel-ObjectData.Coord(ip,2))*sintheta; %projection on the line
666                [Xproj,indsort]=sort(Xproj);
667                for ivar=1:numel(ProjVar)
668                    if ~isempty(ProjVar{ivar})
669                        ProjVar{ivar}=ProjVar{ivar}(indsort);
670                     end
671                end
672            elseif isequal(ProjMode,'interp') %linear interpolation:
673                npoint=floor(linelength/DX)+1;% nbre of points in the profile (interval DX)
674                Xproj=linelength/(2*npoint):linelength/npoint:linelength-linelength/(2*npoint);
675                xreg=cos(theta(ip))*Xproj+ObjectData.Coord(ip,1);
676                yreg=sin(theta(ip))*Xproj+ObjectData.Coord(ip,2);
677                for ivar=1:numel(ProjVar)
678                     if ~isempty(ProjVar{ivar})
679                        ProjVar{ivar}=griddata_uvmat(X_sel,Y_sel,ProjVar{ivar},xreg,yreg);
680                     end
681                end
682            elseif isequal(ProjMode,'filter') %filtering
683                npoint=floor(linelength/DX)+1;% nbre of points in the profile (interval DX)
684                Xproj=linelength/(2*npoint):linelength/npoint:linelength-linelength/(2*npoint);
685                siz=size(X_sel);
686                xregij=cos(theta(ip))*ones(siz(1),1)*Xproj+ObjectData.Coord(ip,1);
687                yregij=sin(theta(ip))*ones(siz(1),1)*Xproj+ObjectData.Coord(ip,2);
688                xij=X_sel*ones(1,npoint);
689                yij=Y_sel*ones(1,npoint);
690                Aij=exp(-lambda*((xij-xregij).*(xij-xregij)+(yij-yregij).*(yij-yregij)));
691                norm=Aij'*ones(siz(1),1);
692                for ivar=1:numel(ProjVar)
693                     if ~isempty(ProjVar{ivar})
694                        ProjVar{ivar}=Aij'*ProjVar{ivar}./norm;
695                     end
696                end             
697            end
698            %prolongate the total record
699            for ivar=1:numel(ProjVar)
700                  if ~isempty(ProjVar{ivar})
701                     ProjLine{ivar}=[ProjLine{ivar}; ProjVar{ivar}];
702                  end
703            end
704            XLine=[XLine ;(Xproj+linelengthtot)];%along line abscissa
705            linelengthtot=linelengthtot+linelength;
706            %     circul=circul+(sum(U_sel))*linelength/npoint;
707            %     flux=flux+(sum(V_sel))*linelength/npoint;
708        end
709        ProjData.X=XLine';
710        ProjData.ListVarName=[ProjData.ListVarName {XName}];
711        ProjData.VarDimName=[ProjData.VarDimName {XName}];
712        ProjData.VarAttribute{1}.long_name='abscissa along line';
713        for iselect=1:numel(VarIndex)
714            VarName=FieldData.ListVarName{VarIndex(iselect)};
715            eval(['ProjData.' VarName '=ProjLine{iselect};'])
716            ProjData.ListVarName=[ProjData.ListVarName {VarName}];
717            ProjData.VarDimName=[ProjData.VarDimName {XName}];
718            ProjData.VarAttribute{iselect}=FieldData.VarAttribute{VarIndex(iselect)};
719            if strcmp(ProjMode,'projection')
720                ProjData.VarAttribute{iselect}.Role='discrete';
721            else
722                 ProjData.VarAttribute{iselect}.Role='continuous';
723            end
724        end
725   
726    %case of structured coordinates
727    elseif  numel(VarType.coord)>=2 & VarType.coord(1:2) > 0;
728        if ~isequal(ObjectData.Type,'line')% exclude polyline
729            errormsg=['no  projection available on ' ObjectData.Type 'for structured coordinates']; %
730        else
731            test_Amat=1;%image or 2D matrix
732            test_interp2=0;%default
733%             if ~isempty(VarType.coord_y) 
734            AYName=FieldData.ListVarName{VarType.coord(1)};
735            AXName=FieldData.ListVarName{VarType.coord(2)};
736            eval(['AX=FieldData.' AXName ';']);% set of x positions
737            eval(['AY=FieldData.' AYName ';']);% set of y positions 
738            AName=FieldData.ListVarName{VarIndex(1)};
739            eval(['A=FieldData.' AName ';']);% scalar
740            npxy=size(A);
741            npx=npxy(2);
742            npy=npxy(1);
743            if numel(AX)==2
744                DX=(AX(2)-AX(1))/(npx-1);
745            else
746                DX_vec=diff(AX);
747                DX=max(DX_vec);
748                DX_min=min(DX_vec);
749                if (DX-DX_min)>0.0001*abs(DX)
750                    test_interp2=1;
751                    DX=DX_min;
752                end   
753            end
754            if numel(AY)==2
755                DY=(AY(2)-AY(1))/(npy-1);
756            else
757                DY_vec=diff(AY);
758                DY=max(DY_vec);
759                DY_min=min(DY_vec);
760                if (DY-DY_min)>0.0001*abs(DY)
761                   test_interp2=1;
762                    DY=DY_min;
763                end     
764            end             
765            AXI=linspace(AX(1),AX(end), npx);%set of  x  positions for the interpolated input data
766            AYI=linspace(AY(1),AY(end), npy);%set of  x  positions for the interpolated input data
767            if isfield(ObjectData,'DX')
768                DXY_line=ObjectData.DX;%mesh on the projection line
769            else
770                DXY_line=sqrt(abs(DX*DY));% mesh on the projection line
771            end
772            dlinx=ObjectData.Coord(2,1)-ObjectData.Coord(1,1);
773            dliny=ObjectData.Coord(2,2)-ObjectData.Coord(1,2);
774            linelength=sqrt(dlinx*dlinx+dliny*dliny);
775            theta=angle(dlinx+i*dliny);%angle of the line   
776            if isfield(FieldData,'RangeX')
777                XMin=min(FieldData.RangeX);%shift of the origin on the line
778            else
779                XMin=0;
780            end
781            eval(['ProjData.' AXName '=linspace(XMin,XMin+linelength,linelength/DXY_line+1);'])%abscissa of the new pixels along the line
782            y=linspace(-width,width,2*width/DXY_line+1);%ordintes of the new pixels (coordinate across the line)
783            eval(['npX=length(ProjData.' AXName ');'])
784            npY=length(y); %TODO: utiliser proj_grid
785            eval(['[X,Y]=meshgrid(ProjData.' AXName ',y);'])%grid in the line coordinates
786            XIMA=ObjectData.Coord(1,1)+(X-XMin)*cos(theta)-Y*sin(theta);
787            YIMA=ObjectData.Coord(1,2)+(X-XMin)*sin(theta)+Y*cos(theta);
788            XIMA=(XIMA-AX(1))/DX+1;%  index of the original image along x
789            YIMA=(YIMA-AY(1))/DY+1;% index of the original image along y
790            XIMA=reshape(round(XIMA),1,npX*npY);%indices reorganized in 'line'
791            YIMA=reshape(round(YIMA),1,npX*npY);
792            flagin=XIMA>=1 & XIMA<=npx & YIMA >=1 & YIMA<=npy;%flagin=1 inside the original image
793            ind_in=find(flagin);
794            ind_out=find(~flagin);
795            ICOMB=(XIMA-1)*npy+YIMA;
796            ICOMB=ICOMB(flagin);%index corresponding to XIMA and YIMA in the aligned original image vec_A
797            nbcolor=1; %color images
798            if numel(npxy)==2
799                nbcolor=1;
800            elseif length(npxy)==3
801                nbcolor=npxy(3);
802            else
803                errormsg='multicomponent field not projected';
804                display(errormsg)
805                return
806            end
807            nbvar=length(ProjData.ListVarName);% number of var from previous cells
808            ProjData.ListVarName=[ProjData.ListVarName {AXName}];
809            ProjData.VarDimName=[ProjData.VarDimName {AXName}];
810            for ivar=VarIndex
811                %VarName{ivar}=FieldData.ListVarName{ivar};
812                if test_interp2% interpolate on new grid
813                    FieldData.(FieldData.ListVarName{ivar})=interp2(FieldData.(AXName),FieldData.(AYName),FieldData.(FieldData.ListVarName{ivar}),AXI,AYI);%TO TEST
814                end
815                vec_A=reshape(squeeze(FieldData.(FieldData.ListVarName{ivar})),npx*npy,nbcolor); %put the original image in colum
816                if nbcolor==1
817                    vec_B(ind_in)=vec_A(ICOMB);
818                    vec_B(ind_out)=zeros(size(ind_out));
819                    A_out=reshape(vec_B,npY,npX);
820                    ProjData.(FieldData.ListVarName{ivar}) =sum(A_out,1)/npY;
821                elseif nbcolor==3
822                    vec_B(ind_in,1:3)=vec_A(ICOMB,:);
823                    vec_B(ind_out,1)=zeros(size(ind_out));
824                    vec_B(ind_out,2)=zeros(size(ind_out));
825                    vec_B(ind_out,3)=zeros(size(ind_out));
826                    A_out=reshape(vec_B,npY,npX,nbcolor);
827                    ProjData.(FieldData.ListVarName{ivar})=squeeze(sum(A_out,1)/npY);
828                end 
829                ProjData.ListVarName=[ProjData.ListVarName FieldData.ListVarName{ivar}];
830                ProjData.VarDimName=[ProjData.VarDimName {AXName}];%to generalize with the initial name of the x coordinate
831                ProjData.VarAttribute{ivar}.Role='continuous';% for plot with continuous line
832            end
833            if testU
834                 vector_x =ProjData.(FieldData.ListVarName{VarType.vector_x});
835                 vector_y =ProjData.(FieldData.ListVarName{VarType.vector_y});
836                 ProjData.(FieldData.ListVarName{VarType.vector_x}) =cos(theta)*vector_x+sin(theta)*vector_y;
837                 ProjData.(FieldData.ListVarName{VarType.vector_y}) =-sin(theta)*vector_x+cos(theta)*vector_y;
838            end
839            ProjData.VarAttribute{nbvar+1}.long_name='abscissa along line';
840            if nbcolor==3
841                ProjData.VarDimName{end}={AXName,'rgb'};
842            end
843        end
844    elseif test_tps
845         if isfield(ObjectData,'DX')&~isempty(ObjectData.DX)
846                DX=abs(ObjectData.DX);%mesh of interpolation points along the line
847                Xproj=linelength/(2*npoint):linelength/npoint:linelength-linelength/(2*npoint);
848                xreg=cos(theta(ip))*Xproj+ObjectData.Coord(ip,1)
849                yreg=sin(theta(ip))*Xproj+ObjectData.Coord(ip,2)
850%                 coord_x_proj=XMin:DX:XMax;
851%                 coord_y_proj=YMin:DY:YMax;
852                DataOut=calc_field(FieldData.FieldList,FieldData,cat(3,xreg,yreg));
853                ProjData.ListVarName=[ProjData.ListVarName DataOut.ListVarName];
854                ProjData.VarDimName=[ProjData.VarDimName DataOut.VarDimName];
855                ProjData.VarAttribute=[ProjData.VarAttribute DataOut.VarAttribute];   
856                DataOut.ListVarName(1)=[];
857                DataOut.VarDimName(1)=[];
858                DataOut.VarAttribute(1)=[];
859                for ilist=2:length(DataOut.ListVarName)% reshape data, excluding coordinates (ilist=1-2), TODO: rationalise
860                    VarName=DataOut.ListVarName{ilist};
861                     ProjData.(VarName)=DataOut.(VarName);
862                end
863                ProjData.coord_x=Xproj;
864         end
865    end
866end
867
868% %shotarter case for horizontal or vertical line (A FAIRE
869% %     Rangx=[0.5 npx-0.5];%image coordiantes of corners
870% %     Rangy=[npy-0.5 0.5];
871% %     if isfield(Calib,'Pxcmx')&isfield(Calib,'Pxcmy')%old calib
872% %         Rangx=Rangx/Calib.Pxcmx;
873% %         Rangy=Rangy/Calib.Pxcmy;
874% %     else
875% %         [Rangx]=phys_XYZ(Calib,Rangx,[0.5 0.5],[0 0]);%case of translations without rotation and quadratic deformation
876% %         [xx,Rangy]=phys_XYZ(Calib,[0.5 0.5],Rangy,[0 0]);
877% %     end
878%
879% %     test_scal=0;%default% 3- 'UserData':(get(handles.Tag,'UserData')
880
881
882%-----------------------------------------------------------------
883%project on a plane
884% AJOUTER flux,circul,error
885 function  [ProjData,errormsg] = proj_plane(FieldData, ObjectData)
886%-----------------------------------------------------------------
887
888%% rotation angles
889PlaneAngle=[0 0 0];
890norm_plane=[0 0 1];
891cos_om=1;
892sin_om=0;
893test90x=0;%=1 for 90 degree rotation alround x axis
894test90y=0;%=1 for 90 degree rotation alround y axis
895if isfield(ObjectData,'Angle')&& isequal(size(ObjectData.Angle),[1 3])&& ~isequal(ObjectData.Angle,[0 0 0])
896    test90y=isequal(ObjectData.Angle,[0 90 0]);
897    PlaneAngle=(pi/180)*ObjectData.Angle;
898    om=norm(PlaneAngle);%norm of rotation angle in radians
899    OmAxis=PlaneAngle/om; %unit vector marking the rotation axis
900    cos_om=cos(om);
901    sin_om=sin(om);
902    coeff=OmAxis(3)*(1-cos_om);
903    %components of the unity vector norm_plane normal to the projection plane
904    norm_plane(1)=OmAxis(1)*coeff+OmAxis(2)*sin_om;
905    norm_plane(2)=OmAxis(2)*coeff-OmAxis(1)*sin_om;
906    norm_plane(3)=OmAxis(3)*coeff+cos_om;
907end
908testangle=~isequal(PlaneAngle,[0 0 0]);% && ~test90y && ~test90x;%=1 for slanted plane
909
910%% mesh sizes DX and DY
911if isfield(ObjectData,'DX') && ~isempty(ObjectData.DX)
912     DX=abs(ObjectData.DX);%mesh of interpolation points
913else
914    DX=FieldData.Mesh;
915end
916if isfield(ObjectData,'DY') && ~isempty(ObjectData.DY)
917     DY=abs(ObjectData.DY);%mesh of interpolation points
918else
919    DY=FieldData.Mesh;
920end
921if  ~strcmp(ObjectData.ProjMode,'projection') && (DX==0||DY==0)
922        errormsg='DX or DY missing';
923        display(errormsg)
924        return
925end
926
927%% extrema along each axis
928testXMin=0;
929testXMax=0;
930testYMin=0;
931testYMax=0;
932
933if isfield(ObjectData,'RangeX')
934        XMin=min(ObjectData.RangeX);
935        XMax=max(ObjectData.RangeX);
936        testXMin=XMax>XMin;
937        testXMax=1;
938else
939    XMin=FieldData.XMin;%default
940XMax=FieldData.XMax;%default
941end
942if isfield(ObjectData,'RangeY')
943        YMin=min(ObjectData.RangeY);
944        YMax=max(ObjectData.RangeY);
945        testYMin=YMax>YMin;
946        testYMax=1;
947else
948    YMin=FieldData.YMin;%default
949YMax=FieldData.YMax;%default
950end
951width=0;%default width of the projection band
952if isfield(ObjectData,'RangeZ')
953        width=max(ObjectData.RangeZ);
954end
955
956%% initiate Matlab  structure for physical field
957[ProjData,errormsg]=proj_heading(FieldData,ObjectData);
958ProjData.NbDim=2;
959ProjData.ListVarName={};
960ProjData.VarDimName={};
961ProjData.VarAttribute={};
962if ~isequal(DX,0)&& ~isequal(DY,0)
963    ProjData.Mesh=sqrt(DX*DY);%define typical data mesh, useful for mouse selection in plots
964elseif isfield(FieldData,'Mesh')
965    ProjData.Mesh=FieldData.Mesh;
966end
967error=0;%default
968flux=0;
969testfalse=0;
970ListIndex={};
971
972%% group the variables (fields of 'FieldData') in cells of variables with the same dimensions
973% CellVarIndex=cells of variable index arrays
974[CellVarIndex,NbDimVec,VarTypeCell,errormsg]=find_field_cells(FieldData);
975if ~isempty(errormsg)
976    errormsg=['error in proj_field/proj_plane:' errormsg];
977    return
978end
979
980%% projection modes
981check_grid=0;
982ProjMode=cell(size(VarTypeCell));
983for icell=1:numel(VarTypeCell)% TODO: recalculate coordinates here to get the bounds in the rotated coordinates
984    ProjMode{icell}=ObjectData.ProjMode;
985    if isfield(VarTypeCell{icell},'FieldRequest')
986        switch VarTypeCell{icell}.FieldRequest
987            case 'interp_lin'
988                ProjMode{icell}='interp';
989            case 'interp_tps'
990                ProjMode{icell}='filter';
991        end
992    end
993    if strcmp(ProjMode{icell},'interp')||strcmp(ProjMode{icell},'filter')
994        check_grid=1;
995    end
996end
997
998%% define the new coordinates in case of interpolation on a grid
999if check_grid% TODO: recalculate coordinates to get the bounds in the rotated coordinates
1000    ProjData.ListVarName={'coord_y','coord_x'};
1001    ProjData.VarDimName={'coord_y','coord_x'}; 
1002    ProjData.VarAttribute={[],[]};
1003    ProjData.coord_y=[YMin YMax];
1004    ProjData.coord_x=[XMin XMax];
1005end
1006
1007%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1008% LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
1009% CellVarIndex=cells of variable index arrays
1010ivar_new=0; % index of the current variable in the projected field
1011% icoord=0;
1012nbcoord=0;%number of added coordinate variables brought by projection
1013nbvar=0;
1014vector_x_proj=[];
1015vector_y_proj=[];
1016for icell=1:length(CellVarIndex)
1017    NbDim=NbDimVec(icell);
1018    if NbDim<2
1019        continue % only cells represnting 2D or 3D fields are involved
1020    end
1021    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
1022    VarType=VarTypeCell{icell};
1023    ivar_U=VarType.vector_x;
1024    ivar_V=VarType.vector_y;
1025    if ~isempty(VarType.vector_x_tps)&&~isempty(VarType.vector_y_tps)
1026        ivar_U=VarType.vector_x_tps;
1027        ivar_V=VarType.vector_y_tps;
1028    end
1029    ivar_W=VarType.vector_z;
1030
1031    %type of coordinates
1032    if ~isempty(VarType.coord_x) && ~isempty(VarType.coord_y)
1033        CoordType='unstructured';
1034    elseif ~isempty(VarType.coord_tps)
1035        CoordType='tps';
1036    else
1037        CoordType='structured';
1038    end
1039   
1040    %dimensions
1041    DimCell=FieldData.VarDimName{VarIndex(1)};
1042    if ischar(DimCell)
1043        DimCell={DimCell};%name of dimensions
1044    end
1045    coord_z=0;%default
1046
1047    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1048    switch CoordType
1049       
1050        %% case of input fields with unstructured coordinates
1051        case 'unstructured'
1052            if strcmp(ProjMode{icell},'filter')
1053                continue %skip for filter (needs tps field cell)
1054            end
1055            coord_x=FieldData.(FieldData.ListVarName{VarType.coord_x});% initial x coordinates
1056            coord_y=FieldData.(FieldData.ListVarName{VarType.coord_y});% initial y coordinates
1057            if ~isempty(VarType.coord_z)
1058                coord_z=FieldData.(FieldData.ListVarName{VarType.coord_z});% initial z coordinates
1059            end
1060           
1061            % translate  initial coordinates to account for the new origin
1062            coord_x=coord_x-ObjectData.Coord(1,1);
1063            coord_y=coord_y-ObjectData.Coord(1,2);
1064            if ~isempty(VarType.coord_z)
1065                coord_z=coord_z-ObjectData.Coord(1,3);
1066            end
1067           
1068            % selection of the vectors in the projection range (3D case)
1069            if ~isempty(VarType.coord_z) &&  width > 0
1070                %components of the unitiy vector normal to the projection plane
1071                fieldZ=norm_plane(1)*coord_x + norm_plane(2)*coord_y+ norm_plane(3)*coord_z;% distance to the plane
1072                indcut=find(abs(fieldZ) <= width);
1073                for ivar=VarIndex
1074                    VarName=FieldData.ListVarName{ivar};
1075                    eval(['FieldData.' VarName '=FieldData.' VarName '(indcut);'])
1076                    % A VOIR : CAS DE VAR STRUCTUREE MAIS PAS GRILLE REGULIERE : INTERPOLER SUR GRILLE REGULIERE
1077                end
1078                coord_x=coord_x(indcut);
1079                coord_y=coord_y(indcut);
1080                coord_z=coord_z(indcut);
1081            end
1082           
1083            %rotate coordinates if needed: coord_X,coord_Y= = coordinates in the new plane
1084            Psi=PlaneAngle(1);
1085            Theta=PlaneAngle(2);
1086            Phi=PlaneAngle(3);
1087            if testangle && ~test90y && ~test90x;%=1 for slanted plane
1088                coord_X=(coord_x *cos(Phi) + coord_y* sin(Phi));
1089                coord_Y=(-coord_x *sin(Phi) + coord_y *cos(Phi))*cos(Theta);
1090                coord_Y=coord_Y+coord_z *sin(Theta);
1091                coord_X=(coord_X *cos(Psi) - coord_Y* sin(Psi));%A VERIFIER               
1092                coord_Y=(coord_X *sin(Psi) + coord_Y* cos(Psi));
1093            else
1094                coord_X=coord_x;
1095                coord_Y=coord_y;
1096            end
1097           
1098            %restriction to the range of X and Y if imposed by the projection object
1099            testin=ones(size(coord_X)); %default
1100            testbound=0;
1101            if testXMin
1102                testin=testin & (coord_X >= XMin);
1103                testbound=1;
1104            end
1105            if testXMax
1106                testin=testin & (coord_X <= XMax);
1107                testbound=1;
1108            end
1109            if testYMin
1110                testin=testin & (coord_Y >= YMin);
1111                testbound=1;
1112            end
1113            if testYMin
1114                testin=testin & (coord_Y <= YMax);
1115                testbound=1;
1116            end
1117            if testbound
1118                indcut=find(testin);
1119                if isempty(indcut)
1120                    errormsg='data outside the bounds of the projection object';
1121                    return
1122                end
1123                for ivar=VarIndex
1124                    VarName=FieldData.ListVarName{ivar};
1125                    FieldData.(VarName)=FieldData.(VarName)(indcut);
1126                end
1127                coord_X=coord_X(indcut);
1128                coord_Y=coord_Y(indcut);
1129                if ~isempty(VarType.coord_z)
1130                    coord_Z=coord_Z(indcut);
1131                end
1132            end
1133           
1134            % different cases of projection
1135            switch ProjMode{icell}
1136                case 'projection' 
1137                    nbvar=numel(ProjData.ListVarName);
1138                    for ivar=VarIndex %transfer variables to the projection plane
1139                        VarName=FieldData.ListVarName{ivar};
1140                        if ivar==VarType.coord_x %x coordinate
1141                            ProjData.(VarName)=coord_X;
1142                        elseif ivar==VarType.coord_y  % y coordinate
1143                            ProjData.(VarName)=coord_Y;
1144                        elseif isempty(VarType.coord_z) || ivar~=VarType.coord_z % other variables (except Z coordinate wyhich is not reproduced)
1145                            ProjData.(VarName)=FieldData.(VarName);
1146                        end
1147                        if isempty(VarType.coord_z) || ivar~=VarType.coord_z
1148                            ProjData.ListVarName=[ProjData.ListVarName VarName];
1149                            ProjData.VarDimName=[ProjData.VarDimName DimCell];
1150                            nbvar=nbvar+1;
1151                            if isfield(FieldData,'VarAttribute') && length(FieldData.VarAttribute) >=ivar
1152                                ProjData.VarAttribute{nbvar}=FieldData.VarAttribute{ivar};
1153                            end
1154                        end
1155                    end
1156                case 'interp'%interpolate data on a regular grid
1157                    coord_x_proj=XMin:DX:XMax;
1158                    coord_y_proj=YMin:DY:YMax;
1159                    [XI,YI]=meshgrid(coord_x_proj,coord_y_proj);
1160                    if ~isempty(VarType.errorflag)
1161                        VarName_FF=FieldData.ListVarName{VarType.errorflag};
1162                        indsel=find(FieldData.(VarName_FF)==0);
1163                        coord_X=coord_X(indsel);
1164                        coord_Y=coord_Y(indsel);
1165                    end
1166%                     testFF=0;
1167%                     nbvar=numel(ProjData.ListVarName);
1168                    if isfield(VarType,'vector_x')&&isfield(VarType,'vector_y')&&~isempty(VarType.vector_x)
1169                        VarName_x=FieldData.ListVarName{VarType.vector_x};
1170                        VarName_y=FieldData.ListVarName{VarType.vector_y};
1171                        if ~isempty(VarType.errorflag)
1172                            FieldData.(VarName_x)=FieldData.(VarName_x)(indsel);
1173                            FieldData.(VarName_y)=FieldData.(VarName_y)(indsel);
1174                        end
1175                        %FieldVar=cat(2,FieldData.(VarName_x),FieldData.(VarName_y));
1176                        if ~isfield(VarType,'CheckSub') || ~VarType.CheckSub
1177                            vector_x_proj=numel(ProjData.ListVarName)+1;
1178                            vector_y_proj=numel(ProjData.ListVarName)+2;
1179                        end
1180                    end
1181                    if ~isempty(VarType.scalar)
1182                        VarName_scalar=FieldData.ListVarName{VarType.scalar};
1183                        if ~isempty(VarType.errorflag)
1184                            FieldData.(VarName_scalar)=FieldData.(VarName_scalar)(indsel);
1185                        end
1186                       % FieldVar=FieldData.(VarName_scalar);
1187                    end
1188                    if ~isempty(VarType.ancillary)% do not project ancillary data with interp
1189                        FieldData=rmfield(FieldData,FieldData.ListVarName{VarType.ancillary});
1190                    end
1191                    if ~isempty(VarType.warnflag)% do not project ancillary data with interp
1192                        FieldData=rmfield(FieldData,FieldData.ListVarName{VarType.warnflag});
1193                    end
1194                    [VarVal,ListFieldProj,VarAttribute,errormsg]=calc_field_interp([coord_X coord_Y],FieldData,VarType.Operation,XI,YI);
1195                    if isfield(VarType,'CheckSub') && VarType.CheckSub && ~isempty(vector_x_proj)
1196                        ProjData.(ProjData.ListVarName{vector_x_proj})=ProjData.(ProjData.ListVarName{vector_x_proj})-VarVal{1};
1197                        ProjData.(ProjData.ListVarName{vector_y_proj})=ProjData.(ProjData.ListVarName{vector_y_proj})-VarVal{2};
1198                    else
1199                        VarDimName=cell(size(ListFieldProj));
1200                        for ilist=1:numel(ListFieldProj)% reshape data, excluding coordinates (ilist=1-2), TODO: rationalise
1201                            ListFieldProj{ilist}=regexprep(ListFieldProj{ilist},'(.+','');
1202                            if ~isempty(find(strcmp(ListFieldProj{ilist},ProjData.ListVarName)))
1203                                ListFieldProj{ilist}=[ListFieldProj{ilist} '_1'];
1204                            end                       
1205                            ProjData.(ListFieldProj{ilist})=VarVal{ilist};
1206                            VarDimName{ilist}={'coord_y','coord_x'};
1207                        end
1208                        ProjData.ListVarName=[ProjData.ListVarName ListFieldProj];
1209                        ProjData.VarDimName=[ProjData.VarDimName VarDimName];
1210                        ProjData.VarAttribute=[ProjData.VarAttribute VarAttribute];
1211                    end
1212            end
1213
1214            %% case of tps interpolation (applies only in filter mode and for spatial derivatives)
1215        case 'tps'
1216            if strcmp(ProjMode{icell},'filter')
1217                Coord=FieldData.(FieldData.ListVarName{VarType.coord_tps});
1218                NbSites=FieldData.(FieldData.ListVarName{VarType.nbsites_tps});
1219                SubRange=FieldData.(FieldData.ListVarName{VarType.subrange_tps});
1220                if isfield(VarType,'vector_x_tps')&&isfield(VarType,'vector_y_tps')
1221                    FieldVar=cat(3,FieldData.(FieldData.ListVarName{VarType.vector_x_tps}),FieldData.(FieldData.ListVarName{VarType.vector_y_tps}));
1222                end
1223                coord_x_proj=XMin:DX:XMax;
1224                coord_y_proj=YMin:DY:YMax;
1225                np_x=numel(coord_x_proj);
1226                np_y=numel(coord_y_proj);
1227                [XI,YI]=meshgrid(coord_x_proj,coord_y_proj');
1228                XI=XI+ObjectData.Coord(1,1);
1229                YI=YI+ObjectData.Coord(1,2);
1230                [DataOut,VarAttribute,errormsg]=calc_field_tps(Coord,NbSites,SubRange,FieldVar,VarType.Operation,cat(3,XI,YI));   
1231                ListFieldProj=(fieldnames(DataOut))';
1232                VarDimName=cell(size(ListFieldProj));
1233                for ilist=1:numel(ListFieldProj)% reshape data, excluding coordinates (ilist=1-2), TODO: rationalise
1234                    VarName=ListFieldProj{ilist};
1235                    ProjData.(VarName)=DataOut.(VarName);
1236                    VarDimName{ilist}={'coord_y','coord_x'};
1237                end
1238                ProjData.ListVarName=[ProjData.ListVarName ListFieldProj];
1239                ProjData.VarDimName=[ProjData.VarDimName VarDimName];
1240                ProjData.VarAttribute=[ProjData.VarAttribute VarAttribute];
1241            end
1242           
1243            %% case of input fields defined on a structured  grid
1244        case 'structured'
1245           
1246            VarName=FieldData.ListVarName{VarIndex(1)};%get the first variable of the cell to get the input matrix dimensions
1247            DimValue=size(FieldData.(VarName));%input matrix dimensions
1248            DimValue(DimValue==1)=[];%remove singleton dimensions
1249            NbDim=numel(DimValue);%update number of space dimensions
1250            nbcolor=1; %default number of 'color' components: third matrix index without corresponding coordinate
1251            if NbDim>=3
1252                if NbDim>3
1253                    errormsg='matrices with more than 3 dimensions not handled';
1254                    return
1255                else
1256                    if numel(find(VarType.coord))==2% the third matrix dimension does not correspond to a space coordinate
1257                        nbcolor=DimValue(3);
1258                        DimValue(3)=[]; %number of 'color' components updated
1259                        NbDim=2;% space dimension set to 2
1260                    end
1261                end
1262            end
1263            AYName=FieldData.ListVarName{VarType.coord(NbDim-1)};%name of input x coordinate (name preserved on projection)
1264            AXName=FieldData.ListVarName{VarType.coord(NbDim)};%name of input y coordinate (name preserved on projection)
1265            if testangle% TODO modify name also in case of origin shift in x or y
1266                AYProjName='Y';
1267                AXProjName='X';
1268                count=0;
1269                %modify coordinate names if they are already used
1270                while ~(isempty(find(strcmp('AXName',ProjData.ListVarName),1)) && isempty(find(strcmp('AYName',ProjData.ListVarName),1)))
1271                    count=count+1;
1272                    AYProjName=[AYProjName '_' num2str(count)];
1273                    AXProjName=[AXProjName '_' num2str(count)];
1274                end
1275            else
1276                AYProjName=AYName;% (name preserved on projection)
1277                AXProjName=AXName;%name of input y coordinate (name preserved on projection)
1278            end
1279            ListDimName=FieldData.VarDimName{VarIndex(1)};
1280            ProjData.ListVarName=[ProjData.ListVarName {AYProjName} {AXProjName}]; %TODO: check if it already exists in Projdata (several cells)
1281            ProjData.VarDimName=[ProjData.VarDimName {AYProjName} {AXProjName}];
1282            ProjData.VarAttribute=[ProjData.VarAttribute {[]} {[]}];
1283            Coord_z=[];
1284            Coord_y=[];
1285            Coord_x=[];
1286           
1287            for idim=1:NbDim %loop on space dimensions
1288                test_interp(idim)=0;%test for coordiate interpolation (non regular grid), =0 by default
1289                ivar=VarType.coord(idim);% index of the variable corresponding to the current dimension
1290                if ~isequal(ivar,0)%  a variable corresponds to the dimension #idim
1291                    eval(['Coord{idim}=FieldData.' FieldData.ListVarName{ivar} ';']) ;% coord values for the input field
1292                    if numel(Coord{idim})==2 %input array defined on a regular grid
1293                        DCoord_min(idim)=(Coord{idim}(2)-Coord{idim}(1))/DimValue(idim);
1294                    else
1295                        DCoord=diff(Coord{idim});%array of coordinate derivatives for the input field
1296                        DCoord_min(idim)=min(DCoord);
1297                        DCoord_max=max(DCoord);
1298                        %    test_direct(idim)=DCoord_max>0;% =1 for increasing values, 0 otherwise
1299                        if abs(DCoord_max-DCoord_min(idim))>abs(DCoord_max/1000)
1300                            msgbox_uvmat('ERROR',['non monotonic dimension variable # ' num2str(idim)  ' in proj_field.m'])
1301                            return
1302                        end
1303                        test_interp(idim)=(DCoord_max-DCoord_min(idim))> 0.0001*abs(DCoord_max);% test grid regularity
1304                    end
1305                    test_direct(idim)=(DCoord_min(idim)>0);
1306                else  % no variable associated with the  dimension #idim, the coordinate value is set equal to the matrix index by default
1307                    Coord_i_str=['Coord_' num2str(idim)];
1308                    DCoord_min(idim)=1;%default
1309                    Coord{idim}=[0.5 DimValue(idim)-0.5];
1310                    test_direct(idim)=1;
1311                end
1312            end
1313            if DY==0
1314                DY=abs(DCoord_min(NbDim-1));
1315            end
1316            npY=1+round(abs(Coord{NbDim-1}(end)-Coord{NbDim-1}(1))/DY);%nbre of points after interpol
1317            if DX==0
1318                DX=abs(DCoord_min(NbDim));
1319            end
1320            npX=1+round(abs(Coord{NbDim}(end)-Coord{NbDim}(1))/DX);%nbre of points after interpol
1321            for idim=1:NbDim
1322                if test_interp(idim)
1323                    DimValue(idim)=1+round(abs(Coord{idim}(end)-Coord{idim}(1))/abs(DCoord_min(idim)));%nbre of points after possible interpolation on a regular gri
1324                end
1325            end
1326            Coord_y=linspace(Coord{NbDim-1}(1),Coord{NbDim-1}(end),npY);
1327            test_direct_y=test_direct(NbDim-1);
1328            Coord_x=linspace(Coord{NbDim}(1),Coord{NbDim}(end),npX);
1329            test_direct_x=test_direct(NbDim);
1330            DAX=DCoord_min(NbDim);
1331            DAY=DCoord_min(NbDim-1);
1332            minAX=min(Coord_x);
1333            maxAX=max(Coord_x);
1334            minAY=min(Coord_y);
1335            maxAY=max(Coord_y);
1336            xcorner=[minAX maxAX minAX maxAX]-ObjectData.Coord(1,1);
1337            ycorner=[maxAY maxAY minAY minAY]-ObjectData.Coord(1,2);
1338            xcor_new=xcorner*cos_om+ycorner*sin_om;%coord new frame
1339            ycor_new=-xcorner*sin_om+ycorner*cos_om;
1340            if ~testXMax
1341                XMax=max(xcor_new);
1342            end
1343            if ~testXMin
1344                XMin=min(xcor_new);
1345            end
1346            if ~testYMax
1347                YMax=max(ycor_new);
1348            end
1349            if ~testYMin
1350                YMin=min(ycor_new);
1351            end
1352            DXinit=(maxAX-minAX)/(DimValue(NbDim)-1);
1353            DYinit=(maxAY-minAY)/(DimValue(NbDim-1)-1);
1354            if DX==0
1355                DX=DXinit;
1356            end
1357            if DY==0
1358                DY=DYinit;
1359            end
1360            if NbDim==3
1361                DZ=(Coord{1}(end)-Coord{1}(1))/(DimValue(1)-1);
1362                if ~test_direct(1)
1363                    DZ=-DZ;
1364                end
1365                Coord_z=linspace(Coord{1}(1),Coord{1}(end),DimValue(1));
1366                test_direct_z=test_direct(1);
1367            end
1368            npX=floor((XMax-XMin)/DX+1);
1369            npY=floor((YMax-YMin)/DY+1);
1370            if test_direct_y
1371                coord_y_proj=linspace(YMin,YMax,npY);%abscissa of the new pixels along the line
1372            else
1373                coord_y_proj=linspace(YMax,YMin,npY);%abscissa of the new pixels along the line
1374            end
1375            if test_direct_x
1376                coord_x_proj=linspace(XMin,XMax,npX);%abscissa of the new pixels along the line
1377            else
1378                coord_x_proj=linspace(XMax,XMin,npX);%abscissa of the new pixels along the line
1379            end
1380            % case with no  interpolation
1381            if isequal(ProjMode{icell},'projection') && (~testangle || test90y || test90x)
1382                if  NbDim==2 && ~testXMin && ~testXMax && ~testYMin && ~testYMax
1383                    ProjData.ListVarName=[ProjData.ListVarName FieldData.ListVarName(VarIndex)];
1384                    ProjData.VarDimName=[ProjData.VarDimName FieldData.VarDimName(VarIndex)]; 
1385                    ProjData.VarAttribute=[ProjData.VarAttribute FieldData.VarAttribute(VarIndex)];
1386                    ProjData.(AYProjName)=FieldData.(AYName);
1387                    ProjData.(AXProjName)=FieldData.(AXName);
1388                    for ivar=VarIndex
1389                        VarName=FieldData.ListVarName{ivar};
1390                        ProjData.(VarName)=FieldData.(VarName);% no change by projection
1391                    end
1392                else
1393                    indY=NbDim-1;
1394                    if test_direct(indY)
1395                        min_indy=ceil((YMin-Coord{indY}(1))/DYinit)+1;
1396                        max_indy=floor((YMax-Coord{indY}(1))/DYinit)+1;
1397                        Ybound(1)=Coord{indY}(1)+DYinit*(min_indy-1);
1398                        Ybound(2)=Coord{indY}(1)+DYinit*(max_indy-1);
1399                    else
1400                        min_indy=ceil((Coord{indY}(1)-YMax)/DYinit)+1;
1401                        max_indy=floor((Coord{indY}(1)-YMin)/DYinit)+1;
1402                        Ybound(2)=Coord{indY}(1)-DYinit*(max_indy-1);
1403                        Ybound(1)=Coord{indY}(1)-DYinit*(min_indy-1);
1404                    end
1405                    if test_direct(NbDim)==1
1406                        min_indx=ceil((XMin-Coord{NbDim}(1))/DXinit)+1;
1407                        max_indx=floor((XMax-Coord{NbDim}(1))/DXinit)+1;
1408                        Xbound(1)=Coord{NbDim}(1)+DXinit*(min_indx-1);
1409                        Xbound(2)=Coord{NbDim}(1)+DXinit*(max_indx-1);
1410                    else
1411                        min_indx=ceil((Coord{NbDim}(1)-XMax)/DXinit)+1;
1412                        max_indx=floor((Coord{NbDim}(1)-XMin)/DXinit)+1;
1413                        Xbound(2)=Coord{NbDim}(1)+DXinit*(max_indx-1);
1414                        Xbound(1)=Coord{NbDim}(1)+DXinit*(min_indx-1);
1415                    end
1416                    min_indy=max(min_indy,1);% deals with margin (bound lower than the first index)
1417                    min_indx=max(min_indx,1);
1418                   
1419                    if test90y
1420                        ind_new=[3 2 1];
1421                        DimCell={AYProjName,AXProjName};
1422                        %                     DimValue=DimValue(ind_new);
1423                        iz=ceil((ObjectData.Coord(1,1)-Coord{3}(1))/DX)+1;
1424                        for ivar=VarIndex
1425                            VarName=FieldData.ListVarName{ivar};
1426                            ProjData.ListVarName=[ProjData.ListVarName VarName];
1427                            ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
1428                            ProjData.VarAttribute{length(ProjData.ListVarName)}=FieldData.VarAttribute{ivar}; %reproduce the variable attributes
1429                            eval(['ProjData.' VarName '=permute(FieldData.' VarName ',ind_new);'])% permute x and z indices for 90 degree rotation
1430                            eval(['ProjData.' VarName '=squeeze(ProjData.' VarName '(iz,:,:));'])% select the z index iz
1431                        end
1432                        eval(['ProjData.' AYProjName '=[Ybound(1) Ybound(2)];']) %record the new (projected ) y coordinates
1433                        eval(['ProjData.' AXProjName '=[Coord{1}(end),Coord{1}(1)];']) %record the new (projected ) x coordinates
1434                    else
1435                        if NbDim==3
1436                            DimCell(1)=[]; %suppress z variable
1437                            DimValue(1)=[];
1438                            if test_direct(1)
1439                                iz=ceil((ObjectData.Coord(1,3)-Coord{1}(1))/DZ)+1;
1440                            else
1441                                iz=ceil((Coord{1}(1)-ObjectData.Coord(1,3))/DZ)+1;
1442                            end
1443                        end
1444                        max_indy=min(max_indy,DimValue(1));%introduce bounds in y and x indices
1445                        max_indx=min(max_indx,DimValue(2));
1446                        for ivar=VarIndex% loop on non coordinate variables
1447                            VarName=FieldData.ListVarName{ivar};
1448                            ProjData.ListVarName=[ProjData.ListVarName VarName];
1449                            ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
1450                            if isfield(FieldData,'VarAttribute') && length(FieldData.VarAttribute)>=ivar
1451                                ProjData.VarAttribute{length(ProjData.ListVarName)}=FieldData.VarAttribute{ivar};
1452                            end
1453                            if NbDim==3
1454                                eval(['ProjData.' VarName '=squeeze(FieldData.' VarName '(iz,min_indy:max_indy,min_indx:max_indx));']);
1455                            else
1456                                eval(['ProjData.' VarName '=FieldData.' VarName '(min_indy:max_indy,min_indx:max_indx,:);']);
1457                            end
1458                        end
1459                        eval(['ProjData.' AYProjName '=[Ybound(1) Ybound(2)];']) %record the new (projected ) y coordinates
1460                        eval(['ProjData.' AXProjName '=[Xbound(1) Xbound(2)];']) %record the new (projected ) x coordinates
1461                    end
1462                end
1463            else       % case with rotation and/or interpolation
1464                if NbDim==2 %2D case
1465                    [X,Y]=meshgrid(coord_x_proj,coord_y_proj);%grid in the new coordinates
1466                    XIMA=ObjectData.Coord(1,1)+(X)*cos(PlaneAngle(3))-Y*sin(PlaneAngle(3));%corresponding coordinates in the original image
1467                    YIMA=ObjectData.Coord(1,2)+(X)*sin(PlaneAngle(3))+Y*cos(PlaneAngle(3));
1468                    XIMA=(XIMA-minAX)/DXinit+1;% image index along x
1469                    YIMA=(-YIMA+maxAY)/DYinit+1;% image index along y
1470                    XIMA=reshape(round(XIMA),1,npX*npY);%indices reorganized in 'line'
1471                    YIMA=reshape(round(YIMA),1,npX*npY);
1472                    flagin=XIMA>=1 & XIMA<=DimValue(2) & YIMA >=1 & YIMA<=DimValue(1);%flagin=1 inside the original image
1473                    if isequal(ProjMode{icell},'filter')
1474                        npx_filter=ceil(abs(DX/DAX));
1475                        npy_filter=ceil(abs(DY/DAY));
1476                        Mfilter=ones(npy_filter,npx_filter)/(npx_filter*npy_filter);
1477                        test_filter=1;
1478                    else
1479                        test_filter=0;
1480                    end
1481                    eval(['ProjData.' AYName '=[coord_y_proj(1) coord_y_proj(end)];']) %record the new (projected ) y coordinates
1482                    eval(['ProjData.' AXName '=[coord_x_proj(1) coord_x_proj(end)];']) %record the new (projected ) x coordinates
1483                    for ivar=VarIndex
1484                        VarName=FieldData.ListVarName{ivar};
1485                        if test_interp(1) || test_interp(2)%interpolate on a regular grid
1486                            eval(['ProjData.' VarName '=interp2(Coord{2},Coord{1},FieldData.' VarName ',Coord_x,Coord_y'');']) %TO TEST
1487                        end
1488                        %filter the field (image) if option 'filter' is used
1489                        if test_filter
1490                            Aclass=class(FieldData.A);
1491                            eval(['ProjData.' VarName '=filter2(Mfilter,FieldData.' VarName ',''valid'');'])
1492                            if ~isequal(Aclass,'double')
1493                                eval(['ProjData.' VarName '=' Aclass '(FieldData.' VarName ');'])%revert to integer values
1494                            end
1495                        end
1496                        eval(['vec_A=reshape(FieldData.' VarName ',[],nbcolor);'])%put the original image in line
1497                        %ind_in=find(flagin);
1498                        ind_out=find(~flagin);
1499                        ICOMB=(XIMA-1)*DimValue(1)+YIMA;
1500                        ICOMB=ICOMB(flagin);%index corresponding to XIMA and YIMA in the aligned original image vec_A
1501                        vec_B(flagin,1:nbcolor)=vec_A(ICOMB,:);
1502                        for icolor=1:nbcolor
1503                            vec_B(ind_out,icolor)=zeros(size(ind_out));
1504                        end
1505                        ProjData.ListVarName=[ProjData.ListVarName VarName];
1506                        ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
1507                        if isfield(FieldData,'VarAttribute')&&length(FieldData.VarAttribute)>=ivar
1508                            ProjData.VarAttribute{length(ProjData.ListVarName)+nbcoord}=FieldData.VarAttribute{ivar};
1509                        end
1510                        eval(['ProjData.' VarName '=reshape(vec_B,npY,npX,nbcolor);']);
1511                    end
1512                    ProjData.FF=reshape(~flagin,npY,npX);%false flag A FAIRE: tenir compte d'un flga antérieur
1513                    ProjData.ListVarName=[ProjData.ListVarName 'FF'];
1514                    ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
1515                    ProjData.VarAttribute{length(ProjData.ListVarName)}.Role='errorflag';
1516                elseif ~testangle
1517                    % unstructured z coordinate
1518                    test_sup=(Coord{1}>=ObjectData.Coord(1,3));
1519                    iz_sup=find(test_sup);
1520                    iz=iz_sup(1);
1521                    if iz>=1 & iz<=npz
1522                        %ProjData.ListDimName=[ProjData.ListDimName ListDimName(2:end)];
1523                        %ProjData.DimValue=[ProjData.DimValue npY npX];
1524                        for ivar=VarIndex
1525                            VarName=FieldData.ListVarName{ivar};
1526                            ProjData.ListVarName=[ProjData.ListVarName VarName];
1527                            ProjData.VarAttribute{length(ProjData.ListVarName)}=FieldData.VarAttribute{ivar}; %reproduce the variable attributes
1528                            eval(['ProjData.' VarName '=squeeze(FieldData.' VarName '(iz,:,:));'])% select the z index iz
1529                            %TODO : do a vertical average for a thick plane
1530                            if test_interp(2) || test_interp(3)
1531                                eval(['ProjData.' VarName '=interp2(Coord{3},Coord{2},ProjData.' VarName ',Coord_x,Coord_y'');'])
1532                            end
1533                        end
1534                    end
1535                else
1536                    errormsg='projection of structured coordinates on oblique plane not yet implemented';
1537                    %TODO: use interp3
1538                    return
1539                end
1540            end
1541    end
1542   
1543    %% projection of  velocity components in the rotated coordinates
1544    if testangle && length(ivar_U)==1
1545        if isempty(ivar_V)
1546            msgbox_uvmat('ERROR','v velocity component missing in proj_field.m')
1547            return
1548        end
1549        UName=FieldData.ListVarName{ivar_U};
1550        VName=FieldData.ListVarName{ivar_V};
1551        eval(['ProjData.' UName  '=cos(PlaneAngle(3))*ProjData.' UName '+ sin(PlaneAngle(3))*ProjData.' VName ';'])
1552        eval(['ProjData.' VName  '=cos(Theta)*(-sin(PlaneAngle(3))*ProjData.' UName '+ cos(PlaneAngle(3))*ProjData.' VName ');'])
1553        if ~isempty(ivar_W)
1554            WName=FieldData.ListVarName{ivar_W};
1555            eval(['ProjData.' VName '=ProjData.' VName '+ ProjData.' WName '*sin(Theta);'])%
1556            eval(['ProjData.' WName '=NormVec_X*ProjData.' UName '+ NormVec_Y*ProjData.' VName '+ NormVec_Z* ProjData.' WName ';']);
1557        end
1558        if ~isequal(Psi,0)
1559            eval(['ProjData.' UName '=cos(Psi)* ProjData.' UName '- sin(Psi)*ProjData.' VName ';']);
1560            eval(['ProjData.' VName '=sin(Psi)* ProjData.' UName '+ cos(Psi)*ProjData.' VName ';']);
1561        end
1562    end
1563end
1564
1565% %prepare substraction in case of two input fields
1566% SubData.ListVarName={};
1567% SubData.VarDimName={};
1568% SubData.VarAttribute={};
1569% check_remove=zeros(size(ProjData.ListVarName));
1570% for iproj=1:numel(ProjData.VarAttribute)
1571%     if isfield(ProjData.VarAttribute{iproj},'CheckSub')&&isequal(ProjData.VarAttribute{iproj}.CheckSub,1)
1572%         VarName=ProjData.ListVarName{iproj};
1573%         SubData.ListVarName=[SubData.ListVarName {VarName}];
1574%         SubData.VarDimName=[SubData.VarDimName ProjData.VarDimName{iproj}];
1575%         SubData.VarAttribute=[SubData.VarAttribute ProjData.VarAttribute{iproj}];
1576%         SubData.(VarName)=ProjData.(VarName);
1577%         check_remove(iproj)=1;       
1578%     end
1579% end
1580% if ~isempty(find(check_remove))
1581%     ind_remove=find(check_remove);
1582%     ProjData.ListVarName(ind_remove)=[];
1583%     ProjData.VarDimName(ind_remove)=[];
1584%     ProjData.VarAttribute(ind_remove)=[];
1585%     ProjData=sub_field(ProjData,[],SubData);
1586% end   
1587
1588%-----------------------------------------------------------------
1589%projection in a volume
1590 function  [ProjData,errormsg] = proj_volume(FieldData, ObjectData)
1591%-----------------------------------------------------------------
1592ProjData=FieldData;%default output
1593
1594%% axis origin
1595if isempty(ObjectData.Coord)
1596    ObjectData.Coord(1,1)=0;%origin of the plane set to [0 0] by default
1597    ObjectData.Coord(1,2)=0;
1598    ObjectData.Coord(1,3)=0;
1599end
1600
1601%% rotation angles
1602VolumeAngle=[0 0 0];
1603norm_plane=[0 0 1];
1604if isfield(ObjectData,'Angle')&& isequal(size(ObjectData.Angle),[1 3])&& ~isequal(ObjectData.Angle,[0 0 0])
1605    PlaneAngle=ObjectData.Angle;
1606    VolumeAngle=ObjectData.Angle;
1607    om=norm(VolumeAngle);%norm of rotation angle in radians
1608    OmAxis=VolumeAngle/om; %unit vector marking the rotation axis
1609    cos_om=cos(pi*om/180);
1610    sin_om=sin(pi*om/180);
1611    coeff=OmAxis(3)*(1-cos_om);
1612    %components of the unity vector norm_plane normal to the projection plane
1613    norm_plane(1)=OmAxis(1)*coeff+OmAxis(2)*sin_om;
1614    norm_plane(2)=OmAxis(2)*coeff-OmAxis(1)*sin_om;
1615    norm_plane(3)=OmAxis(3)*coeff+cos_om;
1616end
1617testangle=~isequal(VolumeAngle,[0 0 0]);
1618
1619%% mesh sizes DX, DY, DZ
1620DX=0;
1621DY=0; %default
1622DZ=0;
1623if isfield(ObjectData,'DX')&~isempty(ObjectData.DX)
1624     DX=abs(ObjectData.DX);%mesh of interpolation points
1625end
1626if isfield(ObjectData,'DY')&~isempty(ObjectData.DY)
1627     DY=abs(ObjectData.DY);%mesh of interpolation points
1628end
1629if isfield(ObjectData,'DZ')&~isempty(ObjectData.DZ)
1630     DZ=abs(ObjectData.DZ);%mesh of interpolation points
1631end
1632if  ~strcmp(ProjMode,'projection') && (DX==0||DY==0||DZ==0)
1633        errormsg='grid mesh DX , DY or DZ is missing';
1634        return
1635end
1636
1637%% extrema along each axis
1638testXMin=0;
1639testXMax=0;
1640testYMin=0;
1641testYMax=0;
1642if isfield(ObjectData,'RangeX')
1643        XMin=min(ObjectData.RangeX);
1644        XMax=max(ObjectData.RangeX);
1645        testXMin=XMax>XMin;
1646        testXMax=1;
1647end
1648if isfield(ObjectData,'RangeY')
1649        YMin=min(ObjectData.RangeY);
1650        YMax=max(ObjectData.RangeY);
1651        testYMin=YMax>YMin;
1652        testYMax=1;
1653end
1654width=0;%default width of the projection band
1655if isfield(ObjectData,'RangeZ')
1656        ZMin=min(ObjectData.RangeZ);
1657        ZMax=max(ObjectData.RangeZ);
1658        testZMin=ZMax>ZMin;
1659        testZMax=1;
1660end
1661
1662%% initiate Matlab  structure for physical field
1663[ProjData,errormsg]=proj_heading(FieldData,ObjectData);
1664ProjData.NbDim=3;
1665ProjData.ListVarName={};
1666ProjData.VarDimName={};
1667if ~isequal(DX,0)&& ~isequal(DY,0)
1668    ProjData.Mesh=sqrt(DX*DY);%define typical data mesh, useful for mouse selection in plots
1669elseif isfield(FieldData,'Mesh')
1670    ProjData.Mesh=FieldData.Mesh;
1671end
1672
1673error=0;%default
1674flux=0;
1675testfalse=0;
1676ListIndex={};
1677
1678%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1679%% group the variables (fields of 'FieldData') in cells of variables with the same dimensions
1680%-----------------------------------------------------------------
1681idimvar=0;
1682[CellVarIndex,NbDimVec,VarTypeCell,errormsg]=find_field_cells(FieldData);
1683if ~isempty(errormsg)
1684    errormsg=['error in proj_field/proj_plane:' errormsg];
1685    return
1686end
1687
1688% LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
1689% CellVarIndex=cells of variable index arrays
1690ivar_new=0; % index of the current variable in the projected field
1691icoord=0;
1692nbcoord=0;%number of added coordinate variables brought by projection
1693nbvar=0;
1694for icell=1:length(CellVarIndex)
1695    NbDim=NbDimVec(icell);
1696    if NbDim<3
1697        continue
1698    end
1699    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
1700    VarType=VarTypeCell{icell};
1701    ivar_X=VarType.coord_x;
1702    ivar_Y=VarType.coord_y;
1703    ivar_Z=VarType.coord_z;
1704    ivar_U=VarType.vector_x;
1705    ivar_V=VarType.vector_y;
1706    ivar_W=VarType.vector_z;
1707    ivar_C=VarType.scalar ;
1708    ivar_Anc=VarType.ancillary;
1709    test_anc=zeros(size(VarIndex));
1710    test_anc(ivar_Anc)=ones(size(ivar_Anc));
1711    ivar_F=VarType.warnflag;
1712    ivar_FF=VarType.errorflag;
1713    check_unstructured_coord=~isempty(ivar_X) && ~isempty(ivar_Y);
1714    DimCell=FieldData.VarDimName{VarIndex(1)};
1715    if ischar(DimCell)
1716        DimCell={DimCell};%name of dimensions
1717    end
1718
1719%% case of input fields with unstructured coordinates
1720    if check_unstructured_coord
1721        XName=FieldData.ListVarName{ivar_X};
1722        YName=FieldData.ListVarName{ivar_Y};
1723        eval(['coord_x=FieldData.' XName ';'])
1724        eval(['coord_y=FieldData.' YName ';'])
1725        if length(ivar_Z)==1
1726            ZName=FieldData.ListVarName{ivar_Z};
1727            eval(['coord_z=FieldData.' ZName ';'])
1728        end
1729
1730        % translate  initial coordinates
1731        coord_x=coord_x-ObjectData.Coord(1,1);
1732        coord_y=coord_y-ObjectData.Coord(1,2);
1733        if ~isempty(ivar_Z)
1734            coord_z=coord_z-ObjectData.Coord(1,3);
1735        end
1736       
1737        % selection of the vectors in the projection range
1738%         if length(ivar_Z)==1 &&  width > 0
1739%             %components of the unitiy vector normal to the projection plane
1740%             fieldZ=NormVec_X*coord_x + NormVec_Y*coord_y+ NormVec_Z*coord_z;% distance to the plane           
1741%             indcut=find(abs(fieldZ) <= width);
1742%             for ivar=VarIndex
1743%                 VarName=FieldData.ListVarName{ivar};
1744%                 eval(['FieldData.' VarName '=FieldData.' VarName '(indcut);']) 
1745%                     % A VOIR : CAS DE VAR STRUCTUREE MAIS PAS GRILLE REGULIERE : INTERPOLER SUR GRILLE REGULIERE             
1746%             end
1747%             coord_x=coord_x(indcut);
1748%             coord_y=coord_y(indcut);
1749%             coord_z=coord_z(indcut);
1750%         end
1751
1752       %rotate coordinates if needed: TODO modify
1753       if testangle
1754           coord_X=(coord_x *cos(Phi) + coord_y* sin(Phi));
1755           coord_Y=(-coord_x *sin(Phi) + coord_y *cos(Phi))*cos(Theta);
1756           if ~isempty(ivar_Z)
1757               coord_Y=coord_Y+coord_z *sin(Theta);
1758           end
1759           
1760           coord_X=(coord_X *cos(Psi) - coord_Y* sin(Psi));%A VERIFIER
1761           coord_Y=(coord_X *sin(Psi) + coord_Y* cos(Psi));
1762           
1763       else
1764           coord_X=coord_x;
1765           coord_Y=coord_y;
1766           coord_Z=coord_z;
1767       end
1768        %restriction to the range of x and y if imposed
1769        testin=ones(size(coord_X)); %default
1770        testbound=0;
1771        if testXMin
1772            testin=testin & (coord_X >= XMin);
1773            testbound=1;
1774        end
1775        if testXMax
1776            testin=testin & (coord_X <= XMax);
1777            testbound=1;
1778        end
1779        if testYMin
1780            testin=testin & (coord_Y >= YMin);
1781            testbound=1;
1782        end
1783        if testYMax
1784            testin=testin & (coord_Y <= YMax);
1785            testbound=1;
1786        end
1787        if testbound
1788            indcut=find(testin);
1789            for ivar=VarIndex
1790                VarName=FieldData.ListVarName{ivar};
1791                eval(['FieldData.' VarName '=FieldData.' VarName '(indcut);'])           
1792            end
1793            coord_X=coord_X(indcut);
1794            coord_Y=coord_Y(indcut);
1795            if length(ivar_Z)==1
1796                coord_Z=coord_Z(indcut);
1797            end
1798        end
1799        % different cases of projection
1800        if isequal(ObjectData.ProjMode,'projection')%%%%%%%   NOT USED %%%%%%%%%%
1801            for ivar=VarIndex %transfer variables to the projection plane
1802                VarName=FieldData.ListVarName{ivar};
1803                if ivar==ivar_X %x coordinate
1804                    eval(['ProjData.' VarName '=coord_X;'])
1805                elseif ivar==ivar_Y % y coordinate
1806                    eval(['ProjData.' VarName '=coord_Y;'])
1807                elseif isempty(ivar_Z) || ivar~=ivar_Z % other variables (except Z coordinate wyhich is not reproduced)
1808                    eval(['ProjData.' VarName '=FieldData.' VarName ';'])
1809                end
1810                if isempty(ivar_Z) || ivar~=ivar_Z
1811                    ProjData.ListVarName=[ProjData.ListVarName VarName];
1812                    ProjData.VarDimName=[ProjData.VarDimName DimCell];
1813                    nbvar=nbvar+1;
1814                    if isfield(FieldData,'VarAttribute') && length(FieldData.VarAttribute) >=ivar
1815                        ProjData.VarAttribute{nbvar}=FieldData.VarAttribute{ivar};
1816                    end
1817                end
1818            end 
1819        elseif isequal(ObjectData.ProjMode,'interp')||isequal(ObjectData.ProjMode,'filter')%interpolate data on a regular grid
1820            coord_x_proj=XMin:DX:XMax;
1821            coord_y_proj=YMin:DY:YMax;
1822            coord_z_proj=ZMin:DZ:ZMax;
1823            DimCell={'coord_z','coord_y','coord_x'};
1824            ProjData.ListVarName={'coord_z','coord_y','coord_x'};
1825            ProjData.VarDimName={'coord_z','coord_y','coord_x'};   
1826            nbcoord=2; 
1827            ProjData.coord_z=[ZMin ZMax];
1828            ProjData.coord_y=[YMin YMax];
1829            ProjData.coord_x=[XMin XMax];
1830            if isempty(ivar_X), ivar_X=0; end;
1831            if isempty(ivar_Y), ivar_Y=0; end;
1832            if isempty(ivar_Z), ivar_Z=0; end;
1833            if isempty(ivar_U), ivar_U=0; end;
1834            if isempty(ivar_V), ivar_V=0; end;
1835            if isempty(ivar_W), ivar_W=0; end;
1836            if isempty(ivar_F), ivar_F=0; end;
1837            if isempty(ivar_FF), ivar_FF=0; end;
1838            if ~isequal(ivar_FF,0)
1839                VarName_FF=FieldData.ListVarName{ivar_FF};
1840                eval(['indsel=find(FieldData.' VarName_FF '==0);'])
1841                coord_X=coord_X(indsel);
1842                coord_Y=coord_Y(indsel);
1843            end
1844            FF=zeros(1,length(coord_y_proj)*length(coord_x_proj));
1845            testFF=0;
1846            [X,Y,Z]=meshgrid(coord_y_proj,coord_z_proj,coord_x_proj);%grid in the new coordinates
1847            for ivar=VarIndex
1848                VarName=FieldData.ListVarName{ivar};
1849                if ~( ivar==ivar_X || ivar==ivar_Y || ivar==ivar_Z || ivar==ivar_F || ivar==ivar_FF || test_anc(ivar)==1)                 
1850                    ivar_new=ivar_new+1;
1851                    ProjData.ListVarName=[ProjData.ListVarName {VarName}];
1852                    ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
1853                    if isfield(FieldData,'VarAttribute') && length(FieldData.VarAttribute) >=ivar
1854                        ProjData.VarAttribute{ivar_new+nbcoord}=FieldData.VarAttribute{ivar};
1855                    end
1856                    if  ~isequal(ivar_FF,0)
1857                        eval(['FieldData.' VarName '=FieldData.' VarName '(indsel);'])
1858                    end
1859                    eval(['InterpFct=TriScatteredInterp(double(coord_X),double(coord_Y),double(coord_Z),double(FieldData.' VarName '))'])
1860                    eval(['ProjData.' VarName '=InterpFct(X,Y,Z);'])
1861%                     eval(['varline=reshape(ProjData.' VarName ',1,length(coord_y_proj)*length(coord_x_proj));'])
1862%                     FFlag= isnan(varline); %detect undefined values NaN
1863%                     indnan=find(FFlag);
1864%                     if~isempty(indnan)
1865%                         varline(indnan)=zeros(size(indnan));
1866%                         eval(['ProjData.' VarName '=reshape(varline,length(coord_y_proj),length(coord_x_proj));'])
1867%                         FF(indnan)=ones(size(indnan));
1868%                         testFF=1;
1869%                     end
1870                    if ivar==ivar_U
1871                        ivar_U=ivar_new;
1872                    end
1873                    if ivar==ivar_V
1874                        ivar_V=ivar_new;
1875                    end
1876                    if ivar==ivar_W
1877                        ivar_W=ivar_new;
1878                    end
1879                end
1880            end
1881            if testFF
1882                ProjData.FF=reshape(FF,length(coord_y_proj),length(coord_x_proj));
1883                ProjData.ListVarName=[ProjData.ListVarName {'FF'}];
1884               ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
1885                ProjData.VarAttribute{ivar_new+1+nbcoord}.Role='errorflag';
1886            end
1887        end
1888       
1889%% case of input fields defined on a structured  grid
1890    else
1891        VarName=FieldData.ListVarName{VarIndex(1)};%get the first variable of the cell to get the input matrix dimensions
1892        eval(['DimValue=size(FieldData.' VarName ');'])%input matrix dimensions
1893        DimValue(DimValue==1)=[];%remove singleton dimensions       
1894        NbDim=numel(DimValue);%update number of space dimensions
1895        nbcolor=1; %default number of 'color' components: third matrix index without corresponding coordinate
1896        if NbDim>=3
1897            if NbDim>3
1898                errormsg='matrices with more than 3 dimensions not handled';
1899                return
1900            else
1901                if numel(find(VarType.coord))==2% the third matrix dimension does not correspond to a space coordinate
1902                    nbcolor=DimValue(3);
1903                    DimValue(3)=[]; %number of 'color' components updated
1904                    NbDim=2;% space dimension set to 2
1905                end
1906            end
1907        end
1908        AYName=FieldData.ListVarName{VarType.coord(NbDim-1)};%name of input x coordinate (name preserved on projection)
1909        AXName=FieldData.ListVarName{VarType.coord(NbDim)};%name of input y coordinate (name preserved on projection)   
1910        eval(['AX=FieldData.' AXName ';'])
1911        eval(['AY=FieldData.' AYName ';'])
1912        ListDimName=FieldData.VarDimName{VarIndex(1)};
1913        ProjData.ListVarName=[ProjData.ListVarName {AYName} {AXName}]; %TODO: check if it already exists in Projdata (several cells)
1914        ProjData.VarDimName=[ProjData.VarDimName {AYName} {AXName}];
1915
1916%         for idim=1:length(ListDimName)
1917%             DimName=ListDimName{idim};
1918%             if strcmp(DimName,'rgb')||strcmp(DimName,'nb_coord')||strcmp(DimName,'nb_coord_i')
1919%                nbcolor=DimValue(idim);
1920%                DimValue(idim)=[];
1921%             end
1922%             if isequal(DimName,'nb_coord_j')% NOTE: CASE OF TENSOR NOT TREATED
1923%                 DimValue(idim)=[];
1924%             end
1925%         end 
1926        Coord_z=[];
1927        Coord_y=[];
1928        Coord_x=[];   
1929
1930        for idim=1:NbDim %loop on space dimensions
1931            test_interp(idim)=0;%test for coordiate interpolation (non regular grid), =0 by default
1932            ivar=VarType.coord(idim);% index of the variable corresponding to the current dimension
1933            if ~isequal(ivar,0)%  a variable corresponds to the dimension #idim
1934                eval(['Coord{idim}=FieldData.' FieldData.ListVarName{ivar} ';']) ;% coord values for the input field
1935                if numel(Coord{idim})==2 %input array defined on a regular grid
1936                   DCoord_min(idim)=(Coord{idim}(2)-Coord{idim}(1))/DimValue(idim);
1937                else
1938                    DCoord=diff(Coord{idim});%array of coordinate derivatives for the input field
1939                    DCoord_min(idim)=min(DCoord);
1940                    DCoord_max=max(DCoord);
1941                %    test_direct(idim)=DCoord_max>0;% =1 for increasing values, 0 otherwise
1942                    if abs(DCoord_max-DCoord_min(idim))>abs(DCoord_max/1000)
1943                        msgbox_uvmat('ERROR',['non monotonic dimension variable # ' num2str(idim)  ' in proj_field.m'])
1944                                return
1945                    end               
1946                    test_interp(idim)=(DCoord_max-DCoord_min(idim))> 0.0001*abs(DCoord_max);% test grid regularity
1947                end
1948                test_direct(idim)=(DCoord_min(idim)>0);
1949            else  % no variable associated with the  dimension #idim, the coordinate value is set equal to the matrix index by default
1950                Coord_i_str=['Coord_' num2str(idim)];
1951                DCoord_min(idim)=1;%default
1952                Coord{idim}=[0.5 DimValue(idim)-0.5];
1953                test_direct(idim)=1;
1954            end
1955        end
1956        if DY==0
1957            DY=abs(DCoord_min(NbDim-1));
1958        end
1959        npY=1+round(abs(Coord{NbDim-1}(end)-Coord{NbDim-1}(1))/DY);%nbre of points after interpol
1960        if DX==0
1961            DX=abs(DCoord_min(NbDim));
1962        end
1963        npX=1+round(abs(Coord{NbDim}(end)-Coord{NbDim}(1))/DX);%nbre of points after interpol
1964        for idim=1:NbDim
1965            if test_interp(idim)
1966                DimValue(idim)=1+round(abs(Coord{idim}(end)-Coord{idim}(1))/abs(DCoord_min(idim)));%nbre of points after possible interpolation on a regular gri
1967            end
1968        end       
1969        Coord_y=linspace(Coord{NbDim-1}(1),Coord{NbDim-1}(end),npY);
1970        test_direct_y=test_direct(NbDim-1);
1971        Coord_x=linspace(Coord{NbDim}(1),Coord{NbDim}(end),npX);
1972        test_direct_x=test_direct(NbDim);
1973        DAX=DCoord_min(NbDim);
1974        DAY=DCoord_min(NbDim-1); 
1975        minAX=min(Coord_x);
1976        maxAX=max(Coord_x);
1977        minAY=min(Coord_y);
1978        maxAY=max(Coord_y);
1979        xcorner=[minAX maxAX minAX maxAX]-ObjectData.Coord(1,1);
1980        ycorner=[maxAY maxAY minAY minAY]-ObjectData.Coord(1,2);
1981        xcor_new=xcorner*cos(Phi)+ycorner*sin(Phi);%coord new frame
1982        ycor_new=-xcorner*sin(Phi)+ycorner*cos(Phi);
1983        if ~testXMax
1984            XMax=max(xcor_new);
1985        end
1986        if ~testXMin
1987            XMin=min(xcor_new);
1988        end
1989        if ~testYMax
1990            YMax=max(ycor_new);
1991        end
1992        if ~testYMin
1993            YMin=min(ycor_new);
1994        end
1995        DXinit=(maxAX-minAX)/(DimValue(NbDim)-1);
1996        DYinit=(maxAY-minAY)/(DimValue(NbDim-1)-1);
1997        if DX==0
1998            DX=DXinit;
1999        end
2000        if DY==0
2001            DY=DYinit;
2002        end
2003        if NbDim==3
2004            DZ=(Coord{1}(end)-Coord{1}(1))/(DimValue(1)-1);
2005            if ~test_direct(1)
2006                DZ=-DZ;
2007            end
2008            Coord_z=linspace(Coord{1}(1),Coord{1}(end),DimValue(1));
2009            test_direct_z=test_direct(1);
2010        end
2011        npX=floor((XMax-XMin)/DX+1);
2012        npY=floor((YMax-YMin)/DY+1);   
2013        if test_direct_y
2014            coord_y_proj=linspace(YMin,YMax,npY);%abscissa of the new pixels along the line
2015        else
2016            coord_y_proj=linspace(YMax,YMin,npY);%abscissa of the new pixels along the line
2017        end
2018        if test_direct_x
2019            coord_x_proj=linspace(XMin,XMax,npX);%abscissa of the new pixels along the line
2020        else
2021            coord_x_proj=linspace(XMax,XMin,npX);%abscissa of the new pixels along the line
2022        end
2023       
2024        % case with no rotation and interpolation
2025        if isequal(ProjMode,'projection') && isequal(Phi,0) && isequal(Theta,0) && isequal(Psi,0)
2026            if ~testXMin && ~testXMax && ~testYMin && ~testYMax && NbDim==2
2027                ProjData=FieldData;
2028            else
2029                indY=NbDim-1;
2030                if test_direct(indY)
2031                    min_indy=ceil((YMin-Coord{indY}(1))/DYinit)+1;
2032                    max_indy=floor((YMax-Coord{indY}(1))/DYinit)+1;
2033                    Ybound(1)=Coord{indY}(1)+DYinit*(min_indy-1);
2034                    Ybound(2)=Coord{indY}(1)+DYinit*(max_indy-1);
2035                else
2036                    min_indy=ceil((Coord{indY}(1)-YMax)/DYinit)+1;
2037                    max_indy=floor((Coord{indY}(1)-YMin)/DYinit)+1;
2038                    Ybound(2)=Coord{indY}(1)-DYinit*(max_indy-1);
2039                    Ybound(1)=Coord{indY}(1)-DYinit*(min_indy-1);
2040                end   
2041                if test_direct(NbDim)==1
2042                    min_indx=ceil((XMin-Coord{NbDim}(1))/DXinit)+1;
2043                    max_indx=floor((XMax-Coord{NbDim}(1))/DXinit)+1;
2044                    Xbound(1)=Coord{NbDim}(1)+DXinit*(min_indx-1);
2045                    Xbound(2)=Coord{NbDim}(1)+DXinit*(max_indx-1);
2046                else
2047                    min_indx=ceil((Coord{NbDim}(1)-XMax)/DXinit)+1;
2048                    max_indx=floor((Coord{NbDim}(1)-XMin)/DXinit)+1;
2049                    Xbound(2)=Coord{NbDim}(1)+DXinit*(max_indx-1);
2050                    Xbound(1)=Coord{NbDim}(1)+DXinit*(min_indx-1);
2051                end
2052                if NbDim==3
2053                    DimCell(1)=[]; %suppress z variable
2054                    DimValue(1)=[];
2055                                        %structured coordinates
2056                    if test_direct(1)
2057                        iz=ceil((ObjectData.Coord(1,3)-Coord{1}(1))/DZ)+1;
2058                    else
2059                        iz=ceil((Coord{1}(1)-ObjectData.Coord(1,3))/DZ)+1;
2060                    end
2061                end
2062                min_indy=max(min_indy,1);% deals with margin (bound lower than the first index)
2063                min_indx=max(min_indx,1);
2064                max_indy=min(max_indy,DimValue(1));
2065                max_indx=min(max_indx,DimValue(2));
2066                for ivar=VarIndex% loop on non coordinate variables
2067                    VarName=FieldData.ListVarName{ivar};
2068                    ProjData.ListVarName=[ProjData.ListVarName VarName];
2069                    ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
2070                    if isfield(FieldData,'VarAttribute') && length(FieldData.VarAttribute)>=ivar
2071                        ProjData.VarAttribute{length(ProjData.ListVarName)}=FieldData.VarAttribute{ivar};
2072                    end
2073                    if NbDim==3
2074                        eval(['ProjData.' VarName '=squeeze(FieldData.' VarName '(iz,min_indy:max_indy,min_indx:max_indx));']);
2075                    else
2076                        eval(['ProjData.' VarName '=FieldData.' VarName '(min_indy:max_indy,min_indx:max_indx,:);']);
2077                    end
2078                end 
2079                eval(['ProjData.' AYName '=[Ybound(1) Ybound(2)];']) %record the new (projected ) y coordinates
2080                eval(['ProjData.' AXName '=[Xbound(1) Xbound(2)];']) %record the new (projected ) x coordinates
2081            end
2082        elseif isfield(FieldData,'A') %TO GENERALISE       % case with rotation and/or interpolation
2083            if NbDim==2 %2D case
2084                [X,Y]=meshgrid(coord_x_proj,coord_y_proj);%grid in the new coordinates
2085                XIMA=ObjectData.Coord(1,1)+(X)*cos(Phi)-Y*sin(Phi);%corresponding coordinates in the original image
2086                YIMA=ObjectData.Coord(1,2)+(X)*sin(Phi)+Y*cos(Phi);
2087                XIMA=(XIMA-minAX)/DXinit+1;% image index along x
2088                YIMA=(-YIMA+maxAY)/DYinit+1;% image index along y
2089                XIMA=reshape(round(XIMA),1,npX*npY);%indices reorganized in 'line'
2090                YIMA=reshape(round(YIMA),1,npX*npY);
2091                flagin=XIMA>=1 & XIMA<=DimValue(2) & YIMA >=1 & YIMA<=DimValue(1);%flagin=1 inside the original image
2092                if isequal(ObjectData.ProjMode,'filter')
2093                    npx_filter=ceil(abs(DX/DAX));
2094                    npy_filter=ceil(abs(DY/DAY));
2095                    Mfilter=ones(npy_filter,npx_filter)/(npx_filter*npy_filter);
2096                    test_filter=1;
2097                else
2098                    test_filter=0;
2099                end
2100                eval(['ProjData.' AYName '=[coord_y_proj(1) coord_y_proj(end)];']) %record the new (projected ) y coordinates
2101                eval(['ProjData.' AXName '=[coord_x_proj(1) coord_x_proj(end)];']) %record the new (projected ) x coordinates
2102                for ivar=VarIndex
2103                    VarName=FieldData.ListVarName{ivar};
2104                    if test_interp(1) || test_interp(2)%interpolate on a regular grid       
2105                          eval(['ProjData.' VarName '=interp2(Coord{2},Coord{1},FieldData.' VarName ',Coord_x,Coord_y'');']) %TO TEST
2106                    end
2107                    %filter the field (image) if option 'filter' is used
2108                    if test_filter 
2109                         Aclass=class(FieldData.A);
2110                         ProjData.(VarName)=filter2(Mfilter,FieldData.(VarName),'valid');
2111                         if ~isequal(Aclass,'double')
2112                             ProjData.(VarName)=Aclass(FieldData.(VarName));%revert to integer values
2113                         end
2114                    end
2115                    eval(['vec_A=reshape(FieldData.' VarName ',[],nbcolor);'])%put the original image in line             
2116                    %ind_in=find(flagin);
2117                    ind_out=find(~flagin);
2118                    ICOMB=(XIMA-1)*DimValue(1)+YIMA;
2119                    ICOMB=ICOMB(flagin);%index corresponding to XIMA and YIMA in the aligned original image vec_A
2120                    vec_B(flagin,1:nbcolor)=vec_A(ICOMB,:);
2121                    for icolor=1:nbcolor
2122                        vec_B(ind_out,icolor)=zeros(size(ind_out));
2123                    end
2124                    ProjData.ListVarName=[ProjData.ListVarName VarName];
2125                    ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
2126                    if isfield(FieldData,'VarAttribute')&&length(FieldData.VarAttribute)>=ivar
2127                        ProjData.VarAttribute{length(ProjData.ListVarName)+nbcoord}=FieldData.VarAttribute{ivar};
2128                    end     
2129                    eval(['ProjData.' VarName '=reshape(vec_B,npY,npX,nbcolor);']);
2130                end
2131                ProjData.FF=reshape(~flagin,npY,npX);%false flag A FAIRE: tenir compte d'un flga antérieur 
2132                ProjData.ListVarName=[ProjData.ListVarName 'FF'];
2133                ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
2134                ProjData.VarAttribute{length(ProjData.ListVarName)}.Role='errorflag';
2135            else %3D case
2136                if ~testangle     
2137                    % unstructured z coordinate
2138                    test_sup=(Coord{1}>=ObjectData.Coord(1,3));
2139                    iz_sup=find(test_sup);
2140                    iz=iz_sup(1);
2141                    if iz>=1 & iz<=npz
2142                        %ProjData.ListDimName=[ProjData.ListDimName ListDimName(2:end)];
2143                        %ProjData.DimValue=[ProjData.DimValue npY npX];
2144                        for ivar=VarIndex
2145                            VarName=FieldData.ListVarName{ivar};
2146                            ProjData.ListVarName=[ProjData.ListVarName VarName];
2147                            ProjData.VarAttribute{length(ProjData.ListVarName)}=FieldData.VarAttribute{ivar}; %reproduce the variable attributes 
2148                            eval(['ProjData.' VarName '=squeeze(FieldData.' VarName '(iz,:,:));'])% select the z index iz
2149                            %TODO : do a vertical average for a thick plane
2150                            if test_interp(2) || test_interp(3)
2151                                eval(['ProjData.' VarName '=interp2(Coord{3},Coord{2},ProjData.' VarName ',Coord_x,Coord_y'');'])
2152                            end
2153                        end
2154                    end
2155                else
2156                    errormsg='projection of structured coordinates on oblique plane not yet implemented';
2157                    %TODO: use interp3
2158                    return
2159                end
2160            end
2161        end
2162    end
2163
2164    %% projection of  velocity components in the rotated coordinates
2165    if testangle
2166        if isempty(ivar_V)
2167            msgbox_uvmat('ERROR','v velocity component missing in proj_field.m')
2168            return
2169        end
2170        UName=FieldData.ListVarName{ivar_U};
2171        VName=FieldData.ListVarName{ivar_V};   
2172        eval(['ProjData.' UName  '=cos(Phi)*ProjData.' UName '+ sin(Phi)*ProjData.' VName ';'])
2173        eval(['ProjData.' VName  '=cos(Theta)*(-sin(Phi)*ProjData.' UName '+ cos(Phi)*ProjData.' VName ');'])
2174        if ~isempty(ivar_W)
2175            WName=FieldData.ListVarName{ivar_W};
2176            eval(['ProjData.' VName '=ProjData.' VName '+ ProjData.' WName '*sin(Theta);'])%
2177            eval(['ProjData.' WName '=NormVec_X*ProjData.' UName '+ NormVec_Y*ProjData.' VName '+ NormVec_Z* ProjData.' WName ';']);
2178        end
2179        if ~isequal(Psi,0)
2180            eval(['ProjData.' UName '=cos(Psi)* ProjData.' UName '- sin(Psi)*ProjData.' VName ';']);
2181            eval(['ProjData.' VName '=sin(Psi)* ProjData.' UName '+ cos(Psi)*ProjData.' VName ';']);
2182        end
2183    end
2184end
2185
2186%------------------------------------------------------------------------
2187%--- transfer the global attributes
2188function [ProjData,errormsg]=proj_heading(FieldData,ObjectData)
2189%------------------------------------------------------------------------
2190ProjData=[];%default
2191errormsg='';%default
2192
2193%% transfer error
2194if isfield(FieldData,'Txt')
2195    errormsg=FieldData.Txt; %transmit erreur message
2196    return;
2197end
2198
2199%% transfer global attributes
2200if ~isfield(FieldData,'ListGlobalAttribute')
2201    ProjData.ListGlobalAttribute={};
2202else
2203    ProjData.ListGlobalAttribute=FieldData.ListGlobalAttribute;
2204end
2205for iattr=1:length(ProjData.ListGlobalAttribute)
2206    AttrName=ProjData.ListGlobalAttribute{iattr};
2207    if isfield(FieldData,AttrName)
2208        eval(['ProjData.' AttrName '=FieldData.' AttrName ';']);
2209    end
2210end
2211
2212%% transfer coordinate unit
2213if isfield(FieldData,'CoordUnit')
2214    if isfield(ObjectData,'CoordUnit') && ~strcmp(FieldData.CoordUnit,ObjectData.CoordUnit)
2215        errormsg=[ObjectData.Type ' in ' ObjectData.CoordUnit ' coordinates, while field in ' FieldData.CoordUnit ];
2216        return
2217    else
2218         ProjData.CoordUnit=FieldData.CoordUnit;
2219    end
2220end
2221
2222%% store the properties of the projection object
2223ListObject={'Type','ProjMode','RangeX','RangeY','RangeZ','Phi','Theta','Psi','Coord'};
2224for ilist=1:length(ListObject)
2225    if isfield(ObjectData,ListObject{ilist})
2226        eval(['val=ObjectData.' ListObject{ilist} ';'])
2227        if ~isempty(val)
2228            eval(['ProjData.Object' ListObject{ilist} '=val;']);
2229            ProjData.ListGlobalAttribute=[ProjData.ListGlobalAttribute {['Object' ListObject{ilist}]}];
2230        end
2231    end   
2232end
Note: See TracBrowser for help on using the repository browser.