source: trunk/src/proj_field.m @ 543

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

bugs repaired for mask display in phys coord, display of circles in geometry_calib, introduction of x,y,z initial in proj_field/proj_plane

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