source: trunk/src/proj_field.m @ 493

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

civ corrected to deal with windows system
proj_field improved to provject tps fields on lines

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